Would you explain to me what's happening here? I'm having different compiler behaviours when intdefine OPT = 1, 2 , 3 or 4
I don't get if MyClass() default constructor is a legal C++ call or not if MyClass(short a) constructor has been defined. I also don't get the differences between local vs global context (case OPT = 2 vs 3)
case OPT = 4 seems a fixed bug stable vs devel, but not sure
thanks
{.emit: """
class MyClass {
public:
short attr1;
MyClass(short a) {
attr1 = a;
}
};
""".}
type
MyClass {.importcpp: "MyClass".} = object
attr1: cshort
proc constructMyClass(a: cshort): MyClass {.importcpp: "MyClass(@)", constructor.}
const OPT {.intdefine.}: int = 1
# stable 1.6.12: WORKS
# devel 1.9.5: WORKS
when OPT == 1:
proc main =
var obj = constructMyClass(42)
assert obj.attr1 == 42
main()
# stable 1.6.12: WORKS
# devel 1.9.5: WORKS
when OPT == 2:
var obj = MyClass()
obj.attr1 = 42
assert obj.attr1 == 42
# stable 1.6.12: error: no matching function for call to ‘outer::inner::MyClass::MyClass()’
# devel 1.9.5: error: no matching function for call to ‘outer::inner::MyClass::MyClass(<brace-enclosed initializer list>)’
when OPT == 3:
proc main =
var obj = MyClass()
main()
# stable 1.6.12: error: no matching function for call to ‘outer::inner::MyClass::MyClass()’
# devel 1.9.5: WORKS
when OPT == 4:
let obj = constructMyClass(42)
assert obj.attr1 == 42
been talking with @jmgomez on IRC about this, he proposed to move some insights here
talking about case OPT = 2
18:54 <FromDiscord> <jmgomez> It works by coincidence really
18:54 <FromDiscord> <jmgomez> `N_LIB_PRIVATE MyClass objbugg_6 = {0}`
18:55 <FromDiscord> <jmgomez> it's calling the constructor you defined without intending to. If you add another parameter probably it will fail
18:57 <FromDiscord> <jmgomez> You can ask in #internals or forums or in gh issues if it's the intended behaviors. Im not familiar with how the logic of `{}` is expected to work in Nim
...
19:08 <FromDiscord> <jmgomez> There is no way the Nim compiler knows that you deleted the constructor
This clearly explains case OPT = 2 and 3!
Thanks a lot, I didn't know about non-local variables that can be zero-initialized when constant initialization is not available