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 ?
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.
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.
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.
精彩评论