lundi 27 juillet 2015

Dropping a unique ptr returned from a function?

If I have a function source that returns a unique_ptr, and I have a function sink that calls source in the following way, it works [clang].

But is the behavior undefined? Or is everything copacetic?

class Foo {
  ...
  bool isValid() { return true; }
  ...
}

std::unique_ptr<string> source() {
  auto foo = std::make_unique<Foo>();  // let's pretend this is C++14?
  /* ... initialize foo */
  return std::move(foo);
}

void sink() {
  if (source()->isValid()) {
    /* do something */
  }
  /* ... */
}

Is it valid to use the unique_ptr on that line only? And when is the object theoretically supposed to be destructed? After that line? At the end of the function?

Aucun commentaire:

Enregistrer un commentaire