`
standalone
  • 浏览: 600038 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

copy constructor and copy assignment

    博客分类:
  • c++
阅读更多

When copies of objects are made

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 ashallow copy.

Don't write a copy constructor if shallow copies are ok

If the object has no pointers to dynamically allocated memory, a shallow copy is probably sufficient. Therefore the default copy constructor, default assignment operator, and default destructor are ok and you don't need to write your own.

If you need a copy constructor, you also need a destructor and operator=

If you need a copy constructor, it's because you need something like a deep copy, or some other management of resources. Thus is is almost certain that you will need a destructor and override the assignment operator.

Copy constructor syntax

The copy constructor takes a reference to a const parameter. It is const to guarantee that the copy constructor doesn't change it, and it is a reference because a value parameter would require making a copy, which would invoke the copy constructor, which would make a copy of its parameter, which would invoke the copy constructor, which ...

Here is an example of a copy constructor for the Point class, which doesn't really need one because the default copy constructor's action of copying fields would work fine, but it shows how it works.

//=== file Point.h =============================================
class Point {
    public:
        . . .
        Point(const Point& p);   // copy constructor
        . . .
//=== file Point.cpp ==========================================
. . .
Point::Point(const Point& p) {
    x = p.x;
    y = p.y;
}
    . . .
//=== file my_program.cpp ====================================
. . .
Point p;            // calls default constructor
Point s = p;        // calls copy constructor.
p = s;              // assignment, not copy constructor.

Difference between copy constructor and assignment

A copy constructor is used to initialize a newly declared variable from an existing variable. This makes a deep copy like assignment, but it is somewhat simpler:

  1. There is no need to test to see if it is being initialized from itself.
  2. There is no need to clean up (eg, delete) an existing value (there is none).
  3. A reference to itself is not returned.

Unaddressed issue

[Question: When is the base (parent) class copy constructor called? Is it like Java and the parent constructor is called at the beginning of each constructor? Does it have to be explicit?]

分享到:
评论

相关推荐

    Copy Constructors and Assignment Operators终极解释

    There are plenty of good books written on the subject, but I found no clear and concise set of rules on the Internet for those who don't want to understand every nuance of the language—and just want...

    swap_test.rar_assignment_mv assignment swap

    either copy constructor or assignment operator.

    06-02-2015_05-43-24.zip_assignment

    Your class EnhancedSafeArray will augment the class SafeArray by supporting a copy constructor, a method to return the size of the array, an assignment operator, and an equality test operator.

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Tabs Function Declarations and Definitions Function Calls Conditionals Loops and Switch Statements Pointer and Reference Expressions Boolean Expressions Return Values Variable and Array Initialization...

    Prentice.Hall.C++.for.Business.Programming.2nd.Edition.2005.chm

    The Copy Constructor 528 Section 12.3. Using const with Classes 540 Section 12.4. Objects, Functions and Pointers 556 Section 12.5. Dynamic Allocation of Objects 581 Section 12.6. Static Data...

    浅谈C++ Explicit Constructors(显式构造函数)

    如果自己没有申明,编译器会为我们提供一个copy构造函数、一个copy assignment操作符和一个析构函数。此外,如果没有申明任何构造函数,编译器会为我们申明一个default构造函数。很像下面的Empty类: class Empty{ ...

    Scala for the Impatient 2nd (完整英文第二版 带书签)

    xii Contents14.10 The copy Method and Named Parameters 205 14.11 Infix Notation in case Clauses 206 14.12 Matching Nested Structures 207 14.13 Are Case Classes Evil? 208 14.14 Sealed Classes 209 14.15...

    Addison.Wesley.C++.by.Dissection.2002.pdf

    5.1.6 The Copy Constructor...... 193 5.2 Classes with Destructors...... . . . 195 5.3 Members That Are Class Types..... . . 195 5.4 Example: A Singly Linked List..... . . . 196 5.5 Strings Using ...

    python3.6.5参考手册 chm

    PEP 471 - os.scandir() function – a better and faster directory iterator PEP 475: Retry system calls failing with EINTR PEP 479: Change StopIteration handling inside generators PEP 485: A function...

    一个跨平台的CString源码

    // 2003-MAR-14 - Thanks to Jakko Van Hunen for pointing out a copy-and-paste // bug in one of the overloads of FmtArg. // // 2003-MAR-10 - Thanks to Ronny Schulz for (twice!) sending me some changes /...

    Guide to Scientific Computing in C++

    2.6.3 Tip 3: Equality Versus Assignment . . . . . . . . . . . 2.6.4 Tip 4: Never Ending while Loops . . . . . . . . . . . 2.6.5 Tip 5: Comparing Two Floating Point Numbers . . . . 2.7 Exercises . . . ...

    代码语法错误分析工具pclint8.0

    test.cpp(7): error 1733: (Info -- new in constructor for class 'X' which has no copy constructor) { memset( p, 20, 'a' ); } test.cpp(9): error 669: (Warning -- Possible data overrun for function '...

Global site tag (gtag.js) - Google Analytics