A comparison between C++ and D

Chris Wright via Digitalmars-d digitalmars-d at puremagic.com
Tue Mar 8 18:14:34 PST 2016


On Wed, 09 Mar 2016 01:18:26 +0000, maik klein wrote:
> If you spot any mistakes, please let me know.

> structs in D don’t have a default constructor because every type
> needs exception free default construction

Rather, declaring a variable should never throw an exception. Declaring a 
variable shouldn't create any nontrivial work.

It's trivial to create a type in D that doesn't have exception free 
default construction:

class A {
  this() { throw new Exception(); }
}

> C++ has a static_cast while D does not.

D has one explicit cast operator. It can do much of what static_cast 
does, though D does not let you downcast without a runtime check.

> Exceptions in D require the GC.

You don't need the GC; you just need storage that's not on a stack frame 
below where you're catching the exception.

You can malloc an exception and throw it.

You can allocate space for an exception in the static data region and 
throw it from there, like with OutOfMemoryError.

You can allocate space for an exception on the stack in main() and pass 
it down the call chain.

> To get foo.bar.baz you can create baz.d inside the bar folder and bar
> inside the foo folder.

That's the canonical way of doing it, but with dub, I'm seeing people 
generally adding the project name before that. So, for instance, I have 
module "roguelike.levelgen" in source file "source/levelgen.d". It works.

> D can print any type at compile time or runtime with
> writeln(SomeType.stringof) or writeln(typeof(somevar).stringof)

stringof evaluates an expression or type and produces a string 
representation for that value. That string representation is a compile-
time constant. It doesn't print it at compile time or runtime.

Does writeln print values at compile time? That would be kind of strange. 
Maybe useful in the context of CTFE, but still a little unexpected.


More information about the Digitalmars-d mailing list