c++ - 使用 std::chrono 计算耗时时出现“段错误”

标签 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. 如@Mankarse 所述,从 std::string name_ = 0;
中删除 = 0; 2. 来自here :

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.

因此,将 Timer timer__(name) 更改为 Timer my_timer(name)

关于c++ - 使用 std::chrono 计算耗时时出现“段错误”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34448747/

相关文章:

Python + setuptools : distributing a pre-compiled shared library with boost. python 绑定(bind)

c++ - DoxyGen 忽略函数

c++ - gcc 无法使用此捕获编译通用 lambda

c++ - 二维数组的自定义迭代器

c++ - 通过 ref 传递数组

c++ - std::vector 上的嵌套循环

c++ - 具有模板模板参数的类模板特化

c++ - 当 typedef 名称与可变参数模板参数名称一致时出现 GCC 错误

c++ - 如何使用枚举类值作为 for 循环的一部分?

c++ - 声明适用于 auto 但不是通过显式声明类型?