【问题标题】:Mutability testing for function return values函数返回值的可变性测试
【发布时间】:2014-10-08 04:51:49
【问题描述】:

我没有让别人做作业的习惯,但我一直有任务

“构造一个小程序,说明返回原始类型值的函数返回不可变的右值,而返回类类型值(例如,字符串)的函数返回(可变)右值。”

有人可以对此提供一些提示吗?有没有办法测试可变性,以及如何修改右值?

【问题讨论】:

  • 想一想可以修改 (a) 基本类型和 (b) 类类型的方法。然后编写一个程序,尝试对函数调用的结果执行此操作。

标签: c++ immutability mutable


【解决方案1】:

请记住,obj += 42;obj.operator+=(42); 的简写。可以在右值上调用成员函数(C++11 & 限定的左值函数除外)。

我会使用“modifiable”和“unmodifiable”术语,而不是“mutable”和“immutable" 可能与 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2020-04-23
    • 2016-12-26
    • 1970-01-01
    相关资源
    最近更新 更多