Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

Move std::unique_ptr to Pass to a Function or Assign to Another Variable

$
0
0

The std::unique_ptr has unique ownership of the object it manages. That means only one std::unique_ptr can contain the actual object pointer. That’s why we can not assign a std::unique_ptr to another one. For the same reason we can not pass std::unique_ptr as an argument of a function. But we can move the ownership of the object to a new std::unique_ptr. After moving the ownership new variable (assigned one) will own the object. We’ll no longer be able to access the object from the old std::unique_ptr.

We’ll use this class in our examples in this article.

class C {
public:
  C() {
    std::cout << "Constructing the class..." << std::endl;
  }

  ~C() {
    std::cout << "Destructing the class..." << std::endl;
  }

  void f() {
    std::cout << "Printing from function f()..." << std::endl;
  }
};

We can create a std::unique_ptr of C type object like this.

std::unique_ptr<C> pc = std::unique_ptr<C>(new C());

But we can not assign this std::unique_ptr, pc, to another one.

std::unique_ptr<C> new_pc = pc;

This will produce compilation errors. But we can move the ownership of the actual pointer to new std::unique_ptr.

std::unique_ptr<C> new_pc = std::move(pc);

After this, pc will no longer own the actual pointer. We won’t be able to use the old unique_ptr, pc.

if(pc == nullptr) {
  std::cout << "pc does not own the actual pointer" << std::endl;
}

The “pc == nullptr” checking will return true. But we’ll be able to use the new std::unique_ptr, new_pc. We can call the new_pc->f() function.

Passing std::unique_ptr to Function

Similar thing happens when we try to pass a std::unique_ptr a function as parameter. Here is a function that takes std::unique_ptr as input.

std::unique_ptr<C> func1(std::unique_ptr<C> ptr)
{
  ptr->f();
  return ptr;
}

If we try to call this function like this:

std::unique_ptr<C> pc = std::unique_ptr<C>(new C());
func1(pc)

It will produce compilation errors. We have to move the ownership of the actual pointer like this.

std::unique_ptr ret = func1(std::move(pc));

After this statement, pc will no longer own the actual pointer.

But when a function returns a std::unique_ptr, the ownership is automatically transferred to the returned variable. In this example, after func1 returns, ret will own the actual pointer. We’ll be able to call ret->f() function.

The post Move std::unique_ptr to Pass to a Function or Assign to Another Variable appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>