簡體   English   中英

C++ const 方法返回非 const 指針

[英]C++ const method returning non const pointer

作為學習 C++ 的練習,我創建了以下包裝器 class,它封裝了簡單字符緩沖區的創建/銷毀:

class BufferClass {
  private:
    char *mBufferPtr;
    
  public:
    BufferClass(int pSize)
      : mBufferPtr(new char[pSize]) {}
    
    virtual ~BufferClass() {
      delete[] mBufferPtr;
    }
    
    operator char*() {
      return mBufferPtr;
    }
    
    operator const char*() const {
      return mBufferPtr;
    }
};

If there was a circumstance where I wanted to create a const instance of this class (ie I have no intention of modifying the object once constructed), but had to use it in conjuction with a C API which only accepts non-const char* pointers (甚至認為它不會改變數據),允許以下內容的普遍共識是什么:

operator char*() const {
  return mBufferPtr;
}

我意識到我可以創建緩沖區 class 的非常量實例,但我會對有關此方法有效性的評論感興趣。

您應該正確設計您的 class。 因此,如果這是一個const成員 function,那么它不應該允許以任何方式修改對象的數據。 與 C API 的兼容性不是這個 class 的責任,所以它應該在外面解決,如果需要( const_cast 'ing,復制到另一個緩沖區,等等

此外,您可能還可以為 C API 編寫一些包裝器:

  • 在公共接口中使用正確的常量並轉換為內部所需的常量(如果確實需要)
  • 另外制作 C++ 接口,如果它更有用的話

暫無
暫無

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

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