c++ - When copy constructor or assignment constructor is called? -
triny quiz web , see code. result prints 02
which means default copy constructor used list initialization while assignment constructor used vector. why?
#include <algorithm> #include <iostream> #include <list> #include <vector> class int { public: int(int = 0) : m_i(i) { } public: bool operator<(const int& a) const { return this->m_i < a.m_i; } int& operator=(const int &a) { this->m_i = a.m_i; ++m_assignments; return *this; } static int get_assignments() { return m_assignments; } private: int m_i; static int m_assignments; }; int int::m_assignments = 0; int main() { std::list<int> l({ int(3), int(1) }); l.sort(); std::cout << (int::get_assignments() > 0 ? 1 : 0); std::vector<int> v({ int(2), int() }); std::sort(v.begin(), v.end()); std::cout << (int::get_assignments() > 0 ? 2 : 0) << std::endl; return 0; }
which means default copy constructor used list initialization while assignment constructor used vector
if remove std::sort(v.begin(), v.end());
instruction program prints 00
. assignment operator used sorting.
note: list can sorted modifying pointers (so l.sort()
doesn't require operator=
).
Comments
Post a Comment