I'd like to know what is considered nowadays the best practice when returning a pointer to a polymorphic object from a function, for example when using factories. If I transfer the ownership, should I return boost::unique_ptr<Interface>
? What should I return if I don't t开发者_如何转开发ransfer the ownership (e.g. returning a reference to a member)? Is there an alternative, non boost-based way which is also commonly used? Thanks.
EDIT: it is supposed to be C++03 compatible, with a possibility to easily upgrade to 0x
EDIT2: Please note I'm explicitly asking about common approaches, best practices, and not just "a way to do this". A solution implying a conditional search-and-replace over the codebase in future does not look like a good practice, does it?
EDIT3: Another point about auto_ptr is that it is deprecated, whatever neat it is, so it looks strange to advertise its usage at the interface level. Then, someone unaware will put the returned pointer into a STL container, and so on and so forth. So if you know another somehow common solution, you are very welcome to add an answer.
Use ::std::auto_ptr
for now, and when C++0x is available, then switch to ::std::unique_ptr
. At least in the factory case where you are handing ownership back to the caller.
Yes ::std::auto_ptr
has problems and is ugly. Yes, it's deprecated in C++0x. But that is the recommended way to do it. I haven't examined ::boost::unique_ptr
, but without move semantics I don't see that it can do any better than ::std::auto_ptr
.
I prefer the idea of upgrading by doing a search and replace, though there are some unusual cases in which that won't have the expected result. Fortunately, these cases generate compiler errors:
::std::auto_ptr<int> p(new int);
::std::auto_ptr<int> p2 = p;
will have to become at least like this
::std::unique_ptr<int> p(new int);
::std::unique_ptr<int> p2 = ::std::move(p);
I prefer search and replace because I find that using macros and typedefs for things like this tend to make things more obscure and difficult to understand later. A search and replace of your codebase can be applied selectively if need be (::std::auto_ptr
won't go away in C++0x, it's just deprecated) and leaves your code with clear and obvious intent.
As for what's 'commonly' done, I don't think the problem has been around for long enough for there to be a commonly accepted method of handling the changeover.
精彩评论