编译器会优化这段代码,而不是创建临时字符串对象吗?
std::vector<std::string> vector;
vector.push_back(std::string());
std::string& str = vector.back();
编译器将创建一个临时的 std::string 对象;这是标准行为。
使用 C++11 容器方法
emplace_back()
或 emplace()
来存储 std::string
,而无需调用 std::string constructor
两次:
std::vector<std::string> vector;
vector.emplace_back("Hello!");
std::string& str = vector.back();
std::cout << str << "\n";
输出:
Hello!
emplace_back()
根据需要调整矢量大小。