LoginSignup
0
1

More than 1 year has passed since last update.

継承を用いない多態性を持つポインタ(std::variant型を利用)

Last updated at Posted at 2022-02-09

std::variant型を用いて、継承を用いずに多態性を持つunique_ptr型のポインタを考えました。

template< typename... A >
using A_ptr = std::variant< std::monostate, std::unique_ptr< A >... >;

■メリット
・継承関係の無いクラス同士を同一のスマートポインタA_ptrに入れられる
A_ptrの消滅時に、その時点で格納しているクラスのデストラクタを呼ぶので、メモリリークの心配がない

■デメリット
A_ptrがどのクラスのポインタなのか、variant::index()の返り値で判断する必要がある
・共通のインターフェースを持たないクラスを格納した場合、メンバにアクセスするために型キャストする必要がある
・通常のunique_ptrよりサイズが少し増える(msvcのx64環境で8byte → 16byte)

パフォーマンスに関しては未計測です。

2020/02/24追記
しばらく使ってみて感想を追加いたします。
また、皆様のご意見ご感想いただければありがたく存じます。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1