从指针转换为引用

时间:2015-12-23 02:18:44

标签: c++ templates static-cast

我有一个通用的Singleton类,我将用于许多单例类。从指针转换为引用时,泛型类会产生编译错误。

  

错误3错误C2440:'static_cast':无法从'IApp *'转换为'IApp&'

下面是泛型类,instance()函数中出现编译器错误。

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.

};

有可能这样投吗?我不希望instance()返回指针,我更喜欢引用。或者是weak_ptr?任何想法如何投这个?

1 个答案:

答案 0 :(得分:6)

您正在寻找的是使用间接运算符* 取消引用指针。你想要

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

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

或简单地说:

return *_instance;
//   ^^^^^

因为_instance 已经的类型为Derived *,而且上面的两个演员都是无操作。