badmaash
badmaash

Reputation: 4845

Can someone explain what is happening with this unique_ptr code?

This is a code that uses unique_ptr:

struct Foo{
  Foo(){std::cout << "Ctor called\n";}
  ~Foo(){std::cout << "Dtor called\n";}
  void bar(){std::cout << "bar called\n";}
}

int main(){
 unique_ptr<Foo> up(new Foo);
 {
  vector<unique_ptr<Foo>> v;
  v.push_back(move(up));
 }

 up->bar();
 return 0;
}

The output of the run is:

Ctor called
Dtor called
bar called

I was expecting the call to bar() fail because from what i have understood, up was supposed to get destroyed with v because of the moveing. Looks like i haven't understood correctly. Can someone walk me through what is happening? (g++ 4.7.0)

Upvotes: 0

Views: 109

Answers (2)

K-ballo
K-ballo

Reputation: 81409

What you see is undefined behavior, caused by the last call up->bar(). Its probably be the same if you try:

static_cast<Foo*>(0)->bar();

Note that undefined behavior really means undefined, so it could crash or do somewhat totally unexpected, like appearing to work ok. The compiler could also understand that the last line of code will never be reached (under defined behavior), and decide to generate an empty executable that does nothing at all.

Upvotes: 3

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234654

from what i have understood, up was supposed to get destroyed with v because of the moveing.

It was destroyed. Why else would "Dtor called" show up on the output? An object is destroyed when the destructor executes. No other magic happens.

I was expecting the call to bar() fail

You can't expect anything when the behaviour is undefined, which is the case for dereferencing an empty unique_ptr.

Upvotes: 3

Related Questions