我想用一个特殊的析构函数重新定义unique_ptr。因此,我使用下面的代码,尝试模拟unique_ptr的一些构造函数。不幸的是,constexpr构造函数拒绝构建,我不知道为什么。
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构造函数中使用?
谢谢你的帮助。
发布于 2014-07-26 21:37:41
Constexpr构造函数是可能的,但是要求相当严格。对于您来说,主要的问题是,正如@dyp所说的,std::unique_ptr不是一个平凡的析构函数,因此不是一个LiteralType。
如果您尝试在int下使用g++:
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()(活跑
https://stackoverflow.com/questions/24975149
复制相似问题