gpt4 book ai didi

c++ - constexpr 构造函数中不能使用 constexpr 构造函数

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:58 28 4
gpt4 key购买 nike

我想重新定义unique_ptr用一个特殊的析构函数。因此,我使用以下代码尝试模仿 unique_ptr 的一些构造函数.遗憾constexpr施 worker 员拒绝 build ,我不知道为什么。

class job_ptr : public unique_ptr<Job>
{
public:
constexpr job_ptr()
: unique_ptr<Job>(), sequencer( nullptr ) {}
constexpr job_ptr( nullptr_t )
: unique_ptr<Job>( nullptr ), sequencer( nullptr ) {}
private:
FIFOSequencer* sequencer;
};

初始化列表中的两个构造函数都被声明为constexpr , 然而 clang++认为constexpr constructor never produces a constant expression因为non-literal type 'unique_ptr<Job>' cannot be used in a constant expression .它是什么意思? constexpr构造函数不能在 constexpr 中使用构造函数?

感谢您的帮助。

最佳答案

Constexpr 构造函数是可能的,但是 the requirement are quite strict .正如@dyp 所说,您面临的主要问题是 std::unique_ptr 不是平凡的析构函数,因此不是 LiteralType。 .

如果您尝试在 g++ 下使用 int:

class int_ptr : public std::unique_ptr<int>
{
public:
constexpr int_ptr()
: std::unique_ptr<int>(), sequencer( nullptr ) {}
constexpr int_ptr( nullptr_t )
: std::unique_ptr<int>( nullptr ), sequencer( nullptr ) {}
private:
int* sequencer;
};

constexpr int_ptr ptr;

你有一个非常明确的错误信息:

unique_ptr.cpp:40:20: error: the type ‘const int_ptr’ of constexpr variable ‘ptr’ is not literal
constexpr int_ptr ptr;
^
unique_ptr.cpp:27:7: note: ‘int_ptr’ is not literal because:
class int_ptr : public std::unique_ptr<int>
^
unique_ptr.cpp:27:7: note: ‘int_ptr’ has a non-trivial destructor

在您的情况下,如评论中所建议,使用自定义删除器。 STL 容器不太适合继承。

这里是自定义删除器的示例:

#include <memory>
#include <iostream>

template <typename T>
struct Deleter
{
void operator()(T* t)
{
std::cout << "Deleter::oerator(): " << t << std::endl;
delete t;
}
};

struct A
{
A()
{
std::cout << "A::A()" << std::endl;
}

~A()
{
std::cout << "A::~A()" << std::endl;
}
};

int main(int argc, char const *argv[])
{
std::unique_ptr<A, Deleter<A>> ptr(new A);


return 0;
}

输出:

A::A()
Deleter::oerator(): 0x600010480
A::~A()

( live run

关于c++ - constexpr 构造函数中不能使用 constexpr 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24975149/

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