Talk:Copy constructor (C++)

Latest comment: 10 years ago by 2001:4898:80E8:EE31:0:0:0:4 in topic Example wrong?

[Headline text]

edit

I think, it will be great if someone with good c++ skills will modify Copy constructors and templates section, and write more about "An explicit, non-template, copy constructor must also be provided for construction of Array from Array." with examples.I found this article with Google with hope to find hints about it, but it's not enough for me to understand it(may be i'm stupid? :) ) --Anonymous —Preceding unsigned comment added by 93.178.67.13 (talk) 00:08, 1 October 2008 (UTC)Reply

Why do we need to use & in the definition of a copy constructor? --Anonymous


This article has an error regarding the implicit copy constructor. It does not perform a "byte-by-byte" copy of its members, since its members could have user-defined copy constructors as well. The standard (2003, 12</math>.8.8) specifies:

The implicitly-defined copy constructor for class X performs a memberwise copy of its subobjects. The order of 
copying is the same as the order of initialization of bases and members in a user-defined constructor (see 12.6.2). 
Each subobject is copied in the manner appropriate to its type:

— if the subobject is of class type, the copy constructor for the class is used;
— if the subobject is an array, each element is copied, in the manner appropriate to the element type;
— if the subobject is of scalar type, the built-in assignment operator is used.

Virtual base class subobjects shall be copied only once by the implicitly-defined copy constructor (see
12.6.2).

I will correct this now. If someone has a reference that says that "trivial copy constructors" are defined as being just bitwise copies, please add that explanation (or give me the reference and I will add it).

--Gfaraj 04:18, 23 October 2006 (UTC)Reply


I added a definition for the copy constructor as it is defined in the C++ standard. There is a bug in the example program that was provided for the explicit copy constructor. First, it is not allocating the correct length of characters: it should be strlen(dsgn) + 1. It's missing the "+ 1". Also, it's unsafe to call setDesignation with a string longer than the string used to construct the Employee instance. The default constructor does nothing to initialize the designation string either. Finally, the whole example is very unsafe and promotes incorrect C++ programming. I suggest it be replaced with a more effective example.

--Gfaraj 05:39, 23 October 2006 (UTC)Reply

Deep copy

edit

I have moved this from the article because it needs work:

  1. it needs tidying up for tone and style
  2. I don't think it actually compiles
  3. it appears to repeat deep copy and is probably unnecessarily detailed for this article as well as repeating the preceeding example

Section content

edit

Deep copy is a way how the data inside the objects are copied during invocation of copy constructor or assignment operator. The essence of deep copy is that it copies all data inside the object (not only pointers on the data). Other ways doesn't copy dynamic alocated data, they create a bit copy of first object, so the copied pointers inside the new object still refers to the memory of the first one. In same cases it might be a problem, which you can solve using deep copy. What do you need to create a deep copy?

  1. Constructor - It creates internal dynamic data structures
  2. Destructor - It destroys internal dynamic data structures
  3. Copy constructor - It creates internal dynamic data structures and makes a copy of internal data of the objects
  4. Overload assigment operator - It makes a copy of internal data of the objects

Example of deep copy implementation:

# include <iostream>

using namespace std;

class deep_copy
{
     int *dynamic_data;                   
     public:

     /* Constructor initializes internal data structures */
     deep_copy(int data) 
     { 
       dynamic_data = new int;
       *dynamic_data = data; 
     }
            
     /* Copy constructor initializes internal data structures and copies all data from the other object to self */
     deep_copy(const deep_copy& dc) 
     { 
      if (dynamic_data == NULL) dynamic_data = new int;
      if (this != &dc) *dynamic_data =* (dc.dynamic_data);                      
     }     

     /* Overloaded assigment operator which copies all data from the other object to self  */
     deep_copy& operator=(const deep_copy& dc)
     { 
      if (this != &dc) *dynamic_data = *(dc.dynamic_data);
      return *this;                 
     }                                  

     /* Destructor which delete all dynamic allocated data */           
     ~deep_copy() { delete(dynamic_data); }            

     /* Prints data inside object - only for demonstration of functionality */
     void vypis() { cout << *dynamic_data; }          
};

int main(int argc, char *argv[])
{
   deep_copy *x = new deep_copy(3); // I create new dynamic number
   deep_copy *y = new deep_copy(0); // I create new dynamic number
   *y = *x;    		     // I make a deep copy, so y = 3
   *x = 4;			     // Using a copy constructor i set x to 4 	
   x->vypis();			     // Prints 4	
   y->vypis();			     // Prints 3 - that's because i have made a deep copy
   return 0;
}

Rich257 10:07, 30 October 2006 (UTC)Reply


Yes, I agree. A better example should be written for this article. Why does the above example allocate a deep_copy in the free store? It is an unnecessary (and misleading) complication that contributes nothing to this article. --Gfaraj 04:24, 5 November 2006 (UTC)Reply



A copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment).

A variable is declared which is initialized from another object, eg,

Person q("Mickey"); // constructor is used to build q.

Person r(p); // copy constructor is used to build r.

Person p = q; // copy constructor is used to initialize in declaration.

p = q; // Assignment operator, no constructor or copy constructor.

A value parameter is initialized from its corresponding argument.

f(p); // copy constructor initializes formal value parameter.

An object is returned by a function. C++ calls a copy constructor to make a copy of an object in each of the above cases. If there is no copy constructor defined for the class, C++ uses the default copy constructor which copies each field, ie, makes a shallow copy.

BY D Murli(India-Bhilai(C.G)) 25-6-2007 : 12:08:26

Category

edit

Hello, Isn't this page a candidate for "Articles with example C++ code" category? Can some one please edit this to reflect the same. Thanks, Raoravikiran (talk) 09:11, 6 March 2009 (UTC)Reply

Done. decltype 09:58, 6 March 2009 (UTC)Reply

Qualifier order

edit

Note that it is a purely aesthetic change, however there was mixed usage throughout the article, so this change might reduce any confusion for those new to the language. In addition, although it violates the easy-to-read nature of right-to-left declarations, it is the far more common form, though I am too lazy to prove that. It is, however, the order that the standard uses so it is probably best to talk about qualifier order else-where, and focus on the copy constructors themselves here. To clarify the change I made is here: http://en.wikipedia.org/w/index.php?title=Copy_constructor&oldid=309822601 I was bold and hope this improves the article 216.94.43.50 (talk) 18:19, 24 August 2009 (UTC)Reply

C++11

edit

Hello!

I read in this article : "Hence, there is always one copy constructor that is either defined by the user or by the system." However, it seems to me that one can remove such a copy constructor in C++11 such as in the following example :

   SymbolIndexer(const SymbolIndexer& that) = delete;

The sentence in the introduction might need some modifications ?


Example wrong?

edit

In the comments for example

 X a = X();

it is mentioned that the compiler will create a temporary object, then invoke the copy constructor X::X(const X&) Not sure what the standard says, but with Visual Studio, the copy constructor is not invoked in the following example:

 class X {
 public:
   X() { printf("X::X()\n"); }
   X(const X& copy_from_me) { printf("X::X(const X&)\n"); }
 }
 ...
 X a = X();

instead the default constructor is called (and if only the copy constructor is defined, it doesn't compile). — Preceding unsigned comment added by 2001:4898:80E8:EE31:0:0:0:4 (talk) 23:15, 19 August 2014 (UTC)Reply