C + +: the most powerful. NET language memory and resources

Source: Internet
Author: User
Tags garbage collection resource
It is important to distinguish between memory management and resource management when the garbage collection mechanism is included in the operating environment. Typically, the garbage collector is interested only in allocating and releasing memory that contains objects, and it does not care if your object has other resources, such as a database connection or a handle to a core object.

Memory management

Local C + + provides programmers with direct control over memory management, and assigning an object on the stack means that the object is allocated memory only when a particular function is entered, and memory is freed when the function returns or the stack expands. You can use operator new to dynamically allocate memory to an object, where memory is allocated in the CRT heap, and the programmer needs to use the operator delete on the object pointer to release it. This precise control of memory is one of the reasons why C + + can be used to write extremely efficient programs, but if the programmer is not careful, this is also the reason for the memory leak. On the other hand, you don't have to turn to the garbage collector to avoid a memory leak--it's actually a method that the CLR takes, and it's a very effective way, and of course, there are other benefits to the garbage collection heap, such as improved allocation efficiency and the advantages associated with referencing locations. All of this can be done in C + + through library support, in addition to this, the CLR provides a single memory management programming model that is common to all programming languages, thinking about all the work you need to do to interact with COM automation objects in C + + and schedule data types, The important point is that the garbage collector, which spans a number of programming languages, has a huge effect.

For efficiency, the CLR also retains the notion of a stack so that value types can be allocated on them, but the CLR also provides an newobj intermediate language directive to allocate an object in the managed heap, but this instruction is provided only in C # for referencing objects using the operator new. In the CLR, there is no function that corresponds to the delete operator in C + +, and when an application no longer references an object, the allocated memory is eventually reclaimed by the garbage collector.

When operator new is applied to a reference type, managed C + + also generates the newobj instruction, which is, of course, illegal to use the delete operator. This is a real paradox, but it also proves why it is not a good idea to use the C + + pointer concept to represent a reference type.

In memory management, in addition to the content discussed above in the Object Construction section, C++/CLI does not provide anything new; resource management is C++/CLI's forte.

Resource Management

The CLR can outperform local C + + only in terms of resource management. Bjarne Stroustrup's "Resource acquisition is initialization" Technology view, basically defines the resource type pattern, namely class's constructor obtains the resource, the destructor frees the resource. These types are used as local objects on the stack, or as members of complex types, whose destructors automatically release previously allocated resources. As Stroustrup said, "C + + is the best language for the garbage collection mechanism, mainly because it generates very little rubbish." "

It may be surprising that the CLR does not provide any explicit run-time support for resource management, and the CLR does not support C + + concepts like destructors, but rather in the. NET framework, to elevate the resource management pattern to the central location of a IDisposable core interface type. This idea stems from the type of wrapper resource that should implement a single Dispose method of this interface so that the caller can call the method when the resource is no longer in use. Needless to say, C + + programmers think this is a throwback to the times, because they are accustomed to writing code that is the correct default state cleanup.

Because a method must be invoked to free resources, the problem is that it is now much harder to write "no exceptions" code. Because an exception can occur at any time, you cannot simply place a call to the Dispose method of an object after a piece of code, and in doing so, you must risk a resource leak. The solution to this problem in C # is to use try-finally blocks and using statements to provide a more reliable way to invoke the Dispose method when facing an exception. Sometimes constructors use this method, but the general situation is that you have to remember to write them manually, and if you forget, the generated code may have a silent error. The need for try-finally blocks and using statements for languages lacking real destructors remains to be argued.

using (SqlConnection connection = new SqlConnection ("Database=master; Integrated SECURITY=SSPI "))
{
SqlCommand Command = connection. CreateCommand ();
Command.commandtext = "Sp_databases";
Command.commandtype = CommandType.StoredProcedure;

Connection. Open ();

using (SqlDataReader reader = command. ExecuteReader ())
{
while (reader. Read ())
{
Console.WriteLine (reader. GetString (0));
}
}
}

For managed C + +, the plot is also very similar and requires a try-finally statement, but it is an extension of Microsoft to C + +. Although it is easy to write a simple using template class to wrap the GCHandle and invoke the Dispose method of the managed object in the destructor of the template class, there is still no equivalent for C # using statements in Managed C + +.

Using<sqlconnection> Connection (The new SqlConnection (S) Database=master; Integrated SECURITY=SSPI "));

sqlcommand* command = Connection->createcommand ();
Command->set_commandtext (S "sp_databases");
Command->set_commandtype (commandtype::storedprocedure);

Connection->open ();

Using<sqldatareader> Reader (Command->executereader ());

while (Reader->read ())
{
Console::WriteLine (reader->getstring (0));
}

Think about the traditional support for resource management in C + +, it is also applicable to C++/CLI, but c++/cli language design as if for C + + resource management brought a gust of breeze. First, when writing a class that manages resources, one of the problems with most CLR platform languages is how to implement the Dispose pattern correctly, which is not as easy to implement as a classic destructor in local C + +. When you write a Dispose method, you need to determine that the Dispose method of the base class is invoked-if so, and if you choose to implement the Finalize method of the class by calling the Dispose method, you must also be concerned about concurrent access. Because the Finalize method is likely to be invoked by different threads. In addition, as opposed to normal program code, if the Dispose method is actually called by the Finalize method, the managed resource needs to be carefully disposed.

C++/CLI is not too far from the above, but it provides a lot of help, and before we look at what it offers, let's take a quick look at how close today's C # and managed C + + are. The following example assumes that base is derived from IDisposable.

Class Derived:base
{
public override void Dispose ()
{
Try
{
Releasing managed and unmanaged resources
}
Finally
{
Base. Dispose ();
}
}

~derived ()//implementation or overload Object.Finalize method
{
Release only unmanaged Resources
}
}
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.