c++ - 构造函数/析构函数是否必须有代码,或者函数是否足够?

标签 c++

如果我要上课

class Transaction {

int no;
char dollar;

public:

    Transaction();
    ~Transaction();
}

在我的构造函数/析构函数中

Transaction::Transaction {
    cout << "Entering constructor" << endl;
}

Transaction::~Transaction {
    cout << "Leaving program" << endl;
}

该代码是否足以让我的构造函数和析构函数工作?即使我在构造函数中未声明任何内容,它是否会将我类中的数据成员设置为安全状态?

最佳答案

如果您提供构造函数而没有为所述子对象指定初始化器,则每个子对象都将被默认初始化。

标准第 8.5 节规定:

If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value. [ Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. — end note ]

还有那个

To default-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type, the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is an array type, each element is default-initialized;
  • otherwise, no initialization is performed.

If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

有两种方法可以初始化子对象:在 ctor-initializer-list 中,以及在成员声明中的 brace-or-equal-initializer 中(对于非-static 成员,后者是 C++11 中的新成员)。

实际上,这意味着当您不提供初始值设定项时,基本类型的变量,例如 intchar,将保留内存中剩余的任何值之前。在大多数情况下,很难预测该值是什么,但您应该意识到它可能是遗留的敏感数据,例如密码。

在初始化静态存储持续时间的变量(例如 namespace 范围内的对象及其成员)的情况下,标准进一步规定(同一部分):

Every object of static storage duration is zero-initialized at program startup before any other initialization takes place.

如果您没有定义构造函数,这与值初始化期间发生的情况略有不同:

To value-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type with a user-provided constructor, then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.
  • if T is an array type, then each element is value-initialized;
  • otherwise, the object is zero-initialized.

但效果是一样的——原始成员被设置为零,所有其他成员都调用了它们的零参数构造函数。

nneonneo 明确初始化所有成员的建议很好,因为仅对静态存储持续时间的变量进行零初始化通常会导致难以发现的错误。但是使用 brace-or-equal-initializer 技术是完全可行的:

class Transaction
{
    int no = 0;
    char dollar = 0;
public:

    Transaction();
    ~Transaction();
}

关于c++ - 构造函数/析构函数是否必须有代码,或者函数是否足够?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15149363/

相关文章:

c++ - 函数总是返回 1

c++ - 引用初始化表格

c++ - ZeroMQ dealer--to-dealer 与 winsock 相比延迟高

c++ - 获取 OpenCV 错误 : Insufficient memory while running OpenCV Sample Program: "stitching_detailed.cpp"

c++ - C++-有什么方法可以为性能和封装构造常量数据?

c++ - 为什么 0 乘以负 double 会变成 -0?

c++ - 类的成员应该是指针吗?

c++ - 带有文件流的 RAII

java - 从 BST 获取最大值和最小值(C++ 与 Java)

c++ - 如何处理模板类 header 中的循环 #include 调用?