vector push_back calling copy_constructor more than once?

后端 未结 5 1212
刺人心
刺人心 2020-11-29 10:23

I am a bit confused with the way vector push_back behaves, with the following snippet I expected the copy constructor to be invoked only twice, but the output suggest otherw

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 11:23

    You got it...it was the resizing. But I'll just point out that if you're doing some bean counting on your constructors, you might be interested in "emplacement":

    #include 
    #include 
    using namespace std;
    
    class Myint
    {
    private:
        int my_int;
    public:
        explicit Myint(int value = 0) : my_int(value) 
        {
            cout << "Inside default " << endl;
        }
        Myint(const Myint& x) : my_int(x.my_int)
        {
            cout << "Inside copy with my_int = " << x.my_int << endl;
        }
        Myint(const Myint&& x) noexcept : my_int(x.my_int) {
            cout << "Inside move with my_int = " << x.my_int << endl;
        } 
    };
    
    int main() {
        vector myints;
        myints.reserve(2);
    
        myints.emplace_back(0);
        myints.emplace_back(1);
    
        // your code goes here
        return 0;
    }
    

    That should give you:

    Inside default 
    Inside default
    

    And, due to the noexcept on the move constructor...if you delete the reserve you'd get a move, not a copy:

    Inside default 
    Inside default 
    Inside move with my_int = 0
    

    There's no real advantage with this datatype of a move over a copy. But semantically it could be a big difference if your data type was more "heavy weight" and had a way of "moving" its members that was more like transferring ownership of some pointer to a large data structure.

提交回复
热议问题