const 成员如何在 C++ 复制交换习语中设置?

How does a const member get set in C++ copy-swap idiom?

一个简单的复制交换设置。不担心移动操作员。 constmem 有一个名为 xconst 成员。使用复制赋值运算符时,看起来 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;
}

这一行:

constmem c = a; 

调用operator=

此语法只是 copy-initialization 的另一种形式,它实际上调用了复制构造函数。