在 T 的静态成员中使用 sizeof(T) 的 C++ 错误
c++ error using sizeof(T) in static member of T
为什么我的编译器不允许这样做?
class Resource
{
private:
static const int max_instances = 10;
// set aside memory to be used later with placement new
static char memory[max_instances * sizeof(Resource)]; // error: invalid application of 'sizeof' to incomplete type 'Resource'
};
我认为这是因为您还没有完成对 class 的定义,因此编译器不知道它的大小,因此会产生此错误。我不知道你想在这里完成什么,按照 aschepler 的回答并在实际 class 定义
之外定义 static const char
The sizeof
operator shall not be applied to an expression that has function or incomplete type
[class.mem]/6,强调我的:
A class is considered a completely-defined object type ([basic.types]) (or complete type) at the closing }
of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, noexcept-specifiers, and default member initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.
我的老药方,把它包在一个函数里:
class Resource{
//...
auto constexpr max_instances=10;
static auto& memory(){
static std::aligned_storage<sizeof(Resource),alignof(Resource)> storage[max_instances];
return storage;
};
};
为什么我的编译器不允许这样做?
class Resource
{
private:
static const int max_instances = 10;
// set aside memory to be used later with placement new
static char memory[max_instances * sizeof(Resource)]; // error: invalid application of 'sizeof' to incomplete type 'Resource'
};
我认为这是因为您还没有完成对 class 的定义,因此编译器不知道它的大小,因此会产生此错误。我不知道你想在这里完成什么,按照 aschepler 的回答并在实际 class 定义
之外定义 static const charThe
sizeof
operator shall not be applied to an expression that has function or incomplete type
[class.mem]/6,强调我的:
A class is considered a completely-defined object type ([basic.types]) (or complete type) at the closing
}
of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, noexcept-specifiers, and default member initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.
我的老药方,把它包在一个函数里:
class Resource{
//...
auto constexpr max_instances=10;
static auto& memory(){
static std::aligned_storage<sizeof(Resource),alignof(Resource)> storage[max_instances];
return storage;
};
};