Title.
I've been trying to understand this better, and it's... kind of working. In my example I've been working on:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
Gun *rifle = new Gun();
std::cout << "get rifle accuracy: " << rifle->getAccuracy() << std::endl;
std::vector<GunPart*> parts;
parts.push_back(&rifle->barrel);
parts.push_back(&rifle->stock);
parts.push_back(&rifle->magazine);
parts.push_back(&rifle->grip);
parts.push_back(&rifle->chamber);
parts.push_back(&rifle->scope);
Gun *pistol = new Gun(*parts.at(0), *parts.at(1), *parts.at(2), *parts.at(3), *parts.at(4), *parts.at(5));
delete rifle;
parts.erase(parts.begin(), parts.end());
std::cout << "pistol accuracy: " << pistol->getAccuracy() << std::endl;
std::cout << "rifle accuracy: " << rifle->getAccuracy() << std::endl;
delete pistol;
|
I'm trying to work with objects that can be deleted at any time, for any number of reasons. Gun and GunPart are two different classes, Gun has 5 GunPart members. (this is just testing code, not any actual code)
This compiles and runs and everything. The part I'm confused on involves the results of trying to manage the memory here.
I declared *rifle, and later store it's GunPart members into a vector. Those parts get copied over to a different Gun object. I then delete rifle and erase the vector's elements. I've checked, the destructors are called on rifle and it's member GunPart's.
But, the line where I cout the accuracy still works. Meaning, it gives the correct value. The same as the first time it's called. But I was supposedly deleted the data. I've read the dynamic memory part of the tutorial a few times, but I feel there is still some concept I'm missing.
Any help is appreciated.