Using memnew to create a Node that has two constructor parameters.
Asked Answered
D

7

0

When creating a ::godot::Node we should use memnew instead of new. I have made a subclass of Node3D that has two constructor parameters. I tried to create an instance with

memnew (MySubclassOfNode3D {x, y})

This fails, because memnew is a macro, and to the C++ preprocessor this is a macro call with two arguments, rather than one.

How do I create an instance of my class? Thanks!

Downcome answered 12/10, 2023 at 16:30 Comment(0)
S
0

Downcome What happens if you do memnew(MySubclassOfNode3D(x, y)) ?

Sabatier answered 12/10, 2023 at 18:25 Comment(0)
D
0

Sabatier
Congratulations, then it works!

But I thought that the curly braces were now the preferred syntax for initialisation, in general in C++?

Downcome answered 12/10, 2023 at 20:2 Comment(0)
S
0

Downcome There's no preferred syntax. You can use any syntax supported by the standard. Of course, it's best to keep it consistent within a project. So you should probably follow the style that Godot's source uses.

Looks like the macro doesn't like braces for some reason. This issue should perhaps be reported. What errors do you get from the compiler?

Sabatier answered 12/10, 2023 at 20:16 Comment(0)
D
0

Sabatier
The compiler says

error: macro "memnew" passed 2 arguments, but takes just 1

The error is a generic error related to macros, it's the way the preprocessor parser arguments to macros.

Downcome answered 13/10, 2023 at 9:36 Comment(0)
D
0

Sabatier

So you should probably follow the style that Godot's source uses.

This is not always feasible. I might be working on a project that has it's own style guide. Or working with other libraries that each have their own style guide.

Downcome answered 13/10, 2023 at 9:38 Comment(0)
D
0

Sabatier
Btw, if I redefine the memnew macro as

#define memnew(...) ::godot::_post_initialize(new ("") __VA_ARGS__)

then it works. But I do not know enough about macros to be able to say whether this may cause other issues.

Downcome answered 13/10, 2023 at 9:55 Comment(0)
D
0

I raised an issue, see https://github.com/godotengine/godot-cpp/issues/1274

Downcome answered 18/10, 2023 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.