简体   繁体   English

为什么我不能将元素 push_back 到向量指针中?

[英]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?有一个指向vector的指针(特别是智能指针)是否有意义? In my online searches, I only saw it the other way around, a vector of unique_ptr 's.在我的在线搜索中,我只看到了相反的方向,一个unique_ptrvector 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.您需要创建一个 object 供您的指针指向。 For instance, you could dynamically-allocate a new std::vector<int> :例如,您可以动态分配一个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. std::vector本质上已经只是一个指向动态分配数组的指针,外加一点额外的元数据来存储数组的大小。 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而不是仅在本地声明它(或作为某些 class 等的数据成员)的正当理由很少:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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