4

I have a class to measure and log the time consumption in a scope

class MeasureTime {
  public:
    MeasureTime(const std::string log_message) : log_message(log_message), t_start(std::chrono::steady_clock::now()){};
    ~MeasureTime() {
        const auto t_end = std::chrono::steady_clock::now();
        const auto duration = std::chrono::duration_cast<std::chrono::duration<double>>(t_end - t_start).count();
        std::cout << "Time measurement: " << log_message << " took " << duration " seconds.\n";
    }

  private:
    const std::chrono::_V2::steady_clock::time_point t_start;
    const std::string log_message;
};

If I have a scope like this everything works fine.

{
    MeasureTime measureTime("message");
    // do something
} // The destructor of MeasureTime is called here

On the other hand, if I just construct the object without assigning it to a variable the constructor is called immediately and the time measurement fails.

{
    MeasureTime("message"); // The destructor of MeasureTime is called immediately here
    // do something
}

How can I ensure that the created object is assigned to an object?

Cœur
  • 37,241
  • 25
  • 195
  • 267
schorsch312
  • 5,553
  • 5
  • 28
  • 57

0 Answers0