Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a const char* cast to std::string work?

Tags:

c++

This cast puzzles me:

#include <string>
#include <iostream>
#include <memory>

using namespace std;

int main() {
    string str1 =  (string)"I cast this thing" +  " -- then add this";
    cout << str1 << endl;
}

Can someone explain why this c-style cast to string works (or is allowed)? I compared the generated optimized assembly with that from:

string str1 =  string("I construct this thing") +  " -- then add this";

and they appear to be identical, so I feel like I'm forgetting some c++ semantics that actually allow this kind of cast/construction to be interchanged.

 std::string str2 =  std::string("I construct this thing") +  " -- then add this";
like image 489
Mike Ellery Avatar asked Jan 12 '16 17:01

Mike Ellery


People also ask

Can you cast a char to a string in C++?

2) Using string class operator = The one which we will be using today is: string& operator= (char c); This operator assigns a new character c to the string by replacing its current contents.

What is the difference between const char * and string?

string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.

How do I get const char from STD string?

You can use the c_str() method of the string class to get a const char* with the string contents.

What is const char * in CPP?

char* const says that the pointer can point to a char and value of char pointed by this pointer can be changed. But we cannot change the value of pointer as it is now constant and it cannot point to another char.


1 Answers

A C-style cast will do a const cast and static cast or reinterpret cast whichever is possible.

A static cast will use a user-defined conversion if defined.

std::string has a constructor string(const char *).

The syntaxes std::string("something"), static_cast<std::string>("something") and (std::string)"something" are equivalent. They will all construct a temporary std::string using the std::string::string(const char *) constructor. The only difference between the syntaxes would be when casting pointers.

like image 59
Jan Hudec Avatar answered Sep 22 '22 22:09

Jan Hudec