簡體   English   中英

從指針投射到參考

[英]Cast from pointer to reference

我有一個通用的Singleton類,將用於許多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 有任何想法如何投射嗎?

您正在尋找的是使用間接運算符* 取消對指針的引用 你想要

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

要么

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

或者簡單地:

return *_instance;
//   ^^^^^

因為_instance 已經具有Derived *類型,並且上面的兩個強制類型轉換為no-ops。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM