2011-04-08 81 views
0

我有一個類定義如下:C++隱含的拷貝構造函數和賦值操作符

#include <iostream> 

using namespace std; 

class Point 
{ 
    int x, y; 

public: 

    Point(int a, int b) : x(a), y(b) 
    { 
     std::cout << "Constructing point (" << a << ", " << b << ") " 
       << std::endl; 
    } 

    Point(const Point& p) : x(p.x), y(p.y) 
    { 
     std::cout << "In copy constructor " << p.x << " " << p.y 
       << std::endl; 
    } 

    Point& operator=(const Point& p) 
    { 
     std::cout << "In assignment operator " << p.x << " " << p.y 
       << std::endl; 
     x = p.x; 
     y = p.y; 
     return *this; 
    } 
}; 

int main() 
{ 
    Point p1 = Point(1, 2); 

    return 0; 
} 

現在,當我執行此我看到的是Constructing point (1, 2)。我假設編譯器在這裏做一些優化。從理論上來說,臨時構造是否正確,然後調用賦值運算符來初始化p1?

回答

2

不,在像這樣的聲明中,=操作符實際上仍然意味着調用構造函數,編譯器可能會將任何可能的拷貝構造作爲優化消除。聲明中的=永遠不會導致調用任務。因此理論上可以創建臨時文件並將其複製到p1中。

+0

確定這是有道理的 - 我想'點P2 = P1;',它被稱爲拷貝構造函數爲好,所以我沒有完全脫離標準,歡呼! – 2011-04-08 04:33:44

1

如果你想看到運營商爲被叫,你必須寫這樣的代碼:

Point p1(5, 5); 
Point p2(0, 0); //You don't have a default constructor. 

p2 = p1; // Now operator = is called.