Skip to content

Allow std::vector::insert to compile when elements have a deleted copy assignment operator #47963

@iboB

Description

@iboB
mannequin
Bugzilla Link 48619
Version unspecified
OS All
CC @iboB,@dwblaikie,@mclow

Extended Description

Create a class X which is copy-constructible but not copy-assignable

struct X {
    X();
    X(const X&);
    X& operator=(const X&) = delete; // !!
    X(X&&) noexcept;
    X& operator=(X&&) noexcept;
    int data = 54;
};

Have vectors of X a and b. Try to add all elements of b at the front of a:

void add_to_front(std::vector<X>& a, const std::vector<X>& b) {
    a.insert(a.begin(), b.begin(), b.end());
}

Live demo: https://godbolt.org/z/K1WT8n

It doesn't compile. My guess is that code which will never get invoked, still needs to compile (or, worse yet, copy assignment does get invoked?!)

The only way to achieve the desired behavior efficiently is to use a custom vector implementation. There is a stackoverflow question which has some worse workarounds: https://stackoverflow.com/questions/65489039/how-to-efficiently-insert-multiple-copy-constructible-but-not-copy-assignable-el

This does compile and work on msvc, so a compile-time check for the copy-assignment code is possible.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugzillaIssues migrated from bugzillalibc++libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.rejects-valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions