0

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;
}
2
  • Here is your answer stackoverflow.com/questions/817263/… you need to use new Commented Apr 26, 2016 at 14:29
  • The correct use of pointers in a vector is to have a vector of smart pointers, the kind that handle deallocation of the target's memory. Commented Apr 26, 2016 at 14:51

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Can I ask one more question? delete a1 will release the memory of the object in the second way, but it looks like in the first way memory will not be released. So does this mean we should use the second way? @NPE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.