gpt4 book ai didi

c++ - constrexpr 继承自 shared_ptr 的构造函数

转载 作者:太空狗 更新时间:2023-10-29 20:57:08 25 4
gpt4 key购买 nike

我想实现我自己的从 shared_ptr 扩展的指针(有几个辅助方法)。

class Event;

class EventPtr : public std::shared_ptr<Event> {
public:
constexpr EventPtr()
: std::shared_ptr<Event>() {
}

constexpr EventPtr(std::nullptr_t p)
: std::shared_ptr<Event>(p) {
}

explicit EventPtr(Event* ptr)
: std::shared_ptr<Event>(ptr) {
}
};

问题是编译器为我提供了以下两个 constexpr 构造函数的错误:constexpr 构造函数从不生成常量表达式

请告诉我如何解决它。

最佳答案

constexpr 构造函数的规则在 C++11 和 C++14 之间发生了变化;见DR1911 constexpr constructor with non-literal base classthis bug .

修复是在 C++14 模式下编译 (-std=c++14)。

C++11 中的语言[dcl.constexpr]:

For a constexpr function, if no function argument values exist such that the function invocation substitution would produce a constant expression (5.19), the program is ill-formed; no diagnostic required. For a constexpr constructor, if no argument values exist such that after function invocation substitution, every constructor call and full-expression in the mem-initializers would be a constant expression (including conversions), the program is ill-formed; no diagnostic required.

在 C++11 下,shared_ptr 可以有 constexpr 构造函数,但是任何继承自 shared_ptr 或带有 shared_ptr< 的类类型 成员不能,因为 shared_ptr 不是文字类型(它有析构函数),因此不能出现在常量表达式中。对于 C++14,这被简化为:

For a non-template, non-defaulted constexpr function or a non-template, non-defaulted, non-inheriting constexpr constructor, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression (5.19), the program is ill-formed; no diagnostic required.

不幸的是,这使得非文字类型的所有 constexpr 构造函数成为未定义的行为; DR1911 通过添加子条款(下面的粗体)解决了这个问题:

For a non-template, non-defaulted constexpr function or a non-template, non-defaulted, non-inheriting constexpr constructor, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression (5.20), or, for a constructor, a constant initializer for some object (3.6.2), the program is ill-formed; no diagnostic required.

struct X { ~X() {} constexpr X() {} };   // OK in C++11, UB in C++14, OK since DR1911
struct Y : X { constexpr Y() : X() {} }; // UB in C++11, UB in C++14, OK since DR1911

关于c++ - constrexpr 继承自 shared_ptr 的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31583326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com