Strings

closed account (zwpL3TCk)
Can anyone explain me what does this code

 
string str = "";
That code declares a variable (str) of type string and assigns to that variable an empty string.
that code initializes str to an empty string

Note: initialize not assign
string str = "";

This code fragment declares a variable (str) of type string and pointlessly initializes it to contain an empty string.

The default constructor of std::string already inititlizes it to blank, so you might as well write.

string str;

Andy

str_default == str_set_blank -> true


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std; 

int main () {
    cout << boolalpha;

    string str_default;
    string str_set_blank = "";

    cout << "str_default == str_set_blank -> "
         << (str_default == str_set_blank) << "\n";

    return 0;
}
Last edited on
@basetwo: Splitting hairs much?

@andywestken: This is true!
Bazetwo isn't splitting hairs. The point is that assignment calls operator=() and initialization calls a constructor. It would make a difference in something like this:
1
2
3
4
5
6
7
8
9
class C {
   C(const char *cp) { do_something_fast(); ]
   C() { do_something_slow(); }
   C& operator=(const C& src) { do something_slow(); }
}

C c1("this is fast");
C c2;
c2 = "this is slow";

@dhayden: Yes, I know. My bad for not being thorough-enough.
Topic archived. No new replies allowed.