Question

I'm rather new to c++. I have been programming Java for quite some time so i apologize in advance if i use some java terminology instead of the proper c++ terminology.

I want to create a hash map(unordered_map) which maps int to pointers to a class. Now the trouble for me is to create "new" instances of the class at different addresses.

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <tr1/unordered_map>
using namespace std;

class paul{
    public:
        paul(int n) {stuff = n;}
        int stuff;
};

int main(void) {
    tr1::unordered_map<int,paul*> glenn;

    for(int i = 0; i < 5; i++){
        paul victor(i*i);
        glenn[i] = &victor;
    }

    for(int i = 0; i < 5; i++){
        cout << i*i << "," << (*glenn[i]).stuff << "\n";
    }

    return EXIT_SUCCESS;
}

The code above does not work. It produces the output:

0,16
1,16
4,16
9,16
16,16

This is due to the fact that each new instance of paul gets created at the same address and thus every key in glenn will map to the same instance of paul.

So my question is now this how can i create several instances of a class at different addresses?

Was it helpful?

Solution

So my question is now this how can i create several instances of a class at different addresses?

Forget about addresses and pointers, and store objects:

tr1::unordered_map<int, paul> glenn;

for(int i = 0; i < 5; i++){
    glenn[i] = paul(i*i);
}

OTHER TIPS

If you really want to store pointers in your map, allocate them on the heap to extend their lifetime and prefer to use smart pointers such as std::unique_ptr or std::shared_ptr (these smart pointers require the use of C++11 or higher).

The heap allocation will store each newly created object at a different address in memory on the heap. The smart pointers will clean up the objects when they're lifetime is up (a primitive form of garbage collection).

int main(void) {
    tr1::unordered_map<int,std::unique_ptr<paul>> glenn;

    for(int i = 0; i < 5; i++){
        glenn[i].reset(new paul(i*i)); // prefer to use std::make_unique if/when it is available.
    }

    for(int i = 0; i < 5; i++){
        cout << i*i << "," << (*glenn[i]).stuff << "\n";
    }

    return EXIT_SUCCESS;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top