简体   繁体   中英

what does this “new” syntax mean?

Recently I read a piece of code like this:

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);}
};

I have sliced the code to make sure it's not that complicated, the main question is about the construct(T const & t) function.

What does new (GetT()) T(t); exactly means?

btw, which version of GetT() is called?

What does new (GetT()) T(t); exactly means?

It is Placement new , it allows you to place an object at a particular location in memory, which is returned by Get() .

which version of GetT() is called?

The Second one.
Whenever the compiler has option of choosing between a const and a non-const function, it chooses the non-const version.
Specifically, in this case as @James points out in comments:
Non-const version is given preference because the member function which calls it is non-const.

That's called " Placement new ".

It means that you create a new object on a given memory buffer.

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

This allows you to have memory buffers and custom allocators, without having to request and allocate new memory from the operating system.

Read this: What uses are there for "placement new"?

This looks like a placement new call. Here no memory is allocated. new simply returns the address in parenthesis and calls the constructor on the object being virtually constructed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM