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. 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. It I had no m_info
field, I would use boost::ptr_vector<P> objects
我想这里的问题在于auto_ptr。每个人都知道将auto_ptr推入容器是一件坏事,将那些持有auto_ptr的人推入容器也是一件坏事。我没有m_info字段,我会使用boost :: ptr_vector
对象
How would you suggest to sort it out?
你会怎么建议把它整理出来?
2 个解决方案
#1
0
You can either manage the raw pointer yourself (allocate in constructor, deallocate in destructor and implement copy semantics - conformant with RAII) or change the type of the pointer from std::auto_ptr to std::shared_ptr / boost::shared_ptr / something else.
您可以自己管理原始指针(在构造函数中分配,在析构函数中释放并实现复制语义 - 符合RAII)或将指针类型从std :: auto_ptr更改为std :: shared_ptr / boost :: shared_ptr / something 。
#2
0
I assume your class Obj is suppose to take ownership of p. Why not, simply use a normal pointer, with RAII (assign m_p in Obj(P *p, int i) and delete it in ~Obj() ) ?
我假设你的班级Obj假设取得p的所有权。为什么不,简单地使用普通指针,使用RAII(在Obj中指定m_p(P * p,int i)并在~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
#1
0
You can either manage the raw pointer yourself (allocate in constructor, deallocate in destructor and implement copy semantics - conformant with RAII) or change the type of the pointer from std::auto_ptr to std::shared_ptr / boost::shared_ptr / something else.
您可以自己管理原始指针(在构造函数中分配,在析构函数中释放并实现复制语义 - 符合RAII)或将指针类型从std :: auto_ptr更改为std :: shared_ptr / boost :: shared_ptr / something 。
#2
0
I assume your class Obj is suppose to take ownership of p. Why not, simply use a normal pointer, with RAII (assign m_p in Obj(P *p, int i) and delete it in ~Obj() ) ?
我假设你的班级Obj假设取得p的所有权。为什么不,简单地使用普通指针,使用RAII(在Obj中指定m_p(P * p,int i)并在~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