【发布时间】:2020-01-04 02:02:36
【问题描述】:
如何理解下面的std::string init 语法?
#include <iostream>
#include <string>
int main ()
{
std::string y;
std::string x = "x str";
new (&y) std::string(x);
std::cout << y << std::endl;
return 0;
}
输出:
x str
我们可以把语句分成两步吗?
1.
string* temp = new std::string(x);
2.
(&y) = temp
所以原始语句只是步骤 1 + 2 的捷径。
参考:
1。 https://en.cppreference.com/w/cpp/string/basic_string/basic_string
【问题讨论】:
-
这里没有什么特别的,只是使用了placement new,这在代码中并不常用。
标签: c++ string constructor