vector<int> v;
v.push_back(1);
v.push_back(v[0]);
Run Code Online (Sandbox Code Playgroud)
如果第二个push_back导致重新分配,则向量中对第一个整数的引用将不再有效.那么这不安全吗?
vector<int> v;
v.push_back(1);
v.reserve(v.size() + 1);
v.push_back(v[0]);
Run Code Online (Sandbox Code Playgroud)
这样可以安全吗?
使用push_back时std::vector,我可以推送向量本身的元素,而不必担心因重新分配而使参数无效:
std::vector<std::string> v = { "a", "b" };
v.push_back(v[0]); // This is ok even if v.capacity() == 2 before this call.
Run Code Online (Sandbox Code Playgroud)
但是,在使用时emplace_back,std::vector将参数转发给构造函数,std::string以便复制构造在向量中发生.这使我怀疑向量的重新分配在新字符串被复制构造之前发生(否则它不会被分配到位),从而在使用之前使参数无效.
这是否意味着我无法添加向量本身的元素emplace_back,或者在重新分配的情况下是否有某种保证,类似于push_back?
在代码中:
std::vector<std::string> v = { "a", "b" };
v.emplace_back(v[0]); // Is this valid, even if v.capacity() == 2 before this call?
Run Code Online (Sandbox Code Playgroud) 这是代码:
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <iomanip>
class Date
{
public:
Date(int year, int month, int day) : year(year), month(month), day(day) {}
Date(const Date &d) : year(d.year), month(d.month), day(d.day) {}
std::string to_string() {
std::stringstream ss;
ss << std::setfill('0') << std::setw(4) << year << '-' << std::setw(2) << month << '-' << day;
return ss.str();
}
private:
int year, month, day;
};
int main()
{
std::vector<Date> vd;
vd.emplace_back(2017, 1, 13);
vd.emplace_back(vd[0]);
std::cout << vd.back().to_string() << "\n";
} …Run Code Online (Sandbox Code Playgroud)