c++ - 为什么使用指针而不是直接实例化对象时不使用类成员的默认值?

标签 c++ oop initialization

在下面的代码中:

#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;objdefault-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/

相关文章:

c++ - 是什么激发了 Stroustrup 对资源管理技术的偏好顺序?

java - A 类中的构造函数 A 不能应用于给定类型;

c++ - C++ 中是否存在未初始化的对象?

java - 初始化静态字段(例如 BigDecimal)时如何避免魔数(Magic Number)警告?

c++ - 生成库版本和构建版本

c++ - 对 'ClassName::memberField[abi:cxx11]' 的 undefined reference

c++ - 如何独立于所用机器测量性能

c++ - 有什么 C++ 可以比 D 做得更好,或者 D 不能做的吗? (多重继承的例子)

c++ - 与 std::list 一起使用的指针上的接口(interface)类型转换的多重继承

java - 如何修复返回 int 的方法中的 int 初始化问题