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>;
the caller must clear:
vector<MyClass>* v = myMethod();
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;
the caller should not remove this vector in this case:
vector<MyClass>* v = myMethod();
source share