Difference between vector of pointers for a class and vector for a class?

2

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

Vector <class*> nameOfVector;
Vector <class> nameOfVector;
    
asked by anonymous 15.12.2016 / 14:32

1 answer

2

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

The first one waits for a memory address, so that's what you should provide. You can do this with something that already generates a pointer for you, you can use the new that allocates memory, you can even use the malloc() function, although it is not recommended , you can use anything that allocates memory. Or you can use a reference for an address .

The first line reading is

  

Declare the variable nameOfVector that will be of type vector of pointers to objects of type class

If you choose to get the address of something already existing you have to take care for the lifetime of this object. It should be of equal or greater duration than the vector, otherwise a dangling pointer will occur.

But it is not common to do this and it is 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 allocate memory in the heap (read to understand the function of each area of memory) and it is your responsibility to manage your memory. It's common to use smart pointers ( question here on the site ), which is slightly different from the raw pointer that was used.

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

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

The first line reading is

  

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

More information on How to use the vector to store a class? .

    
15.12.2016 / 14:54