如何在c++中修改const引用

How to modify a const reference in C++

本文关键字:修改 const 引用 c++      更新时间:2023-10-16

我是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 复制