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?

10
  • #5: en.cppreference.com/w/cpp/string/basic_string/basic_string Commented Apr 13, 2013 at 4:59
  • question is, is the second version's argument treated as an array of char instead? Commented Apr 13, 2013 at 5:00
  • 1
    Please don't put C tags on C++ programs. Commented Apr 13, 2013 at 5:03
  • 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. Commented Apr 13, 2013 at 5: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. Commented Apr 13, 2013 at 5:07

1 Answer 1

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")).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.