本文介绍了习惯使用std :: auto_ptr或只使用shared_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在 shared_ptr 在tr1中,您认为应该如何使用 std :: auto_ptr ?它们都有不同的用例,但是 auto_ptr 的所有用例也可以用 shared_ptr 来解决。您是否愿意放弃 auto_ptr 或继续使用它,以便明确表示在任何给定点上只有一个类拥有所有权?

Now that shared_ptr is in tr1, what do you think should happen to the use of std::auto_ptr? They both have different use cases, but all use cases of auto_ptr can be solved with shared_ptr, too. Will you abandon auto_ptr or continue to use it in cases where you want to express explicitly that only one class has ownership at any given point?

我的想法是使用 auto_ptr 可以增加代码的清晰度,精确地通过添加细节和代码的设计指示,但另一方面,它增加了另一个微妙的问题,当训练新程序员:他们需要了解智能指针和细节如何工作。当你每个地方只使用一个智能指针时,你可以放下一个规则包装 shared_ptr '中的所有指针,并使用它。

My take is that using auto_ptr can add clarity to code, precisely by adding nuance and an indication of the design of the code, but on the other hand, it add yet another subtle issue when training new programmers: they need to understand smart pointers and the fine details of how they work. When you use only one smart pointer everywhere, you can just lay down a rule 'wrap all pointers in shared_ptr' and be done with it.

您对此采取了什么?

推荐答案

c $ c> std :: auto_ptr 'camp: auto_ptr 在下一个标准(C ++ 0x)中被弃用。

To provide a little more ammunition to the 'avoid std::auto_ptr' camp: auto_ptr is being deprecated in the next standard (C++0x). I think this alone is good enough ammunition for any argument to use something else.

但是,因为提到,默认替换 auto_ptr 应该是 boost :: scoped_ptr scoped_ptr 的语义更接近地匹配 auto_ptr 的语义,并且它用于类似的用途。

However, as Konrad Rudolph mentioned, the default replacement for auto_ptr should probably be boost::scoped_ptr. The semantics of scoped_ptr more closely match those of auto_ptr and it is intended for similar uses. The next C++09 standard will have something similar called unique_ptr.

但是, shared_ptr c $ c> scoped_ptr 应该使用不会破坏任何东西,它只是添加一个非常轻微的低效率来处理引用计数,如果对象从来没有实际上要共享。所以对于将永远不会交给另一个对象的私有成员指针 - 使用 scoped_ptr 。如果指针将被交给别的东西(这包括在容器中使用它们,或者如果你想做的是转移所有权而不保留或共享它) - 使用 shared_ptr

However, using shared_ptr anywhere that scoped_ptr should be used will not break anything, it'll just add a very slight bit of inefficiency to deal with the reference count if the object is never actually going to be shared. So for private member pointers that will never be handed out to another object - use scoped_ptr. If the pointer will be handed out to something else (this includes using them in containers or if all you want to do is transfer ownership and not keep or share it) - use shared_ptr.

这篇关于习惯使用std :: auto_ptr或只使用shared_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!