Difference between pointer vector for a class and vector for a class?

Asked

Viewed 193 times

3

When is pointer to class will we have to allocate memory space? What is the difference between the following two statements and when they should be used ?

Vector <class*> nameOfVector;
Vector <class> nameOfVector;

1 answer

2


Not necessarily. It depends on what you want, but almost always will be the case.

The first one expects a memory address, so that’s what it should provide. You can do this with:

  • something that already generates a pointer for you
  • use the operator new that allocates the memory
  • use the function malloc(), although it is not recommended
  • use anything that stores memory
  • use a reference to an address.

The first line reading is

Declare the variable nameOfVector which will be of the pointer vector type for class-type objects

If you choose to take the address of something already existing you have to take care for the lifetime of this object. It must have equal or longer duration than the vector, otherwise it will occur a dangling Pointer.

But it’s rare to have a situation that makes sense to do something like this. Either use the object itself, or use a pointer to an area of allocated memory.

Note that if you are going to allocate memory in heap (read to understand the function of each area of memory) and it is your responsibility to manage your memory. It is common to use smart pointers (question here on the website), which is slightly different from the raw pointer that was used.

Read on When to choose whether to use a pointer when creating an object?.

The second example awaits the instantiated object itself by the type represented by class in the example (this name is reserved and cannot be used). You must copy the object into the vector, there will be no reference to it. In general it pays to do it only in small objects and immutable.

The first line reading is

Declare the variable nameOfVector which will be of type vector objects of type class

Has more information on How to use vector to store a class?.

Browser other questions tagged

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