A Baker's Dozen: Thirteen Things You Should Know Before Porting Your Visual C ++ .NET Programs to Visual Studio 2005

xiaoxiao2021-03-06  105

Introduction

Those of us in the C community feel a bit like the older child in a family when the new baby is brought home. Oohs and aahs circle around the new little tyke, who everybody wants to hold and make goo-goo faces at. If we 're lucky, we get a pat on the head. Maybe our hair is ruffled. It's hard not to feel suddenly ignored and a bit hurt. Actually, it's a tad worse in technology, where the ground is constantly shifting and keeping abreast is a Matter of Survival.

Of course, today, .NET is the new technology-quite a feast at that, and everyone is oohing and aahing about C #. It is hard not to wonder if maybe we as C programmers ought not to learn C #. After all, in all The .NET Discussion, There IS Hardly A Mention Of C , Except To Maybe Contrast It With The New Kid All, Missing The Boat Can Mean Losing your meal ticket as well.

Are C programmers obsolete? Absolutely not! In this article, I'll touch on what's new in the current release of Microsoft Visual Studio .NET, and then give you some idea of ​​our future plans. All of us on the Visual C team think You'll be pleasantly surprised.

I wrote that for an MSDN article introducing our Visual C work for Microsoft Visual Studio.NET. With the beta release of Microsoft Visual Studio 2005, this seems a good time for a reality check on my earlier promises. It's really not an idle question for the Visual C programmer. And it's really not a question of whether we've given Visual C a future in the .NET environment, but rather, have we given it a present? That, for me, has been the measure of all our work . in redesigning the CLI binding for Visual C Not to put too fine a point on it: the original work to integrate Visual C into .NET fell short Oh, it succeeded very well in its primary purpose:. provide a bridge over which to integrate existing native code into a .NET application-the technology is called IJW (It Just Works). And that's very cool. Unfortunately, other aspects of the language were less successful. Personally, I found writing C # code closer in spirit to C than I Did Writing Code in the Managed Extensions . That had to be fixed.

The good news is that we did not just fix the language;. We reinvented it We added deterministic finalization, support for automatic memberwise copy and initialization, first class support for operator overloading-heck, we even threw in support for STL, as well As Support for Both the Template and CLI Generic Parameterized Type Mechanisms. It is now my language of preference for programming under .net. We Hope It Will Be your preferred language, AS Well.

The bad news is that we did not just fix the language; we reinvented it Getting from point A to point B, from the old language binding to the new language binding, is a bit like getting from Kansas to Oz It is just.. NOT A MECHANICAL TRANSPSITION, But Requires a bit of incentation.to Ease The Transition, We've Moved Forward In Three Primary Co.

The compiler continues to accept the original syntax with a special switch (/ clr: old_syntax). We're working on an informal translation tool that can get you 80% of the way there It will likely be made available for test-driving during. the time-frame of the second beta. We're providing this document, and a companion translation guide, Moving Your Programs from Managed Extensions for C to C / CLI, lists each language change in detail with original and revised code snippets and a motivation as to why each sign.

This article is meant as a developer summary. It highlights a baker's dozen issues that you'll need to consider in order to have a safe and pleasant porting experience. (To help you get a feel for the differences, an Appendix lists the issues in Tabular form.)

The original language binding to the CLI was called Managed Extensions to C . The revised language binding is referred to as C / CLI, and an ECMA standard of this binding is currently progressing well. For convenience, within this article I refer to the original binding As v1, and the revised binding as v2.

The Language Revisions Fall Into The Following General Categories:

Syntax. This represents changes in the way we define and manipulate our CLI types to make programming more elegant and pleasant. This is particularly true in the specification of CLI arrays and in scalar and index properties. While these changes are extensive, they are also largely mechanical. CLI conformance. The CLI object model differs in some significant ways from that of C . The V1 binding at times resisted that, such as in its treatment of string literals, its handling of the CLI enum, and in the definition of value types . These changes, we believe, improve the fidelity of the dynamic programming model. Unfortunately, they do not in all cases provide a mechanical translation from V1 to V2. For example, value types no longer support a default constructor-Item # 10. A CLI enum can no longer be forwardly declared-Item # 7. CLI enhancements. If you are a C programming, the absence of support for copy construction and the automatic invocation of a destructor on a reference type is no t just aggravating but error-prone. These represent beneficial patterns of object management that enhance the integrity of our programs. These and other design patterns from ISO-C have been integrated within the CLI binding in V2. That's the good news. The bad news , again, is that they do not in all cases provide a mechanical translation from V1 to V2. for example, support for deterministic-finalization changes the meaning of a class destructor between V1 and V2-Item # 6. An explicit overriding of an interface Member is now integrated Into a Virtual Function Override Mechanism-item # 12.The New Syntactic Landscape

People rarely call home about the syntax of a programming language, except if it's to complain. Mostly, the best we can do is hope that we do not confuse people and that we have not made it too painful for them to spend hours at a time .. over weeks and months employing our language to implement and deploy programs The least excusable sin of language syntax is to leave the programmer unsure as to the meaning of her program Not only can that compromise the quality of the software; it can also diminish the quality of a programmer's life. The new language binding is a more inhabitable environment for the zestful development of complex software. If you are a Visual C programmer working to develop under .NET, I believe you will agree that we have significantly improved the language experience .1. Contextual keywords replace__

The double-underscores are gone That's the first obvious difference The reason for their introduction in V1 was two-fold:.. (A) conformance to the ISO policy of setting off language extensions, and (b) providing a non-invasive strategy for introducing new keywords. So, the motivation was well-mannered and reasonable. The reason for their removal in V2 was that the result was an ugly syntax that felt both complex and unsightly. The V2 solution to (b) is to introduce contextual keywords. (The Solution to (a) IS A Bit More of a Tap Dance and is Performed in The Full Translation Guide.)

A contextual keyword has a special meaning within specific program contexts. Within the general program, for example, sealed is treated as an ordinary identifier. However, when it occurs within the declaration portion of a managed reference class type, it is treated as a keyword within the context of that class declaration. This minimizes the potential invasive impact of introducing a new keyword in the language, something that we feel is very important to users with an existing code base. At the same time, it allows users of the new functionality to have a first-class experience of the additional language feature-something we felt was missing from the original language design.Table 1.1 provides a listing of the changes in the syntax of declaring the CLI types.

Table 1.1 The CLI TYPE SYNTAX CHANGES

CLI TypeManaged Extension C / CLIreference class__gc class Rref class Rvalue class__value class Vvalue class Vabstract class__gc __abstract class Rref class R abstractsealed class__gc __sealed class Rref class R sealedinterface class__gc __interface IBarinterface class IBarCLI enum__value enum Eenum class Edelegate type__delegate void CallBack () delegate void CallBack ()

2. Tracking Handle (^) Replaces Pointer (*)

In V1, an object of a reference type is declared using pointer syntax. Under the revised language design, a reference class type object is declared using a new declarative token (^) referred to formally as a tracking handle and more informally as a hat. (The tracking adjective underscores the idea that a reference type sits within the CLI heap, and can therefore transparently move locations during garbage collection heap compaction. A tracking handle is transparently updated during runtime. Two analogous concepts are (a) the tracking reference (% ), AND (b) The interior Pointer (Interior_Ptr <>) - See The Main Document for a Discussion of these Changes.) for example, // v1 Declaration of a CLI Reference Type

String * ps = s "a string literal";

// v2 Declaration of a CLI REFERENCE TYPE

String ^ ps = "a string literal";

(We have also cleaned up the handling of string literals that promote to the System :: String Unicode representation. In this example, the programmer no longer must manual identify a string literal as being a System literal.)

This also allows us to provide a uniform syntax across both reference and value types that are located on the CLI heap. Unlike C # and Microsoft Visual Basic .NET, the C binding to the CLI allows the programmer to directly manipulate a boxed instance of a value Type; this can be considrably more effect. Here is how it is done in Both V1 and V2,

Double result = 3.14159;

// v1 Syntax

__box double * br = __box (result);

// v2 Syntax

Double ^ br = result;

The Use of the Pointer Syntax Was Problematic In Two Primary Areas (A More Aggressive Defense of The Change Can Be Found In The Companion Translation Guide):

The use of the pointer syntax did not allow overloaded operators to be directly applied to a reference object; rather, one had to call the operator through its internal name, such as r1-> op_Addition (r2) rather than the more intuitive r1 r2 . There are a number of pointer operations, such as casting and pointer arithmetic, that are disallowed for objects stored on a garbage collected heap. This lead to confusion among users, and we believe a separate token better captures the notion of a CLI reference type .There are two auxiliary changes that accompany the change from R * to R ^ -the replacement of operator new with a CLI specific heap operator, and the introduction of a special token to represent a null tracking handle.

A New CLI Heap Allocation Operator, gcnew. For example, // v1 Syntax

StreamReader * ifile = new streamreader (filename);

NativeClass * PNC = New NativeClass (ARGS);

// v2 Syntax

StreamReader ^ ifile = gcnew streamreader (file);

NativeClass * PNC = New NativeClass (ARGS);

In v1, weinitialize a reference type to address no object as follows, // v1: ok ... we set obj to reference to no ibject

Object * Obj = 0;

// v1: error ... no ketlicit boxing ...

Object * Obj2 = 1;

In V2, any initialization or assignment of a value type to an Object results in an implicit boxing of that value type. In V2, therefore, both obj and obj2 are initialized to addressed boxed Int32 objects holding, respectively, the values ​​0 and 1. For example, // v2: ok ... causes the implicit boxing of Both 0 and 1

// But That is not what we intended for obj!

Object ^ obj = 0;

Object ^ obj2 = 1;

Therefore, in order to allow the explicit initialization, assignment, and comparison of a tracking handle against referring to no object, we introduced a new keyword, nullptr. And this should replace each instance of 0 And so the correct revision of the V1 example looks As Follows: // v2: ok ... we set obj to reference to no objectObject ^ obj = NULLPTR

// v2: ok ... weinitize obj2 to a int32 ^

Object ^ obj2 = 1;

3. CLI Array Syntax IS Simplified

The declaration of a CLI array object in V1 was a slightly non-intuitive extension of the standard array declaration in which a __gc keyword is placed between the name of the array object and its possibly comma-filled dimension. For example,

// v1 Syntax

Void PrintValues ​​(Object * myarr __gc []);

Void PrintValues ​​(int myarr __gc [,]);

This has been simplified in V2, in which we use a template-like declaration that suggests the STL vector declaration. The first parameter indicates the element type. The second parameter specifies the array dimension (with a default value of 1, so only multiple dimensions Require a second argument). The Array Object Itself Is A Tracking Handle and Therefore Requires a Hat. if The Element Type Is Also A Reference Type, That, Too, Must Be Given a Hat. for Example,

// v2 Syntax

Void PrintValues ​​(Array ^ Myarr);

Void PrintValues ​​(Array ^ myarr);

4. Properties Are Unified

In V1, each set or get property accessor is specified as an independent member function. The declaration of each method is prefixed with the __property keyword. The method name begins with either set_ or get_ followed by the actual name of the property. For example,

// v1 Syntax

PUBLIC __GC __SEALED CLASS vector {

Float_x;

PUBLIC:

__property double get_x () {return _x;} __property void set_x (double newx) {_x = newx;}

}

This was found to be confusing, because it spreads out the functionality associated with a property and requires the user to lexically unify the associated sets and gets. Moreover, it is lexically verbose, and feels inelegant. In the revised language design, the property keyword is followed by the type of the property and its unadorned name. The set and get access methods are placed within a block following the property name. (Note that unlike C #, the signature of the access method is specified.) For example,

// v2 Syntax

Public ref class vector sealed {

Float_x;

PUBLIC:

Property Double X

{

Double get () {return _x;}

Void set (double newx) {_x = newx;}

} // NOTE: No Semi-Colon ...

}

Index Properties

The primary V1 shortcoming of indexed properties is its inability to provide class-level subscripting. A second, less significant, shortcoming is that it is visually difficult to distinguish a property from an indexed property-the number of parameters is the only indication. The indexed Properties in V1 Also Suffer from the Same Problems As Those of Scalar Properties: The Accessors Are Not Treated as an atomic unit, but self, but separated INTO Individual Methods. For Example,

// v1 Syntax

PUBLIC __GC CLASS.

Public __gc class matrix

{

FLOAT MAT [,]; // v1 array syntax ...

PUBLIC:

__property void set_item (int R, int C, float value);

__property int GET_ITEM (int R, INT C);

__property void set_row (int r, vector * value);

__property int GET_ROW (INT R);

}

In V2, the index properties are distinguished by the bracket ([,]) following the name of the indexer and indicating the number and type of each index. Here is the Matrix declaration recast into the new syntax. (Note that a forward CLI class Declaration is no longer permitted to indeicate its public or private access level-as illustrate in the forward decaration of the vector class.) // v2 syntax

// Now Illegal to Specify Public Here ...

Ref class vector;

Public Ref class matrix {

Private:

Array ^ mat; // v2 array syntax ...

PUBLIC:

Property Int item [int, int]

{

INT GET (INT R, INT C);

Void Set (int R, int C, Float Value);

}

Property int Row [INT]

{

INT GET (INT R);

Void Set (int R, Vector ^ Value);

}

}

To indexer, The Default Keyword Is Reuse To Substitution for An Explicit Name. For Example,

Public Ref class matrix {

Private:

Array ^ mAT;

PUBLIC:

// ok: Class Level Indexer Now

// Matrix Mat ...

// Mat [0, 0] = 1;

// Invokes the set accessor of the default indexer ...

Property Int default [int, int]

{

INT GET (INT R, INT C);

Void Set (int R, int C, Float Value);

}

}

5. Operators Are Integrated with ISO-C

Perhaps the most striking aspect of V1 is its support for operator overloading-or rather, its effective absence. Within the declaration of a reference type, for example, rather than using the native operator syntax, one had to explicitly write out the underlying internal name of the operator-for example, op_Addition More onerous, however, is the fact that the invocation of an operator had to be explicitly invoked through that name, thus precluding the two primary benefits of operator overloading:. (a) the intuitive syntax, and (b) The Ability to Intermix New Types with existing type. for example, // v1 Syntax

PUBLIC __GC __SEALED CLASS vector {

PUBLIC:

VECTOR (Double X, Double Y, Double Z);

Static Bool Op_equality (const vector *, const vector *);

Static vector * op_division (const vector *, double);

Static Vector * OP_Addition (const vector *, const vector *);

Static Vector * OP_SUBTRAction (const vector *, const vector *);

}

int main ()

{

Vector * PA = New Vector (0.231, 2.4745, 0.023);

Vector * Pb = New Vector (1.475, 4.8916, -1.23);

Vector * pc1 = Vector :: op_addition (pa, pb);

Vector * pc2 = Vector :: op_subtraction (pa, pc1);

Vector * PC3 = Vector :: op_division (pc1, pc2-> x ());

IF (Vector :: op_equality (pc1, p2)) // ...

}

In V2, the usual expectations of a native C programmer are restored, both in the declaration and in the use of the static operators (the C instance operators are also supported in V2, but that is not a translation issue). For example,

// v2 Syntax

Public ref class vector sealed {

PUBLIC:

VECTOR (Double X, Double Y, Double Z);

Static Bool Operator == (const vector ^, const vector ^);

Static Vector ^ Operator / (const vector ^, double); static vector ^ operator (const vector ^, const vector ^);

Static Vector ^ Operator - (const vector ^, const vector ^);

}

int main ()

{

Vector ^ Pa = GCNew Vector (0.231, 2.4745, 0.023),

Vector ^ PB = GCNew Vector (1.475, 4.8916, -1.23);

Vector ^ pc1 = pa pb;

VECTOR ^ PC2 = PA - PC1;

VECTOR ^ PC3 = PC1 / PC2-> x ();

IF (PC1 == P2) // ...

}

Changes in semantic meaning

It can be a difficult and somewhat frustrating experience to change from a programming paradigm with which one has become an expert to a new paradigm with which one finds oneself making clumsy, new-kid-on-the block sorts of errors. V2 has extended the CLI binding with a number of C -. specific extensions to make the transition to a dynamic programming paradigm more familiar This includes support for memberwise copy semantics and the automatic invocation of a reference type destructor at the end of its lifetime.

6. Destructor Goes To Idisposable :: Dispose

Before the memory associated with an object is reclaimed by the garbage collector, an associated Finalize () method, if present, is invoked. You can think of this method as a kind of super-destructor since it is not tied to the program lifetime of the object. We refer to this as finalization. The timing of just when or even whether a Finalize () method is invoke is undefined. This is what is meant when we say that garbage collection exhibits non-deterministic finalization.

Non-deterministic finalization works well with dynamic memory management. When available memory gets sufficiently scarce, the garbage collector kicks in and things pretty much just work. Under a garbage collected environment, destructors to free memory are unnecessary.Non-deterministic finalization does not work well, however, when an object maintains a critical resource such as a database connection or a lock of some sort. In this case, we need to release that resource as soon as possible. In the native world, that is done through the pairing of a constructor / destructor pair. As soon as the lifetime of the object ends, either through the completion of the local block within which it is declared or through the unraveling of the stack because of a thrown exception, the destructor kicks in and the resource is Automatically Released. it works very well, and its absence under the original language design.

The solution provided by the CLI is for a class to This is error-prone and therefore a step backwards implement the Dispose () method of the IDisposable interface. The problem here is that Dispose () requires an explicit invocation by the user.. The C # Language Provides a Modest Form of Automation Through a Special Using Statement. V1 Province.

In V1, The Destructor of a Reference Class Is Implement THROUGH The FOLLOWING TWO Steps:

The user-supplied destructor is renamed internally to Finalize (). If the class has a base class (remember, under the CLI Object Model, only single inheritance is supported), the compiler injects a call of its finalizer following execution of the user- Supplied code. for Example, Given the Following Trivial Hierarchy Taken from The V1 Language Specification, __GC Class A {public:

~ A () {console :: WriteLine (s "in ~ a");}

}

__GC Class B: Public a {

PUBLIC:

~ B () {Console :: WriteLine (s "in ~ b");}

}; Both destructors are renamed Finalize () B's Finalize () method has an invocation of A's Finalize () method added following the invocation of WriteLine () This is what the garbage collector will invoke by default during finalization Here is what this... INTERNAL TRANSFORMATION Might Look Like, // Internal Transformation of Destructor Under V1

__gc class a {

// ...

Void finalize () {console :: WriteLine (s "in ~ a");}

}

__GC Class B: Public a {

// ...

Void finalize () {

Console :: WriteLine (s "in ~ b");

A :: finalize ();

}

}

In the second step, the compiler synthesizes a virtual destructor. This destructor is what our V1 user-programs invoke, either directly or through an application of the delete expression. It is never invoked by the garbage collector. What is placed within this synthesized destructor ? Two statements. One is a call to GC :: SuppressFinalize () to make sure there are no further invocations of Finalize (). The second is the actual invocation of Finalize (). This, recall, represents the user-supplied destructor for That Class. Here is what this might look like, __gc class a {

PUBLIC:

Virtual ~ a ()

{

System :: GC :: SuppressFinalize (this);

A :: finalize ();

}

}

__GC Class B: Public a {public:

Virtual ~ b ()

{

SYSTEM :: GC: SuppressFinalize (THIS);

B :: finalize ();

}

}

While this implementation allows the user to explicitly invoke the class Finalize () method now rather than whenever, it does not really tie in with the Dispose () method solution. This is changed in the revised language design.

IN V2, THE DESTRUCTOR IS RENAMED INTERLY TO The dispose () Method and The Reference Class IS Automatical Extended to Implement The Idispose Interface.

When either a destructor is invoked explicitly under V2, or when delete is applied to a tracking handle, the underlying Dispose () method is invoked automatically. If it is a derived class, a call of the Dispose () method of the base class is INSERTED ATHE Close of the synthesized method.

But this does not get us all the way to deterministic finalization. In order to reach that, we need the additional support of local reference objects. (This has no analogous support within V1, and so it is not a translation issue-nor is IT Available in The Beta1 Release. A Description Can Be Found In The Full Translation Guide.)

In V2, as we've seen, the destructor is synthesized into the Dispose () method. This means that in cases where the destructor is not explicitly invoked, the garbage collector, during finalization, will not as before find an associated Finalize () Method for the object. in Order to Support Both Destruction and finalization, V2 HAS Introducesd a Special Syntax for Providing a finalizer. for example,

// v2 Syntax

Public Ref class r {

protected:

! R () {Console :: WriteLine ("I am the r :: firmizer ()!");}

}

The! Prefix is ​​meant to suggest the analogous tilde (~) that introduces a class destructor-that is, both post-lifetime methods have a token prefixing the name of the class. If the synthesized Finalize () method occurs within a derived class, an invocation of the base class Finalize () method is inserted at its end. If the destructor is explicitly invoked, the finalizer is suppressed. (Note that a finalizer must be declared as a protected and not a public member.) This means that the Runtime Behavior of a V1 Program Is Silently Changed When Compiled Under V2 WHENEVER A Reference Class Contains a Non-Trivial Destructor. The Required Translation Algorithm Is To Do The Following:

If a destructor is present, rewrite that to be the class finalizer. If a Dispose () method is present, rewrite that into the class destructor. If the original code contained an explicit invocation of the class destructor or an application of the delete operator to An Instance of the Type, You Will Need To Also Provide a Public Method Through Which To Invoke The Finalizer in Order to Duplicate The V1 Behavior. for Example, Public Ref Class R {

PUBLIC:

Void CallFinalizer ()

{

System :: GC :: SuppressFinalize (this);

THIS ->! R ();

}

protected:

! R () {Console :: WriteLine ("I am the r :: firmizer ()!");}

}

For Example, The Following V1 Code, Void F (r * r)

{

r-> dispose (); // 1

Delete r; // 2

}

Would Be Transformed Into The Following V2 Code, Void F (R ^ R)

{

Delete r; // now Equivalent TO 1

R-> CallFinalizer (); // 2

}

7. CLI ENUMS

The V1 CLI enum declaration is preceded by the __value keyword. The idea here is distinguish the native enum from the CLI enum that is derived from System :: ValueType, while suggesting an analogous functionality. For example, // V1 Syntax

__Value Enum E1 {Fail, Pass};

Public __Value Enum E2: Unsigned SHORT

{NOT_OK = 1024, Maybe, OK = 2048};

V2 solves the problem of distinguishing native and CLI enums by emphasizing the class nature of the latter rather than its value type roots. As such, the __value keyword is discarded, replaced with the spaced keyword pair of enum class. This provides a paired keyword symmetry To The Declarations of The Reference, Value, And Interface Classes. The Translation of The Enumation Pair E1 And E2 in V2 Looks as Follows,

// v2 Syntax

ENUM CLASS E1 {Fail, Pass};

Public ENUM CLASS E2: Unsigned Short

{NOT_OK = 1024, Maybe, OK = 2048};

Apart from this Small Syntactic Change, The Behavior of The CLI ENUM TYPE HAS BEEN CHANGED IN A Number of Ways:

A forward declaration of a CLI enum is no longer supported in V2. There is no mapping. It is simply flagged as a compile-time error. The overload resolution between the built-in arithmetic types and the Object class hierarchy has reversed between V1 and V2. As a side-effect, CLI ENUMS Are No Longer Implicitly Converted to Arithmetic Types in v2 as the the Following Code Fragment: // V1 SYNTAX

__Value enum status {fail, pass};

Void f (Object *) {cout << "f (object) / n";

Void f (int) {cout << "f (int) / n";}

int main ()

{

STATUS RSLT;

f (RSLT); // Which f is invoked?

}

For the native C programmer, the natural answer to the question, which instance of the overloaded f () in invoked ?, is that of f (int). An enum is a symbolic integral constant, and it participates in the standard integral promotions that take precedence in this case. in V1, this is the instance to which the call resolves. However, this resolution caused a number of surprises-not when we used them in a native C frame of mind, but when we needed them to interact with the existing Base class Library framework, where an Enum is a class indirectly derived from Object. In V2, the instance of f () invoked is that of f (Object ^). As a side-effect, the revised language does not support implicit conversions between a CLI enum type and the arithmetic types. Any code that used a CLI enum where an arithmetic type is expected now requires an explicit cast. in V2, a managed enum maintains its own scope, in conformance with the CLI object model, but Counter-Intuitive to the Native C

programmer. In V1, an attempt was made to define weakly injected names for the enumerators of a CLI enum in order to simulate the absence of scope within the native enum. This did not prove successful. The problem is that this causes the enumerators to spill into the global namespace, resulting in difficult to manage name-collisions. in V2, therefore, we have conformed to the other CLI languages ​​in supporting scopes within the managed enum. Under V1, that is, the enumerators of a CLI enum are visible within the containing scope of the enum. In V2, the enumerators are encapsulated within the scope of the enum. This means that any unqualified use of an enumerator of a CLI enum is not recognized under V2. For example, // V1 supporting weak injection__gc class Xdcmake {

PUBLIC:

__Value enum _xdc {

Undefined, Option_USAGE, XDC4_XML_LDFAIL = 4};

Xdcmake () {

// UNQualified use of _xdc enumerators ...

OPLIST-> add (__box (undefined)); // (1)

OPLIST-> add (__box (option_usage)); // (2)

Itaglist-> add (__box (xDC4_XML_LDFAIL); // (3)

}

}

Each of the threea e e (1), (2), AND (3)) NEED TO BE Qualified in The Translation To V2. For Example, // V2 Syntax - Cli Enum Exhibits Scope

Ref class xdcmake {

PUBLIC:

ENUM CLASS _XDC {

Undefined, Option_USAGE, XDC4_XML_LDFAIL = 4

}

XDCMAKE ()

{// Explicit Qualification Required ...

Oplist-> add (_xdc :: undefined); // (1)

Oplist-> add (_xdc :: option_usage); // (2)

Itaglist-> add (_xdc :: xdc4_xml_ldfail); // (3)

}

}

8. PINNING POINTERS

The garbage collector may optionally move objects that reside on the CLI heap to different locations within the heap during a compaction phase. This movement is not a problem for tracking handles, tracking references, and interior pointers, which update these entities transparently. This movement is a problem, however, if the user has passed the address outside of the runtime environment. In this case, the volatile movement of the object is likely to cause a runtime failure. to exempt objects such as these from being moved, we must locally pin them to their location for the extent of their outside use.In V1, a pinning pointer is declared by qualifying a pointer declaration with the __pin keyword. In V2, a pinning pointer is declared with a pseudo-template syntax. The original constraints on a PINNING POINTER Remain. for Example, IT Cannot Be Used As a parameter or return type of a method; rather, IT CAN Only BE DECLY ON A local Object. a Number of Additional Constraints Are Added in V2:

The default value of a pinning pointer is nullptr, not 0. A pin_ptr <> can not be initialized or assigned 0. All assignments and explicit comparisons to 0 need to be changed to nullptr. (This is true of all reference types.) In V1 A PINNING POINTER IS Permitted to Address A Whole Object. In V2, PINNING A WHOL Object IS Not Supported. Rather, The Address of An Interior Member Needs To Be Pinned. for Example, // V1 Syntax

__GC struct h {Int j;};

__GC Class g {...};

Void f (g * g)

{

// v1: Pinning a whole object

H __pin * ph = new h;

g-> incr (& pH -> j);

}

THE Member That Case Is H :: J. The Revision of The Program To Compile Under V2 Is To Retarget The Source of the Pinning To That Me MEMBER. For Example, // V2 SYNTAX

Ref struct h {int j;};

REF Class g {...};

Void f (g ^ g)

{

H ^ ph = gcnew h;

// v2: Pin Interior MEMBER ...

PIN_PTR PJ = & ph-> J;

g-> incr (pj);

}

9. Static Const Members Go to Literal

Although static const integral members are still supported, their linkage attribute has changed between V1 and V2. Their V1 linkage attribute is now carried in a literal integral member under V2. For example, consider the following class declared under V1,

// v1 Syntax

PUBLIC __GC CLASS Constants {

PUBLIC:

Static const INT log_debug = 4;

// ...

}

This generates the following underlying cil attributes for the field (Note The Literal Attribute in Boldface),

.field public static literal INT32

Modopt ([Microsoft.visualc] Microsoft.Visualc.isconstmodifier) ​​Standard_client_prx = int32 (0x00000004)

While this STILL Compiles Under V2,

// v2 Syntax

Public ref class constants {

PUBLIC:

Static const INT log_debug = 4;

// ...

}

IT NO LONGER EMITS The Literal Attribute, And Therefore Is Not Viewed As a constant by the cli runtime,

.field public static int32 modopt ([Microsoft.visualc] Microsoft.visualc.isconstmodifier) ​​Standard_client_prx = int32 (0x00000004)

In Order to Have The Same Inter-Language Literal Attribute, The Declaration Needs To Be Changed To The Newly Supported Literal Data Member. For example,

// v2 Syntax

Public ref class constants {

PUBLIC:

LITERAL INT log_debug = 4;

// ...

}

This Change Should Only Be Applied To Static Const Members of Integral Type. All Others Types SHOULD Remain As Before.changes WITHOUT One-To-One Mapping

In designing C , Bjarne Stroustrup, over the years, admittedly made a few mistakes. For example, in the initial version of the language, the invocation of a virtual function within a constructor resolved to the most derived instance. Over time, it became clear that, in general, this was the wrong behavior, and he reversed the behavior with Release 1.2 of cfront back in the 1980s. We also have made some mistakes-perhaps are still making some now. I do not believe we are the only language That Has Done So; Still, We Are The Only Language About Which I am Writing. Except for Item # 13, Which Makes Use of a New Override Facility, Thene Items Reperse Reversals That Invalidate V1 usage.

10. Constructors Are Implicitly Explicit

Under V1, a single argument constructor defines the conversion of a class object into an object of a second type. If an object of a class is expected, and the value supplied is of a type that matches a single argument constructor of that class, the compiler silently invokes the constructor to create a temporary object of that class, which it then applies to the expression. This impacts initialization, assignment, and function and operator overload resolution. In V2, single-argument constructors behave as if they have been declared explicit ...............................

// a CREATION CAST ... Constructor Invoked ...

Buffer (128);

Invokes The Associated Class Constructor, The Same As IN V1. HOWEVER, A Conversion Cast, of The Following Forms, // Conversion Castries ... Constructor is Never Invoked for Tse ...

(Buffer) 128;

(Buffer) (128);

Static_cast (128);

NEVER RESULTS INVTRUCATION OF A Associated Construction of An Associated Cast Only successs if the class defines an appropriate converness operator.

.................. ..

11. No Value Class Default Constructor

In both V1 and V2, a value class does not support special class member functions (SMF) such as a copy constructor, a copy assignment operator, and a destructor. In V1, however, a value class did allow the definition of a default constructor -That IS, A Constructor Taking No Arguments. In v2, this Permission Has Been Rescinded; A Value Class CAN No Longer Provide a Default Construction.

The problem, in this case, is that there are run-time occasions in which we could not guarantee the invocation of the associated default constructor. Given that absence of guarantee, it was felt to be better to drop the support altogether rather than have it Be Non-Deterministic in ITS Application.

In general, the absence of this special member function is not a problem if we use a value class in a constrained way; that is, if we only allow it to contain value members so that it supports bitwise copy We do not need a copy. constructor nor a copy operator when the aggregate type supports bitwise copy. Similarly, we do not need a destructor when the state of the aggregate type exhibits value semantics. Finally, since the runtime zeros out all states by default, we do not require a default constructor. (in C , primitive data types are not automatically zeroed out, and so most of our default constructor-use-but granted, not all-is used to put the object in an uninitialized state.) The problem, of course, is when a V1 value class uses the default constructor to perform non-zeroing operations. In this case, the code within the constructor will likely need to be migrated into a named initialization function. This is potentially error-prone, of course, because this method Must be evlici Tly invoked by the programmer.

12. Override of Private Virtual Function

In V1, the access level of a virtual function does not constrain its ability to be overridden within a derived class. (The same is true in ISO-C .) Under V2, a virtual function can not override a base class virtual function that it can not For example,

__gc class my {

Private:

Virtual void g (); // inaccessible to a deerived class ...

}

__gc class file: public my {

PUBLIC:

// in V1, OK: g () Overrides my :: g ()

// in v2, error: cannot Override: my :: g () inaccessible ...

Void g ();

}

The most obvious solution under V2 is to make the private base class member non-private The inherited methods do not have to bear the same access;.. They simply have to be accessible In this example, the least invasive change is to make the My MEMBER Protected. this Way The General Program's access to the method through my is stock prohibited, ref class my {

protected:

Virtual void g ();

}

Ref class file: my {

PUBLIC:

Void g ();

}

Note that the absence of the explicit virtual keyword in the base class, under the revised language, generates a warning message. It wants you to become a more responsible programmer by squawking until you make its virtual nature explicit.

13. Explicit Interface Function Override

It is often desirable to provide two instances of an interface member within a class that implements the interface-one that is used when class objects are manipulated through an interface handle, and one that is used when class objects are used through the class interface. For EXAMPLE,

// v1 Syntax

Public __gc class r: public iCloneable

{

// to be used through iCloneable ...

Object * icloneable :: clone ();

// TO BE Used Through AN R ...

R * clone ();

}

In V1, we do this by providing an explicit declaration of the interface method with the method's name qualified with the name of the interface. The class-specific instance is unqualified. This eliminates the need to downcast the return value of Clone (), in This Example, When Explicitly Called Through An Instance of R.

In V2, A General Overriding Mechanism Has Been Introducesd That Replace The Previous Syntax. Our Example Needs To BE Rewritten As Follows,

// v2 Syntax

Public Ref Class R: Public iCloneable

{

// to be used through iCloneable ... Object ^ interfaceclone () = iCloneable :: Clone;

// TO BE Used Through AN R ...

Virtual r ^ clone () New;

}

This revision requires that the interface member that is being explicitly overridden be given a unique name within the class. Here, I've provided the rather awkward name of InterfaceClone (). The behavior is still the same-an invocation through the ICloneable interface invokes .....................

Conclusion

So there you have it-a baker's dozen of the most visible change points between the original and revised C binding to the CLI. We believe the radical redesign in the language, although invasive, is a necessary step in making C a first-class denizen of the .NET environment. I would like to believe that we have been successful, but we will not have succeeded unless you agree as well. It is my hope that this article, the companion full Translation Guide, and the V1-to-V2 .

Related books

STL Tutorial and Reference Guide by David Musser, Gillmer Derge, And Atul Saini, Addison-Wesley, 2001

C Standard Library by Nicolai Josuttis, Addison-Wesley, 1999

C Primer by Stanley Lippman and Josee Lajoie, Addison-Wesley, 1998

Acknowledgements

I would like to thank the members of the Visual C Team for their help and guidance in detailing these issues. Thanks go to Arjun Bijanki, Artur Laksberg, Brandon Bray, Jonathan Caves, Siva Challa, Tanveer Gani, Mark Hall, Mahesh Hariharan, Jeff Peil, Andy Rich, Alvin Chardon, and Herb Sutter. All Have Been of Incredible Help and Responscept. This document is a tribute to all their expertise.about the Author

Stanley Lippman, Architect, Visual C , Microsoft Corporation. He began working on C with its inventor Bjarne Stroustrup back in 1984 within Bell Laboratories. In between, he worked in Feature Animation at Disney and DreamWorks, and was a Software Technical Director on Fantasia 2000 .

转载请注明原文地址:https://www.9cbs.com/read-101428.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.052, SQL: 9