在工厂模型中使用const_cast

Using const_cast in factory model

本文关键字:const cast 工厂 模型      更新时间:2023-10-16

如果我的命名不正确,请原谅/纠正我。

我从未理解const_cast的用途。一般来说,在我看来,如果您必须使用const_cast,那么您的类/方法可能存在根本缺陷,除非您使用的是不正确的遗留函数。然而,我可能偶然发现了一个恰当使用它的案例。我有一个很大的类,有几个成员在构造过程中分配,并且在对象的使用寿命内保持不变。

因为这些对象经常被破坏和构造,所以我想尝试一下我认为所谓的工厂模型:我不想创建/破坏对象,而是想检索/返回到未分配对象的缓存中。例如(当然是简化的):

class PersonFactory {
public:
const Person* getPerson(const QString& newname) {
//I can't assign the new name because it's const
if(m_personCache.isEmpty())
return createNewPerson();
else
return m_personCache.pop();
}
void returnPerson(Person* person) { m_personCache.push(person); person = 0; }
static PersonFactory* instance;
private:
Person* createNewPerson() const { return new Person(""); }
QStack<Person*> m_personCache;
}
class Person {
public:
friend Person* PersonFactory::createNewPerson();
const QString& name() const {
return m_name;
}
void destroy() {
PersonFactory::returnPerson(this);
}
private:
Person(QString name) : m_name(name) {}
//m_name is const and should remain that way to prevent accidental changes
const QString m_name;
}

我无法分配新名称,因为它是const。这是const_cast的一个好例子吗?还是我错过了一个明显的替代方案?使用const_cast会影响性能吗?

使用const_cast会导致性能下降吗?

也许吧。当对象实际上是const时,丢弃const来存储值会产生未定义的行为。未定义的行为可以表现为性能上的成功。