My question is explained in the example below. It is weird that the parent object loses the internal data of its child object, if the parent object is instantiated before the child object populates its internal data.
The code has a TicketService
, which internally holds a TicketStore
instance. The store
is populated with 20 concerts
. If the code has the following order, everything works as expected, and the service will be able to see 20 concerts in the store.
TicketStore store;
Add20Concerts(store);
TicketService service(store); // <- instantiating service after populating the store
// # of concerts in service=20
cout<<"# of concerts in service="<<service.GetNumberOfConcerts()<<endl;
However, if service
is instantiated before the store is populated, it sees zero concert in the store.
TicketStore store;
TicketService service(store); // <- instantiating service before populating the store
Add20Concerts(store);
// # of concerts in service=20
cout<<"# of concerts in service="<<service.GetNumberOfConcerts()<<endl;
Why service
has a store
that is empty? If service
is instantiated by passing a reference to store
, and since store will use a default copy constructor, the underlying concert_map_
should have already held the 20 concerts.
A more-detailed skeleton of the code is as below, but the above is pretty much what my confusion is.
*******************************************************************************/
// ticket_service.h
class TicketService {
public:
explicit TicketService(const TicketStore& store) {
store_ = store; // should use the default copy constructor, which is a shallow copy of the original store
}
int32_t GetNumberOfConcerts() {
return store_.GetStoreSize();
}
private:
TicketStore store_;
};
*******************************************************************************/
// ticket_store.h
class TicketStore {
public:
TicketStore() {}
void AddConcert(const Concert& concert) {
concert_map_[concert.id()] = concert;
}
int32 GetStoreSize() const {
return concert_map_.size();
}
private:
absl::flat_hash_map<int64, Concert> concert_map_;
};
*******************************************************************************/
// main.cc
int main(int argc, char* argv[]) {
TicketStore store;
TicketService service(store);
Add20Concerts(store);
// if service is instantiated here, # of concerts in service=20.
// TicketService service(store);
cout<<"store size="<<store.GetStoreSize()<<endl; // store size=20
// # of concerts in service=0 ??
cout<<"# of concerts in service="<<service.GetNumberOfConcerts()<<endl;
}
void Add20Concerts(TicketStore &store) {
for(int i=0; i<10; i++) {
Concert concert;
concert.set_id(i);
store.AddConcert(concert);
}
}