constructor and destructor when initializing sized vector

J

jjleto

When I run this simple program:

#include <vector>
#include <iostream>
using namespace std;

class A {
public:
A() { cout << "[ctor]" << endl; }
~A() { cout << "[dtor]" << endl; }

};

int main()
{
vector<A> v(3);
return 0;
}

I've got the following result:

[ctor]
[dtor]
[dtor]
[dtor]
[dtor]

(gcc 3.3.4)

How to explain that ? Should not the constructor be called 3 times and
the destructor also ?

Thanks.
 
R

Ron Natalie

jjleto said:
When I run this simple program:

#include <vector>
#include <iostream>
using namespace std;

class A {
public:
A() { cout << "[ctor]" << endl; }
~A() { cout << "[dtor]" << endl; }
Add:
A(const A&) { cout << "[copy ctor]" << endl; }
A& operator=(const A&) { cout << "[op=]" <<endl; return *this; }
int main()
{
vector<A> v(3)

The constructor you are using above has a second defaulted argument
which is the value to fill the vector with. It is defaulted to a default
constructoed A object.

So you get:
ctor - default constructed object for second constructor parameter
copy ctor - v[0] being filled
copy ctor - v[1] being filled
copy ctor - v[2] being filled.
 
J

jjleto

Ron Natalie a écrit :
jjleto said:
When I run this simple program:

#include <vector>
#include <iostream>
using namespace std;

class A {
public:
A() { cout << "[ctor]" << endl; }
~A() { cout << "[dtor]" << endl; }

Add:
A(const A&) { cout << "[copy ctor]" << endl; }
A& operator=(const A&) { cout << "[op=]" <<endl; return *this; }
int main()
{
vector<A> v(3)


The constructor you are using above has a second defaulted argument
which is the value to fill the vector with. It is defaulted to a default
constructoed A object.

So you get:
ctor - default constructed object for second constructor parameter
copy ctor - v[0] being filled
copy ctor - v[1] being filled
copy ctor - v[2] being filled.

Thanks. It is clear now.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top