smart pointers + “this” considered harmful?

后端 未结 8 1989
情书的邮戳
情书的邮戳 2020-12-14 12:10

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

8条回答
  •  感情败类
    2020-12-14 12:14

    I personally like to use the this pointer when accessing member variables of the class. For example:

    void foo::bar ()
    {
        this->some_var += 7;
    }
    

    It's just a harmless question of style. Some people like it, somepeople don't.

    But using the this pointer for any other thing is likely to cause problems. If you really need to do fancy things with it, you should really reconsider your design. I once saw some code that, in the constructor of a class, it assigned the this pointer to another pointer stored somewhere else! That's just crazy, and I can't ever think of a reason to do that. The whole code was a huge mess, by the way.

    Can you tell us what exactly do you want to do with the pointer?

提交回复
热议问题