14

What are the known shortfalls of const in C++ and C++0x?

11
  • 3
    I think they're useful because make the code easier to understand. Commented Jan 12, 2011 at 14:28
  • 9
    Need to state a question before you'll get your answer, methinks Commented Jan 12, 2011 at 14:31
  • The only problem I see with const is that its readiness and undertandiness varies widely depending on the level of the C++ programmer, (some confusion about to which element const does apply in a complex declaration, for instance). Besides it is part of the language, and should be used - as long as the book from B.Stroustrup has been read :-) Commented Jan 12, 2011 at 14:37
  • @Vilx don't you think that "while(x < ThingsToDo)" has much more sense than "while(x < 314145.315)"?? Commented Jan 12, 2011 at 14:38
  • 5
    Interesting to see how many times this question gets closed and reopened. Commented Jan 12, 2011 at 16:59

13 Answers 13

59

The only thing wrong with const is that it is seriously underrated by to many developers. It's one of the best tools in C++'s toolbox, very sharp, and yet not dangerous to cut yourself with.

Sign up to request clarification or add additional context in comments.

1 Comment

"But what made those who had laughed at me stop laughing was when, after several days, it became obvious that some several very hard to reproduce bugs which a few of my coworkers were desperately looking for had disappeared." (from chat)
54

The main problem is that you have to write it. It should be the default, and all mutable variables or parameters should be specified explicitly.

10 Comments

Can’t upvote this enough. Even though (or because) it would wreak havoc with most programmers’ preconceptions.
Except for two things: The majority of variables are created to be written to. Having them all read only by default creates more work. Also the C and C++ language philosophy is that the programmer knows what they're doing and the language shouldn't prevent you from doing what ever you want.
@Jay “The majority of variables are created to be written to.” – Once. Rarely do I change the value of a variable after its first assignment (containers are kind of an exception).
You're never going to find that one way or the other is better. Some objects you create for reading/writing (loop counters, iterators, containers, streams, most strings) and others you only assign to once -- actually, I can't think of any examples for that one. Why are your one-time writes not constant initialisations?
wow, i totally missed your answer when i wrote my own (now deleted, was saying the same). One reason I deleted mine is that I can't imagine it's a sane default for local variables. But I definitely can imagine it's sane for by-value parameters. So maybe making parameters const by default, unless you put the "mutable" keyword?
|
19

What's wrong with const is that many programmers don't seem to be able to understand it completely, and a "half-const-correct" project simply does not work. This is what you need to know:

  1. Foo vs. const Foo (or Foo const)
  2. Foo& vs. const Foo& (or Foo const&)
    • references-to-const bind to all kinds of things, while references-to-non-const don't
  3. Foo* vs. const Foo* (or Foo const*)
    • pointer variables can also be Foo* const and const Foo* const (or Foo const* const)
  4. void Foo::mutator() vs. int Foo::accessor() const
    • but pointer members inside const member functions still point to non-const objects
    • so we can accidentally return non-const data from a const-function
  5. iterator vs. const_iterator
    • iterator variables can also be const iterator and const const_iterator

Migrating to C++ from a language that has no const concept is quite hard, any many fail to see the point.

7 Comments

Nit-picking: references to objects can't be const, but references can reference const objects. (Most people know what you mean, but the distinction is more important with pointers, where we have both const pointers and pointers to const.)
@Phil: Right, I changed the relevant parts from English to C++ ;-)
That many programmers don't understand it is not a problem with const. It's a problem with the programmers, and the seriously pathetic state of programming education across the Western world.
@Chris: Thanks for catching that!
@OverTheEdge I suggest you buy "Effective C++" (3rd Edition) by Scott Meyers. Item 3 devotes 10 pages to the topic.
|
17

The two main issues that I have seen frequent complaints about in newsgroups, are

I think the latter could/should be supported by the language.

Possibly in conjunction with support for covariant member function implementations, because both need some way to pick up the type of the this pointer.

A third issue is that

Cheers & hth.,

14 Comments

Which Microsoft APIs are not-const-aware? IIRC the Windows API uses LPCTSTRs, MFC uses const correctly IIRC, etc. I can't think of any.
@Rup: Many Microsoft APIs don't use a lot of const. When was the last time you saw a const HANDLE? Or a const IDirect3DDevice9*? Microsoft uses const for strings and that's about it.
@DeadMG: A HANDLE is an opaque object that you cannot modify anyway without using API functions. For the COM interfaces they use attributes like [in] and [out]. And for most other C types, they do use const.
Perhaps it's not purely Win32 but COM's BSTR can't be a const (since it's a typedef which doesn't allow putting the const on the correct part of the type).
+1 for "The need to define both const and non-const version of a method." !
|
3

The problem with const is the programmers that use it incorrectly our inconsistently

Comments

3

One thing that is "wrong" is that you cannot convert T** to T const * const * which should be allowed because it is not dangerous. Not allowing T** to convert to T const ** is correct, that conversion is not valid.

I have sometimes mentioned that const actually is a cheap way to "split" your interface into read-only methods and write methods. It would probably be impractical in C++. It would be more practical in Java to have ReadOnly versions of collections though, where they don't have const and where their collection types are more object-orientated.

const-ness does not propagate: The issue here is that if I pImpl my class, the constness is not "checked" by the compiler, i.e. my interface class can have a "const" method call a non-const method on the pImpl and the compiler won't complain. That is because the only thing my const method is guaranteed not to do is change the pointer to point to a different object, and my pImpl is never going to change. It could even be a const pointer (not pointer to const).

The lack of proper co-variance between shared_ptr<T> and shared_ptr<const T> might be an issue too, although in general I have seen that not to be the problem, but that developers usually typedef their shared_ptrs and rarely typedef the shared_ptr to const. And they will sometimes pass const shared_ptr<T> & and think that they are passing a shared pointer to a const T (as with const T*) which they are not.

3 Comments

"cannot convert T** to T const * const *" - this part is wrong (at least with the compilers i use); i recall it was an annoyance in C but C++ got it right.
you can have const-checking for pimpl class, no big deal ... for example look at Qts use of pimpl classes.. (they use 2 private pimpl-accessor functions (const/nonconst) for accessing the pimpl object, if you want to make sure you dont access the pimpl object without using these functions (und thus circumventing the const-check), you can use a fully opaque void* for the pimpl object, and add some reinterpret_casts to the acessor functions (look at the implemtation of i.e. Q_DECLARE_PRIVATE)
@anatolyg: You are correct. The first paragraph doesn't describe something "wrong" with const because it's not true. See 4.4 [conv.qual] / 4 of ISO/IEC 14882:2003.
1

"issues"?

If you aren't going to be modifying the value of a passed pointer (it is used purely for pass-by-reference input to a function), mark it is const. Ditto if the value of a particular variable will not change after its initialization. If a function is safe to call on a const class instance, mark it const too. The more items are correctly annotated const, the less likely you are to inadvertently make a mistake and the more optimizations the compiler will be theoretically able to perform in the absence of complete knowledge (such as when compiling with only function prototypes available).

Modern versions of gcc have support for warning when you try to cast a const variable to a non-const one. I suggest you leave those warnings enabled.

The only thing to watch out for is exactly what you are marking const; const char * foo() is not the same as char * foo() const.

1 Comment

I'm not asking how to use const. I already know how to use const. I was looking for problems with const.
1

const is theoretically good but, in practice bad. Too models are possible.

Deep const, const X* Y::GetX() const

Shallow const, X* Y::GetX() const

Which is correct? Also does const apply to the logic or to the implementation. What about on demand (lazy) creation? There are often good reasons not to set everything up in the constructor.
const X* Y::GetX() const
{ if (!x) m_x=new X(); return m_x; }
This is const in spirit but not by the letter of the law. And sure you can use mutable or const_cast, but this disarms const or leads to ugly confusing code.

So the idea of const is great but the implementation is off. In a meta-verse there is a better implementation. In that universe, a variables value may be unknown and setting it does not violate const.

1 Comment

What would you expect hypothetically to be safe and clear semantics of returned pointer in X* Y::GetX() const? Should it be const X*? Or X * const? Or even const X * const? It's ambigous.
0

One problem is that the language also lets you const_cast it away, which defeats the purpose of using const in the first place.

10 Comments

Not this again... const would be useless without the ability to cast it away, because in real world code, you have to deal with APIs written by programmers who don't understand const correctness (or way back in a time were const wasn't part of C++ yet).
@FredOverflow: but maybe it would be a good thing if those programmers were hunted down and killed by people who can no longer work around their broken code by const-casting? ;-) Regarding ancient code - something can still be a shortfall of the language even if the motivation for the shortfall is to support pre-standard code and/or conventions. For instance you might think that the automatic conversion to void* is a shortfall of C++: it's needed for e.g. std::memcpy, but in the context of C++, functions shouldn't be designed to silently accept any pointer regardless of type-safety.
@Dave: Why did the developer cast it away? Most casts are evil and/or unnecessary. If you don't trust programmers, C++ is the wrong language.
@Steve: How would killing them now solve the problem? Let the damn terminators do the job thoroughly and wipe the non-believers from history!
No, although const_cast is legal, writing to an object-created-as-const (even if you've casted away the constness on the variable) is not legal.
|
0

Most of the answers below state things such as "what is wrong with const is that X people do Y". Those are not answers but symptoms. Those are not things wrong with const. There's barely any wrong thing with const... Those are things wrong with people who can't RTFM.

Comments

0

const is great. const is important. const-correctness is necessary condition for an API to be good.

Yet there are two issue I've had with const, repeatedly.

  • There's no way to mark a variable as const retroactively. You must either declare a variable code, in which case you have to initialize it immediatly. What if the initialization code contains an if, though? You have the choice of either omitting the const (undesirably), using operator ? instead of if (harms readability). Java get's that right, BTW - const variables don't have to be initialized right away, they just have to be initialized before they're first read, and they have to be initialized in all branches of an if.

  • There's no way to specifiy that an object passed by reference to a function won't change for the duration of the function call. const T& t does not mean that the object pointed to by t won't change, but only that the reference t cannot be used to change it. The compiller still has to assume that any function call which it does not see into might change the object. It some cases, that prevents quite a few optimizations.

Comments

0

Another problem that has not been mentioned yet is the possibility for a badly designed interface to subvert const (even in the absence of casts).

Example:

class TreeNode { public: TreeNode& getParent() const { return *parent_; } TreeNode& getLeft() const { return *left_; } TreeNode& getRight() const { return *right_; } private: //TreeNode has a pointer to the Tree to enable navigation of the tree. //Assume that other design constraints mean that this must be a pointer //rather than a reference. TreeNode* parent_; TreeNode* left_; TreeNode* right_; }; //This function demonstrates the ability for const to be subverted. TreeNode& remove_const(TreeNode const& toRemoveConstFrom) { TreeNode& parent(toRemoveConstFrom.getParent()); TreeNode& leftChild(parent.getLeft()); TreeNode& rightChild(parent.getRight()); return &toRemoveConstFrom == &leftChild ? leftChild : rightChild; } 

The intransitive nature of const means that it is possible to have an interface where a non-const reference to an object can be obtained from a const reference to an object. This is something to be careful of when designing interfaces.

Comments

-2

One thing is that it is still possible subvert it. i.e. it is still legal to do something like this:

void foo(const inst& x) { const_cast<int&> x = 3; } 

You can even use things like memset to subvert it without an explicit const_cast.

This is a trade-off between having the compiler enforce const and allowing some flexibility for non const aware interfaces.

Which leads to another limitation, in that it has not been universally embraced, which is in part due to another problem, which is that using const is an all-or-nothing proposition. If you start using it, you will need to propagate it throughout your code base.

3 Comments

No, this is possibly Undefined Behaviour (if the original object was created const) and in the context of this function must be assumed to be. A const_cast is legal, but writing to an object created as const, whether you've casted away the constness or not, is illegal.
Well, yes, but if you think as const in terms of a contract or promise that I won't change it (even if it was non-const before), then it is possible to break it.
But you can make promises in form of comments in every language and then subvert them. const however is a non-comment/builtin tool that forces you to not break the contract by default, whereas in non-const-correct languages you may accidentally change something documented as invariant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.