In learning c++, I first use Qt library instead of the standard C++, STL and all that (Ok, so I’m new with c++ and spoiled by Qt). On Qt, QString used implicit sharing, thus enabling me to just copy assign it to another variable like:
QString var1=QString("Hi there!");
QString var2=var1
And that would do nicely without much overhead. But now, i’m trying std::string so, should I do
std::string var1=std::string()
or
std::string* var1=new std::string()
And also, how about QVector and std::vector. And If I do have to use the pointer… any tips?
Whether
std::stringuses copy-on-write depends on the implementation (i.e. your standard library vendor decides that). However, moststd::stringimplementations will not use COW, largely due to the fact that most if not all read operations force a copy —operator[]returns a reference,c_str()anddata()return a pointer. Compare this toQString::operator[], which returns a proxy object.In spite of the above, don’t use pointers to
std::string, unless you determine (by measuring) that string copies are the bottleneck in your application.Also, beware that
QStringstores UTF-16 strings, whereasstd::stringstores a sequence ofchars —QByteArraywould be the Qt equivalent.