Returning a raw pointer is usually a bad idea because it's unclear who has responsibility for free the allocated memory (or even how to free it - delete, delete[], some sort of custom allocator).
It can be done safely as a private function for class implementation, seeing as the class it belongs to can take responsiblity for deallocation.
c++, I got a function that returns a new pointer, is this bad?
Personally I see nothing wrong in functions that return newly allocated objects, as long as they're clearly marked as such (typically with a large comment saying /* FACTORY METHOD */ or similar. But of course, as others point out, if you can return it in a safer form without compromising your design or performance, do that instead.
Quote:Original post by johnnyBravo
Thanks
...Too bad 'auto_ptr' doesn't work with arrays ;(
Well, conceptually, an auto_ptr<> of array is a vector<>...
Regards,
Quote:Original post by johnnyBravoQuote:
Or, you could pass in an array and fill in each triangle (make sure to pass in an integer telling how many triangles in the array.)
I don't understand, do you mean have the function return one triangle at a time?
Triangle* Array = new Triangles[NUMBER_THAT_IS_NEEDED];
void SomeFunction(Array, NUMBER_THAT_IS_NEEDED);
delete [] Array;
Quote:Original post by Kylotan
Personally I see nothing wrong in functions that return newly allocated objects, as long as they're clearly marked as such (typically with a large comment saying /* FACTORY METHOD */ or similar. But of course, as others point out, if you can return it in a safer form without compromising your design or performance, do that instead.
*Nods* look up the Factory Pattern
If your function contract is clear, then there's no harm in returning a new object.
In those kind of cases, I usually go for this:
void func(){int elementCount;TElement *element;elementCount=Object.GetElementCount();//get number of elementselement=new TElement[elementCount];//alloc memoryObject.GetElements(element);//fill in the array of elements...//Use elements here...delete[] element;}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement