I have a Foobar class with a sayHello() method that outputs “Well hello there!”. 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;
The output is:
Well hello there!
Well hello there!
vector size: 1
I’m confused why this works. Shouldn’t fooList[0] become null when I do the first move? Why does myFoo2 work?
Here’s what Foobar looks like:
class Foobar
{
public:
Foobar(void) {};
virtual ~Foobar(void) {};
void sayHello() const {
cout << "Well hello there!" << endl;
};
};
Yes.
It doesn’t; it causes undefined behaviour. Your compiler happens to produce code that doesn’t crash if you use a null pointer to call a non-virtual function that doesn’t dereference
this.If you change the function as follows, it will be clearer what’s happening: