在成员函数中,我想返回一个新创建的字符串向量。从内存分配和构造函数调用的角度来看,哪个版本最有效?theString(i)
返回一个const std::string &
std::vector<std::string> result(depth());
for(int i=0;i<depth;i++) {
result[i] = theString(i);
}
或者
std::vector<std::string> result;
result.reserve(depth());
for(int i=0;i<depth;i++) {
result.emplace_back(theString(i));
}
在我看来:
- 解决方案 1 首先构造每个空字符串,然后复制分配它们 => 不完美
- 解决方案 2 更好,因为它将复制构造每个字符串,而向量数据由
reserve
(或者有没有更有效的解决方案?)