Vector and Class Relationship Confusion | SoloLearn: Learn to code for FREE!

+1

Vector and Class Relationship Confusion

I posted the code here: https://www.sololearn.com/post/419897/?ref=app

5/25/2020 4:23:21 PM

CeePlusPlus

3 Answers

New Answer

+7

If you look at std::vector constructor definitions, the fill constructor, vector(n, val): "... Constructs a container with n elements. Each element is a *copy* of val." What vector<A> v(5,1) does, is create a vector of 5 elements of type class A, each initialized using the value 1. http://www.cplusplus.com/reference/vector/vector/vector/ In this case, it appears that the fill constructor initializes one instance of class A, and makes 5 copies of the same object which fills the vector. Hence, the destructor was called once for that object, incrementing A::cnt by 1. Interesting! Consider the example of not using the fill constructor: vector<A> v = {A(1), A(1), A(1), A(1), A(1)}; In this case, 5 distinct temporary objects were created, and the destructor will be called five times in total, resulting in the value of A::cnt being 5. https://code.sololearn.com/c9oyM2cdqrS1/?ref=app

+2

Oh thanks @Hatsy Rei! :D

+1

Is it because the class is called once by initiating vector<A>?