2

Is passing a string by "" equivalent to passing a string by calling std::str("") in C++?

e.g. given a function which accepts std::str as an argument:

void funcA(std::string arg) {
    arg = "abc";
}

Should I call it by funcA(std::string("abc")); or funcA("abc"); ? i.e. is the second version a typecast from an array of char?

Jim Balter
  • 16,163
  • 3
  • 43
  • 66
jhtong
  • 1,529
  • 4
  • 23
  • 34
  • #5: http://en.cppreference.com/w/cpp/string/basic_string/basic_string – chris Apr 13 '13 at 04:59
  • question is, is the second version's argument treated as an array of char instead? – jhtong Apr 13 '13 at 05:00
  • @toiletfreak - `string` is just an array of chars, but in nicer wrapping – Lemur Apr 13 '13 at 05:01
  • 1
    Please don't put C tags on C++ programs. – Jim Balter Apr 13 '13 at 05:03
  • @PabloLemurr Nah, not even close. –  Apr 13 '13 at 05:03
  • @H2CO3 - so you tell me than I lived in lie whole my life? D: – Lemur Apr 13 '13 at 05:04
  • Slightly off-topic, but this discussion is interesting and vaguely related: http://stackoverflow.com/questions/6727412/inconsistency-between-stdstring-and-string-literals – Kirby Apr 13 '13 at 05:04
  • Both work. In FuncA("abc") the compiler adds the call to string( const char * ) for you. – brian beuning Apr 13 '13 at 05:06
  • 1
    @PabloLemurr Kind of. `string` and `char []` are two very distinct data types, and although they represent the same concept (character strings), when discussing a question like this, the difference is not negligible. –  Apr 13 '13 at 05:07
  • 1
    @PabloLemurr An array in C++ is a data type containing a fixed number of objects of the same type. A `std::string` maintains a variable number of characters in a contiguous block of memory. Quite different, but same in terms of pointer arithmetic. – Potatoswatter Apr 13 '13 at 05:07

1 Answers1

4

They are equivalent. Because the constructor std::string::string( char const * ) is not declared as explicit, it is called implicitly to provide a conversion from char * to string. The implicit call does the same thing as the explicit call (written out as std::string("abc")).

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421