Passing and storing const reference through constructor?

This is probably a simple question, but I'm stuck on it. I am trying to pass an object from ObjectA to ObjectB (which is a member of ObjectA) through the constructor. However, instead of passing by value, I want to pass only a link to a constant and store this link indefinitely. The problem is that I'm not sure how to do this.

I can get this to work with pointers like this:

class ClassB { private: int *ptrInternalX; public: ClassB( int *tempX ); } ClassB::ClassB( int *tempX ) { ptrInternalX = tempX } 

Thus, an object is created and a pointer to int is passed, and this pointer is stored inside the class for later use.

However, pointers make me worry about memory leaks and other problems when using large objects, so I would like to try to do something like this using "constant references" (const &). However, this does not seem to work ...

 class ClassB { private: int &internalX; public: ClassB( const int &tempX ); } ClassB::ClassB( const int &tempX ) { internalX = tempX } 

I know that references are essentially "aliases" for an existing variable (another name that refers to the same memory address), and they should be immediately initialized using the existing variable. Thus, this creates an error in my program!

Is it possible? Or is there a better / clearer way to do something like this? The reasons why I want to use permalinks is the transfer speed of only the link instead of the large object, saving data from accidental changes and memory leaks ... I'm sure there is a simple and direct way to do this, but I'm not very familiar with the transfer links const.

+7
source share
1 answer
 class ClassB { private: const int& internalX; public: ClassB(const int& tempX); } ClassB::ClassB(const int& tempX): internalX(tempX) { } 

As you said, a reference should be initialized immediately. That way, if you want your reference be a member of the class, you have to use the constructor initialization list to set it.

(This short explanation may also make you clearer, as it focuses specifically on the situation you just met)

Good luck.

+9
source

All Articles