赋值运算符和复制构造函数有什么区别?

2023-05-09C/C++开发问题
14

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

问题描述

限时送ChatGPT账号..

我不明白 C++ 中赋值构造函数和复制构造函数之间的区别.是这样的:

I don't understand the difference between 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 to know how to allocate memory of the assignment constructor and copy constructor?

推荐答案

复制构造函数用于初始化一个之前未初始化的 对象来自其他对象的数据.

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

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

例如:

A aa;
A a = aa;  //copy constructor

赋值运算符用于用其他对象的数据替换先前初始化对象的数据.

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;}

例如:

A aa;
A a;
a = aa;  // assignment operator

您可以通过默认构造加赋值来替换复制构造,但这会降低效率.

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.)

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6