string_view是C++ Library Fundamentals TS(N3921)中添加到C++ 17中的一个提议特性
据我所知,它是一种代表某种字符串"概念"的类型,它是任何类型的容器的视图,可以存储可视为字符串的东西.
const std::string&参数类型应该
变成string_view吗?string_view需要考虑吗?我只是遇到了一些误解:至少在libc ++实现中,std :: experimental :: string_view具有以下简洁的实现:
template <class _CharT, class _Traits....>
class basic_string_view {
public:
typedef _CharT value_type;
...
template <class _Allocator>
basic_string_view(const basic_string<_CharT, _Traits, _Allocator>& str):
__data(str.data()), __size(str.size())
{
}
private:
const value_type* __data;
size_type __size;
};
Run Code Online (Sandbox Code Playgroud)
这个实现是否意味着如果我们将rvalue表达式传递给这个构造函数,在构造之后使用__data时我们会得到未定义的行为?
库基础知识的C++扩展,版本2(N4564)介绍了该类型std::experimental::source_location.
§14.1.2[reflection.src_loc.creation]说:
Run Code Online (Sandbox Code Playgroud)static constexpr source_location current() noexcept;返回:当函数调用(C++14§5.2.2)调用其后缀表达式(可能是带括号的)id-expression命名时
current,返回source_location带有实现定义值的a.该值应受#line(C++14§16.4)影响,其方式与__LINE__和__FILE__.如果以其他方式调用,则返回的值未指定.备注:当使用大括号或等于初始化程序来初始化非静态数据成员时,任何调用都
current应该对应于构造函数的位置或初始化成员的聚合初始化.[ 注意:当用作默认参数(C++14§8.3.6)时,该值
source_location将是current呼叫站点呼叫的位置.- 结束说明 ]
如果我理解正确,那么该功能就像这样使用.
#include <experimental/source_location> // I don't actually have this header
#include <iostream>
#include <string>
#include <utility>
struct my_exception
{
std::string message {};
std::experimental::source_location location {};
my_exception(std::string msg,
std::experimental::source_location loc = std::experimental::source_location::current()) :
message {std::move(msg)},
location {std::move(loc)}
{ …Run Code Online (Sandbox Code Playgroud)