C++ 将值赋给返回的共享ptr不会';I don’我没有表现得像预期的那样

C++ 将值赋给返回的共享ptr不会';I don’我没有表现得像预期的那样,c++,c++11,shared-ptr,C++,C++11,Shared Ptr,我有一个私有的共享的\u ptr对象的三维向量,如下所示: private: vector<vector<vector<shared_ptr<Room>>>> world; 同样在同一个类中,我初始化了world结构: for (int x = 0; x < C::WORLD_X_DIMENSION; ++x) { vector<vector<shared_ptr<Room>>> row;

我有一个私有的
共享的\u ptr
对象的三维向量,如下所示:

private:
    vector<vector<vector<shared_ptr<Room>>>> world;
同样在同一个类中,我初始化了
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);
}
world
中的
shared_ptr
按预期开始为
nullptr
,但在上面的最后一行没有更改

根据我在SO上的发现,我尝试了
operator=
(如上)、
.reset(room)
,和
使共享(room)
(使用实际的
room
对象,而不是
共享的ptr
),但在所有情况下,
world
中的
共享的ptr
保持设置为
nullptr


将对象分配到
world
的正确方法是什么?

room\u at
返回一个值。当你改变这个值时,谁在乎呢?你只是在变异一些随机的暂时性基因。它对复制它的对象没有意义

为了支持您想要的内容,
room_at
将需要返回一个可变的引用—对于这种方式的公共API来说,这是一个非常糟糕的主意


您可能希望提供一个分析性的私有方法来返回可变引用,然后将
room\u at
实现为只返回该函数引用的对象的副本。

room\u at
返回一个值。当它从函数返回时,它会被复制,因此对返回值执行的任何操作都不会影响原始值。如果要更改原始值,必须返回如下引用:

shared_ptr<Room>& room_at(const int & x, const int & y, const int & z) const
{
   return world.at(x).at(y).at(z);
}
const int&x、const int&y、const int&z)const处的共享房间
{
返回世界。在(x)、在(y)、在(z);
}

如果您不希望类的用户能够执行此操作,请将此方法声明为私有,并保持原始方法不变。

这解决了我的问题,谢谢。我使用您的代码重载了该方法,以允许可变和不可变的访问。
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<Room>& room_at(const int & x, const int & y, const int & z) const
{
   return world.at(x).at(y).at(z);
}