【发布时间】:2020-03-14 18:04:05
【问题描述】:
这里有一些代码
#include <iostream>
struct A {
A(int) {}
};
struct B {
B(A) {
std::cout<<"0"<<std::endl;
}
B(B const&) {
std::cout << "1" << std::endl;
}
B(B&&) {
std::cout << "2" << std::endl;
}
};
int main() {
B b0{{0}}; // this is ok #1
B b( {0} ); //this is error #2
}
g++ 报告:
main.cpp: In function ‘int main()’:
main.cpp:17:11: error: call of overloaded ‘B(<brace-enclosed initializer list>)’ is ambiguous
B b({ 0 });
^
main.cpp:12:2: note: candidate: B::B(B&&)
B(B&&) {
^
main.cpp:9:2: note: candidate: B::B(const B&)
B(B const&) {
^
main.cpp:6:2: note: candidate: B::B(A)
B(A) {
叮当报告:
main.cpp:17:4: error: call to constructor of 'B' is ambiguous
B b({ 0 });
^ ~~~~~
main.cpp:6:2: note: candidate constructor
B(A) {
^
main.cpp:12:2: note: candidate constructor
B(B&&) {
^
main.cpp:9:2: note: candidate constructor
B(B const&) {
^
1 error generated.
{0} 将转换为临时对象 A 并选择构造器 B(A), #1 和#2 都是“直接构造函数”的形式,为什么#1 可以,#2 有三个候选构造函数并且是模棱两可的?
【问题讨论】:
-
{0}也可以是B,从0隐式转换为A。 -
@Jarod42 这是问题,#1 使用 B(A) 而#2 是模棱两可的?
-
一个{0};乙 b { 0 };这些都是有效的。那么,在 B b( { 0 }) 中,{ 0 } 代表什么? A 或 B 的实例?没有人知道,这就是它模棱两可的原因:您是在调用 B ( A ) 还是在调用 B ( const B& ) ?甚至是 B ( B && ) ?
-
而 #1 有效,因为 B b0{ 不管 };调用构造函数,而不是复制或移动构造函数。
-
@MFnx2 谢谢,你有一些关于你的解释“B b0{whatever};调用构造函数,而不是复制或移动构造函数”的c ++标准引用吗?
标签: c++ c++11 language-lawyer