`
standalone
  • 浏览: 609785 次
  • 性别: 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终极解释

    在C++编程语言中,复制构造函数(Copy Constructor)和赋值运算符(Assignment Operator)是两个非常关键的概念,特别是在处理对象的拷贝和赋值时。它们默认由编译器提供,但通常需要根据具体需求进行自定义,以确保正确...

    C++箴言:资源管理类的拷贝行为

    // Copy constructor and copy assignment operator are deleted to prevent copying. Lock(const Lock &) = delete; Lock &operator=(const Lock &) = delete; private: Mutex *mutexPtr; }; ``` #### 拷贝...

    swap_test.rar_assignment_mv assignment swap

    这个模式被称为“copy-and-swap”或“move-and-swap”策略,其中“mv_assignment”可能就是指的这个策略。这种策略结合了复制构造函数和赋值运算符的优点,提供了一种安全且高效的实现方式。基本步骤是: 1. 创建一...

    面向对象程序设计英文教学课件:08 Copy Control.ppt

    Copy Control 涉及到对象复制和赋值操作时的行为控制,包括拷贝构造函数(Copy Constructor)、赋值运算符(Assignment Operator)以及移动语义(Move Semantics)。这个英文教学课件"08 Copy Control.ppt"主要讲解...

    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.

    面向对象程序设计英文教学课件:08-Copy-Control.pptx

    复制控制涉及到两个主要操作:拷贝构造函数(Copy Constructor)和赋值运算符(Assignment 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{ ...

    effective c++

    3. **Item 14: Make your copy constructor and copy-assignment operator either both trivial or both non-trivial** - **核心观点**:指出复制构造函数和复制赋值运算符应保持一致性,要么同时为简单实现,要么...

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

    - **Constructors:** Explains constructor definitions, including default constructors, initializer lists, and copy constructors. - **Destructors:** Describes destructor definitions. - **Members That ...

    c++ Strings

    // Copy constructor std::string str3(5, 'a'); // Five 'a's ``` 2. **Assignment**: - The `std::string` class overloads the assignment operator (`=`) for easy assignment between strings. ```cpp ...

    快速复制结构体变量和类实例

    在C++中,可以使用拷贝构造函数(Copy Constructor)和赋值运算符(Assignment Operator)来实现深拷贝。拷贝构造函数用于初始化新对象为已有对象的副本,而赋值运算符则用于将一个已存在对象的值赋给另一个对象。这...

    工学四川大学C构造函数和析构函数PPT学习教案.pptx

    除了以上介绍,构造函数和析构函数还有其他应用场景,如移动构造函数(Move Constructor)和移动赋值运算符(Move Assignment Operator),这些在现代C++中用于优化对象的复制效率,特别是在处理大对象或资源密集型...

    C++综合实验报告.doc

    3. **拷贝构造函数(Copy Constructor)**:当一个对象被用作另一个对象的初始值时自动调用。在这个实验中,拷贝构造函数用于确保新创建的对象与原有对象具有相同的值。 4. **赋值运算符重载(Overloading ...

    C++专有名词定义

    85. **复制构造函数(Copy Constructor)**:用于创建对象的副本。 86. **默认构造函数(Default Constructor)**:没有参数的构造函数。 87. **默认赋值运算符(Default Assignment Operator)**:用于对象赋值的...

    c++中拷贝构造函数的参数类型必须是引用

    4. `copy constructor`:`CExample ccc = aaa;`这里`ccc`尚未实例化,所以调用拷贝构造函数。 5. `copy constructor`:`bbb.myTestFunc(aaa);`这里的参数传递实际上也涉及拷贝构造函数,因为对象被用作函数参数。 ...

    C++类模板实现的队列

    在实际应用中,队列可能还需要其他功能,如获取队列的大小(size)、合并两个队列(merge)或者复制队列(copy constructor和assignment operator)。这些功能可以根据具体需求进行扩展。 文件名称“TQueue”可能是...

Global site tag (gtag.js) - Google Analytics