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";
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.
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.
You can use the c_str() method of the string class to get a const char* with the string contents.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With