zoukankan      html  css  js  c++  java
  • Accustoming_Yourself_to_C++

    //条款1 用const,enum,inline 替换#define
    
    //1 const 替换 #define 常量
    /*
    * 对于浮点数,const double 代码小
    * 在class内不能提供封装性
    * #defien函数用 
    * template<typename>
    * inline dectltype(auto) function 替换
    */
    #include<cstring>
    #include<string>
    class CTextBlock
    {
    public:
        size_t length() const;
    private:
    private:
        char* pText;
        mutable size_t textLength;
        mutable bool lengthIsValid;
    };
    
    size_t CTextBlock::length() const
    {
        if (!lengthIsValid)
        {
            //function const 由于正在通过常量对象访问“textLength”,因此无法对其进行修改    
            //解决:mutable
            textLength = std::strlen(pText);
            lengthIsValid = true;
        }
        return textLength;
    }
    //解决 代码只有返回类型的重复问题:令non-const function 调用另一个 const-function
    class TextBlock
    {
    public:
        const char& operator[](std::size_t position) const
        {
            //bounds chexking
            //log access data
            //verify data integrity
            return text[position];
        }
        char& operator[](std::size_t position)
        {
            return
                const_cast<char&>(//去掉 返回值的const 
                    static_cast<const TextBlock&>//调用 operator[]()const 
                    (*this)[position]);
        }
    private:
        std::string text;
    };
    //因为为 const 成员函数承若绝不改变其对象的逻辑状态,So don't const function call non-const function
    
    //条款四:Make sure that objects are initialized before they're used
    /*
    *在构造函数中使用()初始化:减少一次copy
    
    问题:如果某编译单元(cpp)内的某个non-local static对象的初始化
          使用了另一个编译单元(cpp)的non-local static对象
    
    c++对“定义于不同编译单元内的non-local static对象”的初始化次序并无明确定义
    
    解决:用local static 替换 non-local static(已经被未命名空间取代)
    
    c++保证:函数内的local static 对象会在“该函数被调用期间”“首次遇上该对象的定义”时被初始化
    */
    class FileSystem
    {
    public:
        std::size_t numDisks() const;
    };
    inline FileSystem& tfs() //tfs:the file system
    {
        static FileSystem fs;
        return fs;
    }
    class Directory
    {
    public:
        Directory() = default;
        Directory(std::string params);
    };
    Directory::Directory(std::string params)
    {
        std::size_t disks = tfs().numDisks();
    }
    inline Directory& tempDir()
    {
        static Directory td;
        return td;
    }
    int main()
    {
        return 0;
    }
  • 相关阅读:
    jquery easyui-datagrid手动增加删除重置行
    jsp中一行多条数据情况
    JQuery操作下拉框
    解决juqery easyui combobox只能选择问题
    oracle中WMSYS.WM_CONCAT函数的版本差异
    oracle wm_concat(column)函数的使用
    Javascript九大排序算法详解
    C#和VB新版本的最新特性列表
    Oracle中如何区别用户和模式
    远程控制数据库实用SQL重启功能
  • 原文地址:https://www.cnblogs.com/Z-s-c11/p/14142364.html
Copyright © 2011-2022 走看看