使用declard和argument-forwarding构造函数隐式复制结构

时间:2016-04-03 23:35:13

标签: c++ forward-declaration default-copy-constructor

我想让一个struct用转发参数初始化它的成员。这个编译和工作正常,除非我声明一个析构函数,当我尝试从函数返回结构时(我认为这需要一个复制构造函数)。

#include <utility>

struct Foo 
{
  int val;

  Foo(int val) : val(val)
  {
  }
};

struct FooContainer
{
    Foo member;

    template<typename... Args>
    FooContainer(Args&&... args) : 
      member(std::forward<Args>(args)...)
    {}

    ~FooContainer() {}
};

FooContainer getFooContainer()
{
  FooContainer retval(0);
  return retval;
}

int main() {}

编译错误是:

example.cc: In constructor ‘FooContainer::FooContainer(Args&& ...) [with Args = FooContainer&]’:
example.cc:27:   instantiated from here
example.cc:18: error: no matching function for call to ‘Foo::Foo(FooContainer&)’
example.cc:7: note: candidates are: Foo::Foo(int)
example.cc:4: note:                 Foo::Foo(const Foo&)

看起来它正在尝试为FooContainer生成一个复制构造函数,但是失败了,因为它没有办法初始化Foo。然而,如果我删除FooContainer构造函数或析构函数,它编译得很好。*为什么会这样做?

无论如何,在http://cpp.sh/上使用GCC 4.9.2

*。即使未声明析构函数,Ubuntu上的g ++ 4.4.3也会出现相同的错误。

1 个答案:

答案 0 :(得分:1)

我无法确切地告诉你为什么会发生这种情况(标准专家能够)但问题实际上是因为你已经定义了一个用户定义的析构函数。

删除它并且问题消失了(无论如何你想要使用零规则,对吗?)

如果你必须有析构函数并且由于某种原因无法重构它,那么替换move-constructor(你通过提供析构函数隐式删除它)也将解决它。

解决方案1 ​​ - 使用0规则:

#include <utility>

struct Foo
{
    int val;

    Foo(int val) : val(val)
    {
    }
};

struct FooContainer
{
    Foo member;

    template<typename... Args>
    FooContainer(Args&&... args) :
    member(std::forward<Args>(args)...)
    {}

//    ~FooContainer() {}
};

FooContainer getFooContainer()
{
    FooContainer retval(0);
    return retval;
}

int main() {}

解决方案2 - 使用规则5:

#include <utility>

struct Foo
{
    int val;

    Foo(int val) : val(val)
    {
    }
};

struct FooContainer
{
    Foo member;

    template<typename... Args>
    FooContainer(Args&&... args) :
    member(std::forward<Args>(args)...)
    {}

    FooContainer(const FooContainer&) = default;
    FooContainer(FooContainer&&) = default;
    FooContainer& operator=(const FooContainer&) = default;
    FooContainer& operator=(FooContainer&&) = default;

    ~FooContainer() {}
};

FooContainer getFooContainer()
{
    FooContainer retval(0);
    return retval;
}

int main() {}