Pointer and vectors in C ++

I am starting with C ++ and I have doubts:

I am creating a function that will return a vector of objects of class MyClass .

 vector<MyClass>* myMethod() 

First question: is it correct to return the pointer?

Second question: if I am going to return a pointer, should I also insert a pointer to the MyClass object in the vector?

 MyClass* object; myVector.push_back(*object); 
+4
source share
4 answers

There is nothing wrong with a method that returns a pointer to a vector as follows: vector<MyClass>* myMethod() . But you have to ask yourself a few questions, for example:

  • Should there be a pointer to a vector? Cannot be just vector<MyClass> ?
  • Should this method also allocate memory for this vector?
  • Should calling this method delete / free this memory?

And to your second question: I would make a vector of pointers to MyClass objects ( vector<MyClass*> ) only if it is really necessary. This will cause you some memory management problems, so let me choose a simpler way.

Ok, let's talk about this question: If this method also allocates memory for this vector?
If the purpose of this method is to create a vector, then yes , the method should also allocate memory for it:

 vector<MyClass>* myMethod() { vector<MyClass>* v = new vector<MyClass>; // initialize, fill or do whatever with this vector return v; } 

the caller must clear:

  vector<MyClass>* v = myMethod(); // do some stuff delete v; // clean up 

If the goal is only to obtain a pointer to a specific vector that cannot be received by the caller, it may look like this:

 vector<MyClass> _x; // caller can not access _x but myMethod can vector<MyClass>* myMethod() { return &_x; } 

the caller should not remove this vector in this case:

  vector<MyClass>* v = myMethod(); // do some stuff, don't delete v 
+6
source

The vector can be a vector of objects or a vector of pointers. This is completely independent of whether you have a vector or a pointer to a vector.

If you are starting with C ++, try to avoid pointers. Just return the vector of the objects. Remember that a vector contains its contents. When you put an object in a vector, it will be copied.

+8
source

In C ++ 11, you can just return std::vector<T> and it will be fast. There is no temporary useless since std::vector supports move-semantic, which means that resources allocated to the temporary will be stolen by the semantic move functions.

And if your type T manages resources, then you should also implement move-semantic along with a regular semantic copy.

+5
source

Yes, you can return a pointer to a vector, and that means you want to be able to modify this vector. Just keep in mind that you should not return a pointer to a local variable.

As for clicking pointers in a vector, it depends on what you want to do, but you SHOULD NOT click the punches.

+1
source

Source: https://habr.com/ru/post/1395651/


All Articles