我有一个私有(private)的三维 vector shared_ptr<Room>
对象如下:
private:
vector<vector<vector<shared_ptr<Room>>>> world;
在同一个类(class),我提供访问Room
对象:
public:
shared_ptr<Room> room_at(const int & x, const int & y, const int & z) const
{
return world.at(x).at(y).at(z);
}
同样在同一个类中,我初始化了 world
结构:
for (int x = 0; x < C::WORLD_X_DIMENSION; ++x)
{
vector<vector<shared_ptr<Room>>> row;
for (int y = 0; y < C::WORLD_Y_DIMENSION; ++y)
{
vector<shared_ptr<Room>> vertical_stack; // "stack"
for (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);
}
后来我想存一个Room
对象进入 world
:
void add_room_to_world(const int & x, const int & y, const int & z)
{
shared_ptr<Room> room = make_shared<Room>(); // create an empty room
/* (populate room's member fields) */
// add room to world
room_at(x, y, z) = room; // This doesn't work as expected
}
shared_ptr
在 world
内开始为 nullptr
正如预期的那样,但在上面的最后一行没有改变。
根据我在 SO 上的发现,我尝试了 operator=
(上图),.reset(room)
, 和 make_shared<Room>(room)
(使用实际的 Room
对象而不是 shared_ptr<Room>
)但在所有情况下, shared_ptr
在 world
内保持设置为 nullptr
.
将对象分配到 world
中的正确方法是什么? ?
最佳答案
room_at
返回一个值。当它从函数返回时它被复制,所以你对返回值所做的任何操作都不会影响原始值。如果你想改变原始值,你必须像这样返回一个引用:
shared_ptr<Room>& room_at(const int & x, const int & y, const int & z) const
{
return world.at(x).at(y).at(z);
}
如果您不希望您的类的用户能够执行此操作,请将此方法声明为私有(private)并保持原始状态不变。
关于c++ - 为返回的 shared_ptr 赋值不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29871868/