【问题标题】:Is changing the std::string value through it's address is valid?通过地址更改 std::string 值是否有效?
【发布时间】:2022-01-04 20:00:39
【问题描述】:

我想知道我们是否可以通过指向它的指针来修改 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++。所有人都在修改字符串 valirable str 没有任何警告或错误,但我不太确定这样做是否合法。

请澄清。

【问题讨论】:

标签: c++ string pointers stdstring


【解决方案1】:

这是合法的。

您正在为字符串分配新值,但使用指针来引用原始字符串;这不再是非法的,而不是不使用指针来引用原始字符串,即

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2010-11-10
    相关资源
    最近更新 更多