2015-06-20 121 views
-1

Triny從網絡測驗,看到這段代碼。打印結果爲02當調用複製構造函數或賦值構造函數時?

這意味着默認複製構造函數用於列表初始化,而賦值構造函數用於矢量。爲什麼?

#include <algorithm> 
#include <iostream> 
#include <list> 
#include <vector> 

class Int 
{ 
public: 
    Int(int i = 0) : m_i(i) { } 

public: 
    bool operator<(const Int& a) const { return this->m_i < a.m_i; } 

    Int& operator=(const Int &a) 
    { 
     this->m_i = a.m_i; 
     ++m_assignments; 
     return *this; 
    } 

    static int get_assignments() { return m_assignments; } 

private: 
    int m_i; 
    static int m_assignments; 
}; 

int Int::m_assignments = 0; 

int main() 
{ 
    std::list<Int> l({ Int(3), Int(1) }); 
    l.sort(); 
    std::cout << (Int::get_assignments() > 0 ? 1 : 0); 

    std::vector<Int> v({ Int(2), Int() }); 
    std::sort(v.begin(), v.end()); 
    std::cout << (Int::get_assignments() > 0 ? 2 : 0) << std::endl; 

    return 0; 
} 

回答

1

這意味着默認的拷貝構造函數用於列表初始化而分配的構造函數用於向量

如果去掉std::sort(v.begin(), v.end());指令程序打印00。賦值運算符僅用於排序。

注意:該列表可以簡單地通過修改指針排序(因此l.sort()不需要operator=)。