Search code examples
c++classc++11type-conversionshared-ptr

specialized shared_ptr conversion C++0x


This could probably be generalized to any templated class, but I've run into this with shared_ptr. I have class system that goes like:

class A {
protected:
    // some data
}

class B : public A {
    // some access functions
}

class C : public A {
    // some other access functions
}

I'm using this concept because in my library I'm using set of functions that shouldn't be exposed to user, so I divide these functions into two interface classes. Now, I know I could use one class and friends but this would get ugly if more than one class needed to access those functions.

However, I have problem that those classes are passed arround in shared_ptr and I need to retain reference counts (as the data would get destroyed). Therefore I need to convert in this example shared_ptr<B> to shared_ptr<C> and vice versa. Does shared_ptr allow such thing if needed functions are provided and if so what are those? Constructor? Assign operator? Or do I need to go level higher and cast whole pointers instead of just content? I had no luck so far.

And yes if you have a better/more neat method for hiding certain functions I'll be glad to hear it, but I would like to have this question answered too.


Solution

  • You want std::static_pointer_cast and std::dynamic_pointer_cast, from <memory>:

    struct A {}; struct B : A {};
    
    std::shared_ptr<B> p(std::make_shared<B>());
    std::shared_ptr<A> q(std::static_pointer_cast<A>(p));
    // now p and q **share** ownership over their pointed-to object.