我想知道我們是否可以通過指向它的指標修改 std::string 值。請考慮以下示例。
#include <iostream>
void func(std::string *ptr) {
*ptr = "modified_string_in_func";
}
int main()
{
std::string str = "Original string";
func(&str);
std::cout << "str = " << str << std::endl;
return 0;
}
我嘗試了 GCC、Clang 和 Visual C 。所有人都在修改字串 valirablestr沒有任何警告或錯誤,但我不太確定這樣做是否合法。
請說清楚。
uj5u.com熱心網友回復:
那是合法的。
您正在為字串分配一個新值,但正在使用指標來參考原始字串;這不再是非法的,然后不使用指標來參考原始字串即
std::string foo = "foo";
foo = "bar";
// is pretty much the same thing as
std::string* foo_ptr = &foo;
*foo_ptr = "bar";
// which is what you are doing.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/367094.html
上一篇:反轉字串的范圍
