I found unions to be useful when dealing whith 128 bit data (used when working with sse)
Code:union
{
_m128 sseData;
float normalData[4];
}
Printable View
I found unions to be useful when dealing whith 128 bit data (used when working with sse)
Code:union
{
_m128 sseData;
float normalData[4];
}
You can also use unions to initialize arrays within classes/structs.
This is how I do it, at least:
I think it only works with POD types, though.Code:class MyClass
{
public:
union
{
const int array [3]; // These both have the
struct { const int array0, array1, array2; }; // same memory layout.
};
MyClass (int val0, int val1, int val2)
: array(), array0 (val0), array1 (val1), array2 (val2)
{
}
};
MyClass object (3, 4, 5);
// object.array[0] = 3, object.array[1] = 4, object.array[2] = 5
Well, that one is pretty useless. You have your array. Why re-name the elements in the array to arrayN?
To get access to the array structure, but that can't be much better than the copy algorithm. I would avoid this kind of premature pessimism, unless you absolutely cannot afford the temporary array, and in that case I would want a completely different object design.
Code:#include <algorithm>
namespace {
template<class T, std::size_t N>
class Foo
{
public:
Foo (const T * elems, std::size_t elemssize)
{
if (elemssize <= N)
std::copy(elems, elems + elemssize, _elems);
}
~Foo ()
{
//nothing
}
private:
T _elems[N];
};
}
int main ()
{
const std::size_t barsize = 5;
int * bar = new int [barsize];
for (int i = 0; i < barsize; i++) {
bar[i] = i * 2 + 1;
}
Foo<int, barsize> bomb(bar, barsize);
delete [] bar;
// use bomb ...
}
Yes, there's no need for the union in the first place. You could merely place the array outside, because it really doesn't do much being placed inside there...
My example does not break encapsulation: an object simply takes ownership of another object, namely the array is copied into Foo and then blips out of existence. There are neater ways to do that, but it's certainly ok.
Still, I'm not impressed by your reasoning. Thinking about it some more, std::fill or std::generate could probably do the job most of the time if you really depended on certain array values for your object and had no other array to copy from.
If that isn't a good decision, then I'd make an init method of some sort, which also solves the problem of encapsulation.
Otherwise, just make an assign method or something like that and wait until the values are really needed. That makes the underlying array structure a more dynamic one as well, allowing you to determine when it can extend and shrink.