【问题标题】:Determine whether a constructor of an abstract base class is noexcept?判断一个抽象基类的构造函数是否为noexcept?
【发布时间】:2016-06-17 01:56:12
【问题描述】:

在C++11及以后,如何判断抽象基类的构造函数是否为noexcept?以下方法无效:

#include <new>
#include <type_traits>
#include <utility>

struct Base { Base() noexcept; virtual int f() = 0; };

// static assertion fails, because !std::is_constructible<Base>::value:
static_assert(std::is_nothrow_constructible<Base>::value, "");

// static assertion fails, because !std::is_constructible<Base>::value:
static_assert(std::is_nothrow_default_constructible<Base>::value, "");

// invalid cast to abstract class type 'Base':
static_assert(noexcept(Base()), "");

// invalid new-expression of abstract class type 'Base'
static_assert(noexcept(new (std::declval<void *>()) Base()), "");

// cannot call constructor 'Base::Base' directly:
static_assert(noexcept(Base::Base()), "");

// invalid use of 'Base::Base':
static_assert(noexcept(std::declval<Base &>().Base()), "");

一个简单的用途是:

int g() noexcept;
struct Derived: Base {
    template <typename ... Args>
    Derived(Args && ... args)
            noexcept(noexcept(Base(std::forward<Args>(args)...)))
        : Base(std::forward<Args>(args)...)
        , m_f(g())
    {}

    int f() override;

    int m_f;
};

关于如何归档这个或者在不修改抽象基类的情况下是否有可能?

PS:也欢迎任何对 ISO C++ 缺陷报告或正在进行的工作的引用。

编辑: 正如两次指出的那样,将 Derived 构造函数默认为 = default 会使 noexcept 被继承。但这并不能解决一般情况下的问题。

【问题讨论】:

  • 如果你知道抽象方法,你可以像this那样做。如果您想要一个完全通用的解决方案,我认为您不走运

标签: c++ c++11 c++14 c++17 noexcept


【解决方案1】:

[更新:值得跳到编辑部分]

好的,我找到了一个解决方案,尽管由于 GCC 中的一个错误,它不能与所有编译器一起编译(有关详细信息,请参阅 this question)。

该解决方案基于继承的构造函数和函数调用的解析方式。
考虑以下示例:

#include <utility>
#include <iostream>

struct B {
    B(int y) noexcept: x{y} { }
    virtual void f() = 0;
    int x;
};

struct D: public B {
private:
    using B::B;

public:
    template<typename... Args>
    D(Args... args)
    noexcept(noexcept(D{std::forward<Args>(args)...}))
        : B{std::forward<Args>(args)...}
    { }

    void f() override { std::cout << x << std::endl; }
};

int main() {
    B *b = new D{42};
    b->f();
}

我想这很清楚。
无论如何,如果您发现某些内容需要更多详细信息,请告诉我,我很乐意更新答案。
基本思想是我们可以直接从基类及其构造函数继承noexcept 定义,这样我们就不必再在noexcept 语句中引用该类了。

Here你可以看到上面提到的工作示例。

[编辑]

从 cmets 来看,如果基类的构造函数和派生类的构造函数具有相同的签名,则该示例会遇到问题。
感谢 Piotr Skotnicki 指出这一点。
我将提到那些 cmets,我将复制并粘贴与它们一起提出的代码(在需要的地方提及作者)。

首先,here 我们可以看到该示例无法按预期工作(感谢 Piotr Skotnicki 提供的链接)。
代码与之前发布的几乎相同,因此不值得在这里复制和粘贴。
此外,来自同一作者,它遵循一个示例 that shows that the same solution works as expected under certain circumstances(有关更多详细信息,请参阅 cmets):

#include <utility>
#include <iostream>

struct B {
    B(int y) noexcept: x{y}
    {
        std::cout << "B: Am I actually called?\n";
    }
    virtual void f() = 0;
    int x;
};

struct D: private B {
private:
    using B::B;

public:
    template<typename... Args>
    D(int a, Args&&... args)
    noexcept(noexcept(D{std::forward<Args>(args)...}))
        : B{std::forward<Args>(args)...}
    {
        std::cout << "D: Am I actually called?\n";
    }
    void f() override { std::cout << x << std::endl; }
};

int main()
{
    D* d = new D{71, 42};
    (void)d;
}

另外,我提出了一个更具侵入性的替代解决方案,它基于std::allocator_arg_t 所代表的想法,这也是 Piotr Skotnicki 在评论中提出的相同:

如果派生类的构造函数在重载决议中获胜就足够了。

它遵循here提到的代码:

#include <utility>
#include <iostream>

struct B {
    B(int y) noexcept: x{y}
    {
        std::cout << "B: Am I actually called?\n";
    }
    virtual void f() = 0;
    int x;
};

struct D: public B {
private:
    using B::B;

public:
    struct D_tag { };

    template<typename... Args>
    D(D_tag, Args&&... args)
    noexcept(noexcept(D{std::forward<Args>(args)...}))
        : B{std::forward<Args>(args)...}
    {
        std::cout << "D: Am I actually called?\n";
    }
    void f() override { std::cout << x << std::endl; }
};

int main()
{
    D* d = new D{D::D_tag{}, 42};
    (void)d;
}

再次感谢 Piotr Skotnicki 的帮助和 cmets,非常感谢。

【讨论】:

  • @PiotrSkotnicki 相当聪明,肯定比我还聪明。 :-) ... Completeley 错过了打破一切的public。好吧,我在等公共汽车上班的时候用手机上的编译器写了,真遗憾我没有在工作中检查过两次。对不起。无论如何,that one 也不能按预期工作,但应该是 D(int) 无法访问?
  • 问题是您的解决方案是侵入性的,因为它将基类的构造函数导入派生类的范围,因此,它们参与重载决议,这可能会带来意想不到的结果,因为我显示。除此之外,your solution does work for other cases
  • @PiotrSkotnicki 它也适用于这种带有标签调度的情况(类似于分配器标签所代表的),请参阅coliru.stacked-crooked.com/a/df24001de4f3f925 - 我说的对吗?
  • 如果派生类的构造函数在重载决议中获胜就足够了。在您介绍的情况下,它是一个函数模板,因此基类的构造函数是首选
  • @PiotrSkotnicki 好的,我将更新答案,首先感谢您,而不是其他示例并提及我们的 cmets。像往常一样谢谢你,真的很感激!!
【解决方案2】:

基于skypjack's answer,一个不需要更改Derived构造函数签名的更好的解决方案是定义Base的模拟子类作为Derived的私有类型成员,并使用构造Derived 构造函数 noexcept 规范中的那个:

class Derived: Base {

private:

    struct MockDerived: Base {
        using Base::Base;

        // Override all pure virtual methods with dummy implementations:
        int f() override; // No definition required
    };

public:

    template <typename ... Args>
    Derived(Args && ... args)
            noexcept(noexcept(MockDerived(std::forward<Args>(args)...)))
        : Base(std::forward<Args>(args)...)
        , m_f(g())
    {}

    int f() override { return 42; } // Real implementation

    int m_f;

};

【讨论】:

  • 好吧,我也探索了那个解决方案,这里的问题是,只要你有一个虚拟方法就很容易做到,但是当它们数量增加时就很烦人,因为你必须定义一个仅与 noexcept 子句一起使用的新且完全无用的类。无论如何,赞成,因为它仍然是一个可行的解决方案。
  • 是的,但我认为保持Derived 构造函数签名不变和干净是一个很好的权衡。如果Derived 的公共接口发生变化(更糟),那么更改所有构造函数调用以考虑到这种变通方法可能会很乏味。
  • 您可以做的另一件事是,根本不用费心为虚函数提供实现,甚至是虚拟实现。出于未评估上下文的目的,它们只需要声明 - 如果根本不定义它们可能会更好。
  • 我原来的工作实现实际上只有声明。我不知道为什么我将它们添加到这个例子中。 :D 感谢您的注意,我更改了示例以反映这一点。
  • 这个解决方案的问题是你会从你的基类中复制字段,使内存占用比必要的大。例如:在您的基类中添加一个int foo;,您将获得一个Derived::foo 和一个Derived::MockDerived::foo 字段。
【解决方案3】:

一个简单但可行的示例是引入一个非虚拟基类并通过using 指令导出其构造函数。这是一个例子:

#include<utility>

struct BaseBase {
    BaseBase() noexcept { }
};

struct Base: public BaseBase {
    using BaseBase::BaseBase;
    virtual int f() = 0;
};

struct Derived: public Base {
    template <typename ... Args>
    Derived(Args && ... args)
        noexcept(noexcept(BaseBase(std::forward<Args>(args)...)))
        : Base(std::forward<Args>(args)...)
    { }

    int f() override { }
};

int main() {
    Derived d;
    d.f();
}

【讨论】:

  • 这算作“修改抽象基类”,但在某些情况下可能是一种解决方法。之前Base构造函数所依赖的所有字段和功能,都必须包含在BaseBase构造函数或类中,所有依赖于纯虚方法的东西都必须留在Base中。如果我们认为纯方法调用是一件坏事,那么乍一看似乎这种重构实际上是有用的。但在一般情况下它仍然无济于事。我会为你的努力投赞成票。
  • @jotik 你是对的,绝对是,这就是为什么我说天真,但工作。 ;-) ...无论如何,这确实是一个有趣的问题,我仍在努力弄清楚该怎么做。
  • @jotik 我添加了另一个更合适的答案,也许你会发现它不是一种解决方法。让我知道它是否解决了问题。确实是一个很好的问题。
【解决方案4】:

我遇到了同样的问题,我找到的解决方案是实现额外的特征。

你可以看看我的帖子here。

【讨论】:

    猜你喜欢
    • 2018-09-15
    • 2013-11-17
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 2012-01-20
    • 1970-01-01
    相关资源
    最近更新 更多