I have to admit my C++ is a bit rusty. In a project I try to create a vector of classes and use them. There is a problem because I want to identify each entry of the vector with a unique pointer to it for fast access but it does not work. Here is a minimal example of my problem:
#include <iostream>
#include <vector>
class Foo{
public:
Foo() { ptr = this; }
~Foo() {}
Foo * ptr;
};
int main()
{
std::vector<Foo> vec;
for(unsigned int i = 0; i < 2; ++i)
vec.push_back(Foo());
for(unsigned int i = 0; i < vec.size(); ++i)
std::cout << "Object Self-Pointer: " << std::hex << reinterpret_cast<unsigned int>(vec[i].ptr) << std::endl;
}
Actual output:
Object Self-Pointer: bfbebc18
Object Self-Pointer: bfbebc18
Intended output:
Object Self-Pointer: bfbebc18
Object Self-Pointer: bfbebc1c
(some pointers to the actual objects).
I hope you can help me with this issue, thank you in advance.
When you do this:
A new temporary
Fooobject is created, but each time it is created in the same address (because it is created on stack and the stack pointer is the same). So thethispointer, and therefore theptrmember of each of these instances is the same.When you add each instance to the vector, the default copy constructor is called, so the
ptrmember is copied, and therefore all instances in the vector have the same value.