Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Problem with putting temporary variables in constructors

25 views
Skip to first unread message

Paul

unread,
Oct 7, 2018, 3:28:35 PM10/7/18
to
In the code below , TextNextNum has a constructor
of the form TestNextNum(const RandomGen&)
and DisplayNextNum has a constructor of the form
DisplayNextNum(const TestNextNum&)

I suspect that there's a problem below with using
the temporary variable RandomGen(Constants::testRandomNums, Constants::testProbabilities) as a parameter for the TestNextNum
constructor.

Is this a problem?

Thank you very much for your help,

Paul


DisplayExample::DisplayExample() :
DisplayNextNum(TestNextNum(RandomGen(Constants::testRandomNums, Constants::testProbabilities)))

{
// Some code

}

Ian Collins

unread,
Oct 7, 2018, 10:51:55 PM10/7/18
to
What errors do you see?

--
Ian.

Alf P. Steinbach

unread,
Oct 8, 2018, 4:50:10 AM10/8/18
to
On 07.10.2018 21:28, Paul wrote:
> In the code below , TextNextNum has a constructor
> of the form TestNextNum(const RandomGen&)
> and DisplayNextNum has a constructor of the form
> DisplayNextNum(const TestNextNum&)
>
> I suspect that there's a problem below with using
> the temporary variable RandomGen(Constants::testRandomNums, Constants::testProbabilities) as a parameter for the TestNextNum
> constructor.
>
> Is this a problem?

Could be, if you're binding a member reference to the argument.

Clever idea to not show the code.



> Thank you very much for your help,

Oh, you're welcome. :)


Cheers!,

- Alf

Juha Nieminen

unread,
Oct 8, 2018, 5:06:10 AM10/8/18
to
Paul <peps...@gmail.com> wrote:
> I suspect that there's a problem below with using
> the temporary variable RandomGen(Constants::testRandomNums, Constants::testProbabilities) as a parameter for the TestNextNum
> constructor.
>
> Is this a problem?

It depends on what exactly you are doing with that reference.

If you are, for example, just using the object pointed by that reference
within that constructor implementation and nothing else, then there's no
problem (because the object will exist for as long as the constructor is
being executed). If you are initializing a member variable of TestNextNum
(by calling its copy or move constructor, or possibly the copy or move
assignment operator) with that parameter, there's also no problem (because
the parameter itself won't be used anymore after that).

If you are assuming the lifetime of the object pointed to by the rerence
is longer than the duration of the constructor, then you would have a
problem.
0 new messages