gpt4 book ai didi

c++ - 将 std::unique_ptr 类成员标记为 const

转载 作者:可可西里 更新时间:2023-11-01 17:44:33 27 4
gpt4 key购买 nike

许多使用 std::unique_ptr 来管理类依赖项所有权的示例如下所示:

class Parent
{
public:
Parent(Child&& child) :
_child(std::make_unique<Child>(std::move(child))){}
private:
std::unique_ptr<Child> _child;
};

我的问题是将 _child 成员标记为 const 是否会产生意想不到的副作用? (除了确保不能在 _child 上调用 reset()release() 等)。

我问是因为我还没有在示例中看到它,也不知道这是故意的还是只是为了简洁/一般性。

最佳答案

由于 std::unique_ptr 的性质(对象的唯一所有权),它需要没有任何复制构造函数。 move constructor (6) 只接受非 const 右值引用,这意味着如果你试图让你的 _child const 移动它,你会得到一个很好的编译错误: )

即使自定义 unique_ptr 将采用 const 右值引用,也无法实现。

关于c++ - 将 std::unique_ptr 类成员标记为 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39370779/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com