有没有办法保持一个内存块为容器? [英] Is there any way to keep a memory block for a container?
问题描述
我希望我会清楚....
I hope I'll be clear....
在我的代码中,我定义了一个框
它包含一组元素( bead
):
In my code, I define a box
which holds a set of elements (bead
):
vector<vector<vector<set<std::tr1::shared_ptr<bead> > > > > boxes;
我在框中添加元素
:
boxes[i][j][k].insert(aBead);
由于某种原因,我在这里得到一个分割错误。据我所知,由于非法 bead
和 i
, j
, k
都小于框的大小,并且不为负数。
For some reason I get a segmentation fault here. As far as I can tell, The segmentation fault does not occur because of illegal bead
and i
, j
, k
, are all smaller than the box's size and are not negative.
如果你想知道是什么:
class particle{
public:
vec pos;
vec oldPos;
vec vel;
vec F;
vec oldF;
int charge;
int type;
double U;
double nextU;
};
class bead: public particle{
public: //most of this is redundant...
int charge;
int type;
double rho;
double nextRho;
int LID;
bool keep;
bool touch;
double radius;
}
class vec{
public:
double x;
double y;
double z;
velarray<double> coor; //on it's way to being canceled
}
推荐答案
p>当创建 shared_ptr< T>
时,您将想要使用指向已使用 new
关键字,而不是实际的对象或对象引用。例如:
When creating a shared_ptr<T>
, you will want to intiailize it with a pointer to the object type that has been created using the new
keyword, not with an actual object or object reference. For instance:
shared_ptr<bead> ptr(new bead);
不
bead aBead;
shared_ptr<bead>(aBead);
BTW,还不要执行以下操作:
BTW, also do not do the following:
bead* ptr = new bead();
shared_ptr<bead> sptr(ptr);
delete ptr;
shared_ptr< bead>
对象管理指针的生命周期。它将引用计数指针,并在 shared_ptr< T>
析构函数内部的指针上调用 delete
没有更多的指针的引用。如果在初始化 shared_ptr< T>
对象后,在指针上手动调用 delete
因为你基本上试图自我管理内存的生命周期,击败一个托管的智能指针,如 shared_ptr< T>
的整个指针。
The shared_ptr<bead>
object manages the lifetime of the pointer. It will reference count the pointer, and call delete
on the pointer internally in the shared_ptr<T>
destructor when there are no more references to the pointer. If you manually call delete
on the pointer after initializing the shared_ptr<T>
object, you will end up with a segmentation fault as well, since you've basically tried to self-manage the memory life-time, defeating the whole pointer of a managed "smart" pointer like shared_ptr<T>
.
这篇关于有没有办法保持一个内存块为容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!