Namespaces
Variants
Actions

Talk:cpp/chrono/duration/duration

From cppreference.com

I don't think it's clear what's intended to happen when you construct a duration object from a double set to std::numeric_limits<double>::infinity().

I would have expected an exception, but running the following code in g++ -std=c++11 gives me

   std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(
                  std::chrono::duration<double,std::ratio<1,1>>(
                    std::numeric_limits<double>::infinity()
                  )
                ).count();

Output: -9223372036854775808

193.44.5.120 06:29, 2 February 2015 (PST)


It behaves exactly as specified, could you explain why do you expect an exception and of what type? --Cubbi (talk) 07:18, 2 February 2015 (PST)


  • For a positive infinity I find it peculiar to get a large negative value
  • I think documentation should explicitly state that such values is not "correctly" handled
If the duration object can not represent infinity my opinion is that it should do one of the following:
  • Implementation may throw an exeption, for example std::overflow_error
  • Implementation may convert it to the closest possible value (which in this case would be max() not min())
  • Or the interface should change not to accept double types (since it can not handle all possible values)
193.44.5.120 23:50, 2 February 2015 (PST)
This wiki has no control over the C++ language, so it can't change interfaces or behaviors. I edited std::chrono::duration_cast to mention that the conversion is as if by static_cast, including the undefined behavior on float to integer conversion where the float is out of range. --Cubbi (talk) 03:03, 3 February 2015 (PST)


Out of curiosity, does anyone know why the constructor from a Rep value takes Rep by reference? I see that the gcc implementation just copies the value anyway... taking a reference seems more restrictive (can't pass rvalues etc) and I am not clear on the benefit. gubbins (talk) 17:13, 28 June 2015 (PDT)

I think there may be a typo. From the example:

std::chrono::hours h(1); // one hour
std::chrono::milliseconds ms{3}; // 3 milliseconds
std::chrono::duration<int, std::kilo> ks(3); // 3000 seconds

Am I correct in assuming the second line should read "ms(3)", to initialize "ms" with the value of 3? 132.183.13.76 07:54, 12 August 2016 (PDT)

ms{3} and ms(3) do the same thing in this case: they are both value-initialization. Not sure why the example doesn't use the same throughout, probably just to show that both ways work. Given that C++14 is standard now, we could add a literal for variety. --Cubbi (talk) 09:31, 12 August 2016 (PDT)
Um, that's not value-initialization... T. Canens (talk) 11:47, 12 August 2016 (PDT)
Right, was actually thinking direct-initialization, but linked the wrong thing. --Cubbi (talk) 11:50, 12 August 2016 (PDT)