Jump to content

  • Log In with Google      Sign In   
  • Create Account


Static as substitute of private members.


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
19 replies to this topic

#1 gasto   Members   -  Reputation: 261

Like
0Likes
Like

Posted 10 April 2014 - 06:25 PM

The C way to deal with variables that are not supposed to be used by client programmers is by using the static keyword in global space. In this way the variables are not available to external files, so that, even if an implementation file imports the header that contains such private variables, they are unavailable (name-definition-unaware, or more technically: out of scope).

 

If I can recall correctly, extern variables are declared in the header and defined in the implementation file.

 

What disadvantages are there from e.g. C++'s private class members?


Intel Core 2 Quad CPU Q6600, 2.4 GHz. 3GB RAM. ATI Radeon HD 3400.

Sponsor:

#2 L. Spiro   Crossbones+   -  Reputation: 13423

Like
4Likes
Like

Posted 10 April 2014 - 06:58 PM

Static members are global, global is bad.

But the main problem is that static members are not instance members.  You decide to use static when there will only be one member for all instances of that class globally, not based on visible scope.

 

 

Static is not a replacement for private in C.  Declaring and defining them only in the .C file is.

 

 

L. Spiro


It is amazing how often people try to be unique, and yet they are always trying to make others be like them. - L. Spiro 2011
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
I went to my local Subway once to find some guy yelling at the staff. When someone finally came to take my order and asked, “May I help you?”, I replied, “Yeah, I’ll have one asshole to go.”
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums

#3 Alundra   Members   -  Reputation: 846

Like
0Likes
Like

Posted 10 April 2014 - 07:04 PM

Static members are global, global is bad.

But the main problem is that static members are not instance members.  You decide to use static when there will only be one member for all instances of that class globally, not based on visible scope.

 

 

Static is not a replacement for private in C.  Declaring and defining them only in the .C file is.

 

 

L. Spiro

Why static is bad ? In an engine class it's good to have all init using Init() function.

You use this way on your engine : http://lspiroengine.com/docs/classlse_1_1_c_engine.html

On a renderer it's nice to have RenderState class with static variables + Init() to avoid Renderer.cpp of 4000 lines.

Do you think struct + extern is better to use than class/struct with static ?

I really want your opinion about all that L. Spiro smile.png.


Edited by Alundra, 10 April 2014 - 07:06 PM.


#4 SeanMiddleditch   Members   -  Reputation: 5337

Like
1Likes
Like

Posted 10 April 2014 - 07:19 PM

Why static is bad ? In an engine class it's good to have all init using Init() function.


It's non-ideal, not bad. There are a lot of problems with it, however. It makes threading a pain in the butt. It makes writing tests against mock objects a pain in the butt. It makes some kinds of debugging a pain in the butt.

On a renderer it's nice to have RenderState class with static variables + Init() to avoid Renderer.cpp of 4000 lines.


That doesn't follow. Nothing about static variables makes the rest of your code smaller. You've got a false equivalency going on here.

Do you think struct + extern is better to use than class/struct with static ?


I don't understand what these have to do with each other.

Make functions or classes that take as parameters any dependencies they have and don't rely on statics. This is called Dependency Injection, and is something to strive for. That way, for instance, you can pass in a NullaryRenderDevice or something so you can test your renderer in a unit test on your build machine without needing an actual GPU, or a MockFileSystem that serves up only some cooked-in test files for tests. It lets you switch out things at runtime easily.

There are many places for static values. I use them extensively in reflection code, error dialog and assert code, memory space support, and so on. They're all hidden behind very special-case features and not part of the main game code or even the main game systems.

Everything else are systems/manager encapsulated in classes that require references to interfaces for other systems. e.g the GraphicsSystem requires a reference to IResourceSystem so that it can load textures and such on demand. The AudioSpace attached to any Space on the GameObjectSystem has a reference to an IAudioSystem so that sound sources in game can play sound. etc. No statics, no globals, no singletons, no service locator, none of that cruft. I can initialize the engine, systems, or spaces in any configuration I need, including initializing them completely differently in the release mode game, debug mode game, editor, asset baker, multiplayer server, etc.

#5 phil_t   Crossbones+   -  Reputation: 3318

Like
1Likes
Like

Posted 10 April 2014 - 07:21 PM


On a renderer it's nice to have RenderState class with static variables + Init() to avoid Renderer.cpp of 4000 lines.

 

Huh? How does a static Init avoid 4000 lines?

 

There's really no good reason to have your renderer or engine be static/global.



#6 L. Spiro   Crossbones+   -  Reputation: 13423

Like
5Likes
Like

Posted 10 April 2014 - 07:26 PM

I explain my use of statics here: http://lspiroengine.com/?p=570
And because I dislike statics and tend to avoid them myself, anyone who disagrees with my use there is perfectly in the right.  A graphics module doesn’t need to be global, but I also strongly dislike having to pass an instance down to every graphics resource such as a vertex buffer.  I also disagree with a graphics object that spits out vertex buffers, textures, etc., which would solve that problem, but breaks the single-responsibility rule in my opinion; I prefer a vertex buffer/texture/index buffer/shader/etc. that can simply be made just like any other object and it knows by itself how to allocate its resources and activate them.
 
All that being said, I finally decided to use static for that small section of the engine because statics are not always evil, you just have to use them responsibly.
http://www.gamedev.net/topic/647440-why-are-static-variables-bad/
The downsides of statics are explained there and above.
As I use them sparingly and after much consideration, I do not have a problem with any of these downsides.


L. Spiro
It is amazing how often people try to be unique, and yet they are always trying to make others be like them. - L. Spiro 2011
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
I went to my local Subway once to find some guy yelling at the staff. When someone finally came to take my order and asked, “May I help you?”, I replied, “Yeah, I’ll have one asshole to go.”
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums

#7 SeanMiddleditch   Members   -  Reputation: 5337

Like
1Likes
Like

Posted 10 April 2014 - 09:04 PM

A graphics module doesn’t need to be global, but I also strongly dislike having to pass an instance down to every graphics resource such as a vertex buffer.


I solve this by making my graphics resources opaque objects. Only things that manipulate resources need the graphics system, which turns out to be relatively rare (it's mostly the code that generates the draw commands). It's fairly D3D11-ish. As a further bonus, all my graphics resource handles are C++ wrappers around ints, making it much easier to sort by material/buffer for rendering (especially as I guarantee that the unique bits of those integers are the lower X bits, meaning you can radix sort on only X bits instead of on most of the bits of a pointer).

#8 Aardvajk   Crossbones+   -  Reputation: 5968

Like
1Likes
Like

Posted 11 April 2014 - 05:58 AM

As a side note, the actual use of C-style static in global space has really been replaced by anonymous namespaces now and static in global space in C++ is really only for backwards compatibility with legacy C code as far as I'm aware. I prefer anonymous namespaces because its too easy to forget to add static to the front of a new definition but easy to remember to include it in the namespace.

 

I don't use much, if any, static global state but I tend to put implementation functions in anonymous namespaces to avoid accidental linking and name clashes.


Edited by Aardvajk, 11 April 2014 - 05:59 AM.


#9 Buster2000   Members   -  Reputation: 1639

Like
2Likes
Like

Posted 11 April 2014 - 06:27 AM


Static is not a replacement for private in C. Declaring and defining them only in the .C file is.

 

Don't they need to be declared static inside the .C file so that they only visible from within that compilation unit.



#10 SimonForsman   Crossbones+   -  Reputation: 6066

Like
-2Likes
Like

Posted 11 April 2014 - 07:12 AM

 


Static is not a replacement for private in C. Declaring and defining them only in the .C file is.

 

Don't they need to be declared static inside the .C file so that they only visible from within that compilation unit.

 

 

No, each compilation unit is compiled individually, a variable has to be declared as extern to become accessible across compilation units.

 

Edit: Sorry, obviously incorrect.


Edited by SimonForsman, 11 April 2014 - 10:36 AM.

I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

#11 Alundra   Members   -  Reputation: 846

Like
0Likes
Like

Posted 11 April 2014 - 07:33 AM

Alundra, on 11 Apr 2014 - 03:04 AM, said:
On a renderer it's nice to have RenderState class with static variables + Init() to avoid Renderer.cpp of 4000 lines.

That doesn't follow. Nothing about static variables makes the rest of your code smaller. You've got a false equivalency going on here.

I was not clean on this view, but L. Spiro said the reason after.

It's to have a class who store all render state object needed for the render static to avoid to have monster function call with 10 parameters.

And one Init() in RenderState class to avoid Renderer Init() function to be large code.

But I have to say that I don't allow external render state, for example I have that in Material :

enum TBlendMode
{
  BM_OPAQUE   = 0, //!< Opaque blend mode.
  BM_ADDITIVE = 1, //!< Additive blend mode.
  BM_ALPHA    = 2  //!< Alpha blend mode.
};
RenderState has (and init) :
ID3D11BlendState* m_OpaqueBlendState; //!< Opaque blend state.
ID3D11BlendState* m_AlphaBlendState; //!< Alpha blend state.
ID3D11BlendState* m_AdditiveBlendState; //!< Additive blend state.
ID3D11BlendState* m_AdditiveSrcAlphaBlendState; //!< AdditiveSrcAlpha blend state.

But it's not just that, it has too :

ID3D11DepthStencilState* m_DisabledDepthStencilState; //!< Disabled depth stencil state.
ID3D11DepthStencilState* m_LessEqualDepthStencilState; //!< Less-Equal depth stencil state.
ID3D11RasterizerState* m_NoneCullRasterizerState; //!< NoneCull rasterizer state.
ID3D11RasterizerState* m_ClockWiseCullRasterizerState; //!< ClockWiseCull rasterizer state.
ID3D11RasterizerState* m_CounterClockWiseCullRasterizerState; //!< CounterClockWiseCull rasterizer state.
ID3D11SamplerState* m_ClampLinearSamplerState; //!< ClampLinear sampler state.
ID3D11SamplerState* m_RepeatLinearSamplerState; //!< RepeatLinear sampler state.
ID3D11SamplerState* m_ClampPointSamplerState; //!< ClampPoint sampler state.
ID3D11SamplerState* m_RepeatPointSamplerState; //!< RepeatPoint sampler state.

I have a list of Vertex/Pixel/Hull/Geometry/Compute shader as well but inside renderer actually, but I would change to avoid monster params function call.

All that combined to give that : http://uppix.com/f-GameD3D11_135347f06e001605d7.png

The probleme is to have renderer cleaned about clustered renderer/shadow mapping.


Edited by Alundra, 11 April 2014 - 07:46 AM.


#12 TheComet   Members   -  Reputation: 1519

Like
0Likes
Like

Posted 11 April 2014 - 07:38 AM

 

 


Static is not a replacement for private in C. Declaring and defining them only in the .C file is.

 

Don't they need to be declared static inside the .C file so that they only visible from within that compilation unit.

 

 

No, each compilation unit is compiled individually, a variable has to be declared as extern to become accessible across compilation units.

 

 

To expand on what people are saying with a few examples:

 

 

 

CASE 1

 

test.h

extern int x;
void foo(void);

test.c

int x;
void foo(void) { x = 1; }

main.c

#include "test.h"
int main(void)
{
    foo(); /* ok */
    x = 6; /* ok */
    return 0;
}

x and foo() are both visible in external modules.

 

 

CASE 2

 

test.h

/* extern int x removed */
void foo(void);

test.c

int x;
void foo(void) { x = 1; }

main.c

#include "test.h"
int main(void)
{
    foo(); /* ok */
    x = 6; /* ERROR, x undeclared */
    return 0;
}

x wasn't declared as extern in the header file and is therefore invisible to external modules.

 

 

CASE 3

 

test.h

extern int x;
static void foo(void);

test.c

int x;
static void foo(void) { x = 1; }

main.c

#include "test.h"
int main(void)
{
    foo(); /* ERROR: foo() undeclared */
    x = 6; /* ok */
    return 0;
}

foo() was declared static and therefore is invisible to external modules.


Edited by TheComet, 11 April 2014 - 09:34 AM.

YOUR_OPINION >/dev/null


#13 Buster2000   Members   -  Reputation: 1639

Like
0Likes
Like

Posted 11 April 2014 - 08:05 AM




CASE 1



test.h

extern int x;
void foo(void);

test.c

int x;
void foo(void) { x = 1; }

main.c

#include "test.h"
int main(void)
{
foo(); /* ok */
x = 6; /* ok */
return 0;
}

x and foo() are both visible in external modules.

 

But in this case if you were to declare x as static within test.c you could could redclare it in main and it would be a different variable.



#14 TheComet   Members   -  Reputation: 1519

Like
0Likes
Like

Posted 11 April 2014 - 08:52 AM

[never mind]


Edited by TheComet, 11 April 2014 - 09:33 AM.

YOUR_OPINION >/dev/null


#15 Álvaro   Crossbones+   -  Reputation: 13033

Like
2Likes
Like

Posted 11 April 2014 - 09:00 AM

Static is not a replacement for private in C. Declaring and defining them only in the .C file is.

 
Don't they need to be declared static inside the .C file so that they only visible from within that compilation unit.

 
No, each compilation unit is compiled individually, a variable has to be declared as extern to become accessible across compilation units.

If you declare and define the variable in global scope in the .C file, it's implicitly static anyway.


What do you mean "implicitly static"? If you have two compilation units that define variables with the same name in the global scope and none of them are static, you will get a "multiple definition" error when linking. There is no such thing as "implicitly static".

#16 Buster2000   Members   -  Reputation: 1639

Like
1Likes
Like

Posted 11 April 2014 - 09:00 AM

If you DON'T declare it static AND you DON'T declare it extern either BUT you have two variables in two C files both called x AND both files are in the same linker unit you WILL get a linker error because the linker WILL see them as the same object in global scope even though you haven't declared either of them extern.  If you declare both variables as static then you will not get a linker error.

 

 

Alvaro got there before me.


Edited by Buster2000, 11 April 2014 - 09:01 AM.


#17 TheComet   Members   -  Reputation: 1519

Like
1Likes
Like

Posted 11 April 2014 - 09:30 AM


What do you mean "implicitly static"? If you have two compilation units that define variables with the same name in the global scope and none of them are static, you will get a "multiple definition" error when linking. There is no such thing as "implicitly static".

I was mistaken, sorry.


YOUR_OPINION >/dev/null


#18 gasto   Members   -  Reputation: 261

Like
0Likes
Like

Posted 11 April 2014 - 09:53 AM


Static is not a replacement for private in C.  Declaring and defining them only in the .C file is.

 

 

L. Spiro

 

Actually, technically one could import (include) the .c file and use it in another .c file through the extern keyword(which declares, does not define. Hence why header files contain many extern keywords for variables but not for functions, since for global functions it is optional.)


Intel Core 2 Quad CPU Q6600, 2.4 GHz. 3GB RAM. ATI Radeon HD 3400.

#19 wack   Members   -  Reputation: 1292

Like
0Likes
Like

Posted 11 April 2014 - 11:15 AM

As a side note, the actual use of C-style static in global space has really been replaced by anonymous namespaces now and static in global space in C++ is really only for backwards compatibility with legacy C code as far as I'm aware. I prefer anonymous namespaces because its too easy to forget to add static to the front of a new definition but easy to remember to include it in the namespace.
 
I don't use much, if any, static global state but I tend to put implementation functions in anonymous namespaces to avoid accidental linking and name clashes.


Using static this way used to be deprecated, but is not deprecated in C++ 11 anymore.

Guess they realized it's kind of a silly thing to deprecate.

#20 SeanMiddleditch   Members   -  Reputation: 5337

Like
1Likes
Like

Posted 11 April 2014 - 11:24 AM

Static and anonymous namespaces can still lead to problems if you're definining globals or helper functions with identical names. For instance, if you ever try a "unity build" (nothing to do with the game engine).

Name things uniquely. If you need some local helper functions, consider giving them a namespae wrapper, e.g.

// foo.cpp
namespace /*anonymous*/ {
  namespace FooHelpers {
    void do_thing() { /*...*/ {
  }
}

void PublicClass::Method() {
  using namespace FooHelpers;
  // ...
  do_thing();
}

void PublicClass::OtherMethod() {
  using namespace FooHelpers;
  do_thing();
  // ...
}
using statements in global contexts is also bad in a unity build scenario (even more so than they are in general) so only use them inside function bodies.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS