智能指针+“this”认为有害? [英] smart pointers + "this" considered harmful?

查看:581
本文介绍了智能指针+“this”认为有害?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用智能指针的C ++项目中,例如 boost :: shared_ptr ,关于使用

In a C++ project that uses smart pointers, such as boost::shared_ptr, what is a good design philosophy regarding use of "this"?

    $ b

存储任何智能指针中包含的原始指针以供将来使用是危险的。

  • It's dangerous to store the raw pointer contained in any smart pointer for later use. You've given up control of object deletion and trust the smart pointer to do it at the right time.

非静态类成员本质上使用 > this 指针。

Non-static class members intrinsically use a this pointer. It's a raw pointer and that can't be changed.

如果我曾经存储过 在另一个变量或传递给另一个函数,可能存储它以后或在回调中绑定,我创建的错误,当任何人决定制作一个共享指针到我的类。

If I ever store this in another variable or pass it to another function which could potentially store it for later or bind it in a callback, I'm creating bugs that are introduced when anyone decides to make a shared pointer to my class.

鉴于此,何时适合我明确使用指针? strong>有没有设计范例可以防止与此相关的错误?

Given that, when is it ever appropriate for me to explicitly use a this pointer? Are there design paradigms that can prevent bugs related to this?

推荐答案

虽然我没有一般的答案或一些惯用法,有 boost :: enable_shared_from_this 。它允许您获得一个shared_ptr管理已经由shared_ptr管理的对象。因为在成员函数中,你没有引用那些管理shared_ptr的函数,enable_shared_ptr允许你获得一个shared_ptr实例,并在需要传递this指针时传递它。

While i don't have a general answer or some idiom, there is boost::enable_shared_from_this . It allows you to get a shared_ptr managing an object that is already managed by shared_ptr. Since in a member function you have no reference to those managing shared_ptr's, enable_shared_ptr does allow you to get a shared_ptr instance and pass that when you need to pass the this pointer.

但这不会解决在构造函数中传递这个的问题,因为那时, shared_ptr正在管理您的对象。

But this won't solve the issue of passing this from within the constructor, since at that time, no shared_ptr is managing your object yet.

这篇关于智能指针+“this”认为有害?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆