简体   繁体   中英

How to modify a const reference in C++

I am new to C++ and I am trying to modify some existing code. I basically have to modify a const reference variable in C++. Is there a way to do so?

I want to remove a subtring from a constant string reference. This obviously wouldn't work, since id is a constant reference. What would be the correct way to modify 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.

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 ... :

#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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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