2014-10-08 57 views
2

我不是讓習慣別人做我的功課,但我一直在負責爲函數的返回可變性測試值

「建設一個小程序,說明在返回原始類型值的函數返回不可變的右值,而返回類類型值(例如,字符串)的函數返回(可變)右值。「

有人可以提供一些關於這方面的提示嗎?有沒有辦法測試可變性,以及如何修改右值?

+1

想想你可以修改(a)原始類型和(b)類類型的方式。然後編寫一個程序,試圖對函數調用的結果做到這一點。 – 2014-10-08 04:54:12

回答

0

請記住,obj += 42;obj.operator+=(42);的簡寫。可以在rvalues上調用成員函數(除了用於I值的C++ 11 &限定函數外)。

我會使用「修改」和「不可修改」術語,而不是「可變」和「不可改變」可以與mutable關鍵字相混淆。

// 3.10/p1 - A prvalue ("pure" rvalue) is an rvalue that is not an xvalue. [ Example: The result of calling a function 
// whose return type is not a reference is a prvalue. The value of a literal such as 12, 7.3e5, or true is 
// also a prvalue. — end example ] 

struct obj { 
    obj() : value(0) {} 
    obj& operator+=(int val) { 
     value = val; // Can modify the value representation 
     return *this; 
    } 
    int value; 
}; 

int returnPrimitive() { 
    return 42; 
} 

obj returnObject() { 
    return obj(); 
} 

int main() 
{ 
    returnPrimitive() += 42; // error: rvalue expression is not assignable 
    returnObject() += 42; // member functions can be called on rvalues 
}