0

I have managed to fix, or rather work around, the issue, so I'm not looking for help but I'm just really curious what the underlying reason in the language is.

I have the following code in my (cocos2d-x, but I don't think that's relevant) game:

const Size& Checkbox::getContentSize() const
{
    Size size;
    size.height = label->getContentSize().width;
    size.width = label->getContentSize().height + hPadding + checkbox->getContentSize().height;

    return size;
}

The function returns a Size with only the width while the height remains 0. However, if I add any code before returning, the function returns a Size containing the correct width and height.

const Size& Checkbox::getContentSize() const
{
    Size size;
    size.height = label->getContentSize().width;
    size.width = label->getContentSize().height + hPadding + checkbox->getContentSize().height;

    int meaninglessInteger = 10;

    return size; //size gets returned properly
}

It also returns properly if I do it like this:

const Size& Checkbox::getContentSize() const
{
    float height = label->getContentSize().width;
    float width = label->getContentSize().height + hPadding + checkbox->getContentSize().height;

    return Size(width, height); //size gets returned properly
}

It's a virtual function from the cocos2d-x engine itself so I can't play around with the parameters or make anything not const or a reference. Anyway, I'd just like to know what causes this behavior, and especially why it gets fixed by adding code that does nothing.

  • These all invoke **undefined behaviour** - you can't return a reference to a local object. – Oliver Charlesworth Jun 11 '17 at 18:26
  • `and especially why it gets fixed by adding code that does nothing.` things like this can happen in undefined-behavior-land. Returning a reference to a local variable is never a good idea. – tkausl Jun 11 '17 at 18:26
  • You should [receive a warning](http://cpp.sh/9xenr) from your compiler if you have your warnings on, **don't ignore them** – Passer By Jun 11 '17 at 18:28
  • So the only proper way to do it would be to have a Size in my class which would get updated by the function and returned? As for warnings, I get way too many about cocos's deprecated functions so it's hard to filter out anything meaningful. But neither Resharper, nor Visual Studio have warned me in the editor. – user8145466 Jun 11 '17 at 18:31

1 Answers1

0

size is in the stack, and it's deallocated after that you return. You're returning a reference to a variable that will be deallocated. This is undefined behavior.

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187