复制构造函数、赋值运算符C++

Copy Constructors, Assignment Operator C++

本文关键字:C++ 赋值运算符 构造函数 复制      更新时间:2023-10-16

我对OOP很陌生,仍在尝试理解构造函数的所有概念。我有一个包含一些数据的类,我必须做一个Copy ConstructorAssignment Operator,但是,由于这是我第一次做这样的事情,我不确定我写的内容是否有意义。所以,我问我写的是否是有效的复制构造函数和赋值运算符。该类保存在一个名为BKS.h谢谢! 这是类:

#include <iostream>
#include <vector>
#include <cassert>
#include <algorithm>
using namespace std;
template <class T>
class BKS final
{
public:
struct Item
{
T identifier;
int weight;
int benefit;
};
BKS() {}
BKS(const BKS<T> &copy);
BKS(const vector<Item> &items) : itemlist_{items} {}
BKS(const vector<pair<int, int>> &weight_benefit_list);
BKS<T> &operator=(const BKS<T> &copy);
// some methods ....
private:
vector<Item> itemlist_;
vector<int> current_selection_;
int current_capacity_ {0};
int maximal_benefit_ {0};
};

复制构造函数和辅助运算符:

#include "bks.h"
template <class T>
BKS<T>::BKS(const BKS<T> &copy)                 // copy constructor 
{   
std::vector<Item> itemlist_ = copy.itemlist_;
std::vector<int> current_selection_ = copy.current_selection_;
int current_capacity_ = copy.current_capacity_;
int maximal_benefit_ = copy.maximal_benefit_;  
}
template <class T>
BKS<T> &BKS<T>::operator=(const BKS<T> &copy)
{
if (&copy != this)
{ // check for self-assignment
this->itemlist_ = copy.itemlist_;
this->current_selection_ = copy.current_selection_;
this->current_capacity_ = copy.current_capacity_;
this->maximal_benefit_ = copy.maximal_benefit_;
}
return *this;
}

也欢迎任何关于构造函数的一般建议:)

如果你的导师坚持你必须声明特殊成员,但没有给出如何的指导,那么最好的方法是:

template <class T>
class BKS final
{
public:
~BKS() = default;
BKS(const BKS &) = default;
BKS& operator=(const BKS &) = default;
BKS(BKS &&) = default;
BKS& operator=(BKS &&) = default;
/* other members... */
};

如果您的教师不要求您声明它们,而只要求它们存在,最好的方法是

template <class T>
class BKS final
{
public:
/* other members... */
};

当您在不声明复制构造函数、复制赋值运算符和析构函数的情况下创建新类时,编译器将声明自己的复制构造函数、复制赋值运算符和析构函数版本。 此外,如果您不声明构造函数,编译器将为您隐式声明一个构造函数。

所有这些默认编译器生成的函数都是publicinline的。请注意,隐式声明的析构函数是非虚拟的。

那么默认构造函数、默认复制构造函数、默认复制赋值运算符和默认析构函数会做什么呢?

  • 默认构造函数(隐式声明或用户定义(:调用类的基和非静态成员的默认构造函数;

  • 默认复制
  • 构造函数(隐式声明(和默认复制赋值运算符(隐式声明(:将源对象的每个非静态数据成员复制到目标对象;

  • 默认析构函数(隐式声明或用户定义(:调用基类的析构函数和派生类的成员。

在您的例子中,您的非静态数据成员将由默认的复制构造函数和默认的复制赋值运算符复制。无需定义自己的复制构造函数和复制赋值运算符,除非您要为复制构造函数和复制赋值运算符添加特定行为。

引用:

https://en.cppreference.com/w/cpp/language/default_constructor

https://www.ibm.com/support/knowledgecenter/SSLTBW_2.3.0/com.ibm.zos.v2r3.cbclx01/cplr380.htm

书籍:斯科特·迈耶斯(Scott Meyers(的"有效C++",第2章