ck4e
ck4e

Reputation: 75

Does using the * operator on a pointer create a copy?

I've been curious about this for some time. Say we have the following cases for accessing a data member of a class stored in dynamically allocated memory:

class C {
public :
    C() = default; 
    int a = 4; 
}

int main () {
    C * ptr = new C(); 
    std::cout << "pointer->::" << ptr->a << std::endl; 
    std::cout << "dereference*().::" << (*ptr).a << std::endl; 
}

I'm sure the pointer method is the preferred method, and my guess is that dereferencing the pointer provides a reference, at least in C++. But in C, where there are no references (and assuming appropriate modifications to convert the class to a struct etc), would dereferencing and accessing the member like this result in a temporary shallow copy? Is this something that the compiler optimizes out?

Upvotes: 1

Views: 535

Answers (2)

Zig Razor
Zig Razor

Reputation: 3515

Dereferencing a pointer does not create a copy neither for C neither for C++. The result of a dereferencing operation is a lvalue that describe a pointed object. But in any case the behaviour is the same for C and C++.

Upvotes: 1

Pascal Getreuer
Pascal Getreuer

Reputation: 3256

In both C and C++, *p (dereferencing) and p->m (member access through pointer) are "lvalue expressions". An lvalue "evaluates to the object identity". *p or p->m does not (by itself) create a copy, it refers to a variable that already exists.

Upvotes: 1

Related Questions