CDZ*_*CDZ 11 c++ new-operator c++11
我尝试使用new
运算符来实例化特定的类,而不是new
关键字后面的类.
我尝试为抽象类提供一种"工厂".
在我看来,这是不可能的,但让我们仔细检查!这段代码编译,但主代码将其视为Test
(而不是TestImpl
类)
class Test
{
public:
virtual int testCall() { return 0; };
static void* operator new(std::size_t);
};
class TestImpl : public Test
{
virtual int testCall() override
{
return i;
}
int i = 15;
};
void* Test::operator new(size_t sz)
{
return ::new TestImpl();
}
void main()
{
Test * t = new Test(); // Call the new operator, correctly
int i = test->testCall(); // i == 0 and not 15
}
Run Code Online (Sandbox Code Playgroud)
son*_*yao 21
请注意,对于每个新表达式,将执行以下两项操作:
operator new
.所以operator new
只分配内存,不构造对象.这意味着,Test * t = new Test();
仍将Test
构建一个由重载分配的内存operator new
; 即使你构建了一个TestImpl
内部operator new
,但它很快就会被覆盖在同一个内存中,operator new
完成之后.