Memory pointer and allocation

Asked

Viewed 99 times

1

I know which pointer stores memory address. And a variable stores a value. But taking into account that I have a class class player {} and create a variable player p; and an instance of a pointer player *np = null; What is the difference between these 2 statements. What happens in the system, what are the advantages of using one or the other.

Taking into account the same class used earlier, I could say that creating an object of the type player and also create a pointer of the same type and store the address of that object is the same thing to create a new player()? That is to say:

player x;
player *z = &x;

is equivalent to:

player *z = new player

1 answer

1


I know which pointer stores memory address.

A pointer is a memory address.

And a variable stores a value.

Yes, even this value can be a pointer.

But considering I have a class class player {} and create a variable player p; and an instance of a pointer player *np = null; What is the difference between these 2 statements. What happens in the system, what are the advantages of using one or the other.

The first is in stack and the second is in heap. This has a lot of implications, advantages and disadvantages.

Taking into account the same class used earlier, I could say that creating an object of the type player and also create a pointer of the same type and store the address of that object is the same thing to create a new player()?

Not exactly, but I think I understand what you’re saying, so we can say they’re almost equivalent, but the memory allocation of each is in a different location and has a lifespan different.

  • Following the C++ specification, it would make more sense to talk about automatic and dynamic storage duration. Things like stack and heap are implementation details, compilers are not required to use these strategies.

  • True, but practically no one uses an implementation other than this. The answer is suitable for 99.99% of cases, the others will only be used by very experienced people.

  • Thanks for the clarification Maniero.

Browser other questions tagged

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