I'm working on some code in which a variable of type std::vector<double>
is declared, before the value is specified. I can't define the value together with declaration, because it takes many lines of code to set the value. The thing is that this variable is a constant in essence, meaning it shouldn't be modified once it's set. However, it can't be declared const
.
One way is to create another variable which is const
and copy the value into it. const std::vector<double> a(b);
would do, and use a
instead of b
in the program. However, my variable can be large and I wish to learn a way other than having to perform copying.
Any suggestions from you guys?
You may create a function to initialize it. In worst, you have a move
. at best you have (N)RVO (return value optimization).
std::vector<Object> CreateBigVector();
And then
const std::vector<Object> myObject = CreateBigVector();
One way is to create a function
std::vector<Object> CreateYourVector();
and use it to initialise
const std::vector<Object> vec = CreateYourVector();
Another (technically a variation) is to create a helper class that contains your vector, and do all the work in a constructor
class Helper
{
std::vector<Object> vec;
public:
Helper()
{
// initialise your vector here
};
const std::vector<Object> &TheVec() const {return vec;};
};
const Helper helper;
The above techniques can be combined, for example change the constructor
Helper() : vec(CreateYourVector()) {};
These techniques can also be mixed with others, such as the singleton pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With