Should I use pointer to std::string
Solution 1
Whether std::string
uses copy-on-write depends on the implementation (i.e. your standard library vendor decides that). However, most std::string
implementations 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()
and data()
return a pointer. Compare this to QString::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 QString
stores UTF-16 strings, whereas std::string
stores a sequence of char
s -- QByteArray
would be the Qt equivalent.
Solution 2
std::string var1("Hi there!");
std::string var2=var1;
std::string class has an =
operator defined as:
string& operator= ( const string& str );
Solution 3
std::string* var1=new std::string()
Don't do that. Just pass it by reference wherever possible:
void f(const std::string& s); // no copying
If you really need to share the string, use:
std::shared_ptr<std::string> var1 = std::make_shared<std::string>();
Solution 4
If you are going to return std::string
from function then don't use pointer - return by value. In this case most likely Return Value Optimization will be applied and string data will not be copied.
asdacap
Updated on October 31, 2020Comments
-
asdacap over 3 years
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?