bcsta
bcsta

Reputation: 2307

c++ how to create a pointer that will last even when object is overwritten?

I am creating a std::map of type <int, Foo*>. I am populating this map in a for loop with the emplace function. In this loop I am creating a Foo object Foo f = Foo() with every loop iteration and inserting this to map like so:

std::map<int, Foo*> mymap;
for(int i = 0 ; i < 4; i ++)
{
    Foo f = Foo();
    mymap.emplace(i, &f);
    mymap[i]->a.pushback(pow(i,2));
}

where a is a vector<int> in class Foo The problem is very clear. I am inserting a reference to f in mymap while on the next iteration I am recreating f, making the previous pointer to f obsolete. how can I resolve this while still keeping a pointer to f in mymap rather than storing a copy of f? are smart pointer a solution? (i never used them before).

Upvotes: 0

Views: 74

Answers (2)

Jarod42
Jarod42

Reputation: 217255

You probably simply want:

std::map<int, Foo> mymap;
for(int i = 0 ; i < 4; i ++)
{
    //mymap.emplace(i, Foo()); // operator[] would do similar anyway
    mymap[i].a.pushback(pow(i, 2));
}

or, if really you want pointer semantic

std::map<int, std::unique_ptr<Foo>> mymap;
for(int i = 0 ; i < 4; i ++)
{
    mymap.emplace(i, std::make_unique<Foo>());
    mymap[i]->a.pushback(pow(i,2));
}

And if you really want raw owning pointer:

std::map<int, Foo*> mymap;
for(int i = 0 ; i < 4; i ++)
{
    mymap.emplace(i, new Foo()); // calling delete later is required to avoid leak
    mymap[i]->a.pushback(pow(i,2));
}

Upvotes: 2

Lukas-T
Lukas-T

Reputation: 11340

Use new.

mymap.emplace(i, new Foo());

See here for more information about the new-oeprator.

Upvotes: 4

Related Questions