Mr.Y
Mr.Y

Reputation: 875

Should we de-reference a pointer before passing by reference?

Years ago, I learned from my teacher from C++ course. He shows how to use pointer and linked list in C++: [Not exact syntax]

//Declaration
Nodetype *head = new NodeType()...

//Call insertnode method: 
InsertNode(head, val1);

//The InsertNode function
void InsertNode(NodeType& head, int val1){}

As you can see above, we didn't de-reference "head". We use "InsertNode(head, val1);" instead of "InsertNode(*head, val1);"

However yesterday, when I learned smart pointer from the microsoft site: They use "ProcessLargeObject(*pLarge);" instead of "ProcessLargeObject(pLarge);".

Should we dereference a pointer before pass by reference? or should we just pass by pointer without derefencing? Please advise

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

.

Upvotes: 1

Views: 96

Answers (2)

Spencer
Spencer

Reputation: 2214

It was probably a typo on the part of your instructor. If, as in the example you provide

void InsertNode(NodeType& head, int val1){}

the signature has a reference parameter, then passing in a pointer

NodeType *p = new NodeType;
InsertNode (p, 1);   // error

is ill-formed and shouldn't even compile. Allowing a pointer would violate the strongly-typed nature of C++. If you have a pointer to an object that you want to pass in to such a function, you must dereference the pointer.

InsertNode (*p, 1); // correct

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

As you can see above, we didn't de-reference "head". We use "InsertNode(head, val1);" instead of "InsertNode(*head, val1);"

That is an error, so the premise of your question is broken. You must have misremembered, or perhaps it is a typo in your course material. Or, maybe, your professor was simply mistaken.

You have to dereference head, because InsertNode accepts a NodeType (by reference), not a NodeType*.

In general, I can say that how you will use a linked list completely depends on the implementation. There is no "one way" to implement a linked list type in C++. You will have to read the documentation for the class you're using to find out how to use it properly.

FWIW, in actual production code, you would generally use std::list and be done with it.

Upvotes: 4

Related Questions