c++ - 通过右值修改对象值
问题描述
来自最新的 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;
}
解决方案
推荐阅读
- javascript - 无法在 Node 中接收我的机器的本地 IP 地址
- javascript - Vue中点击槽子组件时忽略父组件的发射
- ios - 使用 OCaml for ARM (android/ios) 作为 C 接口库
- javascript - 无法从 Javascript 函数返回输出
- android-studio - 无法创建 Vulkan 实例 - Android Studio、Windows 10
- reactjs - 在模板中进行更改后再次调用 ReactDOM.render() 时不起作用
- python - 移动到 Web Scraper 中具有相同名称的下一个类
- python - 在 python-fastApi 中间件中引发异常
- javascript - 在页面底部缩放图像后防止滚动条
- android - 第一次无法解决android gradle build的问题