官术网_书友最值得收藏!

Unmanaged memory – using new/delete

The new operator is almost the same as a malloc call, except that it invokes a constructor call on the object created immediately after the memory is allocated. Objects allocated with the operator new should be deallocated with the operator delete (and not free()).

Getting ready

In C++, use of malloc() was replaced, as best practice, by use of the operator new. The main difference between the functionality of malloc() and the operator new is that new will call the constructor on object types after memory allocation.

How to do it...

In the following code, we declare a simple Object class, then construct an instance of it using the operator new:

class Object
{
  Object()
  {
    puts( "Object constructed" );
  }
  ~Object()
  {
    puts( "Object destructed" );
  }
};
Object* object= new Object(); // Invokes ctor
delete object; // Invokes dtor
object = 0; // resets object to a null pointer

How it works…

The operator new works by allocating space just as malloc() does. If the type used with the operator new is an object type, the constructor is invoked automatically with the use of the keyword new, whereas the constructor is never invoked with the use of malloc().

There's more…

You should avoid using naked heap allocations with the keyword new (or malloc for that matter). Managed memory is preferred within the engine so that all memory use is tracked and clean. If you allocate a UObject derivative, you definitely need to use NewObject< > or ConstructObject< > (outlined in subsequent recipes).

主站蜘蛛池模板: 长葛市| 迁西县| 喀喇沁旗| 新建县| 醴陵市| 岳普湖县| 遵化市| 霍林郭勒市| 清徐县| 新田县| 绿春县| 安义县| 花垣县| 尚志市| 达拉特旗| 海南省| 永泰县| 莲花县| 大余县| 宁远县| 张家界市| 瑞安市| 阿鲁科尔沁旗| 西乌珠穆沁旗| 门源| 咸丰县| 囊谦县| 新乡市| 泾阳县| 海兴县| 永和县| 长兴县| 健康| 山东| 舞钢市| 嘉兴市| 图们市| 枣庄市| 友谊县| 丰镇市| 高台县|