Invalid use of relocation?

Can someone give me hints why this code does not output anything? I guess this has something to do with the line of movement ...

#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ vector<int> v{66,79,154,24,76,13,7}; v = move(v); for(auto i: v) cout << i << " "; } 

Update: so I added a system ("pause"); to help yourself. Whether I need it or not, this is not what I focus on. When I ran the code again in Visual Studio 2013, it worked. However, when I ran it through Ideone using C ++ 14, it did not output anything. A little embarrassed.

Visual studio 2013 Ideone

+6
source share
2 answers

I will have to say that it is irreproducible.

I used my version of Visual Studio 2015 Update 3, and the output is normal:

66 79 154 24 76 13 7

In addition, when implementing VC ++, there are no problems with moving the vector to itself:

 _Myt& operator=(_Myt&& _Right) { // assign by moving _Right if (this != &_Right) { // different, assign it clear(); if (_Alty::propagate_on_container_move_assignment::value && this->get_allocator() != _Right.get_allocator()) { // assign vector, dumping proxy this->_Free_proxy(); this->_Myvec = _STD move(_Right._Myvec); this->_Alloc_proxy(); } else this->_Myvec = _STD move(_Right._Myvec); this->_Mysize = _Right._Mysize; _Right._Mysize = 0; } return (*this); } 

as you can see from the condition this != &_Right , the movement will happen only if you do not move the vector toward you.

EDIT:

Apparently, the compiler that is used to compile “C ++ 14” to Ideone (GCC?) Decides not to check the self-translation of the destination and decides to free the vector data. as we can see from this small experiment , after moving the size of the vector is 0. as stated in other previous answers / comments, assigning a move for itself implements the implementation. I think VC ++ is doing the right thing in this case.

EDIT 2:

it seems that GCC does not really check self-esteem. it moves vector data to temporary and accepts __x data that is already empty at that point. man, sometimes GCC behaves stupidly for radial performance (because cmp + jz will really slow down your program?)

+2
source

Standard library functions called with xvalue arguments can assume that the argument is the only reference to the object; if it was built from an lvalue with std::move , no aliasing checks are performed. In particular, this means that the standard library redirection assignment operators do not need to perform self-determination checks:

 std::vector<int> v = {2, 3, 3}; v = std::move(v); // undefined behavior 

See std :: move and this question for more details.

+4
source

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


All Articles