如何在C++; 我是C++的新手,我正在修改一些现有代码。我基本上必须修改C++中的一个const引用变量。有没有办法做到这一点

如何在C++; 我是C++的新手,我正在修改一些现有代码。我基本上必须修改C++中的一个const引用变量。有没有办法做到这一点,c++,constants,C++,Constants,我想从常量字符串引用中删除子字符串。这显然行不通,因为id是一个常量引用。修改id的正确方法是什么?谢谢 const std::string& id = some_reader->Key(); int start_index = id.find("something"); id.erase(start_index, 3); 创建字符串的副本并修改它,然后将其设置回原来的位置(如果需要的话) 除非你知道你在做什么,为什么要这样做,并且考虑了所有其他的选择,否则应该避免其他的路线。。

我想从常量字符串引用中删除子字符串。这显然行不通,因为id是一个常量引用。修改id的正确方法是什么?谢谢

const std::string& id = some_reader->Key();
int start_index = id.find("something");
id.erase(start_index, 3);

创建字符串的副本并修改它,然后将其设置回原来的位置(如果需要的话)


除非你知道你在做什么,为什么要这样做,并且考虑了所有其他的选择,否则应该避免其他的路线。。。在这种情况下,您根本不需要首先问这个问题。

如果它是const,并且如果您试图更改它,那么您正在调用未定义的行为

为了使用const_cast,以下代码(使用char*而不是std::string&-我无法显示std::string的错误)在运行时编译并中断,在地址写入时会出现访问冲突…:

#包括
使用名称空间std;
常量字符*getStr(){
返回“abc”;
}
int main(){
char*str=const_cast(getStr());
str[0]=“A”;

cout
const\u cast(id).擦除(开始索引,3)
。我会让其他人告诉你为什么这是一个坏主意。删除
const
修饰符。你正在编程的API显然不希望你修改返回值;你确定你需要这样做吗?@BenjaminBannier是的,这是真的,有点麻烦。但这是我能做的最快的方法,而且是为了研究arch项目,所以我想现在已经足够好了。。
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
#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;
}