I'm working on the following code snippet:
#include <iostream>
#include <vector>
class myclass
{
public:
myclass()
{
std::cout << this << std::endl;
}
};
int main()
{
std::vector<myclass> v;
for(uint32_t i = 0; i < 10; i++)
v.push_back(myclass());
return 0;
}
I'm compiling the code using g++ main.cpp
. When I execute the compiled binary, I get:
0x7ffebb8f8cab
0x7ffebb8f8cab
0x7ffebb8f8cab
0x7ffebb8f8cab
0x7ffebb8f8cab
0x7ffebb8f8cab
0x7ffebb8f8cab
0x7ffebb8f8cab
0x7ffebb8f8cab
0x7ffebb8f8cab
My question is why are all the this
pointers identical? If I'm creating 10 different objects of the same class, there should be 10 distinct this
pointers. Right?
As far as I understand, my code is currently using the references of the same objects to populate the vector v
. However, what I want are 10 distinct objects of myclass
. How can I get this? This code is a part of a larger project and that project has some issues with new
and delete
. So I cannot use that API. What am I doing wrong and how can I fix this?
emplace_back
. Or add logging move & copy constructors. Currently you're printing out the default constructor of a temporary, which is then moved (without logging). – Godricmyclass()
makes a temporary that exists only long enough for it to be copied intov
. This allows the system to keep reusing that space in storage over and over. – Illiniumv
you will see different addresses: godbolt.org/z/1Enn9zMnP Also added a copy constructor so you could get a better look at everything that's going on, including the vector resizes. – Illiniumemplace_back
worked. Just to be sure, the problem was thatpush_back
was using the default copy constructor of the class. Since the object that was being copied was getting destroyed in every iteration of the loop, the next time it was allocated, it was getting allocated at the same address resulting in identical values of thethis
pointer. Am I correct? – Goldypush_back
has to make a copy (because it takes its parameter by value). This is whyemplace_back
was invented - it's more efficient. – Mipush_back
does not take in its parameter by value, but rather by const reference. But yes, it does make a copy of the parameter when inserting into the vector. – Rauthis
. – Reticulationemplace_back
constructs an object in place, passing the parameters passed in (if any) on to the constructor. A bit of simple template magic + placementnew
, I've had to code it myself. – Mithis
unless you have a constructed object. – Vinegarettepush_back
gets an r-value reference and moves. Which doesn’t make a difference for this class, but still. – Okhotsk