【发布时间】:2019-03-08 05:38:08
【问题描述】:
我写了一个程序检查类创建的init过程,发现多次调用构造函数改变了成员指针地址。看看下面的sn-p。
#include <iostream>
using namespace std;
class FF {
public:
FF(){
this->ptr = NULL;
value = 1;
cout << "ptr address in 1: " << this->ptr <<endl;
}
FF(const int* ptrcopy, const int valuecopy){
cout << "ptr address in 2: " << this->ptr << endl;
FF();
/* Is this equivalent with FF() ?
this->ptr = NULL;
value = 1;
*/
init(ptrcopy, valuecopy);
}
void init(const int* ptrcopy, const int valuecopy) {
cout << "ptr address in 3: " << this->ptr << endl;
if (this->ptr != NULL)
{
cout << "error happened, the address of ptr is " << this->ptr << endl;
return;
}
}
private:
int* ptr;
int value;
};
int main(){
int *ptr = new int(10);
int value = 1;
FF fclass(ptr, value);
delete(ptr);
return 0;
}
输出是
ptr address in 2: 0x400b40
ptr address in 1: 0
ptr address in 3: 0x400b40
error happened, the address of ptr is 0x400b40
看来FF()的调用只是将ptr所在空间初始化为NULL,调用后ptr又变回原来的0x400b40。
有人可以解释一下吗?
【问题讨论】:
-
离题:更喜欢 C++ 关键字 (
nullptr) 而不是旧的(过时的)C 宏 (NULL)。优先使用构造函数的初始化列表(不要与std::initializer_list混淆)而不是in-body-initialisation,即。 e.FF() : ptr(nullptr) { }而不是FF() { ptr = nullptr; };您避免默认初始化+赋值,而是直接使用参数进行初始化,在某些情况下(引用、没有默认构造函数的类、const 对象),初始化列表是构造/初始化成员的唯一方法。
标签: c++ pointers construction