C++ 特殊成员函数

C++ Special member functions

一直知道C++的特殊成员函数有:

现在我正在阅读 Meyers Effective C++ 书并且意识到还有一对 address-of operators.

我可以这样重新定义它:

class A
{
public:
  A* operator&()
  {
    std::cout << "Address of operator" << std::endl;
  }
};

int main()
{
  A a;
  B* b = &a; // Will call address-of operator.
}

为什么在 C++ 标准第 12 节(特殊成员函数)中没有关于此运算符的字样。

如果您更仔细地阅读标准,您会发现特殊成员函数是编译器可以隐式声明的函数,如果您不显式声明它们的话。

来自 C++ 标准:

12 Special member functions [special] 1 The default constructor (12.1), copy constructor and copy assignment operator (12.8), move constructor and move assignment operator (12.8), and destructor (12.4) are special member functions. [ Note: The implementation will implicitly declare these member functions for some class types when the program does not explicitly declare them. The implementation will implicitly define them if they are odr-used (3.2). See 12.1, 12.4 and 12.8. —end note ] An implicitly-declared special member function is declared at the closing } of the class-specifier. Programs shall not define implicitly-declared special member functions.

顺便说一下,您显示的运算符的定义是错误的,因为它returns 什么都没有。

至于其他成员函数,包括运算符,例如应声明为 class 成员,则实现不会隐式声明它们。由程序员决定是否声明某些运算符。例如,您的 class 可能包含一打赋值运算符。

"Why then in C++ standard section 12 (Special member functions) there is no word about this operator. "

因为这个运算符不是特殊成员函数。它实际上包含在 this section

13.5 Overloaded operators
1 A function declaration having one of the following operator-function-ids as its name declares an operator function. A function template declaration having one of the following operator-function-ids as its name declares an operator function template. A specialization of an operator function template is also an operator function. An operator function is said to implement the operator named in its
operator-function-id.

operator-function-id:
operator operator
operator: one of

new delete new[] delete[]
+ - * / % ˆ & | ∼
! = < > += -= *= /= %=
ˆ= &= |= << >> >>= <<= == !=
<= >= && || ++ -- , ->* ->
( ) [ ]

...

2 Both the unary and binary forms of + - * & can be overloaded.

这应该是一个答案,而不是评论,就这样吧:

这是您的 Effective C++ 版本中的一个错误。我的副本说:

If you don't declare them yourself, your thoughtful compilers will declare their own versions of a copy constructor, an assignment operator, and a destructor.

如您所见,不再提及任何寻址运算符。 errata for the second edition 明确提及此更改:

A class declaring no operator& function(s) does NOT have them implicitly declared. Rather, compilers use the built-in address-of operator 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.