Constructors/destructors/STL question

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#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:
    static int m_copy_ctor_calls;
    static int 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
Last edited on
I've tried codepad online and personally I would trust it no further than I could throw it. - I'm sure it's using some well outdated compiler.

But correct answer is probably
5 (copy constructors) and 3 (destructors).


{{EDIT:
Note actual final number of destructors will probably be 6 because the
vector will be destroyed when the main function finishes.}}
it is implementation-defined
On my tests, i get
5 and 3 from GNU gcc and Sun CC
3 and 1 from HP acc,
6 and 4 from IBM xlc
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
Last edited on
Topic archived. No new replies allowed.