[英]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.