Non-POD derived class PayloadMessage contains an array data member (_payload) whose elements appear to be getting zero initialized upon construction. I don’t want this to happen for performance/efficiency reasons — it is a large array. Suggestions? (Placement new maybe?) I’m using an older g++ compiler, 3.4.6.
#include <iostream>
class BaseMessage {
public:
enum CCC_MessageType { START_THREAD, KILL_THREAD };
CCC_MessageType _type;
virtual ~BaseMessage() {} // class has other non-POD class stuff
};
class PayloadMessage : public virtual BaseMessage {
public:
uint16_t _payload_length;
uint8_t _payload[3000];
};
int main(int argc, char* argv[]) {
PayloadMessage* m = new PayloadMessage;
size_t i = 0;
for(; i < 3000; i++) {
std::cout << ' ' << static_cast<int>(m->_payload[i]); // all zeros, not what I want
}
}
EDIT: Okay, based on comments/answers, and some testing (shown below), the array is not being initialized. (Does anyone know what might be causing the memory to appear to be zero-ed out?)
To performance test, I changed main() to the following:
int main(int argc, char* argv[]) {
PayloadMessage* m = new PayloadMessage;
size_t i = 0;
for(; i < 1400000; i++) { // allocates just under 4GB, for 32-bit compatibility
m = new PayloadMessage;
}
}
Then compiled and ran a timed test:
$ g++ -O3 test.cpp
$ time ./a.out
real 0m7.068s
user 0m1.393s
sys 0m4.730s
I then added a constructor to do explicit value initialization for _payload and ran the test again:
PayloadMessage() : _payload() {}
$ g++ -O3 test.cpp
$ time ./a.out
real 0m10.361s
user 0m3.582s
sys 0m5.797s
Yep, the second version with the explicit initialization takes longer, so I assume the first version is not doing initialization (it just looks that way). Thanks all for your help.
POD is only explicitly value initialized when using
()(8.5 in the C++ standard), otherwise, it is default initialized. Default initialization of POD means it does not do anything to the memory. Ifoperator newis returning zero initialized memory, then the constructor ofPayloadMessageisn’t doing any extra work. Out of curiosity, did you inspect the disassembly ofPayloadMessage‘s constructor to determine if it’s actually doing anything expensive?