bart.z33
bart.z33

Reputation: 149

Unwanted creation of object at same memory address

I haven't been working with C++ for a long time and now I need to do some small "project".
I reviewed few topics trying to find solution for my problem with no results...

Here is "pseudo-code" (Pair is my class):

Pair** pairs;

I get size of table from input and create table of pointers:

pairs = new Pair*[size];

I have a loop which creates some object and puts it's reference into table of pointers. More or less:

while (...)
{
    Pair pair(...); // calling constructor, creating object type of Pair.
    pairs[i] = &pair;
    i++;
}

The problem is that &pair is the same number everytime (every step of loop). Let's say the address of first created object is 1234. So with every step in loop it overrides this object at 1234. So each pointer in pairs points to the same address -> same object. I would like to force creating this object at new place in memory.

I've been trying to put those objects into other table and then pass their reference to table of pointers:

Pair* clearPairs = new Pair[size];
while (...)
{
    clearPairs[i] = Pair(...);
    pairs[i] = &clearPairs[i];
    i++;
}

But problem still occurs.

Any tips?, mistakes/errors in my code (or thinking)? Shall I implement some "copying constructor"?

Upvotes: 1

Views: 956

Answers (1)

Ed Swangren
Ed Swangren

Reputation: 124652

while (...)
{
    Pair pair(...); // calling constructor, creating object type of Pair.
    pairs[i] = &pair;
    i++;
}

pair is allocated with automatic storage duration and goes out of scope upon each iteration of the loop. You are saving a pointer to an invalid object (a bunch of them).

You should use a collection of smart pointers if you really need pointers (this is true when objects cannot be copied or copies are expensive), which may not be necessary at all. Try this instead:

vector<Pair> pairs;
// and if you need pointers...
vector<unique_ptr<Pair>> pairs;

while(whatever) {
    pairs.push_back(Pair(...));
    // or...
    pairs.push_back(unique_ptr<Pair>(new Pair(...)));
}

Upvotes: 4

Related Questions