C++模板类copy-constructor和assignment-operator

riz*_*ize 1 c++ templates class

我有一个模板类Triple的实现,它是一个容纳任意三种类型的容器.我的问题是,我的类将三个const引用作为参数值,并且值必须是私有的(定义),但是,我还必须实现copy-constructor和重载赋值运算符.

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;
 };
Run Code Online (Sandbox Code Playgroud)

如何在不分配const变量的情况下实现copy-constructor和赋值运算符?

Mot*_*tti 5

您可能不应该将const引用作为成员,因为您不能(通常)知道对象的生命周期将超过对象的生命周期a,b并且c几乎肯定是类型Tx而不是Tx const&.

如果您确实知道这一点(确保您这样做,除非您是专家C++开发人员,否则您更不可能理解其含义),那么您可以使用初始化列表来创建复制构造函数.

Triple(const Triple& other) {
  : a(other.a)
  , b(other.b)
  , c(other.c)
{ }
Run Code Online (Sandbox Code Playgroud)

你不能拥有赋值运算符,因为赋值给引用改变了引用的对象而不是引用,你可以用指针模拟引用,但是因为我认为这不是你想要的,所以我不会拼写它.

在任何情况下,你应该做的真正的事情是使用std::tuple而不是重新发明轮子.