Vorac
Vorac

Reputation: 9124

Why am I forbidden to alter a pass-by-value field?

 1 #include <iostream>                                                             
 2                                                                                 
 3 struct A                                                                        
 4 {                                                                               
 5     int b = 30;                                                                 
 6 };                                                                              
 7                                                                                 
 8                                                                                 
 9 int main()                                                                      
10 {                                                                               
11     A a;                                                                        
12     std::cout << a.b << '\n';                                                   
13     [=] ()                                                                      
14     {                                                                           
15         a.b = 22;                                                               
16     }();                                                                        
17     std::cout << a.b << '\n';                                                   
18 }

$ nano main.cpp && g++ -Wall -std=c++20 main.cpp && ./a.out 
main.cpp: In lambda function:
main.cpp:15:13: error: assignment of member 'A::b' in read-only object
   15 |         a.b = 22;
      |         ~~~~^~~

Wyt?? A.b isn't even a pointer. What am I missing?


The question is dupe - as expected. To summarize the answers - because it is what it is. <rant> The standards community is finally realizing default-const is the way to go but can't change older rules brought around from C.</rant>

Upvotes: 0

Views: 93

Answers (0)

Related Questions