What is boost's shared_ptr(shared_ptr const & r, T * p) used for?

后端 未结 6 1234
孤街浪徒
孤街浪徒 2021-02-01 04:28

boost::shared_ptr has an unusual constructor

template shared_ptr(shared_ptr const & r, T * p);

and I a

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-01 05:03

    I have put shared_ptr's aliasing constructor in use in my little library:

    http://code.google.com/p/infectorpp/ (just my simple IoC container)

    The point is that since I needed a shared_ptr of known type to be returned from a polymorphic class (that does not know the type). I was not able to implicitly convert the shared_ptr to the type I needed.

    In the file "InfectorHelpers.hpp" (line 72-99) you can see that in action for the type IAnyShared.

    Aliasing constructor creates shared_ptr that does not delete the pointers they are actually pointing to, but they still increase the reference counter to the original object and that can be tremendously usefull.

    Basically you can create a pointer to anything using aliasing constructor and threat it as a reference counter.

    //my class
    std::shared_ptr ist;
    int a; //dummy variable. I need its adress
    
    virtual std::shared_ptr getReferenceCounter(){
        return std::shared_ptr(ist,&a); //not intended for dereferencing
    }
    
    virtual void* getPtr(); //return raw pointer to T
    

    now we have both "a reference counter" and a pointer to a istance of T, enough data to create something with the aliasing constructor

    std::shared_ptr aPtr( any->getReferenceCounter(), //share same ref counter 
                   static_cast(any->getPtr()) ); //potentially unsafe cast!
    

    I don't pretend to have invented this use for the aliasing constructor, but I never seen someone else doing the same. If you are guessing if that dirty code works the answer is yes.

提交回复
热议问题