函数返回值的可变性测试

时间:2014-10-08 04:51:49

标签: c++ immutability mutable

我不习惯让别人做我的作业,但我的任务是

"构造一个小程序,说明返回基本类型值的函数返回不可变rvalue,而返回类类型值的函数(例如,字符串)返回(可变)rvalue。"

有人可以给出一些暗示吗?有没有办法测试可变性,你如何修改右值?

1 个答案:

答案 0 :(得分:0)

请注意obj += 42;obj.operator+=(42);的简写。可以在rvalues上调用成员函数(C ++ 11 &除外 - l值的限定函数)。

我会使用" 可修改的"和" 不可修改的"术语而不是" mutable "和" 不可变"可能会与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
}
相关问题