#include <iostream>
#include <vector>
class A
{
public:
A(int n) : m_n(n) { }
A(const A &a) : m_n(a.m_n) { ++m_copy_ctor_calls; }
~A() { ++m_dtor_calls; }
private:
int m_n;
public:
staticint m_copy_ctor_calls;
staticint m_dtor_calls;
};
int A::m_copy_ctor_calls = 0;
int A::m_dtor_calls = 0;
int main()
{
const A a = 2;
std::vector<A> v;
v.reserve(2);
v.push_back(a);
v.push_back(1);
v.push_back(a);
std::cout << A::m_copy_ctor_calls << " " << A::m_dtor_calls << std::endl;
return 0;
}
What is the outptut of the program?
Codepad.org gives me "64", but this is not accepted as the correct answer!! (this is the quiz question)
Can anybody give reference to an article describing what is generally happening at the moment of vector "reserve" call relating to objects construction/destruction?
javascript:editbox1.editSend()
Quiz question link: http://www.interqiew.com/ask?ta=tqcpp03&qn=5
OK let it be implementation-dedfined, but this doesn't make the things clearer for me:
1) There is definitely 2 destructors calls when memory is reallocated from 2 to 3 capacity. Why does this number vary? Why "3" (to guestgulkan)?
2) For me there is obviously 2 copy constructors calls when passing A-object by value, what are other calls?
What is the source for copying in these cases?
The minimum (what I got on HP-UX) is 3 and 1: each of push_back(a) is a copy constructor and push_back(1) is a constructor from int, copy constructor and destructor.
Now, if reserve doesn't over-allocate, then the third push_back causes reallocation, which adds 2 destructors and 2 copy constructors, which is likely what happens on the systems that print 5 and 3.
Finally, a particularly non-optimizing compiler (I actually forgot to turn on optimizations in my xlc test earlier) will call a constructor from int, a copy constructor, and a destructor on the line const A a = 2; -- that's where codepad.org gets 6 and 4