开发者

Issue with overloaded = function

开发者 https://www.devze.com 2023-01-26 22:58 出处:网络
Here is my issue. I have a class called AguiFont. It internally has a pointer to whatever type of font the font loader is set to. I overloaded the = operator so that users wouldn\'t ever have to mana

Here is my issue.

I have a class called AguiFont. It internally has a pointer to whatever type of font the font loader is set to. I overloaded the = operator so that users wouldn't ever have to manage its memory.

It works great except for one circumstance. When I set the font for a widget in its constructor, for some reason when I come to use that font, I get 0xfefefe which is due to the memory at that pointer already being freed. If in a function in main I create some fonts and ='d them it's fine. And when i call someWidget.setFont() that is fine too, but calling setFont(); in the constructor causes the issue.

Here is the overloaded = operator:

AguiFont& AguiFont::operator=(const AguiFont &tmp)
{
    loader->destroyFont(nativeFontPtr);

    nativeFontPtr = 0;
    if(tmp.getFont())
        this->nativeFontPtr = loader->loadFont(tmp.getPath().c_str(),tmp.getSize());

    this->fontLineHeight = tmp.getLineHeight();
    this->fontPath = tmp.getPath();
    this->fontSize =开发者_StackOverflow tmp.getSize();

    return *this;
}

Here is the constructor for a widget: (I have it loading a test font which should indeed succeed)

AguiWidget::AguiWidget(void)
{
    location = AguiPoint(0,0);
    size = AguiSize(0,0);

    parentWidget = 0;
    dockingStyle = DockingNone;
    userData = 0;
    opacity = 1.0f;
    setFont(AguiFont(std::string("test.ttf"),24));
    tintColor = AguiColor(1.0f,1.0f,1.0f,opacity);
    fontColor = AguiColor(0.0f,0.0f,0.0f,1.0f);
    isWidgetVisible = true;
    isWidgetEnabled = true;
    isWidgetFocusable = false;
    isWidgetTabable = false;
    clipChildren = true;
}

Thanks


I'm inclined to blame the copy ctor (which you don't show). If the font is copied when a temporary is created, the first destructor will probably call loader->destroyFont(nativeFontPtr);. If the copy ctor didn't duplicate nativeFontPtr, this will destroy the single underlying font as soon as the temporary goes out of scope.


What is the signature of setFont ? It looks like it could be that you are missing the copy constructor for AguiFont.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号