C++标准中短语"constructors do not have names"的含义

Meaning of phrase "constructors do not have names" in the C++ Standard

本文关键字:names have not do 标准 短语 constructors C++      更新时间:2023-10-16

在试图理解C++标准中的短语"构造函数没有名称"时,我似乎在clang中发现了一个错误。有人能证实吗?

VS2015 gcc拒绝此代码,我认为他们它是是正确的。至少,这是我从N4140:中的§12.1[class.ctor]/2中得到的印象

#include <iostream>
class A {
public:
    A() { std::cout << "A()" << 'n'; }
};
int main()
{
  A::A();
}

N4140:中的§12.1[class.ctor]/2

构造函数用于初始化其类类型的对象。因为构造函数没有名称,在名称过程中永远找不到它们查找。。。

对于上面的表达式A::A();,clang通过名称查找来查找构造函数,而应该查找类型名称A。请参阅实例。

你的直觉是正确的。这是一个已知的Clang bug 13403,状态为NEW

我同意这不应该编译。

事实上,这比你想象的还要奇怪。试试这个:

#include <iostream>
#include <string>
class A {
public:
    A() {
        std::cout << "A() " << this << 'n';
    }
    void foo() {
        std::cout << _message << std::endl;
    }
    std::string _message = "hello";
};
int main()
{
    A::A().foo();
}

示例输出:

A() 0x7fff5cd105f8
hello

在我看来,似乎在隐式地创建一个未命名的A。