开发者

Memory allocation operators and expressions

In C++, is开发者_运维技巧 'new' an operator or an expression or some kind of keyword? a similar question that comes in mind is, should i call '=' an operator or expression?


C++ separates the notion of memory allocation and object lifetime. This is a new feature compared to C, since in C an object was equivalent to its memory representation (which is called "POD" in C++).

An object begins its life when a constructor has completed, and its life ends when the destructor has completed. For an object of dynamic storage duration, the life cycle thus consists of four key milestones:

  1. Memory allocation.
  2. Object construction.
  3. Object destruction.
  4. Memory deallocation.

The standard way in C++ to allocate memory dynamically is with the global ::operator new(), and deallocation with ::operator delete(). However, to construct an object there is only one method: A new expression:

T * p = new T;

This most common form of the new expression does allocation and construction in one step. It is equivalent to the broken down version:

void * addr = ::operator new(sizeof(T));
T * p = new (addr) T;  // placement-new

Similarly, the delete expression delete p; first calls the destructor and then releases memory. It is equivalent to this:

p->~T();
::operator delete(addr);

Thus, the default new and delete expressions perform memory allocation and object construction in one wash. All other forms of the new expression, collectively called "placement new", call a corresponding placement-new operator to allocate memory before constructing the object. However, there is no matching "placement delete expression", and all dynamic objects created with placement-new have to be destroyed manually with p->~T();.

In summary, it is very important to distinguish the new expression from the operator new. This is really at the heart of memory management in C++.


It's all of those.

2.13 Table 4 explicitly lists new as a keyword.

5.3.4 Introduces the new-expression. This is an expression such as new int(5) which uses the new keyword, a type and an initial value.

5.3.4/8 Then states that operator new is called to allocate memory for the object created by the new-expression

= works quite the same. Each class has an operator= (unless explicitly deleted), which is used in assignment expressions. We usually call a=5; just an assignment, even when it's technically "an expression statement containing an assignment expression."


new is operator. You can overload it and write your own version of it. Also I think that = is operator. Expression is more complex thing which consist of operators, variables, function calls etc. And please try to get C++ language standard. It must describe all things you mentioned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜