我有这样的代码
#include <chrono>
using std::chrono::steady_clock;
using std::chrono::time_point;
class MyClass
{
public:
MyClass() noexcept = default;
MyClass(MyClass const&) noexcept = default;
MyClass(MyClass&&) noexcept = default;
MyClass& operator=(MyClass const&) noexcept = default;
MyClass& operator=(MyClass&&) noexcept = default;
private:
time_point<steady_clock> timestamp;
};
int main() {
MyClass myObject;
MyClass myOtherObject(myObject);
return 0;
}试图编译它会导致
prog.cpp: In function ‘int main()’:
prog.cpp:18:10: error: use of deleted function ‘constexpr MyClass::MyClass()’
MyClass myObject;
^~~~~~~~
prog.cpp:8:5: note: ‘constexpr MyClass::MyClass() noexcept’ is implicitly deleted because
its exception-specification does not match the implicit exception-specification ‘’
MyClass() noexcept = default;但是,如果删除默认构造函数的noexcept说明符,则编译良好:
MyClass() = default;
MyClass(MyClass const&) noexcept = default;
MyClass(MyClass&&) noexcept = default;
MyClass& operator=(MyClass const&) noexcept = default;
MyClass& operator=(MyClass&&) noexcept = default;所以我有两个问题:
noexcept**?** --据我所知,它只包含一个表示自纪元以来时间的整数,如果我相信优先选择,默认构造函数应该是0noexcept ?如果编译器说它生成了MyClass()而不是MyClass() noexcept,并因此删除了它,那么对于MyClass(MyClass const&)来说应该是一样的,对吧?但是编译器允许我在这里不抱怨地复制..。发布于 2020-12-19 14:17:45
当noexcept第一次进入C++11的标准时,委员会对“过度应用”非常犹豫不决。在标准中添加noexcept要比删除容易得多。在保守地应用它时,“条件”noexcept常常被回避。
我希望看到“条件”noexcept应用于<chrono>。对于time_point默认构造函数,noexcept将以rep是否为noexcept默认构造函数为条件。rep不必是整数。它可能是一个具有抛出默认构造函数的类类型。但是专门化的steady_clock::time_point总是noexcept,因为它的rep必须是整数的。
因为具有用户声明的默认构造函数,但具有编译器提供的复制构造函数。。这是编译器提供的特殊成员比用户声明的成员更“聪明”的一个例子。
编译器提供的time_point副本构造函数实际上已经有了一个“条件”noexcept。您可以通过编写更少的代码来免费获得这些信息。如果time_point默认构造函数是编译器提供的(它应该是编译器),那么它也会在您的示例中工作。
https://stackoverflow.com/questions/65368064
复制相似问题