godotengine / godot-cpp

C++ bindings for the Godot script API
MIT License
1.71k stars 575 forks source link

error: returning reference to local temporary object #785

Open AbanoubNassem opened 2 years ago

AbanoubNassem commented 2 years ago

I'm trying to connect the animation_finished event as follow:

    void Hero::_register_methods() {
//....
       register_method("_ready", &Hero::_ready);
        register_method("AnimationFinished", &Hero::AnimationFinished);
    }

    void Hero::_ready() {
        m_anim_player = get_node<AnimationPlayer>("Body/Skeleton/AnimationPlayer");

        m_anim_player->connect("animation_finished", this, "AnimationFinished");
    }

    void Hero::AnimationFinished(const String& animation) {

    }

but I get this error:

build/darwin/_deps/godot-cpp-src/include/core/Godot.hpp:163:10: error: returning reference to local temporary object [-Werror,-Wreturn-stack-address]
                return a;
template <class T>
struct _ArgCast {
    static T _arg_cast(Variant a) {
    >>> return a;
    }
};

however if I made the method accept normal String not by reference , it works fine void Hero::AnimationFinished( String animation) {}

but isn't that unnecessary copying the parameters on each call?

Zylann commented 2 years ago

When you interact with the Godot API (here via the signal system) it limits what you can write in the function signature. In Godot Strings are internally refcounted, so this doesn't actually copy the string, it only does a bit of refcount bookeeping. It's arguably still more than passing a pointer but it's not as bad. Maybe the binding system could be improved to support such signatures, but I it doesnt guarantees Godot will use a pointer to string all the way (especially if it gets converted to Variant at some point).