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;
};
Bar
?main
? DoesFoo
ownBar
? Or do you wantFoo
to have it for as long as it exists, but you also want another function to haveBar
for as long as required (shared ownership)? – wallym_bar
a reference? – wallym_bar
is an instance member variable. It's concrete. Anything you pass to an instance ofFoo
will copy into it's own memory. Do you want your code to be "SomeType<Bar> m_bar;
please advise me which", or do you want your code to be#ifdef PRODUCTION Bar m_bar; #else SomeType<Bar> m_bar;
? In which case - well done - you're not actually unit testing your production code, WTG. – kfsone