C++ 생성자, 컴파일러
조회수 1934회
#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;
}
생성자를 호출하는 갯수를 카운트 하는 코드입니다
제 생각에는 myPoint생성할때 한번 yourPoint생성할때 한번, operator+에서 리턴할때 한번 그래서 count = 3이 되어야 한다고 생각하는데,
gcc컴파일러를 쓰는 Codeblocks에서는 2번으로 출력되고 visual studio 에서는 3번이라고 출력되더군요.. 둘중에 어떤차이인가요..?
-
(•́ ✖ •̀)
알 수 없는 사용자 - 〉
1 답변
-
(myPoint + yourPoint).printValues();
부분에서 Return value optimization이 다르게 적용되서 그런것 아닐까요?여기에 비슷한 실험을 여러 컴파일러에서 한 결과가 있으니 참고해 보세요.
댓글 입력