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.