Reputation: 26060
Often I declare classes to wrap a single Plain Old Data value; simple classes without virtual functions, like:
class Velocity {
int vel;
public:
// functions to work with velocity ...
}
Working with such object is the same as working with POD values? -- Is there any difference in space or time usage, if in my code I used an int
, instead of a Velocity
? Does the standard say anything about this?
Can I cast a pointer or an array of such objects as a pointer/array of POD values and viceversa? -- Am I totally safe doing Velocity *v = reinterpret_cast< Velocity* >( int_pointer )
?
Upvotes: 2
Views: 831
Reputation: 145379
Re "is the same as POD", not entirely in C++98. C++98 doesn't permit PODs to have private members. C++0x lifts this restriction (and a few others).
Re efficiency, or lack thereof, it's a Quality of Implementation issue.
Ask your compiler to optimize, then measure, if it matters.
Re casting: no, that has implementation defined effect. Don't do it.
Cheers & hth.,
Upvotes: 4
Reputation: 507125
Working with such object is the same as working with POD values?
No. You are not totally safe to use memcpy
and friends on it (only allowed on PODs!).
Can I cast a pointer or an array of such objects as a pointer/array of POD values and viceversa?
If it is a POD, you are perfectly safe. But this is not a POD because it has a private data member.
Both of that said, in practice it will work fine for that class (and in C++0x, you are allowed to use such a class with private members with memcpy
, because it allows it for all trivially copyable types, which includes your type and many other non-PODs).
Upvotes: 4
Reputation: 64253
1) Your example is not POD, because the class has the private field
2) The standard doesn't define what happens when the reinterpret_cast is used. Anything that happen is implementation defined.
Upvotes: 1