Bug 1735 – classinfo.create returns null if no default constructor

Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D1 (retired)
Platform
x86
OS
Windows
Creation time
2007-12-16T14:51:00Z
Last change time
2014-02-24T16:00:22Z
Assigned to
andrei
Creator
wbaxter

Comments

Comment #0 by wbaxter — 2007-12-16T14:51:41Z
Not sure if this is a bug or just incomplete documentation. ClassInfo.create is documented as: "Create instance of Object represented by 'this'." http://www.digitalmars.com/d/1.0/phobos/object.html However if you try to call classinfo.create on a classinfo for a class that has no default constructor then you get back null. It should be possible for the standard library implementation to create an instance in any event since it knows what members exist. The resulting object may not be usable, but it would facilitate the implementation of dup() methods. For example: class Base { Base dup() { auto ret = cast(Base) this.classinfo.create; ret.x = this.x; ret.y = this.y; return ret; } string toString() { return "I'm Base"; } int x = 6; double y = 8; } class DerivedA : Base { this(int px, int py) {} DerivedA dup() { auto ret = cast(DerivedA) super.dup; ret.w = this.w; return ret; } string toString() { return "I'm DerivedA"; } long w = 42; } void main() { Base b = new DerivedA(5,10); Base c = b.dup(); } That will create an access violation at run time because DerivedA doesn't have a default constructor.
Comment #1 by dhasenan — 2007-12-16T21:36:04Z
This is an interesting situation. Related to #1712 -- you can't fake the functionality because of interfaces. Otherwise, it's a pretty dangerous situation to create an instance of a class without calling the constructor. I'd say the default action should be throwing an exception if there is no default constructor. It would be convenient to have an official, endorsed method for getting an object of a given type without calling the constructor, though.
Comment #2 by bugzilla — 2008-02-16T12:44:13Z
At the moment I'm just going to document that it returns null if there is no default constructor. It's a bad idea to create an object anyway if there are constructors but no default one.
Comment #3 by andrei — 2010-09-26T11:47:00Z
The behavior is as intended. For lower-level object constructions mechanisms, emplace() is recommended.