c++ - 从赋值运算符函数调用复制构造函数

标签 c++ visual-studio

我有一个指向动态分配数组的类,所以我创建了复制构造函数和赋值运算符函数。由于复制构造函数和赋值运算符函数执行相同的工作,我从赋值运算符函数调用复制构造函数但得到 “错误 C2082:形式参数的重新定义”。我正在使用 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。这是因为构造函数没有名字,不能直接调用。

只要运算符未声明为虚拟,您就可以从构造函数中安全地调用复制赋值运算符。

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

这将非常有效,或者您可以使用 Vaughn Cato's answer 中建议的 copy-and-swap 习语的典型指南。

关于c++ - 从赋值运算符函数调用复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17480396/

相关文章:

c++ - 跨库的模板函数特化符号匹配

c++ - 如何从 SimpleIni 打印同一键的多个值

c++ - 视觉 C++ 2010 SP1

windows - Visual Studio Express 2013 for windows with update 2 安装在 "Configuring Your System"中花费太多时间

c++ - 逐行读取 QString 的最佳方法

c++ - QObject 派生类有哪些要求?

c++ - Visual Studio : Variable is being used without being initialized

c# - 读取表单文档的应用程序(scantron-ish)

visual-studio - Visual Studio 2019 中缺少 std::aligned_alloc() 吗?

c++ - 在安装了 gcc-c++ rpm 的 centos 中,在哪里可以找到 iostream.h?