user5965026
user5965026

Reputation: 485

Is there any advantage to moving a pointer?

I'm working with a code base right now, and there's this section that has the following:

if(const auto *temp_ptr = obj->get_ptr()) {
  perm_ptr = std::move(temp_ptr);
}

What is the point of the std::move in this case when it's just a simple pointer? It doesn't seem there's any advantage over simply doing perm_ptr = temp_ptr?

Upvotes: 3

Views: 1319

Answers (1)

user4442671
user4442671

Reputation:

As said in the comments, if the type of perm_ptr is a raw pointer type, then the move is pointless.

However, it is possible to define a type for perm_ptr that would make this syntax meaningful. Whether it would be useful is at best highly debatable, and results in unintuitive and unconventional code.

It involves defining an assignment operator that only accepts a RValue to a pointer. Like so: operator=(T*&& p);.

This could, for instance, be used to ensure that no one accidentally assigns a raw pointer to something that will eventually calling delete on it without doing so intentionally.

It could also be used to reset the pointer to nullptr (or some other value) as part of the assignment.

#include <utility>

template<typename T>
struct my_unique_ptr {
  ~my_unique_ptr() {
    if(ptr_) delete ptr_;
  }

  my_unique_ptr& operator=(T*&& p) { 
    ptr_ = p; 
    p = nullptr;
    return *this; 
  }

private:
  T* ptr_ = nullptr;
};

int main() {
    my_unique_ptr<int> perm_ptr ;

    int* ptr = new int;

// all good.
    owning_ptr = std::move(ptr);

// compile error!
    owning_ptr = ptr;  

}

To be 100% clear: This is a only an example that could result in the program presented by the OP being intentional and meaningful. I am not advocating for such a technique. Even if it was a good idea, it would still be fraught with caveats and pitfalls that are not being covered by this answer.

Upvotes: 3

Related Questions