【问题标题】:C++ template class copy-constructor and assignment-operatorC++ 模板类复制构造函数和赋值运算符
【发布时间】:2012-10-05 06:26:52
【问题描述】:

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

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 变量的情况下实现复制构造函数和赋值运算符?

【问题讨论】:

  • 请注意,赋值运算符的问题是 not 由于 const。这是因为引用必须在创建时初始化(即她在构造函数的初始化列表中)并且之后不能更改。赋值运算符更改一个已经完全创建的对象。

标签: c++ class templates


【解决方案1】:

您可能不应该将 const 引用作为成员,因为您不能(通常)知道对象的生命周期将超过您的对象的生命周期,abc 几乎可以肯定是输入Tx 而不是Tx const&amp;

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2013-09-28
    • 2020-06-13
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多