C ++ smart pointers and functions

0

I'm reading an article in msdn about smart pointers. In the article there is this example:

class LargeObject
{
public:
    void DoSomething(){}
};

void ProcessLargeObject(const LargeObject& lo){}
void SmartPointerDemo()
{    
    // Create the object and pass it to a smart pointer
    std::unique_ptr<LargeObject> pLarge(new LargeObject());

    //Call a method on the object
    pLarge->DoSomething();

    // Pass a reference to a method.
    ProcessLargeObject(*pLarge);

} //pLarge is deleted automatically when function block goes out of scope.

My question is in the ProcessLargeObject function. Does the passage necessarily have to be by reference? And if the function ProcessLargeObject had the following signature ProcessLargeObject(LargeObject *lo) what would be the difference?

    
asked by anonymous 21.03.2016 / 19:01

1 answer

1

Yes, in the way that the ProcessLargeObject () function is declared, the object is passed as an immutable reference. Because it is immutable, it is no less safe than value, besides being faster for objects of non-trivial size.

There is an important difference between references and pointers: references can not be null . In this case, the ProcessLargeObject () function always wants to receive a valid object. If it were necessary to sometimes pass NULL (as is customary to do when the parameter is "optional") then it would be necessary to use pointer as a parameter.

More modern languages have abolished this "object or null" language in favor of ensuring an object always valid in its own type. For example, in Swift a Type? can be "Type or nil" while "Type" is necessarily a Type object. To extract the object from a Type variable? you must write "variable!" to make clear what is happening.

    
22.03.2016 / 05:25