请引用下面的代码。在此代码中,我将 test.c_str()
返回的 const char*
存储到一个引用中。我的问题是 - data
是否会正确引用 test
的内容?我认为 test.c_str()
返回的 ptr 将是临时的,如果我将它绑定(bind)到一个引用,该引用将无效。
我的想法对吗?
class RefPtrTest
{
std::string test;
StoringClass storingClass;
public:
RefPtrTest(): test("hello"), storingClass(test.c_str())
{
}
}
存储类在哪里
class StoringClass
{
const char*& data;
public:
StoringClass (const char*& input): data(input)
{
}
}
编辑 1:
让我们不考虑 std::string 在做什么。假设我正在使用我自己的名为 mystring 的类
class RefPtrTest
{
const mystring test;
StoringClass storingClass;
public:
RefPtrTest(): test("hello"), storingClass(test.getInternalPointer())
{
}
}
getInternalPointer
直接返回内部指针。我想验证这个假设,而 test.getInternalPointer()
返回的 storingClass(test.getInternalPointer())
ptr 将是临时的,如果我将它绑定(bind)到引用该引用将无效。我的想法对吗?
编辑 2:
那个 StoringClass 不在我的控制之下。基本上它是一个模板类,它存储对该类型的引用。我将它用于 const char*
。我知道您提出的所有设计问题。但我无法更改该类,我必须将它用于 const char *
。别无选择。
最佳答案
标准对 c_str
(21.3.6/2) 有以下说法
Requires: The program shall not alter any of the values stored in the array. Nor shall the program treat the returned value as a valid pointer value after any subsequent call to a non-const member function of the class basic_string that designates the same object as this.
所以答案是否定的,您不能将指针视为对字符串内容的引用(在对字符串进行任何非 const 函数调用之后)。
关于c++ - 将指针临时绑定(bind)到引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2560859/