在C++ 03中,表达式是rvalue或lvalue.
在C++ 11中,表达式可以是:
两类已成为五大类.
下面的代码:
#include <iostream>
struct A {
A() { std::cout << "()" << std::endl; }
A(A&&) { std::cout << "(A&&)" << std::endl; }
A(const A&) { std::cout << "(const A&)" << std::endl; }
};
A fun (A&& a){
return a;
}
int main(){
A a;
fun(std::move(a));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在 clang 16.0.3 (arm64-apple-darwin22.4.0 和 c++17) 中产生
()
(A&&)
Run Code Online (Sandbox Code Playgroud)
虽然大多数编译器给出
()
(const A&)
Run Code Online (Sandbox Code Playgroud)
哪一个是正确的?
为什么在从而bar不是移动构造函数返回时调用复制构造函数?
#include <iostream>
using namespace std;
class Alpha {
public:
Alpha() { cout << "ctor" << endl; }
Alpha(Alpha &) { cout << "copy ctor" << endl; }
Alpha(Alpha &&) { cout << "move ctor" << endl; }
Alpha &operator=(Alpha &) { cout << "copy asgn op" << endl; }
Alpha &operator=(Alpha &&) { cout << "move asgn op" << endl; }
};
Alpha foo(Alpha a) {
return a; // Move ctor is called (expected).
}
Alpha bar(Alpha …Run Code Online (Sandbox Code Playgroud)