zoukankan      html  css  js  c++  java
  • Effective C++ 笔记 —— Item 5: Know what functions C++ silently writes and calls

    For an enpty class, if you don't declare them yourself, compilers will declare their own versions of a copy constructor, a copy assignment operator, and a destructor. Furthermore, if you declare no constructors at all, compilers will also declare a default constructor for you.

    These functions are generated only if they are needed.

    Note that the generated destructor is non-virtual unless it's for a class inheriting from a base class that itself declares a virtual destructor (in which case the function's virtualness comes from the base class).

    If you want to support copy assignment in a class containing a reference member, you must define the copy assignment operator yourself.

    Compilers behave similarly for classes containing const members (such as objectValue in the modified class above). It's not legal to modify const members, so compilers are unsure how to treat them during an implicitly generated assignment function.

    Finally, compilers reject implicit copy assignment operators in derived classes that inherit from base classes declaring the copy assignment operator private.

    template<typename T>
    class NamedObject {
    public:
        // this ctor no longer takes a const name, because nameValue
        // is now a reference-to-non-const string. The char* constructor
        // is gone, because we must have a string to refer to.
        NamedObject(std::string& name, const T& value);
        //... // as above, assume no
        // operator= is declared
    private:
        std::string& nameValue; // this is now a reference
        const T objectValue; // this is now const
    };
    
    //Now consider what should happen here :
    std::string newDog("Persephone");
    std::string oldDog("Satch");
    
    NamedObject<int> p(newDog, 2); // when I originally wrote this, our dog Persephone was about to have her second birthday
    
    NamedObject<int> s(oldDog, 36); // the family dog Satch (from my childhood) would be 36 if she were still alive
    
    p = s; // what should happen to the data members in p?
  • 相关阅读:
    Python实现二分法查找
    Python实现冒泡排序
    issues:closeForm字段默认值设置,roo创建应用的默认语言设置
    howto:IEDA 中运行Maven项目
    将繁体中文国际化文件,变为简体中文国际化文件
    JasperServer安装XP异常解决
    note:maven 简介
    note:addon开发基础知识
    issues:close 云端 STS 启动报找不到 jdk
    小程序ios设置map圆角不生效的问题解决方案
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/14921810.html
Copyright © 2011-2022 走看看