避免在复制构造函数和运算符=

问题描述 投票:0回答:3

在 C++ 中,当类包含动态分配的数据时,显式定义复制构造函数、operator= 和析构函数通常是合理的。但这些特殊方法的活动是重叠的。更具体地说,operator= 通常首先进行一些破坏,然后进行与复制构造函数中类似的处理。

我的问题是如何以最佳方式编写此代码,而无需重复相同的代码行,并且不需要处理器执行不必要的工作(例如不必要的复制)。

我通常会得到两种帮助方法。一种用于建设,一种用于破坏。第一个是从复制构造函数和运算符 = 调用的。第二个由析构函数和运算符=使用。

这是示例代码:

    template <class T>
    class MyClass
    {
        private:
        // Data members
        int count;
        T* data; // Some of them are dynamicly allocated
        void construct(const MyClass& myClass)
        {
            // Code which does deep copy
            this->count = myClass.count;
            data = new T[count];
            try
            {
                for (int i = 0; i < count; i++)
                    data[i] = myClass.data[i];
            }
            catch (...)
            {
                delete[] data;
                throw;
            }
        }
        void destruct()
        {
            // Dealocate all dynamicly allocated data members
            delete[] data;
        }
        public: MyClass(int count) : count(count)
        {
            data = new T[count];
        }
        MyClass(const MyClass& myClass)
        {
            construct(myClass);
        }
        MyClass& operator = (const MyClass& myClass)
        {
            if (this != &myClass)
            {
                destruct();
                construct(myClass);
            }
            return *this;
        }
        ~MyClass()
        {
            destruct();
        }
    };

这是否正确? 以这种方式拆分代码是一个好习惯吗?

c++ destructor copy-constructor assignment-operator code-sharing
3个回答
8
投票

一个初步评论:

operator=
确实开始于 破坏,而是通过建设。否则就会留下 如果构造通过以下方式终止,则对象处于无效状态 例外。因此您的代码不正确。 (注意 测试自我分配的必要性通常表明 赋值运算符正确。)

处理这个问题的经典解决方案是交换惯用法:你 添加成员函数 swap:

void MyClass::swap( MyClass& other )
{
    std::swap( count, other.count );
    std::swap( data, other.data );
}

保证不会抛出。 (在这里,它只是交换一个 int 和一个指针,两者都不能抛出。)然后你 将赋值运算符实现为:

MyClass& MyClass<T>::operator=( MyClass const& other )
{
    MyClass tmp( other );
    swap( tmp );
    return *this;
}

这很简单直接,但是任何解决方案 在开始之前所有可能失败的操作都已完成 更改数据是可以接受的。对于像你这样的简单案例 代码,例如:

MyClass& MyClass<T>::operator=( MyClass const& other )
{
    T* newData = cloneData( other.data, other.count );
    delete data;
    count = other.count;
    data = newData;
    return *this;
}

(其中

cloneData
是一个成员函数,它执行大部分操作 你的
construct
确实如此,但返回了指针,并且没有 修改
this
) 中的任何内容。

编辑:

与您最初的问题没有直接关系,但一般来说,在 在这种情况下,您确实不想想要做

new T[count]
cloneData
(或
construct
,或其他)。这构建了所有 的
T
与默认构造函数,然后分配它们。 这样做的惯用方法是这样的:

T*
MyClass<T>::cloneData( T const* other, int count )
{
    //  ATTENTION! the type is a lie, at least for the moment!
    T* results = static_cast<T*>( operator new( count * sizeof(T) ) );
    int i = 0;
    try {
        while ( i != count ) {
            new (results + i) T( other[i] );
            ++ i;
        }
    } catch (...) {
        while ( i != 0 ) {
            -- i;
            results[i].~T();
        }
        throw;
    }
    return results;
}

大多数情况下,这将使用单独的(私人)经理来完成 班级:

//  Inside MyClass, private:
struct Data
{
    T* data;
    int count;
    Data( int count )
        : data( static_cast<T*>( operator new( count * sizeof(T) ) )
        , count( 0 )
    {
    }
    ~Data()
    {
        while ( count != 0 ) {
            -- count;
            (data + count)->~T();
        }
    }
    void swap( Data& other )
    {
        std::swap( data, other.data );
        std::swap( count, other.count );
    }
};
Data data;

//  Copy constructor
MyClass( MyClass const& other )
    : data( other.data.count )
{
    while ( data.count != other.data.count ) {
        new (data.data + data.count) T( other.date[data.count] );
        ++ data.count;
    }
}

(当然还有赋值的交换习惯)。这允许 多个计数/数据对,没有丢失异常的风险 安全。


0
投票

我不认为这有任何固有的问题,只要你确保不声明构造或析构虚拟。

您可能对《Effective C++》(Scott Meyers)的第 2 章感兴趣,该章完全致力于构造函数、复制运算符和析构函数。

至于您的代码未按应有的方式处理异常,请考虑更有效的 C++ (Scott Meyers) 中的第 10 和 11 项。


0
投票

通过首先复制右侧然后与之交换来实现作业。通过这种方式,您还可以获得异常安全性,这是上面的代码所没有提供的。否则,当 destruct() 成功后,construct() 失败时,您可能会得到一个损坏的容器,因为成员指针引用了一些已释放的数据,并且在销毁时将再次释放这些数据,从而导致未定义的行为。

foo&
foo::operator=(foo const& rhs)
{
   using std::swap;
   foo tmp(rhs);
   swap(*this, tmp);
   return *this;
}
© www.soinside.com 2019 - 2024. All rights reserved.