boost::beast::static_string 是 memcopyable/trivial 类型吗? [英] Is boost::beast::static_string memcopyable/trivial type?

查看:31
本文介绍了boost::beast::static_string 是 memcopyable/trivial 类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种具有固定上限的字符串实现,它可以在 memcopy 环境中使用,并且可以简单地构造和复制.

I am looking for a string implementation with fixed upper size that can be used in memcopy environment and that is trivially constructible and copyable.

我发现 boost beast static_string,但 IDK 如果我的 example 是偶然工作还是没有?>

I found boost beast static_string, but IDK if my example works by accident or no?

#include <algorithm>
#include <iostream>
#include <boost/beast/core/static_string.hpp>
boost::beast::static_string<16> s1("abc");

int main(){
    boost::beast::static_string<16> s2;
    std::copy_n((char*)&s1, sizeof(s2), (char*)&s2);
    s1.push_back('X');
    std::cout << "--" << std::endl;
    std::cout << s2 << std::endl;
    s2.push_back('Y');
    std::cout << s2 << std::endl;
    std::cout << std::is_trivial_v<decltype(s2)> << std::endl;
}

注意:最后一行说 type 不能简单地复制,但可能只是 Vinnie 忘记添加类型特征.

note: last line says type is not trivially copyable, but it could be just that Vinnie forgott to add a type trait.

附言我知道这通常是一个坏主意,我要替换的更糟,只是一个普通的 C 数组,修改分配/复制以支持 std::string 需要做更多的工作.

P.S. I know this is a generally bad idea, what I am replacing is even worse, just a plain C array and modifying the allocation/copying to support std::string is much much more work.

推荐答案

技术上没有,有用户定义的复制构造函数和运算符(都调用 assign),这意味着类不是 简单可复制.

Technically no, there are user defined copy constructors and operators (both call assign) which mean the class is not trivially copyable.

这些似乎作为优化存在,如果 static_string 有很大的尺寸,但只存储一个小字符串,assign 只复制字符串的使用部分,加上一个空终止符.

These appear to exist as an optimisation, if a static_string has a large size, but only stores a small string, assign only copies the used portion of the string, plus a null terminator.

C++ 不允许 std::is_trivially_copyable 被程序专门化,所以我认为目前没有办法同时获得.

C++ does not allow for std::is_trivially_copyable to be specialized by programs, so I don't believe there is a way to get both at present.

static_string 只包含一个 size_t 成员和一个 CharT[N+1],所以如果这两个是默认的,那就是.

static_string does just contain a size_t member and a CharT[N+1], so if those two were default, it would be.

这篇关于boost::beast::static_string 是 memcopyable/trivial 类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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