如何修改 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 copy.