c++ - Assigning value to returned shared_ptr doesn't behave as expected -
i have private 3 dimensional vector of shared_ptr<room>
objects follows:
private: vector<vector<vector<shared_ptr<room>>>> world;
in same class, provide access room
objects:
public: shared_ptr<room> room_at(const int & x, const int & y, const int & z) const { return world.at(x).at(y).at(z); }
also in same class, initialize world
structure:
for (int x = 0; x < c::world_x_dimension; ++x) { vector<vector<shared_ptr<room>>> row; (int y = 0; y < c::world_y_dimension; ++y) { vector<shared_ptr<room>> vertical_stack; // "stack" (int z = 0; z < c::world_z_dimension; ++z) { vertical_stack.push_back(shared_ptr<room>(nullptr)); } row.push_back(vertical_stack); } world.push_back(row); }
later, want save room
object world
:
void add_room_to_world(const int & x, const int & y, const int & z) { shared_ptr<room> room = make_shared<room>(); // create empty room /* (populate room's member fields) */ // add room world room_at(x, y, z) = room; // doesn't work expected }
the shared_ptr
within world
starts out nullptr
expected, doesn't change on last line above.
based on i've found on so, i've tried operator=
(above), .reset(room)
, , make_shared<room>(room)
(using actual room
object rather shared_ptr<room>
) in cases, shared_ptr
within world
stays set nullptr
.
what correct way assign objects world
?
room_at
returns value. when returned function copied, operations on returned value don't affect original value. if want change original value have return reference this:
shared_ptr<room>& room_at(const int & x, const int & y, const int & z) const { return world.at(x).at(y).at(z); }
if don't want users of class able this, declare method private , keep original is.
Comments
Post a Comment