[C++] Ce este 'mutable' in C++?

Despre limbajul de programare C++ si biblioteca standard STL (forum moderat)
Post Reply
User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi
Contact:

[C++] Ce este 'mutable' in C++?

Post by Ovidiu Cucu » 17 Jun 2011, 14:14

Intrebare
Ce este mutable in C++?

Raspuns
Specificatorul mutable, aplicat unei date membru al unei clase permite modificarea ei intr-un obiect constant.

Exemplu

Code: Select all

class A
{
public:
   A() : x(0), y(0) {}
   int x;
   mutable int y;
};

int main()
{
   const A a; // declare constant object
   a.x = 1;   // Error: cannot assign to a variable that is const
   a.y = 1;   // OK: mutable member can be modified
}
De asemenea, o data membru mutable poate fi modificata intr-o functie membru const.

Code: Select all

class A
{
   int x;
   mutable int y;
public:
   A() : x(0), y(0) {}
   void test_modify_x(int i) const
   {
      x = i; //  Error: l-value specifies const object
   }
   void test_modify_y(int i) const
   {
      y = i; // OK: A::y is 'mutable'
   }
};
Note
  1. mutable nu se aplica membrilor declarati const sau static.
    Exemplu

    Code: Select all

    class A
    {
       mutable static int m; // Error: illegal storage class
       mutable const int n;  // Error: illegal storage class
       // ...
    };
  2. mutable a fost introdus pentru a se evita (atunci cand musai e nevoie) casting away const-ness care poate cadea in categoria undefined behavior in incercarea de a modifica un obiect constant.
    Exemplu

    Code: Select all

       // simplified, just to show the idea.
       const char* name = "programmer";
       char* p = const_cast<char*>(name);
       p[0] = 'b'; // <-- Bang! (although there is no compiler error) 
Resurse
  • ISO/IEC 14882:2003 Programming languages — C++
  • Bjarne Stroustrup — The C++ Programming Language



Post Reply