c++ - Is it a bad design decision to manually call the destructor in the following case? -


so working on oop/c++ skills , stumbled upon following case:

i making game populated entities, have eat in order survive. can either eat other entities or food. in order achieve behaviour created edible interface forces every implementing class create getnutritionalinformation() method calculate how saturated unit after feasting.

so whole thing supposed work code-wise:

std::unique_ptr<entity> e1(new entity); std::unique_ptr<entity> e2(new entity);  std::cout << "pre feasting energy: " << e1->getnutritionalinformation() << std::endl; e1->eat(*e2); std::cout << "after feasting energy: " << e1->getnutritionalinformation() << std::endl; 

after operation c1s energy should higher before, value randomly assigned during creation of entity. in order simulate death of eaten entity want manually kill while being eaten. achieved following way:

void entity::eat(edible& subject) {    this->energy += subject.getnutritionalinformation();    delete &subject; } 

but in end seems kind of dirty me, let smart pointer know in way, object holds/points not valid longer. there cleaner way achieve this? pretty sure way trying hacky , not considered proper oop programming.

thank in advance.

well, e2 "eating" e1 taking ownership of it. specifically, has take ownership of it, in order destroy it. way this:

void entity::eat(std::unique_ptr<edible> subject) {     this->energy += subject->getnutritionalinformation(); } 

and... that's it. subject automatically destroyed @ end of scope. in order use this, you'll need call std::move explicitly; indicates transferring ownership calling scope, e2.

std::unique_ptr<entity> e1(new entity); std::unique_ptr<entity> e2(new entity);  std::cout << "pre feasting energy: " << e1->getnutritionalinformation() << std::endl; e1->eat(std::move(e2)); std::cout << "after feasting energy: " << e1->getnutritionalinformation( << std::endl; 

note after std::move has been called on e2, e2 can no longer assumed point entity (since ownership has been transferred).


Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -