initializing strings as null vs. empty string

后端 未结 6 687
独厮守ぢ
独厮守ぢ 2020-12-24 01:07

How would it matter if my C++ code (as shown below) has a string initialized as an empty string :

std::string myStr = \"\";
....some code to optionally popul         


        
6条回答
  •  生来不讨喜
    2020-12-24 01:29

    The default constructor initializes the string to the empty string. This is the more economic way of saying the same thing.

    However, the comparison to NULL stinks. That is an older syntax still in common use that means something else; a null pointer. It means that there is no string around.

    If you want to check whether a string (that does exist) is empty, use the empty method instead:

    if (myStr.empty()) ...
    

提交回复
热议问题