首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用std::chrono::time_point隐式删除特殊函数

用std::chrono::time_point隐式删除特殊函数
EN

Stack Overflow用户
提问于 2020-12-19 08:40:20
回答 1查看 187关注 0票数 3

我有这样的代码

代码语言:javascript
复制
#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;
}

试图编译它会导致

代码语言:javascript
复制
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说明符,则编译良好:

代码语言:javascript
复制
MyClass() = default;
MyClass(MyClass const&) noexcept = default;
MyClass(MyClass&&) noexcept = default;
MyClass& operator=(MyClass const&) noexcept = default;
MyClass& operator=(MyClass&&) noexcept = default;

所以我有两个问题:

  • 为什么time _point的默认构造函数不是noexcept**?** --据我所知,它只包含一个表示自纪元以来时间的整数,如果我相信优先选择,默认构造函数应该是0
  • 为什么只从默认构造函数中删除noexcept ?如果编译器说它生成了MyClass()而不是MyClass() noexcept,并因此删除了它,那么对于MyClass(MyClass const&)来说应该是一样的,对吧?但是编译器允许我在这里不抱怨地复制..。
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-19 14:17:45

  • 为什么time_point的默认构造函数不是空的?

noexcept第一次进入C++11的标准时,委员会对“过度应用”非常犹豫不决。在标准中添加noexcept要比删除容易得多。在保守地应用它时,“条件”noexcept常常被回避。

我希望看到“条件”noexcept应用于<chrono>。对于time_point默认构造函数,noexcept将以rep是否为noexcept默认构造函数为条件。rep不必是整数。它可能是一个具有抛出默认构造函数的类类型。但是专门化的steady_clock::time_point总是noexcept,因为它的rep必须是整数的。

  • 为什么只从默认构造函数中删除Why?

因为具有用户声明的默认构造函数,但具有编译器提供的复制构造函数。。这是编译器提供的特殊成员比用户声明的成员更“聪明”的一个例子。

编译器提供的time_point副本构造函数实际上已经有了一个“条件”noexcept。您可以通过编写更少的代码来免费获得这些信息。如果time_point默认构造函数是编译器提供的(它应该是编译器),那么它也会在您的示例中工作。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65368064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档