0

How I can access and print the value of unique_ptr, how to delete the 3rd value and accordingly reduce the container's value without making segmentation fault.

#include <memory>
#include <vector>
#include <iostream>

int main()
{
    std::vector<std::unique_ptr<int>> vec;

    for (int i = 0; i < 5; i++) {
        int x(i);
        std::unique_ptr<int> ptr2x(&x);
        vec.push_back(std::move(ptr2x)); 
    }
    
    for (int i = 0; i != vec.size(); i++) {
         std::cout << vec.at(i).get() << std::endl;
         /* How to print the data stored in the unique_ptr */

         if (i == 2) {
             /* I want to remove the 3rd element from the vec
                simultaneously, vec.size() should reduce to 4.
              */
         }
    }
      
    return 0;
}

The below is the output I got.

Moreover, why the address is same for all the 5 elements.

0x7fff6641258c
0x7fff6641258c
0x7fff6641258c
0x7fff6641258c
0x7fff6641258c
munmap_chunk(): invalid pointer

The solution for this problem can be found here.

Rose
  • 11
  • 6
  • You simply use `std::vector`'s `.erase` method. The value type doesn't matter. – user17732522 Jul 11 '22 at 11:06
  • `int x(i); std::unique_ptr ptr2x(&x);` That's undefined behavior. Create `std::unique_ptr`s only with `std::make_unique`: `auto ptr2x = std::make_unique(i);`. – user17732522 Jul 11 '22 at 11:08
  • One question per question please. – Some programmer dude Jul 11 '22 at 11:08
  • Looks like you don't understand how `unique_ptr` works, and what it is all about. Back up a little bit. Start with the basics of understanding why `unique_ptr` exists and what it's used for. Once you're up to speed on that, you should be able to figure out the rest of your answers yourself. Furthermore, a `unique_ptr` gets removed from a vector exactly the same way everything else gets removed from a vector. Using a `unique_ptr` does not change anything how a vector works in any fundamental way. – Sam Varshavchik Jul 11 '22 at 11:08

1 Answers1

-1

Every time the loop iterates you get a brand new variable x. Each iteration it goes out of scope and its life-time will end. Each and every pointer to x will be invalid.

Not to mention that you attempt to take over the ownership of x, but x isn't something you can own. You must create a brand new value and copy the value to it.

The simple solution is to skip the variable x and just create your copy of i directly:

vec.emplace_back(new int(i));
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    I was able to find a way to fix the issue and it worked. Here is the https://onlinegdb.com/CMv4y5plD3 – Rose Jul 11 '22 at 11:41