|
|
|
|
||||||
![]() |
|
|
LinkBack | Outils de la discussion |
|
|
#1 |
|
Messages: n/a
Hébergeur: |
How can I modify member variable inside class if member function has
const like mem_Func(void) const. Please do not offer the keyword -- mutable. I want to know if keyword -- const_cast can be done. If mutable is only the solution, I will follow not to use const_cast. |
|
|
|
#2 |
|
Messages: n/a
Hébergeur: |
Immortal Nephi wrote:
> How can I modify member variable inside class if member function has > const like mem_Func(void) const. Please do not offer the keyword -- > mutable. Why not? It's meant to be used for member variables that do not affect logical constness. If the member variable you are modifying better not be declared mutable, you probably shouldn't be modifying it in a const member function. > I want to know if keyword -- const_cast can be done. Yes it can be used to cast away constness, but it will produce undefined behavior if you use it on an object declared const. > If mutable is only the solution, I will follow not to use const_cast. What is the underlying problem that you are trying to solve? I looks as though you might be headed the wrong direction, and in order to give better advice some additional information about the background would be good. Best Kai-Uwe Bux |
|
|
|
#3 |
|
Messages: n/a
Hébergeur: |
"Immortal Nephi" <Immortal_Nephi@satx.rr.com> a écrit dans le message de news: 1db02a01-0b82-4fb7-b701-ca2a5b183f8a...oglegroups.com... > How can I modify member variable inside class if member function has > const like mem_Func(void) const. Please do not offer the keyword -- > mutable. I want to know if keyword -- const_cast can be done. > > If mutable is only the solution, I will follow not to use const_cast. Ok it is Evil but you can do it. struct EvilClass { void EvilFunct() const; int _a; }; void EvilClass::EvilFunct() const { int& tmp = const_cast<int&>(_a); tmp = 5; // now _a == 5 } You can also define a template function if you have many variables like that. struct EvilClass { void EvilFunct() const; template<typename T> void EvilSet(T const& val, T const& NewVal) const; int _a; }; void EvilClass::EvilFunct() const { EvilSet(_a, 5); // much cleaner but maybe also much evil } template<typename T> void EvilClass::EvilSet(T const& val, T const& NewVal) const { T& tmp = const_cast<T&>(val); tmp = NewVal; } ------------------------ Eric Pruneau |
|
![]() |
| Outils de la discussion | |
|
|