GNOME Bugzilla – Bug 589477
classes without constructors leave static strings as NULL
Last modified: 2018-05-22 13:22:01 UTC
This simple class class Foo { public static string foo = "boo"; } generates something like this in C: char *foo = NULL; But the generated code is not pushing any constructor in there. The compiler must do a workaround for this. The possibilities are: 1) show an error complaining about the lack of constructor 2) warn the user about the need to use 'const' 3) fill the variable with a const string The third option should be the expected one for the user, but programatically can be problematic because the string is stored in rodata instead of the heap and will have to track the correct use of it making this option harder.
Using the following code it works. But being static should imply a non-instantiation access with initialized data. public const string foo = "boo"
Here's a example code to reproduce the issue: -------------------------------------- class Foo { public static string foo = "boo"; } void main() { print ("%s\n", Foo.foo); Foo f = new Foo(); print ("%s\n", f.foo); } -------------------------------------- Vala should detect use non-const static fields and initialize them before the class constructor, or just give them the constant value. A warning would be good, because I understand that it is not correct to use non-const static public fields in classes... what do you think is the right solution for this situation?
Unfortunately, I don't think there is anything we can do about this. We don't have anywhere to initialize them before the class constructor is called--that would require something like __attribute__((constructor)), which isn't portable. We can't just initialize them in C with constant values (i.e., generate static gchar* foo = "boo"). What would happen if you did public static Bar bar = new Bar ()? Even for the example you have above with a simple string it wouldn't work because we have to g_strdup the value, otherwise the program will crash as soon as you try to change the value. We can't emit a warning because it's not possible to detect when the use is valid and when it isn't at compile time. We can't wrap up the access in a function which uses a GOnce because that would break the C API. We can't initialize them in main() because that doesn't cover libraries. It sucks, but I don't think there is really anything we can do without a runtime. I vote we close this :(
-- GitLab Migration Automatic Message -- This bug has been migrated to GNOME's GitLab instance and has been closed from further activity. You can subscribe and participate further through the new bug through this link to our GitLab instance: https://gitlab.gnome.org/GNOME/vala/issues/38.