mardi 30 juin 2015

why so many copying while transforming/copying vector

Why so many calls to copy cons, i would expect only last nine of them? Or even not at all duy to return value optimization.

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); 
    });
}

Output:

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

Aucun commentaire:

Enregistrer un commentaire