+ 1

Vector and Class Relationship Confusion

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

25th May 2020, 4:23 PM
CeePlusPlus
CeePlusPlus - avatar
3 ответов
+ 9
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
25th May 2020, 4:28 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Oh thanks @Hatsy Rei! :D
26th May 2020, 1:45 PM
CeePlusPlus
CeePlusPlus - avatar
+ 1
Is it because the class is called once by initiating vector<A>?
25th May 2020, 4:24 PM
CeePlusPlus
CeePlusPlus - avatar