从外部使用 "class::func()" 调用非静态函数或构造函数
Calling non static function or constructor using "class::func()" from outside
我在 Meeting C++ (@meetingcpp) 上看到了这个片段
以下代码在 clang and MSVC (Can try here) but fails on gcc 和 icc.
上编译良好
#include <iostream>
using namespace std;
struct B {};
struct C {
C() { cout << "C()\n"; }
C(B *) { cout << "C(B *)\n"; }
};
B *p = nullptr;
int main() {
C::C(p);
return 0;
}
这是 Clang 和 MSVC 中的已知错误,还是此代码可能合法?
p
的类型是 B *
,但 C::C
不应该编译?
根据标准 12.1/p2 构造函数[class.ctor](Emphasis Mine):
A constructor is used to initialize objects of its class type.
Because constructors do not have names, they are never found during name lookup; however an explicit type conversion using the
functional notation (5.2.3) will cause a constructor to be called to
initialize an object. [ Note: For initialization of objects of class
type see 12.6. — end note ]
因此,您不能直接调用构造函数,因为构造函数没有名称,并且在名称查找过程中永远找不到它们。
因此,GCC 是符合规范的,而 CLANG 和 VC++ 不是。
这是 Clang 中的一个已知错误,错误报告 23253, 23254 and 13403 are all reports of the issue. Ironically, this question is actually a duplicate of 。
我在 Meeting C++ (@meetingcpp) 上看到了这个片段
以下代码在 clang and MSVC (Can try here) but fails on gcc 和 icc.
上编译良好#include <iostream>
using namespace std;
struct B {};
struct C {
C() { cout << "C()\n"; }
C(B *) { cout << "C(B *)\n"; }
};
B *p = nullptr;
int main() {
C::C(p);
return 0;
}
这是 Clang 和 MSVC 中的已知错误,还是此代码可能合法?
p
的类型是 B *
,但 C::C
不应该编译?
根据标准 12.1/p2 构造函数[class.ctor](Emphasis Mine):
A constructor is used to initialize objects of its class type. Because constructors do not have names, they are never found during name lookup; however an explicit type conversion using the functional notation (5.2.3) will cause a constructor to be called to initialize an object. [ Note: For initialization of objects of class type see 12.6. — end note ]
因此,您不能直接调用构造函数,因为构造函数没有名称,并且在名称查找过程中永远找不到它们。
因此,GCC 是符合规范的,而 CLANG 和 VC++ 不是。
这是 Clang 中的一个已知错误,错误报告 23253, 23254 and 13403 are all reports of the issue. Ironically, this question is actually a duplicate of