c++ - 为返回的 shared_ptr 赋值不符合预期

标签 c++ c++11 shared-ptr

我有一个私有(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_ptrworld 内开始为 nullptr正如预期的那样,但在上面的最后一行没有改变。

根据我在 SO 上的发现,我尝试了 operator= (上图),.reset(room) , 和 make_shared<Room>(room) (使用实际的 Room 对象而不是 shared_ptr<Room> )但在所有情况下, shared_ptrworld 内保持设置为 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/

相关文章:

c++ - 如何使用 openssl 或任何其他带有智能卡签名的库创建 PKCS7 signedData 结构?

c++ - 通过 shared_ptr : ThreadSanitzier false positive? 同步

c++ - 如果继承不是公开的而不是出错,为什么 enable_shared_from_this 会崩溃

c++ - 如何简单地调整指针的集合或映射排序谓词

c++ - Eigen::vector ;在函数中使用 Eigen::Matrix3f 的值初始化 vector ,大于 4 个条目

c++ - 基于范围的循环和内联函数

c++ - 将 C++11 std::function 传递给采用 boost::function 的遗留函数是否安全

c++ - 'class std::map<std::basic_string<char>, Gui >' has no member named ' emplace'

c++ - 不传递参数重载运算符

c++ - 将静态 unordered_map 放入 XCode 中的不同编译单元时被删除