Brandon
Brandon

Reputation: 23485

Difference between T* and T*& C++

What is the difference between the two copy functions below? I do not seem to see a difference between them. Specifically the void*& vs the void*.

So what is the difference between T*& and T*? When would I use one over the other? Also, if I made them accept const parameters, what would happen? What would the difference be?

#include <iostream>

void Copy(void* Source, void* Destination, int Size)
{
    //memcpy(Destination, Source, Size);
    char* S = static_cast<char*>(Source);
    char* D = static_cast<char*>(Destination);
    *D = *S;
}

void Copy2(void* &Source, void* &Destination, int Size)
{
    char* S = static_cast<char*>(Source);
    char* D = static_cast<char*>(Destination);
    *D = *S;
}


int main()
{
    int A = 2;
    int B = 5;
    int C = 7;

    void* pA = &A;
    void* pB = &B;
    void* pC = &C;

    Copy(pA, pB, 1);
    Copy2(pA, pC, 1);

    std::cout<< B <<std::endl;
    std::cout<< C <<std::endl;
}

Both of the above print "2". Both are the same no?

Upvotes: 2

Views: 3045

Answers (1)

Ryan Guthrie
Ryan Guthrie

Reputation: 688

One is a pointer, the other is a reference to a pointer.

Google both and pick up a C++ basics book.

Think of passing by pointer as passing a memory address by value (ie, a copy). In the receiving function, you have a copy of the memory address and you can change where that memory address pointer points to, and what that destination memory contents looks like. When you return from that function, the destination memory is still changed, but the original pointer is unchanged.

In contrast, a reference to a pointer allows you to change where that memory points to after you return from the function. Otherwise it is the same.

A common usage is a funciton which allocates memory such as:

SomeClass *someClass = null;
PopulateSomeClass(someClass);
...

void PopulateSomeClass(SomeCLass* &someCLass)
{
   someClass = new SomeClass;
}

But really, google this for more detail - this is a more basic C++ concept.

For instance, a reference is typically implemented as a const * under the covers in the compiler. So it is a const pointer to pointer.

Upvotes: 7

Related Questions