I am working on an Entity
class which needs to provide access to its data members through setter methods, which check that a value is allowed before storing it (checking code not shown). The Select
class is one of the types stored and it needs to do some very specific cleaning up when destroyed:
#include<memory>
#include <iostream>
class Select {
int i, j;
friend class Entity;
public:
Select(int a, int b) : i{a}, j{b} { }
~Select() {
cout << "destroying " << i << j << endl;
}
protected:
Select() { };
};
class Entity {
Select select_;
public:
void select_setter(const Select &select) {
cout << "to be assigned... " << select.i << select.j << endl;
select_ = select;
}
static shared_ptr<Entity> create(const Select &s) {
auto sp = make_shared<Entity>(Entity{});
sp->select_setter(s);
return sp;
}
};
This block demonstrates how I want the Entity
type to be used:
int main() {
auto sp = Entity::create({1, 1});
sp->select_setter({2, 2});
sp->select_setter({3, 3});
cout << "the end" << endl;
return 0;
}
Here is the output:
destroying 00
to be assigned... 11
destroying 11
to be assigned... 22
destroying 22
to be assigned... 33
destroying 33
the end
destroying 33
A) Why is e.g. Select
00 destroyed before the code reaches the =
-assign statement?
B) Why is 33 destroyed twice, but 00, 11 and 22 only once?
Aucun commentaire:
Enregistrer un commentaire