gpt4 book ai didi

c++ - 在 C++ 中选择可行的构造函数时,何时不考虑用户定义的转换序列?

转载 作者:搜寻专家 更新时间:2023-10-31 00:57:42 26 4
gpt4 key购买 nike

在C++标准草案N4582中看到了如下文字:

[over.best.ics/4] However, if the target is

(4.1) the first parameter of a constructor or

(4.2) the implicit object parameter of a user-defined conversion function

and the constructor or user-defined conversion function is a candidate by

(4.3) 13.3.1.3, when the argument is the temporary in the second step of a class copy-initialization, or

(4.4) 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),

user-defined conversion sequences are not considered.

我对加粗部分一头雾水,不知道怎么理解。我写了下面的程序:

#include <iostream>
using namespace std;
struct A {
A(int) {}
operator int() {cout << "user-defined conversion" << endl; return 0;}
A(A&) {} //prevent default copy
};
int main()
{
A a = A(0);
}

在g++ 5.3.0中运行良好,输出“user-defined conversion”,表示发生了用户自定义的转换。当然,它可以解释为临时 A(0) 不是 copy-initialization 的结果。接下来我将程序更改为:

#include <iostream>
using namespace std;
struct A {
A(int) {}
operator int() {cout << "user-defined conversion" << endl; return 0;}
A(A&) {} //prevent default copy
};
A foo() {return A(0);}
int main()
{
A a = foo();
}

现在 foo() 的值是从 A(0) 初始化的临时拷贝,但程序仍然有效。为什么会这样?

最佳答案

你可以去读[dcl.init]/17对于实际的标准语。这里的“第二步”是指从不相关类型的 b 中复制初始化类类型 A 的变量。在这种情况下,复制初始化分两步进行:

  • 第 1 步:将 b 隐式转换为 A。如果为此调用转换构造函数,它会创建一个临时的 A
  • 第 2 步:然后根据转换结果初始化 A 变量。 (在理智的类(class)中,这通常被省略。)

这句话的意思是您不会在第二步中进行用户定义的转换。

例如,对于您的AA a = 0;。在第一步中,您从 0 中创建一个临时的 A。在第二步中,您尝试使用该临时变量初始化 a,而不使用用户定义的转换。那失败了,因为 A 构造函数都不可行。

关于c++ - 在 C++ 中选择可行的构造函数时,何时不考虑用户定义的转换序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36910778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com