从赋值运算符函数调用副本构造函数 [英] call copy constructor from assignment operator function

查看:123
本文介绍了从赋值运算符函数调用副本构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指向动态分配数组的类,因此我创建了复制构造函数和赋值运算符函数.由于复制构造函数和赋值运算符函数完成相同的工作,因此我从赋值运算符函数调用了复制构造函数,但得到了"error C2082: redefinition of formal parameter".我正在使用Visual Studio 2012.

I have a class with a point to dynamically allocated array, so I created copy constructor and assignment operator function. Since copy constructor and assignment operator function do the same work, I call copy constructor from the assignment operator function but get "error C2082: redefinition of formal parameter". I am using Visual Studio 2012.

// default constructor
FeatureValue::FeatureValue()
{
    m_value = NULL;
}

// copy constructor 
FeatureValue::FeatureValue(const FeatureValue& other)
{
    m_size = other.m_size;  
    delete[] m_value;
    m_value = new uint8_t[m_size];

    for (int i = 0; i < m_size; i++)
    {
        m_value[i] = other.m_value[i];
    }
}

// assignment operator function
FeatureValue& FeatureValue::operator=(const FeatureValue& other)
{
    FeatureValue(other); // error C2082: redefinition of formal parameter
    return *this;
}

推荐答案

违规行并非您所想.它实际上声明了类型为FeatureValue的变量other.这是因为构造函数没有名称并且不能直接调用.

The offending line isn't what you think it is. It actually declares a variable other of type FeatureValue. This is because constructors to not have names and cannot be called directly.

只要未将操作符声明为虚拟操作,就可以从构造函数中安全地调用复制赋值操作符.

You can safely invoke the copy assignment operator from the constructor as long as the operator is not declared virtual.

FeatureValue::FeatureValue(const FeatureValue& other)
    : m_value(nullptr), m_size(0)
{
    *this = other;
}

// assignment operator function
FeatureValue& FeatureValue::operator=(const FeatureValue& other)
{
    if(this != &other)
    {
        // copy data first. Use std::unique_ptr if possible
        // avoids destroying our data if an exception occurs
        uint8_t* value = new uint8_t[other.m_size];
        int size = other.m_size;  

        for (int i = 0; i < other.m_size; i++)
        {
            value[i] = other.m_value[i];
        }

        // Assign values
        delete[] m_value;
        m_value = value;
        m_size = size;
    }
    return *this;
}

这仅适用于花花公子,或者您可以使用典型的准则进行复制& 沃恩·卡托的答案

This will works just dandy or you can use the typical guidelines for the copy & swap idiom suggested in Vaughn Cato's answer

这篇关于从赋值运算符函数调用副本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆