我有一个问题,即后续工作如何覆盖operator new。我有一个基类Task与一个重写的运算符new:
foreach (PropertyEditor editor in ((DetailView)View).GetItems<PropertyEditor>())
{
var control = editor.Control as IntegerEdit;
if (control != null)
{
if (editor.Id == "Id" || editor.Caption == "Id")
{
control.Enabled = false;
}
}
}
此运算符用于分配新任务并从当前工作任务设置私有字段。 allocate_continuation_proxy&安培;是指当前的任务。
void* operator new(size_t bytes, const allocate_continuation_proxy& p);
我尝试执行此代码:
class allocate_continuation_proxy;
class Task {
public:
virtual ~Task() {
}
void* operator new(size_t size) {
return ::operator new(size);
}
void* operator new(size_t bytes, const allocate_continuation_proxy& p);
allocate_continuation_proxy& allocate_continuation() {
return *reinterpret_cast<allocate_continuation_proxy*>(this);
}
virtual Task* Compute() = 0;
inline Task* Continuation() {
return _continuation;
}
inline void Continuation(Task& task) {
_continuation = &task;
}
inline void ContinuationAsNull() {
_continuation = nullptr;
}
protected:
Task() {
}
private:
Task* _continuation;
Ct* _cancellationToken;
};
class allocate_continuation_proxy {
public:
Task& allocate(size_t size) const;
};
inline Task& allocate_continuation_proxy::allocate(size_t size) const {
Task& t = *((Task*)this);
Task* c = (Task*) ::operator new(size);
c->CancellationToken(nullptr);
c->Continuation(*t.Continuation());
c->PendingCount(0);
t.ContinuationAsNull();
return *c;
}
inline void* Task::operator new(size_t bytes, const allocate_continuation_proxy& p) {
return &p.allocate(bytes);
}
我的问题是这一行:
class C0 : public Task {
public:
//C0() {
//}
Task* Compute() override {
std::cout « "C0 is computing..." « std::endl;
Task* c = Continuation()
c->Compute(); //if constuctor C0() is not been to define, this line throw exception because "c" = nullptr, but "c" has to point on instance of C2
return nullptr;
}
};
class C2 : public Task {
public:
Task* Compute() override {
std::cout « "C2 is computing..." « std::endl;
return nullptr;
}
};
class C1 : public Parallel::Task {
public:
Task* Compute() override {
std::cout « "C1 is computing..." « std::endl;
C0& c = *new (allocate_continuation()) C0();
c.Compute();
return nullptr;
}
};
int main() {
C1& c1 = *new C1();
c1.Continuation(*new C2());
c1.Compute();
return 0;
}
如果未定义constuctor C0(),则引用“c”没有已设置为allocate_continuation_proxy :: allocate(size_t size)的_continuation。但是如果我将构造函数定义到类C0中,请参考“c”将有_continuation。我不明白为什么?如果不将构造函数定义到派生类中,我怎样才能获得正确的行为?