jeudi 29 août 2019

Confusion about scope of smart pointers

Suppose I have the following function with some hypothetical class Obj that can hold a (smart) pointer to an object of type Foo:

Obj* getObj() {
  std::shared_ptr<Foo> fooPtr = std::make_shared<Foo>(new Foo());
  Obj *obj = new Obj();
  obj->setFoo(fooPtr);
  return obj; 
}

When will my smart pointer be deleted?

  1. When we return from getObj because it's now out of the function's scope and obj is not pointed-at "smartly"?
  2. Whenever obj is deleted later in my program?

My tests make me think its 2., but a colleague thinks it's 1.

I couldn't find documentation that would answer my question, as all explanations of smart pointers I read didn't do anything with the pointer that would make it escape the scope of its creator...

Aucun commentaire:

Enregistrer un commentaire