I have some std::vector and I have to resize it with some default value. Here is the code:
static int Counter = 0;
class Data
{
/* ... */
Data() {
Counter++;
std::cout << Counter << std::endl;
}
};
std::vector<Data> mArray;
for (int i=0; i <= 200; ++i)
{
mArray.push_back(Data());
}
// And resizing somewhere:
std::cout << "Resizing!\n";
mArray.resize(400, Data());
As I understand, after inserting 200 items, I can resize it with resize
function which takes new size and default value for each new element.
When I run that program I see:
0
1
2
...
199
200
Resizing
201
Why does only 1 item is inserted after resizing?
You're only seeing a count from your default constructor, when the entries being added are copy constructed. You'll have to add a copy constructor that counts copies as well:
Data(const Data& other) {
// Actual copying code, whatever that may be
Counter++;
std::cout << Counter << std::endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With