Store address of objects...

Hi at all! I'm new on "game programming". And I might say that I am a newbie! I'm using the SDL library and trying to match the C++11 standards...
Anyway, I thought about a vector where I store all the addresses of game instances, so I can access them anytime...
I tried with this function:

1
2
3
4
5
6
7
int instance_new(std::vector<uintptr_t> &instance_id, unsigned &instance_size, Instance *pointer)
{
    instance_id[instance_size] = reinterpret_cast<std::uintptr_t>(pointer);
    instance_size++;
    instance_id.resize(instance_size);
    return 0;
}


Where "Instance" is the 'parent' class of various child classes like the player.
So, if I have to search the existing of a thing in my game, I should check if the address references to an instance of class. How can I do this?
Excuse my terrible english, and also my skills... And I'm am sure that I misunderstood something...
I am a beginner and I'm teaching myself...
Thanks in advance!
Last edited on
Just a little thing first: Rather than your manipulation of size that you have, why not simply use push_back to add the instance to the vector?
1
2
3
void instance_new(std::vector<std::uintptr_t>& instance_id, Instance* pointer) {
    instance_id.push_back(reinterpret_cast<std::uintptr_t>(pointer));
}


As for your question, just compare the pointer. If they are the same object, the pointers will be the same. Though, I don't see the need for storing them as uintprt_ts, rather than just Instance*s.

Apart from that, rather than doing some dodgy thing with casting pointers to and fro, why not use something like std::shared_ptr?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <memory>
#include <vector>

//...

// A vector to store instances in
std::vector<std::shared_ptr<Instance>> instances;

// Add an item with one of the following:
instances.push_back(std::make_shared<Instance>());
instances.push_bacK(std::shared_ptr<Instance>(new Instance));

// You can copy shared pointers, once all references to an object disappear
// it will be automatically deleted, and you can compare with a raw pointer using .get() 
Last edited on
Registered users can post here. Sign in or register to post.