c++ - 在复制初始化中,对复制构造函数的调用是显式的还是隐式的?

标签 c++ g++ language-lawyer

class AAA {
public:
    explicit AAA(const AAA&) {}
    AAA(int) {}
};


int main() {
    AAA a = 1;
    return 0;
}

在上面的代码中,据我了解,虽然在大多数情况下被省略,但在语义上仍然需要调用复制构造函数。我的问题是,调用是显式的还是隐式的?很长一段时间以来,我的脑海里都得出这样的结论:对 AAA::AAA(int) 的调用是隐式的,但对复制构造函数的调用不是。今天不小心弄到g++编译上面的代码,报错了。 (VC12编译OK。)

在标准的第 8.5 节中:

If the destination type is a (possibly cv-qualified) class type:

  • If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.

  • Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3). If the conversion cannot be done or is ambiguous, the initialization is ill-formed. The function selected is called with the initializer expression as its argument; if the function is a constructor, the call initializes a temporary of the cv-unqualified version of the destination type. The temporary is a prvalue. The result of the call (which is the temporary for the constructor case) is then used to direct-initialize, according to the rules above, the object that is the destination of the copy-initialization. In certain cases, an implementation is permitted to eliminate the copying inherent in this direct-initialization by constructing the intermediate result directly into the object being initialized; see 12.2, 12.8.

上面引号中的粗体direct-initialize 表示复制构造函数的调用是显式的,对吧?是 g++ 错误还是我对标准的解释错误?

最佳答案

看起来像这个错误:g++ fails to call explicit constructors in the second step of copy initialization

g++ fails to compile the following code

struct X
{
    X(int) {}
    explicit X(X const &) {}
};

int main()
{
    X x = 1; // error: no matching function for call to 'X::X(X)'
}

The second step of a copy initialization (see 8.5/16/6/2) is a direct-initialization where explicit constructors shall be considered as candidate functions.

关于c++ - 在复制初始化中,对复制构造函数的调用是显式的还是隐式的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21822438/

相关文章:

c++ - 在 pthreads 中指定线程堆栈大小

c++ - 霍夫变换

c++ - 通过迭代器获取集合元素的 "index"

c++ - MingW 上更新的 G++ 收到大量错误消息

c++ - 为什么 MinGW-w64 浮点精度取决于 winpthreads 版本?

c++ - 替换#define

c++ - 包含和/或链接二进制文件未使用的内容会产生什么负面影响?

c++ - 不使用 EOF 位作为我们的流提取条件的真正原因是什么?

c++ - 复制省略直接基类初始化?

javascript - 带有 *this* 的简写属性名称