Reputation: 387
void* GetData()
{
return reinterpret_cast<unsigned char*>(this);
}
Is there a case of automatic type coercion happening in this case ??? How could I convert the object of my class to an unsigned char* ??
Upvotes: 0
Views: 282
Reputation: 58677
I assume you refer to return reinterpret_cast<unsigned char*>(this);
This is a nasty chunk that is probably taking the wrong approach in solving the wrong problem. Technically, it asks the compiler to re-interpret the type of the this
pointer as an unsigned char*
pointer. No work is done here: the statement only instructs the compiler to think of the pointer as of a different type. This is disastrous if it's wrong to interpret the type as such.
If you wish to inspect your object bitwise then you might try something like this:
union inspect_klass {
klass obj;
char bits[sizeof(klass)];
};
EDIT: My confidence about the above union is shaken now. Don't use it just yet, I'm looking for confirmation that this trick is indeed broken. :s
Upvotes: 6
Reputation: 43
Strictly speaking, unsigned char* is a byte array. It seems like a perfectly logical thing to do if the caller is going to serialize the data.
Upvotes: 0
Reputation: 4336
I agree with the other posts: this is almost certainly not what you intend to do.
However, IIRC, you are guaranteed by the C++ standard to be able to convert a pointer of any type (not including function or member pointers) to an unsigned char *
or a void *
and back without entering the realm of undefined behavior. Additionally, you may access any object through an lvalue of type char *
or unsigned char *
(see ISO 14882:2003 section 3.10.15). I have made use of this before in order to inspect the internal representation of arbitrary object types. This results, if my reading of the standard is correct, in "implementation-defined behavior" (obviously, the internal representation of types depends upon the implementation).
For example,
template<class T> std::vector<unsigned char> to_bytes (const T& t)
{
const unsigned char *p = reinterpret_cast<const unsigned char *>(&t);
return std::vector<unsigned char>(p, p + sizeof(T));
}
is a template function that will yield a std::vector<unsigned_char>
which is a copy of the object's internal representation.
However, the fact that you cast to void *
when you return makes me suspect you are doing something perhaps more unsavory and more undefined.
Upvotes: 1
Reputation: 33177
First off, your GetData() return type does not match the return type of the expression.
reinterpret_cast is similar to old an old style C cast - you are simply returning a pointer to a unsigned char*. It is completely unsafe. In effect, you are creating a view into the data of a class, which can be accessed byte-wise.
Upvotes: 0