c++ std::move详解

c++ std::move详解

img

img

在移动构造中的时候,移动拷贝其实就是把原来参数对象的指针地址给到了构造的对象,再把原先对象的指针置为NULL,这样内存就不会被原来函数给析构了。对于实体的对象执行的其实也是拷贝构造。

&&是可以直接对目标进行直接操作的,对操作者是可见的,不是副本

#include 
#include 
#include 
#include 
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 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 zxa: 11
value: 11b: 10c: d: hello
析构函数
析构函数

参考链接


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部