c++ - Deleted implicitly-declared copy assignment operator
问题描述
According to the C++ reference on Copy assignment operator:
A defaulted copy assignment operator for class T is defined as deleted if any of the following is true
T has a non-static data member of non-class type (or array thereof) that is const ...
I was hoping to create a case where I had a const class-type data member and a defaulted copy assignment operator not defined as deleted. In doing so, I found a discrepancy between clang and gcc. Consider the following code:
struct B {
void operator=(const B&) const {}
};
struct A {
const B b{};
A& operator=(const A&) = default;
};
int main() {
A a1{}, a2{};
a1 = a2; //only works with clang
B b1{}, b2{};
b1 = b2; //works in both
}
When I compile this with g++ -std=c++14
I get the following errors:
In member function ‘A& A::operator=(const A&)’:
error: non-static const member ‘const B A::b’, can’t use default assignment operator
note: synthesized method ‘A& A::operator=(const A&)’ first required here
This does, comma, however, compile with clang
, as the reference seems to indicate that it should. Am I in error? Which compiler is correct?
I'm using gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04)
and clang version 6.0.0-1ubuntu2
.
解决方案
看来clang是对的,
尽管尚未确认,但有一份关于 gcc 主题的报告,正如有人指出的那样,与本案相关的两条规则不适用
(7.2) const 非类类型(或其数组)的非静态数据成员,或
[...]
(7.4) 类类型 M(或其数组)的直接非静态数据成员或由于重载决议([over.match])而无法复制/移动的直接基类 M,用于查找 M 的相应赋值运算符,导致歧义或从默认赋值运算符中删除或无法访问的函数。
推荐阅读
- c# - 将正则表达式字符串传递给程序集
- google-chrome - Chrome 扩展程序未显示在商店中
- r - R:hunspell 总是返回 false
- elasticsearch - 在现有索引的现有字段中添加带有分析器的多字段
- go - 使用 Go-Github 和 http.Transport 时如何设置 HTTP 请求标头?
- ios - 使用 CMRotationMatrix 旋转 CALayer
- automation - 如何在空手道中使用特定于环境的测试数据
- kubernetes - 无法使用 helm 在 AKS 上安装 Keda
- java - Apache Ignite:缓存 ClusterGroup
- spring-boot - 如何对 Spring Cloud 功能应用程序进行单元测试?