加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 派生类中的sizeof(* this)和decltype(* this)

发布时间:2020-12-16 10:14:44 所属栏目:百科 来源:网络整理
导读:假设有类: struct A { int a; virtual size_t GetMemoryUsage() const { return sizeof(*this); }};struct B : public A { int b;}; 并且可能存在更深层次的继承. 我想要的是有一个方法,它将返回一个对象在内存中占用的字节数,在这种情况下是GetMemoryUsage
假设有类:

struct A {
  int a;

  virtual size_t GetMemoryUsage() const {
    return sizeof(*this);
  }
};

struct B : public A {
  int b;
};

并且可能存在更深层次的继承.

我想要的是有一个方法,它将返回一个对象在内存中占用的字节数,在这种情况下是GetMemoryUsage().通常可以通过使用sizeof(* this)来实现.问题是(至少AFAIU),我必须覆盖每个派生类中的方法,并实际复制粘贴其正文.我不喜欢重复的代码:)

我对么?如何通过仅从基类的方法调用sizeof(* this)和decltype(* this)来返回我想要的子类?有更优雅的解决方案吗?

解决方法

您不必手动为每个派生类实现GetMemoryUsage,只需将其保留为纯虚拟.例如.:

struct A
{
    virtual ~A() = default;
    virtual size_t GetMemoryUsage() const noexcept = 0;
};

struct B : A
{
    int b;
};

但是,在创建对象时,必须实现该功能.您可以使用工厂函数来执行此操作,该函数使用该纯虚拟的通用实现“修饰”该类:

// Can alternatively be defined inside function template create.
template<class T>
struct GetMemoryUsageImpl : T
{
    using T::T;
    size_t GetMemoryUsage() const noexcept final {
        return sizeof(T);
    }
};

template<class T,class... Args>
std::unique_ptr<T> create(Args&&... args) {
    return std::unique_ptr<T>(new GetMemoryUsageImpl<T>(std::forward<Args>(args)...));
}

用法:

void f(A& a) {
    auto object_size = a.GetMemoryUsage();
}

int main() {
    auto b = create<B>();
    f(*b);
}

You can also implement a hierarchy of interfaces incrementally easily using this idiom.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读