Show: Delphi C++
Display Preferences

DCPC -- Define Copy Constructor

From RAD Studio
Jump to: navigation, search

Go Up to C++ Audits

Description

DCPC detects using default copy-constructor.

Copy-constructor is called when an object is passed by value or an object is returned from a method. If a user does not define a copy constructor, the compiler will create a default copy-constructor that copies objects using bitcopy.

Incorrect

 class SomeClass{
   static int instances;
   std::string myName;
 public:
   SomeClass(const string& name = "") : myName(name){
     instances++;
   };
   ~SomeClass(){
      instances--;
   };
 };
 
 int SomeClass::instances = 0;
 
 int main() {
   SomeClass a("One");
   SomeClass b("Two");
   SomeClass c = a;
 }

Correct

 class SomeClass{
   static int instances;
   std::string myName;
 public:
   SomeClass(const string& name = "") : myName(name){
     instances++;
   };
   SomeClass(const SomeClass& copy) : myName(copy.myName){
     instances++;
   };
   ~SomeClass(){
      instances--;
   };
 };

See Also

Personal tools
RAD Studio 10.2 Tokyo
In other languages
Previous Versions
Assistance