简体   繁体   中英

Why can I not push_back a element into a vector pointer?

My code is the following:

#include <vector>

int main() {
    std::vector<int> *vec;
    vec->push_back(1);
    return 0;
}

This program segfaults, no matter which compiler I try it with. I also tried using a smart pointer, but it also segfaults. I now have two questions:

  • Why and how can I solve this?
  • Does having a pointer to a vector (specifically a smart pointer) even make sense? In my online searches, I only saw it the other way around, a vector of unique_ptr 's. Which makes more sense and why?

Pointers are trivial objects, so the result of default-initializing one is that its value is indeterminant. Since that's what you did, your pointer doesn't point to anything. That means trying to access the thing it points to results in undefined behavior.

You need to create an object for your pointer to point to. For instance, you could dynamically-allocate a new std::vector<int> :

std::vector<int>* vec = new std::vector<int>;
vec->push_back(1); // fine
delete vec; // dynamically-allocated, so you have to delete it when you're done with it

There's basically no reason to do that though. A std::vector is already essentially just a pointer to a dynamically-allocated array plus a little bit of extra metadata to store the size of the array. There are very few legitimate reasons to dynamically-allocate a std::vector instead of just declaring it locally (or as a data member of some class, etc):

std::vector<int> vec;
vec.push_back(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM