Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make variable unchangeable without copying in C++

Tags:

c++

vector

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?

like image 777
yu quan Avatar asked Dec 19 '22 00:12

yu quan


2 Answers

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();
like image 156
Jarod42 Avatar answered Dec 21 '22 13:12

Jarod42


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.

like image 33
Peter Avatar answered Dec 21 '22 14:12

Peter