第2个回答 推荐于2017-09-29
{
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
可以看到尽管调用了A(0),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