[問題] move constructor

作者: KaryuuIssen (一閃)   2018-10-15 05:06:13
開發平台(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 否則會編譯錯
感謝解答
作者: bachelorwhc (單身老王)   2018-10-15 06:24:00
編譯器幫你選move constructor 你有沒有轉都沒有意義你把rvalue reference的constructor刪掉
作者: w0005151 (藍廳)   2018-10-16 09:53:00
轉型跟constructor無關

Links booklink

Contact Us: admin [ a t ] ucptt.com