Hello everyone,
I wrote the following code to regenerate the problem I met:
I'm trying to have a static member ("accommodation") that contains unique_ptr. When I define accommodation in the first object "human1" it looks ok, but when i want to get it in the second object "human2" I got an error.
Why is it like that? Shouldn't the ownership of "unique_ptr<int[]> address_idx" always stay in the static member?
Human::accomodation is set to point to a temporary in Human::changeAddress(). When you use it in human2.getAccomodationCount(), it's invalid, your program isn't deterministic.
The problem isn't that accommodation changes its value - it doesn't. The problem is that that the value you assign to it is worthless in the first place, because it's pointing to a local object ac that is destroyed when it goes out of scope.
You need to make it point to something that persists after the changeAddress() method exits, i.e. to something that isn't an object with local scope.
Perhaps dynamically allocate the Accommodation object on the heap, rather than creating a local variable for it?