C 复制分配运算符,用于参考对象变量

c++ copy assignment operator for reference object variable

本文关键字:参考 对象 变量 用于 复制 分配 运算符      更新时间:2023-10-16

我给出以下示例以说明我的问题:

class Abc
{
public:
    int a;
    int b;
    int c;
};
class Def
{
public:
    const Abc& abc_;
    Def(const Abc& abc):abc_(abc) { }
    Def& operator = (const Def& obj)
    {
        // this->abc_(obj.abc_);
        // this->abc_ = obj.abc_;
    }
};

在这里,我不知道如何定义复制分配运算符。你有什么想法?谢谢。

不能分配给。您需要可以的东西。指针会起作用,但它们非常滥用。

std::reference_wrapper

怎么样
#include <functional>
class Abc
{
public:
    int a;
    int b;
    int c;
};
class Def
{
public:
    std::reference_wrapper<const Abc> abc_;
    Def(const Abc& abc):abc_(abc) { }
    // rule of zero now supplies copy/moves for us
    // use the reference
    Abc const& get_abc() const {
      return abc_.get();
    }
};

无法分配参考。因此,只能通过新的和复制结构来定义它:

Def& operator = (const Def& obj)
{
      this->~Def(); // destroy
      new (this) Def(obj); // copy construct in place
}

,但这确实是不确定的。只需使用指针。