October 03, 2006
The question behind the question
How often has someone asked you how to do something and your reaction has been "Why would anyone want to do that?" In my experience, such a reaction is often a signal that the questioner is asking the wrong question.
Such a question showed up today in one of the C++ newsgroups. The questioner wanted to know how to allocate memory, put its address into a pointer to const, and then use the pointer to change the memory.
That's almost surely a mistake. The whole purpose of having a pointer to const is to be able to promise that the pointer won't be used to change the memory; so using that pointer to change it defeats the purpose. It's misusing the abstraction.
The straightforward answer to the question would be to use a const_cast to cast the pointer into a plain pointer, then use that pointer to change the memory. But before suggesting such a course of action, I would first want to know what the original problem was.
The problem might come from a desire to avoid changing the memory in one part of the program, even though it's necessary to change it in another part. In that case, why not have two pointers?
T* p = new T; const T* cp = p;
This way, you can make cp available to the part of the program that modifies the memory, and use p when you want to promise that the memory won't change.
This suggestion is speculation, of course. My point is that when something feels wrong about a question, that's a good time to look for the question behind the question.
Posted by Andrew Koenig at 01:44 PM Permalink
|