tags:

views:

1052

answers:

5

Hi, as a novice C++ programmer there are some constructs that look still very obscure to me, one of these is const. You can use it in so many places and with so many different effects that is nearly impossible for a beginner to come out alive. Will some C++ guru explain once forever the various uses and whether and/or why not to use them?

Long life to StackOverflow

+5  A: 

I found "The C++ 'const' Declaration: Why & How" to be helpful. Hope that helps..

driAn
Thank you, I already read it, but I don't know if it's really exhaustive.
tunnuz
+19  A: 

Trying to collect some uses:

Binding some temporary to reference-to-const, to lengthen its lifetime. The reference can be a base - and the destructor of it doesn't need to be virtual - the right destructor is still called:

ScopeGuard const& guard = MakeGuard(&cleanUpFunction);

Explanation, using code:

struct ScopeGuard { 
    ~ScopeGuard() { } // not virtual
};

template<typename T> struct Derived : ScopeGuard { 
    T t; 
    Derived(T t):t(t) { }
    ~Derived() {
        t(); // call function
    }
};

template<typename T> Derived<T> MakeGuard(T t) { return Derived<T>(t); }

This trick is used in Alexandrescu's ScopeGuard utility class. Once the temporary goes out of scope, the destructor of Derived is called correctly. The above code misses some small details, but that's the big deal with it.


Use const to tell others methods won't change the logical state of this object.

struct SmartPtr {
    int getCopies() const { return mCopiesMade; }
};


Use const for copy-on-write classes, to make the compiler help you to decide when and when not you need to copy.

struct MyString {
    char * getData() { /* copy: caller might write */ return mData; }
    char const* getData() const { return mData; }
};

Explanation: You might want to share data when you copy something as long as the data of the originally and the copie'd object remain the same. Once one of the object changes data, you however need now two versions: One for the original, and one for the copy. That is, you copy on a write to either object, so that they now both have their own version.

Using code:

int main() {
    string const a = "1234";
    string const b = a;
    // outputs the same address for COW strings
    cout << (void*)&a[0] << ", " << (void*)&b[0];
}

The above snippet prints the same address on my GCC, because the used C++ library implements a copy-on-write std::string. Both strings, even though they are distinct objects, share the same memory for their string data. Making b non-const will prefer the non-const version of the operator[] and GCC will create a copy of the backing memory buffer, because we could change it and it must not affect the data of a!

int main() {
    string const a = "1234";
    string b = a;
    // outputs different addresses!
    cout << (void*)&a[0] << ", " << (void*)&b[0];
}


For the copy-constructor to make copies from const objects and temporaries:

struct MyClass {
    MyClass(MyClass const& that) { /* make copy of that */ }
};


For making constants that trivially can't change

double const PI = 3.1415;


For passing arbitrary objects by reference instead of by value - to prevent possibly expensive or impossible by-value passing

void PrintIt(Object const& obj) {
    // ...
}
Johannes Schaub - litb
Can you explain please the first and the third usage in your examples?
tunnuz
"For guaranteeing the callee that the parameter can't be NULL" I don't see how const has anything to do with that example.
Logan Capaldo
oops, i so fail. i somehow started to write about references. thank you so much for moaning :) i'll of course remove that stuff now :)
Johannes Schaub - litb
+6  A: 

I found this to be useful Prashift Const Corectness

kal
Const Correctness is great - I have a printout of it pinned to my tackboard in my office, and I refer to it constantly ;-)
unforgiven3
You're right, this is a great document :)
tunnuz
+5  A: 

There are really 2 main uses of const in C++.

Const values

If a value in the form a variable, member or parameter will not (or should not) be altered during it's lifetime you should mark it const. This helps to prevent mutations on the object. For instance, in the following function I do not need to change the Student intstance passed so I mark it const.

void PrintStudent(const Student& student) {
  cout << student.GetName();
}

As to why you would do this. It's much easier to reason about an algorithmn if you know that the underlying data cannot change. "const" helps, but does not guarantee this will be achieved.

Obviously, printing data to cout does not require much thought :)

Marking a member method as const

In the previous example I marked Student as const. But how did C++ know that calling the GetName() method on student would not mutate the object? The answer is that the method was marked as const.

class Student {
  public:
    string GetName() const { ... }
};

Marking a method "const" does 2 things. Primarily it tells C++ that this method will not mutate my object. The second thing is that all member variables will now be treated as if they were marked as const. This helps but does not prevent you from modifying the instance of your class.

This is an extremely simple example but hopefully it will help answer your questions.

JaredPar
+3  A: 

Take care to understand the difference between these 4 declarations:

The following 2 declarations are identical semantically. You can change where ccp1 and ccp2 point, but you can't change the thing they're pointing at.

const char* ccp1;
char const* ccp2;

Next, the pointer is const, so to be meaningful it must be initialised to point to something. You can't make it point to something else, however the thing it points to can be changed.

char* const cpc = &something_possibly_not_const;

Finally, we combine the two - so the thing being pointed at cannot be modified, and the pointer cannot point to anywhere else.

const char* const ccpc = &const_obj;

The clockwise spiral rule can help untangle a declaration http://c-faq.com/decl/spiral.anderson.html

Steve Folly
I personally always do my const pointers as such:`char const * kpPointer;``char const * const kpPointer;`Reason being, it reads correctly left to right. ("Pointer to a const char", or 'const pointer to a const char"). Maybe that's what your link says; just don't have the time to read it. ;)
Eddie Parker
In a roundabout way, yes it does! The clockwise spiral rule describes it better - start at the name (kpPointer) and draw a clockwise spiral going out through the token, and say each token. Obviously, there's nothing to the right of kpPointer but it still works.
Steve Folly