Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : how to duplicate std::string *

Tags:

c++

string

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"
like image 928
Jérémy Pouyet Avatar asked Jan 15 '14 17:01

Jérémy Pouyet


3 Answers

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;
like image 191
juanchopanza Avatar answered Oct 17 '22 08:10

juanchopanza


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;
like image 44
David Heffernan Avatar answered Oct 17 '22 08:10

David Heffernan


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;

?

like image 34
Sebastian Redl Avatar answered Oct 17 '22 08:10

Sebastian Redl