gpt4 book ai didi

c++ - 存储字符串文字指针是否安全?

转载 作者:行者123 更新时间:2023-12-04 14:55:30 26 4
gpt4 key购买 nike

根据标准:

5.13.5 String literals [lex.string]

16 Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified.



和:

6.6.4.1 Static storage duration [basic.stc.static]

1 All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program



我认为存储指向字符串文字的指针是安全的,例如:
struct Base
{
Base(const char* name)
: _name(name)
{
}

void print()
{
std::cout<<_name<<std::endl;
}

const char* _name = nullptr;
};

struct MyDerived : public Base
{
MyDerived () : Base("MyDerived")
{
}
};

上面的代码定义好了吗?是否有任何我必须注意的标准的黑暗角落?

最佳答案

Is the above code well defined?


是的。

Are there any dark corners of standard that I have to be aware of?


也许不是标准中的黑暗角落,但一个问题是您有一个指针并且您允许 Base像这样被实例化和使用:
Base foo(nullptr);
foo.print();
来自 operator<< :
“如果 s 是空指针,则行为未定义。”
一个更安全的构造函数:
template<size_t N>
constexpr Base(const char(&name)[N]) : _name(name) {}
我这么说是因为你仍然可以这样做:
auto Foo() {
const char scoped[] = "Fragile";
Base foo(scoped);
foo.print(); // OK
return foo;
} // "scoped" goes out of scope, "_name" is now dangling

int main() {
auto f = Foo();
f.print(); // UB
}

关于c++ - 存储字符串文字指针是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68111251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com