zoukankan      html  css  js  c++  java
  • effective c++读书随记

    一 View C++ as a federation of language

      c++ 可以看成4部分组成:

      1. c  
      2. Object-Oriented c++
      3. Template c++
      4. STL

    二 Perfer consts, enums, inlines to #defines

    1. *左表示所指不能改变,*右则表示指针不能改变
    2. 类中的专属常量(static const)为了只有一份拷贝通常加static,因此需要类外增加一个定义式(类中是申明)
    3. 类中的常量也可以用 the enum hack 的方法定义
    4. template inline函数可以替换宏函数

    三 Use const whenever possible

    1. passed by pointer-to-const passed by reference-to-const
    2. bitwise constness 和 logical constness(const成员函数)
      1. 前者要求函数内部不能改变类对象,后者要求使用该类的人感受不到其改变了类对象(mutable私有变量)
      2. 提供成员函数的const,non-const版本为避免代码重复,可以用non-const调用const成员函数的方法(static_cast,const_cast)
      3. 注意const成员函数返回值是否需要为const

    四 Make sure that objects are initialized before they're used

    1. 构造函数使用成员参数列表初始化变量(对于类中存在const,引用时必须如此)
    2. 将non-local static 变成 local static 对象(通过专属factory函数),可以避免纠结多个不同类对象之间不明确的初始化顺序,因为它会在使用时初始化
    3. 对于多线程,为了消除与初始化的竞争关系,可以在启动多线程前把所有reference-returning

    五 Know what functions C++ silently writes and calls

    1. copy constructor, copy assignment, destructor
    2. 类成员有const/reference,default copy constructor 会编译出错

    六 Explicitly disallow the use of compiler-generated functions you don't want

    1. 方法一:直接放到private中,缺点是可能是link的时候报错
    2. 方法二:申明一个基类,函数放在private里(不用实现)

    七 Declare destructors virtual in polymorphic base calsses

    1. pure virtual
    2. 可以防止只析构了 base class 部分
    3. 如果不是作为base class 使用或者不是为了具有多态性,请勿申明virtual,会增加体积

    八 Prevent exceptions from leaving destructors(wait,cannot understand now)

    九 Never call virtual functions during construction or destruction

    1. 这样调用的不是派生类的virtual函数

    十 Have assignment operators return a reference to *this

    1. 便于写成连锁形式
  • 相关阅读:
    [lua]原来这才是表驱动的正确表达方式
    [lua]再版jobSchedule与脚本描述范型
    (景德镇)麻将计分规则
    日志输出法则
    去掉谷歌浏览器获取焦点时默认的input、textarea的边框和背景
    使用@font-face 属性 实现在网页中嵌入任意字体
    【问题】/usr/bin/env: php: 没有那个文件或目录
    Centos下nginx支持https协议
    PHP下生成非重复的id
    PHP下的手机号码效验
  • 原文地址:https://www.cnblogs.com/ACystalMoon/p/3151456.html
Copyright © 2011-2022 走看看