Tuesday, September 29, 2009

comp.lang.c++ - 22 new messages in 8 topics - digest

comp.lang.c++
http://groups.google.com/group/comp.lang.c++?hl=en

comp.lang.c++@googlegroups.com

Today's topics:

* Pass a pointer variable to a function accept reference - 4 messages, 4
authors
http://groups.google.com/group/comp.lang.c++/t/330170d81fae3d1c?hl=en
* about new and delete - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c++/t/85fc26a34c7b73d3?hl=en
* How to get file count under a directory? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/85c9fe56a4fecd6f?hl=en
* RVO - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c++/t/a41ed66263ac91f0?hl=en
* C++ - expected unqualified-id before " /" token? - 5 messages, 4 authors
http://groups.google.com/group/comp.lang.c++/t/7cb3f7b37b9e0b0d?hl=en
* A few questions about singletons... - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c++/t/dd7f3af258a800cd?hl=en
* list.front() question - 4 messages, 3 authors
http://groups.google.com/group/comp.lang.c++/t/1905a1f360fa414a?hl=en
* Const Static variables set at run time and a design question. - 2 messages,
2 authors
http://groups.google.com/group/comp.lang.c++/t/b605293a5a67061f?hl=en

==============================================================================
TOPIC: Pass a pointer variable to a function accept reference
http://groups.google.com/group/comp.lang.c++/t/330170d81fae3d1c?hl=en
==============================================================================

== 1 of 4 ==
Date: Mon, Sep 28 2009 11:33 pm
From: "Louis"


Hi all:

Im having a little bit confuse of passing a pointer variable to a function
that accept reference:

void test(int &temp)
{

temp+= temp + 2;

cout << "function:" << temp << endl;
cout << "function:" << &temp << endl; //c:0x22ff1c
}

int main(int argc, char *argv[])
{

int c = 0;
int *d = &c;
cout << "d:" << *d << endl;
test(*d); // i guess, *d is dereference of d, which is value of c, and
same as int &temp = c, like passing reference?
cout << "c:" << &c << endl; //function:0x22ff1c,
return 0;
}

it works, i guess, *d is dereference of d, which is value of c, and same as
int &temp = c, like passing reference?

In the above code i'm trying to pass a dereference pointer d, which is
contain value of c, can anyone can explain to me if this is a good way to
pass a pointer variable?

Many Thanks

L

== 2 of 4 ==
Date: Tues, Sep 29 2009 1:42 am
From: Michael Tsang


Louis wrote:

> Hi all:
>
> Im having a little bit confuse of passing a pointer variable to a function
> that accept reference:
>
> void test(int &temp)
test is a void function accepting an int lvalue
> {
>
> temp+= temp + 2;
>
> cout << "function:" << temp << endl;
> cout << "function:" << &temp << endl; //c:0x22ff1c
> }
>
> int main(int argc, char *argv[])
> {
>
> int c = 0;
> int *d = &c;
> cout << "d:" << *d << endl;
*d is an int lvalue which is the same object as c
> test(*d); // i guess, *d is dereference of d, which is value of c,
c is passed into test
> and
> same as int &temp = c, like passing reference?
> cout << "c:" << &c << endl; //function:0x22ff1c,
> return 0;
> }
>
> it works, i guess, *d is dereference of d, which is value of c, and same
> as int &temp = c, like passing reference?
>
> In the above code i'm trying to pass a dereference pointer d, which is
> contain value of c, can anyone can explain to me if this is a good way to
> pass a pointer variable?
>
> Many Thanks
>
> L

== 3 of 4 ==
Date: Tues, Sep 29 2009 2:31 am
From: pjb@informatimago.com (Pascal J. Bourguignon)


"Louis" <islouis@hotmail.com> writes:

> Hi all:
>
> Im having a little bit confuse of passing a pointer variable to a
> function that accept reference:
>
> void test(int &temp)
> {
>
> temp+= temp + 2;
>
> cout << "function:" << temp << endl;
> cout << "function:" << &temp << endl; //c:0x22ff1c
> }
>
> int main(int argc, char *argv[])
> {
>
> int c = 0;
> int *d = &c;
> cout << "d:" << *d << endl;
> test(*d); // i guess, *d is dereference of d, which is value of c,
> and same as int &temp = c, like passing reference?
> cout << "c:" << &c << endl; //function:0x22ff1c,
> return 0;
> }
>
> it works, i guess, *d is dereference of d, which is value of c, and
> same as int &temp = c, like passing reference?
>


Perhaps you could get a hint from the character used to denote a reference: &

When you write: int &temp; temp = c; int x = temp;
what actually happen is like: int * temp; temp = &c; int x = *temp;

int x = *temp;
<=> int x = *&c; // since temp = &c
<=> int x = c; // since *& = identity.

You may consider the reference variables as pointers that are
automatically deferenced everytime they're used.


> In the above code i'm trying to pass a dereference pointer d, which is
> contain value of c, can anyone can explain to me if this is a good way
> to pass a pointer variable?

You didn't pass a pointer, you passed an int.
To pass a pointer you'd have to use the *.


void take_a_raw_pointer (int* param){
(*param)=42; // modifies the int pointed to by param.
param=0; // modifies param.
}

void take_a_pointer_reference(int*& param){
(*param)=42; // modifies the int pointed to by the pointer referenced by param.
param=0; // modifies the pointer referenced by param.
}

/*
The difference is that take_a_raw_pointer will accept temporary
pointers returned by functions, while take_a_pointer_reference will
want a pointer variable.
*/

int* p=&c;
int* compute_some_int_pointer();

take_a_raw_pointer(&c);
take_a_raw_pointer(p); // p cannot be modified assert(p==&c);
take_a_raw_pointer(compute_some_int_pointer());

take_a_pointer_reference(p); // p might be modified and be null or point to another int than c.


--
__Pascal Bourguignon__


== 4 of 4 ==
Date: Tues, Sep 29 2009 3:01 am
From: Paul N


On 29 Sep, 07:33, "Louis" <islo...@hotmail.com> wrote:

>     temp+= temp + 2;

Just a side point, but is this line doing what you think it does?

==============================================================================
TOPIC: about new and delete
http://groups.google.com/group/comp.lang.c++/t/85fc26a34c7b73d3?hl=en
==============================================================================

== 1 of 2 ==
Date: Tues, Sep 29 2009 12:34 am
From: SG


Sam wrote:
> Juha Nieminen writes:
> >> And what is the complexity of removing an element from the middle of the
> >> list, versus the middle of a vector?
>
> > O(n) for both.
>
> Hahahahahaha.
>
> std::list<obj> theList;
>
> // …
>
> std::list<obj>::iterator p;
>
> // …
>
> theList.erase(p);  // Warning, O(n)!!!!!
>
> Very funny.
>
> >                   If you want to prove me wrong, write a function which
> > takes a std::list as parameter and removes the element at the exact
> > middle faster than O(n).
>
> What you fail to grok, is that when you have a member of containe that you
> want removed, you already have its iterator, you don't need to search for
> it.

Who said something about "having a member"?

> Thank you for playing.

*yawn*

You simply phrased your question badly, Sam. It's not obvious if an
iterator to the middle element is already known. I do think you're
smart enough to grok what was going on. Juha even explained how he
interpreted the question by saying "write a function which takes a
std::list as parameter and removes the element at the exact middle
faster than O(n)". But instead of saying something like

"Yes, O(n) if you don't know the iterator. But I was assuming
that it is known. In that case std::list makes a difference."

you try to make it look like you're the only sane person here.
-1 for weak communication skills.

Cheers,
SG


== 2 of 2 ==
Date: Tues, Sep 29 2009 2:18 am
From: Richard Herring


In message <cone.1254177887.469434.13831.500@commodore.email-scan.com>,
Sam <sam@email-scan.com> writes
>Richard Herring writes:
>
>> In message
>><cone.1254136305.452816.10312.500@commodore.email-scan.com>, Sam
>><sam@email-scan.com> writes
>>
>>>If there's even one non-inlined function call in the body of the
>>>loop, there are only a very limited amount of cases where the
>>>compiler will know that the function call cannot possibly modify the
>>>container using some other pointer or reference, elsewhere, and it is
>>>safe to optimize out the ending iterator evaluation on every
>>>iteration. Otherwise, each function call can potentially modify the
>>>container, and since each iteration compares against the value of
>>>end() that exists at that time, it cannot be optimized out.
>> So the saving is something like one load, or similar, per iteration,
>>_if_ the loop body is complex enough to contain a non-inline function
>>call. What's that as a fraction of the overall execution time?
>
>Whatever it is, I wouldn't consider it something to be ignored.

cf. "you need a magnifying glass to see it."

> Always producing the best possible code is a good habit to have.

Indeed, and "best" is about more than speed. If you subsequently
"substitute the underlying implementation, without changing the code" by
changing the container type, the hidden assumption that end() is
invariant may come back to bite you.

> As I mentioned elsewhere, in certain situations, a difference of a few
>milliseconds in latency of production code means whether you come out
>in the black, or in the red, at the end of the day.

In that case you should also be worrying about the relative cost of
_incrementing_ different kinds of iterator. How does an increment
compare with an indirection on your target architecture? ;-)

And, as I mentioned elsewhere, you should really be much more concerned
about maximizing locality of reference. If the next element of your
sequence isn't already in the cache, all those micro-savings on iterator
manipulation are pointless.

>But, I suppose, if you're not doing anything particularly important,
>and you don't care, you shouldn't.

'We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil.'

> If you forget the whole thing, but this suddenly becomes important
>enough for someone to care about it, it won't be you.


--
Richard Herring

==============================================================================
TOPIC: How to get file count under a directory?
http://groups.google.com/group/comp.lang.c++/t/85c9fe56a4fecd6f?hl=en
==============================================================================

== 1 of 1 ==
Date: Tues, Sep 29 2009 12:45 am
From: James Kanze


On Sep 28, 9:18 pm, Marcel Müller <news.5.ma...@spamgourmet.com>
wrote:
> rockdale wrote:
> > I have an application which writes log files out. If then
> > log file size is great than let's say 1M, the application
> > will create a new log file with sequence number. the log
> > file format likes mylogfile_mmddyy_1.txt,
> > mylogfile_mmddyy_2.txt. ....without upper limit.

> don't do that.

> Use a time stamp and use a naming convention that follows a
> canonical sort order. E.g. mylogfile_yyyy-mm-dd_hh-mm-ss.txt.
> The guys that must service your application will appreciate
> greatly. Furthermore you should prefer UTC time stamps for
> logging to avoid confusion with daylight saving.

That sounds like a good idea. I'm used to putting the date in
the logfile name, and using a sequential number (with a fixed
number of digits, so a straight sort will put them in order),
but using the time does sound better.

> > Now the problem is if my application get restarted, I need
> > to know what is the largest sequence number of my log file.

> Either create always a new log if the application gets
> restarted or forbear from the size limit and use a time limit
> instead. I would recommend the latter. If your application is
> under heavy load the files grow larger. What's bad with that?

Files that are too large are hard to read and to manipulate.
Depending on the application, a time limit might either result
in an occasional file which is awkwardly large, or a lot of very
small files.

That doesn't mean that you should forego using time completely.
If there are particular moments when the application is largely
quiescent, those are good times to rotate the log; it reduces
the probability of a sequence which interests someone spanning
two different files. (Ideally, of course, the files should be
small enough so that the reader can easily concatenate two of
them, in cases where what interests him spans a rotation.)

> From the service point of view it is a big advantage to have a
> deterministic relation between the file name (in fact
> something like a primary key) and the content. And it is even
> better if the canonical file name ordering corresponds to
> their logical order.

> > I am thinking in a loop from 1 to like 100000, check if the
> > file exist, if it does not , then I get the max sequence
> > number I need.

> From that you see how bad the idea is. Everyone who searches
> for a certain entry has to do the same loop, regardless if
> program or human. In fact you have absolutely no advantage
> over putting all logs of a day into a single file in this
> case.

The readers can do a binary search. For that matter, so could
the program. (But again depending on the application, there may
be so few files that it isn't worth it.)

> > But this method looks very awkward. Is there another way to
> > do this(get the max number for a series of similar files)?

> No. And since most file systems do not maintain a defined sort
> ordering, there is no cheaper solution in general. You could
> scan the entire directory content, but this is in the same
> order.

> > My applicaiton is running on windows platform but did not
> > using MFC function very much.

> That makes no difference here.

> Using rotating logs with a fixed time slice is straight
> forward to implement, although in case of application
> restarts. You could use a simple and fast hash function on the
> time stamp, that controls log file switches.

You don't even need that. On program start-up, it's easy to
calculate the last rotation time from current time; just open
that file for append. There is some argument, however, for
always opening a new log file on program start-up.

> Every time the hash changes a virtual method that switches the
> log could be invoked. Only his method implements the full
> rendering of the file name scheme.
> This makes it very easy and with good performance to implement
> different cycle times, e.g once per week, once per day and
> once per hour.

> And if you are even smarter you could add a functionality that
> cleans up old log automatically once they exceed a configured
> age. This prevents from the common issue of full volumes.

This is usually done by means of a cronjob (or whatever it is
called under Windows---it surely exists), using a fairly simple
script. Typically, the log files will go through a stage where
they are compressed, before being completely deleted. (E.g.
compress anything older than a day, and delete anything older
than a week.)

--
James Kanze

==============================================================================
TOPIC: RVO
http://groups.google.com/group/comp.lang.c++/t/a41ed66263ac91f0?hl=en
==============================================================================

== 1 of 2 ==
Date: Tues, Sep 29 2009 12:50 am
From: James Kanze


On Sep 29, 6:53 am, Gareth Owen <gwo...@gmail.com> wrote:
> As I think I understand it, RVO requires a hidden parameter.

In practice, returning a class type in general requires a hidden
parameter, or at least uses one in most implementations.

> Assuming that the call has access to the declaration, and not
> the definition, how can the compiler possibly know whether the
> compilation of the function used RVO, and thus whether to pass
> a hidden argument to facilitate RVO.

> That being the case, is RVO possible in library functions?

There's no difference in the calling conventions when RVO is
concerned. (There's also nothing that says that the compiler
can't know about what happens in the library functions.)

--
James Kanze


== 2 of 2 ==
Date: Tues, Sep 29 2009 1:17 am
From: gwowen


> There's no difference in the calling conventions when RVO is
> concerned.  

That's what I missed... that the standard calling convention
specifies to use a hidden argument for all arguments of a certain
size, and that RVO merely uses this. In my head, the hidden argument
only existed when the compiler used RVO.

Thanks James and Alf.

==============================================================================
TOPIC: C++ - expected unqualified-id before " /" token?
http://groups.google.com/group/comp.lang.c++/t/7cb3f7b37b9e0b0d?hl=en
==============================================================================

== 1 of 5 ==
Date: Tues, Sep 29 2009 3:04 am
From: hon123456


Dear all,
Please bear with me, I am new to C++ programming to
windows . What I am trying is build a simple window. And I am using g+
+ .I have the following program run with the error:
simplewnd.cpp:221: error: expected unqualified-id before " /"
token.

The code is as follows:

//
=============================================================================
//SIMPLE WINDOW - Copyright © 2000,2005 Ken Fitlike
//
=============================================================================
//API functions used:
CreateWindowEx,DefWindowProc,DispatchMessage,GetMessage,
//
GetSystemMetrics,LoadImage,MessageBox,PostQuitMessage,RegisterClassEx,
//ShowWindow,UpdateWindow,TranslateMessage,WinMain.
//
=============================================================================
//This creates a window, half the height and half the width of the
desktop
//which is centred on the desktop.
//
//WinMain is the entry point function for winapi applications
(equivalent to
//main). _tWinMain is a placeholder for WinMain (non-unicode fn) or
wWinMain
//(unicode) but, since there is currently no wWinMain defined for
MinGW just
//use WinMain; if a unicode command line string is required then use
the
//GetCommandLine api function.
//
=============================================================================
#include <windows.h> //include all the basics
#include <tchar.h> //string and other mapping macros
#include <string>

//define an unicode string type alias
typedef std::basic_string<TCHAR> ustring;
//
=============================================================================
//message processing function declarations
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);

//non-message function declarations
inline int ErrMsg(const ustring&);
//
=============================================================================
int WINAPI WinMain(HINSTANCE hInst,HINSTANCE,LPSTR pStr,int nCmd)
{
ustring classname=_T("SIMPLEWND");
WNDCLASSEX wcx={0}; //used for storing information about the wnd
'class'

wcx.cbSize = sizeof(WNDCLASSEX);
wcx.lpfnWndProc = WndProc; //wnd Procedure pointer
wcx.hInstance = hInst; //app instance
//use 'LoadImage' to load wnd class icon and cursor as it supersedes
the
//obsolete functions 'LoadIcon' and 'LoadCursor', although these
functions will
//still work. Because the icon and cursor are loaded from system
resources ie
//they are shared, it is not necessary to free the image resources
with either
//'DestroyIcon' or 'DestroyCursor'.
wcx.hIcon = reinterpret_cast<HICON>(LoadImage
(0,IDI_APPLICATION,
IMAGE_ICON,
0,0,LR_SHARED));
wcx.hCursor = reinterpret_cast<HCURSOR>(LoadImage(0,IDC_ARROW,
IMAGE_CURSOR,
0,0,LR_SHARED));
wcx.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);
wcx.lpszClassName = classname.c_str();
//the window 'class' (not c++ class) has to be registered with the
system
//before windows of that 'class' can be created
if (!RegisterClassEx(&wcx))
{
ErrMsg(_T("Failed to register wnd class"));
return -1;
}

int desktopwidth=GetSystemMetrics(SM_CXSCREEN);
int desktopheight=GetSystemMetrics(SM_CYSCREEN);

HWND hwnd=CreateWindowEx(0, //extended styles
classname.c_str(), //name: wnd 'class'
_T("Simple Window"), //wnd title
WS_OVERLAPPEDWINDOW, //wnd style
desktopwidth/4, //position:left
desktopheight/4, //position: top
desktopwidth/2, //width
desktopheight/2, //height
0, //parent wnd handle
0, //menu handle/wnd id
hInst, //app instance
0); //user defined info
if (!hwnd)
{
ErrMsg(_T("Failed to create wnd"));
return -1;
}

ShowWindow(hwnd,nCmd);
UpdateWindow(hwnd);
//start message loop - windows applications are 'event driven' waiting
on user,
//application or system signals to determine what action, if any, to
take. Note
//that an error may cause GetMessage to return a negative value so,
ideally,
//this result should be tested for and appropriate action taken to
deal with
//it(the approach taken here is to simply quit the application).
MSG msg;
while (GetMessage(&msg,0,0,0)>0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return static_cast<int>(msg.wParam);
}
//
=============================================================================
LRESULT CALLBACK WndProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM
lParam)
{
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage(0); //signal end of application
return 0;
default:
//let system deal with msg
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
}
//
=============================================================================
inline int ErrMsg(const ustring& s)
{
return MessageBox(0,s.c_str(),_T("ERROR"),MB_OK|MB_ICONEXCLAMATION);
}
//
=============================================================================


== 2 of 5 ==
Date: Tues, Sep 29 2009 3:35 am
From: "Balog Pal"

"hon123456" <peterhon321@yahoo.com.hk>
simplewnd.cpp:221: error: expected unqualified-id before " /" token.

The code is as follows:

your code has only 141 lines even with those extra line breaks the news
inserted...


== 3 of 5 ==
Date: Tues, Sep 29 2009 3:42 am
From: hon123456


On 9月29日, 下午6時35分, "Balog Pal" <p...@lib.hu> wrote:
> "hon123456" <peterhon...@yahoo.com.hk>
>  simplewnd.cpp:221: error: expected unqualified-id before " /" token.
>
> The code is as follows:
>
> your code has only 141 lines even with those extra line breaks the news
> inserted...

That is the problem . So I guess the number is representing other
meaning. for other warning,it will like this:
simplewnd.cpp:221:3 error: expected unqualified-id before " /"
But for this error it only show as follows:
simplewnd.cpp:221: error: expected unqualified-id before " /"

So I cannot find out which line is having the problem.
Please help.

== 4 of 5 ==
Date: Tues, Sep 29 2009 4:07 am
From: "Fred Zwarts"


"hon123456" <peterhon321@yahoo.com.hk> wrote in message news:76941cce-7325-4bc4-8520-c48b60fbfced@w37g2000prg.googlegroups.com...
> Dear all,
> Please bear with me, I am new to C++ programming to
> windows . What I am trying is build a simple window. And I am using g+
> + .I have the following program run with the error:
> simplewnd.cpp:221: error: expected unqualified-id before " /"
> token.

I don't know this error message, but may be it is the following:

> The code is as follows:
>
> //
> =============================================================================

The last line is not valid C++. The next line starts with /. The compiler expected something to follow the last =.

> //SIMPLE WINDOW - Copyright © 2000,2005 Ken Fitlike
> //
> =============================================================================

Again an invalid line with multiple = followed by /.

> //API functions used:

== 5 of 5 ==
Date: Tues, Sep 29 2009 4:42 am
From: "Francesco S. Carta"


On 29 Set, 12:42, hon123456 <peterhon...@yahoo.com.hk> wrote:
> On 9月29日, 下午6時35分, "Balog Pal" <p...@lib.hu> wrote:
>
> > "hon123456" <peterhon...@yahoo.com.hk>
> > simplewnd.cpp:221: error: expected unqualified-id before " /" token.
>
> > The code is as follows:
>
> > your code has only 141 lines even with those extra line breaks the news
> > inserted...
>
> That is the problem . So I guess the number is representing other
> meaning. for other warning,it will like this:
> simplewnd.cpp:221:3 error: expected unqualified-id before " /"
> But for this error it only show as follows:
> simplewnd.cpp:221: error: expected unqualified-id before " /"
>
> So I cannot find out which line is having the problem.
> Please help.

Hi there,
your code runs fine on my GCC 3.4.5 (after having fixed all those
broken // comments).

To spot your actual problem, try adding an evident error at the end of
your program, and then check out its line number in the corresponding
error message.

Maybe something weird is going on, such as an "unexpected" macro being
expanded. If you end up having errors with line numbers beyond that
added-last-error's line number, then probably something is going wrong
with your compiler, IDE or whatsoever.

Everything right off the top of my head, no guarantees.

In any case, take the habit to use /* */ comments when posting code
here.

To ensure that no comment gets broken, put the stop-comment character
combination on a separate line, in this way:

/* incredibly long comment
*/

In that way, you are ensured that no comment gets ever broken, and
will help people testing your code.

Hope that helps.

Have good time,
Francesco
--
Francesco S. Carta, hobbyist
http://fscode.altervista.org

==============================================================================
TOPIC: A few questions about singletons...
http://groups.google.com/group/comp.lang.c++/t/dd7f3af258a800cd?hl=en
==============================================================================

== 1 of 2 ==
Date: Tues, Sep 29 2009 4:21 am
From: Michael Doubez


On 25 sep, 20:45, Joshua Maurice <joshuamaur...@gmail.com> wrote:
> On Sep 25, 1:05 am, Michael Doubez <michael.dou...@free.fr> wrote:
>
> > You can use a Meyer singleton which solve the initialisation order
> > issue:
>
> > static CSingleton& GetInstance()
> > {
> >  CSingleton static_instance;
>
> >  return static_instance;
>
> > }
>
> > And the cleanup is made at termination. The cleanup of a singleton is
> > delicate because you don't known how is currently using it (it is even
> > worse when in a DLL); you should let the system decide when it is no
> > longer needed.
>
> Suffice to say, actually suggesting the simplest Meyer's singleton is
> bad advice. Frankly, I've made so many mistakes on this topic recently
> that I'll just point you to the thread where someone more
> knowledgeable than me suggests more correct ways to do this.
>
> http://groups.google.com/group/comp.lang.c++/browse_thread/thread/bca...
>
> 1- Your singleton may cause static deinit issues. If you can leak it,
> just leak it. Otherwise, it'll work correctly if all other statics
> call getSingleton in their constructors. This will guarantee correct
> destruction order, Last In First Out.

You mean if a static gets latter on (after its initialisation) a
reference on the singleton ? This is not limited to singleton but to
every storage management; have seen some case where the singleton is
resetable causing that kind of problem but it is more related to the
logic of the program(er).

Betting on a singleton with the longest lifetime does guarantee your
program doesn't crash for this reason but it is IMHO at best a patch.

> 2- It's not thread-safe. There's the simple ways to do this correctly
> which come with the caveat that "No nontrivial threads during static
> init".

That is alas true. The next standard does provide atomic operations
which will ease that pain (I hope).

> Alternatively, use the more complex designs of Chris M.
> Thomasson, which just guarantee single correct construction with
> minimal overhead. There are several, depending on platform, and
> exactly what guarantees you want.

I have seen the code mentioned and it supposes that initialisation of
the mutex is atomic.

If I replace in the header:
typedef HANDLE pthread_mutex_t;
#define PTHREAD_MUTEX_INITIALIZER CreateMutex(/* params */)
You see the problem with:
static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;

In fact, it is possible that two mutex will be created and the mutex
is then useless.

In practice, IIRC it does work with the usual libpthread.

> Short version: Actually doing a correct singleton in C++ is hard (tm).

It is hard and not really useful in most cases.

Unless you are paid per "pattern-point". :)

--
Michael


== 2 of 2 ==
Date: Tues, Sep 29 2009 5:02 am
From: Nick Keighley


On 25 Sep, 06:40, karthik <karthik....@gmail.com> wrote:
> Hi,
>
> Idea of a singleton class is to have a common instance which can be
> used in other objects. If someone creates or gets an object, he has to
> delete or release it also.
>
> > 1) what is the interview approved way to clean up the created object? Having
> > a static "clean up" method that the user is responsible for calling seems
> > completely retarded and anti-encapsulation.
>
> I couldn't really understand what does the above mean by retarded and
> anti-encapsulation method. If some user creates an object, he should
> delete it somehow. Since interface of the class suggests the person to
> use "GetInstance", it should have reverse method like
> "ReleaseInstance" which makes sure deletion of instance will happen if
> no one is using the instance currently.
>
> * Initially there will be no instance.
>
> * Some user calls "GetInstance", static userCount variable will be
> one, hence an object will be created. Further calls to "GetInstance"
> will simply
>   increase userCount.
>
> * "ReleaseInstance" decrements userCount and deletes the object, if
> userCount is zero.
>
> Missing of calling "ReleaseInstance" will lead to Memory leak,
> obviously. Static "userCount" variable is un-avoidable. But It won't
> cause memory leak.

that's an unusual form of the singleton pattern. I've never seen
one where each user had to do a ReleaseInstance(). The GoF one doesn't

==============================================================================
TOPIC: list.front() question
http://groups.google.com/group/comp.lang.c++/t/1905a1f360fa414a?hl=en
==============================================================================

== 1 of 4 ==
Date: Tues, Sep 29 2009 4:35 am
From: coolchap


Hi,
I have a query regarding the front() function in list. Lets say
that I have a list of pointers

list <ptr *> aListofPtrs;

Size of aListPtrs is zero

now i get the first element... and call a function in the class ptr..
lets say getSomething()

aListofPtrs.front()->getSomething()

As for me, this should return a nullpointer exception, But instead the
program was compiled and ran too.. getSomething() returned an arbitary
value.

I just want to understand how the front() method works in case the
list has zero elements and we call the front() method.

Regards,
Prashant


== 2 of 4 ==
Date: Tues, Sep 29 2009 4:41 am
From: Michael Doubez


On 29 sep, 13:35, coolchap <b.prash...@gmail.com> wrote:
> Hi,
>       I have a query regarding the front() function in list. Lets say
> that I have a list of pointers
>
> list <ptr *> aListofPtrs;
>
> Size of aListPtrs is zero
>
> now i get the first element... and call a function in the class ptr..
> lets say getSomething()
>
> aListofPtrs.front()->getSomething()
>
> As for me, this should return a nullpointer exception,

Assuming that list<ptr*>::front() returns NULL when empty.

> But instead the
> program was compiled and ran too.. getSomething() returned an arbitary
> value.
>
> I just want to understand how the front() method works in case the
> list has zero elements and we call the front() method.

Because list<ptr*>::front() returns a random value when empty. You are
using a uninitialised pointer, this is undefined behavior.

In fact, since front() returns a reference, calling it may be
undefined behavior in itself.

--
Michael


== 3 of 4 ==
Date: Tues, Sep 29 2009 5:20 am
From: pjb@informatimago.com (Pascal J. Bourguignon)


coolchap <b.prashant@gmail.com> writes:

> Hi,
> I have a query regarding the front() function in list. Lets say
> that I have a list of pointers
>
> list <ptr *> aListofPtrs;
>
> Size of aListPtrs is zero
>
> now i get the first element... and call a function in the class ptr..
> lets say getSomething()
>
> aListofPtrs.front()->getSomething()
>
> As for me, this should return a nullpointer exception, But instead the
> program was compiled and ran too.. getSomething() returned an arbitary
> value.
>
> I just want to understand how the front() method works in case the
> list has zero elements and we call the front() method.

There's no way to understand how ti works whe the list is empty,
because it is not in the contract.

You must always test whether the list is not empty before using
front(). It is like in C where you must always test whether there
won't be an overflow before using a+b, or whether a pointer is not
null before using *p.


ALWAYS WRITE:

if(not list.empty()){
list.front()->getSomething();
}

if(((a>=0) and (INT_MAX-a<=b)) or ((a<0) and (INT_MIN-a>=b)))
error("overflow");
}else{
int c=a+b;
}

if(p!=0){
(*p)=42;
}


NEVER WRITE:

list.front()->getSomething();

int c=a+b;

(*p)=42;

ALONE.


(Then of course, if your compiler is smart enough, it may determine
that some of these tests are dead code and eliminate them).

--
__Pascal Bourguignon__


== 4 of 4 ==
Date: Tues, Sep 29 2009 5:33 am
From: prashant


On Sep 29, 2:20 pm, p...@informatimago.com (Pascal J. Bourguignon)
wrote:
> coolchap <b.prash...@gmail.com> writes:
> > Hi,
> >       I have a query regarding the front() function in list. Lets say
> > that I have a list of pointers
>
> > list <ptr *> aListofPtrs;
>
> > Size of aListPtrs is zero
>
> > now i get the first element... and call a function in the class ptr..
> > lets say getSomething()
>
> > aListofPtrs.front()->getSomething()
>
> > As for me, this should return a nullpointer exception, But instead the
> > program was compiled and ran too.. getSomething() returned an arbitary
> > value.
>
> > I just want to understand how the front() method works in case the
> > list has zero elements and we call the front() method.
>
> There's no way to understand how ti works whe the list is empty,
> because it is not in the contract.
>
> You must always test whether the list is not empty before using
> front().  It is like in C where you must always test whether there
> won't be an overflow before using a+b, or whether a pointer is not
> null before using *p.
>
> ALWAYS WRITE:
>
>    if(not list.empty()){
>       list.front()->getSomething();
>    }
>
>    if(((a>=0) and (INT_MAX-a<=b)) or ((a<0) and (INT_MIN-a>=b)))
>       error("overflow");
>    }else{
>       int c=a+b;
>    }
>
>    if(p!=0){
>        (*p)=42;
>    }
>
> NEVER WRITE:
>
>       list.front()->getSomething();
>
>       int c=a+b;
>
>       (*p)=42;
>
> ALONE.
>
> (Then of course, if your compiler is smart enough, it may determine
> that some of these tests are dead code and eliminate them).
>
> --
> __Pascal Bourguignon__

thanks for the replies...

As mentioned its an undefined behaviour, but i had expected it to
throw a nullpointer exception which would have led me to detect the
error. anyways somethings need to be checked before using it..

Thanks,
Regards,
Prashant

==============================================================================
TOPIC: Const Static variables set at run time and a design question.
http://groups.google.com/group/comp.lang.c++/t/b605293a5a67061f?hl=en
==============================================================================

== 1 of 2 ==
Date: Tues, Sep 29 2009 4:55 am
From: Jim


Hi,
I've a set of data which has two spectra associated with each
position. For each spectra you convert from an array position to a
real value using an array offset, a delta and a velocity offset.
These are common to all spectra of the same type and don't change
through the program's run. Unfortunately I don't know them until I
load the file, unless I hard code them and I don't want to do that.
Only solution I can think of is to have a user-defined object called
conversion which has const members set in the constructor and const
accessor methods and have a static object in each type of the specific
spectra classes which inherit from the spectra base class. Does this
seem correct?

Thanks,
Jim


== 2 of 2 ==
Date: Tues, Sep 29 2009 5:49 am
From: Marcel Müller


Hi,

Jim wrote:
> I've a set of data which has two spectra associated with each
> position. For each spectra you convert from an array position to a
> real value using an array offset, a delta and a velocity offset.
> These are common to all spectra of the same type and don't change
> through the program's run. Unfortunately I don't know them until I
> load the file, unless I hard code them and I don't want to do that.

so they are NOT const static because they change while the application runs.

> Only solution I can think of is to have a user-defined object called
> conversion which has const members set in the constructor and const
> accessor methods and have a static object in each type of the specific
> spectra classes which inherit from the spectra base class. Does this
> seem correct?

Something like that is possible. But I would keep conversion as simple
as possible:

struct conversion
{ double offset;
double whatever;
};

class SpectraBase
{
public virtual const conversion& GetConversion() const = 0;
...
};


Marcel


==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.c++"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.c++?hl=en

To unsubscribe from this group, send email to comp.lang.c+++unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.c++/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

No comments: