[英]How does a const member get set in C++ copy-swap idiom?
一个简单的复制交换设置。 不担心移动运营商。 constmem
有一个名为x
的const
成员。 使用复制赋值运算符时,看起来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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.