在创建 class 实例时使用 () 和不使用 () 有什么区别

What is the difference between using () and not using () in creating class instance

我写了一个class这样的

#include <iostream>
using std::cout;

class Resource
{
    public:
        Resource(){ cout << "allocated\n";}
        ~Resource(){ cout << "deleted\n";}
};

然后在 int main() 我创建了 class

的 2 个实例
int main()
{
    Resource* p1 = new Resource();
    Resource* p2 = new Resource;
}

new Resourcenew Resource()有什么区别?

new Resource()执行value initialization, new Resource performs default initialization,它们在这里的作用相同,即对象由用户提供的默认构造函数初始化。

对于非class类型,或具有非用户提供的默认构造函数的class类型,它们的行为是不同的;对于值初始化,对象将是 zero-initialized(首先,如果 class 类型的默认构造函数是非平凡的,则对象将被默认初始化)。

...

  1. if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor;

...

  1. otherwise, the object is zero-initialized.

括号确实有所作为!正如@songyuanyao 指出的那样:您使用括号调用 value initialisation ,而没有它的默认初始化。对于像 Resource 这样的 class 类型,您不会看到任何差异。在这两种情况下都会调用构造函数。

但是,如果您有 int 等基本数据类型,则差异会更大:

int a{};
int b;

a 的值为 0,因为它是已初始化的值(默认为 0)。然而,b 将具有垃圾值,即统一化的值。这就是为什么使用未初始化的变量被认为是不好的做法,因为它可能会导致意想不到的后果。


值得补充的是,从 C++11 开始,我们有了使用大括号初始化变量的统一方式:{}。它消除了以前对基本类型、聚合和非聚合类型、数组和标准容器的区分。