Value and size of an uninitialized std::string variable in c++

倖福魔咒の 提交于 2019-12-28 12:49:31

问题


If a string is defined like this

std::string name;

What will be the value of the uninitialized string "name" and what size it would be?


回答1:


Because it is not initialized, it is the default constructor that is called. Then :

empty string constructor (default constructor) :

Constructs an empty string, with a length of zero characters.

Take a look : http://www.cplusplus.com/reference/string/string/string/

EDIT : As stated in C++11, §21.4.2/1 :

Effects: Constructs an object of class basic_string. The postconditions of this function are indicated in Table 63.

-> Table 63
+-----------------------------------------------------------------------------+
| data()     | a non-null pointer that is copyable and can have 0 added to it |
+------------+----------------------------------------------------------------+
| size()     | 0                                                              |
+------------+----------------------------------------------------------------+
| capacity() | an unspecified value                                            |
+-----------------------------------------------------------------------------+



回答2:


It's not uninitialized, its default constructor is called.

From http://en.cppreference.com/w/cpp/string/basic_string/basic_string:

Default constructor. Constructs empty string.




回答3:


Default constructed user-defined types are not uninitialized. The default constructor defines an empty string (i.e "") with a size/length of zero.




回答4:


The Standard (C++11, §21.4.2/1) describes the results of default-constructing a std::basic_string (of which std::string is a specialization) as follows:

[...] an object of class basic_string. The postconditions [...] are indicated in Table 63.

And Table 63 says:

data() a non-null pointer that is copyable and can have 0 added to it
size() 0
capacity() an unspecified value




回答5:


value is null , and size is 0 But you can directly chk if the string is empty or not by empty()

Just in case you want to check that in your application , Do this

std::string name // Construct an empty string  
if(name.empty()) { // Check if its empty
  name="something";
}

Similar and more detailed discussion is here initializing strings as null vs. empty string



来源:https://stackoverflow.com/questions/17738439/value-and-size-of-an-uninitialized-stdstring-variable-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!