How to assign unique ptr?

closed account (Ey80oG1T)
I was using raw pointers, but I decided to switch over to smart ptrs instead. I've never used them before, so I'm really clueless.

So I have a unique ptr like so:

1
2
3
4
5
6
std::unique_ptr<Node> node_ptr(nullptr);
while (head != nullptr)
{
    node_ptr = head->next;
    head = node_ptr;
}


head is also a unique_ptr. But that gives me an error. So how can I reassign a unique_ptr?

Here's what my original code look like (without smart pointers):

1
2
3
4
5
6
7
Node* node_ptr = nullptr;
while (head != nullptr)
{
    node_ptr = head->next;
    delete head;
    head = node_ptr;
}
You assign one std::unique_ptr to another by moving, they can't be copied. Once you've moved ownership to the 2nd the 1st no longer owns the data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <memory>
#include <utility>  // std::move

int main()
{
   std::unique_ptr<int> uptr1(new int(15));

   std::cout << "Has uptr1 an associated object? " << (uptr1 ? "true" : "false") << '\n';
   std::cout << "uptr1 = " << *uptr1 << "\n\n";

   std::unique_ptr<int> uptr2;

   // can't copy between std::unique_ptrs, the managed pointer has to be moved
   // uptr2 = uptr1; // error!  can't copy!
   std::cout << "Transferring ownership......\n";
   uptr2 = std::move(uptr1);

   std::cout << "Has uptr2 an associated object? " << (uptr2 ? "true" : "false") << '\n';
   std::cout << "Has uptr1 an associated object? " << (uptr1 ? "true" : "false") << "\n\n";

   std::cout << "uptr2 = " << *uptr2 << '\n';
}

Has uptr1 an associated object? true
uptr1 = 15

Transferring ownership......
Has uptr2 an associated object? true
Has uptr1 an associated object? false

uptr2 = 15

http://www.cplusplus.com/reference/memory/unique_ptr/operator=/
Topic archived. No new replies allowed.