问题
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