Using const std::unique_ptr for pimpl idiom

我与影子孤独终老i 提交于 2019-12-03 01:50:21

If your class is supposed to be never-empty, a non-const unique ptr (with default move/assigns) is not appropriate. The move ctor and move assign will both empty the rhs.

A const unique ptr will disable these automatic methods, and if you want move you will have to write it within the impl (and a bit of glue outside).

I would personally write a value ptr with the semantics I want (then let compiler write the glue), but starting with a const unique_ptr sounds reasonable as a first pass.

If you relax the never-empty, and make it almost never-empty, you now have to reason about preconditions of a lot of methods, and possible knock-on bugs.

The biggest cost of this technique, difficulty in returning values, goes away with C++17.

How is this suppose to work with move constructors/assignments?

Move constructors:

The implicitly-declared or defaulted move constructor for class T is defined as deleted if any of the following conditions are true:

  • T has non-static data members that cannot be moved (have deleted, inaccessible, or ambiguous move constructors)

const std::unique_ptr is such a data member because of const.

If const is dropped the compiler generates the move constructor and assignment, but not the copying ones.


Herb explains why he uses const unique_ptr:

non-const can work too, but it is more brittle because default move semantics are probably incorrect.

With const member it is more robust because const members must be initialized in the constructor. And const documents that the implementation of the object does not change, it is not State or Strategy design pattern.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!