c_cpp 复制和移动语义
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 复制和移动语义相关的知识,希望对你有一定的参考价值。
#include <iostream>
using namespace std;
class A {
public:
A(int id) : id(id) {
cout << "CONSTRUCTOR ID" << endl;
}
A() {
cout << "CONSTRUCTOR" << endl;
}
~A() {
cout << "DESTRUCTOR" << endl;
}
A(const A &other) {
cout << "COPY CONSTRUCTOR" << endl;
}
A(A &&other) : id(0) {
cout << "MOVE CONSTRUCTOR" << endl;
}
A &operator=(const A &other) {
cout << "COPY on Lvalue" << endl;
return *this;
}
A &operator=(A &&other) {
cout << "MOVE on Rvalue" << endl;
return *this;
}
// Invokes move constructor
A &&move_test() {
A a(11);
return move(a);
}
// DANGER! Invokes copy constructor, but after a has been destructed
A ©_test() {
A a(12);
return a;
}
// Passes by value
A value_test() {
A a(12);
return a;
}
// parameter is created by COPY constructor
// return value is created by MOVE constructor
A move_arg_test1(A a) {
// return move(a); // same
return a;
}
// parameter is passed by address
// return value is created by COPY constructor
A &move_arg_test2(A &a) {
return a;
}
// parameter is passed by address (takes only Rvalue)
// return value is created by MOVE constructor
A &&move_arg_test3(A &&a) {
return move(a);
}
private:
int id;
};
int main() {
A a1(6);
A a2(7);
// A a2 = A(4); // calls constructors ???
// A c = a1; // calls COPY constructor
// a1 = a2; // calls COPY operator= on Lvalue
// a1 = a2.move_test(); // calls MOVE operator= on Rvalue
// a1 = A(4); // calls MOVE operator= on Rvalue
A a(8);
// A d = a.move_arg_test1(a);
// A d = a.move_arg_test2(a);
// A d = a.move_arg_test3(A(4));
// A d = a.copy_test();
// A e = a.value_test();
// A c = a.move_test();
return 0;
}
以上是关于c_cpp 复制和移动语义的主要内容,如果未能解决你的问题,请参考以下文章
std::vector 和移动语义
❥关于C++之右值引用&移动语义┇移动构造&移动复制
“语义”是啥意思?为啥“移动语义”这样命名,而不是任何其他术语?
[c++11]右值引用移动语义和完美转发
[转][c++11]我理解的右值引用移动语义和完美转发
右值引用,移动语义,完美转发