该克隆模式被用来做派生类的副本,而不拆毁到基类.不幸的是,clone必须在每个子类中实现(或者使用带有CRTP的mixin).
C++ 11是否有可能decltype使其不必要?
我不认为下面的代码实际上是复制original,而只是指向它的引用.当我试图使用时new decltype(*original),我收到一个错误:
error: new cannot be applied to a reference type.
是clone仍然走在C++ 11的方式吗?或者是否有一些新方法使用RTTI从基类指针复制派生类对象?
#include <iostream>
struct Base
{
virtual void print()
{
std::cout << "Base" << std::endl;
}
};
struct Derived : public Base
{
int val;
Derived() {val=0;}
Derived(int val_param): val(val_param) {}
virtual void print()
{
std::cout << "Derived " << val << std::endl;
}
};
int main() {
Base * original = new Derived(1);
original->print();
// copies by casting down to Base: you need to know the type of *original
Base * unworking_copy = new Base(*original);
unworking_copy->print();
decltype(*original) on_stack = *original;
on_stack.print();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Nic*_*las 21
decltype是一个静态构造.与所有C++类型构造一样,它不能推断出对象的运行时类型.decltype(*original)只是Base&.
| 归档时间: |
|
| 查看次数: |
2474 次 |
| 最近记录: |