After reading quite a bit about (smart)-pointers in the context of class members, I am still not sure how to handle to follwoing situation.
I want to create objects of type Foo, either by calling the deafult constructor which instantiates a specifc Bar object, or by passing a some sort of pointer to the one argument constructor of Foo.
- I can't use unique_ptr because I still need to access the Bar object outside of Foo.
- If I used raw pointers, then I would need to call delete if the deafult constructor of Foo was called but not if the one-arg ctr was called.
- Then there are shared_ptr, but quoting Herb Sutter "Don’t pass a smart pointer as a function parameter unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership."
So in the snippet below (which does not compile of course), what type should m_bar be?
struct Bar {
Bar(int k) {}
Bar operator=(const Bar&) =delete;
Bar (const Bar&) = delete;
};
struct Foo {
Foo() : m_bar(5) {}
Foo(Bar b) : m_bar(b);
Bar m_bar;
};
Aucun commentaire:
Enregistrer un commentaire