将项目添加到向量而不创建临时对象

问题描述 投票:0回答:1

编译器会优化这段代码,而不是创建临时字符串对象吗?

std::vector<std::string> vector;
vector.push_back(std::string());
std::string& str = vector.back();
c++ vector stl compiler-optimization c++03
1个回答
0
投票

编译器将创建一个临时的 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()
根据需要调整矢量大小。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.