Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper idiom for std::string assignment

Tags:

c++

string

When constructing a std::string from a const 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?

like image 487
Robᵩ Avatar asked Jul 06 '11 18:07

Robᵩ


People also ask

How do I assign a string in C++?

std::string::assign() in C++ The member function assign() is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str.

How do you assign a string?

String assignment is performed using the = operator and copies the actual bytes of the string from the source operand up to and including the null byte to the variable on the left-hand side, which must be of type string. You can create a new variable of type string by assigning it an expression of type string.

What does std::string () do?

std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.

Can we assign one string to another in C++?

The value of a string can be copied into another string. This can either be done using strcpy() function which is a standard library function or without it.


1 Answers

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();
like image 186
Xeo Avatar answered Oct 13 '22 22:10

Xeo