在下面的代码中,struct A有立即函数默认构造函数,并在动态内存中创建该结构的对象new A{}:
struct A {
consteval A() {}
};
int main() {
new A{};
}
Run Code Online (Sandbox Code Playgroud)
只有 Clang 接受。
海湾合作委员会抱怨
error: the value of '<anonymous>' is not usable in a constant expression
6 | new A{};
| ^
note: '<anonymous>' was not declared 'constexpr'
Run Code Online (Sandbox Code Playgroud)
MSVC 也这样做:
error C7595: 'A::A': call to immediate function is not a constant expression
Run Code Online (Sandbox Code Playgroud)
演示: https: //gcc.godbolt.org/z/6Px5WYGzd
这里是哪个编译器?
考虑以下代码:
#include <cstdint>
#include <vector>
class ClassT
{
public:
consteval static size_t GetSize()
{
return sizeof(int);
}
void Resize()
{
_Data.resize(GetSize(), 0);
}
std::vector<uint8_t> _Data;
};
int main()
{
ClassT Object;
Object.Resize();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
GCC编译成功,但是MSVC给出以下错误:
error C7595: 'ClassT::GetSize': call to immediate function is not a constant expression
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?或者这真的是 MSVC 的错误吗?
编译器版本:x86-64 gcc 10.2和x64 msvc v19.28. (链接到神箭)