KnowItAllWannabe KnowItAllWannabe - 1 year ago 91
C++ Question

What is the maximum reference count in std::shared_ptr? What happens if you try to exceed it?

If we assume that

stores a reference count (which I realize the standard does not require, but I am unaware of any implementations that don't), that reference count has a limited number of bits, and that means there is a maximum number of references that are supported. That leads to two questions:

  • What is this maximum value?

  • What happens if you try to exceed it (e.g., by copying a std::shared_ptr that refers to an object with the maximum reference count)? Note that
    's copy constructor is declared

Does the standard shed any light on either of these questions? How about common implementations, e.g., gcc, MSVC, Boost?

Jon Jon
Answer Source

We can get some information from the shared_ptr::use_count() function. § says:

long use_count() const noexcept;

Returns: the number of shared_ptr objects, *this included, that share ownership with *this, or 0 when *this is empty.

[Note: use_count() is not necessarily efficient.—end note ]

At first sight the long return type seems to answer the first question. However the note seems to imply that shared_ptr is free to use any type of reference counting it wants to, including things like a list of references. If this were the case then theoretically there would be no maximum reference count (although there would certainly be a practical limit).

There is no other reference to limits on the number of references to the same object that I could find.

It's interesting to note that use_count is documented to both not throw and (obviously) to report the count correctly; unless the implementation does use a long member for the count I don't see how both of these can be theoretically guaranteed at all times.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download