下面是一個重載賦值運算符的模板類的示例。鑑於此類:在模板類上覆蓋賦值運算符時出現奇怪的行爲
template<class Type>
class Attribute
{
public:
Type operator=(const Type rhs)
{
mData = rhs;
return mData;
}
private:
Type mData;
};
爲什麼下面的代碼沒有任何錯誤地編譯?
Attribute<std::string> str;
str = 0;
雖然看似矛盾,這樣的代碼:
std::string test;
test = 0;
產生以下錯誤?
error C2593: 'operator =' is ambiguous
首先,總是使用const引用重載賦值運算符,所以這應該是'Type operator =(const Type&rhs)' – legends2k
@ legends2k不是真的。通過價值允許您使用複製和交換成語來強有力的例外保證。此外,它爲編譯器提供了更多機會來消除不必要的副本,並在可用時自動調用移動構造函數(僅限C++ 11)。 – Tomek