C++
  Home arrow C++ arrow Page 5 - Who`s Afraid to Be Const Correct? Take You...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

Who`s Afraid to Be Const Correct? Take Your Object`s Bits Literally
By: J. Nakamura
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 2
    2005-08-23

    Table of Contents:
  • Who`s Afraid to Be Const Correct? Take Your Object`s Bits Literally
  • Bitwise Copy Construction
  • Bitwise Constness
  • Make Your Interface Conceptually Const.
  • Const and Mutable

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Who`s Afraid to Be Const Correct? Take Your Object`s Bits Literally - Const and Mutable


    (Page 5 of 5 )

    Conceptually we can also reason that const should guarantee the user that no changes were made to the object that are visible to the user (when you are not caught stealing, is it a crime? When a tree falls in the forest does it make a sound?). If we consider MyClass again that wraps *m_pLabel, we can easily add a function that returns the length of that label:

    class MyClass {

    public:

     ...

     size_t  LabelLength() const { return strlen(m_pLabel); }

     ...

    };

    Instead of calculating the length of the label every time the function is called, we could cache its length whenever it is calculated… and let’s assume that we only want to calculate its length when this is requested.

    This is what MyClass could look like:

    class MyClass {

    public:

     // ctor makes m_pLabel point to a copy of label MyClass(char const *label)

      : m_LabelLength(-1)

    {

      m_pLabel=new char[MAX_LABEL_LEN];

      SetLabel(label);

      }

     

    ~MyClass() {

     try { delete m_pLabel; }

     catch (...) { }

     }

     

     char const* GetLabel() const { return m_pLabel; }

     

     void SetLabel(char const *label) {

      if (0 != label)

      {

    assert( (int)(strlen(label)+1)

     < MAX_LABEL_LEN);

    (void)sprintf(m_pLabel, “%s”, label);

    }

       else

        m_pLabel[0]=’’;

    m_LabelLength = -1; // calculate length when needed

    }

     

    size_t GetLabelLength() const {

     if (-1 == m_LabelLength)

    m_LabelLength = strlen(m_pLabel); // ERROR!

     return m_LabelLength;

    }

     

    private:

     static int const MAX_LABEL_LEN;

     char *m_pLabel;

    };

    int const MyClass::MAX_LABEL_LEN = 1024;

    This class may look a bit awkward, but remember that it just serves as an example. Notice how bitwise constness prevents us from caching the length of the label, while conceptually it makes perfect sense. After all, the user won’t notice any changes made to the private data members of this class; its outward appearance (the label) remains exactly the same.

    If only we could make an exception for the class itself and allow it to modify its private data members in a const member function.

    This is exactly what the keyword ‘mutable’ allows us to do. It can be applied to non-static data members to free them from bitwise constness. It is a very handy keyword that makes your life a bit easier as far as creating const-correct classes are concerned. And as long as your classes are const-correct, others using your classes can be assured that they can maintain const-correctness themselves.

    class MyClass { public:

     ...

    private:

     ...

     mutable char *m_pLabel;

       };

    If you are still in doubt whether or not your code should be const correct, then please read Item 21 ‘Use const whenever possible’ [Meyers] and try Item 43 ‘Const-Correctness’ [Sutter]. The const keyword was introduced over a quarter of a century ago; make sure you don’t miss out on taking advantage of its value!

    References

    [K&R] – Kernighan and Ritchie

    “The C Programming Language” – ISBN 0131103628

    [Meyers] – Scott Meyers

    “Effective C++” – ISBN 0201924889

    item 20 ‘Avoid data members in the public interface’

    item 21 ‘Use const whenever possible’

    [Sutter] – Herb Sutter

    “Exceptional C++” -  ISBN 0201615622

     


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

     

    C++ ARTICLES

    - Paths and Files
    - Directories in C++
    - Focusing on C++ Files
    - Const Correctness in C++
    - Manipulating Streams and Files with C++
    - Streams and Files
    - Multiplying Large Numbers with Karatsuba`s A...
    - Large Numbers
    - Dijkstra`s Shunting Algorithm with STL and C...
    - Brief Introduction to the STL Containers
    - The Standard Template Library
    - Templates in C++
    - C++ Programmer Alerts
    - C++ Programming Tips
    - First Steps in (C) Programming, conclusion






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT