【发布时间】:2011-02-23 21:43:01
【问题描述】:
我有一个一般性问题,可能与编译器有关。 我对调用构造函数的条件感兴趣。具体来说,在发布模式/针对速度优化的构建中,当您实例化一个对象时,是否总是会调用编译器生成的或空的构造函数?
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 中查看生成的汇编代码。不过,在发布版本中可能很难遵循。
总结: 构造函数总是被调用吗?如果有,为什么?
我知道这在很大程度上取决于编译器,但肯定有一个共同的立场。您可以引用的任何示例/来源将不胜感激。
【问题讨论】:
-
如果您不介意我的提问,这只是出于好奇,还是您的成品质量取决于编译器是否对此进行了优化?
-
两者都有。我正在编写一个数组类(作为练习),它使用类似于 boost::is_pod 的东西来决定是否将模板特化与使用 memswap/memcopy 的实现一起使用,而不是显式调用构造函数/析构函数/赋值运算符。这让我想知道这实际上会对 pod 类型的性能产生多大影响。
-
我希望你不是在你的真实程序中那样动态分配。
标签: c++ constructor compiler-optimization default-constructor