class myMem{};
class Test{
public:
initMem1(myMem& mInput){/*initialize _mem1*/}
initMem2(shared_ptr<myMem> &pmInput){/*initialize _mem2*/}
myMem _mem1;
shared_ptr<myMem> _mem2;
};
Test myTest;
myTest()
So, in the code above, members belong to a class. One member is a value type and another member is a shared_ptr type. Which way is better for a class member? Moreover, I also have the functions to initialize the members. Which way is better?
In general what is the advantage of passing by reference to shared_ptr over passing by reference directly?
The only reason a function should accept a std::shared_ptr
as a argument is if it may need to share or modify the ownership of the resource. If not, don't pass a std::shared_ptr
.
If the function will definitely need to take shared ownership then it should accept a std::shared_ptr
by value. Only accept a std::shared_ptr&
if the function may or may not take shared ownership.
If the function does not modify ownership then pass a reference to the resource, not a std::shared_ptr
.