gpt4 book ai didi

c++ - 复制构造函数未被调用

转载 作者:太空狗 更新时间:2023-10-29 23:21:32 25 4
gpt4 key购买 nike

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

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

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

AguiBitmap bitmap;
bitmap = AguiBitmap("somepath");

永远不会调用复制构造函数代码(设置断点)。因此,当临时对象被销毁时,我提出的在从临时对象重建的对象中有一个无效指针的问题变得无效。

我该怎么做才能调用我的复制构造函数?

谢谢

最佳答案

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

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

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

width = bmp.width;
height = bmp.height;

关于c++ - 复制构造函数未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3977893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com