在派生类中sizeof(* this)和decltype(* this) [英] sizeof(*this) and decltype(*this) in derived classes

查看:339
本文介绍了在派生类中sizeof(* this)和decltype(* this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有类:

struct A {
  int a;

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

struct B : public A {
  int b;
};

可能有更深的继承。

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

What I want is to have a method which will return the number of bytes an object occupies in memory, GetMemoryUsage() in this case. Usually it can be achieved by using sizeof(*this). The problem is (at least AFAIU) that I have to override the method in each derived class and actually copy-paste its body. I don't like duplicated code :)

我是否正确?如何通过调用 sizeof(* this) decltype(* this)在子类中返回我想要的内容它们只来自基类的方法?有更优雅的解决方案吗?

Am I correct? How can I make sizeof(*this) and decltype(*this) return what I want in subclasses, by calling them only from base class's methods? Is there a more elegant solution?

推荐答案

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

You do not have to implement GetMemoryUsage for each of your derived classes manually, just leave it as pure virtual. E.g.:

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

struct B : A
{
    int b;
};

但是,在创建对象时,必须实现该功能。你可以使用一个工厂函数来做到这一点,该函数使用该纯虚拟的通用实现修饰类:

When creating objects, however, that function must be implemented. You can do that using a factory function that "decorates" the class with a generic implementation of that pure virtual:

// 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);
}

您还可以使用此习语以增量方式逐步实现接口层次结构。

这篇关于在派生类中sizeof(* this)和decltype(* this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆