5

Compare two codes as follow:

  1 #include <new>
  2 #include <cstdio>
  3 class CA
  4 {
  5 public:
  6     int i, j, k;
  7 };  
  8 
  9 int main()
 10 {
 11     int aa[4] = { 1, 2, 3, 4 };
 12     CA *i = new(aa) CA();
 13     printf("%d %d %d %d\n", aa[0], aa[1], aa[2], aa[3]);
 14     return 0;
 15 }   

  1 #include <new>
  2 #include <cstdio>
  3 class CA
  4 {
  5 public:
  6     int i, j, k;
  7 };  
  8 
  9 int main()
 10 {
 11     int aa[4] = { 1, 2, 3, 4 };
 12     CA *i = new(aa) CA;
 13     printf("%d %d %d %d\n", aa[0], aa[1], aa[2], aa[3]);
 14     return 0;
 15 }   

The difference at line 12. At environment of gcc4.1.2, these two codes will get the same result 1 2 3 4 But at gcc4.4 and gcc4.5, the first code will get 0 0 0 4

Why ?

Wei dong
  • 69
  • 1
  • 1
  • 2
  • I believe this is a relevant question for this one (esp. the standard quotes): http://stackoverflow.com/questions/3931312/value-initialization-and-non-pod-types – Naveen Oct 26 '10 at 07:43

3 Answers3

2

First of all, different versions of GCC have different levels of standard compliance.

In this case later versions are "more right" - value initialization must take place in the first snippet (since you implicitly invoke the default compiler-generated constructor for a class with POD member variables) and this will lead to member variables of class CA initialized to zeroes. See this very detailed answer by user Michael Burr as well as this answer to a closely related question.

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
1

That is placement new. You initialized an object of type CA into that memory, and the default values for the i,j and k are zeros, therefore aa[0], aa[1] amd aa[2] are getting zeroed.

BЈовић
  • 62,405
  • 41
  • 173
  • 273
0

I'm inclined to think that both are correct. You've overwritten (part of) the memory used by int aa[4], and then try to access that array. That's not correct: the memory contains an CA object and must be accessed through that type or a compatible type. int [4] and class CA are not compatible types.

This rule is important: an optimizer might cache the value aa[0] in a register, and not reload the register when you put an object at the same memory address.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • This is not correct. He is using placement new. The only requirement is that the storage is greater or equal then the object size (and that is fulfilled). The gcc 4.1 is less standard compliant then gcc 4.5, and this is just one out of many things not comformant with the standard. – BЈовић Oct 26 '10 at 07:54
  • Obviously it's placement new, and that is perfectly allowed. What is _not_ allowed is to use the memory afterwards as if the placement new never happened. – MSalters Oct 27 '10 at 08:14