简体   繁体   English

持有指针的对象的C ++向量

[英]c++ vector of objects holding pointer

struct Obj
{
    Obj(P *p, int i): m_p(p), m_info(info) {}
    std::auto_ptr<P> m_p;
    int m_info;
};

std::vector<Obj> objects; // error C2558: struct 'Obj' : no copy constructor available...

The problem here resides in auto_ptr , I guess. 我想这里的问题出在auto_ptr Everybody knows that it's a bad thing to push auto_ptr into containers, and it's also a bad to push those who holds auto_ptr into containers. 大家都知道将auto_ptr推入容器是一件坏事,而将那些持有auto_ptr容器推入容器也是一件坏事。 It I had no m_info field, I would use boost::ptr_vector<P> objects 如果没有m_info字段,我将使用boost::ptr_vector<P> objects

How would you suggest to sort it out? 您会如何建议解决呢?

I assume your class Obj is suppose to take ownership of p. 我假设您的班级Obj假设拥有p的所有权。 Why not, simply use a normal pointer, with RAII (assign m_p in Obj(P *p, int i) and delete it in ~Obj() ) ? 为什么不使用RAII来简单地使用普通指针(在Obj(P * p,int i)中分配m_p并在〜Obj()中将其删除)?

Or you could easily create a ScopedPointer class, like that one http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/scoped_ptr.htm 或者,您可以轻松地创建一个ScopedPointer类,例如一个http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/scoped_ptr.htm

您可以自己管理原始指针(在构造函数中分配,在析构函数中释放并实现复制语义-与RAII一致),也可以将指针的类型从std :: auto_ptr更改为std :: shared_ptr / boost :: shared_ptr /其他。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM