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?
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With