C++ template class copy-constructor and assignment

2019-07-29 13:56发布

I have an implementation of a template class Triple, which is a container holding any three types. My problem is that, my class takes three const references to values as parameter, and the values have to be private (definition), however, I also have to implement the copy-constructor and overloaded assignment operator.

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;
 };

How would you implement the copy-constructor and assignment operator without assigning to const variables?

1条回答
家丑人穷心不美
2楼-- · 2019-07-29 14:24

You should probably not have const references as members since you can't (in general) know that the objects lifetime will outlast the lifetime of your object, a, b and c should almost certainly be of type Tx and not Tx const&.

If you do know this (be sure that you do, it's more probable that you don't understand the implications unless you're an expert C++ developer), then you can have a copy constructor using an initialization list.

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

You can't have assignment operator since assigning to a reference changes the referred to object not the reference, you could simulate references with pointers but since I think this is not what you want I won't spell it out.

In any case the real thing you should be doing is using std::tuple and not reinventing The wheel.

查看更多
登录 后发表回答