简体   繁体   English

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

[英]How to modify a const reference in C++

I am new to C++ and I am trying to modify some existing code. 我是C ++的新手,正在尝试修改一些现有代码。 I basically have to modify a const reference variable in C++. 我基本上必须在C ++中修改const引用变量。 Is there a way to do so? 有办法吗?

I want to remove a subtring from a constant string reference. 我想从常量字符串引用中删除subtring。 This obviously wouldn't work, since id is a constant reference. 显然,这是行不通的,因为id是一个常量引用。 What would be the correct way to modify id? 修改ID的正确方法是什么? Thanks. 谢谢。

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

Create a copy of the string and modify that, then set it back (if that's what you need). 创建字符串的副本并对其进行修改,然后将其重新设置(如果需要的话)。

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

Other routes shall be avoided unless you know what you're doing, why you're doing it and have considered all other options ... in which case you would never need to ask this question in the first place. 除非您知道自己在做什么,为什么要这样做并且已经考虑了所有其他选择,否则应避免使用其他路线...在这种情况下,您根本不需要首先提出这个问题。

If it is const and if you try to change it, you are invoking undefined behaviour. 如果它是const并且尝试更改它,则表示正在调用未定义的行为。

The following code (using char * instead of std::string& - I could not exhibit the error with std::string) in order to use a const_cast compiles and breaks at run-time with Access violation when writing at address ... : 以下代码(使用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;
}

So stick to @Macke's solution and use a non const copy . 因此,请坚持使用@Macke的解决方案,并使用非const 副本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM