1

How to use uniform_int_distribution as the class field in constructor. I am new in ++. I am trying next approach and just got error.

class RandomConnectionsProvider : RandomProviderBase { public: RandomConnectionsProvider(mainDataType operatorsCount); ~RandomConnectionsProvider(void); static mainDataType GetNextConnectedOper(); private: uniform_int_distribution<int>* connections_dist; static random_device rd; static mt19937 rnb; }; RandomConnectionsProvider::RandomConnectionsProvider(mainDataType operatorsCount) { uniform_int_distribution<int> op_dist(1, OperatorsCount); connections_dist = &op_dist; } mainDataType RandomConnectionsProvider::GetNextConnectedOper() { return *connections_dist(rnb);//Triing to dereference as i remember it but got error there } 

2 Answers 2

4

You make connections_dist point to a local variable in the constructor. This local variable will be destroyed when the constructor returns, and so the pointer will no longer point to a valid object.

Instead I suggest you skip the use of pointers, and do something like this instead:

class RandomConnectionsProvider : RandomProviderBase { std::uniform_int_distribution<int> connections_dist; // Note: no pointer // ... public: RandomConnectionsProvider::RandomConnectionsProvider(mainDataType operatorsCount) : connections_dist(1, operatorsCount) { } // ... }; 

The part after the colon in the constructor is called an initializer list and is used to initialize member variables in the object.

Not using a pointer will help you fix the other error as well, as you won't be needing to use dereferencing. That error, by the way, is because the function call has higher operator precedence than the dereference operator (so the compiler thinks you are doing *(connections_dist(rnb))).

Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that the local op_dist object is destroyed when your constructor finishes, so you cannot use it afterwards. Your connections_dist points to invalid memory.

You have 2 possible solutions:
1. Don't use a pointer, but an object member:
Use uniform_int_distribution<int> connections_dist directly and initialize it using the initializer list, like this:

RandomConnectionsProvider::RandomConnectionsProvider(mainDataType operatorsCount) : connections_dist ( 1, OperatorsCount ) { } 

2. Dynamically allocate the object, and by this prolong its lifetime:
You need to delete it again in the destructor, like this:

RandomConnectionsProvider::RandomConnectionsProvider(mainDataType operatorsCount) { connections_dist = new uniform_int_distribution<int>(1, OperatorsCount); } RandomConnectionsProvider::~RandomConnectionsProvider() { delete connections_dist; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.