指针向量中的for_each指针

cpp*_*cpp 1 c++ pointers stl

我想在for_each()函数中初始化一个指针向量:

#include <stdlib.h>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

class Cow{
        public:
                Cow(){ _age = rand()% 20; }
                int get_age() { return _age;}
        private:
                int _age;
};

void add_new(Cow* cowp)
{
        cowp = new Cow;
}

int main()
{
        srand(time(NULL));
        const int herd_size=10;
        vector<Cow*> herd(herd_size);
        for_each(herd.begin(), herd.end(),add_new);
        cout << "Age: " << herd[0]->get_age() << endl; // line 27
}
Run Code Online (Sandbox Code Playgroud)

但是,我在第27行得到了运行时"分段错误"错误.牧群向量似乎未被启用.为什么?

Ben*_*ley 8

您的函数按值获取指针,然后重新分配这些副本.您需要通过引用将它们引入以影响向量中的指针.

void add_new(Cow *& cowp) 
Run Code Online (Sandbox Code Playgroud)