Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: POD and POD-wrapping objects

Tags:

c++

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 ...
}
  1. 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?

  2. 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 )?

like image 363
peoro Avatar asked Apr 18 '26 02:04

peoro


2 Answers

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).

like image 128
Johannes Schaub - litb Avatar answered Apr 19 '26 15:04

Johannes Schaub - litb


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.,

like image 45
Cheers and hth. - Alf Avatar answered Apr 19 '26 16:04

Cheers and hth. - Alf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!