Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which cases is the copy constructor called, if a container is copied

I tested the following code:

#include <iostream>
#include <vector>

class foo {
public:
    int m_data;
    foo(int data) : m_data(data) {
        std::cout << "parameterised constructor" << std::endl;
    }
    foo(const foo &other) : m_data(other.m_data) {
        std::cout << "copy constructor" << std::endl;
    }
};

main (int argc, char *argv[]) {
    std::vector<foo> a(3, foo(3));
    std::vector<foo> b(4, foo(4));
    //std::vector<foo> b(3, foo(4));
    std::cout << "a = b" << std::endl;
    a = b;
    return 0;
}

I get

   parameterised constructor
   copy constructor
   copy constructor
   copy constructor
   parameterised constructor
   copy constructor
   copy constructor
   copy constructor
   copy constructor
   a = b
   copy constructor
   copy constructor
   copy constructor
   copy constructor

However, if I replace std::vector<foo> b(4, foo(4)); by std::vector<foo> b(3, foo(4)); the copy constructor is not called by a = b and the output is

parameterised constructor
copy constructor
copy constructor
copy constructor
parameterised constructor
copy constructor
copy constructor
copy constructor
a = b

Why is in this case the copy constructor not called?

I'm using g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1

like image 795
Michael Avatar asked Apr 25 '12 10:04

Michael


1 Answers

In the first case, a needs to grow when you assign to it, which means that all its elements must be reallocated (and therefore destructed and constructed).

In the second case, a does not need to grow, hence the assignment operator is used.

See http://ideone.com/atPt9; adding an overloaded copy assignment operator that prints a message, we get the following for the second example:

parameterised constructor
copy constructor
copy constructor
copy constructor
parameterised constructor
copy constructor
copy constructor
copy constructor
a = b
copy assignment
copy assignment
copy assignment
like image 191
Oliver Charlesworth Avatar answered Oct 12 '22 22:10

Oliver Charlesworth