0

在我们的大型项目中,我们有很多具有以下内容typedef的类:

class Foo
{
  public:
    typedef std::auto_ptr<Foo> Ptr;
    typedef boost::shared_ptr<Foo> Ref;
  ...
};
...
Foo::Ref foo(new Foo);
...
doBar(foo);
...

它们的使用非常方便。但我怀疑在auto_ptr语义上是否接近Ptrshared_ptr与 ref 相同?还是应该auto_ptr明确使用,因为它具有“所有权转移”语义?

谢谢,

4

5 回答 5

2

std::auto_ptr has ownership transfer semantics, but it's quite broken. If you can use boost::shared_ptr, then you should use boost::unique_ptr instead of std::auto_ptr, since it does what one would expect. It transfers ownership and makes the previous instance invalid, which std::auto_ptr doesn't.

Even better, if you can use C++11, then swap to std::unique_ptr and std::shared_ptr.

于 2012-01-31T08:32:37.240 回答
1

You shouldn't use std::auto_ptr, its deprecated and I consider it dangerous, even more so when you hide it behind such a generic typedef as Ptr.

I don't think it makes any sense to called shared_ptrRef, in this case it is more Ptr than auto_ptr.

EDIT: I consider it dangerous because you can easily misuse it, even when you fully understand its workings, you can accidentally misuse it, especially when hiding it behind a typedef. A good class should be easy to use right and should be difficult to misuse. Especially with the advent of unique_ptr I can't see any useful scenario for auto_ptr.

于 2012-01-31T08:33:16.887 回答
0

auto_ptr is deprecated in C++11. You might want to stop using it and just use the shared_ptr. For shared_ptr, there is no ownership transfer on assignment, the number of references to the object is counted and the object is destroyed when the last pointer is destroyed.

于 2012-01-31T08:32:48.857 回答
0

I believe the order is just a nomenclature which someone used.
It probably should have been, ref for auto_ptr and ptr for shared_ptr, because:

References are immutable and hence cannot be made to refer to other object. auto_ptr has a similar(albeit remotely similar) semantics, transfer of ownership which means you would probably not want to assign a auto_ptr for the non-intuitive behavior it shows. The assigned object gains ownership while the object being assigned loses ownership.

On the Other hand shared_ptr has an reference counting mechanism which is similar(again remotely) to multiple pointers which can point to the same object. The ownership of the pointer rests with the shared_ptr itself and it gets deallocated as soon as there are no pointer instances referring to it.

于 2012-01-31T08:33:04.680 回答
0

很大程度上取决于它们的用途。在这种情况下 Ref,人们对它的理解。在标准之前的日子里,我经常使用 typedef 来Ptr作为我的(侵入性)引用计数指针;实际上,这种 typedef 的存在表明该类型支持引用计数,并且应该始终动态分配它。

两者都std::auto_ptr具有boost::shared_ptr非常特殊的语义。我倾向于不为它们使用 typedef,这既是因为特殊的语义,也是因为(与我的侵入性引用计数指针的情况不同)它们完全独立于指向的类型。对于任何给定的类型,您可以根据程序逻辑的需要使用或不使用它们。(由于其特殊的语义,我发现 . 有很多用途std::auto_ptr。但是,我倾向于避免使用boost::shared_ptr;它相当危险。)

于 2012-01-31T08:35:48.647 回答