effective c++ 条款3 use const whereever you can

1 const 传达的意思应该是这个变量是常量不能更改

2 const 在 * 左边表示数据是const,在右边表示指针是const

   //
   char greeting[] = "hello";

   char* p = greeting;

   //const *: const data
   //* const: const pointer
   char const *p1 = greeting;    // const data
   char * const p2 = greeting;   // const pointer
   const char * const p3 = greeting; // const data and pointer

   //not correct p1 is const data
   //(*p1)++;

   //correct p1 is const data
   p1++;

   //correct p2 is const pointer
   (*p2)++;

   //not correct p2 is const pointer
   //p2++;

   //not correct p3 is  const data and pointer
   //(*p3)++;

   //not correct p3 is  const data and pointer
   //p3++;

  3

//1 const return value avoid the error like this
// if( a+b = c) {...}
//2 const parameter
// it can avoid unintentioned change of parameter inside the function
const Rational operator+ (const Rational& lhs, const Rational& rhs)
{
   Rational tmp;
   tmp.real = lhs.real + rhs.real;
   tmp.img = lhs.img + rhs.img;

   return tmp;
}

class Rational
{
   public:
      float real;
      float img;

      Rational():real(0),img(0){};

};

  4 const 成员函数

声明方式

作用

ConstMemberFunc.h

//---------------------------------------------------------------------------

#ifndef ConstMemberFuncH
#define ConstMemberFuncH
//---------------------------------------------------------------------------

#include <cstddef>    //for std::size_t

//1 const member function is used to operate const object
// eg. we have a class Textblock and it has a operator[] which is const
// when we have a const Textblock, the operator[] const will be used

//2
// a  const member function can change static class member
// b  const member function can not change non-static class member
// c  use mutable decleared variable can be changed in const member function

//3 const member function can only call const member function
//                        can not call non-const member function

//4 const object can only call const member function
//  const object can not call non const member function
class TextBlock
{
   public:

     static int TextBlockStaticNum;

      char* text;

       //1 const member function is used to operate const object
       //  eg. we have a class Textblock and it has a operator[] which is const
       //  when we have a const Textblock, the operator[] const will be used
      const char& operator[](std::size_t position) const
      {
         return text[position];

        //validate 3
        //not correct
        //3 const member function can only call const function
        //                        can not call non-const  function
       // print(); is the non-const function of vector

      };

      char& operator[](std::size_t position)
      {
         //return text[position];

        //call const operator[] and remove constness for return
        //not recommended
         return const_cast<char&>(                                      // remove the const from the return of const []
                                   static_cast<const TextBlock&>(*this) // add const to *this
                                                             [position] // call const []
                                   );
      };

      //2
      // a  const member function can change static class member
      // b  const member function can not change non-static class member
      // c  use mutable decleared variable can be changed in const member function
      int nonStaticOrMutable;
      mutable int textLen;
      const void constMemberFunctionTest(int Num) const
      {
         //a change static member
         TextBlockStaticNum = 1;

         //b
         //not correct
         //can not change non-static class member
         //nonStaticOrMutable = 1;

         //c  use mutable decleared variable can be changed in const member function
         textLen = 2;

      };

      //3 const member function can only call const member function
      //                        can not call non-const member function
       void print()
       {
         ;
       }

      TextBlock( char charArray[])
      {
          text = charArray;
          TextBlockStaticNum = 0;
          textLen = 0;
          nonStaticOrMutable=0;
      };
} ;

//1 const member function is used to operate const object
// eg. we have a class Textblock and it has a operator[] which is const
// when we have a const Textblock, the operator[] const will be used
//Test function
extern void ConstAndNonConstObjCallConstMemberFunction();

//2
// a  const member function can change static class member
// b  const member function can not change non-static class member
// c  use mutable decleared variable can be changed in const member function
extern void ConstMemFunctionChangeClassMember();

//4 const object can only call const member function
//  const object can not call non const member function
extern void ConstObjCanNotCallNonConstMember(const TextBlock & ctb)
{
    //not correct
    //print is not a const member function
    //ctb.print();

    //correct
    const char t = ctb[0];

};

#endif

 ConstMemberFunc.cpp 

//---------------------------------------------------------------------------

#pragma hdrstop

#include "ConstMemberFunc.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)

#include "ConstMemberFunc.h"

void ConstAndNonConstObjCallConstMemberFunction()
{
   TextBlock tb("test");
   const TextBlock ctb("test");

   //call non const operator[]
   //correct
   tb[0] = ‘1‘;

   //call const operator[]
   //not correct, since ctb is const operator
   //ctb[0] = ‘1‘;
   //normally this is used as a function call
   //e.g. void print(const TextBlock ctb) //we do not change ctb in this function
}

void ConstMemFunctionChangeClassMember()
{
   TextBlock tb("test");
   tb.constMemberFunctionTest(5);

   const TextBlock ctb("test");
   ctb.constMemberFunctionTest(2);
}

  

effective c++ 条款3 use const whereever you can,布布扣,bubuko.com

时间: 2024-10-10 08:33:16

effective c++ 条款3 use const whereever you can的相关文章

Effective C++ 条款3 尽可能用const

1. const可被施加于任何作用域内的对象,函数参数,函数返回类型,成员函数本体.用const修饰指针,如果const出现在*之前,表明指针不能更改所指向的对象的内容,如果const出现在*之后,表明指针只能指向同一块内存.另外int const*p和const int*p含义相同.如果对象成员有普通指针,那么构造该类的一个const对象时,const修饰使得该指针只能指向同一块内存,但指针指向的内容可以改变. 2. 将某些东西声明为const可以帮助编译器侦测出错误用法. 3. 编译器强制实

Effective C++ 条款三 尽可能使用const

参考资料:http://blog.csdn.net/bizhu12/article/details/6672723      const的常用用法小结 1.用于定义常量变量,这样这个变量在后面就不可以再被修改     const int val = 90;      val = 100;   错误 2. 保护传参时参数不被修改,如果使用引用传递参数或按地址传递参数给一个函数,在这个函数里这个参数的值若被修改, 则函数外部传进来的变量的值也发生改变,若想保护传进来的变量不被修改,可以使用const

More Effective C++ 条款35 让自己习惯于标准C++ 语言

(由于本书出版于1996年,因此当时的新特性现在来说可能已经习以为常,但现在重新了解反而会起到了解C++变迁的作用) 1. 1990年后C++的重要改变 1). 增加了新的语言特性:RTTI,namespaces,bool,关键词mutable和explicit,enums作为重载函数之自变量所引发的类型晋升转换,以及"在class 定义区内直接为整数型(intergral) const static class members设定初值"的能力. 2). 扩充了Templates的特性

effective c++ 条款4 make sure that objects are initialized before they are used

1 c++ 类的数据成员的初始化发生在构造函数前 class InitialData { public: int data1; int data2; InitialData(int a, int b) { data1 = a: //this is assignment data2 = b; //this is assignment } /* InitialData(int a, int b):data1(a),data2(b) //this is initial {} */ } 2 不同cpp文

Effective C++ 条款九、十 绝不在构造和析构过程中调用virtual函数|令operator=返回一个reference to *this

  1.当在一个子类当中调用构造函数,其父类构造函数肯定先被调用.如果此时父类构造函数中有一个virtual函数,子类当中也有,肯定执行父类当中的virtual函数,而此时子类当中的成员变量并未被初始化,所以无法调用子类与之对应的函数.即为指向虚函数表的指针vptr没被初始化又怎么去调用派生类的virtual函数呢?析构函数也相同,派生类先于基类被析构,又如何去找派生类相应的虚函数? 2.做法:将子类的某个函数改为non-virtual,然后在子类构造函数中传递参数给父类函数.然后父类的构造函数

Effective C++ 条款11,12 在operator= 中处理&ldquo;自我赋值&rdquo; || 复制对象时不要忘记每一个成分

1.潜在的自我赋值     a[i] = a[j];     *px = *py; 当两个对象来自同一个继承体系时,他们甚至不需要声明为相同类型就可能造成别名. 现在担心的问题是:假如指向同一个对象,当其中一个对象被删,另一个也被删,这会造成不想要的结果. 该怎么办? 比如:   widget& widget:: operator+ (const widget& rhs) {    delete pd;    pd = new bitmap(*rhs.pb);    return *thi

Effective C++ 条款六 若不想使用编译器自动生成的函数,就该明确拒绝

class HomeForSale //防止别人拷贝方法一:将相应的成员函数声明为private并且不予实现 { public: private: HomeForSale(const HomeForSale&); HomeForSale& operator = (const HomeForSale&);//只有申明,此函数很少被使用   };   //方法二,设计一个专门用来阻止copying动作的基类,然后让其他类继承这个类即可   class Uncopyable { prot

Effective C++ 条款15、16 在资源管理类中提供对原始资源的访问||成对使用new 与 delete要采取相同形式

1.在资源管理类中提供对原始资源的访问     前几个条款很棒,它们是对抗资源泄露的壁垒,但很多APIs直接指向 资源,这个时候,我们需要直接访问原始资源.     这里,有两种方法解决上述问题,我们可将RAII对象转换为原始资源.通过 显式转换与隐式转换.     通常,tr1:: shared_ptr 和 auto_ptr 都提供一个get成员函数,用来执行显式转换,也就是返回智能指针内部的原始指针的复件.因为它也重载了指针取值操作符* –>.当然也可以通过隐式转换为底部原始指针.     

Effective C++ 条款四 确定对象被使用前已被初始化

1.对于某些array不保证其内容被初始化,而vector(来自STL)却有此保证. 2.永远在使用对象前初始化.对于无任何成员的内置类型,必须手工完成.      int x = 0;      const int * p = &x; 3.不要混淆赋值与初始化的区别.一般初始化在定义的时候一起进行.而赋值是在定义之后的动作.      比如说在某一个类中的构造函数中,函数的行为都是赋值操作,而非初始化操作.      一般来说,对象的成员变量的初始化动作发生在进入构造函数本体之前.所以,我们一