赋值运算符和拷贝构造函数有什么区别? [英] What's the difference between assignment operator and copy constructor?

查看:173
本文介绍了赋值运算符和拷贝构造函数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白在C ++中赋值构造函数和复制构造函数的区别。它是这样的:

  class A {
public:
(){
cout<< A :: A()< endl;
}
};

//复制构造函数
A a = b;

//赋值构造函数
A c;
c = a;

//对吧?

我想知道如何分配赋值构造函数和复制构造函数的内存?
谢谢!

解决方案

复制构造函数用于从其他对象的数据初始化 以前未初始化的 对象。

  A(const A& rhs):data_(rhs.data_){} 
用于替换 的数据。 对象与其他对象的数据。

  operator =(const A& rhs){data_ = rhs.data_; return * this;} 

您可以通过默认构造加上赋值替换复制构造,高效。



(旁注:上面的实现是编译器免费提供的,所以手动实现它们是没有意义的。这两个中的一个,可能是你手动管理一些资源。在这种情况下,每 三原则 ,你很可能还需要另一个加一个析构函数。)


I don't understand the difference of assignment constructor and copy constructor in C++. It is like this:

class A {
public:
    A() {
        cout << "A::A()" << endl;
    }
};

// The copy constructor
A a = b;

// The assignment constructor
A c;
c = a;

// Is it right?

I want know how to allocate memory of the assignment constructor and copy constructor? Thank you!

解决方案

A copy constructor is used to initialize a previously uninitialized object from some other object's data.

A(const A& rhs) : data_(rhs.data_) {}

An assignment operator is used to replace the data of a previously initialized object with some other object's data.

A& operator=(const A& rhs) {data_ = rhs.data_; return *this;}

You could replace copy construction by default construction plus assignment, but that would be less efficient.

(As a side note: My implementations above are exactly the ones the compiler grants you for free, so it would not make much sense to implement them manually. If you have one of these two, it's likely that you are manually managing some resource. In that case, per The Rule of Three, you'll very likely also need the other one plus a destructor.)

这篇关于赋值运算符和拷贝构造函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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