0

Is there something akin to the post increment operator to set an origin pointer to null ?

Wanted behaviour:

Class MyClass{
   public:
   int * ptr;

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

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

Workaround with wanted semantic:

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

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

Maybe I'm missing something from the standard, but I couldn't find anything to represent a type of pointer to represent not ownership but also the prevents accidental sharing of a pointer.

I could use an unique_ptr with a custom deleter that does nothing, but that'd make the original assignment of the pointer weird.

xvan
  • 4,554
  • 1
  • 22
  • 37

1 Answers1

1

There is no such feature in C++, you have to write it yourself as you had with moveptr. This is the same case when you use delete ptr;, some programmers would like to automatically set ptr to nullptr but delete will not do it.

Another aproach used by some coders is to use swap:

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


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

but before using it, read on whether its worth it:

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

Why do some people use swap for move assignments?

Community
  • 1
  • 1
marcinj
  • 48,511
  • 9
  • 79
  • 100
  • 2
    I prefer `std::exchange`: `MyClass::MyClass(MyClass&& origin) : ptr(std::exchange(origin.ptr, nullptr)) noexcept { }` – ildjarn May 10 '16 at 15:57