長い間、コピー割り当てを実装する正しい方法 (重要なクラスの場合) は、コピー スワップ イディオムを使用することだと考えていました。
struct A{
... pointer to data
A(A const& other){
... complicated stuff, allocation, loops, etc
}
void swap(A& other){... cheap stuff ...}
A& operator=(A const& other){
A tmp{other};
swap(other);
return *this;
}
};
しかし、その後、Howard Hinnant によるこの講演https://www.youtube.com/watch?v=vLinb2fgkHkを聞きました。彼は、copy-swap イディオムは強い例外の保証を満たすのに適しているが、一般的にはやり過ぎだと言っています。
彼はここでそれについて言及しています:https://youtu.be/vLinb2fgkHk?t=2616
そこで彼は、コピー割り当てを明示的に実装し、コピーstrong_assing(A& target, A const& source)
スワップを含む別の関数を用意することを提案しています。
私が理解していないのは、どのA& operator=(A const& other)
ように実装する必要があるのですか?
彼はこのようなものを持っていることを提案していますか?
A& operator=(A const& other){
... don't allocate if not necessary
... loop element by element
... clean the bare minimum if there is a throw
}
これはstd::vector
実装が行うことですか?つまり、彼らは最後にコピースワップイディオムを使用しないのですか? 標準ベクトルには強力な例外保証が必要ではありませんか?