Is C++’s default copy-constructor inherently unsafe? Are iterators fundamentally unsafe too?

C++ copy/move ctor/assign are safe for regular value types. Regular value types behave like integers or other “regular” values.

They are also safe for pointer semantic types, so long as the operation does not change what the pointer “should” point to. Pointing to something “within yourself”, or another member, is an example of where it fails.

They are somewhat safe for reference semantic types, but mixing pointer/reference/value semantics in the same class tends to be unsafe/buggy/dangerous in practice.

The rule of zero is that you make classes that behave like either regular value types, or pointer semantic types that don’t need to be reseated on copy/move. Then you don’t have to write copy/move ctors.

Iterators follow pointer semantics.

The idiomatic/elegant around this is to tightly couple the iterator container with the pointed-into container, and block or write the copy ctor there. They aren’t really separate things once one contains pointers into the other.

Leave a Comment