initializing strings as null vs. empty string

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

    There's a function empty() ready for you in std::string:

    std::string a;
    if(a.empty())
    {
        //do stuff. You will enter this block if the string is declared like this
    }
    

    or

    std::string a;
    if(!a.empty())
    {
        //You will not enter this block now
    }
    a = "42";
    if(!a.empty())
    {
        //And now you will enter this block.
    }
    
    0 讨论(0)
  • 2020-12-24 01:24

    Empty-ness and "NULL-ness" are two different concepts. As others mentioned the former can be achieved via std::string::empty(), the latter can be achieved with boost::optional<std::string>, e.g.:

    boost::optional<string> myStr;
    if (myStr) { // myStr != NULL
        // ...
    }
    
    0 讨论(0)
  • 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().

    0 讨论(0)
  • 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()) ...
    
    0 讨论(0)
  • 2020-12-24 01:31

    I would prefere

    if (!myStr.empty())
    {
        //do something
    }
    

    Also you don't have to write std::string a = "";. You can just write std::string a; - it will be empty by default

    0 讨论(0)
  • 2020-12-24 01:37

    There are no gotchas. The default construction of std::string is "". But you cannot compare a string to NULL. The closest you can get is to check whether the string is empty or not, using the std::string::empty method..

    0 讨论(0)
提交回复
热议问题