[英]How does the C++ create new object with initialize/ constructor?
I was trying to understand how objects create and initialize constructors.我试图了解对象如何创建和初始化构造函数。 I want to create an object with a "person class" with "*name" feature and test if the name pointer is NULL or not once I create a object.我想创建一个 object 和一个带有“*name”功能的“person class”,并在我创建 object 后测试名称指针是否为 NULL。
I first test with dynamic allocation "new" to create the object and the pointer is null.我首先使用动态分配“new”进行测试,以创建 object,指针为 null。 However, If I use static to create the object and the pointer is not null.但是,如果我使用 static 创建 object 并且指针不是 null。
class person{
public:
string *name;
person(){
}
~person(){}
};
The above is class definition.以上是class的定义。
int main(){
person *jack = new person();
cout << jack->name << endl;
if(jack->name == NULL){
cout << "is null" << endl;
} else{
cout << "not null" << endl;
}
return 0;
}
The above will output: 0x0, is null上面会 output: 0x0, 就是 null
int main(){
person louis = person();
cout << louis.name << endl;
if(louis.name == NULL){
cout << "is null" << endl;
} else{
cout << "not null" << endl;
}
return 0;
}
The above will output: 0x7ffeee80b918, not null上面会 output: 0x7ffeee80b918,不是 null
Moreover, if I put the two together:此外,如果我将两者放在一起:
int main(){
person *jack = new person();
cout << jack->name << endl;
if(jack->name == NULL){
cout << "is null" << endl;
} else{
cout << "not null" << endl;
}
person louis = person();
cout << louis.name << endl;
if(louis.name == NULL){
cout << "is null" << endl;
} else{
cout << "not null" << endl;
}
return 0;
}
The above will output: 0x0, is null, 0x0, is null.上面会 output: 0x0, 就是 null, 0x0, 就是 null。
I was trying to figure out why using "new" or not will have a different result on the "name" pointer?我试图弄清楚为什么使用“新”或不使用“名称”指针会有不同的结果?
With "new" the name pointer will be NULL Without "new" the name pointer will not be NULL使用“new”,名称指针将是 NULL 没有“new”,名称指针将不是 NULL
Moreover, If I put create two objects, the first one creates with new and the second one creates without new.此外,如果我创建两个对象,第一个使用 new 创建,第二个创建没有 new。 the result will all become NULL.结果将全部变为 NULL。 why the first object will affect the name pointer on the second object?为什么第一个 object 会影响第二个 object 上的名称指针?
You are dealing with "undefined behavior."您正在处理“未定义的行为”。 So instead of trying to differentiate between the output for both types of initialization, change your declaration of name in your class definition from string *name;
因此,不要尝试区分两种初始化类型的 output,而是将 class 定义中的名称声明从string *name;
to string *name = nullptr;
到string *name = nullptr;
to guarantee that name starts off as NULL保证名称以 NULL 开头
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.