Why copy constructor and assignment operator are disallowed?

后端 未结 3 1243
面向向阳花
面向向阳花 2020-12-19 07:07
#undef GOOGLE_DISALLOW_EVIL_CONSTRUCTORS
#define GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeName)    \\
   TypeName(const TypeName&);                           \\
            


        
3条回答
  •  别那么骄傲
    2020-12-19 07:35

    The problem with the copy constructor and copy-assignment operator is that the compiler generates implementations automatically if they're not explicitly declared.

    This can easily cause unintended problems. If a class has a non-trivial destructor, it almost always needs to provide its own implementations for the copy constructor and copy-assignment operator too (this is the Law of the Big Three) since the default compiler-generated ones usually will do the wrong thing.

    Violating the Law of the Big Three often leads to errors such as double-frees of data members and memory corruption. It's not uncommon for these sort of errors to arise because the author of the class never bothered to think about copy behavior and because it's easy for consumers to copy objects unintentionally.

    Unless the author of the class has actually thought about how to properly copy instances of that class (or unless the class has a trivial destructor), then it's better to explicitly disallow copying to avoid potential problems. Implementing copyability could then be deferred until there's an actual need for it.

提交回复
热议问题