首页 > 解决方案 > 通过右值修改对象值

问题描述

来自最新的 C++ ISO 标准 https://timsong-cpp.github.io/cppwp/expr#basic.lval-10

一个左值是可修改的,除非它的类型是 const 限定的或者是一个函数类型。[注意:试图通过不可修改的左值或右值修改对象的程序是非良构的

但是下面通过右值临时修改的代码运行良好。

https://godbolt.org/z/L9H06i

#include <iostream>
struct A
{
std::string s1;
 A():s1("123") {}
 A&& modify() { s1 = "123411111111111111111111111111111111111111111111111111111111111111111111"; 
  return std::move(*this);                                                  
   } //modifying temporary object through rvalue!
};

void f(A&& o)
{
   std::cout << o.s1.c_str();
}

int main()
{
   f(A().modify());//modifying temporary object through rvalue!
    return 0;
}

标签: c++rvaluetemporary

解决方案


推荐阅读