Question

Forgive/correct me if my nomenclature is incorrect.

I have never understood the use of const_cast. Generally speaking, it seems to me that if you must use const_cast then your class/methods is probably fundamentally flawed unless you're using legacy functions that aren't const-correct. I may have stumbled on a case where its use is appropriate, however. I have a large class with a couple members that are assigned during construction and remain constant for the useful life of the object.

Because these objects are destroyed and constructed frequently, I would like to experiment with what I believe is called the Factory Model: instead of creating/destroying the object, I would like to retrieve/return it to a cache of unassigned objects. For example (simplified, of course):

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;
}

I can't assign a new name because it is const. Is this a good case for const_cast or am I missing an obvious alternative? Would using const_cast result in a performance hit?

Was it helpful?

Solution

Would using const_cast result in a performance hit?

Maybe. Casting away const to store a value when an object is in fact const produces undefined behavior. Undefined behavior can manifest as, among other things, a performance hit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top