如何在c++中修改const引用
How to modify a const reference in C++
我是c++的新手,我正在尝试修改一些现有的代码。我基本上必须修改c++中的const引用变量。有办法吗?
我想从常量字符串引用中删除子字符串。这显然行不通,因为id是一个常量引用。修改id的正确方法是什么?谢谢。
const std::string& id = some_reader->Key();
int start_index = id.find("something");
id.erase(start_index, 3);
创建字符串的副本并修改它,然后设置它(如果这是您需要的)。
std::string newid = some_reader->Key();
int start_index = newid.find("something");
newid.erase(start_index, 3);
some_reader->SetKey(newid); // if required and possible
除非你知道你在做什么,为什么要做,并且考虑了所有其他的选择,否则你应该避免其他的路线…在这种情况下,你根本就不需要问这个问题。
如果它是const,如果你试图改变它,你正在调用未定义行为。
下面的代码(使用char *代替std::string&-我不能显示std::string)的错误,以便使用const_cast编译并在运行时中断访问违反时写入地址…:
#include <iostream>
using namespace std;
const char * getStr() {
return "abc";
}
int main() {
char *str = const_cast<char *>(getStr());
str[0] = 'A';
cout << str << endl;
return 0;
}
所以坚持@Macke的解决方案,使用非const 复制。
相关文章:
- 具体来说,标准在哪里规定修改 const 对象是未定义的行为?
- C++ 为什么const X&可以通过功能进行修改?
- 修改C++中的"Const Char Pointers"
- 修改数据是否由 const shared_ptr&Ok 传递?
- const 方法使用引用修改对象
- 为什么 QObject::d isconnect(const QMetaObject::Connection &connection) 采用 const 参数并打算修改它?
- 有条件地传递修改后的副本而不是const原始副本变得丑陋
- 为什么当返回类型为 const 时可以修改返回值
- 为什么我可以在C 11中使用const函数修改类
- 是否允许在常量定义的对象上丢弃 const 只要它没有实际被修改?
- C++ 可以修改 const 对象的成员
- 修改 const 方法中的 pointee 值
- 临时修改const参数
- 使用引用修改Const对象
- 修改const形参引用
- 通过构造过程中获得的指针修改const对象
- 正在修改const声明对象上的可变对象的未定义行为
- 为什么我能够修改const变量通过类,而不是在纯代码.c++
- 标记所有不修改 const 的变量有什么缺点吗?
- 如何在c++中修改const引用