I am trying to optimize for speed of execution a piece of code using the factory design pattern.
The factory will produce many objects of a class having some members that are constant throughtout the execution of the program, and some members that are not. I always initialize the constant members with literals.
My question is, how is the memory of the constant members going to be managed? Can the compiler optimize the code so that this memory is not allocated/deallocated each time I create/destroy a new object?
Ideally I would like the literals to reside on a fixed piece of memory and only the reference to this memory be given to each new object. I would like to avoid using global variables.
class Test {
private:
const std::string &name_;
int value_;
public:
Test(const std::string &name, int value) : name_(name), value_(value) {}
};
int main() {
Test test1("A", 1);
Test test2("B", 2);
Test test3("B", 3);
Test test4("A", 4);
Test test5("B", 5);
// etc ...
}
PS1. notice that in the code snippet the factory pattern implementation is not shown.
PS2. Assume GCC 11.2.0 on Linux