堆栈上的多态对象? [英] Polymorphic objects on the stack?
问题描述
In a previous question I quoted Stroustrup on why a common Object class for all classes is problematic in c++. In that quote there is the statement:
使用通用基类意味着 成本:对象必须是堆分配的 是多态的;
Using a universal base class implies cost: Objects must be heap-allocated to be polymorphic;
我真的没看过两次,因为它的 Bjarnes主页我想很多眼睛已经扫描了该句子并报告了任何错误陈述.
I really didn't look twice at it, and since its on Bjarnes home page I would suppose a lot of eyes have scanned that sentence and reported any misstatements.
但是,有评论者指出,情况可能并非如此,回想起来,我找不到任何正确的理由.一个简短的测试用例产生了"VDerived :: f()"的预期结果.
A commenter however pointed out that this is probably not the case, and in retrospect I can't find any good reason why this should be true. A short test case yields the expected result of "VDerived::f()".
struct VBase
{
virtual void f() { cout<<"VBase::f()"<<endl; }
};
struct VDerived:VBase
{
void f() { cout<<"VDerived::f()"<<endl; }
};
void test(VBase& obj){
obj.f();
}
int main(int argc, char** argv) {
VDerived obj;
test(obj);
return 0;
}
当然,如果要测试的形式参数是test(VBase obj)
,情况将完全不同,但这不是堆栈vs.堆参数,而是复制语义.
Of course if the formal argument to test was test(VBase obj)
the case would be totally different, but that would not be a stack vs. heap argument but rather copy semantics.
Bjarne是不是完全错了,还是我在这里遗漏了一些东西?
Is Bjarne flat out wrong or am I missing something here?
推荐答案
在我看来,多态性.
具有间接的情况下,C ++中的多态性可以工作;即pointer-to-T
或reference-to-T
. T
的存储位置完全不相关.
Polymorphism in C++ works when you have indirection; that is, either a pointer-to-T
or a reference-to-T
. Where T
is stored is completely irrelevant.
Bjarne还犯了一个错误,说堆分配"在技术上是不准确的.
Bjarne also makes the mistake of saying "heap-allocated" which is technically inaccurate.
(注意:这并不意味着通用基类是好"!)
这篇关于堆栈上的多态对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!