If I had the following two options, which would be more desirable or generally accepted.
1. Creating an object on the stack and returning it by value.
2. Creating an object on the heap, storing it in an auto ptr and returning the auto ptr.
If I had the following two options, which would be more desirable or generally accepted.
1. Creating an object on the stack and returning it by value.
2. Creating an object on the heap, storing it in an auto ptr and returning the auto ptr.
How many are there?
How large are they?
How persistent are they?
If you're trying to optimise already, then stop.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Both are used for a lot of reasons. So both are acceptable. Post some code to get more specific.
Assigning it to an auto_ptr isn't something you ALWAYS the best approach. For example, you might pass the pointer and assign it then on an auto_ptr which should be cleaner. You can also assign it to an object's internal container that would automatically free that memory, so again the auto_ptr might not be used. So it really depends.
Not sure returning an auto_ptr really has any benefits since the user can just as well store the raw pointer in an auto_ptr or boost::shared_ptr or whatever other smart pointer impl they want to use. But again it depends on your requirements. Not even sure allocating memory in the function is best either since this ties the user into your allocation scheme instead of using their own or at least having the option to use their own.
If you are returning a raw pointer you also must ask yourself:
- What if the user deletes the pointer?
- Should the user cleanup the pointer even if your function allocated the memory for it? Usually allocation and cleanup are done in the same object.
- Because of the above, should you allow access to the raw pointer or is there some other approach that is safer?
- Auto_ptr isn't exactly the ideal smart pointer. Do you understand exactly what auto_ptr does and what affects that will have on your current design?
- If you decide to return an auto_ptr is returning a templated type going to cause any problems?
- Is deriving the allocated object from a ref-count base class an option as opposed to using a smart pointer templated type? One is a ref counted object and the other is a ref counted raw pointer.
Last edited by VirtualAce; 08-29-2010 at 02:20 AM.