Простая настройка копирования и обмена. Не переживайте по поводу переезда операторов. constmem
имеет члена const
с именем x
. При использовании оператора копирования-копирования, похоже, что x
будет неинициализировано, но каким-то образом оно будет скопировано. Как это происходит?
#include <algorithm>
#include <iostream>
class constmem
{
public:
constmem(std::size_t xx) : x(xx) {
c = new char[x];
}
constmem(const constmem& rhs)
: x(rhs.x)
{
c = new char[x];
}
constmem& operator=(constmem rhs) {
swap(rhs);
return *this;
}
~constmem() { delete [] c; }
const std::size_t x;
char* c;
void swap(constmem& rhs) {
using std::swap;
swap(c, rhs.c);
}
};
int main(int argc, char** argv)
{
constmem a(5);
// output in parens
std::cout << a.x << "(5) " << std::endl;
constmem b(7);
a = b;
std::cout << a.x << "(5) " << std::endl;
constmem c = a; // How does c.x wind up being the same as a.x??!
std::cout << c.x << "(5) " << std::endl;
return 0;
}