c++. Smart pointer for a member object of a class whose instance itself is owned by a smart pointer. Necessary?

StackOverflow https://stackoverflow.com/questions/23207738

  •  07-07-2023
  •  | 
  •  

문제

class Foo
{
public:
    int fooInt;
};

class Bar
{
    Foo fooInBar;
};

int _tmain(int argc, _TCHAR* argv[])
{
    std::unique_ptr<Bar> myBar = std::make_unique<Bar>();
}

I am aware that myBar is protected against a memory leak pretty well by being owned by a smart pointer.

Is the Foo object fooInBar protected also just by the nature of it being inside myBar, or should the member variable fooInBar also be contained in a smart pointer? Like so:

class Bar:
fooInBar(make_unique<Foo>())
{
    std::unique_ptr<Foo> fooInBar;
};
도움이 되었습니까?

해결책

Member objects, unless dynamically allocated memory, are safe from this point of view. So, no, you don't need to wrap it in a smart pointer.

Specifically fooInBar, being it a subobject of Bar, it will be destroyed automatically by the destructor of Bar. The same goes for fooInt in Foo.

And finally, unless you really need dynamic memory, you can also avoid the use of smart pointers in the first place:

int _tmain(int argc, _TCHAR* argv[])
{
    Bar myBar;
}

다른 팁

You don't have to. Since fooInBar is a sub-object inside object of type Bar, it will be destroyed as part of the containing Bar object when the latter one is released by smart pointer.

If, however, fooInBar is allocated separately on the heap, you should release it first before the containing Bar object is destroyed. E.g. destroy it in the destructor of Bar.

class Bar
{
public:
    Bar()
    {
       // You can also use a smart pointer
       // to manage the life cycle of "fooInBar"
       Foo *fooInBar = new Foo;
       ..
    }
    ~Bar()
    {
       // "fooInBar" needs to be released here
    }
private:
    Foo *fooInBar;
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top