问题
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