加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 派生时使用copy ctor而不是move ctor定义了析构函数

发布时间:2020-12-16 07:03:43 所属栏目:百科 来源:网络整理
导读:当我向派生类添加析构函数时,我在尝试使用copy ctor而不是定义的move ctor时遇到编译器错误(使用 gcc 4.7): #include utility#include iostreamtemplate typename Tstruct Base { T value; Base(T value) : value(value) { std::cout "base ctor" std::endl
当我向派生类添加析构函数时,我在尝试使用copy ctor而不是定义的move ctor时遇到编译器错误(使用 gcc 4.7):

#include <utility>
#include <iostream>

template <typename T>
struct Base 
{
  T value;

  Base(T&& value) :
    value(value)
  {
    std::cout << "base ctor" << std::endl;
  }

  Base& operator=(const Base&) = delete;
  Base(const Base&) = delete;

  Base& operator=(Base&& rhs)
  {
    value = rhs.value;
    std::cout << "move assignment" << std::endl;
  }

  Base(Base&& other) :
    value(other.value)
  {
    std::cout << "move ctor" << std::endl;
  }

  virtual ~Base()
  {
    std::cout << "base dtor" << std::endl;
  }
};

template <typename T>
struct Derived : public Base<T>
{
  Derived(T&& value) :
    Base<T>(std::forward<T>(value))
  {
    std::cout << "derived ctor" << std::endl;
  }

  ~Derived()
  {
    std::cout << "derived dtor" << std::endl;
  }
};

template <typename T>
Derived<T> MakeDerived(T&& value)
{
  return Derived<T>(std::forward<T>(value));
}

struct Dummy {};

int main()
{
  auto test = MakeDerived(Dummy());
}

此代码在gcc-4.5和gcc-4.6上编译良好. gcc-4.7的错误是:

test.cpp: In function ‘int main()’:
test.cpp:61:34: error: use of deleted function ‘Derived<Dummy>::Derived(const Derived<Dummy>&)’
test.cpp:37:8: note: ‘Derived<Dummy>::Derived(const Derived<Dummy>&)’ is implicitly deleted because the default definition would be ill-formed:
test.cpp:37:8: error: use of deleted function ‘Base<T>::Base(const Base<T>&) [with T = Dummy; Base<T> = Base<Dummy>]’
test.cpp:16:3: error: declared here
test.cpp: In instantiation of ‘Derived<T> MakeDerived(T&&) [with T = Dummy]’:
test.cpp:61:34:   required from here
test.cpp:54:43: error: use of deleted function ‘Derived<Dummy>::Derived(const Derived<Dummy>&)’

我在这里遗漏了什么,还是应该在gcc 4.7上编译好?当我在Derived类上注释掉析构函数时,一切都很好.

gcc version 4.5.3 (Ubuntu/Linaro 4.5.3-12ubuntu2) 
gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) 
gcc version 4.7.2 (Ubuntu/Linaro 4.7.2-11precise2)

解决方法

错误是正确的;当类没有用户定义的析构函数时,只会隐式生成移动构造函数.如果添加析构函数,那么您将取消默认的move-constructor,并尝试使用复制构造函数.当类具有不可复制的基类时,将禁止生成默认的复制构造函数,因为Derived既不可复制也不可移动.

解决方案只是向Derived添加一个move-constructor.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读