首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >警告:即使我没有调用复制构造函数,也可以定义隐式复制构造函数。

警告:即使我没有调用复制构造函数,也可以定义隐式复制构造函数。
EN

Stack Overflow用户
提问于 2022-01-16 06:20:12
回答 1查看 772关注 0票数 0

我试图在分配中运行这个示例,但是当我删除默认构造函数和默认复制构造函数: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++报告复制构造函数警告?

这是我的代码:

代码语言:javascript
复制
#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中有一个内联复制构造函数。

代码语言:javascript
复制
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;
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-16 06:34:00

这会调用A的复制构造函数,因为other是一个值副本。

代码语言:javascript
复制
inline A & operator=(A other)

把它改成

代码语言:javascript
复制
inline A & operator=(const A& other)

然后删除掉期,只需将其他成员变量赋值给*

代码语言:javascript
复制
n=other.n;
s1=other.s1;

这就消除了对副本构造函数的要求。但是,定义赋值操作符w/o也定义了复制构造函数,这违反了三条规则,因此编译器发出警告。此外,当在类中定义成员函数时,“内联”是固有的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70727819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档