3

我正在开发一个基于 clang 的 AST 的工具,我很想知道为什么 clang 会这样工作。

这是我的输入。我有一个非常简单的类,定义如下:

class Foo {
    int foo();
};

然后在我的 RecursiveASTVisitor 中,我的代码如下所示:

bool MyASTVisitor::VisitCXXRecordDecl(clang::CXXRecordDecl *D) {
    for (auto const & method : D->methods()) {
        llvm::outs() << method->getQualifiedNameAsString() << "(";
        for (auto const & param : method->params())
            llvm::outs() << param->getType().getAsString() << ", ";
        llvm::outs() << ")";
        if (method->isImplicit())
            llvm::outs() << " [implicit]";
        llvm::outs() << "\n";
    }
    return true;
}

所有这一切都是吐出在所有被访问的类中定义的方法列表。输出如我们所料:

Foo::foo()

现在,让我们对 Foo 类做一个小改动。让我们将 foo() 方法设为虚拟:

class Foo {
    virtual int foo();
};

现在我的输出改变了:

Foo::foo()
Foo::operator=(const class Foo &, ) [implicit]
Foo::~Foo() [implicit]

我的问题是,为什么向类添加虚拟方法会导致 clang 创建隐式赋值运算符和析构函数?如果我添加 --std=c++11,它也会创建一个隐式移动赋值运算符。这是 clang 的实现细节,还是 C++ 标准的一部分?

4

1 回答 1

1

原来我应该只阅读 clang 源代码。 SemaDeclCXX.cpp有一个方法叫做Sema::AddImplicitlyDeclaredMembersToClass. 关于它为什么声明隐式复制分配的评论:

if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
  ++ASTContext::NumImplicitCopyAssignmentOperators;

  // If we have a dynamic class, then the copy assignment operator may be
  // virtual, so we have to declare it immediately. This ensures that, e.g.,
  // it shows up in the right place in the vtable and that we diagnose
  // problems with the implicit exception specification.
  if (ClassDecl->isDynamicClass() ||
      ClassDecl->needsOverloadResolutionForCopyAssignment())
    DeclareImplicitCopyAssignment(ClassDecl);
}

所以它这样做是为了确保隐式定义的方法(可能是虚拟的)最终出现在 vtable 中的正确位置。

于 2015-09-25T00:39:53.687 回答