sazr
sazr

Reputation: 25938

Cast from pointer to reference

I have a generic Singleton class that I'll use for many singleton classes. The generic class is giving a compile error when converting from a pointer to reference.

Error 3 error C2440: 'static_cast' : cannot convert from 'IApp *' to 'IApp &'

Below is the generic class and the compiler error occurs in the instance() function.

template<typename DERIVED>
class Singleton
{
public:

    static DERIVED& instance()
    {
        if (!_instance) {
            _instance = new DERIVED;
            std::atexit(_singleton_deleter); // Destruction of instance registered at runtime exit (No leak).
        }

        return static_cast<DERIVED&>(_instance);
    }

protected:

    Singleton() {}
    virtual ~Singleton() {}

private:

    static DERIVED* _instance;

    static void _singleton_deleter() { delete _instance; } //Function that manages the destruction of the instance at the end of the execution.

};

Is it possible to cast this way? I don't want instance() to return a pointer, I'd prefer a reference. Or maybe a weak_ptr? Any ideas how to cast this?

Upvotes: 0

Views: 167

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477444

What you are looking for is dereferencing of a pointer, using the indirection operator *. You want either

return static_cast<DERIVED&>(*_instance);
//                         ^^^^^

or

return *static_cast<DERIVED*>(_instance);
//   ^^^^^

or simply:

return *_instance;
//   ^^^^^

since _instance already has type Derived * and the two casts above are no-ops.

Upvotes: 6

Related Questions