class variables: scoping

N

Neil Zanella

Hello,

Suppose I have some method:

Foo::foo() {
static int x;
int y;
/* ... */
}

Here variables x is shared by all instances of the class, but has
function scope. On the other hand, variable y, also has function
scope, but is reinitialized each time the method is called.

Now, I would like to have a variable which has function scope,
that is, is not visible by other class functions. However, every
time I instantiate an instance of Foo a new such variable is created.
Essentially, I would like to have something like the equivalent of:

class Foo {
/* ... */
private:
/* ... */
int z;
/* ... */
};

However, I do not want to have all methods inside Foo see z. I only
want method foo to see it, just like I did for x which can only be
seen by foo().

The value of z should survive different calls from within the same
instance, but should be initialized for each new instance, like above.
But it should have method scope, not class scope.

It would be nice if C++ were extended to include this nice idea.
It could for example allow something like:

Foo::foo() {
static int x;
int y;
semistatic z;
/* ... */
}

Where semistatic means: shared by all invocations within the same
instance, and only visible within foo().

I think this feature is missing from C++ and is quite useful. Because
if some class variable is used only in one method, then why should I
have to place it in the class definition. It's like having to make
things global just because they are shared by instances.
Comments welcome.

Regards,

Neil
 
L

Leor Zolman

Hello,

Suppose I have some method:
How about calling them "functions" now? You've been around for a while...
;-)
Foo::foo() {
static int x;
int y;
/* ... */
}

Here variables x is shared by all instances of the class,

Not /that/ variable x, if you're referring to the one in Foo:foo(). That's
a block-scope static, which means it can only be referred to within that
function (and its value persists across multiple calls to it. By the way,
it gets initialized to zero the first time the function is called, if you
don't give it an initializer.)

but has
function scope. On the other hand, variable y, also has function
scope, but is reinitialized each time the method is called.

Not by the code you've shown. Automatic locals without an initializer are
left uninitialized.
Now, I would like to have a variable which has function scope,
that is, is not visible by other class functions. However, every
time I instantiate an instance of Foo a new such variable is created.

So far you've described a simple local automatic variable.
Essentially, I would like to have something like the equivalent of:

class Foo {
/* ... */
private:
/* ... */
int z;
/* ... */
};

Oh boy.
However, I do not want to have all methods inside Foo see z. I only
want method foo to see it, just like I did for x which can only be
seen by foo().

The x you actually defined up there in foo() satisfies this (but not what
you go on to specify below.)
The value of z should survive different calls from within the same
instance, but should be initialized for each new instance, like above.
But it should have method scope, not class scope.

I /think/ I see what you want, but there's no primitive way to declare that
in C++: You want an instance variable (one copy associated with each
instance of an object) that is only in scope within a particular function,
right? No can do. You'll just have to exercise some self-discipline by
declaring a private data member and being careful to only access it from
within the one function.
It would be nice if C++ were extended to include this nice idea.
It could for example allow something like:

Foo::foo() {
static int x;
int y;
semistatic z;
/* ... */
}

Where semistatic means: shared by all invocations within the same
instance, and only visible within foo().

Lots of things would be nice. This one isn't going to happen, though.
I think this feature is missing from C++ and is quite useful. Because
if some class variable is used only in one method, then why should I
have to place it in the class definition.

To indicate to the compiler that it has to make room for it in each object
instantiated. At least the way C++ is currently defined ;-)
It's like having to make
things global just because they are shared by instances.
Comments welcome.

You got 'em.
-leor
 
@

@(none)

Neil said:
[...]However, I do not want to have all methods inside Foo see z. I only
want method foo to see it, just like I did for x which can only be
seen by foo().

The value of z should survive different calls from within the same
instance, but should be initialized for each new instance, like above.
But it should have method scope, not class scope.

It would be nice if C++ were extended to include this nice idea.
It could for example allow something like:

Foo::foo() {
static int x;
int y;
semistatic z;
/* ... */
}

If I understood correctly, you want to associate a variable (state) to a
member function (behavior)... I would say you need a new object for that
(and a class, of course). Your little object would have just one method,
so I guess it's safe to call it a functor, maybe overwrite the "()"
opertor to look more like a function...
Where semistatic means: shared by all invocations within the same
instance, and only visible within foo().

I think this feature is missing from C++ and is quite useful. Because
if some class variable is used only in one method, then why should I
have to place it in the class definition. It's like having to make
things global just because they are shared by instances.
Comments welcome.

I'm not sure it is that common to justify inclusion in the language..
and it's not that difficult to get the same effect using existing
language constructs.

regards,
iuli
 
S

Siemel Naran

Neil Zanella said:
Now, I would like to have a variable which has function scope,
that is, is not visible by other class functions. However, every
time I instantiate an instance of Foo a new such variable is created.
Essentially, I would like to have something like the equivalent of:

Basically, a private data member accessible to one or more member functions.

I tried the following once but it fails compile. But maybe we can tweak it
a bit, and then it will compile? Maybe with the pointer to implementation
concept it would work?

class Foo;

class Foo_f_Data
{
int x;
friend void Foo::f(); // this line fails compile because class Foo not
defined
};

class Foo : private Foo_f_Data
{
public:
void f();
void g();
};

void Foo::f() {
x = 3; // ok
}

void Foo::g() {
x = 5; // fails compile, c
}

Of course, comments are a nice idea too!
 
A

Alf P. Steinbach

* (e-mail address removed) (Neil Zanella) schriebt:
Essentially, I would like to have something like the equivalent of:

class Foo {
/* ... */
private:
/* ... */
int z;
/* ... */
};

However, I do not want to have all methods inside Foo see z. I only
want method foo to see it, just like I did for x which can only be
seen by foo().

The value of z should survive different calls from within the same
instance, but should be initialized for each new instance, like above.
But it should have method scope, not class scope.


class Foo;

class FooFunctor
{
private:
Foo& myFoo;
int myZ;
public:
FooFunctor( Foo& aFoo ): myFoo( aFoo ), myZ( 0 ) {}
int operator()();
};

class Foo
{
private:
int x;
FooFunctor foo;
public:
Foo(): x(0), foo(*this) {}

void bar()
{
x = foo();
}
};

int FooFunctor::eek:perator()(){ ... }

It would be nice if C++ were extended to include this nice idea.
It could for example allow something like:

Foo::foo() {
static int x;
int y;
semistatic z;
/* ... */
}

Where semistatic means: shared by all invocations within the same
instance, and only visible within foo().

As I recall there is a proposal to add members with automatic back-
pointers, like Java inner classes, but whether it will be adopted...
 
N

Neil Zanella

Leor Zolman said:
Not /that/ variable x, if you're referring to the one in Foo:foo(). That's
a block-scope static, which means it can only be referred to within that
function (and its value persists across multiple calls to it. By the way,
it gets initialized to zero the first time the function is called, if you
don't give it an initializer.)

Perhaps my explanation was somewhat inadequate. What you have stated in the
above paragraph is correct. Indeed, x can only be referred to from within
member function Foo::foo(). And indeed since it is static the compiler will
automatically arrange for it to be initialized to zero when no initializer
is present. What I meant to express by saying that x is shared by all
instances of Foo is exemplified in the following code:

#include <iostream>

class Foo {
public:
void foo() {
static int x;
std::cout << x++ << std::endl;
}
};

int main() {
Foo foo;
foo.foo();
foo.foo();
Foo bar;
bar.foo();
Foo foobar;
foobar.foo();
}

Output:

0
1
2
3

The goal is to achieve the output:

0
1
0
0

without changing the contents of main and without changing the contents
of the class definition (which seems impossible in C++, since it does not
support the feature I describe).
I /think/ I see what you want, but there's no primitive way to declare that
in C++: You want an instance variable (one copy associated with each
instance of an object) that is only in scope within a particular function,

Correct. That is indeed the feature I was describing. Furthermore I was
poining out that C++ supports combinations:

(one copy per class, class scope) (static data members in class body)
(one copy per class, function scope) (static data members in function body)
(one copy per instance, class scope) (automatic data in class body)

but not the combination:

(one copy per instance, function scope)

I think this is poor design of the C++ language, because several functions
need have boolean variables called initialize which act as follows. Class
Foo has methods foo(), bar(), and foobar(). We don't want the constructor
to call these because they consume too much precious time, sometimes only
to initialize data members that are not needed later on. So we have the
functions foo(), bar(), and foobar() do the respective data member
initializations they need when they are called. Given that the
sets of data members they initialize are disjoint in the
given scenario, and that foo() may initialize more than
one data member, it makes sense to have a variable
which satisfies the missing C++ feature in order
to perform the initialization when foo() is called.
Alas, I need put such initializer variables inside
the function body.

I wonder if any languages have what I describe. Smalltalk?
right? No can do. You'll just have to exercise some self-discipline by
declaring a private data member and being careful to only access it from
within the one function.

To indicate to the compiler that it has to make room for it in each object
instantiated. At least the way C++ is currently defined ;-)

Hmmm... but the compiler went and fetched those static variables for
the BSS segment. I gues they belong to another data segment altogether
hence that is what makes it possible???

Regards,

Neil
 
G

Gary Labowitz

Neil Zanella said:
I think this is poor design of the C++ language, because several functions
need have boolean variables called initialize which act as follows. Class
Foo has methods foo(), bar(), and foobar(). We don't want the constructor
to call these because they consume too much precious time, sometimes only
to initialize data members that are not needed later on. So we have the
functions foo(), bar(), and foobar() do the respective data member
initializations they need when they are called. Given that the
sets of data members they initialize are disjoint in the
given scenario, and that foo() may initialize more than
one data member, it makes sense to have a variable
which satisfies the missing C++ feature in order
to perform the initialization when foo() is called.
Alas, I need put such initializer variables inside
the function body.

I'm afraid I don't get it. If all three functions need to know if any
of the other's have already run, wouldn't a common variable to all
functions serve the purpose; i.e. a member in the class? If each of
the functions needed to know just which of the functions has already
run, then three statics named fooran, barran, and foobarran would
serve.
Is this right?
 
N

Neil Zanella

* (e-mail address removed) (Neil Zanella) schriebt:


class Foo;

class FooFunctor
{
private:
Foo& myFoo;
int myZ;
public:
FooFunctor( Foo& aFoo ): myFoo( aFoo ), myZ( 0 ) {}
int operator()();
};

class Foo
{
private:
int x;
FooFunctor foo;
public:
Foo(): x(0), foo(*this) {}

void bar()
{
x = foo();
}
};

int FooFunctor::eek:perator()(){ ... }

Thank you for your reply..

I am not sure how your example would help in the situation I describe.
Consider the following code example where having the runFooi variables
being local to the current function would be of practical use. These
would then also have to be initialized within that function with
a scheme similar to that of the initialization of static variables:
on first call for an instance the variable is constructed,
subsequent calls within same object ignore the
construction and use the old value
for current object.

#include <iostream>
#include <cstdlib>

class Foo {
public:
Foo() { init(); }
Foo(int y): y(y) { init(); }
void init() {
/* defer initialization until needed */
runFoo1 = runFoo2 = runFoo3 = runFoo4 = true;
}
int foo1() { if (runFoo1) x1 = compute(0, 0); return x1; }
int foo2() { if (runFoo2) x2 = compute(0, 1); return x2; }
int foo3() { if (runFoo3) x3 = compute(1, 0); return x3; }
int foo4() { if (runFoo4) x4 = compute(1, 1); return x4; }
private:
int compute(int a, int b) {
/* suppose this takes a long time to run */
return rand() + 2 * a + b; /* for simplicity */
}
int x1, x2, x3, x4;
int y;
private:
bool runFoo1, runFoo2, runFoo3, runFoo4;
};

int main() {

/* run program without waiting for unnecessary computations */
/* available which would unnecessarily initialize class data */

Foo foo1;
std::cout << foo1.foo1() << std::endl;

/* foo1.foo2(), foo1.foo3(), and foo1.foo4() never called */
/* hence OO program can run as fast as a procedural program */

Foo foo2;
std::cout << foo2.foo2() << std::endl;
std::cout << foo2.foo3() << std::endl;
std::cout << foo2.foo4() << std::endl;

/* foo1.foo1() never called */
/* hence OO program can run as fast as a procedural program */

}
 
N

Neil Zanella

Siemel Naran said:
Of course, comments are a nice idea too!

I don't understand exactly how usnig functors could
help in this situation. However I have come up with
another solution that solves the problem which I
originally posted. Essentially I achieve the desired
result and feature using an std::map which
associates with each instance the desired variable.
Hence using static local variables associated with
instances achieves the effect of instance specific
local variables, as originally requested. Here we
go. Finally, something that seems to work neatly! I
was getting quite tired of inspecting my class
variables to see whether I don't have some variable
which is not being used by any method. Cluttering
all my function specific methods was simply
unstylish IMHO.

Comments on the solution posted below very welcome!

Regards,

Neil

#include <iostream>
#include <cstdlib>
#include <map>

class Foo {
public:
int foo1() {
static std::map<Foo *, bool> computed;
if (!computed[this]) {
std::cout << "Computing foo1..." << std::endl;
x1 = compute(0, 0);
computed[this] = true;
} else
std::cout << "Reusing computed foo1 result..." << std::endl;
return x1;
}
int foo2() {
static std::map<Foo *, bool> computed;
if (!computed[this]) {
std::cout << "Computing foo2..." << std::endl;
x2 = compute(0, 1);
computed[this] = true;
} else
std::cout << "Reusing computed foo2 result..." << std::endl;
return x2;
}
int foo3() {
static std::map<Foo *, bool> computed;
if (!computed[this]) {
std::cout << "Computing foo3..." << std::endl;
x3 = compute(1, 0);
computed[this] = true;
} else
std::cout << "Reusing computed foo3 result..." << std::endl;
return x3;
}
int foo4() {
static std::map<Foo *, bool> computed;
if (!computed[this]) {
std::cout << "Computing foo4..." << std::endl;
x4 = compute(1, 1);
computed[this] = true;
} else
std::cout << "Reusing computed foo4 result..." << std::endl;
return x4;
}
private:
int compute(int a, int b) {
/* suppose this takes a long time to run */
return rand() + 2 * a + b; /* for simplicity */
}
int x1, x2, x3, x4; /* data to be computed */
};

int main() {

/* run program without waiting for unnecessary computations */
/* available which would unnecessarily initialize class data */

std::cout << "Foo 1 Instance:" << std::endl;

Foo foo1;
std::cout << foo1.foo1() << std::endl;
std::cout << foo1.foo1() << std::endl;
std::cout << foo1.foo2() << std::endl;

/* foo1.foo3(), and foo1.foo4() never called */
/* hence OO program can run as fast as a procedural program */

std::cout << "Foo 2 Instance: " << std::endl;

Foo foo2;
std::cout << foo2.foo2() << std::endl;
std::cout << foo2.foo3() << std::endl;
std::cout << foo2.foo4() << std::endl;
std::cout << foo2.foo4() << std::endl;

/* foo1.foo1() never called */
/* hence OO program can run as fast as a procedural program */

}


Output:

Foo 1 Instance:
Computing foo1...
1804289383
Reusing computed foo1 result...
1804289383
Computing foo2...
846930887
Foo 2 Instance:
Computing foo2...
1681692778
Computing foo3...
1714636917
Computing foo4...
1957747796
Reusing computed foo4 result...
1957747796
 
A

Alf P. Steinbach

* (e-mail address removed) (Neil Zanella) schriebt:
Thank you for your reply..

You're welcome..

I am not sure how your example would help in the situation I describe.

Try it.


Consider the following code example where having the runFooi variables
being local to the current function would be of practical use. These
would then also have to be initialized within that function with
a scheme similar to that of the initialization of static variables:
on first call for an instance the variable is constructed,
subsequent calls within same object ignore the
construction and use the old value
for current object.

That's the same problem again, and it's no more difficult with four
variables than with one.

In addition you have added an irrelevant aspect, namly logical constness.

Look up the keyword 'mutable' for that.
 
S

Siemel Naran

Neil Zanella said:
I don't understand exactly how usnig functors could
help in this situation. However I have come up with

I think I misunderstood your original requirement. Thought you wanted to
make a private variable which is accessible to only 1 member function.


#include <iostream>
#include <cstdlib>
#include <map>

class Foo {
public:
int foo1() {
static std::map<Foo *, bool> computed;
if (!computed[this]) {
std::cout << "Computing foo1..." << std::endl;
x1 = compute(0, 0);
computed[this] = true;
} else
std::cout << "Reusing computed foo1 result..." << std::endl;
return x1;
}
int foo2() {
static std::map<Foo *, bool> computed;
if (!computed[this]) {
std::cout << "Computing foo2..." << std::endl;
x2 = compute(0, 1);
computed[this] = true;
} else
std::cout << "Reusing computed foo2 result..." << std::endl;
return x2;
}
int foo3() {
static std::map<Foo *, bool> computed;
if (!computed[this]) {
std::cout << "Computing foo3..." << std::endl;
x3 = compute(1, 0);
computed[this] = true;
} else
std::cout << "Reusing computed foo3 result..." << std::endl;
return x3;
}
int foo4() {
static std::map<Foo *, bool> computed;
if (!computed[this]) {
std::cout << "Computing foo4..." << std::endl;
x4 = compute(1, 1);
computed[this] = true;
} else
std::cout << "Reusing computed foo4 result..." << std::endl;
return x4;
}
private:
int compute(int a, int b) {
/* suppose this takes a long time to run */
return rand() + 2 * a + b; /* for simplicity */
}
int x1, x2, x3, x4; /* data to be computed */
};

Why not just

class Foo {
public:
Foo() : x1(), x1_computed(false) { }
private:
int x1;
bool x1_computed;

If you want to get fancy, you can try the recursive derivation idea I posted
in "set/get in c++".
 
L

Leor Zolman

Perhaps my explanation was somewhat inadequate. What you have stated in the
above paragraph is correct. Indeed, x can only be referred to from within
member function Foo::foo(). And indeed since it is static the compiler will
automatically arrange for it to be initialized to zero when no initializer
is present. What I meant to express by saying that x is shared by all
instances of Foo is exemplified in the following code:
[code snipped]

I think you're confusing yourself by saying that the x above is "shared by
all instances of Foo" because in fact it is shared by all instances of
/everything/, along with all /non-instances/ of everything (non-member
functions), that end up calling Foo::foo(). x behaves just like a
file-scope ("global") variable...that just happens to only be visible
within Foo::foo().
without changing the contents of main and without changing the contents
of the class definition (which seems impossible in C++, since it does not
support the feature I describe).


Correct. That is indeed the feature I was describing. Furthermore I was
poining out that C++ supports combinations:

(one copy per class, class scope) (static data members in class body)
(one copy per class, function scope) (static data members in function body)
(one copy per instance, class scope) (automatic data in class body)

but not the combination:

(one copy per instance, function scope)

Perhaps it is because Bjarne and everyone else involved in the evolution of
C++ didn't think that last permutation was useful enough, if in fact it
ever occurred to them. I don't know, but the idea sure never occurred to
/me/.

Hmmm... but the compiler went and fetched those static variables for
the BSS segment. I gues they belong to another data segment altogether
hence that is what makes it possible???

What's a BSS segment? I'm sorry, I swore off assembly language and as much
as possible pertaining to it a long time ago. But if you understood what I
said above what it means for a variable to be static to a function, I think
you'll probably have the answer to your question.

Cheers,
-leor
 
N

Neil Zanella

Siemel Naran said:
Why not just

class Foo {
public:
Foo() : x1(), x1_computed(false) { }
private:
int x1;
bool x1_computed;

What if a single function computes 10 data members. Wouldn't you then
rather associate one boolean variable with the function than have one
for each data member? I am not just considering setters and getters.
There are more complicated functions that manipulate multiple data
members in more complicated classes. On the other hand I would
probably have a boolean variable for each private data member
if it were the case that the functions did not operate on
disjoint data members.

Anyhow, to answer your question, I don't like having all those booleans
and what not linger inside class Foo when they are method specific, which
is what I originally posted about. In any case perhaps something like

template<class t>
struct Data {
T value;
bool computed;
};

could perhaps help reduce the clutter... (yes? no?).
If you want to get fancy, you can try the recursive derivation idea I posted
in "set/get in c++".

I would like to comment on the "set/get in C++" thread. The idea described
therein is not a new idea. Some C++ toolkits such as Qt implement it already.
For instance see the Q_PROPERTY Qt macro. This takes the following format:

Q_PROPERTY( Priority priority READ priority WRITE setPriority )

You may want to read about it in with the assistant Qt application.

However, if classes were all about setters and getters that returned and
set a single state variable each then OOAD would be quite uninteresting.
Nevertheless for some applictions several short setters and getters may
be all it takes to describe some of the more trivial classes. In general
however we can have more complicated setter implementations, perhaps even
so for the getters, and the internal representation of the data could be
quite different from what appears to be presented by the class interface.

Thanks,

Neil
 
S

Siemel Naran

Neil Zanella said:
What if a single function computes 10 data members. Wouldn't you then
rather associate one boolean variable with the function than have one
for each data member? I am not just considering setters and getters.
There are more complicated functions that manipulate multiple data
members in more complicated classes. On the other hand I would
probably have a boolean variable for each private data member
if it were the case that the functions did not operate on
disjoint data members.

OK, I understand your question now -- you don't want to clutter the header
file. Initially I thought you wanted to member variable accessible to only
one function (a kind of super-private access mechanism but also an
indication that your class is too big), then I thought you just wanted to
indicate whether a variable was constructed.
Anyhow, to answer your question, I don't like having all those booleans
and what not linger inside class Foo when they are method specific, which
is what I originally posted about. In any case perhaps something like

template<class t>
struct Data {
T value;
bool computed;
};

could perhaps help reduce the clutter... (yes? no?).

It reduces the number of lines in your code, but the clutter is still there
(namely all the boolean variables) once the template code is expanded.
Besides as you point out, if you want one boolean variable for ten data
members which foo() calculates, the Data<T> is overkill as it constructs 10
booleans. I don't have a perfect or good solution, but maybe you could use
a member variable like,

/*mutable*/ std::set<std::string> d_constructed;

and in your functions use the __FUNCTION__ macro to indicate that the
variables of this function are constructed. Note that __FUNCTION__ is not
standard, though there are variations you can try.

void Foo::foo() const {
if (d_constructed.find(__FUNCTION__) == d_constructed.end()) {
d_constructed.insert(__FUNCTION__);
d_x = 3;
d_y = 8;
}
}

The static variables idea in your previous post works could easily cause
trouble in multi-threaded environments.


I would like to comment on the "set/get in C++" thread. The idea described
therein is not a new idea. Some C++ toolkits such as Qt implement it already.
For instance see the Q_PROPERTY Qt macro. This takes the following format:

Q_PROPERTY( Priority priority READ priority WRITE setPriority )

You may want to read about it in with the assistant Qt application.

However, if classes were all about setters and getters that returned and
set a single state variable each then OOAD would be quite uninteresting.
Nevertheless for some applictions several short setters and getters may
be all it takes to describe some of the more trivial classes. In general
however we can have more complicated setter implementations, perhaps even
so for the getters, and the internal representation of the data could be
quite different from what appears to be presented by the class interface.

Right, the idea is best when the function bodies are more complicated.
Though I did not claim the idea was new, and I first learned about it in
Stroustrup's book.
 
N

Neil Zanella

Siemel Naran said:
I don't have a perfect or good solution, but maybe you could use
a member variable like,

/*mutable*/ std::set<std::string> d_constructed;

and in your functions use the __FUNCTION__ macro to indicate that the
variables of this function are constructed. Note that __FUNCTION__ is not
standard, though there are variations you can try.

void Foo::foo() const {
if (d_constructed.find(__FUNCTION__) == d_constructed.end()) {
d_constructed.insert(__FUNCTION__);
d_x = 3;
d_y = 8;
}
}

Is the __FUNCTION__ macro specific to the gcc compiler suite or does it work
with other compilers as well. In any case standard behavior could be attained
by using an enumeration with something similar to function names in it.
The static variables idea in your previous post works could easily cause
trouble in multi-threaded environments.

Perhaps you are referring to the fact that in a multithreaded applications
two objects may have the same virtual address, hence it is not possible to
identify an object on the basis of its virtual address and be certain that
the application will work. Is this what you are referring to when you mention
that problems may arise in multithreaded applications.

Regards,

Neil
 
S

Siemel Naran

Is the __FUNCTION__ macro specific to the gcc compiler suite or does it work
with other compilers as well. In any case standard behavior could be attained
by using an enumeration with something similar to function names in it.

Borland 6 does not support __FUNCTION__. I think Microsoft does, but ask on
a Microsoft group to be sure, or try it on the compiler.

Instead of maintaining an enum, I was thinking of converting the address of
a function to a string, like this,

void * ptr = static_cast<void *>(&X::function);
std::cout << ptr;

But you can't convert a pointer to member function into a void*, even
through reinterpret_cast, because they usually have different sizes. And
typeid(&X::function).name() prints the type of the function, so if
X::function1 and X::function2 have the same signature, typeid.name() prints
the same thing.

To avoid cluttering the header file, why not just use the pointer to
implementation idea where you declare the struct in the cpp file? You get
insulation for free, can use reference counted smart pointers if so desired
(though they have multi-threading problems/challenges too), etc.

Perhaps you are referring to the fact that in a multithreaded applications
two objects may have the same virtual address, hence it is not possible to
identify an object on the basis of its virtual address and be certain that
the application will work. Is this what you are referring to when you mention
that problems may arise in multithreaded applications.

It's the standard one. Two threads call your function X::f(). Both see
that the static variable is not constructed. Then both go ahead and
construct it.

The solution is when one thread sees it is not constructed it blocks the
function memory so the other thread cannot do anything, the the first thread
constructs the object and releases the block, and the other thread then sees
the static variable is constructed. There is no native support for this in
C++. You have to use OS functions like critical section and mutexes. Even
if it works, the use of these OS functions is quite expensive. I'm not an
expert on multi-threading (still learning it myself), but those are the
basics.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top