gpt4 book ai didi

c++ - 这里发生了什么?我失去了常量吗?

转载 作者:太空狗 更新时间:2023-10-29 23:47:17 25 4
gpt4 key购买 nike

我这里有一个 Singleton 类,旨在由想要使用它的类继承。但我对编译器允许的某些问题有疑问,但我不明白为什么:

template<class DerivedT>
class Singleton {
static DerivedT*& internalPointer() {
static DerivedT* object(nullptr);
return object;
}

void reassignIf(Singleton* instance) {
auto& object(internalPointer());
if (object == static_cast<DerivedT*>(instance)) {
object = static_cast<DerivedT*>(this);
}
}

Singleton(Singleton const& other); // = delete

Singleton& operator=(Singleton const& other); // = delete

public:
static DerivedT* instance() { return internalPointer(); }

protected:
Singleton() { reassignIf(nullptr); }

Singleton(Singleton&& other) { reassignIf(&other); }

~Singleton() {
auto& object(internalPointer());
if (object == static_cast<DerivedT*>(this)) {
object = nullptr;
}
}

Singleton& operator=(Singleton&& other) { reassignIf(&other); return *this; }
};

class SingletonMock: Singleton<SingletonMock> {
public:
using Singleton<SingletonMock>::instance;

SingletonMock() : Singleton<SingletonMock>() { }
};

int main() {
SingletonMock x;
SingletonMock const y; // why is this line allowed?
}

为什么允许底线? Singleton 基类有一个名为 internalPointer 的静态成员函数,它有一个静态 DerivedT*。这应该成为 SingletonMock*,但它允许将 const SingletonMock 分配给该变量。

编辑:

我想我从评论中理解了它现在起作用的原因。但是,特别是它允许我这样做:

SingletonMock const y;
SingletonMock* yPtr(SingletonMock::instance());

我怎样才能阻止这样的事情被允许?

最佳答案

C++ 不允许该行。规范说 (8.5p9):

If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (orarray thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlyingclass type shall have a user-declared default constructor.

(强调我的)。 C++0x (FDIS) 措辞(8.5p6 和 8.5p11):

If no initializer is specified for an object, the object is default-initialized;

If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

关于c++ - 这里发生了什么?我失去了常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6378409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com