c++ - 将“this”传递给子对象
问题描述
这种传递和存储this
到子对象的方法在使用时是否仍然被认为是“可接受的” C++17
,或者是否有更合适的方法,符合语言和标准?
我特别询问有关将Parent
对象作为普通指针传递和存储的问题。
class Child
{
public:
void SetParent(Parent* p)
{
_parent = p;
}
private:
Parent* _parent;
};
class Parent
{
public:
void MyMethod()
{
Child c;
c.SetParent(this);
}
};
解决方案
std::weak_ptr<Parent>
假设您正在使用C++11 后,您可以使用std::shared_ptr<Parent>
(并继承自std::enable_shared_from_this
以在内部生成 astd::shared_ptr
或std::weak_ptr
)。
除此之外,是的,使用原始指针来表示缺乏所有权或反向指针仍然是可以接受的(直到委员会添加某种std::owned_ptr<T>
/std::ptr_view<T>
类)。
推荐阅读
- python - OpenCV 将数据从 C++ 传递到 Python
- swift - SKLabelNode PhysicsBody 问题
- python-3.x - list() 定义类型错误
- node.js - coinbase API 问题
- python - 如何更新将其值保存在列表中的字典键?
- reactjs - React/Socket.io - 客户端只向所有其他客户端发出一次,然后只向自己发出一次
- erlang - Elixir/Erlang file_server 消息积压和不可靠的吞吐量导致性能问题
- c# - 使用等待的 Task.Run 中的数据填充 ObservableCollection
- node.js - Web 推送通知不适用于 Firefox,但适用于 Chrome 和 Edge
- reactjs - 如何使用 useState 更新多个状态?