Why aren't there compiler-generated swap() methods in C++0x?

前端 未结 4 1652
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 19:01

C++ compilers automatically generate copy constructors and copy-assignment operators. Why not swap too?

These days the preferred method for implementing

4条回答
  •  醉梦人生
    2020-12-08 19:26

    Is even compiler-generated move constructor/assignment planned (with the default keyword)?

    If there is a compiler-generated swap method, an implicit copy-assignment operator can be implemented using copy-and-swap.

    Even though the idiom leaves the object unchanged in case of exceptions, doesn't this idiom, by requiring the creation of a third object, make chances of failure greater in the first place?

    There might also be performance implications (copying might be more expensive than "assigning") which is why I don't see such complicated functionality being left to be implemented by the compiler.

    Generally I don't overload operator= and I don't worry about this level of exception safety: I don't wrap individual assignments into try blocks - what would I do with the most likely std::bad_alloc at that point? - so I wouldn't care if the object, before they end up destroyed anyway, remained in the original state or not. There may be of course specific situations where you might indeed need it, but I don't see why the principle of "you don't pay for what you don't use" should be given up here.

提交回复
热议问题