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


Vector and Class Relationship Confusion

I posted the code here:

5/25/2020 4:23:21 PM


3 Answers

New Answer


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. 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.


Oh thanks @Hatsy Rei! :D


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