In fact, there are five different possibilities for passing an object to a function:
//Function declarations void passByValue(Derived o); //Not possible with an abstract class. void passByReference(Abstract& o); void passByConstReference(const Abstract& o); void passByPointer(Abstract* o); void passByConstPointer(const Abstract* o); //Function calls Derived o; passByValue(o); passByReference(o); //May change o! passByConstReference(o); passByPointer(&o); //May change o. passByConstPointer(&o);
Since the call to passByReference(o) does not show that the call can change the variable o , I never use pass-by-reference. I always use either pass-by-const-reference or pass-by-pointer.
However, many C ++ programmers today generally prefer to use pointers because they do not play well with smart pointers such as std::unique_ptr<> and std::shared_ptr<> . If you are managing your objects with these smart pointers, you should always pass a smart pointer instead of an open pointer / link, usually with const-reference:
void passBySmartPointer(const std::shared_ptr<Abstract>& o); void passConstBySmartPointer(const std::shared_ptr<const Abstract>& o);
With this approach, you will never see a bare pointer in your code ...
(The reason for passing a smart pointer is because the chain of smart pointers should not be broken: if you convert a smart pointer to a bare pointer and then back to a smart pointer, the second smart pointer does not know about the first, and you will have problems. There are and other ways to avoid this, but this is beyond the scope of this answer.)
source share