[英]Does experimental::basic_string_view<> work with rvalues?
I am not 100% that the following code is semantically correct: 我不是100%以下代码在语义上是正确的:
#include <iostream>
#include <experimental/string_view>
int main()
{
std::string str = "lvalue string";
std::experimental::string_view view_lvalue(str);
std::experimental::string_view view_rvalue(std::string{"rvalue string"});
std::cout << view_lvalue << '\n' << view_rvalue << '\n';
}
Question: Can I legally bind a rvalue to std::experimental::basic_string_view , or is it just UB? 问题:我可以合法地将rvalue绑定到std :: experimental :: basic_string_view ,还是只是UB? If yes, how does it work? 如果是,它是如何工作的? As far as I know, a rvalue does not bind to a const
reference (which I assume the view holds to the original string) via the constructor, so I thought that at the end of the statement std::experimental::string_view view_rvalue(std::string{"rvalue string"});
据我所知,rvalue不会通过构造const
绑定到const
引用(我假设视图保持原始字符串),所以我认为在语句结束时std::experimental::string_view view_rvalue(std::string{"rvalue string"});
the reference will be dangling. 引用将是悬空。 Does string_view
use a more sophisticated approach? string_view
是否使用更复杂的方法?
I am asking this because I am trying to write a similar view for some matrix class, and don't yet know how to deal with rvalues (I can disable them of course, but I don't think it's the best approach). 我问这个是因为我试图为一些矩阵类写一个类似的视图,并且还不知道如何处理rvalues(我当然可以禁用它们,但我不认为这是最好的方法)。
If cpprefernce is correct then this is UB. 如果cpprefernce是正确的,那么这是UB。 std::string_view
has std::string_view
有
A typical implementation holds only two members: a pointer to constant
CharT
and asize
. 典型的实现仅包含两个成员:指向常量CharT
和size
的指针。
And the constructor has 构造函数有
Constructs a view of the first
str.size()
characters of the character array starting with the element pointed bystr.data()
. 构造一个以str.data()
指向的元素开头的字符数组的第一个str.size()
字符的视图。
So if string_view
just points to the underlying char array of the provided string then we will have a dangling pointer once the expression ends and the temporary is destroyed. 因此,如果string_view
只指向提供的字符串的基础char数组,那么一旦表达式结束并且临时被销毁,我们将有一个悬空指针。
As pointed out in the comments one reason this behavior may have been allowed is so you can pass a string_view
to a function and construct that string_view
from a temporary string
正如评论中所指出的,这种行为可能被允许的一个原因是你可以将string_view
传递给一个函数并从一个临时string
构造string_view
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.