简体   繁体   中英

Filling up a vector of pointers

please excuse my noobie question..

I have :

class A;
{
    public:
    A(int i) : m_i(i) {}
    int m_i;
}

A newA(i);
{
    return A(i);
}

And I want to fill the following vector, but using a loop where an object A is created with a function (newA):

vector<A*> list;

for (int i=0 ; i<3; ++i) {  A a = newA(i);  list.push_back(&a); }

That works if I use a vector<A> but not with a vector<A*> since all I do is changing the value at &a and pushing 3 times the same pointer &a.

How can I do so that I create a new A every time, and not change the value of the same pointer.

I came up with the following but I hope it's not the only way, since it includes dynamic allocation..

A newA(i);
{
    return A(i);
}

vector<A*> list;

for (int i=0 ; i<3; ++i)
{
    A a = newA(i);
    list.push_back(new A(a));
}

Note that class A is actually huge in memory, hence the pointers.

You should realize the first method is bad:

 for (int i=0 ; i<3; ++i) {  A a = newA(i);  list.push_back(&a); }

You are creating a local object and then storing a pointer to it. Once you leave the loop the object will not exist anymore and you have undefined behavior. As john said there is no sensible way to do what you want to do without using dynamic allocation. As Billy noted instead of using a raw pointer you can use a shared_ptr or unique_ptr and then you don't have to worry about memory management which is possibly why you want to avoid dynamic allocation.

Storing a vector of pointers does not give the vector ownership of the resulting instances of A . There is going to be dynamic allocation involved in order to populate such a structure.

(Of course, in real code you should probably create a vector<unique_ptr<T>> or a vector<shared_ptr<T>> instead of a vector<T*> but that's another topic)

这是唯一的方法,因为在第一个示例中,存储指针所指向的对象会在for循环的每次迭代中立即消失,因为它超出了范围。

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