+ 4
I have a question about vector (read description)
https://code.sololearn.com/cr4M6UTF0pG5/?ref=app 1. what happens at line 15?(working) 2. why the destructor will be executed before line 16?
12 Antworten
+ 3
@AJbura @Xan I hoped that my previous comment will push you in a right direction. Unfortunately, not. So, here is direct answer on your question:
https://code.sololearn.com/c8qIYdrgN3qF/?ref=app
+ 3
Xan but i don't understand why vector <A> v(5, 6);
create object. cause constructor is execute whenever the object is created.
+ 3
now i got it thanks Nevfy
+ 3
it's work like vector go for the class and (ctor) create elements came back (dtor). And when the program or main return 0; the all vector data obj was destroyed and for all detor is executed.
+ 3
When you create a Vector of Class transmitting some parameters to the constructor, it works like that: one exemplar of Class is created and then Vector is filled by copying this exemplar, after that this exemplar is destroyed. It is like that even if you create a Vector of one element.
However, if you create a Vector of Class without transmitting any parameters to the constructor, this constructor will be called as many times as the number of elements in your Vector. Check this out here:
https://code.sololearn.com/cR3607a73eNF/?ref=app
And compare it with the previous case:
https://code.sololearn.com/c8qIYdrgN3qF/?ref=app
+ 2
I added some debug code:
https://code.sololearn.com/cmo1Oelca9de/#cpp
The output was:
Constructor start: cnt = 0
Destructor start: cnt = 0
Destructor end: cnt = 1
In Main: cnt = 1
Destructor start: cnt = 1
Destructor end: cnt = 2
Destructor start: cnt = 2
Destructor end: cnt = 3
Destructor start: cnt = 3
Destructor end: cnt = 4
Destructor start: cnt = 4
Destructor end: cnt = 5
Destructor start: cnt = 5
Destructor end: cnt = 6
+ 2
it's help me. try to change the value (5,6) with (1, 6).
the destructor execution depend on first element , but why don't know.
+ 2
we have
vector <A> v(5, 1);
so, what is 5 & 1
+ 1
In my understanding, that's how vector works. If you make the same counter for constructor, you will see that it is also called only once, however several elements were created.
0
Yes, I'm confused too.
I thought more debugging output would help you :-)
0
AJbura Great work ☺
0
5 is x-axis and y