有没有一种安全的方法来断言字符串视图是否为null终止? [英] Is there a safe way to assert if a string view is null terminated?

查看:56
本文介绍了有没有一种安全的方法来断言字符串视图是否为null终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一部分广泛使用字符串视图.在任何地方使用 std :: string 都是不可想象的,并且 char const * 将不起作用,因为存在关联容器,许多比较以及此类操作难以执行的操作带有简单的原始字符串.

I have some part in my code that uses string view extensively. It would be inconceivable to use std::string everywhere, and char const* won't work since there is associative containers, many comparisons and such operations that are hard to do with plain raw strings.

但是,有一个地方最终将处理C API,并且它需要以null结尾的字符串:

However, there is a place that will eventually deal with a C API, and it needs null terminated strings:

auto sv = std::string_view{/* ... */};
c_api(sv.data());

尽管在我的情况下这可以正常工作,但我想确保一切正常,并断言字符串以null终止,因为我的系统在构造字符串视图并将其发送到该系统时将不使用子字符串视图,并且使用字符串文字或 std :: string 进行设置.我知道我会没事的.

Although this works fine in my case, I'd like to be sure everything is okay and assert that the strings are null terminated, as my system constructing the string views and send it there will not use substring views, and will either make them from string literals or std::string. I know I will be okay.

但是,问题是另一个程序员可能不知道所有这些,而是​​尝试在字符串视图上使用 substr 或发送非null终止的字符串.非空终止的字符串是不好的,因为它将导致未定义的行为,但是字符串视图中的子字符串甚至更糟,因为在发送给C API时不会应用上限,并且不会调用任何未定义的行为,但是会而是引入一个很难发现的,具有意外行为的错误.

The thing however is that another programmer may not know all of this and try to use substr on a string view, or send a non null terminated string. A non null terminated string is bad since it will lead to undefined behaviour, but a substring in the string view is even worse, since the upper limit will not be applied when sent to the C API and no undefined behavior will be invoked, but will instead introduce a really hard to find bug with unintended behavior.

所以我想用一个断言来传达这一点:

So I wanted to communicate that using an assert:

auto sv = std::string_view{/* ... */};
assert(*(sv.data() + sv.length()) == '\0'); // Yay?
c_api(sv.data());

但是我发现它不完整且容易出错,因为它可能会读取空终止字符串的边界.

But I find it incomplete and error prone, since it may read out of bound of a null terminated string.

是否可以安全地断言字符串视图确实以null终止?

Is there a way to safely assert that a string view is indeed null terminated?

推荐答案

这可能很痛苦,但是我会写自己的 string_view 并确保将其终止.

It might be a pain, but I would write my own string_view that is guaranteed to be null terminated.

因为可以像这样构造 string_view

char array[3] = {'B', 'a', 'r'};
std::string_view array_v(array, sizeof array);

测试

*(sv.data() + sv.length()) == '\0'

在那种情况下,

是未定义的行为,因为最后一个有效索引是 2 ,但是您访问 3 . std :: string_view 将需要公开它不知道的信息,以便您执行此操作,并且由于它不知道,您无法可靠地知道.

is undefined behavior in that case since the last valid index is 2 but you access 3. std::string_view would need to exposes information it can't know in order for you to do this and since it can't, you can't reliably know.

这篇关于有没有一种安全的方法来断言字符串视图是否为null终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆