3

Is there a difference or is just a matter of preference? I'm a beginner to c++ and it bothers me that I am not confident that I'm choosing the right way to initialize a string value.

If I were to just choose one way which works for the vast majority of use cases, which would it be?

// Initializing from a literal. std::string s1{"hello"}; std::string s2("there"); std::string s3 = {"what"}; std::string s4 = "is"; // Initializing from another string object. std::string s5{s1}; std::string s6(s1); std::string s7 = s1; std::string s8 = {s1}; 

PS: Apologies if this question in it's entirety has been asked before, I couldn't find it anywhere and would appreciate it if someone could link to it here.

4
  • I recommend rewording your question to ask about the general technical differences between those different ways of initializing a string, as asking for "the right way" might be closed as off-topic (primarily opinion based). Commented Mar 31, 2019 at 2:52
  • 6
    I expect modern C++ compilers to generate identical code for all of the logically equivalent alternatives. So this is purely a matter of personal opinion and preferences. Commented Mar 31, 2019 at 2:52
  • @MaxVollmer - Good call - edited the question slightly. Commented Mar 31, 2019 at 3:59
  • @SamVarshavchik - Thanks, would you state it as a fact that all compilers would treat them as equivalent? Or are there certain situations where one is preferred over the other? It's a bit strange that c++ allows so many ways to initialize a string, there must be some reasoning behind it other than backwards compatibility? Commented Mar 31, 2019 at 4:01

1 Answer 1

2

For strings in particular, you will always be able to use all of the above, and it's really just a matter of personal preference.

I personally prefer

auto s1 = std::string(); //Initialize empty string auto s2 = std::string("Hello, world"); // Initialize string containing "Hello, world" auto s3 = s2; //Make a copy of s2 auto s4 = std::move(s3); //Move s3 into s4 

And the reason I prefer that is because it works on all types. You can't forget to initialize something if you use auto:

int i; //Oops, forgot to initialize i, because i is a primitive 

Versus:

auto i = 0; //i set to 0 auto i2 = size_t(0); //i2 is a size, and set to 0 auto i3; //Error: forgot to initialize 

The important thing is to remain consistent throughout the codebase.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.