在C++17中,引用const字符串的语义应该是什么
What should be the semantics of a reference to const string in C++17?
有几种方法可以将文本信息传递到C++中的函数中:可以是C-string/std::string、by-value/by-reference、lvalue/rvale、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++17中,void read(const std::string&)
是否应该优先于void read(std::string_view)
。假设不需要向后兼容性。
是否需要null终止?如果是这样,你必须使用其中一个:
// by convention: null-terminated
void read(const char*);
// type invariant: null-terminated
void read(std::string const&);
因为std::string_view
只是char const
的任何连续范围,所以不能保证它是以null结尾的,并且试图越过最后一个字符是未定义的行为。
如果您执行而不需要null终止,但需要获得数据所有权,请执行以下操作:
void read(std::string );
如果你既不需要无效终止,也不需要所有权或修改数据,那么是的,你最好的选择是:
void read(std::string_view );
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- C++避免重复声明的语法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 在C++17中,引用const字符串的语义应该是什么
- 在C++中使用移动语义的正确方法是什么?
- 函数作为变量的语义是什么 C++.
- testb $1, %al 的语义是什么
- 模板化代码的语法和语义是什么C++
- C++11 中已删除成员函数的确切语义是什么?
- 消除默认/删除移动/复制语义中涉及的样板的好方法是什么
- 在共享库中全局声明的非pod对象的语义是什么?
- 语义和顶点布局在D3D11中的意义是什么?
- 移动语义 - 它的全部内容是什么?
- 指向已分配对象的指针没有值语义是什么意思
- 在遵循pimpl设计模式的类中实现move语义的正确方法是什么?
- 我是否正确地使用了move语义?好处是什么?
- "值语义"和"指针语义"是什么意思