隐式构造函数转换的编译器优化
在下面的代码中,我期望调用 A 的构造函数,然后调用 A 的复制构造函数。然而,事实证明只有构造函数被调用。
// MSVC++ 2008
class A
{
public:
A(int i):m_i(i)
{
cout << "constructor\n";
}
A(const A& a)
{
m_i = a.m_i;
cout << "copy constructor\n";
}
private:
int m_i;
};
int main()
{
// only A::A() is called
A a = 1;
return 0;
}
我猜编译器足够聪明,可以优化第二次调用,直接使用构造函数初始化对象a。那么它是标准定义的行为还是只是实现定义的?
In the following code, I expect A's constructor is called, followed by A's copy constructor. However, It turns out only constructor is get called.
// MSVC++ 2008
class A
{
public:
A(int i):m_i(i)
{
cout << "constructor\n";
}
A(const A& a)
{
m_i = a.m_i;
cout << "copy constructor\n";
}
private:
int m_i;
};
int main()
{
// only A::A() is called
A a = 1;
return 0;
}
I guess the compiler is smart enough to optimize away the second call, to initialize the object a directly with the constructor. So is it a standard-defined behavior or just implementation-defined?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是标准的,但不涉及优化。实际上,我相信涉及优化,但它仍然完全标准。†
此代码:
调用 转换
A
的构造函数††。A
有一个转换构造函数A(int i)
,允许从int
到的隐式转换一个。
如果您在构造函数声明前加上
explicit
,您会发现代码无法编译。† 再次查看标准后,我最初可能是错的。
所以从某种意义上说,这很大程度上是一种优化。但我不会担心它,因为它是标准明确允许的,而且现在几乎每个编译器都会这样做。
有关初始化的更彻底的处理,请参阅这篇 GotW 文章 (#36)。文章似乎同意上述标准的解释:
††
ISO/IEC 14882:2003 C++ 标准参考
It's standard, but there's no optimization involved.Actually, I believe there is an optimization involved, but it's still entirely standard.†
This code:
invokes the converting constructor†† of
A
.A
has a single converting constructorA(int i)
that allows an implicit conversion fromint
toA
.If you prepend the constructor declaration with
explicit
, you'll find the code won't compile.† After looking at the standard again, I may have been initially wrong.
So in one sense it is very much an optimization. But I wouldn't worry about it since it is explicitly allowed by the standard and just about every compiler nowadays does the elison.
For a much more thorough treatment on initialization, see this GotW article (#36). The article seems to agree with the above interpretation of the standard:
††
ISO/IEC 14882:2003 C++ Standard reference
这里没有优化。当在初始化中使用
=
时,它相当于(几乎)以右侧作为参数调用构造函数。所以这:(大部分)相当于:
No optimization here. When
=
is used in the initialization, it is eqivalent(nearly) to calling the constructor with the right hand side as an argument. So this:Is (mostly) equivalent to this: