Instantiation of an abstract class via initializer list [duplicate]

与世无争的帅哥 提交于 2019-12-20 11:13:33

问题


I would like to understand why the compiler allows the following code to compile

#include <iostream>

struct A
{
    A()
    {
        std::cout << "A::A\n";
    }

    virtual void f() const = 0;
};

void g(const A& a)
{
    a.f();
}

int main()
{
    g({});
}

It even outputs A::A when run.

If I replace g({}) with g(A()) it obviously doesn't compile. It complains that A is abstract and cannot be instantiated. Both Clang and GCC compile this fine without any warnings. When run both versions print pure virtual method called and terminate.


回答1:


This looks like a known g++ bug number 70939:

creating object of abstract class allowed in all versions of g++

g++ compiles ill formed C++ program successfully

class A {
public:
    A() {
        printf("A()\n");
    }
    virtual void b() const = 0;
};
int main() {
    const A& a{};
    a.b();
    return 0;
}

Your code does the same thing as this line

const A& a{}

as part of g({}) invocation.



来源:https://stackoverflow.com/questions/39392541/instantiation-of-an-abstract-class-via-initializer-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!