简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM