Thread Safety of Static Variable holding Static Cast

Viewed 48

I am doing this:

template<typename Derived>
class Base : std::enable_shared_from_this<Base<Derived>>
{
public:
    Base() {};
    
protected:
    std::shared_ptr<Derived> cast() const
    {
        static std::shared_ptr<Derived> p_derived = std::static_pointer_cast<Derived>(this->shared_from_this());
        return p_derived;
    };
};

Q1: Is this wrong? Or can you see any ugly silent stuff? Any other "standard/smart" way to do this?

Q2: Is the function Base::cast thread safe? (Multiple threads calling cast).

Thank you!

0 Answers
Related