Pure C ++

Source: Internet
Author: User
Hello, C ++/CLI

Stanley B. Lippman

Welcome to my first column for msdn & reg; magazine. I had actually written a completely different first column-one on the new generic programming support in Visual Studio & reg; 2005. reviewing it, though, I realized that it left far too quota unanswered questions. so I put that column aside and wrote this one to provide an overview of my team's work on C ++/CLI for Visual C ++ & reg; 2005. i'll follow this with a fistful of columns on. net generic programming. don't forget that this column is based on a prerelease version and may be subject to change.

What is C ++/CLI?

C ++/CLI represents a tuple. c ++ refers, of course, to the C ++ programming language specified ted by Bjarne stroustrup at Bell Laboratories. it supports a static object model that is optimized for the speed and size of its executables. however, it doesn' t support runtime modification of the program other than heap allocation. it allows unlimited access to the underlying machine, but very little access to the types active in the running program and no real access to the associated infrastructure of that program. herb Suter, a colleague of mine here at Microsoft and the chief effecect of C ++/CLI, refers to C ++ as a concrete language.

CLI refers to the common language infrastructure, a multitiered architecture supporting a dynamic component programming model. in each ways, this represents a complete reversal of the C ++ object model. a runtime software layer, the virtual execution system, runs between the program and the underlying operating system. access to the underlying machine is fairly constrained. access to the types active in the executing program and the associated Program Infrastructure-both as discovery and construction-is supported. the slash (/) represents a binding between C ++ and the CLI. the details surrounding this binding make up the general topic of this column.

So, a first approximation of an answer to what is C ++/CLI is that it is a binding of the static C ++ object model to the dynamic Component Object Model of the CLI. in short, it is how you do. NET Programming Using C ++ rather than C # Or
Visual Basic & reg;. Like C # And the CLI itself, C ++/CLI is undergoing standardization under the European Computer Manufacturers Association (ECMA) and eventually under ISO.

The Common Language Runtime (CLR) is the Microsoft version of the CLI that is specific to the Windows & reg; operating system. similarly and Visual C ++ 2005 is the implementation of C ++/CLI.

As a second approximation of an answer, I wocould say that C ++/CLI integrates. NET programming model within C ++ in the same way as, back at Bell Laboratories, we integrated generic programming using templates within the then existing C ++. in both of these cases your investigation in an existing C ++ codebase and in your existing C ++ expertise are preserved. this was an essential baseline requirement of the design of C ++/CLI.

Learning C ++/CLI

There are three aspects in the design of a CLI language that hold true when SS all ages: a mapping of language-level syntax to the underlying common type System (CTS ), the choice of a level of detail to expose the underlying CLI infrastructure to the direct manipulation of the programmer, and the choice of additional functionality to provide, above and beyond that supported directly by the CLI.

The first item is largely the same authentication SS all CLI commands ages. the second and third items are where one CLI language distinguishes itself from another. depending on the kinds of problems you need to solve, you'll choose one or another language, or possibly combine multiple CLI ages. learning C ++/CLI involves understanding each of these aspects of its design.

Mapping C ++/CLI to the CTS?

It is important when programming C ++/CLI to learn the underlying CTS, which has des these three general class types:

The polymorphic reference type, which is what you use for all class inheritance.
The non-polymorphic value type, which is used for implementing concrete types requiring runtime efficiency, such as the numeric types.
The abstract interface type, which is used for defining a set of operations common to a set of either reference or value types that implement the interface.

This design aspect, the mapping of the CTS to a set of built-in language types, is common across SS all CLI languages ages although, of course, the syntax varies in each CLI language. so, for example, in C #, you wocould write

Abstract class shape {...} // C #

To define an abstract shape base class from which specific Ric objects are to be derived, while in C ++/CLI you write
Ref class shape abstract {...}; // C ++/CLI

To indicate the exact same underlying CLI reference type. the two declarations are represented exactly the same way in the underlying Il. similarly, in C #, you write struct point2d {...} // C #

To define a concrete point2d class, while in C ++/CLI you write: Value class point2d {...}; // C ++/CLI

The family of class types supported with C ++/CLI represents an integration of the CTS with the native facilities, and that determines your choice of syntax. For example:

Class native {};
Value Class V {};
Ref class R {};
Interface Class I {};

The CTS also supports an enumeration class type that behaves somewhat differently from the native enumeration, and support is provided for both of those as well:

Enum native {fail, pass };
Enum class clienum: Char {fail, pass };

Similarly, the CTS supports its own array type that again behaves differently from the native array. And again Microsoft provides support for both:
Int native [] = {1, 1, 2, 3, 5, 8 };
Array <int> ^ managed = {1, 1, 2, 3, 5, 8 };

It is not accurate to think of any one CLI language as closer to or more nearly a mapping to the underlying CTS than is another. rather, each CLI language represents a view into the underlying CTS object model. you'll see this more clearly in the next section.

CLI level of detail

The second design aspect that must be considered when designing a CLI language is the level of detail of the underlying CLI implementation model to ininform ate into the language. what kind of problems will the language be tasked to solve? Does the language have the tools necessary to do this? Also, what sort of programmers is the language likely to attract?

Take, for example, the issue of value types occurring on the managed heap. value types can find themselves on the managed heap in a number of circumstances:

Through implicit boxing, when an instance of a value type is assigned to an object or when a virtual method is invoked through a value type that is not overridden.
When that value type is serving as a member of a reference class type.
When that value type is being stored as the element type of a CLI array.
Whether the programmer shocould be allowed to manipulate the address of a value type of this sort is a CLI language design consideration that must be addressed.

What are the issues?

Any object located on the managed heap is subject to relocation during the compaction phase of a sweep of the garbage collector. any pointers to that object must be tracked and updated by the runtime; the programmer cannot manually track it herself. therefore, if you were allowed to take the address of a value type that might be on the managed heap, there wowould need to be a tracking form of pointer in addition to the existing native pointer.

What are the trade-offs to consider? On the one hand, there's simplicity and safety. directly introducing support in the language for either one or a family of tracking pointers makes it a more complicated language. by not supporting this, the available pool of programmers is expanded because less sophistication is required. in addition, allowing the programmer access to these ephemeral value types increases the possibility of programmer error-she may purposely or inadvertently do dangerous things to the memory. by not supporting tracking pointers, a potentially safer runtime environment is created.

On the other hand, efficiency and flexibility must be considered. each time you assign the same object with a value type, a new boxing of the value occurs. allowing access to the boxed Value Type allows in-memory update, which may provide significant performance improvements. without a form of tracking pointer, you cannot iterate over a CLI Array Using pointer arithmetic. this means that the CLI array cannot participant in the standard template library (STL) iterator pattern and work with the generic algorithms. allowing access to the boxed Value Type allows significant design flexibility.

Microsoft chose to provide a collection of addressing modes that handle value types on the managed heap in C ++/CLI:

Int ivals = 1024;
Int ^ boxedi = ival;

Array <int> ^ iA = gcnew array <int> {1, 1, 2, 3, 5, 8 };
Interior_ptr <int> begin = & Ia [0];

Value struct smallint {int m_ival;...} Si;
Pin_ptr <int> PPI = & Si. m_ival;

The typical C ++/CLI developer is a sophisticated system programmer tasked with providing infrastructure and organizationally critical applications that serve as the Foundation over which a business builds its future. She must address
Both scalability and performance concerns and must therefore have a system-level view into the underlying cli. The level of detail of a CLI language reflects the face of its programmer.

Complexity is not in itself a negative quality. human beings are more complicated than single-cell bacteria, and that is certainly not a bad thing. however, when the expression of a simple concept is made complicated, that is usually considered to be a bad thing. in C ++/CLI, the CLI team has tried to provide an elegant way to express complex subject matter.

Additional functionality

A third design aspect is a language-specific layer of functionality above and beyond what is directly supported by the CLI. this may require a mapping between the language-level support and the underlying implementation model of the CLI. in some cases, this just isn' t possible because the language cannot intercede with the behavior of the CLI. one example of this is the virtual function resolution in the constructor and destructor of a base class. to reflect ISO-C ++ semantics in this case wowould require a resetting of the virtual table within each base class constructor and destructor. this is not possible because virtual table handling is managed by the runtime and not by the individual language.

So this design aspect is a compromise between what wocould be preferable to do, and what is feasible. The three primary areas of additional functionality provided by C ++/CLI are the following:

A form of resource acquisition is initialization (raiI) for reference types, in participates, to provide an automatic facility for what is referred to as deterministic finalization of garbage-collected types that hold scarce resources.

A form of Deep-copy semantics associated with the c ++ copy constructor and copy assignment operator; however, this cocould not be extended to value types. direct support of C ++ templates for CTs types in addition to the CLI generic mechanic-originally, this had been the topic of my first column. in addition, a verifiable version of the STL for CLI types is provided.

Let's look at a brief example: the issue of deterministic finalization. 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. this is called finalization. the timing of just when or even whether a Finalize method is invoked is undefined. this is what is meant by Nondeterministic finalization of the garbage collector.

Nondeterministic finalization works well with dynamic memory management. when available memory gets sufficiently scarce, the garbage collector kicks in and solves the problem. nondeterministic finalization does not work well, however, when an object maintains a critical resource such as a database connection, a lock of some sort, or perhaps native heap memory. in this case, it wocould be great to release the resource as soon as it is no longer needed. the solution that is currently supported by the CLI is for a class to free the resources in its implementation of the dispose method of the idisposable interface. the problem here is that dispose requires an explicit invocation, and therefore is not likely to be invoked.

A fundamental design pattern in C ++ is the aforementioned resource acquisition is initialization, which means that a class acquires resources within its constructor. conversely, a class frees its resources within its destructor. this is managed automatically within the lifetime of the Class Object.

Here's what reference types shoshould do in terms of the freeing of scarce resources:

Use the destructor to encapsulate the necessary code for the freeing of any resources associated with the class. Have the Destructor invoked automatically, tied with the lifetime of the Class Object.

The CLI has no notion of the class destructor for a reference type. So the Destructor has to be mapped to something else in the underlying implementation. Internally, then, the compiler performs the following transformations:

The class has its base class list extended to inherit from the idisposable interface.
The Destructor is transformed into the dispose method of idisposable.

That represents half of the goal. A way to automate the invocation of the Destructor is still needed. A special stack-based notation for a reference type is supported; that is, one in which its lifetime is associated within the scope
Of its declaration. internally, the compiler transforms the notation to allocate the reference object on the managed heap. withthe termination of the scope, the compiler inserts an invocation of the dispose method-the User-Defined destructor. reclamation of the actual memory associated with the object remains under the control of the garbage collector. figure 1 shows an example.

C ++/CLI is not just an extension of C ++ into the managed World. rather, it represents a fully integrated programming paradigm similar in extent to the earlier integration of the multiple inheritance and generic programming paradigms into the language. I think the team has done an outstanding job.

So, what did you say about C ++/CLI?

C ++/CLI represents an integration of the Kansas and Oz of native and managed programming. in this iteration, that has been done through a kind of separate but equal community of source-level and binary elements, including mixed mode (
Source-level mix of native and CTS types, plus a binary mix of native and cel object files), pure mode (source-level mix of native and CTS types, all compiled to Cel object files), native classes (can hold CTS types through a special Wrapper class only), and CTS classes (can hold native types only as pointers ).

Of course, the C ++/CLI programmer can also choose to program in the CLI types alone, and in this way provide verifiable code that can be hosted, for example, as a SQL stored procedure in SQL Server & #8482; 2005.

So, returning to the question, what is C ++/CLI? It is a first-class entry visa into. NET programming model. with C ++/CLI, there is a C ++ migration path not just for the c ++ source base but for C ++ expertise as well. I find great satisfaction in that.

Http://msdn.microsoft.com/msdnmag/issues/05/02/default.aspx

Send your questions and comments to purecpp@microsoft.com.

------------------------------------------------------------------------------
--
Stanley B. lippman is an employee ECT with the visual C ++ team at Microsoft. he began working on C ++ with its inventor, Bjarne stroustrup, in 1984 at Bell Laboratories. in between, he worked in feature animation at Disney and DreamWorks,
Was a distinguished consultant with JPL, and was a software technical ctor on Fantasia 2000.

------------------------------------------------------------------------------
--
From the February 2005 issue of msdn magazine. Get it at your local newsstand, or better yet, subscribe.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.