gpt4 book ai didi

c++ - 如果它的基类不应该是抽象的,那么处理复制多态对象的虚拟方法的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-01 14:42:31 24 4
gpt4 key购买 nike

我需要复制具有基指针的多态类的对象。我知道我可以为此实现一个虚拟方法。但是如果基类不应该是抽象的呢?如果您忘记在派生中重新实现它,那么在没有纯说明符的情况下保留该方法可能会导致运行时错误。不舒服。处理这个问题的最佳方法是什么?

最佳答案

有充分的理由说明您永远不应该实例化基类。
如果您确实需要创建一个空的最终类,请使用以下内容。

class IBase 
{
virtual void SharedCode()
{
1 + 1;
/// code here
};
virtual void AbstractDecalration() = 0;
};

class Base final: IBase
{
void AbstractDecalration() override;
};

Base b{};
所有 future 派生类都将能够使用 IBase 的 SharedCode,并且您将拥有一个最终的 Base 实例化类。这是为了将来验证您的代码库。
但是我意识到这不是你问的问题,所以这里是一个实现,我使用一个简单的检查类的 vtable 指针来查看我是否有正确的类。
这是一个运行时检查,如果是这种情况,它不适用于跨库使用 dynamic_assert 。
#include <memory>
#include <type_traits>
#include <assert.h>
class Base {
public:
auto clone() const
{
return std::unique_ptr<Base>(this->clone_impl());
}
private:
virtual Base* clone_impl() const
{
Base b{};
int* bVtablePtr = (int*)((int*)&b)[0];
int* thisVtablePtr = (int*)((int*)this)[0];
assert(bVtablePtr == thisVtablePtr);
return new Base(*this);
}
};

class Derived : public Base
{
auto clone() const
{
return std::unique_ptr<Derived>(this->clone_impl());
}
virtual Derived* clone_impl() const
{
return new Derived();
}
};
class Falty : public Base{};

int main(){
std::unique_ptr<Derived> good(new Derived());
std::unique_ptr<Falty> falty(new Falty());
good->clone(); // oke
falty->clone(); // this function asserts at runtime

}
请注意私有(private) clone_impl 和公共(public) unique_ptr 重新调整克隆方法。
对于防止代码中的内存泄漏非常有用

关于c++ - 如果它的基类不应该是抽象的,那么处理复制多态对象的虚拟方法的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62709159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com