调用空类的构造函数实际上是否会使用任何内存? [英] Does calling the constructor of an empty class actually use any memory?

查看:144
本文介绍了调用空类的构造函数实际上是否会使用任何内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类似的课程

Suppose I have a class like

class Empty{
    Empty(int a){ cout << a; }
}

然后我使用

int main(){
    Empty(2);
    return 0;
}

这会导致在堆栈上分配任何内存以创建空"对象吗?显然,需要将参数推入堆栈,但是我不想招致任何额外的开销.基本上,我将构造函数用作静态成员.

Will this cause any memory to be allocated on the stack for the creation of an "Empty" object? Obviously, the arguments need to be pushed onto the stack, but I don't want to incur any extra overhead. Basically I am using the constructor as a static member.

我要这样做的原因是因为模板.实际代码看起来像

The reason I want to do this is because of templates. The actual code looks like

template <int which>
class FuncName{
    template <class T>
    FuncName(const T &value){
        if(which == 1){
            // specific behavior
        }else if(which == 2){
            // other specific behavior
        }
    }
};

这让我写了类似的东西

int main(){
    int a = 1;
    FuncName<1>(a);
}

,这样我就可以专门化一个模板参数,而不必指定T的类型.另外,我希望编译器可以优化构造函数内部的其他分支.如果有人知道这是真的还是如何检查,将不胜感激.我还认为,将模板放入情况中不会从上面改变空类"问题,对吗?

so that I get to specialize one template parameter, while not having to specify the type of T. Also, I am hoping the compiler will optimize the other branches away inside the constructor. If anyone knows if this is true or how to check, that would be greatly appreciated. I assumed also that throwing templates into the situation does not change the "empty class" problem from above, is that right?

推荐答案

引用Stroustrup:

Quoting Stroustrup:

为什么一个空类的大小不为零? 确保两个不同对象的地址不同.由于相同的原因,"new"总是返回指向不同对象的指针.考虑:

Why is the size of an empty class not zero? To ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects. Consider:

class Empty { };

void f()
{
    Empty a, b;
    if (&a == &b) cout << "impossible: report error to compiler supplier";

    Empty* p1 = new Empty;
    Empty* p2 = new Empty;
    if (p1 == p2) cout << "impossible: report error to compiler supplier";
}   

有一条有趣的规则,说空的基类不需要用单独的字节表示:

There is an interesting rule that says that an empty base class need not be represented by a separate byte:

struct X : Empty {
    int a;
    // ...
};

void f(X* p)
{
    void* p1 = p;
    void* p2 = &p->a;
    if (p1 == p2) cout << "nice: good optimizer";
}

此优化是安全的,并且可能是最有用的.它允许程序员使用空类来表示非常简单的概念,而不会增加开销.当前一些编译器提供了这种空基类优化".

This optimization is safe and can be most useful. It allows a programmer to use empty classes to represent very simple concepts without overhead. Some current compilers provide this "empty base class optimization".

这篇关于调用空类的构造函数实际上是否会使用任何内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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