problem with vector

Feb 18, 2012 at 11:27am
Hi all
i am trying following code

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
class myc
{
	static int i;
public:
	myc()
	{
		cout<<++i<<" ctor \n";
	}
	~myc()
	{
		cout<<--i<<" dtor \n";
	}
};

int myc::i = 0;

int main()
{
	{
		vector<myc> vec(5);
	}
	return 0;
}



output
on vs 2010

1 ctor
0 dtor
1 ctor
0 dtor
1 ctor
0 dtor
1 ctor
0 dtor
1 ctor
0 dtor
-1 dtor
-2 dtor
-3 dtor
-4 dtor
-5 dtor
Press any key to continue . . .

on rhel linux

1 base ctor
0 base dtor
-1 base dtor
-2 base dtor
-3 base dtor
-4 base dtor
-5 base dtor

why distructor went up to -5 , (when i have pointer in my class which get deleted in distructor my code fails.)

i think it should create 5 objects of myc & destroy them at end.

thanks in advance.
Feb 18, 2012 at 11:38am
You need to add counters to the copy constructor.
Last edited on Feb 18, 2012 at 11:39am
Feb 19, 2012 at 8:37am
ok here is output after adding copy construcor

1 ctor
2 copy ctor
3 copy ctor
4 copy ctor
5 copy ctor
6 copy ctor
5 dtor
4 dtor
3 dtor
2 dtor
1 dtor
0 dtor

Press any key to continue.

but why copy constructor i think as i am creating 5 objects in vector there should be 5 constructor and 5 distructor
Feb 19, 2012 at 10:46am
http://www.cplusplus.com/reference/stl/vector/vector/

explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );
Repetitive sequence constructor: Initializes the vector with its content set to a repetition, n times, of copies of value.


One temporary constructed and bound to value. 5 copies constructed in the vector.

Last edited on Feb 19, 2012 at 10:47am
Feb 19, 2012 at 3:03pm
http://en.cppreference.com/w/cpp/container/vector/vector
explicit vector( size_type count ); //C++11
constructs the container with count value-initialized (default constructed, for classes) instances of T. No copies are made.
Feb 20, 2012 at 5:46am
as per statement

explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );
Repetitive sequence constructor: Initializes the vector with its content set to a repetition, n times, of copies of value.

the output of rhel linux is correct construct one object and made 5 copies.

but what about vs 2010 ? i think it use c++ 11

Feb 20, 2012 at 12:57pm
VS Release build will produce a more reasonable log.
Feb 22, 2012 at 5:33am
Topic archived. No new replies allowed.