Search code examples
c++pointersclone

Ensure a returned value is not a pointer


I want to ensure myself that in the GetConnections method I am returning an exact copy of connections. I will be editing it outside of the existing Node, and my program will most likely stop functioning if it returns a pointer to the memory location (thus editing the vector of the node). How can I ensure myself I am returning a clone / copy and not a pointer?

std :: vector<NodeConnection*> Node :: GetConnections()
{
    return this->connections;
}


class Node {
    private:
        std :: vector <NodeConnection*> connections;
    public:
        // getters
        std :: vector <NodeConnection*> GetConnections();
};

The NodeConnection* in the vector itself will not be edited, so that's not the issue here.


Solution

  • You can tell what you are returning by looking at the function signature:

    1. SomeType* functionName(ArgType arg) - the function returns a pointer. Whatever the pointer is pointing to can be modified by the caller.
    2. SomeType const * functionName(ArgType arg) - the function returns a pointer to const. Whatever the pointer is pointing to can be examined, but cannot be modified by the caller.
    3. SomeType& functionName(ArgType arg) - the function returns a reference. Whatever the reference is referencing can be modified by the caller.
    4. const SomeType& functionName(ArgType arg) - the function returns a const reference. Whatever the reference is referencing can be examined, but cannot be modified by the caller.
    5. SomeType functionName(ArgType arg) - the function returns a copy. Any modifications the caller might do to the returned value will not be reflected on the original being returned.

    Your function's return type is that of the fifth kind - you are returning by value, i.e. your code makes a copy of the vector of pointers. It should be noted that although the callers cannot modify the vector inside your class, they could certainly call methods on the objects pointed to by the vector's elements. If some of these methods make changes to the items, the items in the original vector will see these changes as well. In other words, when you copy a vector of pointers, you get a shallow copy.

    Also note that it is not necessary to return a copy if all you want is preventing modification: returning a pointer to const or a const reference would achieve the same result with higher efficiency, because the copy would be avoided.