Allow user defined struct constructor #34
IgorDeepakM
started this conversation in
Ideas
Replies: 1 comment 10 replies
-
I'm not against it, but I do suspect the implementation is easier said than done. |
Beta Was this translation helpful? Give feedback.
10 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
This is regarding the disallowed user defined constructor in D.
The biggest obstacle is when you need a non-trivial constructor in struct, typically you need to allocate something. You don't need any parameters but just a parameters less constructor.
This one of the more weird decisions of D and despite this has been discussed several times over the years, I find no real explanation why this wouldn't be possible but answers about the benefits of a non-trivial constructor. Despite of this, non-trivial functions is still allowed after the constructor just as normal.
From: https://wiki.dlang.org/Language_issues#Default_constructors
By these explanations, I don't see really why a user defined constructor wouldn't be possible but rather indolence.
One of the reason is that the default constructor is linked to .init, however there is not real reason why that should be the case. In C++ the struct constructor is just a function and there is no reason it can just be a function in D as well, different from .init. A struct can have both a .init and another default constructor. Between those, you can do optimizations like value not used optimization in order to merge them.
Instead I think D should go the C++ route and define what is a non-trivial constructor and a trivial constructor and the compiler should flag the constructor accordingly. If there are cases where a non-trivial constructor is not allowed, I think that would be a better place to disallow non-trivial constructors than just totally ban them all together.
Such change I think can be more difficult as there might be corner cases where non-trvial constructors are not welcome. However, I think the original D project took a wrong turn by not going the extra mile to make the syntax look clean for such fundamental functionality. If we can make this work, is this a non breaking change as they aren't allowed in old D code?
Beta Was this translation helpful? Give feedback.
All reactions