Does an element from an STL container move it from this container?

I have a Foobar class with the sayHello() method that outputs "Hello, hello!". If I write the following code

 vector<unique_ptr<Foobar>> fooList; fooList.emplace_back(new Foobar()); unique_ptr<Foobar> myFoo = move(fooList[0]); unique_ptr<Foobar> myFoo2 = move(fooList[0]); myFoo->sayHello(); myFoo2->sayHello(); cout << "vector size: " << fooList.size() << endl; 

Output:

 Well hello there! Well hello there! vector size: 1 

I am confused why this works. Should fooList[0] become null when I take the first step? Why does myFoo2 work?

Here Foobar as follows:

 class Foobar { public: Foobar(void) {}; virtual ~Foobar(void) {}; void sayHello() const { cout << "Well hello there!" << endl; }; }; 
+4
source share
2 answers

Should fooList [0] become null when I make the first move?

Yes.

Why does myFoo2 work?

This is not true; this causes undefined behavior. Your compiler has code that doesn't crash if you use a null pointer to call a non-virtual function that doesn't trigger this .

If you change the function as follows, it will be clear what happens:

 void sayHello() const { cout << "Well hello there! My address is " << this << endl; } Well hello there! My address is 0x1790010 Well hello there! My address is 0 vector size: 1 
+12
source

Answer: No, move operations do not remove items from containers.

Another comment: using the emplace_back function is likely to be inadequate.

to try:

 vector<unique_ptr<Foobar>> fooList; fooList.emplace_back( new Foobar ); 
+1
source

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


All Articles