为什么在这种情况下不调用复制构造函数? [英] Why copy constructor is not called in this case?
问题描述
以下是小代码片段:
class A
{
public:
A(int value) : value_(value)
{
cout <<"Regular constructor" <<endl;
}
A(const A& other) : value_(other.value_)
{
cout <<"Copy constructor" <<endl;
}
private:
int value_;
};
int main()
{
A a = A(5);
}
我假设输出将是Regular Constructor LHS的复制构造函数。所以我避免了这种风格,总是声明变量类 A a(5);
。但是令我惊讶的是,在上面的代码中,复制构造函数从未被调用(Visual C ++ 2008)
I assumed that output would be "Regular Constructor" (for RHS) followed by "Copy constructor" for LHS. So I avoided this style and always declared variable of class as A a(5);
. But to my surprise in the code above copy constructor is never called (Visual C++ 2008)
有人知道这种行为是编译器优化的结果,和便携)功能的C ++?谢谢。
Does anybody know if this behavior is a result of compiler optimization, or some documented (and portable) feature of C++? Thanks.
推荐答案
从另一个注释:所以默认情况下我不应该依赖它(因为它可能取决于编译器)
From another comment: "So by default I should not rely on it (as it may depend on the compiler)"
不,它不依赖于编译器,实际上无论如何。任何编译器都不会浪费时间构造一个A,然后复制它。
No, it does not depend on the compiler, practically anyway. Any compiler worth a grain of sand won't waste time constructing an A, then copying it over.
在标准中,它明确表示它完全可以接受 T = x;
等价于说 T(x);
。 (§12.8.15,pg.211)这样做与 T(T(x))
显然是多余的,所以它删除内部 / code>。
In the standard it explicitly says that it is completely acceptable for T = x;
to be equivalent to saying T(x);
. (§12.8.15, pg. 211) Doing this with T(T(x))
is obviously redundant, so it removes the inner T
.
为了获得所需的行为,你必须强制编译器默认构造第一个A:
To get the desired behavior, you'd force the compiler to default construct the first A:
A a;
// A is now a fully constructed object,
// so it can't call constructors again:
a = A(5);
这篇关于为什么在这种情况下不调用复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!