asignment to the const member (g++ vs VC)

V

viki

How exactly do I assign to the member declared as const, portably ?
Casting the lhs compiles in VC but not in g++.

Thanks
V.M.
(This is c++ technical question without "design" dimension ).
 
J

Jim Langston

viki said:
How exactly do I assign to the member declared as const, portably ?
Casting the lhs compiles in VC but not in g++.

Thanks
V.M.
(This is c++ technical question without "design" dimension ).

You can't portably. If it is a constant variable, it can only be
initialized. Changing it after initialization by any means is undefined
behavior. Just because VC may allow it doesn't mean that it's right or that
it'll always work, even in VC.

If you want to change a const member, then don't make it const.
 
G

gpderetta

How exactly do I assign to the member declared as const, portably ?

You don't. AFAIK, casting away constness is UB (except for references
to const that actually point to non const objects).
Casting the lhs compiles in VC but not in g++.

struct a {
const int i;
};

int main() {
a x = { 0 };
const_cast<int&>(x.i) = 10;
}

This compiles with g++-4.1.2. But I think it is still UB.
[/QUOTE]
 
J

Juha Nieminen

viki said:
How exactly do I assign to the member declared as const

You don't. consts cannot be assigned to. That's exactly what you are
saying when you are writing the "const" keyword.

If you want to assign to it, don't make it const.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top