c++ - efficient QVariant construction from a std::string -
i'm trying determine efficient way construct qvariant std::string , have live inside std::vector. i'm doing:
std::string foo = "test"; std::vector<qvariant> variants; ... variants[0] = qstring::fromstdstring(foo); this methodology seems construct temporary qstring, destroyed after qvariant(const qstring &) c'tor called.
any way avoid temp qstring?
if indeed want store qstring, due copy-on-write semantics of qt, temporary qstring object irrelevant performance. doing text decoding std::string qstring going dominate, , cow data not copied anyway (unless modified). if std::string '\0'-terminated text, can use this qvariant constructor, might optimal gets qstring:
variants.emplace(0, qvariant(stdstr.c_str()); alternative solution store std::string qbytearray instead of qstring. 1 thing need decide is, if std::string data needs copied or not. if know pointer string data remain valid lifetime of qbytearray, can use this:
// warning, not copy string data, pointer must remain valid variants.emplace(0, qbytearray::fromrawdata(stdstr.data(), stdstr.size())); safer this, copy no text decoding:
variants.emplace(0, qbytearray(stdstr.data(), stdstr.size())); note std::string not care encoding , 8-bit, in fact qbytearray qt counterpart. qstring stores unicode text, utf-16 internally, conversion needed, no matter encoding of std::string contents.
also, should read std::string::data() , std::vector::emplace() references.
Comments
Post a Comment