c++ std::move详解
在移动构造中的时候,移动拷贝其实就是把原来参数对象的指针地址给到了构造的对象,再把原先对象的指针置为NULL,这样内存就不会被原来函数给析构了。对于实体的对象执行的其实也是拷贝构造。
&&是可以直接对目标进行直接操作的,对操作者是可见的,不是副本
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
class Str {
public:
char *str;
Str(char value[]) {
cout << "普通构造函数..." << endl;
str = NULL;
int len = strlen(value);
str = (char *)malloc(len + 1);
memset(str, 0, len + 1);
strcpy(str, value);
}
Str(const Str &s) {
cout << "拷贝构造函数..." << endl;
str = NULL;
int len = strlen(s.str);
str = (char *)malloc(len + 1);
memset(str, 0, len + 1);
strcpy(str, s.str);
}
Str(Str &&s) {
cout << "移动构造函数..." << endl;
str = NULL;
str = s.str;
s.str = NULL;
}
~Str() {
cout << "析构函数" << endl;
if (str != NULL) {
free(str);
str = NULL;
}
}
};
class f {
public:
f() {}
explicit f(int &&a) {
a = a + 1;
b = a;
}
~f() {}
void get() { std::cout << "value: " << b << std::endl; }
private:
int b;
};
int main() {
char value[] = "I love zx";
Str s(value);
vector<Str> vs;
vs.push_back(move(s));
// vs.push_back(s);
cout << vs[0].str << endl;
if (s.str != NULL) cout << s.str << endl;
// return 0;
int a = 10;
int b = std::move(a);
std::string c("hello");
std::string d = std::move(c);
// &a = NULL;
f object(std::move(a));
std::cout << " a: " << a << std::endl;
object.get();
std::cout << " b: " << b << std::endl;
std::cout << " c: " << c << std::endl;
std::cout << " d: " << d << std::endl;
}
结果
普通构造函数...
移动构造函数...
I love zx
a: 11
value: 11
b: 10
c:
d: hello
析构函数
析构函数