May 18, 2019 at 9:57pm UTC
Dear C++ Community
I found an interesting question in my test about describing a circumstance in which a copy constructor and an assignment operator for a class would be invoked. I did not understand this question after researching it.
Last edited on May 19, 2019 at 5:24pm UTC
May 18, 2019 at 11:59pm UTC
I am right in assume they want a real-life example?
As real-life as a contrived example can be,
copy-and-swap comes to mind:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <iostream>
#include <utility>
struct X
{
explicit X(int n)
: pn(new int {n}) {}
~ X() { delete pn; }
X(X const & other)
: pn(new int {other.get()}) {}
X& operator =(X lhs)
{
using std::swap;
swap(lhs.pn, pn);
return *this ;
}
int get() const { return *pn; }
private :
int * pn = nullptr ;
};
int main()
{
X x{2}, y{4};
// conventionally, y is copied into the parameter of the operator=
x = y;
std::cout << x.get() << ' ' << y.get() << '\n' ;
}
http://coliru.stacked-crooked.com/a/a9ce856c1dbbf2aa
Last edited on May 19, 2019 at 12:00am UTC