c++ - 如果我定义带有非常量参数的复制构造函数和 operator= ,我仍然会得到默认的复制构造函数和 operator= 吗?

标签 c++ constants language-lawyer default-copy-constructor

在 C++ 中,如果我定义了一个复制构造函数和 operator=,它采用对该类的非 const 引用,编译器是否仍应为 const 引用提供默认版本?

struct Test {
  Test(Test &rhs);
  Test &operator=(Test &rhs);

private:
  // Do I still need to declare these to avoid automatic definitions?
  Test(const Test &rhs);
  Test &operator=(const Test &rhs);
};

最佳答案

不,如果你定义一个复制构造函数和赋值运算符,编译器不会隐式声明或定义它自己的。请注意,复制构造函数 的定义允许参数由 const 或非 const 引用获取,因此您的构造函数确实是一个复制构造函数operator=

同样

[省略了很大一部分细节,特别是在什么情况下隐式声明的特殊成员函数也会隐式定义]

12.8 [class.copy]/2 A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

12.8 [class.copy]/7 If the class definition does not explicitly declare a copy constructor, one is declared implicitly.

12.8 [class.copy]/17 A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&.

12.8 [class.copy]/18 If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly.

关于c++ - 如果我定义带有非常量参数的复制构造函数和 operator= ,我仍然会得到默认的复制构造函数和 operator= 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11936730/

相关文章:

c++ - LNK2019 : unresolved external symbol; foreach. h FE_Iterator()

c++ - 如果你在 vector 拷贝中放一个常量会怎样?或移动?

c++ - 非成员函数模板什么时候有内部链接?

c++ - 向下转型时的 static_cast 悬挂引用

c - 定义为宏的标准库函数的参数类型错误

c++ - 调试时间问题

c++ - 在 C++ 中干净地复制基类或子类的实例?

c++ - 何时在函数 args 中使用 const 和 const 引用?

c++ - 用说明符extern声明的C++中的标识符链接

c++ - 基于范围的隐式添加 `const` 限定符?