[英]How to modify a const reference in C++
我是C ++的新手,正在尝试修改一些现有代码。 我基本上必须在C ++中修改const引用变量。 有办法吗?
我想从常量字符串引用中删除subtring。 显然,这是行不通的,因为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 副本 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.