简体   繁体   中英

Why copy constructor and assignment operator are disallowed?

#undef GOOGLE_DISALLOW_EVIL_CONSTRUCTORS
#define GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeName)    \
   TypeName(const TypeName&);                           \
   void operator=(const TypeName&)

I'm, reading open source code from google. Why copy constructor and assignment operator are disallowed?

To prevent instances of the class being copied or assigned. Most classes should not allow copying. Consider for example a BankAccount class - if you are writing software for a bank, they will not be too happy if you create copies of accounts and then apply credits and debits to those different copies.

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.

If your type contains pointer or reference members, or it makes no semantic sense for it to be copied (eg it has a resource handle that must be freed in the destructor) then it is good practice to disable the copy constructor and assignment operator. In C++0x (eg in g++ 4.4 or later in -std=c++0x mode) you can declare them deleted. In older compilers you just declare them private and unimplemented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM