smart pointers + “this” considered harmful?

2019-01-22 15:09发布

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

Consider that:

  • 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.

  • 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.

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?

8条回答
一纸荒年 Trace。
2楼-- · 2019-01-22 15:40

One example of correct use is return *this; in functions like operator++() and operator<<().

查看更多
forever°为你锁心
3楼-- · 2019-01-22 15:42

When you are using a smart pointer class, you are right that is dangerous to directly expose "this". There are some pointer classes related to boost::shared_ptr<T> that may be of use:

  • boost::enable_shared_from_this<T>
    • Provides the ability to have an object return a shared pointer to itself that uses the same reference counting data as an existing shared pointer to the object
  • boost::weak_ptr<T>
    • Works hand-in-hand with shared pointers, but do not hold a reference to the object. If all the shared pointers go away and the object is released, a weak pointer will be able to tell that the object no longer exists and will return you NULL instead of a pointer to invalid memory. You can use weak pointers to get shared pointers to a valid reference-counted object.

Neither of these is foolproof, of course, but they'll at least make your code more stable and secure while providing appropriate access and reference counting for your objects.

查看更多
登录 后发表回答