简体   繁体   中英

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.

Sure!

struct MyPrivateStruct;

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

MyPrivateStruct in std::unique_ptr<MyPrivateStruct> y; does not have to be a complete type .

That is, you can forward declare it by writing

struct MyPrivateStruct;

prior to the declaration of y .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM