Reputation: 376
Say for example that I have a class, that stores a very large array of some datatype (__type) as a pointer. However, I wish to initialize an object of this class using a different type. The code I have can be condensed to below:
template <typename __type> class MyStorageClass {
private:
__type* _data;
public:
template <typename __alt> MyStorageClass(int size, __alt* data) { // some init function }
extern friend print() const; // print to the screen
}
This works fine if I make an object of MyStorageClass<int>
and initialize it to (new int[2] { 1, 2 })
. However, the problem occours if I try to initialize it as: (new float[2] { 1, 2 })
, even though the size of int
and float
are the same (so in theory they will cast to each other).
If I initialize it by: _data = (__type*) data;
, the elements get changed.
MyStorageClass<int> msc1(2, new float[2] { 1, 2 });
msc1.print();
Yields: msc1=[1065353216, 1073741824]
, not msc1=[1, 2]
If I initialize it through a for loop:
// some init function
_data = new __type[size];
for (int i = 0; i < size; i++) _data[i] = data[i];
This works, and properly defines the object. However, It creates a new array in memory (at &_data
) of the same size as sizeof(data)
, rather than use the already allocated memory at &data
, which is unnecessarily memory intensive and can be confusing to the user.
QUESTION: Is there a way to cast an array (from float*
to int*
or another data type) using the same memory address?
UPDATE: Try with unions failed.
union FloatIntUnion{
float _f;
int _i;
FloatIntUnion(int i) { _i = i; }
FloatIntUnion(float f) { _f = f; }
operator float() { return _f; }
operator int() { return _i; }
operator std::string() const { std::stringstream oss; oss << _f; return oss.str(); }
};
MyStorageClass<int> msc2(2, new FloatIntUnion[2]{ float(1), float(2) });
msc2.print();
Yields: msc1=[1065353216, 1073741824]
Upvotes: 0
Views: 77
Reputation: 92261
Even if int(1)
and float(1)
has the same value, the bit patterns stored in memory are totally different.
When you do (int*) data;
you tell the compiler that the bit patterns are the same, but as you see when you print them, they are not.
So this is not going to work.
In the loop in option 2), the assignment _data[i] = data[i];
doesn't just copy 4 bytes, it also transforms the bit patterns from float
to int
.
Upvotes: 2