1

I am trying to use a unique_ptr in C++ to point to a struct. The struct's definition is unknown to the initializer. The header file containing the struct, contains a function to retrieve the size the struct will be, and the struct is constructed and returned via a create(void* memory) call where memory points to a chunk of data of the proper size.

Initializing this unique_ptr with the below example code (malloc success checks will be added after this error is fixed), causes a compile time error: error: invalid application of ‘sizeof’ to incomplete type ‘OlmAccount’ since the code can't access the struct definition.

Is it possible, to specify the size of the struct to the unique pointer, to effectively "override" sizeof for that struct and resolve this error?

An example which causes this issue:

std::unique_ptr<OlmAccount>(static_cast<OlmAccount *>(olm_account(malloc(olm_account_size()))));

Edit: Similar questions are concerned with, and fixed by, specifying a deleter. However, when this code is adapted to use a shared_ptr (which is defined to compile correctly with an incomplete deleter), the same type of size error is thrown:

error: invalid application of ‘sizeof’ to incomplete type ‘OlmAccount’ static_assert( sizeof(_Yp) > 0, "incomplete type" );

aj1996
  • 15
  • 6
  • 3
    Possible duplicate of [Is std::unique\_ptr required to know the full definition of T?](https://stackoverflow.com/questions/6012157/is-stdunique-ptrt-required-to-know-the-full-definition-of-t) – Barmar Mar 13 '18 at 23:34
  • You need to provide a custom deleter for `OlmAccount` and use this deleter in all `unique_ptr`s to `OlmAccount`. Since this looks like this might be a C++ interface for a C structure, you probably have a `_destroy` or `_free` that you can easily use in this case. – Daniel Kamil Kozar Mar 13 '18 at 23:37
  • Thank you for the suggestions. I've updated my question (under the edit section) to address the possible issue of the deleter. – aj1996 Mar 13 '18 at 23:52

1 Answers1

0

Barmar and Daniel were correct, a deleter is necessary.

Since the default deleter is the function calling sizeof, providing a custom deleter will remove the sizeof dependency.

Working Deleter

aj1996
  • 15
  • 6