#include <iostream> #include <vector> using namespace std; class ClassA{ public: ClassA(){cout << "+" << endl;} }; int main(){ vector<ClassA> vectorOfObjectsA; vectorOfObjectsA.resize(2); return 0; } 

result of work in different versions of the compiler:

 sh-4.4$ g++ -std=c++17 -o main *.cpp sh-4.4$ main + + sh-4.4$ g++ -std=c++14 -o main *.cpp sh-4.4$ main + + sh-4.4$ g++ -std=c++11 -o main *.cpp sh-4.4$ main + + sh-4.4$ g++ -std=c++0x -o main *.cpp sh-4.4$ main + + sh-4.4$ g++ -std=c++03 -o main *.cpp sh-4.4$ main + sh-4.4$ g++ -std=c++98 -o main *.cpp sh-4.4$ main + sh-4.4$ 

The code was launched on the site: https://www.tutorialspoint.com/online_cpp_compiler.php

  • because they are different compilers - AR Hovsepyan
  • And what exactly is the difference? Why do different compilers react differently to code? - Taras Viyatyk pm
  • They do not react differently, they simply have different opportunities. Read answer from VTT user - AR Hovsepyan
  • Why in old versions the compiler did not call the class constructor when increasing the size of the vector? - Taras Viyatyk

1 answer 1

Because different standards have different overloads for this function. Prior to C ++ 11, resize took as input the element to be inserted as an optional parameter and copied it n times:

 void resize( size_type count, T value = T() ); // один вызов конструктора по-умолчанию 

But starting with C ++ 11, another overload will be called, creating up to n objects by calling the default constructor:

 void resize( size_type count ); 
  • that is, in old versions of compilers, when calling the resize() function, the second element of the vector was a copy of the first element, and in new versions, the default element was simply called for the second element? - Taras Viyatyk
  • 2
    It would be more appropriate to quote the resize specification, which has changed in exactly the same way. The vector constructor in the code from the question is different. - AnT
  • I agree, quotes or at least an exact reference to the standard in the answer is very lacking ... - Fat-Zer
  • @Taras Viyatyk, in new versions the displacement constructor is more likely to be called - AR Hovsepyan
  • @TarasViyatyk In the old version, an object was first created - a function parameter, then a copy constructor was called for the first and second elements. - VTT