问题
I hope I'll be clear....
In my code, I define a box which holds a set of elements (bead):
vector<vector<vector<set<std::tr1::shared_ptr<bead> > > > > boxes;
I am adding element to the box using:
boxes[i][j][k].insert(aBead);
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.
In case you wonder bead is:
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
}
回答1:
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);
not
bead aBead;
shared_ptr<bead>(aBead);
BTW, also do not do the following:
bead* ptr = new bead();
shared_ptr<bead> sptr(ptr);
delete ptr;
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>.
回答2:
If you have support for C++11, then the preferred way to make a dynamic object plus shared pointer is make_shared:
boxes[i][j][k].insert(std::make_shared<Bead>());
Failing that, you will have to perform the dynamic allocation yourself, but thenceforth the lifetime of the object will be managed by the shared pointer:
boxes[i][j][k].insert(new Bead);
You might like to change your data structure, though, to avoid excessive use of containers. Each container incurs allocations, which may turn out to be expensive. If you need to fill 3D space densely, then you could use a flattened-out 1D view that you access in strides. If you only need sparse points, a map keyed on triples may be an option.
来源:https://stackoverflow.com/questions/7436373/is-there-any-way-to-keep-a-memory-block-for-a-container