C++ 为什么要复制字符串。。。?

C++ 为什么要复制字符串。。。?,c++,C++,想象一下这个小小的简化代码片段: ostringstream os; os << "hello world!"; string str = os.str().c_str(); // copy of os list<string> lst; lst.push_back(str); // copy of str ostringstreamos; 操作系统如果您可以使用C++11,则只需使用move。您可以在此处阅读有关移

想象一下这个小小的简化代码片段:

ostringstream os; 
os << "hello world!";           

string str = os.str().c_str();  // copy of os

list<string> lst;
lst.push_back(str);             // copy of str
ostringstreamos;

操作系统如果您可以使用
C++11
,则只需使用
move
。您可以在此处阅读有关移动语义的内容:

但在这里:

string str = os.str().c_str();

c_str
返回的
const char*
构造新的
string
,只需删除
c_str
,然后c++11编译器将调用移动构造函数,而不是新的字符串构造。

在Qt库中,有不同的写时复制方法。例如:

QString a = "Hello";   // Create string
QString b = a;         // No copy, `b` has pointer to `a`
a += " world!";        // `b` is copied here, because `a` was modified

关于
std::string
C++11试图用移动语义解决这个问题。另一个问题可能是在
QString

这样的容器中处理内存管理是否是个好主意
os.str().c_str()
是一种悲观主义,它首先会阻止编译器做正确的事情。如果你那么在意复制,那么
std::shared\u ptr>
怎么样?因为你在复制它们。没有办法将字符串从
ostringstream
中分离出来。Stringstreams权衡性能以获得方便/安全的界面。最有效的代码重写是
lst.emplace_back(“helloworld!”)
string str=os.str()
无论如何都只会“做正确的事”。@永远,除了str为空之外,“移动”和“复制”有什么区别。@请注意,
move()
不会创建副本。请注意,仍然有多余的副本,你对ostringstream也无能为力,因为它按值返回其内部字符串,无法将其移出。对不起,我今天的思维有点慢。。。“创建副本”是什么意思?移动对我来说就像从一个缓冲区复制到另一个缓冲区。但我想到了指针弯曲。
QString a = "Hello";   // Create string
QString b = a;         // No copy, `b` has pointer to `a`
a += " world!";        // `b` is copied here, because `a` was modified