重载all-const类型的复制赋值运算符的正确方法是什么?

Nee*_*eed 0 c++ overloading operator-keyword

假设我有这样的结构:

struct Foo
{
  const int bar;
  const char baz;

  Foo& operator=(const Foo& other)
  {
    memcpy(this,&other,sizeof(Foo)); //How am I supposed to write this decently?
    return *this;
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望Foo的所有字段都是final,我希望Foo类型的变量与其他原始值类型一样.说,int,当然我们可以写这样的东西:

 int i = 0;
 i = 42;

 Foo foo = {007,'B'}
 foo = {42,'X'}
Run Code Online (Sandbox Code Playgroud)

然而,对于我可怜的Foo类型,我是否必须使用memcpy这样的方法来解决类型安全检查?我知道我可以删除const修饰符,将字段标记为私有并添加一些getter,但这不是重点.我只想知道是否有一种不错的方式来编写=运算符的内容.

提前致谢!

~~~~~

查看以下示例:

//If the = op is not implemented, this won't compile
Foo stat;
for(int i=0;i!=100;++i)
{
  stat = func(i);
  if(stat.bar == 0)...
}

//But weird thing is, if I declare the 'stat' inside the for block, it works just fine with gcc
for(int i=0;i!=100;++i)
{
  Foo stat = func(i); 
  //printf("%p\n",&stat); => same variable same address!!
  if(stat.bar == 0)...
}
Run Code Online (Sandbox Code Playgroud)

这对你有意义吗?

Kon*_*lph 6

在C++中,复制赋值对于所有const类型都没有意义.不要实现它.

不要使用清一色const类型的地方是有道理的,但要知道,这种类型将不会表现得像int是因为int在C++中根本就没有const,除非你声明它如此.