What's the difference between std::string and const char*? consider following example
#include <iostream>
#include <string>
int main()
{
const char* myName1{ "Alex" };
std::cout << myName1 << '\n';
std::string myName2{ "Alex" };
std::cout << myName2 << '\n';
return 0;
}
are they the same?
CodePudding user response:
std::string
will give you the ability to use its member functions and most importantly to modify its contents. The initial data will likely1 be copied to a dynamically allocated memory location when the program reaches its constructor. It will also store its size.
const char*
is only a pointer value that points to a constant that is gonna be baked into the binary. There's no size information stored, and all functions operating on it have to rely on the presence of the '\0'
value at the end.
1 It's possible that Small-String Optimization kicks in here.
CodePudding user response:
As soon as you want to store some string, const char *
doesn't do, you'll need char *
. And you'll have to allocate memory for that char *
to point at. And you'll have to figure out how much memory to allocate. And then reallocate more if you want to, say, append to that string. And you'll have to remember freeing that memory before your pointer goes out of scope (like, an exception being thrown somewhere).
Well, std::string
relieves you of all of that. That's the big difference.
Just like C arrays and std::vector
...
But within the scope of your example, there is very little actual difference.