unique_ptr to an opaque struct? (C++)
Asked Answered
M

2

6

A library defines an opaque data type:

struct OpaqueStruct;

and the client code has to obtain and release an OpaqueStruct*. I have access to the library source.

Unfortunately, neither shared_ptr nor unique_ptr cannot store that pointer giving an error: invalid application of ‘sizeof’ to incomplete type.

The best thing I can think of is to borrow the finally guard from this post.

How do I use RAII for opaque struct pointers?

Malleolus answered 7/12, 2015 at 9:12 Comment(6)
Try this #19053851Byandby
@T.C.: sadly the answer to the duplicate question does not explain how to use a custom deleter with a std::unique_ptr<T> to create these entities in a context where T is undefined (the answer to the question StoryTeller pointed to does, though).Charissa
I've rolled back your edit as it is inappropriate to include the answer in the question. If you think this question should be reopened so you can post your own answer you should edit your question to explain why the duplicate does not solve it.Lecky
@Lecky Well, can you then please redirect the duplicate mark? Currently it is marked as a duplicate of a question that does not contain the answer.Malleolus
The answer that was censored: std::unique_ptr<OpaqueStruct, void(*)(OpaqueStruct*)> ops(newOpaqueStruct(), deleteOpaqueStruct);Malleolus
By editing your question appropriately it will automatically be entered in the Reopen Votes review queue where if the edit is sufficient it will be reopened by reviewers.Lecky
N
3

You can only construct and delete complete types, see also here: Deletion of pointer to incomplete type 'Point'; no destructor called. So at least the code fragment doing the construction / destruction needs to know the complete type.

You can declare a unique_ptr or shared_ptr using an incomplete type. For which members of these smart pointers you can use in a context where only the incomplete type is known, see Is std::unique_ptr<T> required to know the full definition of T?.

Neomaneomah answered 7/12, 2015 at 11:38 Comment(0)
M
3
std::unique_ptr<OpaqueStruct, void(*)(OpaqueStruct*)>
               ops(newOpaqueStruct(), deleteOpaqueStruct)
Malleolus answered 10/12, 2015 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.