C++ constructor, compiler

Asked 2 years ago, Updated 2 years ago, 21 views

 #include <iostream> 
using namespace std; 
class Point { 
   private: 
   float X; float Y; 
   static int count; 
   public: 
   Point() {}; 
   Point(float a) : X(a), Y(a) { ++count; } 
   Point(const Point& a); 
   static void printCount() { 
      cout << "Count = " << count << endl; 
   } 
   void printValues() { cout << "(" << X << "," << Y << ")" << endl; } 
   friend Point operator+(const Point& a, const Point& b); 
}; 
Point operator+(const Point& a, const Point& b) { 
   Point temp; 
   temp.X = a.X + b.X; 
   temp.Y = a.Y + b.Y; 
   return temp; 
} 
Point::Point(const Point& a) { 
   X = a.X; Y = a.Y; 
   ++count; 
} 
int Point::count = 0; 
int main() { 
   Point myPoint(1.0); 
   Point yourPoint(2.0); 
   (myPoint + yourPoint).printValues(); 
   Point::printCount(); 
   return 0; 
}

Code to count the number of times a constructor is called.

In my opinion, when I create my point, when I create your point, when I return from operator+, So I think count = 3

In Codeblocks that use the gcc compiler, it is printed as number 2 In the visual studio, it says number 3. What's the difference between the two?

c++

2022-09-21 22:59

1 Answers

(myPoint + yourPoint).Isn't it because the return value optimization is applied differently in the printValues(); part?

Here is a similar experiment done by multiple compilers.


2022-09-21 22:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.