Why does const char * work when I click on std :: string?

This spell 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 in lines works (or is allowed)? I compared the generated optimized assembly with:

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

and they seem to be the same, so I feel like I forgot some kind of C ++ semantics that actually allows this kind of casting / construction to be exchanged.

 std::string str2 =  std::string("I construct this thing") +  " -- then add this";
+4
source share
3 answers

A C-style cast will perform const casting and static casting or reinterpretation, depending on what is possible.

A static cast will use a user-defined transformation, if one is defined.

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

std::string("something"), static_cast<std::string>("something") (std::string)"something" . std::string std::string::string(const char *). .

+6

, , , . const char* , .

+6

std::string

basic_string( const CharT* s,
              const Allocator& alloc = Allocator() );

. std::string, std::string

+4

Source: https://habr.com/ru/post/1623976/


All Articles