'段错误'使用std :: chrono计算经过时间时

时间:2015-12-24 07:08:33

标签: c++ c++11

我改变了this code并编写了这个函数:

#include <ctime>
#include <iomanip>
#include <iostream>
#include <chrono>

#define TIMER(name) Timer timer__(name);
class Timer
{
public:

    Timer(const std::string& name) :
            name_(name), start_(std::chrono::system_clock::now())
    {
    }

    ~Timer()
    {
        auto duration = std::chrono::system_clock::now() - start_;
        std::cout << std::setw(90) << std::left << name_ << ": " <<  std::chrono::duration_cast<std::chrono::seconds>(duration).count() << "s" << std::endl;
    }
private:
    std::string name_ = 0;
    std::chrono::time_point<std::chrono::system_clock> start_ ;
};

问题是我有时会遇到段故障。

用法:

将这样的东西放在main()中:

TIMER("Total time");

我使用gcc 5.2.1版编译了程序。

1 个答案:

答案 0 :(得分:2)

有两个评论:
1.如@Mankarse所述,从= 0;中删除std::string name_ = 0; 2.来自here

  

包含双下划线__或以下划线后跟大写字母开头的每个标识符保留给实现以供任何使用。

所以将Timer timer__(name)更改为Timer my_timer(name)