在下面的代码中:
#include<iostream>
using namespace std;
class Father
{
public:
int a=11;
void f(){ cout<<"f called"<<endl;}
};
int main(){
Father *obj;
cout <<obj->a<<endl; //I get a garbage value and the compiler issues a warning: 'obj' is used uninitialized in this function
Father f;
cout <<f.a<<endl; // it prints 11
return 1;
}
cout <<obj->a<<endl;
正在打印垃圾值,而不是默认值11,就像上面的一样。他们不是应该打印相同的吗?为什么使用指针而不是直接实例化对象时不使用类成员的默认值?
最佳答案
Aren't they suppose to print the same?
不,这是UB。
给定
Father *obj;
,obj
是default-initialized,其值不确定,Default initialization of non-class variables with automatic and dynamic storage duration produces objects with indeterminate values
这意味着
obj
没有指向任何有效的对象,并且对其取消引用会导致undefined behavior,一切皆有可能。您需要使其指向有效对象,例如Father f;
Father *obj = &f;
cout <<obj->a<<endl;
要么
Father *obj = new Father;
cout <<obj->a<<endl;
delete obj;
Father f;
也执行default-initialization。作为类类型,f.a
初始化为值11
。if T is a
non-POD (until C++11)
class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object;
顺便说一句:C++ 11支持Default member initializer(在
int a=11;
类中编写Father
时),请尝试使用C++ 11(或更高版本)模式编译代码。
关于c++ - 为什么使用指针而不是直接实例化对象时不使用类成员的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59277454/