There have been tons of questions asked about passing by reference or pointer, and when to use pointers.
My understanding of the subject so far is the following rules:
- Always try to pass by reference
- Pass by pointer (only use pointers) if you must
In my case, I must use pointers in order to retain polymorphic behaviours as I am storing the passed object into a vector for later use (it is an 'add' method).
See: C++ Overridden method not getting called
I have read:
- shared_ptr by reference or by value? which talks about passing shared_ptrs specifically
- Passing shared pointers as arguments which tells me that I should only pass by shared_ptr if I am trying to transfer ownership, but later goes on to say that I should then pass by reference
- Should I use std::shared pointer to pass a pointer? which pretty much tells me what the previous question told me, but in the context of a unique_ptr
So my question is this:
If I am trying to pass a pointer already contained in a shared_ptr to add to a vector, should I
- pass a reference to the shared_ptr to be added into the vector (because the other method is unwieldy)
or
- use shared_ptr::get to get the actual pointer, pass that pointer, re-wrap it using shared_ptr::reset, and then add it to the vector? (because I should only pass smart pointers if I'm transferring ownership)
Code:
//method definition
void addToVector(shared_ptr<Object>& obj) {
myVector.push_back(obj);
}
//call
shared_ptr<Object> myObj = make_shared<Object>();
addToVector(myObj);
or
//method definition
void addToVector(Object* obj) {
shared_ptr<Object> toAdd;
toAdd.reset(obj);
myVector.push_back(toAdd);
}
//call
shared_ptr<Object> myObj = make_shared<Object>();
addToVector(myObj.get());