【发布时间】:2016-08-02 12:18:10
【问题描述】:
以下代码运行良好(显示 RVO):
struct A {
A (int) { cout << "A::A()\n"; } // constructor
A (const A&) { cout << "A::A(const A&)\n"; } // copy constructor
};
A foo () { return A(0); }
int main () {
A a = foo();
}
输出:
A::A() // --> which means copy constructor is not called
如果我将复制构造函数标记为explicit:
explicit A (const A&) { ... }
然后编译器报错:
explicit.cpp: In function ‘A foo()’:
explicit.cpp:10:22: error: no matching function for call to ‘A::A(A)’
A foo () { return A(0); }
^
explicit.cpp:5:3: note: candidate: A::A(int)
A (int) { cout << "A::A()\n"; }
^
explicit.cpp:5:3: note: no known conversion for argument 1 from ‘A’ to ‘int’
explicit.cpp: In function ‘int main()’:
explicit.cpp:14:13: error: no matching function for call to ‘A::A(A)’
A a = foo();
^
explicit.cpp:5:3: note: candidate: A::A(int)
A (int) { cout << "A::A()\n"; }
^
explicit.cpp:5:3: note: no known conversion for argument 1 from ‘A’ to ‘int’
为什么会这样,RVO 不应该按原样工作吗?
【问题讨论】:
-
这与 RVO 无关。
-
看起来像这样回答它:stackoverflow.com/questions/29472565/…
-
@KonradRudolph,但是没有
explicit关键字,RVO 正在发生,并且不会制作A的多个副本。当我们将构造函数标记为explicit时,为什么不应该继续进行相同的操作? Q 可能与 RVO 没有直接关系,但我发现两者之间存在一些间接联系。 @NathanOliver,感谢您指出。那个 Q 显示了观察结果。然而,这个问题是关于“为什么?” -
这在答案下方的评论中得到了回答。我想这并不能真正使它成为一个骗局,但嗯。
标签: c++ compiler-errors copy-constructor explicit return-value-optimization