使用const std :: unique_ptr进行pimpl习语 [英] Using const std::unique_ptr for pimpl idiom
问题描述
在 Herb Sutter在CppCon16上的演讲中,他建议使用 const std :: unique_ptr $ c编写pimpl惯用语。 $ c>(大约10分钟)。
In Herb Sutter's talk at CppCon16 he suggested writing pimpl idiom with const std::unique_ptr
(roughly 10 minutes in).
这应该如何与move构造函数/赋值一起使用? c ++ 17中有东西吗?我什么都找不到。
How is this supposed to work with move constructors/assignments? Is there something in c++17? I couldn't find anything.
推荐答案
如果您的类应该是永不为空的,则可以使用非const唯一的ptr(默认移动/分配)是不合适的。
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.
一个const唯一的ptr会禁用这些自动方法,如果要移动,则必须将其写入
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).
我会亲自用自己想要的语义编写一个值ptr(然后让编译器编写该粘合),但是从a开始
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.
C ++ 17消除了这种技术的最大成本,即难以返回值。
The biggest cost of this technique, difficulty in returning values, goes away with C++17.
这篇关于使用const std :: unique_ptr进行pimpl习语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!