简体   繁体   English

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

[英]C++ template class copy-constructor and assignment-operator

I have an implementation of a template class Triple, which is a container holding any three types. 我有一个模板类Triple的实现,它是一个包含任何三种类型的容器。 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. 我的问题是,我的类将对值的三个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;
 };

How would you implement the copy-constructor and assignment operator without assigning to const variables? 在不分配给const变量的情况下,如何实现复制构造函数和赋值运算符?

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& . 您可能不应该将const引用作为成员,因为您(通常)不知道对象的生存期将超过对象的生存期,因此abc几乎应该是Tx类型,而不是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. 如果您确实知道这一点(请确保您知道,除非您是专业的C ++开发人员,否则您很可能不理解其中的含义),那么您可以使用初始化列表创建一个副本构造函数。

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. 无论如何, 您应该做的真正事情是使用std::tuple而不是重新发明Wheel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM