简体   繁体   中英

how to correctly use vector of pointers to objects of class

I wonder why the second part of the following code I wrote doesn't work. I am practicing vector of pointers to class objects. I tried two ways, one is to define a class object; the other is to define a pointer to the object. The second way failed.

#include <iostream>
#include <vector>

using namespace std;

class A{
    public:
        int id;
        A(int id):id(id){}
};

int main()
{
    vector<A*> A_vec, A_vec2;
    A a(5);
    A_vec.push_back(&a);
    cout << A_vec.size() << "; id " << A_vec[0]->id << endl;


    A *a1;
    a1->id = 5;
    A_vec2.push_back(a1);
    cout << A_vec2.size() << "; id " << A_vec2[0]->id << endl;
}

The second snippet doesn't work because you've never allocated memory for the object, so a1 points nowhere.

A *a1 =  new A(5);

...

// Once you're done with `a1', release the memory.
delete a1;

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