Most people when declaring strings in C++, or most other languages, do it like so:
std::string example = "example"; However I've seen some code samples where it is done like this:
std::string example("example"); To me it seems like it needlessly obfuscates the code, particularly if there is a using std::string statement hiding somewhere above the declaration in the code making it look like
string example("example"); To some who may be new to the codebase or are coming from other languages it almost looks like it could be a method or a function.
Is there any practical or performance based reason for using the constructor instead of the assignment operator or does it come down to just personal preference?
string example{"example"};.=only for real assigment, and not for initialization.auto example{"example"s};const char *to initialiseexamplewith the literal"example". In other words, your two examples - despite the syntactic differences - do EXACTLY the same thing. The main difference is the way they are interpreted at times - I've lost count of the number of times I've seen people insist the first is an assignment that callsstd::stringsoperator=()function - which it doesn't. People who get tired of fielding such claims therefore sometimes prefer the second form.