0

According to the reference, when you call count() on a std::chrono::seconds variable, you get the result as the data type rep. Rep is short for "representation".

#include <chrono>
#include <thread>

int main()
{
    using namespace std::chrono_literals;
    std::chrono::time_point<std::chrono::steady_clock> t1 = std::chrono::steady_clock::now();
    std::this_thread::sleep_for(2s);
    std::chrono::time_point<std::chrono::steady_clock> t2 = std::chrono::steady_clock::now();
    auto count = std::chrono::duration_cast<std::chrono::seconds>(t2 - t1).count();
    auto sizeInBytes = sizeof(count);

    size_t countCasted = count; // The warning is produced for this line

    return 0;
}

When I compile this with C++14 for x86, I get following warning:

warning C4244: "Initialization": Conversion from "_Rep" to size_t, possible loss of data

  • sizeInBytes on x86: 8
  • sizeInBytes on x64: 8

Is sizeof(count) always 8? Why doesn't count() return size_t?

nielsen
  • 5,641
  • 10
  • 27
Christian Troester
  • 167
  • 1
  • 2
  • 10
  • `sizeof(count)` is compiler/system-dependent. The C++ standard only places minimum requirements on the `rep` type, it does not require a specific size. It does require that it is signed, though (which makes sense since a difference could be negative). `size_t` has a very different purpose and is unsigned (which makes sense since an amount of memory cannot be negative). – nielsen May 30 '23 at 11:16

1 Answers1

1

Is sizeof(count) always 8?

It is not guaranteed to be.

Why doesn't count() return size_t?

Because it is signed.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111