473,656 Members | 2,997 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Use of static keyword instead of global object

Hi,

I wish to share an object through a bunch of functions without
declaring it globally. I have achieved this through the following
function:

VideoReceiver* getReceiver()
{
static VideoReceiver *vr = new VideoReceiver() ;
return vr;
}

So, the first time it is called a new VideoReceiver object is created.
Subsequent calls return this object (without creating new ones).

E.g, All one needs to do to access the VideoReceiver is:

function blah()
{
VideoReceiver vr = getReceiver();
vr->update()

//do blah
}

Are there any problems or issues I should be aware of using this type
of code? Is it a no-no? I make multiple calls to getReceiver() each
frame.

It was originally a hack to get going but now that I've advanced a
reasonable way I'm considering just leaving it, since it is currently
working as expected.

Thanks for any advice or suggestions,
Sam.

Feb 13 '07 #1
5 2352
"Sa********@gma il.com" <Sa********@gma il.comwrote in
news:11******** *************@a 75g2000cwd.goog legroups.com:
Hi,

I wish to share an object through a bunch of functions without
declaring it globally. I have achieved this through the following
function:

VideoReceiver* getReceiver()
{
static VideoReceiver *vr = new VideoReceiver() ;
return vr;
}
Why dynamically allocate it? Why not simply make it a static local
variable?
So, the first time it is called a new VideoReceiver object is created.
Subsequent calls return this object (without creating new ones).

E.g, All one needs to do to access the VideoReceiver is:

function blah()
{
VideoReceiver vr = getReceiver();
I assume you meant "VideoRecei ver * vr"....
vr->update()

//do blah
}

Are there any problems or issues I should be aware of using this type
of code? Is it a no-no? I make multiple calls to getReceiver() each
frame.
I don't think that the object will ever be destroyed. With a local
static it will (sometime after main....)
It was originally a hack to get going but now that I've advanced a
reasonable way I'm considering just leaving it, since it is currently
working as expected.

Thanks for any advice or suggestions,
Perhaps make it a static local variable and return a reference to it.
Feb 13 '07 #2
On Feb 12, 7:54 pm, "Sam.Gun...@gma il.com" <Sam.Gun...@gma il.com>
wrote:
Hi,

I wish to share an object through a bunch of functions without
declaring it globally. I have achieved this through the following
function:

VideoReceiver* getReceiver()
{
static VideoReceiver *vr = new VideoReceiver() ;
return vr;

}

So, the first time it is called a new VideoReceiver object is created.
Subsequent calls return this object (without creating new ones).

E.g, All one needs to do to access the VideoReceiver is:

function blah()
{
VideoReceiver vr = getReceiver();
vr->update()

//do blah

}

Are there any problems or issues I should be aware of using this type
of code? Is it a no-no? I make multiple calls to getReceiver() each
frame.

It was originally a hack to get going but now that I've advanced a
reasonable way I'm considering just leaving it, since it is currently
working as expected.

Thanks for any advice or suggestions,
Sam.
The function is fine except I would return
a reference to the object - this way there
is no chance of anyone deleting the object
by accident.

Also, as another poster said, there's no
need for dynamic allocation - just use a
static local.

But for multi-threaded programs, the construction
of the object is not safe. See, for instance,
Modern C++ Design for a good discussion on this.

Some times, this is ok. For instance, I use a
static local log object inside a function. But
I make sure it is used (and hence constructed)
in the main thread before any other threads are
invoked.

Feb 13 '07 #3
On 12 Feb 2007 16:54:54 -0800, "Sa********@gma il.com" <Sa********@gma il.com>
wrote:
>Hi,

I wish to share an object through a bunch of functions without
declaring it globally. I have achieved this through the following
function:

VideoReceive r* getReceiver()
{
static VideoReceiver *vr = new VideoReceiver() ;
return vr;
}

So, the first time it is called a new VideoReceiver object is created.
Subsequent calls return this object (without creating new ones).

E.g, All one needs to do to access the VideoReceiver is:

function blah()
{
VideoReceiver vr = getReceiver();
vr->update()

//do blah
}

Are there any problems or issues I should be aware of using this type
of code? Is it a no-no? I make multiple calls to getReceiver() each
frame.

It was originally a hack to get going but now that I've advanced a
reasonable way I'm considering just leaving it, since it is currently
working as expected.

Thanks for any advice or suggestions,
Sam.
There is no problem with this kind of code, except that the VideoReceiver
object is never destroyed.

Your solution is actually a common implementation of the Singleton pattern in
C++. A more typical code would be:
MyClass& getClassInstanc e()
{
MyClass myClass;
return myClass;
}
The pattern you are using also solves a common problems with globals:
initialization order.

-dr
Feb 13 '07 #4
On Feb 12, 9:16 pm, Dave Rahardja
<drahardja_atsi gn_pobox_dot_.. .@pobox.comwrot e:
On 12 Feb 2007 16:54:54 -0800, "Sam.Gun...@gma il.com" <Sam.Gun...@gma il.com>
wrote:
Hi,
I wish to share an object through a bunch of functions without
declaring it globally. I have achieved this through the following
function:
VideoReceiver* getReceiver()
{
static VideoReceiver *vr = new VideoReceiver() ;
return vr;
}
So, the first time it is called a new VideoReceiver object is created.
Subsequent calls return this object (without creating new ones).
E.g, All one needs to do to access the VideoReceiver is:
function blah()
{
VideoReceiver vr = getReceiver();
vr->update()
//do blah
}
Are there any problems or issues I should be aware of using this type
of code? Is it a no-no? I make multiple calls to getReceiver() each
frame.
It was originally a hack to get going but now that I've advanced a
reasonable way I'm considering just leaving it, since it is currently
working as expected.
Thanks for any advice or suggestions,
Sam.

There is no problem with this kind of code, except that the VideoReceiver
object is never destroyed.

Your solution is actually a common implementation of the Singleton pattern in
C++. A more typical code would be:

MyClass& getClassInstanc e()
{
MyClass myClass;
return myClass;

}

The pattern you are using also solves a common problems with globals:
initialization order.

-dr

Like dr says, this is the singleton pattern and is quite useful. I
find it useful to use a singleton as a non-copyable as well like so:

class Singleton
{
public:
virtual ~Singleton() {}

protected:

Singleton() {}

Singleton( const Singleton& singleton ) {}

Singleton&
operator=( const Singleton& singleton ) {}
} ;

class MyClass : public Singleton
{
public:
static MyClass&
Instance()
{
if( !_instance )
{
boost::shared_p tr< MyClass temp( new MyClass() ) ;
_instance = temp ;
}

return _instnace ;
}

void
foo() ;

private:

static boost::shared_p tr< MyClass _instance ;
} ;
And then you can just do:

MyClass::Instan ce().foo() ;

or

MyClass& inst = MyClass::Instan ce() ;
inst.foo() ;

To use it in code.

HTH,
Paul Davis

Feb 13 '07 #5
On Feb 13, 3:58 am, "paul.joseph.da ...@gmail.com"
<paul.joseph.da ...@gmail.comwr ote:
On Feb 12, 9:16 pm, Dave Rahardja

<drahardja_atsi gn_pobox_dot_.. .@pobox.comwrot e:
On 12 Feb 2007 16:54:54 -0800, "Sam.Gun...@gma il.com" <Sam.Gun...@gma il.com>
wrote:
>Hi,
>I wish to share an object through a bunch of functions without
>declaring it globally. I have achieved this through the following
>function:
>VideoReceive r* getReceiver()
>{
static VideoReceiver *vr = new VideoReceiver() ;
return vr;
>}
>So, the first time it is called a new VideoReceiver object is created.
>Subsequent calls return this object (without creating new ones).
>E.g, All one needs to do to access the VideoReceiver is:
>function blah()
>{
VideoReceiver vr = getReceiver();
vr->update()
//do blah
>}
>Are there any problems or issues I should be aware of using this type
>of code? Is it a no-no? I make multiple calls to getReceiver() each
>frame.
>It was originally a hack to get going but now that I've advanced a
>reasonable way I'm considering just leaving it, since it is currently
>working as expected.
>Thanks for any advice or suggestions,
>Sam.
There is no problem with this kind of code, except that the VideoReceiver
object is never destroyed.
Your solution is actually a common implementation of the Singleton pattern in
C++. A more typical code would be:
MyClass& getClassInstanc e()
{
MyClass myClass;
return myClass;
}
The pattern you are using also solves a common problems with globals:
initialization order.
-dr

Like dr says, this is the singleton pattern and is quite useful. I
find it useful to use a singleton as a non-copyable as well like so:

class Singleton
{
public:
virtual ~Singleton() {}

protected:

Singleton() {}

Singleton( const Singleton& singleton ) {}

Singleton&
operator=( const Singleton& singleton ) {}

} ;

class MyClass : public Singleton
{
public:
static MyClass&
Instance()
{
if( !_instance )
{
boost::shared_p tr< MyClass temp( new MyClass() ) ;
_instance = temp ;
}

return _instnace ;
}

void
foo() ;

private:

static boost::shared_p tr< MyClass _instance ;

} ;

And then you can just do:

MyClass::Instan ce().foo() ;

or

MyClass& inst = MyClass::Instan ce() ;
inst.foo() ;

To use it in code.

HTH,
Paul Davis

Totally looked this over after I posted and realized I messed up a
couple points.

in Instance():

should be:

return *( _instance.get() ) ;

And don't forget to put:

boost::shared_p tr< MyClass MyClass::_insta nce, in a source file
somewhere.

Sorry if thats just confusing.

Paul Davis

Feb 13 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2184
by: lkrubner | last post by:
In the code below I'm getting a parse error on this line: static $controllerForAll = new McControllerForAll(); why does this give me a parse error? I'm running PHP 4. function & getController($callingCode=false) { // 11-27-04 - we want to get the controllerForAll variable, and we
5
3215
by: A | last post by:
Hi, Consider this code: //Header File - Foo.h int i = 0; // non-static global variable class Foo{ ...
9
6356
by: Bryan Parkoff | last post by:
I have noticed that C programmers put static keyword beside global variable and global functions in C source codes. I believe that it is not necessary and it is not the practice in C++. Static keyword is useful inside struct, class, and function only unless you want to force local variable to be global variable so static is used. Do you have idea why most programmers do this? Bryan Parkoff
3
3927
by: Datta Patil | last post by:
Hi , #include<stdio.h> func(static int k) /* point2 : why this is not giving error */ { int i = 10 ; // static int j = &i ; /* point 1: this will give compile time error */ return k; } /* in above case where is variable k and j mapped in memory layout ? */
3
2717
by: Bas Wassink | last post by:
Hello there, I'm having trouble understanding a warning produced by 'splint', a code-checker. The warning produced is: keywords.c: (in function keyw_get_string) keywords.c:60:31: Released storage Keywords.Keyword reachable from global A global variable does not satisfy its annotations when control is transferred. (Use -globstate to inhibit warning) keywords.c:60:11: Storage Keywords.Keyword released
8
4859
by: Vishwanathan Raman | last post by:
Hi I have a declared a static DataSet object SOBJ in Global.asax.I also have a localy defined DataSet LSOBJ in Global.asax which I am storing in Application State.Is there any technical differences in the way both the objects are handled by IIS. Are both objects stored in different memory spaces? I can access both the objects in my web page. I will be grateful if some one can help me understand the difference.
4
1795
by: ma740988 | last post by:
Referencing source snippet below, the actual contruction of the foo objects is done in a class. In that regard, I chose methods, class1_construct and class2_construct for demonstration purposes. That aside, I encountered source akin to what's shown below today and I was almost convinced the source is wrought with trouble. On second thought it appears legal. The static ptr_foo object and it's use in assignment to other foo objects (ptr_1...
6
3553
by: Marvin Barley | last post by:
I have a class that throws exceptions in new initializer, and a static array of objects of this type. When something is wrong in initialization, CGI program crashes miserably. Debugging shows uncaught exception. How to catch an exception that happened before main() try { ... } catch (...) { ... } block? Is there a way?
2
3141
by: DaTurk | last post by:
Hi, I have an interesting issue, well, it's not really an issue, but I'd like to understand the mechanics of what's going on. I have a file, in CLI, which has a class declared, and a static fuction. Because the class is declared globally, I declare it as static. Is a function with a namespace scope declared as static by default? So, this worked fine when I was accessing the static function inside
14
6008
by: Jess | last post by:
Hello, I learned that there are five kinds of static objects, namely 1. global objects 2. object defined in namespace scope 3. object declared static instead classes 4. objects declared static inside functions (i.e. local static objects) 5. objects declared at file scope.
0
8296
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8497
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8598
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5627
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2721
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1928
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1598
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.