C++ 类通过成员初始值设定项列表和指向成员地址的指针构造

问题描述

我有一个基于 C 的库(准确地说是 Vulkan),它通过将地址作为参数传递给库函数来初始化和设置值。为了防止任何泄漏并确保调用清理(即使在某处发生某些异常时)我想将该值封装在调用 createdestroy函数的 RAII 类中它:

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 未初始化 - 但这(在某处调用)“没有好的风格”。

此任务的(官方)最佳解决方案是什么?

解决方法

听起来您希望为堆上的对象包装一个指针,即使这不是您提供的 main() 中的用法。一个小的更改将允许这样做,同时还确保您只创建一次对象。第一个例子看起来你可以构造对象两次,一次使用默认构造函数,一次修改它。请参见下面的示例:

bin/watch-storefront.sh

编辑:如果这不是 C 库,您可以使用智能指针而不是原始指针来至少避免 library_destroy_value() 调用。