H'H
H'H

Reputation: 1678

pass unigue_ptr as shared_ptr into a vector

Here is a test to understand more about shared_ptr and unique_ptr:

#include <string>
#include <memory>
#include <vector>

std::vector<std::shared_ptr<int> > vec_ptr;

int* get()
  {
  for (size_t i = 0; i < 1; ++i)
    {
    vec_ptr.push_back(std::make_unique<int>());
    }
  return vec_ptr.back().get();
  }
int main()
  {
  int obj = 5;
  int* ptr = get();
  ptr = &obj;

  std::cout << *ptr << std::endl;
  std::cout << *vec_ptr[0].get() << std::endl; //expect: 5, but it is 0
  }

Apparently nothing is assigned to the vec_ptr. Could someone please explain it to me?

Upvotes: 0

Views: 45

Answers (2)

petersohn
petersohn

Reputation: 11720

Here is what you have in this program:

  • vec_ptr contains 3 elements, each of them is 0.
  • obj, with a value of 5.
  • ptr, which points to obj.

So the program prints the correct values of 5 and 0. If you want to change the value of one of the pointers, then you should assign it like this:

*ptr = obj;

Then, ptr will point to the last element of vec_ptr (as returned by get()), which will have the value of 5. However, your last line will still print 0, because that prints the first element of the vector, not the last.

Upvotes: 2

It seems you wanted to do:

*ptr = obj;

instead of

ptr = &obj;

The former copies the integer obj into the space pointed to by ptr. The latter (which you're doing) re-points ptr to point at obj.

Upvotes: 2

Related Questions