C++ Logo

std-proposals

Advanced search

Re: [std-proposals] inline function within class definition can define member objects

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Sat, 15 Oct 2022 17:48:25 -0400
On Sat, Oct 15, 2022 at 3:50 PM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> I propose that the following:
>
> struct Foo {
>
> int Method(int arg)
> {
> int Foo::record;
>
> record = arg;
>
> return arg + 4u;
> }
> };
>
> behaves the same as:
>
> struct Foo {
>
> int record;
>
> int Method(int arg)
> {
> record = arg;
>
> return arg + 4u;
> }
> };
>
> There are times when a method needs a simple variable such as a
> counter or a boolean, and so we then need to add a member variable to
> the class definition.

If this happens that often, what has likely happened is that your
class has grown way too large and needs to be broken down.

> I'm proposing that we can do all of this inside
> the body of the method -- so long as the body of the method is inline
> inside the class definition. I also propose that the variable "record"
> would be inaccessible by other methods.

What is going on in this function that it needs to store its own
private state as a member subobject of the class? Looking at your code
example, it doesn't even check to see if it initialized that private
member before overwriting it. So it overwrites the value every single
time. And since no other code can access it... why does it need to
persist beyond this function call?

But let's say that you change it to be like function-static: the
initializer expression only gets invoked the first time through the
function. OK... how does *that* work? That first-time initialization
would have to set some kind of state, which must be a private member
of some sort.

At which point, an `optional<T>` member would work just fine.

This is not a good idea.

Received on 2022-10-15 21:49:54