你想要做什麼是行不通的。這是一種替代方法,在這裏我基本上建立自己的基礎設施類型:
#include <functional>
struct Base {
protected:
virtual ~Base() {}
Base() {}
public:
virtual size_t SizeRequired() const = 0;
virtual std::function<Base*(unsigned char* buffer)> Constructor() const = 0;
// note that standard delete is not standards compliant, because the memory
// was allocated as an array of unsigned char's
void SelfDelete() {
SelfDestroy();
delete[] reinterpret_cast<unsigned char*>(this);
}
// you can also create these things in other storage locations:
void SelfDestroy() {
this->~Base();
}
static void Delete(Base* b) {
if (b)
b->SelfDelete();
}
std::function<Base*()> AllocateAndConstructor() const {
size_t required = this->SizeRequired();
auto constructor = this->Constructor();
return [required, constructor]()->Base* {
unsigned char* buff = new unsigned char[ required ];
return constructor(buff);
};
}
};
// CRTP class (google CRTP if you are confused what I'm doing)
template<typename Child>
struct BaseHelper: Base {
static Base* Construct(unsigned char* buffer) {
return new(buffer) Child();
}
static Base* Create() {
unsigned char* buff = new unsigned char[ sizeof(Child) ];
return Construct(buff);
};
virtual size_t SizeRequired() const {
return sizeof(Child);
}
virtual std::function<Base*(unsigned char* buffer)> Constructor() const {
return &BaseHelper<Child>::Construct;
}
};
// use:
struct Bar: BaseHelper<Bar> {
};
struct Foo: BaseHelper<Foo> {
};
Base* test(Base* b) {
auto creator = b->AllocateAndConstructor();
return creator();
}
#include <iostream>
int main() {
Base* b = Bar::Create(); // creates a Bar
Base* b2 = test(b); // creates another Bar, because b is a Bar
Base* f = Foo::Create(); // creates a Foo
Base* f2 = test(f); // creates another Foo, because f is a Foo
std::cout << (typeid(*b) == typeid(*b2)) << " == 1\n";
std::cout << (typeid(*f) == typeid(*f2)) << " == 1\n";
std::cout << (typeid(*f) == typeid(*b)) << " == 0\n";
Base::Delete(b);
Base::Delete(b2);
Base::Delete(f);
Base::Delete(f2);
Base::Delete(0); // does not crash
};
這意味着一個基本的每次運行時實例與它進行訪問,構建基地的實例的能力。重寫新的和刪除可能比使用上面的替換創建和刪除操作更好,並且可以讓某人在堆棧上創建這些東西。
我建議對這種技術的,除非你知道自己在做什麼。
有,但是,相對常見的模式,如克隆和工廠,是接近上述但有點不太傻。
我點擊提交的錯誤...對不起,你發佈你的評論速度非常快... – benjarobin