Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stdstring

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?

like image 422
Charzhard Avatar asked Jul 19 '13 05:07

Charzhard


People also ask

What is the value of uninitialized string in C++?

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.

What is the default value of string variable in C++?

Strings. Variables of type "String" are treated as Objects in this case and have a default value of null.

Is std::string initialized to empty?

A std::string isn't a pointer, so it shouldn't be combined. PS. the initializations are the same: the ctor of std::string sets it to the empty string.

What is std::string in C?

The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.


1 Answers

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                                            | +-----------------------------------------------------------------------------+ 
like image 163
Pierre Fourgeaud Avatar answered Oct 11 '22 12:10

Pierre Fourgeaud