作者KaryuuIssen (一闪)
看板C_and_CPP
标题[问题] move constructor
时间Mon Oct 15 05:06:13 2018
开发平台(Platform): (Ex: Win10, Linux, ...)
Linux
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
GCC 5.4
问题(Question):
#include<iostream>
class A {
public:
A() {}
A(
const A& x) { std::cout <<
"Copy constructor\n"; }
A(A&& x) { std::cout <<
"Move constructor\n"; }
};
A func(
int n) {
// no RVO
A temp1, temp2;
if (n>
0)
return temp1;
else
return temp2;
}
int main() {
A a1 =
static_cast<
const A&>(func(
1));
// Move constructor
}
不知道为什麽输出会是Move constuctor而不是Copy constructor
照理说static_cast<const A&>应该把func(1)转成lvalue了才对
而且就算输出是Move constuctor 也不能不定义Copy constructor 否则会编译错
感谢解答
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.112.30.51
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1539551177.A.F42.html
1F:→ bachelorwhc: 编译器帮你选move constructor 你有没有转都没有意义 10/15 06:24
2F:→ bachelorwhc: 你把rvalue reference的constructor删掉 10/15 06:26
意思是因为转型後是lvalue 还是得定义Copy constructor来维持函式重载的语法正确性
但编译器实作上选择Move constructor是另一回事?
※ 编辑: KaryuuIssen (140.112.30.51), 10/15/2018 11:39:08
3F:推 w0005151: 转型跟constructor无关 10/16 09:53