1.尽量以const,enum,inline替换#define

//.h
class Foo{
    private:
        static const int NUM = 5;//class专属常量声明
} 
//.cpp
const int Foo::NUM;
char grerting[] = "hello";
char* p = grerting; //non-const pointer non-const data
const char* p = grerting;// non-const pointer const data
char* const p = grerting;// const pointer non-const data
const char* const p = grerting;// const pointer const data

std::vector<int> vec;
const std::vector<int>::iterator iterator = vec.begin();
*iterator = 0;// ok
++iterator;// error iterator is const

std::vector<int>::const_iterator iterator = vec.begin();
*iterator = 0;// error ,*iterator is const
++iterator;// ok
class Text{
    public:
        const char& operator[](std::size_t position) const {
            //do something
            return text[position];
        }

        //const_cast转换符移除变量的const
        //static_cast<new_type>(expression):expression->new_type
        char& operator[](std::size_t position){
            //do something
            return const_cast<char&>(
                    static_cast<const Text&>(*this)[position]);
        }

    private:
        std::string text;
};

class Text{
    public:
        Text(std::string str):text(str){};//效率高,直接初始化值
        Text(std::string str){
            text = str; //效率低,先调用default设初值,再赋值
        };
    private:
        std::string text;
};
class FileSystem{
    //...
};

FileSystem& tfs(){
    static  FileSystem tfs;
    return tfs;
}

class Directory{

};

Directory::Directory(params){
    std::size_t disks = tfs().numDisks();//避免无序的初始化
}
Directory& tempDir(){
    static  Directory td;
    return td;
}

2.可禁止使用copy构造函数或copy assignment操作符,使其私有并只作声明

class HomeForSale{
    public:
        ...
    private:
        HomeForSale(const HomeForSale &);
        HomeForSale& operator=(const HomeForSale&);
}
//or
class Uncopyable{
    protected:
        //允许derived对象构造和析构
        Uncopyable(){};
        ~Uncopyable(){};
    private:
        //阻止copying
        Uncopyable(const Uncopyable &);
        Uncopyable& operator=(const Uncopyable&);
}

class HomeForSale : private Uncopyable{
        ...
}


HomeForSale home;
HomeForSale new_home(home);//error
HomeForSale new_home_assign;
new_home_assign = home;//error

3.带多态性质的基类应该声明一个virtual析构函数,如果class带有任何virtual函数,都应拥有一个virtual析构函数

否则调用delete时,删除由base class指针指向的derived class,derived class的析构函数不会被执行,仅执行base class的析构函数

class TimeKeeper{
    public:
        TimeKeeper();
        virtual ~TimeKeeper();
        ...
}
TimeKeeper *ptk = getTimeKeeper();
...
delete ptk;

4.令operator=返回一个reference to this指针

class TimeKeeper{
    public:
        TimeKeeper& operator=(const TimeKeeper& rhs){
            this.name = rhs.name;
            ...
            return *this;
        }
}

5.



C++      C++

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!