开发者

Should I stop using auto_ptr?

开发者 https://www.devze.com 2023-01-10 19:20 出处:网络
I\'ve recently started appreciating std::auto_ptr and now I read that it will be deprecated. I started using it for two situations:

I've recently started appreciating std::auto_ptr and now I read that it will be deprecated. I started using it for two situations:

Examples:

// Exception safe and makes it clear that the caller has ownership.
std::auto_ptr<Component> ComponentFactory::Create() { ... }

// The receiving method/function takes ownership of the pointer. Zero ambiguity.
void setValue(std::auto_ptr<Value> inValue);

Despite the problematic copy semantics I find auto_ptr useful. And there doesn't seem to be an alternative for the above examples.

Should I just keep using it and later switch to std::unique_ptr? Or is it to be avoided?


It is so very very useful, despite it's flaws, that I'd highly recommend just continuing to use it and switching to unique_ptr when it becomes available.

::std::unique_ptr requires a compiler that supports rvalue references which are part of the C++0x draft standard, and it will take a little while for there to be really wide support for it. And until rvalue references are available, ::std::auto_ptr is the best you can do.

Having both ::std::auto_ptr and ::std::unique_ptr in your code might confuse some people. But you should be able to search and replace for ::std::unique_ptr when you decide to change it. You may get compiler errors if you do that, but they should be easily fixable. The top rated answer to this question about replacing ::std::auto_ptr with ::std::unique_tr has more details.


deprecated doesn't mean it's going away, just that there will be a better alternative.

I'd suggest keeping using it on current code, but using the new alternative on new code (New programs or modules, not small changes to current code). Consistency is important


I'd suggest you go use boost smart pointers.

0

精彩评论

暂无评论...
验证码 换一张
取 消