C++模板类复制构造函数和赋值运算符

C++ template class copy-constructor and assignment-operator

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

我有一个模板类Triple的实现,它是一个包含任意三种类型的容器。我的问题是,我的类将对值的三个常量引用作为参数,并且值必须是私有的(定义),但是,我还必须实现复制构造函数和重载赋值运算符。

template <typename T1, typename T2, typename T3>
    class Triple
{
public:
    Triple()
    { }
    Triple(const T1 &a, const T2 &b, const T3 &c) : a(a), b(b), c(c)
    { }
    // copy constructor
    Triple(const Triple &triple) {
        a = triple.first();
        b = triple.second();
        c = triple.third();
    }
    // assignment operator
    Triple &operator=(const Triple& other) {
        //Check for self-assignment
        if (this == &other)
            return *this;
        a = other.first();
        b = other.second();
        c = other.third();
        return *this;
    }
  private:
    T1 const& a;
    T2 const& b;
    T3 const& c;
 };

如何在不赋值 const 变量的情况下实现复制构造函数和赋值运算符?

您可能不应该将 const 引用作为成员,因为您(通常)无法知道对象的生存期将超过对象的生存期,abc几乎肯定应该是 Tx 类型而不是Tx const&

如果您确实知道这一点(请确保您知道,除非您是专家C++开发人员,否则您很可能不了解其含义),那么您可以使用初始化列表拥有一个复制构造函数。

Triple(const Triple& other) {
  : a(other.a)
  , b(other.b)
  , c(other.c)
{ }

你不能有赋值运算符,因为分配给引用会更改引用的对象而不是引用,你可以用指针模拟引用,但由于我认为这不是你想要的,所以我不会详细说明。

无论如何,你应该做的真正事情是使用std::tuple而不是重新发明轮子。