gpt4 book ai didi

c++ - 在 C++ 中总是调用空构造函数吗?

转载 作者:可可西里 更新时间:2023-11-01 18:02:28 25 4
gpt4 key购买 nike

我有一个一般性问题,可能有点特定于编译器。我对调用构造函数的条件很感兴趣。具体来说,在 Release模式/针对速度优化的构建中,当您实例化一个对象时,是否总是会调用编译器生成的或空的构造函数?

class NoConstructor  
{
int member;
};

class EmptyConstructor
{
int member;
};

class InitConstructor
{
InitConstructor()
: member(3)
{}
int member;
};

int main(int argc, _TCHAR* argv[])
{
NoConstructor* nc = new NoConstructor(); //will this call the generated constructor?
EmptyConstructor* ec = new EmptyConstructor(); //will this call the empty constructor?
InitConstructor* ic = new InitConstructor(); //this will call the defined constructor

EmptyConstructor* ecArray = new EmptyConstructor[100]; //is this any different?
}

我进行了大量搜索,并花了一些时间查看 Visual Studio 中生成的汇编代码。不过在发布版本中可能很难遵循。

总结:总是调用构造函数吗?如果是,为什么?

我知道这在很大程度上取决于编译器,但肯定有一个共同的立场。非常感谢您可以引用的任何示例/来源。

最佳答案

will a compiler generated constructor/empty constructor always be called when you instantiate an object?

没有。如果您的类是所谓的“POD”(普通旧数据),那么编译器生成的构造函数不会总是被调用。

具体以下两种情况不会被调用:

struct Pod {
int x;
};

int main() {
Pod pod;
std::cout << pos.x << std::endl; // Value undefined.

Pod pod2 = Pod(); // Explicit value initialization.


Pod* pods = new Pod[10];
// Values of `pods` undefined.

Pod* pods2 = new Pod[10](); // Explicit value initialization.
}

判断一个类型何时是 POD 的条件有点棘手。 C++ FAQ has a nice breakdown .

关于c++ - 在 C++ 中总是调用空构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5097545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com