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

  c++, legacy-code, raii, vulkan

I’ve got a C based library (Vulkan to be precise) that is initializing and setting values by passing their address to a library function as parameter. To prevent any leaks and to make sure that the clean up is called (even when some exception is happening somewhere) I want to encapsulate that value in a RAII class that calls the create and destroy library functions for it:

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

A C program would have no issues to work correctly here:

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;
}

But now writing the C++ RAII wrapper I struggle to find the best solution to initialize the value as I’d normally do:

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
}

Of course I could just do the creation call in the constructor itself and leave myValue uninitialized till then – but that is (called somewhere) "no good style".

What’s the (officially) best solution for this task?

Source: Windows Questions C++

LEAVE A COMMENT