这是什么"新"语法意思?

时间:2012-10-04 08:03:09

标签: c++ syntax new-operator

最近我读了一段这样的代码:

template <unsigned long size>
class FooBase
{
  bool m_bValid;
  char m_data[size];
};

template <class T>
class Foo : public FooBase<sizeof(T)>
{
  // it's constructor
  Foo(){};
  Foo(T const & t) {construct(t); m_bValid = (true);}

  T const * const GetT() const { return reinterpret_cast<T const * const>(m_data); }
  T * const GetT() { return reinterpret_cast<T * const>(m_data);}

  // could anyone help me understand this line??
  void construct(T const & t) {new (GetT()) T(t);}
};

我已经对代码进行了切片以确保它不那么复杂,主要问题是关于construct(T const & t)函数。

new (GetT()) T(t);究竟意味着什么?

顺便说一下,调用GetT()的哪个版本?

3 个答案:

答案 0 :(得分:5)

  

new (GetT()) T(t);究竟意味着什么?

Placement new ,它允许您将对象放在内存中的特定位置,该位置由Get()返回。

  

调用GetT()的哪个版本?

第二个。
只要编译器有选择const和非const函数的选项,它就会选择非const版本 具体来说,在这种情况下,正如@James在评论中指出的那样: 非const版本优先,因为调用它的成员函数是非const。

答案 1 :(得分:2)

这称为“新展示位置”。

这意味着您在给定的内存缓冲区上创建一个新对象。

new (buffer) T(); //means it will instantiate an object T in the buffer.

这允许您拥有内存缓冲区和自定义分配器,而无需从操作系统请求和分配新内存。

阅读本文: What uses are there for "placement new"?

答案 2 :(得分:1)

这看起来像是一个新的来电。这里没有分配内存。 new只是在括号中返回地址,并在虚拟构造的对象上调用构造函数。