English 中文(简体)
C++标准::auto_ptr复制构造函数
原标题:C++ std::auto_ptr copy constructor
  • 时间:2010-10-19 19:11:14
  •  标签:
  • c++
  • auto-ptr

std::auto_ptr缺少const-copy构造函数,因此我不能在集合中直接使用它。有没有一些方法可以在不使用boost指针集合模板的情况下获得例如vector of std::autoptr?

最佳回答

如果您有C++0x编译器,则可以根据需要使用shared_ptrunique_ptr

有一个正确的unique_ptr用法此处由@James McNellis提供。有关shared_ptr演练,请查看此处,由@D.Shawley提供。[我相信,这些帖子仍将获得更多选票。]

auto_ptrvector始终无效,尽管Visual C++v6不同意。

问题回答

不,您只是不能拥有std::auto_ptr的向量,尽管存在许多可以的猜测。但是,如果您的编译器支持C++0x,您可以使用std::unique_ptr,这是不推荐使用的自动指针的新替代方案,引用新标准中的话,它提供了一个更好的替代方案。另请参阅此线程

auto_ptr是为在变量离开作用域时自动删除而设计的。您不想在集合中使用它,相反,如上所述,您希望使用类似shared_ptr的东西。

auto_ptr的典型用法示例:

void foo()
{
   auto_ptr<int> bar = auto_ptr<int>(new int);
   ...

   return;  //memory held by auto_ptr is automatically deleted
}

如果您不确定auto_ptr的特殊语义,那么超出此用途的任何东西都可能是危险的和/或损坏的。(编辑:根据Armen的评论进行澄清)





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签