簡體   English   中英

C++ class 由成員初始化器列表構造,帶有指向成員地址的指針

[英]C++ class construction by member initializer list with pointer to member address

我有一個基於 C 的庫(准確地說是 Vulkan),它通過將它們的地址作為參數傳遞給庫 function 來初始化和設置值。 為了防止任何泄漏並確保調用清理(即使某處發生異常),我想將該值封裝在調用createdestroy庫函數的 RAII class 中:

value_t value; // value must live somewhere else
library_create_value( value_t* value );
library_destroy_value( value_t value ); // must not be forgotten to call at the end

C 程序在這里正常工作沒有問題:

int main() {
  value_t myValue;                // fine, myValue lives on the stack of main()
  library_create_value( &value ); // and is ready to be used now

  // do all work, use myValue

  library_destroy_value( value ); // the required clean up
  return 0;
}

但是現在編寫 C++ RAII 包裝器,我很難像往常一樣找到初始化value的最佳解決方案:

class RAII_wrapper {
  value_t myValue;

public:
  RAII_wrapper() : 
    myValue( library_create_value() ) // doesn't work here as it would normally do!
  {} 

  ~RAII_wrapper() {
    library_destroy_value( value );   // nothing special here
  }

  // other methods to use myValue would be here
}

當然,我可以只在構造函數本身中進行創建調用,然后讓myValue未初始化 - 但那是(在某處調用)“沒有好的風格”。

這項任務的(官方)最佳解決方案是什么?

聽起來您希望在堆上包裝指向 object 的指針,即使這不是您提供的 main() 中的用法。 稍作改動即可實現這一點,同時確保您只創建一次 object。 第一個示例看起來您可以構造 object 兩次,一次使用默認構造函數,然后再次修改它。 請參見下面的示例:

class RAII_wrapper{
    private:
        value_t *myValue; // This maintains same function call as example
    public:
        RAII_wrapper(){
            library_create_value(myValue); 
        }
        ~RAII_wrapper(){
            library_destroy_value(myValue); 
        }
};

編輯:如果這不是 C 庫,您可以使用智能指針而不是原始指針來至少避免 library_destroy_value() 調用。

暫無
暫無

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

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