10 C # errors that C ++ programmers can easily make
We know that the syntax of C # is very similar to that of C ++. The difficulty of the transformation from C ++ to C # lies not in the language itself, but in familiarity.. NET manageable Environment and. NET Framework.
Although the syntax changes of c # And C ++ are very small, they will hardly affect us, but some changes are enough to keep some careless C ++ programmers in mind. In this article, we will discuss the ten mistakes that C ++ programmers are most likely to make.
Trap 1: There is no clear end Method
For most C ++ programmers, the biggest difference between C # And C ++ is fragment collection. This also means that programmers no longer have to worry about memory leaks and ensure that all useless pointers are deleted. But we can no longer precisely control the process of killing useless objects. In fact, there is no clear destructor in C.
If you use non-manageability resources, you must release them explicitly after they are not used. Implicit control over resources is provided by the Finalize method (also known as finalizer). When an object is destroyed, it is called by the fragment collection program to reclaim the resources occupied by the object.
Finalizer should only release non-manageability resources occupied by destroyed objects, and should not involve other objects. If only manageability resources are used in the program, the Finalize method is not required and should not be executed. The Finalize method is only used in the process of non-manageability resources. Because the finalizer occupies a certain amount of resources, you should only execute finalizer in the method that requires it.
Directly calling the Finalize method of an object is absolutely not allowed (unless the Finalize of the basic class is called in the Finalize of the subclass .), The fragment collector automatically calls Finalize.
In terms of syntax, the destructor in C # is very similar to C ++, but they are actually completely different. The destructor in C # is just a shortcut to define the Finalize method. Therefore, the following two pieces of code are different:
~ MyClass ()
{
// Tasks to be completed
}
MyClass. Finalize ()
{
// Tasks to be completed
Base. Finalize ();
}
Error 2: Who is used by Finalize and Dispose?
From the above discussion, we know that explicit calls to finalizer are not allowed, and it can only be called by the fragment collection program. If you want to release a limited number of non-manageability resources (such as file handles) that are no longer in use as soon as possible, you should use the IDisposable interface, which has a Dispose method, it can help you complete this task. Dispose is a method that can release non-manageability resources without waiting for Finalize to be called.