sdgfsdh sdgfsdh - 10 days ago 5
C++ Question

Can I omit the type arguments of smart pointers in my header files?

I am building a C++ library. I have a

struct
that contains a
std::unique_ptr
to another
struct
that I would like to hide from the user.

For example:

struct MyStruct {
int x;
private:
std::unique_ptr<MyPrivateStruct> y;
};


Now, I need to specify
MyStruct
in a header file that the user can include so that they know its layout. However, this requires that I also expose the header for
MyPrivateStruct
, which I do not want to do. Since the size of a
unique_ptr
is the same regardless of the type, is it possible to do something like this?

struct MyStruct {
int x;
private:
std::unique_ptr<auto> y;
};


The type of the
y
would then be determined by my
cpp
files.




This is not quite the same question as Can't use std::unique_ptr<T> with T being a forward declaration since the answer to this question is to use a forward declaration. That question is about a problem when using forward declarations.

Answer

Sure!

struct MyPrivateStruct;

struct MyStruct {
    int x;
  private:
    std::unique_ptr<MyPrivateStruct> y;
};
Comments