簡體   English   中英

如何使靜態類函數返回非常量引用

[英]How to make static class function return non-const reference

問題:如何從靜態類函數返回非常量引用,為什么下面的代碼不這樣做?

我正在嘗試使用自定義分配器初始化向量,該分配器本身是通過對自定義內存管理類的引用進行初始化的。 看起來像這樣:

引用自定義內存管理類初始化的自定義std :: vector分配器

template <class T, std::size_t N, std::size_t MAX_SIZE, int ID>
class short_alloc
{
  arena<N, MAX_SIZE, ID>& a_;    //this is the custom memory  mgmt class
... 
public:
  short_alloc(arena<N, MAX_SIZE, ID>& a) noexcept : a_(a) { 
  std::cout<< "copying from reference" << std::endl;
  }

但是,我希望每個模板類型只有1個內存管理器,因此我嘗試使用單例的GetInstance()方法初始化分配器,以便每個模板類型僅創建1個內存管理器:

Singleton類,以確保每組模板參數只有一個內存管理器

template <typename T>
class Singleton
{
 public:
    static T* m_instance;
    static T& GetInstance(){
    if(!m_instance){
      m_instance = new T();
    }
    return m_instance;  
  };
};

用例:

我使用自定義分配器/內存管理器類實例化矢量,如下所示:

template <class T, std::size_t N, std::size_t MAX_SIZE, int ID>
class SmallVector {
   public:
      std::vector<T, short_alloc<T, N, MAX_SIZE, 1>> vec;
      SmallVector() : vec(Singleton<arena<N, MAX_SIZE, ID>>::GetInstance()){ 
      std::cout << "running constructor" << std::endl;
      }
   ...
  }

並在int main()調用,如下所示:

SmallVector<int, MAX_BLOCK, MAX_INDIV, 1> s;

但是,這會產生編譯器錯誤:

error: invalid initialization of non-const reference of type 'arena<3200ul, 400ul, 1>& from an rvalue of type 'arena<3200ul, 400ul, 1>*' return &m_instance;

因此,似乎我的Singleton類正在返回const引用/ r型引用。 我該如何返回l型引用?

返回類型為Singleton& 但是,在return語句中,您正在使用

return m_instance;  

那應該是

return *m_instance;  

您可以使用以下方法簡化課程:

template <typename T>
class Singleton
{
 public:
   static T& GetInstance(){

      // By using a static variable, its initialization is 
      // thread-safe, per C++11. That's another reason to
      // prefer this method.
      static T m_instance;

      return m_instance;  
   }
};

暫無
暫無

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

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