1
#include <vector>
#include <iostream>
using namespace std;

struct foo
{
    //constructor 1
    foo() { std::cout << "foo()" << endl; }
    ~foo() { std::cout << "~foo()" << endl; }

    //constructor 2
    foo(const foo&) { std::cout << "foo(const foo&)" << endl; }

    //constructor 3
    foo(foo&) { std::cout << "foo(foo&)" << endl; }

    //constructor 4
    foo(foo&&) { std::cout << "foo(foo&&)" << endl; }
};

int main()
{
    std::vector<foo> v;
    foo f0; // constructor 1 is be called

    v.push_back(f0); // constructor 2 is be called

    foo f1 = f0; // constructor 3 is be called

    cout << "-Action-4-" << endl;
    v.push_back(foo{}); // constructor 1,4,2 is called and 2 Desctrunctors

    cout << "Destructors will be called" << endl;
    return 0;
}

Output of the code

The above code snippet calls contructor thrice for Action 4. Can somebody explain why?

1) for foo f0; constructor 1 (Default Constructor) is called

2) for v.push_back(f0); constructor 2 is be called because push_back overloaded for const foo&

3) foo f1 = f0; constructor 3 is called because of assignment operator prefer Lvalue reference foo&

4) v.push_back(foo{}); constructor 1,4,2 is called and 2 Destructors Please explain this behaviour.

Modifying code as std::vector v; v.reserve(10); has done the trick, Now action 4 calls constructor 1,4 is and 1 Destructors

Palash Tichkule
  • 296
  • 4
  • 11
  • 3
    The output of your program is entirely text. Please provide it as text in the question directly instead of providing a link to a picture of the text. – François Andrieux Sep 11 '18 at 14:24
  • 1
    You're not reserving space in the vector so it needs to get resized which causes copies and the constructor calls. – acraig5075 Sep 11 '18 at 14:25
  • 1
    Basically a dupe of [this](https://stackoverflow.com/questions/26740523/vector-push-back-calling-copy-constructor-more-than-once). – NathanOliver Sep 11 '18 at 14:25
  • 2
    And make `foo(foo&&) noexcept`... – Howard Hinnant Sep 11 '18 at 14:26
  • 4
    Because without `noexcept`, `std::vector` will prefer to use copy constructors when reallocating storage. – HolyBlackCat Sep 11 '18 at 14:27
  • https://stackoverflow.com/users/1332041/acraig5075 Got it, adding v.reserve(10); actually worked. Now action 4 calls , constructor 1 & 4 (as expected) is called and 1 Desctrunctors. Thanks!! – Palash Tichkule Sep 11 '18 at 14:40
  • You can step through your code in a debugger and also set breakpoints on every constructor, then you get a full view of why your used STL behaves this way. – Werner Henze Jan 14 '19 at 20:13

0 Answers0