unique_ptr<T>* question

Hi I have been learning and familiarizing with std::unique_ptr and so I decided to emulate std::vector. At line 63, I want my current vector to point at the newly created vector but I can't assign to it. Why is that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <initializer_list>
#include <iostream>
#include <memory>
#include <utility>

template <class T>
class SimpleVector {
 private:
  size_t length{0}, capacity{0};
  std::unique_ptr<T[]> data{};

 public:
  SimpleVector() {}
  SimpleVector(std::initializer_list<T>&& ls) {
    length = ls.size();

    capacity = [](const size_t& n) {
      // capacity must be bigger than or equal to the length
      // if it can't fit the length, it'll try doubling the capacity
      size_t cap{2};
      while (n < cap) {
        cap *= 2;
      }
      return cap;
    }(ls.size());

    // now create and copy the vector
    data = std::make_unique<T[]>(capacity);
    size_t i{0};
    for (auto&& elem : ls) {
      data.get()[i] = elem;
      i++;
    }
  }
  size_t get_capacity() { return capacity; }

  T& operator[](size_t i) { return data.get()[i]; }

  T& at(size_t i) {
    // TODO: i sanitization
    return data.get()[i];
  }

  T size() { return length; }

  void push_back(T elem) {
    if (length < capacity) {
      data.get()[length] = capacity;
      length++;
    } else {
      // okay so the vector is at its maximum capacity
      // crate a new vector, with a bigger(x2) capacity
      // copy all the elements and make this point to the new vector

      ++length;
      capacity = 2 * length;
      auto new_data = std::make_unique<T[]>(capacity);
      size_t i;
      for (i = 0; i < length - 1; ++i) {
        new_data.get()[i] = data.get()[i];
      }
      new_data.get()[i] = elem;
      &data = &new_data;  // NOT ASSIGNABLE
    }
  }
};

int main() {
  SimpleVector v{51, 57, 15};
  std::cout << v[1] << std::endl;
  v.push_back(78);
  std::cout << v[0] << std::endl;
  std::cout << v[1] << std::endl;
  std::cout << v[2] << std::endl;
  std::cout << v[3] << std::endl;
}
&data = &new_data

&data is the address of the unique_pointer. You're creating a temporary variable, a pointer-to-a-unique-pointer.

&new_data is the address of the unique_pointer. You're creating a temporary variable, a pointer-to-a-unique-pointer.

You can't assign a value to a temporary. That's how C++ works. That code simply makes no sense.

It looks like you want the unique_ptr data to now point to the same thing that the unique_ptr new_data is pointing at? In which case &data, the address of the unique_ptr named data, is completely irrelevant.

If that is what you're trying to do, it's done like this:
data = std::move(new_data);

Topic archived. No new replies allowed.