Skip to content

Mutable--keyword#8

Open
Butcher3Years wants to merge 9 commits intomainfrom
Mutable--keyword
Open

Mutable--keyword#8
Butcher3Years wants to merge 9 commits intomainfrom
Mutable--keyword

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

🔄 C++ Mutable Keyword: Const Methods + Lambda Mastery

Mutable in Classes (Const Methods)

mutable lets specific data members change even in const objects/methods:

class Player {
private:
    int health{100};
    mutable int cacheHits{0};  // Cache/counter - logically const
    
public:
    int getHealth() const {    // Promised not to change *logical* state
        ++cacheHits;           // ✅ Allowed: doesn't affect health
        return health;
    }
};

## 🐑 C++ Lambda Mutable: Value vs Reference Capture Deep Dive

### Capture by Value (Default: const copy)
```cpp
int counter = 0;

// ❌ Regular value capture = IMMUTABLE copy
auto lambda1 = [counter]() { 
    // counter = 10;  // ERROR: captured copy is const
    return counter;
};

// ✅ mutable = MODIFIABLE copy  
auto lambda2 = [counter]() mutable {
    counter = 10;      // Modifies lambda's INTERNAL copy only
    return counter;    // Returns 10 on every call after first
};

Capture by Reference (Always mutable)

int counter = 0;

// ✅ Reference = Direct access to original variable
auto lambda3 = [&counter]() { 
    counter = 20;      // Modifies ORIGINAL variable
    return counter;    // Reflects external changes
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant