0

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);
4
  • const_cast<std::string&>(id).erase(start_index,3). I'll let other people tell you why this is a bad idea. Commented May 22, 2015 at 7:43
  • Remove the const modifier. Commented May 22, 2015 at 7:43
  • 2
    The API you are programming against obviously doesn't want you to modify the return value; are you sure you need to do this? Commented May 22, 2015 at 7:45
  • @BenjaminBannier Yes, that's true, it is a bit of a hack. But this is the quickest way I could do this, and it's for a research project, so I guess it's good enough for now.. Commented May 22, 2015 at 7:53

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.