Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

What is “const correctness”?

const correctness
0
Posted

What is “const correctness”?

0

A good thing. It means using the keyword const to prevent const objects from getting mutated.

0

A good thing. Const correctness uses the keyword “const” to ensure const objects don’t get mutated. E.g., if function “f()” accepts a “String”, and “f()” wants to promise not to change the “String”, you: • can either pass by value: void f( String s ) { /*…*/} • or by constant reference: void f(const String& s ) { /*…*/ } • or by constant pointer: void f(const String* sptr) {/*…*/ } • but NOT by non-const ref: void f( String&s ) { /*…*/ } • NOR by non-const pointer: void f( String* sptr) { /*…*/ } Attempted changes to “s” within a fn that takes a “const String&” are flagged as compile-time errors; neither run-time space nor speed is degraded. Declaring the “constness” of a parameter is just another form of type safety. It is almost as if a constant String, for example, “lost” its various mutative operations. If you find type safety helps you get systems correct (it does; especially in large systems), you’ll find const correctness helps also.

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123