C++ - 通过引用派生调用的基本实现?

标签 c++ polymorphism mingw temporary-objects

考虑以下代码(最小版本):

#include <iostream>

struct Base
{
    virtual ~Base() {}

    virtual void test() const { std::cout << "base"; }
};

struct Derived : public Base
{
    void test() const { std::cout << "derived"; }
};

struct Composite
{
    const Derived &ref;

    Composite(const Derived &ref) : ref(ref) {}

    void testRef() const { ref.test(); }
};

int main()
{
    Composite c((Derived()));
    c.testRef();
}

当使用最新的 MinGW g++ 时,这实际上会产生“基础”!那是编译器错误还是我遗漏了什么?有人可以在 VS 中对此进行测试吗?

我认为自己是一名经验丰富的 C++ 程序员,经常使用多态性、基于堆栈的引用、临时对象(C++ 标准 12.2)等。因此我知道应该应用生命周期延长。

此行为仅在 Base 中定义析构函数(虚拟或非虚拟)并使用临时对象时发生,即。 e.以下用法会产生“派生”:

int main()
{
    Derived d;
    Composite c(d);
    c.testRef();
}

最佳答案

Composite c((Derived()));

这一行创建了一个Derived类型的临时对象,将其传递给c的构造函数,然后销毁该临时对象。在那之后,所有赌注都取消了。

关于C++ - 通过引用派生调用的基本实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16328608/

相关文章:

c++ - 如何返回函数的参数数量?

c++ - 为什么模板别名专门化取决于引用它的上下文?

c++ - 如何在 Visual Studio 2005 中创建 ATL/C++ ActiveX DLL

使用继承时的Java动态绑定(bind)

python - 如何使用已编译的 Fortran 扩展模块构建 Python 轮而不需要用户系统上的特定 MinGW 版本?

c# - 获取错误 CS0031 : Constant value `65535' cannot be converted to a `short'

scala - 如何检查值可见类型

ruby-on-rails - RoR : has_one "or the other"?(或者,没有继承的多态性。)

c++ - MinGW 是如何实现 C++ 库支持的?

gcc+mingw 下的 C++ 段错误,但不是 gcc+linux