所谓移动构造已经没有意义了
用不用移动构造都是一次构造一次析构,下面代码c++太蛋疼了
#include <stdio.h>
#include <iostream>
using namespace std;
class A
{
public:
int a;
A(){a = 1; printf ("NULL constructor: %u\r\n", a);}
A (int i){a = i; printf ("INT constructor: %u\r\n", a);}
A (A && aa){a = aa.a; printf ("rref constructor: %u\r\n", a);};
~A(){printf ("destructor: %u\r\n", a);};
};
A tt (void)
{
A a1(10);
return a1;
}
int main (void)
{
A b = tt();
//A b(tt());
b.a=11;
printf ("main exiting\n");
return 0;
}
root@ubuntu:~# g++ -std=c++0x 1.cpp -o ./1
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# ./1
main exiting
destructor: 11
root@ubuntu:~# g++ -std=c++0x 1.cpp -o ./1
root@ubuntu:~# ./1
INT constructor: 10
main exiting
destructor: 11
root@ubuntu:~# g++ -std=c++0x 1.cpp -o ./1
root@ubuntu:~# ./1
INT constructor: 10
main exiting
destructor: 11
root@ubuntu:~#
压根就 不调用什么复制或者移动构造函数,直接就只有一个对象
#include <stdio.h>
#include <iostream>
using namespace std;
class A
{
public:
int a;
A(){a = 1; printf ("NULL constructor: %u\r\n", a);}
A (int i){a = i; printf ("INT constructor: %u\r\n", a);}
A (A && aa){a = aa.a; a = a+1; printf ("rref constructor: %u %u\r\n", a, aa.a);};
A (A & aa){a = aa.a; a = a+1; printf ("Lref constructor: %u %u\r\n", a, aa.a);};
~A(){printf ("destructor: %u\r\n", a);};
};
A tt (void)
{
A a1(10);
return a1;
}
int main (void)
{
//A b = tt();
A b(tt());
b.a=b.a + 2;
printf ("main exiting\n");
return 0;
}
root@ubuntu:~# g++ -std=c++0x 1.cpp -o ./1
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# g++ -std=c++0x 1.cpp -o ./1
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# ./1
INT constructor: 10
main exiting
destructor: 12
root@ubuntu:~# 因为这是C++早就有的 RVO/NRVO 呀,搜索一下 Copy Ellision 就知道了 本帖最后由 mordorwww 于 2017-03-16 08:43 编辑
bruceteen 发表于 2017-03-16 08:25
因为这是C++早就有的 RVO/NRVO 呀,搜索一下 Copy Ellision 就知道了
我昨天半夜跑了下c++ primer 6上的move 构造例子,发现压根就没进move构造函数,一种被大牛忽悠的感觉,泪奔啊
mordorwww 发表于 2017-03-16 08:38
我昨天半夜跑了下c++ primer 6上的move 构造例子,发现压根就没进move构造函数,一种被大牛忽悠的感觉, ...
RVO比move更早吧,你要把返回的变量放其他地方也许就有move了,但是你这个move有个卵用啊,又没有堆上内容,还不是要老老实实的拷贝或者赋值 move constructor应该改个名字叫constructor you can customize when you need to move some data.
编译器才不会帮你去move什么鬼,你得自己去move你想要move的东西。
在你这个例子里根本就没什么可以move的,所以你可以洗洗睡了。 本帖最后由 mordorwww 于 2017-03-20 09:00 编辑
windoze 发表于 2017-03-19 21:09
move constructor应该改个名字叫constructor you can customize when you need to move some data.
编译器 ...
这是c++ primer6的移动构造例子,不是我的例子 回复 7# mordorwww
C++ Primer6很老了,大概是C++11刚发布没多久那会儿,当时很多编译器对C++11的支持还不完整,更别说后来的14和17了。 mordorwww 发表于 2017-03-20 08:55
这是c++ primer6的移动构造例子,不是我的例子
A tt (void)
{
A a1(10);
return std::move(a1);
}好吧,这样就行了
windoze 发表于 2017-03-20 14:58
回复 7# mordorwww
求大佬们写个7
页:
[1]