我试图在分配中运行这个示例,但是当我删除默认构造函数和默认复制构造函数:A() = default; A(A const&) = default;时,clang++说是warning: definition of implicit copy constructor for 'A' is deprecated because it has a user-provided copy assignment operator [-Wdeprecated-copy-with-user-provided-copy]。
我的问题是,我调用了复制赋值而不是复制构造函数,为什么clang++报告复制构造函数警告?
这是我的代码:
#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
struct A
{
int n;
std::string s1;
// user-defined copy assignment (copy-and-swap idiom)
A& operator=(A other)
{
std::cout << "copy assignment of A\n";
std::swap(n, other.n);
std::swap(s1, other.s1);
return *this;
}
};
int main()
{
A a1, a2;
std::cout << "a1 = a2 calls ";
a1 = a2; // user-defined copy assignment
}这里是cppinsight链接,我可以看到在struct中有一个内联复制构造函数。
struct A
{
int n;
std::basic_string<char> s1;
inline A & operator=(A other)
{
std::operator<<(std::cout, "copy assignment of A\n");
std::swap(this->n, other.n);
std::swap(this->s1, other.s1);
return *this;
}
// inline A(const A &) noexcept(false) = default;
// inline ~A() noexcept = default;
// inline A() noexcept = default;
};发布于 2022-01-16 06:34:00
这会调用A的复制构造函数,因为other是一个值副本。
inline A & operator=(A other)把它改成
inline A & operator=(const A& other)然后删除掉期,只需将其他成员变量赋值给*
n=other.n;
s1=other.s1;这就消除了对副本构造函数的要求。但是,定义赋值操作符w/o也定义了复制构造函数,这违反了三条规则,因此编译器发出警告。此外,当在类中定义成员函数时,“内联”是固有的。
https://stackoverflow.com/questions/70727819
复制相似问题