+4

Why is the answer to this question 1?

https://www.sololearn.com/post/173148/?ref=app

11/10/2019 11:51:16 AM

Sonic

5 Answers

New Answer

+6

You can probably see it a bit more clearly if we mark A(int) as explicit. In which case std::vector<A> v( 5, 1 ); is illegal and becomes std::vector<A> v( 5, A( 1 ) ); ( the copy constructor is called for the rest ) As you can probably see, you're creating a temporary variable. It gets destructed immediately after the call, which results in 'cnt' getting incremented once in the destructor.

+8

Thanks ~ swim ~ . Incrementing A::cnt by 5 at the time of termination of the program due to the destruction of the 5 object elements was obvious to me. It was the creation and destruction of the temporary object that was not obvious to me.

+4

Sonic At the place you are printing the value, A::cnt will be one as Dennis has already explained. But the final count will be 6 at the time of termination of the program, you can check like this int main()try { vector<A> v(5, 1); cout << A::cnt << '\n'; throw 1; } catch(...) { cout << A::cnt << '\n'; }

+1

Yep. Imma dumb haha just figured that out hah

+1

Because there is a destructor that increments it