How can I, in c++, duplicate a std::string * ?
I want to do something like that :
std::string *str1 = new std::string("test");
std::string *str2 = strdup(str1);
delete str1;
std::cout << *str2 << std::endl; // result = "test"
If you really must use pointers and dynamic allocation (most likely not), then
std::string *str2 = new std::string(*str1);
In real life,
std::string str1 = "test";
std::string str2 = str1;
I'm pretty sure that you should not be using pointers here. Using pointers forces you to manage the lifetime, protect against exceptions and so on. A world of needless pain.
The code you ought to write is:
std::string str1 = "test";
std::string str2 = str1;
You just do
std::string *str2 = new std::string(*str1);
But I have to ask why you're using pointers in the first place. What's wrong with
std::string str1 = "test";
std::string str2 = str1;
?
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