1

I have this vector of pointers to vector:

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

I want to initialize the first pointer to be a pointer to an empty vector. I tried this:

vec.push_back(nullptr);

Then I want to push_back some value to the vector where the nullptr points. I did this:

vec[0]->push_back(x);

Which I know is wrong, it ends up in segfault. I tried to do something with make_shared() instead of nullptr, but I still can't figure out how to achieve what I mentioned. Could anyone help me fix this example?

T.Poe
  • 1,949
  • 6
  • 28
  • 59

1 Answers1

7

If you want vec to contain one valid shared pointer to a vector, it's as simple as

vec.emplace_back(std::make_shared<std::vector<int>>());

Now there's pointer there, and it points at valid object. Making your subsequent sub-scripting and dereference valid themselves.

Just be sure you don't do it second. If you insert a nullptr first, and then a valid pointer, then it will be vec[1] that points at an object, not vec[0]. Your original attempt places an empty shared pointer at the start of the vector. And it doesn't go anywhere if you insert more elements after it.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Just to add to this, I had a question about `new` vs `make_shared` in this context. [This question](https://stackoverflow.com/questions/18301511/stdshared-ptr-initialization-make-sharedfoo-vs-shared-ptrtnew-foo#18301738) answered that. – Major Feb 26 '18 at 16:32