she*_*ngy 2 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);}
};
Run Code Online (Sandbox Code Playgroud)
我已经对代码进行了切片以确保它并不复杂,主要问题是关于construct(T const & t)
函数.
什么new (GetT()) T(t);
究竟意味着什么?
顺便说一句,哪个版本GetT()
被称为?
什么
new (GetT()) T(t);
究竟意味着什么?
它是Placement new,它允许您将对象放在内存中的特定位置,该位置由返回Get()
.
GetT()
叫哪个版本?
第二个.
只要编译器具有在const和非const函数之间进行选择的选项,它就会选择非const版本.
具体来说,在这种情况下,正如@James在注释中指出的那样:
非const版本被赋予优先级,因为调用它的成员函数是非const的.