+ All Categories
Home > Documents > Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

Date post: 14-Dec-2015
Category:
Upload: osvaldo-scruton
View: 215 times
Download: 0 times
Share this document with a friend
Popular Tags:
41
Herb Sutter Herb Sutter Architect Architect Developer Division, Microsoft Developer Division, Microsoft Converging Roads Converging Roads .NET, Longhorn, and C++ .NET, Longhorn, and C++
Transcript
Page 1: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

Herb SutterHerb Sutter

ArchitectArchitectDeveloper Division, MicrosoftDeveloper Division, Microsoft

Converging RoadsConverging Roads.NET, Longhorn, and C++.NET, Longhorn, and C++

Page 2: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

2

the pit of successthe pit of success

Page 3: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

3

Rationale and GoalsRationale and Goals

Language TourLanguage Tour

Design and Implementation HighlightsDesign and Implementation Highlights• Unified pointer and storage system Unified pointer and storage system

(stack, native heap, gc heap).(stack, native heap, gc heap).

• Deterministic cleanup: Deterministic cleanup: Destruction/Dispose, finalization.Destruction/Dispose, finalization.

• Generics × templates, STL on CLR.Generics × templates, STL on CLR.

Standardization and FuturesStandardization and Futures

OverviewOverview

Page 4: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

6

2002/3: Managed Extensions2002/3: Managed Extensions2004/5: C++ in VS 20052004/5: C++ in VS 2005

Garbage collection, Garbage collection, finalizers.finalizers.

Generics.Generics.

Reference and value Reference and value types.types.

Interfaces.Interfaces.

Verifiability.Verifiability.

Security.Security.

Properties, delegates, Properties, delegates, events.events.

Deterministic cleanup, Deterministic cleanup, destructors.destructors.

Templates.Templates.

Native types.Native types.

Multiple inheritance.Multiple inheritance.

STL, generic algorithms, STL, generic algorithms, lambda expressions.lambda expressions.

Pointer/pointee Pointer/pointee distinction.distinction.

Copy construction, Copy construction, assignment.assignment.

C++ C++ CLRCLR

StandardStandard

C++/CLIC++/CLI

Page 5: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

9

Rationale and GoalsRationale and Goals

Language TourLanguage Tour

Design and Implementation HighlightsDesign and Implementation Highlights• Unified pointer and storage system Unified pointer and storage system

(stack, native heap, gc heap).(stack, native heap, gc heap).

• Deterministic cleanup: Deterministic cleanup: Destruction/Dispose, finalization.Destruction/Dispose, finalization.

• Generics × templates, STL on CLR.Generics × templates, STL on CLR.

Standardization and FuturesStandardization and Futures

OverviewOverview

Page 6: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

10

adjective class C;

Page 7: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

11

Type are declared “Type are declared “adjectiveadjective class”: class”:classclass NN{ /*…*/ };{ /*…*/ }; // native// native

ref classref class RR { /*…*/ };{ /*…*/ }; // CLR reference type// CLR reference type

value classvalue class VV { /*…*/ };{ /*…*/ }; // CLR value type// CLR value type

interface classinterface class II { /*…*/ };{ /*…*/ }; // CLR interface type// CLR interface type

enum classenum class EE { /*…*/ };{ /*…*/ }; // CLR enumeration type// CLR enumeration type

• C++ & CLR fundamental types are mapped to each other C++ & CLR fundamental types are mapped to each other (e.g., int and System::Int32 are the same type).(e.g., int and System::Int32 are the same type).

Examples:Examples:ref class A ref class A abstractabstract { }; { }; // abstract even w/o pure virtuals// abstract even w/o pure virtuals

ref class B ref class B sealedsealed : A { }; : A { }; // no further derivation is allowed// no further derivation is allowed

ref class C : B { };ref class C : B { }; // error, B is sealed// error, B is sealed

Basic Class Declaration Basic Class Declaration SyntaxSyntax

Page 8: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

12

PropertiesPropertiesBasic syntax:Basic syntax:

ref class R {ref class R { int mySize; int mySize;public:public: property int Size {property int Size { int int getget()() { return mySize; }{ return mySize; } void void setset( int val )( int val ) { mySize = val; }{ mySize = val; } }}};};

R r;R r;r.Size = 42;r.Size = 42; // use like a field; calls r.Size::set(42)// use like a field; calls r.Size::set(42)

Trivial properties:Trivial properties:ref class R {ref class R {public:public: property int Size; property int Size; // compiler-generated// compiler-generated};}; // get, set, and backing store// get, set, and backing store

Page 9: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

14

Delegates and EventsDelegates and EventsA trivial event:A trivial event:

delegate void D( int );delegate void D( int );

ref class R {ref class R {public:public: event D^ e; event D^ e; // trivial event; compiler-generated members// trivial event; compiler-generated members

void f() {void f() { e( 42 ); e( 42 ); } } // invoke it// invoke it};};

R r;R r;r.e += gcnew D( this, &SomeMethod );r.e += gcnew D( this, &SomeMethod );r.e += gcnew D( SomeFreeFunction );r.e += gcnew D( SomeFreeFunction );r.f();r.f();

Or you can write add/remove/raise yourself.Or you can write add/remove/raise yourself.

Page 10: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

15

Virtual Functions and Virtual Functions and OverridingOverriding

Explicit, multiple, and renamed overriding:Explicit, multiple, and renamed overriding:interface class I1 { int f();interface class I1 { int f(); int h();int h(); };};

interface class I2 { int f();interface class I2 { int f(); int i();int i(); };};

interface class I3 { interface class I3 { int i();int i(); int j(); };int j(); };

ref class R : I1, I2, I3 {ref class R : I1, I2, I3 {public:public: virtual int e() virtual int e() overrideoverride;; // error, there is no virtual e()// error, there is no virtual e() virtual int f() virtual int f() newnew;; // new slot, doesn’t override any f// new slot, doesn’t override any f virtual int f() virtual int f() sealedsealed;; // overrides & seals I1::f and I2::f// overrides & seals I1::f and I2::f virtual int g() virtual int g() abstractabstract;; // same as “= 0” (for symmetry// same as “= 0” (for symmetry

with class declarations) with class declarations)

virtual int x() virtual int x() = I1::h= I1::h;; // overrides I1::h// overrides I1::h virtual int y() virtual int y() = I2::i= I2::i;; // overrides I2::i// overrides I2::i virtual int z() virtual int z() = j, I3::i= j, I3::i;; // overrides I3::i and I3::j// overrides I3::i and I3::j};};

Page 11: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

18

Rationale and GoalsRationale and Goals

Language TourLanguage Tour

Design and Implementation HighlightsDesign and Implementation Highlights• Unified pointer and storage system Unified pointer and storage system

(stack, native heap, gc heap).(stack, native heap, gc heap).

• Deterministic cleanup: Deterministic cleanup: Destruction/Dispose, finalization.Destruction/Dispose, finalization.

• Generics × templates, STL on CLR.Generics × templates, STL on CLR.

Standardization and FuturesStandardization and Futures

OverviewOverview

Page 12: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

19

C/C++ lets you do (way too?) much with pointers:C/C++ lets you do (way too?) much with pointers:• Hide them:Hide them: Cast to int/void* and back. Write them to disk. Cast to int/void* and back. Write them to disk.• Order them.Order them. Example: Example: set<int*>set<int*>..• XOR them.XOR them.

““XOR them?!” XOR them?!” No, really, this is an actual technique.No, really, this is an actual technique.• Consider a traditional bidirectional list (overhead = two pointers Consider a traditional bidirectional list (overhead = two pointers

per node):per node):

• Instead of storing two pointers, store one: Instead of storing two pointers, store one: x x = prev = prev xorxor next. next.

• When traversing, remember the node you came from, When traversing, remember the node you came from, nn..Regardless of direction, the next node’s address is Regardless of direction, the next node’s address is x xor &nx xor &n..

Stupid Pointer Tricks Stupid Pointer Tricks (or, Why a new (or, Why a new abstraction?)abstraction?)

p n p n p n

x x x

Page 13: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

20

% is to ^as

& is to *

Page 14: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

21

Create objects on the native heap, the gc Create objects on the native heap, the gc heap, or on the stack:heap, or on the stack:• On the native heap (native types):On the native heap (native types): T* t1 = new T;T* t1 = new T;

– As usual, pointers (As usual, pointers (**) are stable, even during GC.) are stable, even during GC.100% backward compatible with all standard and 100% backward compatible with all standard and nonstandard stupid pointer tricks.nonstandard stupid pointer tricks.

– As usual, failure to explicitly call As usual, failure to explicitly call deletedelete will leak. will leak.• On the gc heap (CLR types):On the gc heap (CLR types): T^ t2 = gcnew T;T^ t2 = gcnew T;

– Handles (Handles (^̂) are object references (to whole objects).) are object references (to whole objects).– Calling Calling deletedelete is optional: "Destroy now, or finalize later.“ is optional: "Destroy now, or finalize later.“

• On the stack, or as a class member:On the stack, or as a class member: T t3;T t3;– Q: Why would you? A: Deterministic destruction/dispose Q: Why would you? A: Deterministic destruction/dispose

is automatic and implicit, hooked to stack unwinding or is automatic and implicit, hooked to stack unwinding or to the enclosing object’s lifetime.to the enclosing object’s lifetime.

Storage and Pointer ModelStorage and Pointer Model

Page 15: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

22

Pointers and HandlesPointers and HandlesNative pointers (Native pointers (**) and handles () and handles (^̂):):

• ^̂ is like is like **. Differences: . Differences: ^̂ points to a whole object on the gc heap, can’t be ordered, and can’t be cast to/from void* or an integral type. There is no void^. points to a whole object on the gc heap, can’t be ordered, and can’t be cast to/from void* or an integral type. There is no void^.

WidgetWidget** s1 = new Widget; s1 = new Widget; // point to native heap// point to native heapWidgetWidget^̂ s2 = gcnew Widget; s2 = gcnew Widget;// point to gc heap// point to gc heap

s1s1->->Length();Length(); // use // use ->-> for member access for member accesss2s2->->Length();Length();

((**s1).Length();s1).Length(); // use // use ** to dereference to dereference((**s2).Length();s2).Length();

Use RAII Use RAII pin_ptrpin_ptr to get a to get a ** into the gc heap: into the gc heap:R^ r = gcnew R;R^ r = gcnew R;int* p1 = &r->v; int* p1 = &r->v; // error, v is a gc-lvalue// error, v is a gc-lvaluepin_ptr<int> p2 = &r->v;pin_ptr<int> p2 = &r->v; // ok// okCallSomeAPI( CallSomeAPI( p2p2 ); ); // safe call, CallSomeAPI( int* )// safe call, CallSomeAPI( int* )

Page 16: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

23

Just when you

think you’re safe…

…a big hole

appears, just waiting for you to fall

in.

Page 17: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

24

Rationale and GoalsRationale and Goals

Language TourLanguage Tour

Design and Implementation HighlightsDesign and Implementation Highlights• Unified pointer and storage system Unified pointer and storage system

(stack, native heap, gc heap).(stack, native heap, gc heap).

• Deterministic cleanup: Deterministic cleanup: Destruction/Dispose, finalization.Destruction/Dispose, finalization.

• Generics × templates, STL on CLR.Generics × templates, STL on CLR.

Standardization and FuturesStandardization and Futures

OverviewOverview

Page 18: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

25

Why it’s important to know “why”: A parable.

Page 19: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

26

The GC state of the art is great for memory.The GC state of the art is great for memory.It’s not great for other resource types:It’s not great for other resource types:

• Finalizers usually run too late (e.g., files, database Finalizers usually run too late (e.g., files, database connections, locks). Having lots of finalizers doesn’t scale.connections, locks). Having lots of finalizers doesn’t scale.

• The Dispose pattern (try-finally, or C# “using”) tries to The Dispose pattern (try-finally, or C# “using”) tries to address this, but is fragile, error-prone, and requires the address this, but is fragile, error-prone, and requires the user to write more code.user to write more code.

Instead of writing try-finally or using blocks:Instead of writing try-finally or using blocks:• Users can leverage a destructor. The C++ compiler Users can leverage a destructor. The C++ compiler

generates all the Dispose code automatically, including generates all the Dispose code automatically, including chaining calls to Dispose. (There is no Dispose pattern.)chaining calls to Dispose. (There is no Dispose pattern.)

• Types authored in C++ are naturally usable in other Types authored in C++ are naturally usable in other languages, and vice versa.languages, and vice versa.

• C++: Correctness by default. C++: Correctness by default. Other languages: Correctness by explicit coding.Other languages: Correctness by explicit coding.

Cleanup in C++: Less Code, More Cleanup in C++: Less Code, More ControlControl

Page 20: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

27

T::~T()destroy now

or

T:: !T()finalize later

the pit of success

Page 21: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

28

Every type can have a destructor, Every type can have a destructor, ~T()~T()::• Non-trivial destructor == IDispose. Implicitly run when:Non-trivial destructor == IDispose. Implicitly run when:

– A stack based object goes out of scope.A stack based object goes out of scope.– A class member’s enclosing object is destroyed.A class member’s enclosing object is destroyed.– A A deletedelete is performed on a pointer or handle. Example: is performed on a pointer or handle. Example:

Object^ o = f();Object^ o = f();delete o;delete o; // run destructor now, collect memory // run destructor now, collect memory

laterlater

Every type can have a finalizer, Every type can have a finalizer, !T()!T()::• The finalizer is executed at the usual times and subject to The finalizer is executed at the usual times and subject to

the usual guarantees, if the destructor has the usual guarantees, if the destructor has notnot already run. already run.• Programs should (and do by default) use deterministic cleanup. Programs should (and do by default) use deterministic cleanup.

This promotes a style that reduces finalization pressure.This promotes a style that reduces finalization pressure.• ““Finalizers as a debugging technique”: Placing assertions or log Finalizers as a debugging technique”: Placing assertions or log

messages in finalizers to detect objects not destroyed.messages in finalizers to detect objects not destroyed.

Uniform Uniform Destruction/FinalizationDestruction/Finalization

Page 22: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

29

Microsoft.com live experience Microsoft.com live experience (~7/15/2003):(~7/15/2003):• Too many mid-life objects leaking into Gen2 Too many mid-life objects leaking into Gen2

caused frequent full collections. Result: caused frequent full collections. Result: 70%70% time time in GC.in GC.

• CLR performance team suggested changes to CLR performance team suggested changes to release as many objects as possible before making release as many objects as possible before making server to server calls. Result: server to server calls. Result: ~1%~1% time in GC after time in GC after the fix.the fix.

Determinism Matters: Determinism Matters: PerformancePerformance

Page 23: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

30

Side By Side: Using a Side By Side: Using a StreamReaderStreamReader

C++C++ String^ ReadFirstLineFromFile( String^ path ) {String^ ReadFirstLineFromFile( String^ path ) { StreamReader r(path); StreamReader r(path); return r.ReadLine(); return r.ReadLine();}}

C#C# String ReadFirstLineFromFile( String path ) {String ReadFirstLineFromFile( String path ) { using ( using ( StreamReader r StreamReader r = new StreamReader= new StreamReader(path)(path) ) { ) { return r.ReadLine(); return r.ReadLine(); } }}}

JavaJava String ReadFirstLineFromFile( String path ) {String ReadFirstLineFromFile( String path ) { StreamReader r StreamReader r = null= null;; String s = null; String s = null; try {try { r = new StreamReader r = new StreamReader(path)(path);; s = s = r.ReadLine();r.ReadLine(); } finally { } finally { if ( r != null ) r.Dispose(); if ( r != null ) r.Dispose(); } } return return s s;;}}

Page 24: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

31

Side By Side: Using “lock”Side By Side: Using “lock”C++C++ {{

lock lock ll( obj );( obj ); … do something with shared state … … do something with shared state …}}

C#C# lock( obj ) {lock( obj ) { … do something with shared state … … do something with shared state …}}

JavaJava Monitor.Monitor.Enter( obj ); Enter( obj ); trytry { { … do something with shared state … … do something with shared state …}} finally { finally { Monitor.Exit( obj ); Monitor.Exit( obj );}}

Page 25: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

32

Side By Side: Nontrivial Side By Side: Nontrivial “lock”“lock”

C++C++ {{ lock lock ll( obj, 10 );( obj, 10 ); … do something with shared state … … do something with shared state …}}

C#C# if( !Monitor.Tryif( !Monitor.TryEnter( obj, Enter( obj, TimeSpan.FromSeconds( TimeSpan.FromSeconds( 10 10 ) )) ) ) ) {{ throw new Something(); throw new Something();}}

trytry { { … do something with shared state … … do something with shared state …} } finally {finally { Monitor.Exit( obj ); Monitor.Exit( obj );}}

JavaJava if( !Monitor.Tryif( !Monitor.TryEnter( obj, Enter( obj, TimeSpan.FromSeconds( TimeSpan.FromSeconds( 10 10 ) )) ) ) ) {{ throw new Something(); throw new Something();}}

trytry { { … do something with shared state … … do something with shared state …} } finally {finally { Monitor.Exit( obj ); Monitor.Exit( obj );}}

Page 26: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

33

Side By Side: Nontrivial Side By Side: Nontrivial “lock”“lock”

C++C++ {{ lock lock ll( obj, 10 );( obj, 10 ); … do something with shared state … … do something with shared state …}}

C#C# using( new using( new Lock( obj, 10 )Lock( obj, 10 ) ) ) { { … do something with shared state … … do something with shared state …}}

public class Lockpublic class Lock : IDisposable { : IDisposable { private object target;private object target; public Lock(public Lock( object o, double tm object o, double tm ) { ) { target = o; target = o; if( !Monitor.TryEnter( o, tm ) ) if( !Monitor.TryEnter( o, tm ) ) throw new Something(); throw new Something(); } }

void IDisposable.Dispose() {void IDisposable.Dispose() { Monitor.Exit( target ); Monitor.Exit( target );#if DEBUG#if DEBUG GC.SuppressFinalize( this ); GC.SuppressFinalize( this );#endif#endif } }#if DEBUG#if DEBUG ~Lock() { ~Lock() { Diagnostics.Debug.Fail( Diagnostics.Debug.Fail( "Undisposed lock“ "Undisposed lock“ ); ); } }#endif#endif}}

Page 27: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

34

Deterministic Cleanup in C++Deterministic Cleanup in C++C++ example:C++ example:

void Transfer() {void Transfer() { MessageQueue source( "server\\sourceQueue" ); MessageQueue source( "server\\sourceQueue" ); String^ qname = (String^)source.Receive().Body; String^ qname = (String^)source.Receive().Body;    MessageQueueMessageQueue dest1( "server\\" + qname ),dest1( "server\\" + qname ),

dest2( "backup\\" + qname );dest2( "backup\\" + qname ); Message^ message = source.Receive(); Message^ message = source.Receive(); dest1.Send( message ); dest1.Send( message );  dest2.Send( message );  dest2.Send( message );}}

• On exit (return or exception) from Transfer, destructible/ disposable objects have Dispose implicitly called in reverse order of construction. Here: dest2, dest1, and source.On exit (return or exception) from Transfer, destructible/ disposable objects have Dispose implicitly called in reverse order of construction. Here: dest2, dest1, and source.• No finalization.No finalization.

Page 28: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

35

Deterministic Cleanup in C#Deterministic Cleanup in C#Minimal C# equivalent:Minimal C# equivalent:

void Transfer() {void Transfer() { using(using( MessageQueue source MessageQueue source = new MessageQueue= new MessageQueue( "server\\sourceQueue" ) ( "server\\sourceQueue" ) ) {) { String qname = (String)source.Receive().Body; String qname = (String)source.Receive().Body;    using( using( MessageQueue MessageQueue dest1 dest1 = new MessageQueue= new MessageQueue( "server\\" + qname ),( "server\\" + qname ), dest2 dest2 = new MessageQueue= new MessageQueue( "backup\\" + qname ) ( "backup\\" + qname ) ) {) { Message message = source.Receive(); Message message = source.Receive(); dest1.Send( message ); dest1.Send( message );   dest2.Send( message );   dest2.Send( message ); } } } }}}

Page 29: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

36

Deterministic Cleanup in Deterministic Cleanup in VB/JavaVB/Java

Minimal Java equivalent:Minimal Java equivalent:void Transfer() {void Transfer() { MessageQueue source = null, dest1 = null, dest2 = null; MessageQueue source = null, dest1 = null, dest2 = null; try { try { source source = new = new MessageQueue( "server\\sourceQueue" );MessageQueue( "server\\sourceQueue" ); String qname = (String)source.Receive().Body; String qname = (String)source.Receive().Body; dest1 dest1 = new = new MessageQueue( "server\\" + qname );MessageQueue( "server\\" + qname ); dest2 dest2 = new = new MessageQueue( "backup\\" + qname );MessageQueue( "backup\\" + qname ); Message message = source.Receive(); Message message = source.Receive(); dest1.Send( message ); dest1.Send( message );   dest2.Send( message );   dest2.Send( message ); } } finally { finally { if( dest2 != null ) { dest2.Dispose(); } if( dest2 != null ) { dest2.Dispose(); } if( dest1 != null ) { dest1.Dispose(); } if( dest1 != null ) { dest1.Dispose(); } if( source != null ) { source.Dispose(); } if( source != null ) { source.Dispose(); } } }}}

Page 30: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

37

Rationale and GoalsRationale and Goals

Language TourLanguage Tour

Design and Implementation HighlightsDesign and Implementation Highlights• Unified pointer and storage system Unified pointer and storage system

(stack, native heap, gc heap).(stack, native heap, gc heap).

• Deterministic cleanup: Deterministic cleanup: Destruction/Dispose, finalization.Destruction/Dispose, finalization.

• Generics × templates, STL on CLR.Generics × templates, STL on CLR.

Standardization and FuturesStandardization and Futures

OverviewOverview

Page 31: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

38

generic<typename T>

Page 32: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

39

Generics × TemplatesGenerics × Templates

Both are supported, and can be used together.Both are supported, and can be used together.Generics:Generics:

• Run-time, cross-language, and cross-assembly.Run-time, cross-language, and cross-assembly.• Constraint based, less flexible than templates.Constraint based, less flexible than templates.

generic<typename T>generic<typename T> where T : IDisposable, IFoo where T : IDisposable, IFoo ref class GR { /* … */ };ref class GR { /* … */ };

• Constraints are inheritance-based.Constraints are inheritance-based.

Templates:Templates:• Compile-time, C++, and generally intra-assembly.Compile-time, C++, and generally intra-assembly.• Not a high burden: expose templates through generic Not a high burden: expose templates through generic

interfaces (e.g., expose a_container<T> via IList<T>).interfaces (e.g., expose a_container<T> via IList<T>).• Supports specialization, unique power programming idioms Supports specialization, unique power programming idioms

(e.g., template metaprogramming, policy-based design, (e.g., template metaprogramming, policy-based design, STL-style generic programming).STL-style generic programming).

Page 33: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

40

STL on the CLRSTL on the CLRC++ enables STL on CLR:C++ enables STL on CLR:

• Verifiable.Verifiable.

• Separation of collections and algorithms.Separation of collections and algorithms.

Interoperates with Frameworks library.Interoperates with Frameworks library.

C++ “for_each” and C# “for each” both work:C++ “for_each” and C# “for each” both work:stdcli::vectorstdcli::vector<String^> v;<String^> v;

for_eachfor_each( v.begin(), v.end(), functor );( v.begin(), v.end(), functor );for_eachfor_each( v.begin(), v.end(), ( v.begin(), v.end(), _1 += “suffix”_1 += “suffix” ); ); // C++// C++for_eachfor_each( v.begin(), v.end(), ( v.begin(), v.end(), cout << _1cout << _1 ); ); // lambdas// lambdas

g( %v );g( %v ); // call g( IList<String^>^ )// call g( IList<String^>^ )

forfor( String^ s ( String^ s inin v ) Console::WriteLine( s ); v ) Console::WriteLine( s );

Page 34: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

41

Rationale and GoalsRationale and Goals

Language TourLanguage Tour

Design and Implementation HighlightsDesign and Implementation Highlights• Unified pointer and storage system Unified pointer and storage system

(stack, native heap, gc heap).(stack, native heap, gc heap).

• Deterministic cleanup: Deterministic cleanup: Destruction/Dispose, finalization.Destruction/Dispose, finalization.

• Generics × templates, STL on CLR.Generics × templates, STL on CLR.

Standardization and FuturesStandardization and Futures

OverviewOverview

Page 35: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

42

Why Standardize C++/CLI?Why Standardize C++/CLI?

Primary motivators for C++/CLI standard:Primary motivators for C++/CLI standard:• Stability of language.Stability of language.

• C++ community understands and demands standards.C++ community understands and demands standards.

• Openness promotes adoption. Openness promotes adoption.

• Independent implementations should interoperate.Independent implementations should interoperate.

Same TC39, new TG5: C++/CLI.Same TC39, new TG5: C++/CLI.• C++/CLI is a binding between ISO C++ and ISO CLI C++/CLI is a binding between ISO C++ and ISO CLI

only.only.

• Most of TG5’s meetings are co-located with TG3 (CLI), Most of TG5’s meetings are co-located with TG3 (CLI), and both standards are currently on the same schedule.and both standards are currently on the same schedule.

Page 36: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

43

C++/CLI Participants and C++/CLI Participants and TimelineTimeline

Participants:Participants:• Convener: Convener: Tom PlumTom Plum• Project Editor: Project Editor: Rex JaeschkeRex Jaeschke• Subject Matter Experts:Subject Matter Experts: Bjarne Stroustrup, Herb SutterBjarne Stroustrup, Herb Sutter• Participants: Participants: Dinkumware, EDG, IBM, Dinkumware, EDG, IBM,

Microsoft, Plum Hall…Microsoft, Plum Hall…• Independent conformance test suite: Plum HallIndependent conformance test suite: Plum Hall

Ecma + ISO process, estimated timeline:Ecma + ISO process, estimated timeline:• Oct 1, 2003: Ecma TC39 plenary. Kicked off TG5.Oct 1, 2003: Ecma TC39 plenary. Kicked off TG5.• Nov 21, 2003:Nov 21, 2003: Submitted base document to Ecma.Submitted base document to Ecma.• Dec 2003 – Mar 2005: TG5 meetings.Dec 2003 – Mar 2005: TG5 meetings.• Jun 2005: Vote on whether to adopt as Ecma standard.Jun 2005: Vote on whether to adopt as Ecma standard.• Q3 2005: If successful, submit for ISO fast-track process.Q3 2005: If successful, submit for ISO fast-track process.• Q3 2006: If ready, vote on whether to adopt ISO standard.Q3 2006: If ready, vote on whether to adopt ISO standard.

Page 37: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

44

Future: Unify Memory and Object Future: Unify Memory and Object ModelsModelsSemantically, a C++ program can create an Semantically, a C++ program can create an object object of any type Tof any type T in any storage location: in any storage location:• On the native heap On the native heap (any type)(any type):: T* t1 = new T;T* t1 = new T;

– As usual, pointers (As usual, pointers (**) are stable, even during GC.) are stable, even during GC.– As usual, failure to explicitly call As usual, failure to explicitly call deletedelete will leak. will leak.

• On the gc heap On the gc heap (any type)(any type):: T^ t2 = gcnew T;T^ t2 = gcnew T;– Handles (Handles (^̂) are object references (to whole objects).) are object references (to whole objects).– Calling Calling deletedelete is optional: "Destroy now, or finalize later." is optional: "Destroy now, or finalize later."

• On the stack:On the stack: T t3;T t3;– Q: Why would you? A: Deterministic destruction/dispose is Q: Why would you? A: Deterministic destruction/dispose is

automatic and implicit, hooked to stack unwinding or to the automatic and implicit, hooked to stack unwinding or to the enclosing object’s lifetime.enclosing object’s lifetime.

Arbitrary combinations of members and bases:Arbitrary combinations of members and bases:• Any type can contain members and/or base classes of any Any type can contain members and/or base classes of any

other type. Virtual dispatch etc. work as expected.other type. Virtual dispatch etc. work as expected.

Page 38: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

45

Rationale and GoalsRationale and Goals

Language TourLanguage Tour

Design and Implementation HighlightsDesign and Implementation Highlights• Unified pointer and storage system Unified pointer and storage system

(stack, native heap, gc heap).(stack, native heap, gc heap).

• Deterministic cleanup: Deterministic cleanup: Destruction/Dispose, finalization.Destruction/Dispose, finalization.

• Generics × templates, STL on CLR.Generics × templates, STL on CLR.

Standardization and FuturesStandardization and Futures

OverviewOverview

Page 39: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

46

Summary: C++ × CLRSummary: C++ × CLR

C++ features:C++ features:• Deterministic cleanup, Deterministic cleanup,

destructors.destructors.• Templates.Templates.• Native types.Native types.• Multiple inheritance.Multiple inheritance.• STL, generic algorithms, STL, generic algorithms,

lambda expressions.lambda expressions.• Pointer/pointee Pointer/pointee

distinction.distinction.• Copy construction, Copy construction,

assignment.assignment.

CLR features:CLR features:• Garbage collection, Garbage collection,

finalizers.finalizers.• Generics.Generics.• Reference and value Reference and value

types.types.• Interfaces.Interfaces.• Verifiability.Verifiability.• Security.Security.• Properties, delegates, Properties, delegates,

events.events.

Page 40: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

47

Choosing a LanguageChoosing a LanguageQ: Which .NET language should you use?Q: Which .NET language should you use?

Microsoft’s answer, in our VS 2005 release:Microsoft’s answer, in our VS 2005 release:• Use whichever language you know or like.Use whichever language you know or like.

• If you have an existing C++ code base:If you have an existing C++ code base: Keep using C++. Keep using C++. C++ is the recommended path to .NET and WinFX.C++ is the recommended path to .NET and WinFX.

• If you want to make frequent use of native code/libs:If you want to make frequent use of native code/libs: C++ is far simpler (seamless, no code setup).C++ is far simpler (seamless, no code setup).

• ““Pure .NET:” If you want to write brand-new pure-.NET apps Pure .NET:” If you want to write brand-new pure-.NET apps that rarely or never interop with native code:that rarely or never interop with native code:Use whatever language you’re already comfortable with, Use whatever language you’re already comfortable with, and pick based on language features, performance, etc. The and pick based on language features, performance, etc. The CLR features, .NET Framework, and WinFX are available CLR features, .NET Framework, and WinFX are available equally through all languages.equally through all languages.

Page 41: Herb Sutter Architect Developer Division, Microsoft Converging Roads.NET, Longhorn, and C++

Questions?Questions?

Converging RoadsConverging Roads.NET, Longhorn, and C++.NET, Longhorn, and C++


Recommended