爲什麼這麼多的電話複製缺點,我只希望只有最後九個?甚至根本不會返回價值優化。爲什麼這麼多的複製,而轉換/複製矢量
struct C
{
int _i;
C(int i) : _i(i) {}
C(const C& other) { cout << "copy cons from " << other._i << " to " << _i << endl; _i = other._i; }
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vi{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
vector<C> vc;
transform(vi.begin(), vi.end(), back_inserter(vc),
[](int i)
{
return C(i);
});
}
輸出:
copy cons from 1 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 4 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 4 to - 842150451
copy cons from 5 to - 842150451
copy cons from 6 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 4 to - 842150451
copy cons from 5 to - 842150451
copy cons from 6 to - 842150451
copy cons from 7 to - 842150451
copy cons from 8 to - 842150451
copy cons from 9 to - 842150451
謝謝,這是真的,但爲什麼它增長得如此緩慢,但沒有例如。每次兩倍?這不是很傻嗎? – Yola
@Yola它靠近兩個因子增長。確切的因素取決於實施。 – juanchopanza
許多實現使用接近黃金比例(〜1.62)的增長因子而不是2的主要原因是這可以防止內存碎片。請參閱[本答案](http://stackoverflow.com/a/1100426/358277)以獲得更深入的解釋 –