Getting a boost::shared_ptr for this

前端 未结 6 2066
有刺的猬
有刺的猬 2020-12-02 07:11

I am making extensive use of boost:shared_ptr in my code. In fact, most of the objects that are allocated on the heap are held by a shared_ptr. Unf

6条回答
  •  孤街浪徒
    2020-12-02 07:57

    The function accepting a pointer wants to do one of two behaviors:

    • Own the object being passed in, and delete it when it goes out of scope. In this case, you can just accept X* and immediately wrap a scoped_ptr around that object (in the function body). This will work to accept "this" or, in general, any heap-allocated object.
    • Share a pointer (don't own it) to the object being passed in. In this case you do not want to use a scoped_ptr at all, since you don't want to delete the object at the end of your function. In this case, what you theoretically want is a shared_ptr (I've seen it called a linked_ptr elsewhere). The boost library has a version of shared_ptr, and this is also recommended in Scott Meyers' Effective C++ book (item 18 in the 3rd edition).

    Edit: Oops I slightly misread the question, and I now see this answer is not exactly addressing the question. I'll leave it up anyway, in case this might be helpful for anyone working on similar code.

提交回复
热议问题