C++从重载的复制赋值运算符中调用默认的复制赋值操作符
C++ call default copy assignment operator from overloaded copy assignment operator
我想使用复制分配运算符的默认功能,但可以作为操作的一部分执行一些附加任务。因此,基本形式如下所示:
class Test
{
void operator=(Test& that)
{
*this = that; //do the default copy operation
this->foo() //perform some other tasks
}
};
这可以通过创建一个copy()函数很容易地完成,但最好保持"="操作的干净性。
您可以使用一个基本实现类并从子类委托给基本operator=
// Fill this class with your implementation.
class ClsImpl {
// some complicated class
protected:
~ClsImpl() = default;
};
class Cls : public ClsImpl {
public:
Cls& operator=(const Cls& other) {
if (this == &other) { return *this; }
// assign using the base class's operator=
ClsImpl::operator=(other); // default operator= in ClsImpl
this->foo(); // perform some other task
return *this;
}
};
一种方法是从派生类中再次派生,以提供复制后逻辑。
#include <iostream>
// a wrapper class to provide custom copy actions
template<class Base>
struct CopyActions : Base
{
using base_class = Base;
using CopyActions::base_class::base_class;
// copy operator will call the base and then perform custom action
CopyActions& operator=(const CopyActions& r) {
base_class::operator=(r);
onCustomCopy(r, *this);
return *this;
}
};
// a class to notify us when a copy takes place, without having to write
// custom copy operators
struct copy_sentinel
{
copy_sentinel operator=(const copy_sentinel&) {
std::cout << "copying " << name << 'n';
return *this;
}
const char* name;
};
int test_count = 0;
// a model base class
struct MyBase
{
int base_count = test_count++;
copy_sentinel base_s { "MyBase" };
};
// a model derived class containing only logic
struct MyDerived : MyBase
{
int derived_count = test_count++;
copy_sentinel base_s { "MyDerived" };
};
// a custom copy action (free function)
void onCustomCopy(const MyDerived& from, MyDerived& to)
{
std::cout << "custom copy actionn";
}
// our derived class with custom copy actions
using SuperDerived = CopyActions<MyDerived>;
// test
int main()
{
SuperDerived a; // 0, 1
SuperDerived b; // 2, 3
// prove initial values
std::cout << a.base_count << ", " << a.derived_count << std::endl;
// perform copy and report actions
a = b;
// prove a copy occurred
std::cout << a.base_count << ", " << a.derived_count << std::endl;
}
预期结果:
0, 1
copying MyBase
copying MyDerived
custom copy action
2, 3
相关文章:
- 当从函数参数中的临时值调用复制构造函数时
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 为什么默认复制函数在按值发送参数时不调用?
- 为什么调用复制构造函数而不是移动构造函数?
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 复制构造函数中的递归调用
- 编译器调用复制运算符而不是移动运算符
- 为什么我的运算符 + 重载尽管是通过引用传递的,但仍调用我的复制构造函数?
- 使用 pybind11 调用 Python 函数时避免复制输入数据
- 为什么没有调用此模板类的复制构造函数?
- 为什么当我做复制和交换习语时不调用我的复制构造函数?
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- 调用类模板中隐式删除的复制构造函数
- 我不知道为什么复制构造函数的调用在 c++ 中不稳定
- push_back std::vector,则重复调用复制构造函数
- 减少复制构造函数调用
- 调用值构造函数而不是复制构造函数
- 向量<shared_ptr<X>>复制- 调用 X 构造函数?