Sujet : Re: Why std::vector requires noexcept move constructor?
De : Bonita.Montero (at) *nospam* gmail.com (Bonita Montero)
Groupes : comp.lang.c++Date : 01. Jul 2025, 18:13:09
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <10414v2$2v4e9$1@raubtier-asyl.eternal-september.org>
References : 1
User-Agent : Mozilla Thunderbird
Am 15.06.2025 um 10:25 schrieb Marcel Mueller:
I discovered shortly that a move constructor that is not declared as noexcept is ignored by std::vector. Instead the objects are moved by
the copy constructor.
Why?
The copy constructor is even more likely not declared as noexcept.
Marcel
Unbelievable, but you're right: clang++-20 and g++-14 move only if the
move-constructor is noexcept. MSVC moves always.
#include <iostream>
#include <vector>
using namespace std;
template<bool NX>
struct S
{
inline static size_t nCopied, nMoved;
S() = default;
S( S const &other )
{
++nCopied;
}
S( S &&other ) noexcept(NX)
{
++nMoved;
}
};
int main()
{
auto test = []<bool NX>( bool_constant<NX> )
{
cout << (NX ? "noexcept" : "no noexcept") << endl;
using S = S<NX>;
S::nCopied = 0;
S::nMoved = 0;
vector<S> vs;
for( size_t n = 0; n != 0x1000; ++n )
vs.emplace_back();
cout << "\tcopied: " << S::nCopied << endl;
cout << "\tmoved: " << S::nMoved << endl;
};
test( false_type() );
test( true_type() );
}
I think that's while moving could fail and the runtime may have a
partitially moved vector with that.