开发者

Proper idiom for std::string assignment

开发者 https://www.devze.com 2023-03-18 00:08 出处:网络
When constructing a std::string from a cons开发者_运维问答t char*, I often use the following pattern:

When constructing a std::string from a cons开发者_运维问答t char*, I often use the following pattern:

const char* p = GetString();
std::string s(p);

I suppose I could use the similar pattern:

const char* p = GetString();
std::string s = p;

But, when I want to assign, rather than construct, to a std::string from a const char*, I have too many choices:

s = p;
s.assign(p);
std::string(p).swap(s);

Are the choices above more-or-less equivalent? Which should I prefer, and why?


Go for readability, and just use the idiomatic operator= for assignment. Also, directly construct the std::string from the const char*.

std::string s(GetString());
s = GetString();


Normally, you'd just do

std::string s = GetString();.

For assignment, do

s = GetString();.

This means that the std::string object has the maximum information available to it to produce the fastest operation.


The operator= and .assign are pretty much identical, you should prefer the operator= form as it's more readable.

The last isn't the same. Swapping the content does reduce the amount of time spent on constructing a given object as it doesn't make a copy, it only moves content around. Your syntax first copies p into an std::string and then swaps it with s, which isn't any more performant than the rest as you're still duplicating p. If P had been an std::string somewhere else that you were destructing anyway, this would be faster.


The first two are basically the same thing; assign has a few more overloads that allow you to do interesting things. I would choose the straightforward =, because it's clearer.

The last one seems very verbose and non-intuitive; I'm not sure why you'd do that (unless you were desperate to reclaim the memory that s is using).

0

精彩评论

暂无评论...
验证码 换一张
取 消