Is boost::beast::static_string memcopyable/trivial type?

旧街凉风 提交于 2020-04-18 05:43:42

问题


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.

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;
}

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

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.


回答1:


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

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++ 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 does just contain a size_t member and a CharT[N+1], so if those two were default, it would be.



来源:https://stackoverflow.com/questions/60597850/is-boostbeaststatic-string-memcopyable-trivial-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!