使用另一个(现有)对象创建新对象时会发生什么? [英] What happens when a new object is created using another (existing) object?

查看:58
本文介绍了使用另一个(现有)对象创建新对象时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了一本书,上面写着:当我们使用另一个对象初始化一个新创建的对象时-使用复制构造函数创建一个临时对象,然后使用赋值运算符将值复制到新对象中!

I read in a book, it says: when we initialize a newly created object using another - uses copy constructor to create a temporary object and then uses assignment operator to copy values to the new object!

后来在书中我读到:当使用另一个对象初始化新对象时,编译器会创建一个临时对象,然后使用复制构造函数将其复制到新对象.临时对象作为参数传递给副本构造函数.

And later in the book I read: When a new object is initialized using another object, compiler creates a temporary object which is copied to the new object using copy constructor. The temporary object is passed as an argument to the copy constructor.

真的很困惑,实际上发生了什么!!

Really confused, what actually happens!!

推荐答案

我认为这两个语句都不正确-复制赋值运算符未调用.

I don't think either of these statements is correct - the copy-assignment operator is not called.

我将描述发生的情况:

当您创建新对象作为现有对象的副本时,该副本构造函数将被调用:

When you create a new object as a copy of an existing object, then the copy constructor is called:

// creation of new objects
Test t2(t1);
Test t3 = t1;

仅当您分配给现有对象时,才会调用复制分配运算符

Only when you assign to an already existing object does the copy-assignment operator get called

// assign to already existing variable
Test t4;
t4 = t1;

我们可以通过以下小例子来证明这一点:

We can prove this with the following little example:

#include <iostream>

class Test
{
public:
    Test() = default;
    Test(const Test &t)
    {
        std::cout << "copy constructor\n";
    }
    Test& operator= (const Test &t)
    {
        std::cout << "copy assignment operator\n";
       return *this;
    }
};

int main()
{
    Test t1;

    // both of these will only call the copy constructor
    Test t2(t1);
    Test t3 = t1;

    // only when assigning to an already existing variable is the copy-assignment operator called
    Test t4;
    t4 = t1;

    // prevent unused variable warnings
    (void)t2;
    (void)t3;
    (void)t4;

    return 0;
}

输出:

copy constructor
copy constructor
copy assignment operator

工作示例

这篇关于使用另一个(现有)对象创建新对象时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆