且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在这种情况下不调用复制构造函数?

更新时间:2023-01-09 21:38:56

从另一个注释:所以默认情况下我不应该依赖它(因为它可能取决于编译器)

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);