我有一个类来测量和记录示波器中的时间消耗
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;
};
如果我有这样的示波器,一切正常。
{
MeasureTime measureTime("message");
// do something
} // The destructor of MeasureTime is called here
另一方面,如果我只是构造对象而不将其分配给变量,则构造函数将立即被调用,并且时间测量将失败。
{
MeasureTime("message"); // The destructor of MeasureTime is called immediately here
// do something
}
如何确保将创建的对象分配给对象?