1

Hi I want to learn a professional way to initialize an emtpy string in c++.

I could do

std::string a_string; // way_1 

or

std::string a_string = ""; // way_2 

But I think way_1 is fully depending on the default value defined in std package. To me, it is not an explicit declaration, and it might need to be changed if the codes of std::string is changed in the future. way_2 to me is not directly but using "" which is equivalent to an empty string. To me, a built-in empty string is professional, like nullptr for initializing a pointer.

Do you know how would C++ professional programmers initialize an empty string?

Thanks

4
  • 2
    Take a look at this interesting post about empty strings: survex.com/~olly/blog/coding/empty-strings-in-c%2B%2B.html Commented Dec 21, 2017 at 9:37
  • 2
    There is no such thing as "std package". The string class is a part of the standard library defined in the language standard. The default value of the string is defined in the language standard. If you don't trust the standard, don't use the language. Commented Dec 21, 2017 at 9:46
  • If I wanted to provide an explicit initializer for an empty string, I would use {}: std::string a_string{}; or std::string a_string = {}; or auto a_string = std::string{};. Commented Dec 23, 2017 at 17:41
  • Related: stackoverflow.com/questions/26587110/… Commented Apr 4, 2024 at 2:19

1 Answer 1

11

But I think way_1 is fully depending on the default value defined in std package. To me, it is not an explicit declaration, and it might need to be changed if the codes of std::string is changed in the future.

This is faulty reasoning. The default value of std::string is defined by the C++ standard and is just as stable as every other part of the language. If you are worried about it changing, then you should also be worrying about std::string disappearing completely, or the meaning of "" changing, or the meaning of the initialization with the empty string changing.

If you are going for "professional", then I, if I saw a programmer using the explicit form, would wonder whether this programmer doesn't know what the default initialization of such a fundamental type as std::string does, and therefore what else this programmer might not know.

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.