Difference between revisions of "Programming in D for C++ Programmers"

From D Wiki
Jump to: navigation, search
(Submit WIP draft of Coming_From/C_Plus_Plus page)
 
Line 7: Line 7:
 
without compromising performance, allowing unparalleled code reuse in performance-sensitive projects.
 
without compromising performance, allowing unparalleled code reuse in performance-sensitive projects.
  
D can interface with both C and C++ code, but D sheds the burden of backwards compatibility with C source code,
+
D can interface natively with both C and C++ code while shedding the burden of backwards compatibility with C source code,
which allows it to make the easy way the *correct* way.
+
which allows it to make the easy way the ''correct'' way.
  
 
== Header files ==
 
== Header files ==
Line 21: Line 21:
 
features than C++, compilation times tend to be significantly shorter for equivalent programs.
 
features than C++, compilation times tend to be significantly shorter for equivalent programs.
  
The short compilation time also makes D suitable for writing scripts, executed with rdmd.
+
The short compilation time also makes D suitable for writing scripts, executed with rdmd:
 +
<syntaxhighlight lang="D">
 +
#!/usr/bin/env rdmd
 +
 
 +
void main()
 +
{
 +
    writeln("hello, world");
 +
}
 +
</syntaxhighlight>
 +
<pre>
 +
$ chmod +x hello.d && ./hello.d
 +
hello, world
 +
</pre>
  
 
== Checked memory safety and functional purity ==
 
== Checked memory safety and functional purity ==
 
D supports opt-in, transitively-enforced memory safety:
 
D supports opt-in, transitively-enforced memory safety:
 
 
<syntaxhighlight lang="D">
 
<syntaxhighlight lang="D">
 
import std.stdio;
 
import std.stdio;
Line 31: Line 42:
 
void main() @safe // Verified by the compiler to be memory safe
 
void main() @safe // Verified by the compiler to be memory safe
 
{
 
{
writeln("hello, world");
+
    writeln("hello, world");
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
D also supports opt-in functional purity, giving semantic cues to both the programmer and the compiler.
 
D also supports opt-in functional purity, giving semantic cues to both the programmer and the compiler.
Purity makes programs easier to reason about for programmers, and easier to optimize for compilers.
+
Functional purity makes programs easier to reason about for programmers, and easier to optimize for compilers.
  
 
== Concurrency ==
 
== Concurrency ==
 
D's memory model is designed to make shared memory explicit, greatly reducing the potential for concurrency bugs:
 
D's memory model is designed to make shared memory explicit, greatly reducing the potential for concurrency bugs:
 +
<syntaxhighlight lang="D">
 +
import core.atomic;
 +
 +
// Static variables are TLS by default
 +
int tlsVar = 0;
 +
 +
// Static variables of shared or immutable types are global
 +
shared(int) globalVar = 0;
 +
immutable(int) immutableVar = 42;
 +
 +
void printVars()
 +
{
 +
    import std.stdio;
 +
    writeln(tlsVar, " ", globalVar.atomicLoad(), " ", immutableVar);
 +
}
 +
 +
void main()
 +
{
 +
    import std.concurrency;
 +
 +
    tlsVar = 42;
 +
    globalVar.atomicStore(42);
 +
 +
    printVars(); // Output: 42 42 42
 +
    spawn(&printVars); // Output: 0 42 42
 +
}
 +
</syntaxhighlight>
 +
[http://dlang.org/phobos/std_concurrency.html std.concurrency] presents a message-passing API for threading,
 +
and [http://dlang.org/phobos/std_parallelism.html std.parallelism] presents an API for easy parallelization.
  
 
== Immutability ==
 
== Immutability ==
Line 45: Line 85:
 
after initialization.
 
after initialization.
  
There are also const types, bridging mutable and immutable data into a common supertype, enabling functions to receive both
+
<code>const</code> bridges mutable and immutable data into a common supertype, enabling functions to receive both
 
mutable and immutable data.
 
mutable and immutable data.
  
Line 53: Line 93:
  
 
== Ranges vs iterators ==
 
== Ranges vs iterators ==
D espouses ranges, an evolution of the iterator concept more conducive to component programming:
+
D espouses ranges, an evolution of the iterator concept more conducive to component programming.
 
+
The following program reads lines from standard input, puts them in an array, sorts them, and prints them to standard output
 +
in order:
 
<syntaxhighlight lang="D">
 
<syntaxhighlight lang="D">
 
import std.stdio;
 
import std.stdio;
Line 63: Line 104:
 
{
 
{
 
     stdin
 
     stdin
    .byLine(KeepTerminator.yes)
+
        .byLine(KeepTerminator.yes)
    .map!(a => a.idup)
+
        .map!(a => a.idup)
    .array
+
        .array
    .sort
+
        .sort
    .copy(
+
        .copy(
        stdout.lockingTextWriter());
+
            stdout.lockingTextWriter());
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
 
Ranges are also more conducive to presenting safe interfaces.
 
  
 
== Undefined behaviour ==
 
== Undefined behaviour ==
 
D tastefully reduces the number of undefined behaviours from C++ by defining them out of existence.
 
D tastefully reduces the number of undefined behaviours from C++ by defining them out of existence.
 +
 +
Integers in D are 2's complement, and integer overflow is expected behavior:
 +
<syntaxhighlight lang="D">
 +
ubyte b = 255;
 +
++b;
 +
assert(b == 0);
 +
</syntaxhighlight>
  
 
== Unicode ==
 
== Unicode ==
D and its standard library was designed with Unicode in mind, and supports Unicode on a number of levels:
+
D and its standard library was designed with Unicode in mind, and supports Unicode on a number of levels.
 
+
D source files are UTF encoded, and the types string, wstring and dstring are UTF-8, UTF-16 and UTF-32 strings respectively.
* D source files are UTF encoded
+
[http://dlang.org/phobos/std_utf std.utf] and [http://dlang.org/phobos/std_uni std.uni] are standard library modules
* The types string, wstring and dstring are UTF-8, UTF-16 and UTF-32 strings respectively
+
presenting various UTF and Unicode algorithms. [http://dlang.org/phobos/std_regex std.regex] is Unicode-aware.

Revision as of 10:18, 11 April 2015

Overview

D is a modern multi-paradigm programming language that emphasizes both productivity and native efficiency. D does not compromise performance while making great strides in productivity and program correctness, which makes it a great choice for C++ programmers.

D also emphasizes modeling power: D allows for the design and implementation of high-level interfaces without compromising performance, allowing unparalleled code reuse in performance-sensitive projects.

D can interface natively with both C and C++ code while shedding the burden of backwards compatibility with C source code, which allows it to make the easy way the correct way.

Header files

D has a comprehensive, no-nonsense module system that alleviates the need for header files. Symbols can be forward-referenced freely.

D still supports the equivalent of header files - D interface files - which can be used to interface with C or C++ code, or closed-source D code.

Compile times

D is designed to be fast to compile. Despite having more comprehensive and intuitive metaprogramming features than C++, compilation times tend to be significantly shorter for equivalent programs.

The short compilation time also makes D suitable for writing scripts, executed with rdmd:

#!/usr/bin/env rdmd

void main()
{
    writeln("hello, world");
}
$ chmod +x hello.d && ./hello.d
hello, world

Checked memory safety and functional purity

D supports opt-in, transitively-enforced memory safety:

import std.stdio;

void main() @safe // Verified by the compiler to be memory safe
{
    writeln("hello, world");
}

D also supports opt-in functional purity, giving semantic cues to both the programmer and the compiler. Functional purity makes programs easier to reason about for programmers, and easier to optimize for compilers.

Concurrency

D's memory model is designed to make shared memory explicit, greatly reducing the potential for concurrency bugs:

import core.atomic;

// Static variables are TLS by default
int tlsVar = 0;

// Static variables of shared or immutable types are global
shared(int) globalVar = 0;
immutable(int) immutableVar = 42;

void printVars()
{
    import std.stdio;
    writeln(tlsVar, " ", globalVar.atomicLoad(), " ", immutableVar);
}

void main()
{
    import std.concurrency;

    tlsVar = 42;
    globalVar.atomicStore(42);

    printVars(); // Output: 42 42 42
    spawn(&printVars); // Output: 0 42 42
}

std.concurrency presents a message-passing API for threading, and std.parallelism presents an API for easy parallelization.

Immutability

D supports transitive immutable data, enforced by the type system. A variable of immutable type is guaranteed to never change after initialization.

const bridges mutable and immutable data into a common supertype, enabling functions to receive both mutable and immutable data.

Metaprogramming

D templates are both more expressive and easier to read and write than C++ templates. static-if enables conditional branching in imperative style, eliminating the need for specialized dummy types.

Ranges vs iterators

D espouses ranges, an evolution of the iterator concept more conducive to component programming. The following program reads lines from standard input, puts them in an array, sorts them, and prints them to standard output in order:

import std.stdio;
import std.array;
import std.algorithm;

void main()
{
    stdin
        .byLine(KeepTerminator.yes)
        .map!(a => a.idup)
        .array
        .sort
        .copy(
            stdout.lockingTextWriter());
}

Undefined behaviour

D tastefully reduces the number of undefined behaviours from C++ by defining them out of existence.

Integers in D are 2's complement, and integer overflow is expected behavior:

ubyte b = 255;
++b;
assert(b == 0);

Unicode

D and its standard library was designed with Unicode in mind, and supports Unicode on a number of levels. D source files are UTF encoded, and the types string, wstring and dstring are UTF-8, UTF-16 and UTF-32 strings respectively. std.utf and std.uni are standard library modules presenting various UTF and Unicode algorithms. std.regex is Unicode-aware.