显式复制构造函数行为和pratical使用 [英] Explicit copy constructor behavior and pratical uses
问题描述
最近的一个问题让我想知道显式复制构造函数。下面是我在Visual Studio 2005下编译的示例代码:
A recent question got me wondering about explicit copy constructors. Here is a sample code that I tried compiling under Visual Studio 2005 :
struct A
{
A() {}
explicit A(const A &) {}
};
// #1 > Compilation error (expected behavior)
A retByValue()
{
return A();
}
// #2 > Compiles just fine, but why ?
void passByValue(A a)
{
}
int main()
{
A a;
A b(a); // #3 > explicit copy construction : OK (expected behavior)
A c = a; // #4 > implicit copy construction : KO (expected behavior)
// Added after multiple comments : not an error according to VS 2005.
passByValue(a);
return 0;
}
现在提出问题:
- 标准是否允许#2?如果是,那么描述这种情况的相关部分是什么?
- 你知道显式复制构造函数的任何实际用途吗?
我在 MSDN 具有完全相同的情况,并从主要功能的一个神秘的注释:c被复制(好像很明显)。
I just found a funny link on MSDN with the exact same situation, and a mysterious comment from the main function : "c is copied" (as if it was obvious). As pointed by Oli Charlesworth : gcc does not compile this code and I believe he's right not to.
推荐答案
我相信相关章节的C ++ 03是§12.3.1 2:
I believe the relevant sections of C++03 are §12.3.1 2:
显式构造函数构造对象就像非显式构造函数一样,但只有在直接初始化语法( 8.5 )或其中强制转换( 5.2 .9 , 5.4 )。默认构造函数可以是显式构造函数;这样的构造函数将用于执行默认初始化或值初始化( 8.5 )。
An explicit constructor constructs objects just like non-explicit constructors, but does so only where the direct-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used. A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or value-initialization (8.5).
和 §8.5 12:
在参数传递,函数返回,抛出异常(15.1 ),处理异常( 15.3 )和大括号初始值列表( 8.5。 1 )被称为复制初始化,并相当于
The initialization that occurs in argument passing, function return, throwing an exception (15.1), handling an exception (15.3), and brace-enclosed initializer lists (8.5.1) is called copy-initialization and is equivalent to the form
T x = a;
在新表达式中进行初始化( 5.3.4 ),static_cast表达式( 5.2.9 ),功能符号类型转换( 5.2.3 ),和基本和成员初始值设置( 12.6.2 )被称为直接初始化,并且相当于form
The initialization that occurs in new expressions (5.3.4), static_cast expressions (5.2.9), functional notation type conversions (5.2.3), and base and member initializers (12.6.2) is called direct-initialization and is equivalent to the form
T x(a);
调用 passByValue code>涉及复制初始化,而不是直接初始化,因此应该是一个错误,根据C ++ 03§12.3.1 2。
Calling passByValue(a)
involves copy-initialization, not direct-initialization, and thus should be an error, according to C++03 § 12.3.1 2.
这篇关于显式复制构造函数行为和pratical使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!