点击(此处)折叠或打开
- #ifndef _A_H_
- #define _A_H_
- #include <stdio.h>
- #include <new>
- class A
- {
- public:
-         A()
-         {
-                 printf("In A::(). m_x=%d\n", m_x);
-                 A(0);
-                 printf("Out A::(). m_x=%d\n", m_x);
-         }
-         A(int x)
-         {
-                 printf("In A::(int x). x=%d\n", x);
-                 m_x=x;
-         }
- private:
-         int m_x;
- };
这里第11行的调用A(0);只是构建了一个A的临时对象,并没有调用A(int x)来初始化自己。其运行结果是:
点击(此处)折叠或打开
- [root@tivu25 utcov]# ./UTest.out 
 In A::(). m_x=4268020
 In A::(int x). x=0
 Out A::(). m_x=4268020
正确的方法是使用placement new:
点击(此处)折叠或打开
- //A.h
- #ifndef _A_H_
- #define _A_H_
- #include <stdio.h>
- #include <new>
- class A
- {
- public:
-         A()
-         {
-                 printf("In A::(). m_x=%d\n", m_x);
-                 new(this) A(0);
-                 printf("Out A::(). m_x=%d\n", m_x);
-         }
-         A(int x)
-         {
-                 printf("In A::(int x). x=%d\n", x);
-                 m_x=x;
-         }
- private:
-         int m_x;
- };
- #endif
第11行应为: new(this) A(0); 也就是用当前对象来调用构造函数A(int x)构建一个“新”对象。其运行结果是:
点击(此处)折叠或打开
- [root@tivu25 utcov]# ./UTest.out 
- In A::(). m_x=4268020
- In A::(int x). x=0
- Out A::(). m_x=0
可以看出,当前对象确实被改变了。
《返璞归真--UNIX技术内幕》在全国各大书店及网城均有销售:
