Lets assume I am trying to create "immutable" class objects (i.e. members variables are defined with const
). So when calling the constructor I currently call separate init
functions to initialise the class members. But as a result there seems to be a lot of new vector-creating & vector-copying going on.
If the members weren't const
I could perform the initialisations in the { }
section of the constructor and write directly into values
(which I assume would be more efficient). But this is not possible.
Are there better/cleaner/more efficient ways to design the construction of immutable classes?
#include <vector>
class Data
{
public:
const std::vector<int> values;
Data(unsigned int size, int other) : values(init(size, other)) { }
Data(const std::vector<int>& other) : values(init(other)) { }
private:
std::vector<int> init(unsigned int size, int other) {
std::vector<int> myVector(size);
for (unsigned int i = 0; i < size; ++i)
myVector[i] = other * i;
return myVector;
}
std::vector<int> init(const std::vector<int>& other) {
std::vector<int> myVector(other);
for (unsigned int i = 0; i < other.size(); ++i)
myVector[i] *= myVector[i] - 1;
return myVector;
}
};
int main() {
Data myData1(5, 3); // gives {0, 3, 6, 9, 12}
Data myData2({2, 5, 9}); // gives {2, 20, 72}
return 0;
}