Why is the answer to this question 1? | SoloLearn: Learn to code for FREE!


Why is the answer to this question 1?


11/10/2019 11:51:16 AM


5 Answers

New Answer


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.


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.


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'; }


Yep. Imma dumb haha just figured that out hah


Because there is a destructor that increments it