读书人

C++11 move构造判定(is_move_construc

发布时间: 2012-09-22 21:54:54 作者: rapoo

C++11 move构造判定(is_move_constructible)问题
之前的帖子结贴了,又没说清楚,就重开一帖,顺便散分

回顾:

前两天的帖子
http://topic.csdn.net/u/20120828/20/88cf9c19-7f9c-40b4-9726-f321a0bea64d.html
http://topic.csdn.net/u/20120903/15/c4000066-0247-431f-9d4a-c051f94ef595.html


stackoverflow上的一个帖子
http://stackoverflow.com/questions/7054952/type-trait-for-moveable-types


前景提要:is_move_constructible总是返回ture,没法返回false.

之前看了下gcc4.7的源码,确认is_move_constructible<void>::value会返回false.但当时的楼主说vs2012还是ture,而且提供了一个stackoverflow的帖子(上面有链接)

恰好昨天没事,就装了一个vs2012,用下面的代码测试了下,发现确实返回1(true)

C/C++ code
#include <iostream>using namespace std;struct copy_only {    copy_only(copy_only const&) {} // 屏蔽copy_only(copy_only&&)};int main(){    cout<<std::is_move_constructible<copy_only>::value<<endl;    return 0;}


后来发现 copy_only(copy_only const&)中的这个const应当去掉,否则无法屏蔽 move constructor
于是改写成copy_only(copy_only &),结果还是一样。
而且is_move_constructible<void>::value在vs2012中也是1(ture),不是很信任M$的产品对标准的支持,
于是又换回gcc(至少单从void来讲,gcc在is_move_constructible模板推导时是有void特例的)

果然下面这行代码在gcc4.7中得到了0(false)
C/C++ code
#include <iostream>using namespace std;struct copy_only {    copy_only(copy_only& ) {} //当然这里不能加const,stackoverflow上面那个人应该是笔误};int main(){    cout<<std::is_move_constructible<copy_only>::value<<endl;    return 0;}


最后还要鄙视一下vs2012,因为它还不支持default/delete(不支持的很多,只说与本帖相关的)
gcc4.7中却可以通过这个特性显示的去除编译器生成的构造函数(显然比一杆打死的屏蔽方式好)
C/C++ code
using namespace std;struct copy_only {    copy_only() = default;    copy_only(copy_only&& ) = delete;};int main(){    cout<<std::is_move_constructible<copy_only>::value<<endl;    return 0;}






[解决办法]
不支持比,编译出错误的代码好很多了。
gcc的单数版本慎用 如4.3 4.5 4.7。
[解决办法]
LZ不妨把copy_only(copy_only const&) 声明为private试试
[解决办法]
这说明 is_move_constructible真是只是验证 T obj=T()了。
[解决办法]
呵呵 没有vs2010这些,所以没看过源码。

读书人网 >C++

热点推荐