在msvc2010中移动被左值断开/未完成? [英] Is move by lvalue broken/unfinished in msvc2010?

查看:154
本文介绍了在msvc2010中移动被左值断开/未完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么这个代码不工作。 this_显示为0xcccccccc,v不再为4.为什么?



注意:我试图使用lvalue / move语义。

  struct AA {
void * this_;
int v;
AA(){v = 4; this_ = this; }
AA(AA& a){this_ = this; }
AA(AA& a){
this_ = a.this_;
v = a.v;
}
};
void movetest(AA s){}
void movetest(AA& s){}
// void movetest(AA& s){}
AA& movetest(){return AA(); }
void MyTestCode2(){
AA c = movetest();
printf(wron value。4!='%d'\\\
,c.v);
}


解决方案

本地。它应该是

  AA movetest(){return AA(); } 

此代码要求移动或复制构造函数存在,但MSVC将使用返回值 - 优化,而不是实际调用。一般来说,你应该设计你的对象,好像移动或复制发生在你的控制之外 - 只是保持对象的一致状态,不要依赖他们的副作用。



<例如在调试版本上



AA movetest()
{
AA a;
return a;
}



调用AA(AA&)构造函数而不是AA(AA&)构造函数。


I dont know why this code doesnt work. this_ is shown as 0xcccccccc and v is no longer 4. Why?

Note: I am trying to use the lvalue/move semantics.

struct AA{
    void*this_;
    int v;
    AA() {v=4;this_=this; }
    AA(AA&a){this_=this; }
    AA(AA&&a){
        this_=a.this_;
        v = a.v;
    }
};
void movetest(AA s) {}
void movetest(AA& s) {}
//void movetest(AA&& s) {}
AA&& movetest() { return AA(); }
void MyTestCode2(){
    AA c = movetest();
    printf("wron value. 4 !='%d'\n", c.v);
}

解决方案

That's returning a reference to a local. It should be

AA movetest() { return AA(); }

This code requires either a move or copy constructor to exist, but MSVC will use the return-value-optimization and not actually call either. In general, you should design your objects as if moves or copies happen outside your control--just maintain consistent state of your object, don't rely on their side-effects.

VC2010 is correctly preferring move to copy, for example on a debug build

AA movetest() { AA a; return a; }

calls the AA(AA&&) constructor not the AA(AA&) one.

这篇关于在msvc2010中移动被左值断开/未完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆