C ++ code gets different results in g ++ and vs2008

#include <iostream> #include <string> #include <vector> using namespace std; struct Exmpl{ Exmpl() { cout << "Exmpl()" << endl; } Exmpl(const Exmpl&) { cout << "Exmpl(const Exmpl&)" << endl; } Exmpl& operator=(const Exmpl& rhs) { cout << "operator=Exmpl()" << endl; return *this; } ~Exmpl() { cout << "~Exmpl()" << endl; } }; void func1(Exmpl obj) { } void func2(Exmpl &obj) { } Exmpl func3() { Exmpl obj; return obj; } int main() { Exmpl eobj; func1(eobj); func2(eobj); eobj = func3(); Exmpl *p = new Exmpl; vector<Exmpl> evec(3); delete p; return 0; } 

when compiling in g ++ (4.4.3) I got

 Exmpl() Exmpl(const Exmpl&) ~Exmpl() Exmpl() operator=(const Exmpl&) ~Exmpl() Exmpl() Exmpl() Exmpl(const Exmpl&) Exmpl(const Exmpl&) Exmpl(const Exmpl&) ~Exmpl() ~Exmpl() ~Exmpl() ~Exmpl() ~Exmpl() ~Exmpl() 

and in vs2008 the result:

 Exmpl() Exmpl(const Exmpl&) ~Exmpl() Exmpl() Exmpl(const Exmpl&) ~Exmpl() operator=(const Exmpl&) ~Exmpl() Exmpl() Exmpl() Exmpl(const Exmpl&) Exmpl(const Exmpl&) Exmpl(const Exmpl&) ~Exmpl() ~Exmpl() ~Exmpl() ~Exmpl() ~Exmpl() ~Exmpl() 

when the code goes to "eobj = func3 ();" basically, the 5th and 6th lines in vs2008 results cannot be found in g ++. I tried to perform several levels of optimization, but the result is the same. what is the reason for the difference?

+4
source share
1 answer

C ++ allows copying constructors when an object is returned as a value from a function (as in func3() ). Even if the constructor has a side effect different from constructing a new object, in this case the copy constructor is written to cout .

g++ does this even without the specified optimization, while MSVC will only do this if you ask the optimization to run.

If you reduce the program to the following (just to cut the output to interesting parts):

 int main() { Exmpl eobj; eobj = func3(); return 0; } 

You will see the following for programs generated on these command lines (tests performed using MinGW 4.6.1 and MSVC 16.0, otherwise called VC ++ 2010):

  • g++ -O0 -o test.exe test.cpp (g ++, 'no' optimizations)
  • g++ -O2 -o test.exe test.cpp (g ++, optimization)
  • cl /Ox /EHsc test.cpp (msvc, optimziations)

     Exmpl() Exmpl() operator=Exmpl() ~Exmpl() ~Exmpl() 
  • cl /EHsc test.cpp (msvc, no optimization)

  • g++ -fno-elide-constructors -o test.exe test.cpp (g ++ without any constructors, as suggested by Jesse Good)

     Exmpl() Exmpl() Exmpl(const Exmpl&) ~Exmpl() operator=Exmpl() ~Exmpl() ~Exmpl() 
+8
source

Source: https://habr.com/ru/post/1411041/


All Articles