I was told that the only benefit of passing shared_ptr
by value is sharing ownership, so I am trying to come up with example where we must pass shared_ptr
by value rather than otherwise.
class Foo {
public:
void p() const {}
};
void bar(std::shared_ptr<Foo> f) {f->p();}
void bar2(const Foo* f) {f->p();}
int main() {
std::shared_ptr<Foo> f = std::make_shared<Foo>();
bar(f); // OK
bar2(f.get()); // OK
}
The only example I can came up with seems to be a multiple thread environment where if f
is created in one thread and passed to another thread, in that case it seems that shared_ptr
is needed, otherwise the object may expire in the other thread.
Could someone provide a simple example where bar
would work but bar2
would run into an issue in a single thread program? I am wondering if bar
and bar2
will always work in a single thread program.
This could help me understand how to design proper APIs.
EDIT: Based on the reply, seems that my understanding of ownership was wrong. If I am designing some utility-like API, similar to bar
/bar2
, then I don't need to worry about ownership. Ownership makes sense when there are objects involved.