Skip to content

Containers should correctly handle unusual size_type/difference_type #5546

Description

Describe the bug

Currently, the following program doesn't compile with MSVC STL.

#include <memory>
#include <string>

template <class T>
struct small_ator {
    using value_type = T;

    using size_type       = unsigned short; // !!!
    using difference_type = short; // !!!

    small_ator() = default;
    template <class U>
    constexpr small_ator(const small_ator<U>&) noexcept {}

    T* allocate(size_type n) {
        return std::allocator<T>{}.allocate(n);
    }

    void deallocate(T* p, size_type n) {
        return std::allocator<T>{}.deallocate(p, n);
    }

    friend bool operator==(const small_ator&, const small_ator&) = default;
    template <class U>
    friend constexpr bool operator==(const small_ator&, const small_ator<U>&) {
        return true;
    }
};

int main() {
    std::basic_string<char, std::char_traits<char>, small_ator<char>> s = "hello world";
}

In this case, the size_type is changed in integral promotion, so std::max doesn't work.

Command-line test case

https://godbolt.org/z/xdcqab8xj

Expected behavior

This program compiles, with no C4244 warning (or its friend).

STL version

Effectively, all existing versions since open-sourcing.

Additional context

We should also audit cases where

  • the size_type or difference_type is narrower than int, or
  • on 32-bit platforms, the size_type or difference_type are 64-bit.

And keeps that there're no compile errors or warnings on narrowing, for all containers and container adaptors that can have unusual size_type and difference_type types.

Tasks

Containers:

  • basic_string
  • deque
  • forward_list
  • hive
  • list
  • vector
  • map
  • multimap
  • set
  • multiset
  • unordered_map
  • unordered_multimap
  • unordered_set
  • unordered_multiset

(array and inplace_vector are unrelated, as their size_type and difference_type must be size_t and ptrdiff_t respectively.)

Container adaptors (need to verify adaption of standard sequence containers):

  • priority_queue
  • queue
  • stack
  • flat_map
  • flat_multimap
  • flat_set
  • flat_multiset

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions