繁体   English   中英

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

[英]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=

这种语法只是 复制初始化的另一种形式,它实际上调用了复制构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM