Is lvalue moving broken / incomplete in msvc2010?

I do not know why this code does not work. this_ displays as 0xcccccccc and v is greater than 4. Why?

Note. I am trying to use the semantics of 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 = av; } }; 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", cv); } 
+1
source share
2 answers

This returns a link to local. It should be

 AA movetest() { return AA(); } 

This code requires a move or copy mechanism to exist, but MSVC will use return value optimization and not actually name it. In general, you should design your objects as if movements or copies are happening outside your control - just maintain a consistent state of your object, do not rely on their side effects.

VC2010 correctly prefers move to copy, for example, in a debug assembly

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

calls the constructor AA (AA &), not AA (AA &) alone.

+3
source

Additional info: this is an answer instead of a comment only due to formatting issues.

A warning would be nice, but no language is required. Try returning the local lvalue AA & and see if you get a warning.

clang ++ gives the following warning for your code:

 test.cpp:14:26: warning: returning reference to local temporary object AA&& movetest() { return AA(); } ^~~~ 
+1
source

Source: https://habr.com/ru/post/885472/


All Articles