首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C++17中引用const字符串的语义应该是什么?

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

Stack Overflow用户
提问于 2020-07-07 18:31:38
回答 1查看 101关注 0票数 2

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

代码语言:javascript
复制
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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-07 18:55:11

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

代码语言:javascript
复制
// by convention: null-terminated
void read(const char*);

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

因为std::string_view只是char const的任何连续范围,所以不能保证它是以空结尾的,而且它是未定义的行为,试图查看最后一个字符。

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

代码语言:javascript
复制
void read(std::string );

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

代码语言:javascript
复制
void read(std::string_view );
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62781737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档