复制构造函数未被调用

jma*_*erx 2 c++

我有一个类在堆上分配内存然后析构函数释放它.我的拷贝构造函数由于某种原因从未被调用过,我不明白为什么.这是我的实现:

 AguiBitmap::AguiBitmap( const AguiBitmap &bmp )
    {

        this->nativeBitmapPtr = al_clone_bitmap(bmp.nativeBitmapPtr);
    }

    AguiBitmap::AguiBitmap( char *filename )
    {

        if(!filename)
        {
            nativeBitmapPtr = 0;
            return;
        }

        nativeBitmapPtr = al_load_bitmap(filename);

        if(nativeBitmapPtr)
        {

            width = al_get_bitmap_width(nativeBitmapPtr);
            height = al_get_bitmap_height(nativeBitmapPtr);
        }
        else
        {
            width = 0;
            height = 0;
        }
    }




    ALLEGRO_BITMAP* AguiBitmap::getBitmap() const
    {
        return nativeBitmapPtr;
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我做类似的事情时:

AguiBitmap bitmap;
bitmap = AguiBitmap("somepath");
Run Code Online (Sandbox Code Playgroud)

永远不会调用复制构造函数代码(设置断点).因此,当临时对象被破坏时,我在临时对象的重建对象中具有无效指针的问题变得无效.

我该怎么做才能调用我的拷贝构造函数?

谢谢

Mic*_*urr 12

这段代码不会调用复制构造函数 - 它调用赋值运算符(或复制赋值运算符):

// a helper `swap` function
void AguiBitmap::swap(AguiBitmap& a, AguiBitmap& b)
{
    using std::swap;  // enable the following calls to come from `std::swap`
                      // if there's no better match

    swap(a.nativeBitmapPtr, b.nativeBitmapPtr);
    swap(a.width, b.width);
    swap(a.height,b.height);
}

AguiBitmap::AguiBitmap& operator=( const AguiBitmap &rhs )
{
    // use copy-swap idiom to perform assignment
    AguiBitmap tmp(rhs);

    swap( *this, tmp);
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

另请注意,您的复制构造函数不完整,因为并未复制heightwidth成员:

width = bmp.width;
height = bmp.height;
Run Code Online (Sandbox Code Playgroud)

  • 那个交换函数应该是朋友,你应该按值运算`operator =`.既然你正在复制,那么在函数内部进行复制是没有意义的.在参数列表中执行此操作允许编译器使用临时值进行删除. (2认同)

Tom*_*Tom 7

AguiBitmap("somepath");
Run Code Online (Sandbox Code Playgroud)

将调用:

AguiBitmap::AguiBitmap( char *filename )
Run Code Online (Sandbox Code Playgroud)

并且赋值将调用赋值运算符

要调用您的复制构造函数,请执行以下操作:

AguiBitmap bitmap;
AguiBitmap anotherBitmap(bitmap)
Run Code Online (Sandbox Code Playgroud)