[英]'Segment fault' when calculating the elapsed time using std::chrono
I changed this code and have written this function:我更改了此代码并编写了此函数:
#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_ ;
};
The problem is that sometimes I get segment fault.问题是有时我会遇到段错误。
usage:用法:
put something like this in the main():把这样的东西放在 main() 中:
TIMER("Total time");
I compiled the program with gcc version 5.2.1.我用 gcc 版本 5.2.1 编译了程序。
There are two remarks:有两点说明:
1. as mentioned by @Mankarse, remove = 0;
1. 正如@Mankarse 所提到的,remove
= 0;
from std::string name_ = 0;
来自
std::string name_ = 0;
2. From here : 2. 从这里:
Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.
每个包含双下划线 __ 或以下划线后跟大写字母开头的标识符都保留给实现以供任何使用。
So change Timer timer__(name)
to something like Timer my_timer(name)
因此,将
Timer timer__(name)
更改为Timer my_timer(name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.