C++:如何复制 std::string *

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21143932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:30:00  来源:igfitidea点击:

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

c++string

提问by Jérémy Pouyet

How can I, in c++, duplicate a std::string * ?

我如何在 C++ 中复制 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"

回答by juanchopanza

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;

回答by David Heffernan

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;

回答by Sebastian Redl

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;

?

?

回答by Vlad from Moscow

You could do more simpler without calling new and delete. For example

如果不调用 new 和 delete,您可以做得更简单。例如

std::string *str1 = new std::string("test");
std::string *str2 = str1;

std::cout << *str2 << std::endl; // result = "test"

At least in your example if there is a possibility to access str1 after its deletion it would be better to write

至少在您的示例中,如果在删除 str1 后有可能访问它,那么最好编写

std::string *str1 = new std::string("test");
std::string *str2 = new std::string( *str1 );

delete str1;
str1 = nullptr;

std::cout << *str2 << std::endl; // result = "test"