initializing strings as null vs. empty string

后端 未结 6 726
独厮守ぢ
独厮守ぢ 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:25

    Best:

     std::string subCondition;
    

    This creates an empty string.

    This:

    std::string myStr = "";
    

    does a copy initialization - creates a temporary string from "", and then uses the copy constructor to create myStr.

    Bonus:

    std::string myStr("");
    

    does a direct initialization and uses the string(const char*) constructor.

    To check if a string is empty, just use empty().

提交回复
热议问题