存储用户基础字符数据的时间

快速设置:我想在程序中传递字符串作为指针和大小。 我有一个String类和一个用户定义的文字来构造文字字符串:

struct String { const char *ptr; size_t sz; };

inline constexpr String operator "" _string(const char *s, size_t sz) {
  return {s, sz};
}

int main() {
  auto s = "hello"_string;
  s.ptr[0]; //<-- is this access guaranteed to work?
}

该标准是否指定传递给我的用户定义的文字运算符的参数具有静态持续时间? 即上面的代码实际上相当于写作:

int main() {
  String s{"hello", 5};
}

或者当我使用用户定义的文字时,编译器/链接器是否允许我使用悬挂指针?

(N4527的第2.13.8节似乎没有对用户定义的字符串运算符的参数存储类的主题进行任何说明,任何指向标准相应部分的指针都将被赞赏。


来自[lex.ext]:

如果L是用户定义的字符串文字,则让str为不带ud-suffix的文字 ,并让len为str中的代码单元数(即其长度不包括终止空字符)。 文字L被视为表单的调用:

operator "" X (str , len )

来自[lex.string]:

评估一个字符串文字会产生一个静态存储持续时间的字符串文字对象,从给定的字符初始化,如上所述。

所以:

"hello"_string;

相当于:

operator "" _string("hello", 5)

由于"hello"是一个字符串文字,它具有静态存储持续时间,所以你将没有悬挂指针。

链接地址: http://www.djcxy.com/p/88011.html

上一篇: storage duration of underlying character data with user

下一篇: Feature detect if user gesture is needed