gpt4 book ai didi

c++ - C++17 中 const 字符串引用的语义应该是什么?

转载 作者:行者123 更新时间:2023-12-01 14:37:15 25 4
gpt4 key购买 nike

有多种方法可以将文本信息传递到 C++ 中的函数中:可以是 c-string/std::string、按值/按引用、左值/右值、const/mutable。 C++17 在标准库中添加了一个新类:std::string_view。 string_view 的语义是提供没有所有权的只读文本信息。因此,如果您只需要读取字符串,可以使用:

void read(const char*);        // if you need that in a c-style function or you don't care of the size
void read(const std::string&); // if you read the string without modification in C++98 - C++14
void read(std::string_view); // if you read the string without modification in C++17

我的问题是,在 C++ 中是否应优先选择 void read(const std::string&) 而不是 void read(std::string_view) 17.假设不需要向后兼容。

最佳答案

需要空终止吗?如果是这样,您必须使用其中之一:

// by convention: null-terminated
void read(const char*);

// type invariant: null-terminated
void read(std::string const&);

因为 std::string_view 只是 char const 的任何连续范围,因此不能保证它以 null 终止,并且尝试查看是未定义的行为超过最后一个字符。

如果您不需要需要空终止,但需要获取数据所有权,请执行以下操作:

void read(std::string );

如果您既不需要空终止,也不需要所有权或数据修改,那么是的,您最好的选择是:

void read(std::string_view );

关于c++ - C++17 中 const 字符串引用的语义应该是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62781737/

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