Consider this code:
#include <iostream>
#include <vector>
#include <initializer_list>
using namespace std;
struct BigInteger
{
vector<int> arr;
BigInteger()
{
cout << "default constructor" << endl;
this->arr.push_back(0);
}
BigInteger(initializer_list<int> il)
{
cout << "initializer_list constructor" << endl;
for (const int x : il)
{
arr.push_back(x);
}
}
BigInteger(const BigInteger& obj) //copy constructor
{
cout << "copy constructor" << endl;
this->arr = obj.arr;
}
BigInteger(BigInteger&& obj) //move constructor
{
cout << "move constructor" << endl;
swap(*this, obj);
}
~BigInteger() //destructor
{
cout << "destructor" << endl;
arr.clear(); //probably because of RAII, I guess I don't have to write this
}
BigInteger& operator=(const BigInteger& rhs)
{
cout << "copy assignment" << endl;
BigInteger tmp(rhs);
this->arr = tmp.arr;
return *this;
}
BigInteger& operator=(BigInteger&& rhs) noexcept
{
cout << "move assignment" << endl;
swap(*this, rhs);
return *this;
}
};
int main()
{
BigInteger another = BigInteger({0, 1, 2});
}
So, I’m creating a temporary object BigInteger({0, 1, 2})
and then doing the move assignment for my class instance a
(theoretically). So expected output is:
initializer_list constructor //creating temporary object
default constructor //creating glvalue (non-temporary) object
move assignment
destructor
But the output is:
initializer_list constructor
destructor
And I don’t even understand why is that happening. I suspect that operator=
is not the same as initialization, but still I don’t understand how my object is constructed.
>Solution :
Primarily, move assignment operator isn’t called because you aren’t assigning anything. Type name = ...;
is initialisation, not assignment.
Furthermore, there isn’t even move construction because BigInteger({0, 1, 2})
is a prvalue of the same type as the initialised object, and thus no temporary object will be materialised, but rather the the initialiser of the prvalue is used to initialise another
directly, as if you had written BigInteger another = {0, 1, 2};
(which is incidentally what I recommend that you write; There’s simply no need to repeat the type).
I suspect that operator= is not the same as initialization
This is correct. Assignment operator and initialisation are two separate things. You aren’t using the assignment operator in this example.