C++ smart pointers and functions

Asked

Viewed 134 times

0

I am reading an article on 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 doubt is in the function ProcessLargeObject. Must the passage be by reference? What if the function ProcessLargeObject had the following signature ProcessLargeObject(LargeObject *lo) what would be the difference?

1 answer

1

Yes, the way the Processlargeobject() function is declared, the object is passed as an immutable reference. Because it is immutable, it is no less secure than passing by value, and faster for non-trivial-sized objects.

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

More modern Lingugens have abolished this language "object or null" in favor of securing an object always valid in the type itself. For example, in Swift a Type? can be "Type or nil" while "Type" is a Type object. To extract the object from a Type variable? it is necessary to write "variable!" to make clear what is happening.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.