Non-Movable C++ 17独特指针

tan*_*ngy 18 c++ unique-ptr c++11 c++17

我遇到了这个答案阻止移动unique_ptr C++ 11.然而,当在线编译器上进行尝试时,这适用于C++ 11(std::move编译器错误)但是使用C++ 17,我发现std::move下面的内容是成功的.编译器不应该在该行上抛出错误吗?此外,如果C++ 17中的某些语义发生了变化,那么在C++ 17及更高版本中创建不可移动的unique_ptr的正确方法是什么.

template <typename T>
using scoped_ptr = const std::unique_ptr<T>;

int main()
{
    auto p = scoped_ptr<int>(new int(5));
    auto p2 = std::move(p); // should be error?
    std::cout << *p2 << std::endl; // 5
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里尝试一下.

Yak*_*ont 17

p不是const.在这里看到它会以你期望的方式失败.

auto演绎得像template<class T>void foo(T). T永远不会被推断为const,也不是auto p=.

同时,该auto p =行有效,因为您在模式下编译它.在 它不能编译.这是因为prvalues的差异在17; 有些人称差异保证省略.

如果你想要一个固定的独特ptr:

template<class T, class D>
struct immobile_ptr:private std::unique_ptr<T, D>{
  using unique_ptr<T>::operator*;
  using unique_ptr<T>::operator->;
  using unique_ptr<T>::get;
  using unique_ptr<T>::operator bool;
  // etc

  // manually forward some ctors, as using grabs some move ctors in this case
};
template<class T, class...Args>
immobile_ptr<T> make_immobile_ptr(Args&&...args); // todo
Run Code Online (Sandbox Code Playgroud)

一个替代方案可能是采用一个独特的ptr与一个固定的驱逐舰.

template<class X>
struct nomove_destroy:std::destroy<T>{
  nomove_destroy(nomove_destroy&&)=delete;
  nomove_destroy()=default;
  nomove_destroy& operator=(nomove_destroy&&)=delete;
};
template<class T>
using nomove_ptr=std::unique_ptr<T,nomove_destroy<T>>;
Run Code Online (Sandbox Code Playgroud)

但我不确定这是否有效.