C++ chrono::operator=() Function



The std::chrono::operator=() function in C++, is an assignment operator that assigns one chrono duration, time point or clock type to another of the same type. This operator facilitates copying or moving values, making it easier to manage time based calculations.

For example, if we consider two chono duration instances, using this operator we can directly set one instance to match the others duration.

Syntax

Following is the syntax for std::chrono::operator=() function.

duration& operator=( const duration &other ) = default;

Parameters

  • other − It is the duration to copy from.

Return value

This function returns the result of the operation.

Example 1

In the following example, we are going to assign the duration from one object to another.

#include <iostream>
#include <chrono>
int main() {
   std::chrono::seconds x1(23);
   std::chrono::seconds x2;
   x2 = x1;
   std::cout << "Result : " << x2.count() << " seconds\n";
   return 0;
}

Output

Output of the above code is as follows −

Result : 23 seconds

Example 2

Consider the following example, we are going to reassign the duration using the operator=().

#include <iostream>
#include <chrono>
int main() {
   std::chrono::seconds x(2);
   std::cout << "Initial time : " << x.count() << " seconds\n";
   x = std::chrono::seconds(22);
   std::cout << "After Updation: " << x.count() << " seconds\n";
   return 0;
}

Output

Following is the output of the above code −

Initial time : 2 seconds
After Updation: 22 seconds
cpp_chrono.htm
Advertisements