Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return a variable from a destructor

So I have a struct called timer which determines how much time did a block of code take to execute and complete and I’m going to run few benchmarks on my sorting algorithm and take the average value of time it took for each sorting algorithm.

struct Example{
    std::chrono::time_point<std::chrono::steady_clock> start, end;
    Example() {
        start = std::chrono::high_resolution_clock::now();
    }
    ~Example() {
        end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<float>  duration = end - start;
        float ms = duration.count() * 1000.0f;
        std::cout << ms << " miliseconds\n";
        // a way to return ms?
    }
};

However, I was not able to find a way to get the variable ms out of the destructor and assign it to something after measuring the time. Is there any way to get it out or can I write my struct in a better way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t return anything from the deststructor but you can assign the value to a variable that you supply to Example upon creation. Example:

#include <chrono>
#include <iostream>

template <class Clock = std::chrono::steady_clock>
struct Example {
    std::chrono::time_point<Clock> start;
    std::chrono::duration<float>& duration;         // a reference

    Example(std::chrono::duration<float>& dur) :    // take the duration as an argument
        start(Clock::now()),
        duration(dur)
    {}

    ~Example() {
        auto end = Clock::now();
        duration = end - start; // assign the value
    }
};

int main() {
    std::chrono::duration<float> duration;
    {
        Example<> x(duration);
    }
    std::cout << duration.count() << '\n';  // read it afterawrds
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading