Experience the modern language features of Visual C + + 2005 (1)

Source: Internet
Author: User
Tags garbage collection insert new set readline requires versions visual studio intel pentium

The advent of the Visual Studio.NET 2003 C + + compiler in the year was coveted by countless C + + language enthusiasts; it is 98% consistent with the ISO C + + standard-which is closer than any previous release, and integrated language support features such as local template-specific , also includes enhanced buffer security checks and improved compiler diagnostics. Using C # and Visual Basic.NET developers to generate robust Windows Forms applications with simple drag-and-drop operations, developers of C + + are joining in, and the compiler also has access to Intel Pentium 4 and AMD The Athlon processor is optimized for processing.

If Visual C + +. NET 2003 excites you, its latest version of Visual C + + 2005 is enough to make you crazy. For. NET Development, Visual C + + 2005 now has a new set of syntax that is more "elegant" and more powerful; it has new optimization techniques to increase the speed of the program by 30%, while the new compilation mode guarantees that Microsoft. NET The framework generates verifiable code that complies fully with the CLI (Common Language infrastructure), and the new interop mode, which provides seamless integration of local and managed code. The new compiler also includes an enhanced version of the buffer security check option relative to the first two versions, and a new security-focused version of the library that is commonly used for C + + programs. Visual C + + 2005 provides support for OpenMP standards for intel-based and AMD64 64-bit platforms, fixes problems with mixed DLL loading, and provides automatic runtime elimination for double P/invoke performance problems. There is much more to similar enhancements and improvements, as one C + + architect says, "C + + is finally standing where it should be."

C++/cli New Syntax

Perhaps many of us have found that the use of Managed Extensions syntax in the first two versions of C + + is cumbersome and problematic, and it may be felt that Visual C + + is not. The preferred language for net development. The Microsoft Visual C + + development team has redesigned Visual C + + 2005 on the basis of extensive listening, and the clumsy C + + Managed Extensions syntax in Visual Studio. NET 2002 is gone. The revised language definition brings with it a completely attractive new syntax.

in language design, the Microsoft Visual C + + development team has set some major goals. First (for those who think programming is art, perhaps most important, they want to make sure that developers feel natural when they write C + + code, and to do this, they have a purely syntactic and elegant extension of the ISO C + + standard, in order to click Deployment, form design support, and SQL Server 2005 's managed code supports these places, and it's easier to write verifiable code in C + +. They want to design a language that is more than C + + and bring it all to C + +. NET ability, but also to bring to. NET all the C + + capabilities. Now it seems that they are very successful. The

New extension specification is called "C++/CLI" and is being standardized. The most noticeable aspect of reading code is that the usual double underscore keyword, which defines garbage collection classes, attributes, and so on in Managed Extensions, is now history. Although some similar keywords are retained, they do not affect the readability of the code because they are not used frequently. These double underscore keywords are now replaced by two new "keywords": "Context sensitive" and "spacer." The context sensitive keyword is a keyword only in a specific context, and the "spacer" keyword is only a keyword when it is combined with other keywords. For example: The keyword __property in Managed Extensions has been replaced by the keyword property (not just that, the entire syntax for defining and accessing properties has been refined, its declaration looks very similar to C #, see Insert 1), and in your code you can also use the attribute as the variable name , "property" is treated as a keyword only when it is declared in a type.

Code 1: syntax comparison

Managed Extensions syntax

Public __gc __sealed class Student
{
Private
Double M_grade;
string* M_name;
Public
__property double Get_grade () {return m_grade;}
__property void Set_grade (double newgrade) {m_grade = Newgrade;}

__property string* get_name () {return m_name;}
__property void Set_name (string* newName) {m_name = NewName;}
}

C++/CLI syntax

Public ref class Student sealed
{
Private
Double M_grade;
Public
Standard property syntax
Property Double Grade
{
Double get () {return m_grade;}
void set (double newgrade) {m_grade = Newgrade;}
}
Other properties
Property string^ Name;
}

The type in the new syntax is declared as "what class", and the preceding adjective describes what class you will create, as follows:

Class N {/*...*/}; Local type
Ref class R {/*...*/}; CLR reference type
Value class V {/*...*/}; CLR value type
Interface class I {/*...*/}; CLR Interface interface type
Enum class E {/*...*/}; CLR enum type

In the previous language version, the method of declaring a type shows how it survives and works. Only local classes, structs, and managed value types can be created on the stack, and managed reference classes are always in the managed heap. In Visual C + + 2005, all types, whether local or managed, can be created on the stack by using a stack based deterministic cleanup semantics.

For an object instance that generates type T in the local heap, you can use "new T", which returns a pointer to the location of the object in the local heap (__nogc in Visual Studio. NET 2002 and Visual Studio. NET 2003). Instead of generating an object instance of type T in the managed heap, Visual C + + 2005 introduces the keyword gcnew, and "Gcnew T" returns the handle of the entire object in the managed heap. The handle is treated as a new structure in Visual C + + 2005, somewhat similar to a __gc pointer to Managed Extensions; Now to generate an instance of type T on the stack, the standard "T-T" declaration is sufficient.

Here's how to define an instance where a managed reference class is built in a managed heap, a local type is built on a stack or a local heap, and when a managed reference class is declared on the stack, the compiler actually instantiates it in the managed heap, as shown in Figure 1:


Figure 1:
The managed reference type shown in Figure 1 also poses some problems: what happens when an instance object in a stack is out of range? How did it get cleaned up? Many C # developers complain that the C # language lacks deterministic cleanup, and the C # language can easily erase IDisposable objects by using keywords, but this requires extra code and is a bit obscure compared to the familiar destructor patterns of C + + developers. In C #, security cleanup is turned off by default and requires explicit encoding to open it. For example, take a look at the C # snippet inserted in 3, the object StreamReader declared in the managed heap, when the method in the class has finished executing, there is no longer any reference to the instance of StreamReader, but the object still does not end until the garbage collector reclaims it; The file is not closed and the program still has a handle to the open file. To join deterministic cleanup, you must implement the IDisposable interface through classes that use unmanaged resources.

The second example in Code 2, demonstrates the new code in C # where the code still has good readability, but once you introduce more objects that need to be cleaned up, the code becomes more and more difficult to read, and again, when the garbage collector finally runs, any objects that you forget to erase, Will add to the burden of the final terminator thread (finalizer) and, at the same time, potentially lock up High-value resources. Also, when using visual Basic. NET to achieve the same functionality, this form of encoding becomes even uglier (although Visual Basic 2005 also has a using declaration similar to C #).

Code 2: Deterministic cleanup code

Implementation code

C # (no deterministic cleanup)

String Readfirstlinefromfile (String path)
{
StreamReader reader = new StreamReader (path);
Return reader. ReadLine ();
})

C # (with deterministic cleanup)

String Readfirstlinefromfile (String path)
{
using (StreamReader reader = new StreamReader (path))
{
Return reader. ReadLine ();
}
}

Visual Basic. NET (Deterministic cleanup)

Function readfirstlinefromfile (_byval path As String) as String
Dim Reader as StreamReader
Try
Reader = New StreamReader (path)
Readfirstlinefromfile = reader. ReadLine ()
Finally
If not reader are nothing Then _
CType (reader, IDisposable). Dispose ()
End Try
End Function

C + + (with deterministic cleanup)

string^ readfirstlinefromfile (string^ path)
{
StreamReader Reader (path);
Return reader. ReadLine ();
}

Visual C + + 2005 now provides a destructor or terminator (finalizer) for any type of managed and local object. When the type is managed, the compiler maps a destructor to IDisposable::D Ispose method, which means that you can use C + + to write the same method--such as the fourth code in insert 3, and that the reader's destructor or purge method is invoked automatically, as if in C #. Using "Same as. Thus, when the type created on the stack is out of scope, its destructor is invoked.
 
The biggest problem with Managed Extensions is the problem of pointers, which, while difficult to understand, are "versatile" to cope with multiple tasks and situations. In Visual C + + 2005, the pointer is still an old-fashioned C + + pointer that points to an object and performs some algorithms. Refers to a pointer to an object whose lifetime must be managed by the developer, and when dealing with pointers, the runtime library is not responsible for cleaning it up.

Now, to see how the designers of Visual C + + 2005 are doing this, the new operator in Visual Studio. NET 2003 and Visual Studio. NET 2005 usually returns a pointer, and the gcnew operator returns a "handle". A structure represented by the caret ^ syntax, which points to the object of the managed heap. Therefore, they cannot point to the interior type, and in usage, the compiler also makes a number of limitations so that developers can use them correctly and safely. The handle cannot perform pointer arithmetic, nor can it be converted to a null pointer or any other integer type, but the asterisk (*) and arrow (->) operator can still be used.

This is not to say that you can't get a pointer to a garbage collection heap, in Visual C + + 2005, pin_ptr can be used to get a fixed pointer to an object in the managed heap, as long as the pointer exists and the object is pinned to the managed heap to prevent the garbage collector from clearing it; Visual c+ + 2005 also introduces the "reference tracking" operator, expressed as a percent sign. When the & reference operator was introduced in C + +, most developers interpreted it as a pointer to an object, and the compiler automatically dereference it. In many ways,% is ^, like & to *.

In the managed world, a local reference to a managed object is as dangerous as a local pointer to a managed object, and the rationale for pointers and references is that the referenced object cannot move around. Reference tracking is very similar to a local reference, and can continue to be tracked in addition to the objects it references in the managed heap and after being moved by the garbage collector. The percent percent operator is used to take the address of the managed object, just as the & operator does for local objects, and the percent operator returns a handle to a managed reference type object.

In general, C + + developers know that the ISO standard controls the direction of language, and it is for this reason that the new syntax is proposed as a standard called "c++/cli", in order to increase the probability of being adopted by third parties and to ensure the steady development of the language. In October 2003, ECMA (European Computer Manufacturers Association) voted to establish a task force--TG5, which is specifically responsible for the analysis and adoption of this standard, working in the same way as WG21 is an ISO C + + management unit, and in fact, key team members in WG21 are also serving TG5. The plan is to standardize the c++/cli at the end of 2004.

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.