Suppose I have such a struct:
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;
}
}
I want all fields of Foo to be final, and I want the variables of type Foo to behave just like other primitive value types. Say, int, surely we can write stuff like this:
int i = 0;
i = 42;
Foo foo = {007,'B'}
foo = {42,'X'}
Yet for my poor Foo type, do I have to resort to means like memcpy to work around the type safety check? I know I could drop the const modifiers, mark the fields private and add some getters, but that’s not the point. I just wanna know if there is a decent way to write the content of the = operator.
Thanks in advance!
~~~~~
Check out the following examples:
//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)...
}
Does that make any sense to you?
There’s no pretty way, and I agree with other answers that you should reconsider the design.
But if you still think it’s the least evil for your problem, a couple more options:
Or