空类默认隐式声明的成员函数

来源:岁月联盟 编辑:猪蛋儿 时间:2011-12-27

 最近在论坛上发现的问题,改变了我以前在这方面的错误看法,跟大家分享一下。
据说这个问题在面试中被问到的机率比较高,幸运的是我好像没有碰到过。
一般流行的看法是:

class Empty{};  
相当于:

class Empty  
{  
public:  
    Empty();  
    Empty(const Empty&);  
    ~Empty();  
    Empty& operator=(const Empty& rhs);  
    Empty* operator&();  
    const Empty* operator&() const;  
};  
        结合ISO/IEC 14882:2003(E)中12 Special member functions章节的描述,可以确定的是
默认构造函数 拷贝构造 析构 operator=是隐式声明的。Empty* operator&()和const Empty* operator&() const; 是不会隐式声明的。

        关于错误的来源是侯捷翻译的中文简体《Effective c++, 2nd》
        条款45: 弄清C++在幕后为你所写、所调用的函数
一个空类什么时候不是空类? ---- 当C++编译器通过它的时候。如果你没有声明下列函数,体贴的编译器会声明它自己的版本。这些函数是:一个拷贝构造函数,一个赋值运算符,一个析构函数,一对取址运算符。另外,如果你没有声明任何构造函数,它也将为你声明一个缺省构造函数。所有这些函数都是公有的。换句话说,如果你这么写:

class Empty{}; 
和你这么写是一样的:

class Empty { 
public: 
  Empty();  
  Empty(const Empty& rhs);  
  ~Empty(); 
  Empty& operator=(const Empty& rhs); 
  Empty* operator&(); 
  const Empty* operator&() const; 
}; 
        对于这个问题,早有读者向书的作者Scott Meyers提出了疑问,Scott Meyers也认为上边的答案是有问题的。
下面是作者对于这个问题的解释:
! 2/10/00 ic 212 A class declaring no operator& function(s) 9/10/01
  cxh 213 does NOT have them implicitly declared. Rather,
  245 compilers use the built-in address-of operator
  246 whenever "&" is applied to an object of that
  type. This behavior, in turn, is technically
  not an application of a global operator&
  function. Rather, it is a use of a built-in
  operator.
至此相信读者心中已经有答案了吧。

摘自 姜亚风CSDN博客

图片内容