64,654
社区成员
发帖
与我相关
我的任务
分享
#include <memory>
...
std::allocator<T>().construct(p, T());
如果这个可以编译,那么在construct上点右键,选择“转到定义”,看看stl中如何实现。
#include <iostream>
#include <new>
class custom_new
{
public:
custom_new( int value = 1234 )
: my_value( value )
{
}
operator int() const
{
return my_value;
}
void * operator new ( size_t size )
{
return new char[size];
}
void operator delete( void * p )
{
delete []static_cast<char*>(p);
}
private:
int my_value;
};
template< typename T >
class global_new
{
public:
global_new()
{
my_data = static_cast<T*>(::operator new( sizeof(T)));
::new (my_data)T;
}
~global_new()
{
my_data->~T();
::operator delete(my_data);
}
T * get_data()
{
return my_data;
}
private:
T * my_data;
};
int main(int argc, char **argv)
{
global_new<custom_new> obj;
std::cout << * obj.get_data();
std::cin.get();
return 0;
}
template<typename T>
class CMyWrapper()
{
public:
void TestIt()
{
T* p = ::operator new (sizeof(T)); // 之所以使用::operator new,使因为在T中已经重载了new操作符
new p(T);
//do something
//同时释放时也不能再delete p,而要用全局的delete,
//要与分配代码匹配:
p->~T();
::operator delete(p);
}
}