【问题标题】:Move Semantics: post set nullptr移动语义:post set nullptr
【发布时间】:2016-09-05 15:26:09
【问题描述】:

是否有类似于 post increment 操作符的东西来将源指针设置为 null ?

想要的行为:

Class MyClass{
   public:
   int * ptr;

   MyClass( MyClass && origin) noexcept;
   MyClass(){}
};

MyClass::MyClass( MyClass && origin) noexcept:
   ptr(origin.ptr){origin.ptr=nullptr};   

需要语义的解决方法:

int * moveptr(int * & ptr){
        int * auxptr=ptr;
        ptr=nullptr;
        return auxptr;
}

MyClass::MyClass( MyClass && origin) noexcept: ptr(moveptr( origin.ptr)){};

也许我在标准中遗漏了一些东西,但我找不到任何东西来表示一种指针类型来表示不是所有权,但也可以防止意外共享一个指针。

我可以将 unique_ptr 与不执行任何操作的自定义删除器一起使用,但这会使指针的原始分配变得奇怪。

【问题讨论】:

  • 多写一行rhs.p = nullptr真的很麻烦吗?
  • 这不是打扰,而是忘记做。
  • 无论如何这是惯用的做法,我怀疑它有任何预制解决方案

标签: pointers c++11 move-semantics


【解决方案1】:

C++ 中没有这样的功能,你必须像 moveptr 那样自己编写它。当你使用delete ptr; 时也是这样,有些程序员想将ptr 自动设置为nullptr,但delete 不会这样做。

一些程序员使用的另一种方法是使用swap

MyClass::MyClass( MyClass && origin) noexcept : ptr(nullptr)
   { swap(origin); };   


class MyClass {
   // ...
   inline void swap(MyClass & other) {
        using std::swap;
        swap(ptr, other.ptr);
   }
   // ...
};

但在使用它之前,请阅读它是否值得:

http://scottmeyers.blogspot.com/2014/06/the-drawbacks-of-implementing-move.html

Why do some people use swap for move assignments?

【讨论】:

  • 我更喜欢std::exchangeMyClass::MyClass(MyClass&& origin) : ptr(std::exchange(origin.ptr, nullptr)) noexcept { }
猜你喜欢
  • 2020-08-29
  • 2021-09-24
  • 2011-07-28
  • 2016-02-04
  • 2020-08-20
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多