Why does C++ think my class is copy-constructible when it can’t be copy-constructed? -- Raymond Chen

RaymondChen_5in-150x150.jpgIn C++, the presence of a user-declared (but not explicitly deleted) copy constructor is enough for the type to be considered copy-constructible by traits like std::is_copy_constructible. However, whether that constructor is instantiable is a separate matter—if it attempts to call a deleted base copy constructor, you'll still get a compile-time error when you actually try to use it.

Why does C++ think my class is copy-constructible when it can’t be copy-constructed?

by Raymond Chen

From the article:

Consider the following scenario:

template<typename T>
struct Base
{
    // Default-constructible
    Base() = default;

    // Not copy-constructible
    Base(Base const &) = delete;
};

template<typename T>
struct Derived : Base<T>
{
    Derived() = default;
    Derived(Derived const& d) : Base<T>(d) {}
};

// This assertion passes?
static_assert(
    std::is_copy_constructible_v<Derived<int>>);

Why does this assertion pass? It is plainly evident that you cannot copy a Derived<int> because doing so will try to copy the Base<int>, which is not copyable.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.