Bug 5347 – Add constructors for primitive types to make pointers easier to use

Status
RESOLVED
Resolution
DUPLICATE
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
Other
OS
All
Creation time
2010-12-13T00:10:00Z
Last change time
2015-06-09T05:14:39Z
Assigned to
nobody
Creator
issues.dlang

Comments

Comment #0 by issues.dlang — 2010-12-13T00:10:50Z
I'd like to be able to do something like this: int* i = new int(7); It would create a new pointer to int where the int that it points to has a value of 7. But that code results in the compiler complaining that there is no constructor for int, and as far as I can tell the only way to do it so the far less elegant and definitely less compact: int* i = new int; *i = 7; Ideally, you'd be able to use the first syntax for all primitive types. As it is however, you can only use it for structs (and classes if you're using a reference rather than a pointer). This seems unnecessarily limiting. In fact, I thought that the first syntax _was_ legal, and it threw me off when it didn't work (just goes to show how rarely I use pointers, I guess).
Comment #1 by yebblies — 2010-12-13T02:20:32Z
This doesn't seem like something that would be used very often. You could instead use int* i = [7].ptr; which should generate the same code, due to the way primitive types are allocated.
Comment #2 by issues.dlang — 2010-12-13T02:29:32Z
Not useful very often? How about every time that you create a pointer to an int (or any other primitive type) and want to immediately initialize the value that's pointed to? It seems like it would be _highly_ useful whenever dealing with pointers to primitives. If it's not useful very often, it's because pointers aren't used very often. And a syntax such as new int(7) or new bool(true) would be completely consistent with all of the other types. In fact, adding it would make the language _more_ consistent, not less. This would be particularly true when writing generic code.
Comment #3 by yebblies — 2010-12-13T02:45:34Z
(In reply to comment #2) I agree it would be more consistent that way, for value types. void f(T)(T v) { auto x = new T(v); // what if T is a class, array, static array etc? } A search of my own code doesn't come up with any instances of allocating a single value type like this. Searching phobos gives two instances, both in unittests. If it's not used very often, what's the point of adding syntax for it? Just saying.
Comment #4 by bearophile_hugs — 2010-12-13T04:01:46Z
(In reply to comment #2) > Not useful very often? How about every time that you create a pointer to an int > (or any other primitive type) and want to immediately initialize the value > that's pointed to? The syntax is supported for structs and unions. So please show some use cases for ints, floats, etc.
Comment #5 by yebblies — 2013-01-12T23:17:37Z
Issue 9112 has a pull. *** This issue has been marked as a duplicate of issue 9112 ***