简体   繁体   English

这个C ++代码是否可移植?

[英]Is this C++ code portable?

struct A {
  int a;
  virtual void print() {}
};

struct B : A {
  int b;
  virtual void print() {}
};

int main(void)
{
  A *a = new B;
  a[0].print(); // g++, vs2010, clang call B::print.
}

All three g++, vs2010, clang call B::print. 所有三个g ++,vs2010,clang调用B :: print。 Almost doubting my C++ 101. I was under the impression that using a dot with an object does not result in a dynamic dispatch. 几乎怀疑我的C ++ 101.我的印象是使用带有对象的点不会导致动态调度。 Only -> with a pointer and dot with a reference will result in a dynamic dispatch. 只有 - >带指针和带引号的点将导致动态调度。

So my question is whether this code is portable? 所以我的问题是这段代码是否可移植?

a[0] is the same as *a , and that expression is a reference to an A , and virtual dispatch happens through references just as it does through pointers. a[0]*a相同,该表达式是对A引用 ,虚拟分派通过引用发生,就像通过指针一样。 a->print() and (*a).print() are entirely identical. a->print()(*a).print()完全相同。

It's portable. 它是便携式的。 a[0] returns a reference, and references use dynamic dispatch as well. a [0]返回引用,引用也使用动态分派。

Yes. 是。 It is equivalent to - 它相当于 -

a->print();

It is portable and the behaviour is well-defined. 它是便携式的,行为定义明确。 operator[] on a pointer just does pointer arithmetic and a dereference. 指针上的operator[]只做指针算术和解除引用。 It is adding 0 * sizeof(A) to the pointer, so in a sense it is a "dangerous" operation as any other value but 0 would fail (on an array of Bs), but as 0 * sizeof(A) is 0, in this case you're ok because it's adding 0. 它向指针添加0 * sizeof(A) ,因此在某种意义上它是一个“危险”操作,因为任何其他值,但0将失败(在B数组上),但是因为0 * sizeof(A)是0 ,在这种情况下你很好,因为它增加了0。

Polymorphism works on references as well as pointers. 多态性适用于引用和指针。

Using a[0] with a pointer is well defined and means the same as *(a + 0) . 使用带指针a[0]定义明确,与*(a + 0) That's how the built in [] operator works. 这就是内置[]运算符的工作原理。

You are partly right about the compiler not needing to use dynamic dispatch when there is no polymorphism. 你是有一定道理关于编译器不需要使用动态调度时,有没有多态性。 This is just a common optimization though, and not required by the language. 这只是一个常见的优化,而不是语言所要求的。

When the code is 当代码是

A a;
a.print();

the compiler can call the correct function directly, because it can tell the object type at compile time. 编译器可以直接调用正确的函数,因为它可以在编译时告诉对象类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM