I’m starting with C++ and I have a doubts:
I’m making a function which will return a vector of objects of a class MyClass.
vector<MyClass>* myMethod()
The first question is, it’s correct to return a pointer?
The second question is: if I’m going to return a pointer, should I also insert pointer of MyClass object into the vector?
MyClass* object;
myVector.push_back(*object);
There is nothing wrong with method that returns pointer to vector like this:
vector<MyClass>* myMethod(). But you should ask yourself some questions, like:vector<MyClass>?delete/freethis memory ?And to your second question: I would make vector of pointers to objects of
MyClass(vector<MyClass*>) only if it is really necessary. It will cause you some troubles with memory management, so let’s choose an easier way.Ok, let’s talk about this question: Should this method also allocate 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:
caller should clean up then:
If the purpose is just to retrieve the pointer to some specific vector that can not be obtained by caller, it could look like this:
caller shouldn’t delete this vector in this case: