question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,320,444 | 1,321,000 | Ropes: what's "large enough to benefit from cache effects"? | From Wikipedia:
The main disadvantages are greater
overall space usage and slower
indexing, both of which become more
severe as the tree structure becomes
larger and deeper. However, many
practical applications of indexing
involve only iteration over the
string, which remains fast as long as
the leaf nodes are large enough to
benefit from cache effects.
I'm implementing a sort of compromise between ropes and strings. Basically it's just ropes, except that I'm flattening concatenation objects into strings when the concatenated strings are short. There are a few reasons for this:
The benefits of concatenation objects are minimal when the concatenated strings are short (it doesn't take too long to concatenate two strings in their normal form).
Doing this reduces the largeness/depth of the tree (reducing the downsides of ropes).
Doing this increases the size of the leaf nodes (to take better advantage of cache).
However, as length gets longer, the advantages of the ropes also decrease, so I'd like to find some compromise. The "sweet spot" logically seems to be around where "the leaf nodes are large enough to benefit from cache effects". The problem is, I don't know how large that is.
EDIT: While I was writing this, it occurred to me that the ideal size would be the size of a cache page, because then the rope only causes cache misses when they would happen anyway in a string. So my second question is, is this reasoning correct? And is there a cross-platform way to detect the size of a cache page?
My target language is C++.
| The limit case for a rope-like string would be built on top of a std::list<char>. That obviously isn't very effective. When iterating, you are likely to have have one cache miss per "leaf"/char. As the number of characters per leaf goes up, the average number of misses goes down, with a discontinuity as soon as your leaf allocation exceeds a single cache line.
It might still be a good idea to have larger leafs; memory transfers in cache hierarchies might have different granularities at different levels. Also, when targetting a mixed set of CPUs (i.e. consumer PCs) a leaf size which is a higher power of two will be an integral multiple of the cache line size on more machines. E.g. if you're addressing CPUs with 16 and 32 byte cache lines, 32 bytes would be the better choice, as it's an always integral number of cache lines. Wasting half a cache line is a shame.
|
1,320,460 | 1,321,651 | How do you insert into a sorted linked list? |
Possible Duplicate:
LinkedList “node jump”
I just need to have a linked list in order by name. I can only get it as far as 1st, 3rd, 5th, .. nodes. I just can't think this far. I want to be a C++ programmer but if I can't understand this is their any hope? STL containers std::lists are not an option for me at this point as a student. What you see in the list function is what I am TRYING to understanding.
list::node::node(const winery &winery) : item( winery.getName(), winery.getLocation(),
winery.getAcres(), winery.getRating() ), nextByName( NULL ), nextByRating( NULL )
{
}
void list::insert(const winery& winery)
{
node *current_node = new node( winery ); // but came here and did this so it has new info!
node *next_node = NULL;
node *tail_node = current_node;
if ( headByName == NULL ) // then we are here for the first item
{
headByName = current_node; // the list ptrs will have the first node's address.
headByRating = current_node;
}
while ( headByName->nextByName != NULL )
{
headByName->nextByName = tail_node;
tail_node = next_node;
//next_node = current_node;
}
tail_node = new node( winery );
headByName->nextByName = tail_node;
}
And the pointers that are available to me:
struct node
{
winery item;
node * nextByName;
node * nextByRating;
};
class list
{
...
private:
node * headByName;
node * headByRating;
};
| Of course there's hope, we all have to start somewhere! :)
First of all, I must point out a dangerous practice in your implementation that my own students used, and it usually resulted in lots of head scratching to find the problem:
while ( headByName->nextByName != NULL )
{
headByName->nextByName = tail_node;
tail_node = next_node;
//next_node = current_node;
}
Don't use a list member like headByName as your iterating variable within your loop unless it is absolutely necessary. You should find the appropriate node first using a local variable, and then modify that node.
That said, Rob Kennedy is right that you should handle the name and rating separately (in other words a 'pure' implementation would have two instances of a generic list class that is unaware of what 'name' and 'rating' mean), however I assume the interfaces for list, node and function above were given to you in the assignment (if not, disregard the rest of my answer :) ).
Given the above interfaces, my approach would be as follows:
void list::insert(const winery& winery)
{
node* wineryNode = new node(winery);
assert (wineryNode);
// Find a node in the list with a name greater than wineryNode's
node* prevNode = NULL;
node* searchNode = headByName; // Note: not using the list member itself to iterate but a local variable
while (NULL != searchNode &&
searchNode.winery.getName() < wineryNode.winery.getName())
{
// Keep iterating through the list until there are no more items, or the right node is found
prevNode = searchNode;
searchNode = searchNode->nextByName;
}
/* At this point searchNode is either NULL
or it's name is greater than or equal to wineryNode's */
// Check for the case where the list was empty, or the first item was what we wanted
if (NULL == prevNode)
{
headByName = wineryNode;
}
else
{
// prevNode is not NULL, and it's Name is less wineryNode's
prevNode-> nextByName = wineryNode;
}
wineryNode->nextByName = searchNode;
/* Now you just need to insert sorted by rating using the same approach as above, except initialize searchNode to headByRating,
and compare and iterate by ratings in the while loop. Don't forget to reset prevNode to NULL */
}
|
1,320,899 | 1,321,128 | How to find the menu item (if any) which opens a given HMENU when activated? | I'd like to implement a function with the prototype
/* Locates the menu item of the application which caused the given menu 'mnu' to
* show up.
* @return true if the given menu 'mnu' was opened by another menu item, false
* if not.
*/
bool getParentMenuItem( HMENU mnu, HMENU *parentMenu, int *parentMenuIdx );
Given a HMENU handle, I'd like to be able to find out which menu item (if any) in the application opened it. This is basically the reverse of the GetSubMenu function.
My current approach is to look into each HMENU of the top level windows of the application and check for whether I can find a menu item which would open the given sub menu when activated. I do this recursively, using GetMenuItemCount/GetSubMenu.
This is rather inefficient though, and it fails for menus which are opened by context menu items. Hence, I'm wondering:
Does anybody have a nice idea how to find the menu item (if any) which opens a given HMENU when activated?
UPDATE: An idea which just came to my mind; it should be possible (using the SetWindowsHookEx function) to install a hook which gets notified of all input events which happened in a menu. Whenever a menu item activation is detected, memorize the menu item (identified by a (HMENU,int) pair) and the HMENU which will get opened by the menu item in a global map. The getParentMenuItem function above could then simply perform a lookup into the map.
UPDATE to the update: The hooking idea described in the update above won't work as it is since it will of course only recognize menu item -> menu associations for items which have been activated at some point.
This feels a bit ugly though since it reqiures me to keep a lot of state (the map); are there any easier possibilities?
| You could try setting MENUINFO.dwMenuData to the parent menu handle for all menus you create in your application:
MENUINFO mi;
mi.cbSize = sizeof(MENUINFO);
mi.dwMenuData = (ULONG_PTR)<parent HMENU if this is a sub menu>
mi.fMask = MIM_MENUDATA;
SetMenuInfo(hCreatedMenu, &mi);
Then you only need to query this dwMenuData field in your function:
bool getParentMenuItem(HMENU mnu, HMENU *parentMenu, int *parentMenuIdx)
{
MENUINFO mi;
mi.cbSize = sizeof(MENUINFO);
mi.fMask = MIM_MENUDATA;
if (!GetMenuInfo(mnu,&mi) || mi.dwMenuData == 0)
return false;
*parentMenu = (HMENU)mi.dwMenuData;
// not sure how or why you need the parentMenuIdx, but you should be able
// to derive that from the parent HMENU
return true;
}
Edit: If you don't have control over how all menus are created, you could use a WH_CALLWNDPROC hook to trap when a menu is first created. A good article (with source code) describes how this can be done - you could then look at trying to inject the parent HMENU into the created menu using the method described above.
|
1,320,912 | 1,320,946 | How to terminate a QThread? | QThread::terminate() documentation states that it is discouraged to terminate a thread by calling this function.
In my program, I need to terminate a thread before it finishes execution. The thread is performing some heavy computation and I want the user to have control to stop calculation.
How can I do that instead of calling QThread::terminate()?
| Set a flag from outside the thread that is checked by the computation within the thread and stop the calculation if the flag is set.
|
1,320,915 | 1,323,895 | Why does Visual Studio 2008 highlight internal as a keyword in C++ code? | I'm porting VC++7 codebase to VC++9. Surprisingly Visual Studio 2008 highlights internal as a keyword in C++ code but looks like it is not really treated as such.
What is this - a bug in VS, an environment setting I haven't found yet, or a sign that I will no longer be allowed to use internal as a regular identifier in some upcoming version? What's my best move in this situation?
| Just ignore it. The "problem" is just that not all parts of Visual Studio properly distinguish between C++ and C++/CLI. So certain C++/CLI keywords get highlighted even in plain native C++. (array is another one).
This only affects syntax highlighting, not the actual compiler.
So the only reason to avoid these words is if you 1) find the bad syntax highlighting too annoying, or 2) plan on porting your application to C++/CLI.
|
1,321,062 | 1,321,169 | Object layout in case of virtual functions and multiple inheritance | I was recently asked in an interview about object layout with virtual functions and multiple inheritance involved.
I explained it in context of how it is implemented without multiple inheritance involved (i.e. how the compiler generated the virtual table, insert a secret pointer to the virtual table in each object and so on).
It seemed to me that there was something missing in my explanation.
So here are questions (see example below)
What is the exact memory layout of the object of class C.
Virtual tables entries for class C.
Sizes (as returned by sizeof) of object of classes A, B and C. (8, 8, 16 ?? )
What if virtual inheritance is used. Surely the sizes and virtual table entries should be affected ?
Example code:
class A {
public:
virtual int funA();
private:
int a;
};
class B {
public:
virtual int funB();
private:
int b;
};
class C : public A, public B {
private:
int c;
};
Thanks!
| The memory layout and the vtable layout depend on your compiler. Using my gcc for instance, they look like this:
sizeof(int) == 4
sizeof(A) == 8
sizeof(B) == 8
sizeof(C) == 20
Note that sizeof(int) and the space needed for the vtable pointer can also vary from compiler to compiler and platform to platform. The reason why sizeof(C) == 20 and not 16 is that gcc gives it 8 bytes for the A subobject, 8 bytes for the B subobject and 4 bytes for its member int c.
Vtable for C
C::_ZTV1C: 6u entries
0 (int (*)(...))0
4 (int (*)(...))(& _ZTI1C)
8 A::funA
12 (int (*)(...))-0x00000000000000008
16 (int (*)(...))(& _ZTI1C)
20 B::funB
Class C
size=20 align=4
base size=20 base align=4
C (0x40bd5e00) 0
vptr=((& C::_ZTV1C) + 8u)
A (0x40bd6080) 0
primary-for C (0x40bd5e00)
B (0x40bd60c0) 8
vptr=((& C::_ZTV1C) + 20u)
Using virtual inheritance
class C : public virtual A, public virtual B
the layout changes to
Vtable for C
C::_ZTV1C: 12u entries
0 16u
4 8u
8 (int (*)(...))0
12 (int (*)(...))(& _ZTI1C)
16 0u
20 (int (*)(...))-0x00000000000000008
24 (int (*)(...))(& _ZTI1C)
28 A::funA
32 0u
36 (int (*)(...))-0x00000000000000010
40 (int (*)(...))(& _ZTI1C)
44 B::funB
VTT for C
C::_ZTT1C: 3u entries
0 ((& C::_ZTV1C) + 16u)
4 ((& C::_ZTV1C) + 28u)
8 ((& C::_ZTV1C) + 44u)
Class C
size=24 align=4
base size=8 base align=4
C (0x40bd5e00) 0
vptridx=0u vptr=((& C::_ZTV1C) + 16u)
A (0x40bd6080) 8 virtual
vptridx=4u vbaseoffset=-0x0000000000000000c vptr=((& C::_ZTV1C) + 28u)
B (0x40bd60c0) 16 virtual
vptridx=8u vbaseoffset=-0x00000000000000010 vptr=((& C::_ZTV1C) + 44u)
Using gcc, you can add -fdump-class-hierarchy to obtain this information.
|
1,321,137 | 1,321,154 | Convert String containing several numbers into integers | I realize that this question may have been asked several times in the past, but I am going to continue regardless.
I have a program that is going to get a string of numbers from keyboard input. The numbers will always be in the form "66 33 9" Essentially, every number is separated with a space, and the user input will always contain a different amount of numbers.
I'm aware that using 'sscanf' would work if the amount of numbers in every user-entered string was constant, but this is not the case for me. Also, because I'm new to C++, I'd prefer dealing with 'string' variables rather than arrays of chars.
| I assume you want to read an entire line, and parse that as input. So, first grab the line:
std::string input;
std::getline(std::cin, input);
Now put that in a stringstream:
std::stringstream stream(input);
and parse
while(1) {
int n;
stream >> n;
if(!stream)
break;
std::cout << "Found integer: " << n << "\n";
}
Remember to include
#include <string>
#include <sstream>
|
1,321,407 | 1,321,818 | Programming resources for C++ in Linux | I am new (in a way) to C++ programming. I would like to start doing development in Linux using C and/or C++ as programming languages. I have done some development for a while in Java.
Unfortunately I am not sure where to start. Can you point me to some good resources, and also give me an outline as to what would be the primary difference between C and C++ in Windows and Linux?
Any special steps I need to do to get started? Also any good IDEs. I plan to use Eclipse currently. I am using Kubuntu (version 9.x).
| It is good that you are using a Linux platform as it will help you to program as per the C and C++ standards.
I would recommend
vi/vim --> text editor
gcc --> C compiler
g++ --> C++ compiler
gdb --> Command line debugger
ddd --> GUI debugger
I use the above mentioned tools. If you are hell-bent on IDEs, you can use the ones mentioned by Chen Levy
|
1,321,467 | 1,321,479 | Which programming technique helps you most to avoid or resolve bugs before they come into production | I don't mean external tools. I think of architectural patterns, language constructs, habits. I am mostly interested in C++
| I find the following rather handy.
1) ASSERTs.
2) A debug logger that can output to the debug spew, console or file.
3) Memory tracking tools.
4) Unit testing.
5) Smart pointers.
Im sure there are tonnes of others but I can't think of them off the top of my head :)
|
1,321,530 | 1,322,128 | How do I create synchronization mechanisms in managed shared memory segments? | I'm trying to have 2 processes communicate via an stl container - so I've decided to use the managed shared memory. I'm trying to implement some synchronisation between them - an interprocess_mutex for a start with a scoped_lock - but I'm not having much luck. How is it supposed to be done?
| I think the best solution is a container handler, and all access (getter/setter) to the container through the handler. So in this handler you could implement the synchronisation easily.
Salu2.
|
1,321,731 | 1,321,776 | How to use Winsock 2? | How do I use Windows Sockets 2 in Visual Studio 2008. I'm using precompiled headers, so far what I have tried is:
Included winsock2.h in my StdAfx.h file
and entered WS2_32.LIB as an additional dependency in Project Settings
I get these errors
------ Build started: Project: TestIVR, Configuration: Debug Win32 ------
Compiling...
main.cpp
c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(30) : error C2065: 'WSAEVENT' : undeclared identifier
c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(30) : error C2146: syntax error : missing ';' before identifier 'socketEvent'
c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(30) : error C2065: 'socketEvent' : undeclared identifier
c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(35) : error C2039: 'S_addr' : is not a member of 'in_addr'
c:\program files\microsoft sdks\windows\v6.0a\include\inaddr.h(22) : see declaration of 'in_addr'
c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(40) : error C2065: 'socketEvent' : undeclared identifier
c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(40) : error C3861: 'WSAEventSelect': identifier not found
Build log was saved at "file://c:\Documents and Settings\Hussain\My Documents\Visual Studio 2008\Projects\TestIVR\TestIVR\Debug\BuildLog.htm"
TestIVR - 6 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
By the way, if I include the winsock2.h in my main.cpp (where my main() function resides) then I get different errors
------ Build started: Project: TestIVR, Configuration: Debug Win32 ------
Compiling...
main.cpp
c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(36) : error C2039: 'S_addr' : is not a member of 'in_addr'
c:\program files\microsoft sdks\windows\v6.0a\include\inaddr.h(22) : see declaration of 'in_addr'
Build log was saved at "file://c:\Documents and Settings\Hussain\My Documents\Visual Studio 2008\Projects\TestIVR\TestIVR\Debug\BuildLog.htm"
TestIVR - 1 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Following is the content for my StdAfx.h header file
#pragma once
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <winsock2.h>
| You need to include winsock2.h before windows.h
|
1,321,735 | 1,321,770 | Learning C++ Example Problems | I am currently going though the process of learning C++ though reading programming books. I understand the concept but find a few days after reading, the concepts start to drift from my memory.
The only thing that keeps them there is working through examples/questions.
Are there any good sites or books that can be recommend which give a large number of examples/questions to work through, with explanations of what each example should help you learn?
| If your books don't give you tasks to chew on, get better books.
Look at those mentioned here.
|
1,322,125 | 1,362,409 | The Boost Statechart Library - how to implement time-consuming transitions | In our project we have UI and logic (which may be represented as a state machine). Transitions between some steps in this step machine are long (IO-bound). We don't want to steal our UI thread for all the time the transition is in progress. Therefore we are looking for a way to perform this transitions in a separate thread and then update the UI when the transition finishes.
I currently evaluate the boost statechart library as one of the options to implement such a logic and I'd like to ask what's the proper way of implementing such a long-time transitions functionality using it?
Thanks.
| Transitions between states should be triggered by an event, not a long operation.
If you have logic which has any long operations whatsoever, it would be better to put the UI into its own thread, otherwise you'll be unresponsive.
You can always have two independent state machines in their own threads, and then use inter-thread communications for each to trigger one another. Message-passing is probably the most reliable approach. (boost::interprocess::message_queue may be overkill but it would work)
|
1,322,243 | 1,980,436 | Is switch from MFC to QT or WTL (or other GUI toolkit) recommended for Windows CE development? | There are pretty many questions regarding C++ GUI toolkits for Windows, but they mostly apply to desktop OS versions.
I'm now starting a C++ project for Windows CE 5.0 VGA hand-held device, and thinking about what GUI library to choose. I have some experience using MFC in Windows CE projects, but there are some known weak points of MFC mentioned here at SO (e.g., pretty outdated technologies used, bad abstraction, overuse of C++ preprocessor, etc.). For desktop projects they recommend QT and WTL mostly. At the same time MFC has some characteristics to be still considerable for embedded development.
So, how do you think, is it reasonable to spent some resources learning new GUI toolkit to switch from MFC, and what toolkit would you recommend in this case? Or is MFC still the most considerable for Windows CE embedded development?
The most important characteristics of a toolkit are: moderate CPU and memory load, small runtime size, good object-oriented design, compliance with good modern C++ practices, steep learning curve, development speed, commercial look, handy debug and design tools.
(What is needed in the project: serial port communication, threads, plots and diagrams drawing, ActiveSync communication.)
| We have Qt 4.5 on Windows CE 5.0 project at finishing stage, so I try to tell about advantages / disadvantages of Qt developing comparing to MFC.
Qt Pluses:
Nice OOP design
Natively supported signals/slots abstraction allows develop more rapidly and easily
Qt supports many various features (GUI, filesystem, networking, threading, etc)
LGPL license allows develop commercial application for free
Open sourcecodes, examples, excellent documentation makes learning curve much, much stepper
Multiplatform library. We was able to run our application on device and desktop with Vista OS without any trouble. In 4.6 version Symbian support has been added
Qt minuses:
Pretty big binaries ( > 10 Mb for Core and Gui module with all features "on", but you can tweak library building and make libs smaller)
Big memory and CPU usage comparing to MFC
I think, that main advantage of MFC comparing to Qt it its minimal memory and CPU footprint. If this is not issue - choose Qt.
P.S. Com port communication and plot drawing not natively included in Qt, but LGPL Qt-based libraries exist, which give you such features (As example "Qwt" for plotting).
|
1,322,307 | 1,322,363 | How do I check if a process is running from c++ code? | I'm writing a C++ app that will communicate with another process via boost::interprocess, however I need to check if the other process is actually running first - as the other process is responsible for creating the inter-process shared memory. How do I check if the other process is running ?
folks, I'm specifically required to check other processes
| The managed_shared_memory ctor will throw an interprocess_exception in case it fails to open the given shared memory (assuming you passed open_only to the ctor). You could use the error code in the exception to test whether the shared memory is available or not.
All means to check whether a process is running (by looking at the process tree, testing for magic log files or whatever) suffer from a race condition which occurs if the remote process is running, but it didn't yet manage to setup the shared memory.
Update: If you only want to check whether a process is being executed by the operating system, then you need to walk the list of processes and consider each one. Here you can find an example how to do that.
A much easier, more portable, but less precise technique is to use lock files. Process A creates a magic 'lock file' in some location on startup, and deletes it as it terminates. Process B can then test for the existence of this file to determine whether Process A is running. A null-byte size file would be sufficient for this, but the file could also contain additional information which is helpful to Process B (such as the PID of Process A). However, there's a short time window at the very beginning of Process A at which no lock file exists - yet the process is running.
|
1,322,360 | 1,322,381 | is there such list control in c++ | I am using MFC.
I need a control just like listControl, it has such functions:
MyListControl mylistControl = new MyListControl();
mylistControl.setDataSource(...);
mylistControl.setSQLStatement("select a, b, c, d from table where a > 3");
and system will have a listControl which is populated with the data from database, and generate the corresponding columns a, b, c, d respectively.
If there is such kind of a control, please tell me.
If you have any suggestion, please let me know.
Thanks in advance!
| Depending on your platform you will need different code. You will need to use a GUI framework, there is no GUI standard library in the C++ language.
If you want Windows and C++ you can use MFC's CListCtrl, but this is not as powerful as you mentioned and you need to do your own data loading.
The more portable way would be to use Qt and it's QListView QSqlDatabase classes.
|
1,322,426 | 1,322,452 | Using stl containers without boost pointers | My company are currently not won over by the Boost libraries and while I've used them and have been getting them pushed through for some work, some projects due to their nature will not be allowed to use Boost. Basically libraries, like Boost, cannot be brought in for work so I am limited to the libraries available by default (Currently using Visual Studio 2005).
So... My question is, if I am unable to use Boost::shared_ptr and its little brothers, what is the alternative when using STL containers with pointers?
One option I see is writing a container class like a shared_ptr that looks after a given pointer, but I'd like to know if there are other alternatives first.
| If they're not going to accept boost, I presume other "not developed here" libraries are out of the question.
It seems to me you're left with two options:
Roll your own shared_ptr.
Use raw pointers, and manage the memory yourself.
Neither is ideal, and each comes with it's own pain. Your saving grace might be that you have all of the source to boost available to you. You can use it as a model for writing your own shared_ptr.
|
1,322,442 | 1,322,474 | Getting user temporary folder path in Windows | How I can get the user's temp folder path in C++? My program has to run on Windows Vista and XP and they have different temp paths. How I can get it without losing compatibility?
| Is there a reason you can't use the Win32 GetTempPath API?
http://msdn.microsoft.com/en-us/library/aa364992(VS.85).aspx
This API is available starting with W2K and hence will be available on all of your listed targets.
|
1,322,517 | 1,322,547 | Passing a modifiable parameter to c++ function | Provided, I want to pass a modifiable parameter to a function, what should I choose: to pass it by pointer or to pass it by reference?
bool GetFoo ( Foo& whereToPlaceResult );
bool GetFoo ( Foo* whereToPlaceResult );
I am asking this because I always considered it the best practice to pass parameter by reference (1), but after examining some local code database, I came to a conclusion, that the most common way is (2). Moreover, the man himself (Bjarne Stroustrup) recommends using (2). What are the [dis]advantages of (1) and (2), or is it just a matter of personal taste?
| I prefer a reference instead of a pointer when:
It can't be null
It can't be changed (to point to something else)
It mustn't be deleted (by whoever receives the pointer)
Some people say though that the difference between a reference and a const reference is too subtle for many people, and is invisible in the code which calls the method (i.e., if you read the calling code which passes a parameter by reference, you can't see whether it's a const or a non-const reference), and that therefore you should make it a pointer (to make it explicit in the calling code that you're giving away the address of your variable, and that therefore the value of your variable may be altered by the callee).
I personally prefer a reference, for the following reason:
I think that a routine should know what subroutine it's calling
A subroutine shouldn't assume anything about what routine it's being called from.
[1.] implies that making the mutability visible to the caller doesn't matter much, because the caller should already (by other means) understand what the subroutine does (including the fact that it will modify the parameter).
[2.] implies that if it's a pointer then the subroutine should handle the possibility of the parameter's being a null pointer, which may be extra and IMO useless code.
Furthermore, whenever I see a pointer I think, "who's going to delete this, and when?", so whenever/wherever ownership/lifetime/deletion isn't an issue I prefer to use a reference.
For what it's worth I'm in the habit of writing const-correct code: so if I declare that a method has a non-const reference parameter, the fact that it's non-const is significant. If people weren't writing const-correct code then maybe it would be harder to tell whether a parameter will be modified in a subroutine, and the argument for another mechanism (e.g. a pointer instead of a reference) would be a bit stronger.
|
1,322,578 | 1,322,663 | Win32 API for getting the language(localization info) of the OS? | Can anybody please help me with how to get the language(english,chinese etc) of Windows OS through win32 API(C/C++)??
Thanks,
Sourabh
| You can get the default user locale (which I think is what you're asking) using GetUserDefaultLCID. This will give you an ID which can be used to determine the culture. See here for a table containing IDs and the cultures they represent.
For Vista or Windows 7, Microsoft recommend GetUserDefaultLocaleName.
|
1,323,042 | 1,323,112 | problems with global variables in shared library project (C++) | i have a problem with global variables in a c++ shared library project. my library has to be working as a standard g++ shared library (.so) as well as a dll. i did this by creating files libiup_dll.cpp and libiup_dll.h, where i have something like
#ifdef BUILD_DLL
// code for the dll: wrapper functions around the classes in my shared library
#endif
in my dll, i need functions setloglevel(int) and geterrormsg(). in all my classes, i'd then append to a global variable errormsg all error messages. this variable should then be returned by the geterrormsg() function. i implemented this by using
std::string errormsg;
int loglevel;
in libiup_dll.h (outside and #ifdefs, so it should be globally available), and then putting
extern std::string errormsg;
extern int loglevel;
in my classes' .h files (outside the class, at the top of the files)
now i have two problems:
1) when compiling a command line program with g++, which uses my library, i get errors
Building target: libiup_test Invoking:
GCC C++ Linker g++
-L"/home/hilboll/src/libiup/Release" -L/usr/local/lib -o"libiup_test" ./src/stratcalc/SimpleStratosphericColumnCalculatorTest.o
./src/interp/SimpleInterpolatorTest.o
./src/Test.o -lgsl -lhdf5 -lhdf5_cpp
-lblas -liup /home/hilboll/src/libiup/Release/libiup.so:
undefined reference to loglevel'
/home/hilboll/src/libiup/Release/libiup.so:
undefined reference toerrormsg'
collect2: ld returned 1 exit status
make: *** [libiup_test] Error 1
even though in my command line program, there's no reference whatsoever to errormsg or loglevel.
2) when trying to compile the dll under windows with VS2008, i get
z:\src\vs\libiup_dll\libiup_dll.h(229)
: error C2086: 'std::string errormsg':
Neudefinition
z:\src\libiup\src\stratcalc../interp/SimpleInterpolator.h(16):
Siehe Deklaration von 'errormsg'
z:\src\vs\libiup_dll\libiup_dll.h(234)
: error C2086: 'int loglevel':
Neudefinition
z:\src\libiup\src\stratcalc../interp/SimpleInterpolator.h(17):
Siehe Deklaration von 'loglevel'
as far as i understand, it means that VS thinks i'm defining the two variables twice. however, in SimpleInterpolator.h 16/17, there's the extern declarations only ...
it seems i somehow haven't understood how global variables work, yet. any help is greatly appreciated!
| The trick is to know that each .cpp file is a compilation unit - ie the things that get compiled. Each one is a total individual and know nothing about each other. Its only at the link stage that these are brought together.
Now, extern says "this variable can be found elsewhere" to the compiled cpp file, the compiler just places a reference hint to the linker to sort things out.
So, as you've put the variable definitions in a header file, chances are you're including that header into 2 (or more) cpp files. So each of those cpp files, when compiled, think they have the real variable. The linker then comes along and sees too many.
Place the variables into a cpp file of their own (or into the main cpp file), and only put extern references in header files. You should be ok with multiply-defined symbols then.
|
1,323,824 | 1,323,863 | How to read numbers from an ASCII file (C++) | I need to read in data files which look like this:
* SZA: 10.00
2.648 2.648 2.648 2.648 2.648 2.648 2.648 2.649 2.650 2.650
2.652 2.653 2.652 2.653 2.654 2.654 2.654 2.654 2.654 2.654
2.654 2.654 2.654 2.655 2.656 2.656 2.657 2.657 2.657 2.656
2.656 2.655 2.655 2.653 2.653 2.653 2.654 2.658 2.669 2.669
2.667 2.666 2.666 2.664 2.663 2.663 2.663 2.662 2.663 2.663
2.663 2.663 2.663 2.663 2.662 2.660 2.656 2.657 2.657 2.657
2.654 2.653 2.652 2.651 2.648 2.647 2.646 2.642 2.641 2.637
2.636 2.636 2.634 2.635 2.635 2.635 2.635 2.634 2.633 2.633
2.633 2.634 2.634 2.635 2.637 2.638 2.637 2.639 2.640 2.640
2.639 2.640 2.640 2.639 2.639 2.638 2.640 2.640 2.638 2.639
2.638 2.638 2.638 2.638 2.637 2.637 2.637 2.634 2.635 2.636
2.637 2.639 2.641 2.641 2.643 2.643 2.643 2.642 2.643 2.642
2.641 2.642 2.642 2.643 2.645 2.645 2.645 2.645
What would be the most elegant way to read this file into an array of floats?
I know how to read each single line into a string, and I know how to convert the string to float using atof(). But how do I do the rest the easiest?
I've heard about string buffers, might this help me?
| Since this is tagged as C++, the most obvious way would be using streams. Off the top of my head, something like this might do:
std::vector<float> readFile(std::istream& is)
{
char chdummy;
is >> std::ws >> chdummy >> std::ws;
if(!is || chdummy != '*') error();
std::string strdummy;
std::getline(is,strdummy,':');
if(!is || strdummy != "SZA") error();
std::vector<float> result;
for(;;)
{
float number;
if( !is>>number ) break;
result.push_back(number);
}
if( !is.eof() ) error();
return result;
}
Why float, BTW? Usually, double is much better.
Edit, since it was questioned whether returning a copy of the vector is a good idea:
For a first solution, I'd certainly do the obvious. The function is reading a file into a vector, and the most obvious thing for a function to do is to return its result. Whether this results in a noticeable slowdown depends on a lot of things (the size of the vector, how often the function is called and from where, the speed of the disk this reads from, whether the compiler can apply RVO). I wouldn't want to spoil the obvious solution with an optimization, but if profiling indeed shows that this is to slow, the vector should be passed in per non-const reference.
(Also note that C++1x with rvalue support, hopefully soon to be available by means of a compiler near you, will render this discussion moot, as it will prevent the vector from being copied upon returning from the function.)
|
1,324,411 | 1,324,555 | Question about precompiled headers in Visual C++ | If I put a header (a.h) into stdafx.h and that header includes another header (b.h) that is not mentioned in stdafx.h, will b.h be visited every time someone includes a.h or is it compiled in as part of a.h? If it is compiled into a.h, what happens when someone includes b.h directly? Will this be precompiled or not?
My motivation for asking this question is that I am trying to optimize the content of the stdafx.h files for the software that I work on. Both rebuild and incremental build times are important to us. I was wondering whether I could simply search through all of the .cpp files for #include directives and count the number of times each file is included. Files which were included often might be good candidates for the stdafx.h file. Of course, this strategy is completely bogus if I have to consider not only which files are included, but also which files the included files include.
I doubt it matters, but we are using Visual Studio 2005.
| a.h and b.h will be part of precompiled header, and there is no need to include them later. All you need is to include stdafx.h where a.h or b.h are required. If you'll include a.h or b.h explicitly after stdafx.h (all code before stdafx.h include are ignored), then it'll not be compiled second time (just because they are usually protected by #pragma once directive or defines), but compiler will open that file on hard disk if you are asking about it,
By the way, you should know, that you could use several precompiled header files (but no more than one in every cpp file).
|
1,324,589 | 1,324,598 | what does this code mean? | this is some code that SDL requires in visual studios 2005 in order for my simple program to work. what is the code doing? the only reason i have it is because my instructor told me to put it in and never explained it.
// what is this code doing?
//---------------------------------------------------------
#ifdef WIN32
#pragma comment(lib, "SDL.lib")
#pragma comment(lib, "SDLmain.lib")
#endif
//-------------------------------------------------------
#include <iostream>
#include "SDL.h"
using namespace std;
int main(int argc, char *argv[])
{
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) == -1) {
cerr << "Failed to initialize SDL: " << SDL_GetError() << endl;
exit(1);
}
atexit(SDL_Quit);
system("pause");
return 0;
}
| #pragma is a directive to the compiler. In this case, it asks the compiler to put a "comment" into the final object file, and this comment is then used by the linker to link against the library.
Then it initializes the SDL library.
Then it registers SDL_Quit function to be executed at program exit.
Then pause, otherwise the program quits immediately.
|
1,324,719 | 1,324,765 | using pointers to get values back from a function (c++) | i have a function to calculate several different values:
int ASPfile::get_dimensions(int* Lat, int* Lon,
vector<double>* Latgrid, vector<double>* Longrid) {
_latsize = get_latsize();
_lonsize = get_lonsize();
Lat = &_latsize;
Lon = &_lonsize;
latgrid = read_latgrid();
longrid = read_longrid();
*Latgrid = latgrid;
*Longrid = longrid;
return 0;
}
This function is called as follows:
int* Latsize = NULL;
int* Lonsize = NULL;
vector<double>* Latgrid = NULL;
vector<double>* Longrid = NULL;
int res = asp->get_dimensions(Latsize,Lonsize,Latgrid,Longrid);
and then, I try to access the values as follows:
cout << (*Szagrid)[4];
or like this
cout << Szagrid->at(4);
The program compiles with no warnings. However, when I try to access the pointers which are supposed to be 'filled' by get_dimensions(),
valgrind shows me the following:
==10531== Invalid read of size 8
==10531== at 0x633D5DA: std::vector<double, std::allocator<double> >::operator=(std::vector<double, std::allocator<double> > const&) (in /home/myhome/src/libiup/Release/libiup.so)
==10531== by 0x633CADC: ASPfile::get_dimensions(int*, int*, int*, std::vector<double, std::allocator<double> >*, std::vector<double, std::allocator<double> >*, std::vector<double, std::allocator<double> >*) (in /home/myhome/src/libiup/Release/libiup.so)
==10531== by 0x41B90B: ASPfileTest::test_get_dimensions() (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== by 0x41BACC: ASPfileTest::operator()() (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== by 0x41E229: boost::function0<void>::operator()() const (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== by 0x41E7C2: cute::runner<cute::eclipse_listener>::runit(cute::test const&) (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== by 0x41D26A: runSuite() (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== by 0x41DBC4: main (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==10531==
==10531== Process terminating with default action of signal 11 (SIGSEGV): dumping core
==10531== Access not within mapped region at address 0x0
==10531== at 0x633D5DA: std::vector<double, std::allocator<double> >::operator=(std::vector<double, std::allocator<double> > const&) (in /home/myhome/src/libiup/Release/libiup.so)
==10531== by 0x633CADC: ASPfile::get_dimensions(int*, int*, int*, std::vector<double, std::allocator<double> >*, std::vector<double, std::allocator<double> >*, std::vector<double, std::allocator<double> >*) (in /home/myhome/src/libiup/Release/libiup.so)
==10531== by 0x41B90B: ASPfileTest::test_get_dimensions() (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== by 0x41BACC: ASPfileTest::operator()() (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== by 0x41E229: boost::function0<void>::operator()() const (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== by 0x41E7C2: cute::runner<cute::eclipse_listener>::runit(cute::test const&) (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== by 0x41D26A: runSuite() (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== by 0x41DBC4: main (in /home/myhome/src/libiup_test/Release/libiup_test)
==10531== If you believe this happened as a result of a stack overflow in your
==10531== program's main thread (unlikely but possible), you can try to increase
==10531== the size of the main thread stack using the --main-stacksize= flag.
==10531== The main thread stack size used in this run was 8388608.
I don't quite understand what I'm doing wrong; probably something obvious, but I cannot seem to find the problem.
Any help is greatly appreciated!
| You're writing to memory in get_dimensions, but you're never actually allocating that memory. Instead, you are just passing NULL pointers.
One potential fix is to change your calling code to:
int Latsize, Lonsize;
vector<double> Latgrid;
vector<double> Longrid;
int res = asp->get_dimensions(&Latsize,&Lonsize,&Latgrid,&Longrid);
This allocates space for the variables automatically on the stack, then you pass the address of that allocated space to get_dimensions, which will modify the values.
|
1,324,790 | 1,324,798 | Can an STL map iterator go out of bounds through incrementing? | For associative containers, can the ++ operator send an iterator past the end of a collection?
Example:
map<UINT32, UINT32> new_map;
new_map[0] = 0;
new_map[1] = 1;
map<UINT32, UINT32> new_iter = new_map.begin();
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
At the end of this, does new_iter == new_map.end(), or does it end up in the great unknown?
Note: I know this is messed up and not the way to do things. I'm working around some WTF corporate code.
| If you increment the end iterator, the result is undefined behavior. So, it could remain end, or go off the end, or email your grandmother a link to goatse.
See also: What if I increment an iterator by 2 when it points onto the last element of a vector?
|
1,324,800 | 1,458,470 | Boost Multi-Index Custom Composite Key Comparer | I'm looking to write a custom comparer for a boost ordered_non_unique index with a composite key. I'm not exactly sure how to do this. Boost has a composite_key_comparer, but that won't work for me, because one of the comparers for a member of the key depends on a previous member. This is a simplified example, but I want the index to sort descending on third_ when second_ is 'A' keeping 0 values for third_ first and use std::less in all other cases. Hopefully that makes sense. I would like the code below to print out:
3,BLAH,A,0
5,BLAH,A,11
2,BLAH,A,10
4,BLAH,A,9
1,BLAH,A,8
The code would go in place of WHAT GOES HERE???. Thanks for any help.
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/key_extractors.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <iostream>
namespace bmi = boost::multi_index;
namespace bt = boost::tuples;
struct Widget
{
Widget (const std::string& id, const std::string& f, char s, unsigned int t)
: id_(id)
, first_(f)
, second_(s)
, third_(t)
{ }
~Widget () { }
std::string id_;
std::string first_;
char second_;
unsigned int third_;
};
std::ostream& operator<< (std::ostream& os, const Widget& w)
{
os << w.id_ << "," << w.first_ << "," << w.second_ << "," << w.third_;
return os;
}
struct id_index { };
struct other_index { };
typedef bmi::composite_key<
Widget*,
bmi::member<Widget, std::string, &Widget::first_>,
bmi::member<Widget, char, &Widget::second_>,
bmi::member<Widget, unsigned int, &Widget::third_>
> other_key;
typedef bmi::multi_index_container<
Widget*,
bmi::indexed_by<
bmi::ordered_unique<
bmi::tag<id_index>,
bmi::member<Widget, std::string, &Widget::id_>
>,
bmi::ordered_non_unique<
bmi::tag<other_index>,
other_key,
***************WHAT GOES HERE???***************
>
>
> widget_set;
typedef widget_set::index<other_index>::type widgets_by_other;
typedef widgets_by_other::iterator other_index_itr;
int main ()
{
widget_set widgets;
widgets_by_other& wbo_index = widgets.get<other_index>();
Widget* w;
w = new Widget("1", "BLAH", 'A', 8);
widgets.insert(w);
w = new Widget("2", "BLAH", 'A', 10);
widgets.insert(w);
w = new Widget("3", "BLAH", 'A', 0);
widgets.insert(w);
w = new Widget("4", "BLAH", 'A', 9);
widgets.insert(w);
w = new Widget("5", "BLAH", 'A', 11);
widgets.insert(w);
std::pair<other_index_itr,other_index_itr> range =
wbo_index.equal_range(boost::make_tuple("BLAH", 'A'));
while (range.first != range.second)
{
std::cout << *(*range.first) << std::endl;
++range.first;
}
return 0;
}
| I think you have hit the wall.
You may want to refer here: Ordered Indices
As with the STL, you will actually have to provide the comparison criteria yourself, and thus you will have the ability to tailor it to your needs.
As explained on the page I linked (in 'Comparison Predicates' section):
The last part of the specification of an ordered index is the associated comparison predicate, which must order the keys in a less-than fashion.
Thus, your work is two-fold:
You need to define a suitable comparison predicate, which operates on your types
You need to indicate to Boost.MultiIndex that you wish to use this predicate for the actual comparison of the keys
Here is an example, I am not sure I understood your requirements fully though so you may have to check it indeed sort as you wish.
struct WidgetComparer
{
bool operator()(const Widget& lhs, const Widget& rhs) const
{
if (lhs._second == 'A' && rhs._second == 'A')
{
return lhs._third == 0 || rhs._third < lhs._third;
}
else
{
return lhs._third < rhs._third;
}
} // operator()
};
And then, you just have to complete your index. So replace "other key" with identity < Widget > and "WHAT GOES HERE" with WidgetComparer.
And here you goes!
The important point is that you should not focus on the 'key' part of the container. The key is nothing by itself, it is the couple (key,comparison predicate) which does the actual ordering. The focus is on keys in the documentation to enhance code reuse (and in particular, to benefit from the comparison predicates that are already implemented like std::less).
As an alternative, you could have decided to code a "operator<" for your Widget class or to specialize the std::less algorithm. If you intend to use this way of sorting more than once, you should probably prefer this solution. However if your container is the only one which will use it, then a custom predicate is better.
Hope that helped.
|
1,324,919 | 1,324,955 | What language is .NET Framework written in? | The question I always wanted to ask and was afraid to, actually - what language is .NET Framework written in? I mean library itself.
It seems to me that it was C and C++ mostly. (I hope Jon Skeet is reading this one, it`ll be very interesting to hear what he thinks about it)
| The CLI/CLR is written in C/C++ and assembly. Almost all of the .NET framework classes are written in C# > compiled to IL, which runs in the CLR. If you crack open a framework library in Reflector, class, you may see an attribute such as [MethodImpl(MethodImplOptions.InternalCall)] which delegates the call to the CLI.
|
1,325,270 | 1,325,332 | How to send a string via PostMessage? | Inside my app, I want to send a message to a dialog from a different thread.
I want to pass an std::exception derived class reference to the dialog.
Something like this:
try {
//do stuff
}
catch (MyException& the_exception) {
PostMessage(MyhWnd, CWM_SOME_ERROR, 0, 0); //send the_exception or the_exception.error_string() here
}
I want to receive the message in my dialog and show the error that is in the_exception.error_string()
LPARAM CMyDlg::SomeError(WPARAM, LPARAM)
{
show_error( ?????
return 0;
}
passing the std::string the_exception.error_string() using PostMessage would also be ok, I guess.
| You can't pass the address of the string in PostMessage, since the string is probably thread-local on the stack. By the time the other thread picks it up, it could have been destroyed.
Instead, you should create a new string or exception object via new and pass its address to the other thread (via the WPARAM or LPARAM parameter in PostMessage.) The other thread then owns the object and is responsible for destroying it.
Here is some sample code that shows how this could be done:
try
{
// do stuff
}
catch (const MyException& the_exception)
{
PostMessage(myhWnd, CWM_SOME_ERROR, 0, new std::string(the_exception.error_string));
}
LPARAM CMyDlg::SomeError(WPARAM, LPARAM lParam)
{
// Wrap in a unique_ptr so it is automatically destroyed.
std::unique_ptr<std::string> msg = reinterpret_cast<std::string*>(lParam);
// Do stuff with message
return 0;
}
|
1,325,390 | 1,325,399 | C++ and pulseaudio "not declared in this scope" | I'm trying to use pulseaudio to play the contest of a vorbis-stream but are hitting problems. Basicly I'm told that:
‘pa_simple’ was not declared in this scope
‘pa_simple_new’ was not declared in this scope
‘pa_simple_write’ was not declared in this scope
Some code are shown below:
#include <pulse/pulseaudio.h>
pa_simple *s;
pa_sample_spec ss;
ss.format = PA_SAMPLE_S16NE;
ss.channels = 2;
ss.rate = 44100;
s = pa_simple_new(
NULL, // Use the default server.
"Fooapp", // Our application's name.
PA_STREAM_PLAYBACK, // Playback
NULL, // Use the default device.
"Music", // Description of our stream.
&ss, // Our sample format.
NULL, // Use default channel map
NULL, // Use default buffering attributes.
NULL, // Ignore error code.
);
while((samples=vorbis_synthesis_pcmout(&vd,&pcm))>0){
int j;
int bout=(samples<convsize?samples:convsize);
cout << "D" << endl;
for(i=0;i<vi.channels;i++){
ogg_int16_t *ptr=convbuffer+i;
float *mono=pcm[i];
for(j=0;j<bout;j++){
int val=floor(mono[j]*32767.f+.5f);
*ptr=val;
ptr+=vi.channels;
}
}
cout << "E" << endl;
#ifdef PulseAudio
pa_simple_write(s,convbuffer,2*vi.channels,NULL);
#else
fwrite(convbuffer,2*vi.channels,bout,output);
#endif
vorbis_synthesis_read(&vd,bout);
cout << "F" << endl;
}
It's probably some simple error, but if anyone could point me into the right direction, that would be great!
| Those things are all defined in simple.h, so add a new #include to the top of your file:
#include <pulse/simple.h>
|
1,325,485 | 1,331,777 | How to create a new port and assign it to a printer | We have a virtual printer (provided by a 3rd party) that is getting assigned to an invalid local printer port. The printer is always local (we aren't dealing with a remote print server or anything like that). I'd like to create a new local port (specific for our application), then configure the printer to be assigned to that port instead of the random (and often incorrect) port that the print driver installer chooses.
I believe that I need to use the XcvData and/or XcvDataPort functions to do this, but I'm at a bit of a loss as to how.
Does anyone have any examples or pointers on how to proceed?
I'd imagine that I need to do the following:
Check to ensure the port name doesn't already exist (I can probably use EnumPorts for this, but I'm not sure that's the best approach given that I have to also create ports)
Create the port name if it does exist
Change the printer configuration to use the new port
and for uninstall:
Remove the port
| Wow, looks like that one stumped everyone... After much digging, here's how to do it:
DWORD CreatePort(LPWSTR portName)
{
HANDLE hPrinter;
PRINTER_DEFAULTS PrinterDefaults;
memset(&PrinterDefaults, 0, sizeof(PrinterDefaults));
PrinterDefaults.pDatatype = NULL;
PrinterDefaults.pDevMode = NULL;
PrinterDefaults.DesiredAccess = SERVER_ACCESS_ADMINISTER;
DWORD needed;
DWORD rslt;
if (!OpenPrinter(",XcvMonitor Local Port", &hPrinter, &PrinterDefaults))
return -1;
DWORD xcvresult= 0;
if (!XcvData(hPrinter, L"AddPort", (BYTE *)portName, (lstrlenW(portName) + 1)*2, NULL, 0, &needed, &xcvresult))
rslt= GetLastError();
if (!ClosePrinter(hPrinter))
rslt= GetLastError();
return rslt;
}
Setting the port on a given printer is relatively straight forward - OpenPrinter(), GetPrinter() with PRINTER_INFO_2, SetPrinter(), ClosePrinter()
Cheerio.
|
1,325,494 | 1,325,515 | can't step into c++ program pixel city in netbeans on ubuntu | I'm using NetBeans 6.7 on Ubuntu, and I downloaded a linux port of shamus young's pixel city,
http://github.com/BryanKadzban/pixelcity/tree/master
but I can't step into it (it compiles and builds and runs fine (a little slow but fine)). I can step into a c++ sample project in netbeans which seems to mean that gdb is working properly. What are some of the workarounds / reasons I wouldn't be able to step into a c++ program ? Thanks in advance.
| Did you build it with debugger info enabled? For example, if CCFLAGS is used to specify compiler flags, does it include the -g option? You'll need this before you can use gdb.
|
1,325,553 | 1,325,580 | link with DB2 ODBC drivers on Linux | I need to link our C/C++ code that is using the DB2 ODBC driver on linux, and although ive pulled in sqlcli.h I dont know where to find the objects so i can link.
Ive installed DB2 v9.1 ESE so i wouldve thought i could get everything.
Anybody got any ideas?
| Your application (on the client) would link to a Unix ODBC library -- either iODBC or unixodbc. Both are commonly available on Debian and Ubuntu and other distros.
Next, you install the ODBC driver from the server database. This means you need to get a DB2 ODBC driver onto your system.
With that, your application is capable of 'talking ODBC' and has someone to talk to: the ODBC driver of DB2.
To give another concrete example, I compile RODBC again unixodbc-dev for Debian and can then talk via ODBC to MySQL and Postgresql as I have drivers for both. [ This is of course contrived as both MySQL and Postgresql have native drivers too, but it servers as a test of RODBC. ]
|
1,325,607 | 1,325,613 | accessing static member variables | Can I access static member variables of a class using dot notation or should I stick in access operator which is double colon?
| If you have an instance variable you may use dot operator to access static members if accessible.
#include <iostream>
using namespace std;
class Test{
public:
static int no;
};
int Test::no;
int main(){
cout << "\n" << Test::no;
Test::no=100;
Test a;
cout << "\n" << a.no;
return 0;
}
|
1,326,118 | 1,326,134 | sum of square of each elements in the vector using for_each | As the function accepted by for_each take only one parameter (the element of the vector), I have to define a static int sum = 0 somewhere so that It can be accessed
after calling the for_each . I think this is awkward. Any better way to do this (still use for_each) ?
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
static int sum = 0;
void add_f(int i )
{
sum += i * i;
}
void test_using_for_each()
{
int arr[] = {1,2,3,4};
vector<int> a (arr ,arr + sizeof(arr)/sizeof(arr[0]));
for_each( a.begin(),a.end(), add_f);
cout << "sum of the square of the element is " << sum << endl;
}
In Ruby, We can do it this way:
sum = 0
[1,2,3,4].each { |i| sum += i*i} #local variable can be used in the callback function
puts sum #=> 30
Would you please show more examples how for_each is typically used in practical programming (not just print out each element)? Is it possible use for_each simulate 'programming pattern' like map and inject in Ruby (or map /fold in Haskell).
#map in ruby
>> [1,2,3,4].map {|i| i*i}
=> [1, 4, 9, 16]
#inject in ruby
[1, 4, 9, 16].inject(0) {|aac ,i| aac +=i} #=> 30
EDIT: Thank you all. I have learned so much from your replies. We have so many ways to do the same single thing in C++ , which makes it a little bit difficult to learn. But it's interesting :)
| Use std::accumulate
#include <vector>
#include <numeric>
// functor for getting sum of previous result and square of current element
template<typename T>
struct square
{
T operator()(const T& Left, const T& Right) const
{
return (Left + Right*Right);
}
};
void main()
{
std::vector <int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
int x = std::accumulate( v1.begin(), v1.end(), 0, square<int>() );
// 0 stands here for initial value to which each element is in turn combined with
// for our case must be 0.
}
You could emulate std::accumulate as in nice GMan's answer, but I believe that using std::accumulate will make your code more readable, because it was designed for such purposes. You could find more standard algorithms here.
|
1,326,163 | 1,332,306 | How to tell a column is text or ntext when connecting to database using CDynamicAccessor? | I'm having a C++ application connecting to the MS SQL Server 2005 using CDynamicAccessor.
When my column is text or ntext, the CDynamicAccessor::GetColumnType always return DBTYPE_IUNKNOWN. I can bind the data as ISequentialStream and read the byte stream out. However, how can I tell if the column that I'm reading is text or ntext, and hence, to interpret the byte stream as ASCII or Unicode?
| The CDynamicAccessor class overwrites the original DBTYPE value of the column with DBTYPE_UNKNOWN. In order to get the original DBTYPE, we need to call the GetColumnInfo function. An example of how to do this is the DynamicConsumer sample application included in the Visual Studio 2008 samples:
// the following case will handle BLOBs binded as ISequentialStream/IStream pointer
if( dbtype == DBTYPE_IUNKNOWN )
{
// first we have to determine what was the column's type originally reported by the provider
CComHeapPtr<DBCOLUMNINFO> spColumnInfo;
CComHeapPtr<OLECHAR> spStringsBuffer;
DBORDINAL nColumns = 0;
HRESULT hres = rs.CDynamicAccessor::GetColumnInfo( rs.m_spRowset, &nColumns, &spColumnInfo, &spStringsBuffer );
ATLASSERT( SUCCEEDED( hres ) );
ATLASSERT( col <= nColumns );
DBTYPE wType = spColumnInfo[col-1].wType;
...
}
The alternative solution is to set the CDynamicAccessor to DBBLOBHANDLING_NOSTREAMS, which seems to result in much less complicated code to handle data loading (you can see this in the full VS2008 sample code).
However, I'm not sure why using stream is the default option, and if there is any disadvantages with using no streams.
|
1,326,446 | 1,326,456 | Best Tools for helping debug an Interop issues | One of our customers is getting an interop issue, there is nothing in the stack trace that is worth noting, just ComException with an InterOp issue.
I've tried Process Monitor and Dependency Walker, but nothing seems to pop up.
It is C++ Managed running on .net 1.1.
Any helps with any tools would be a life saver!?
| The managed debugging assistants in Visual Studio are designed for precisely this sort of thing and will catch things like GC releasing an COM pointer that's already gone (ie. native side reference counting problems).
Other than that the best tool I've found is a lot of patience and using WinDBG with SOS
|
1,326,468 | 1,326,513 | multiple definition for static member? | Failed to link up following two files, when I remove the "static" keyword, then it is okay. Tested with g++.
Check with readelf for the object file, the static member seems is exported as a global object symbol... I think it should be a local object ...?
static1.cpp
class StaticClass
{
public:
void setMemberA(int m) { a = m; }
int getMemberA() const { return a; }
private:
static int a;
};
int StaticClass::a = 0;
void first()
{
StaticClass statc1;
static1.setMemberA(2);
}
static2.cpp
class StaticClass
{
public:
void setMemberA(int m) { a = m; }
int getMemberA() const { return a; }
private:
static int a;
};
int StaticClass::a = 0;
void second()
{
StaticClass statc1;
static1.setMemberA(2);
}
With error info:
/tmp/ccIdHsDm.o:(.bss+0x0): multiple
definition of `StaticClass::a'
| It seems like you're trying to have local classes in each source file, with the same name. In C++ you can encapsulate local classes in an anonymous namespace:
namespace {
class StaticClass
{
public:
void setMemberA(int m) { a = m; }
int getMemberA() const { return a; }
private:
static int a;
};
int StaticClass::a = 0;
} // close namespace
void first()
{
StaticClass statc1;
static1.setMemberA(2);
}
|
1,326,510 | 1,326,524 | c++ rounding of numbers away from zero | Hi i want to round double numbers like this (away from zero) in C++:
4.2 ----> 5
5.7 ----> 6
-7.8 ----> -8
-34.2 ----> -35
What is the efficient way to do this?
| inline double myround(double x)
{
return x < 0 ? floor(x) : ceil(x);
}
As mentioned in the article Huppie cites, this is best expressed as a template that works across all float types
See http://en.cppreference.com/w/cpp/numeric/math/floor and http://en.cppreference.com/w/cpp/numeric/math/floor
or, thanks to Pax, a non-function version:
x = (x < 0) ? floor(x) : ceil(x);
|
1,326,588 | 1,329,640 | WSAEventSelect model | Hey I'm using the WSAEventSelect for event notifications of sockets. So far everything is cool and working like a charm, but there is one problem.
The client is a .NET application and the server is written in Winsock C++. In the .NET application I'm using System.Net.Sockets.Socket class for TCP/IP. When I call the Socket.Shutdown() and Socket.Close() method, I receive the FD_CLOSE event in the server, which I'm pretty sure is fine. Okay the problem occurs when I check the iErrorCode of WSANETWORKEVENTS which I passed to WSAEnumNetworkEvents. I check it like this
if (listenerNetworkEvents.lNetworkEvents & FD_CLOSE)
{
if (listenerNetworkEvents.iErrorCode[FD_CLOSE_BIT] != 0)
{
// it comes here
// which means there is an error
// and the ERROR I got is
// WSAECONNABORTED
printf("FD_CLOSE failed with error %d\n",
listenerNetworkEvents.iErrorCode[FD_CLOSE_BIT]);
break;
}
closesocket(socketArray[Index]);
}
But it fails with the WSAECONNABORTED error. Why is that so?
EDIT: Btw, I'm running both the client and server on the same computer, is it because of that? And I received the FD_CLOSE event when I do this:
server.Shutdown(SocketShutdown.Both); // in .NET C#, client code
| I'm guessing you're calling Shutdown() and then Close() immediately afterward. That will give the symptom you're seeing, because this is "slamming the connection shut". Shutdown() does initiate a graceful disconnect (TCP FIN), but immediately following it with Close() aborts that, sending a TCP RST packet to the remote peer. Your Shutdown(SocketShutdown.Both) call slams the connection shut, too, by the way.
The correct pattern is:
Call Shutdown() with the direction parameter set to "write", meaning we won't be sending any more data to the remote peer. This causes the stack to send the TCP FIN packet.
Go back to waiting for Winsock events. When the remote peer is also done writing, it will call Shutdown("write"), too, causing its stack to send your machine a TCP FIN packet, and for your application to get an FD_CLOSE event. While waiting, your code should be prepared to continue reading from the socket, because the remote peer might still be sending data.
(Please excuse the pseudo-C# above. I don't speak .NET, only C++.)
Both peers are expected to use this same shutdown pattern: each tells the other when it's done writing, and then waits to receive notification that the remote peer is done writing before it closes its socket.
The important thing to realize is that TCP is a bidirectional protocol: each side can send and receive independently of the other. Closing the socket to reading is not a nice thing to do. It's like having a conversation with another person but only talking and being unwilling to listen. The graceful shutdown protocol says, "I'm done talking now. I'm going to wait until you stop talking before I walk away."
|
1,326,795 | 1,331,731 | Need to parse a string, having a mask (something like this "%yr-%mh-%dy"), so i get the int values | For example i have to find time in format mentioned in the title(but %-tags order can be different) in a string "The date is 2009-August-25." How can i make the program interprete the tags and what construction is better to use for storing them among with information about how to act with certain pieces of date string?
| First look into boost::date_time library. It has IO system witch may be what you want but I see lack of searching.
To do custom date searching you need boost::xpressive. It contain anything you will need. Lets look into my hastily writed example. First you should parse your custom pattern, witch is easy with Xpressive. First look at header you need:
#include <string>
#include <iostream>
#include <map>
#include <boost/xpressive/xpressive_static.hpp>
#include <boost/xpressive/regex_actions.hpp>
//make example shorter but less clear
using namespace boost::xpressive;
Second define map of your special tags:
std::map<std::string, int > number_map;
number_map["%yr"] = 0;
number_map["%mh"] = 1;
number_map["%dy"] = 2;
number_map["%%"] = 3; // escape a %
Next step is to create a regex witch will parse our pattern with tags and save values from map into variable tag_id when it find tag or save -1 otherwise:
int tag_id;
sregex rx=((a1=number_map)|(s1=+~as_xpr('%')))[ref(tag_id)=(a1|-1)];
More information and description look here and here.
Now lets parse some pattern:
std::string pattern("%yr-%mh-%dy"); // this will be parsed
sregex_token_iterator begin( pattern.begin(), pattern.end(), rx ), end;
if(begin == end) throw std::runtime_error("The pattern is empty!");
The sregex_token_iterator will iterate over our tokens, and each time it will set tag_id varible. All we have to do is to build regex using this tokens. We will construct this regex using tag corresponding parts of static regex defined in array:
sregex regex_group[] = {
range('1','9') >> repeat<3,3>( _d ), // 4 digit year
as_xpr( "January" ) | "February" | "August", // not all month XD so lazy
repeat<2,2>( range('0','9') )[ // two digit day
check(as<int>(_) >= 1 && as<int>(_) <= 31) ], //only bettwen 1 and 31
as_xpr( '%' ) // match escaped %
};
Finally, lets start build our special regex. The first match will construct first part of it. If the tag is matched and tag_id is non negative we choose regex from array, else the match is probably the delimiter and we construct regex witch match it:
sregex custom_regex = (tag_id>=0) ? regex_group[tag_id] : as_xpr(begin->str());
Next we will iterate from begin to end and append next regex:
while(++begin != end)
{
if(tag_id>=0)
{
sregex nextregex = custom_regex >> regex_group[tag_id];
custom_regex = nextregex;
}
else
{
sregex nextregex = custom_regex >> as_xpr(begin->str());
custom_regex = nextregex;
}
}
Now our regex is ready, lets find some dates :-]
std::string input = "The date is 2009-August-25.";
smatch mydate;
if( regex_search( input, mydate, custom_regex ) )
std::cout << "Found " << mydate.str() << "." << std::endl;
The xpressive library is very powerful and fast. It's also beautiful use of patterns.
If you like this example, let me know in comment or points ;-)
|
1,326,811 | 1,326,905 | How does a blur gauss algorithm look like? Are there examples of implementation? | I have a bitmap image context and want to let this appear blurry. So best thing I can think of is a gauss algorithm, but I have no big idea about how this kind of gauss blur algorithms look like? Do you know good tutorials or examples on this? The language does not matter so much, if it's done all by hand without using language-specific API too much. I.e. in cocoa the lucky guys don't need to think about it, they just use a Imagefilter that's already there. But I don't have something like this in cocoa-touch (objective-c, iPhone OS).
| This is actually quite simple. You have a filter pattern (also known as filter kernel) - a (small) rectangular array with coefficients - and just calculate the convolution of the image and the pattern.
for y = 1 to ImageHeight
for x = 1 to ImageWidth
newValue = 0
for j = 1 to PatternHeight
for i = 1 to PatternWidth
newValue += OldImage[x-PatternWidth/2+i,y-PatternHeight/2+j] * Pattern[i,j]
NewImage[x,y] = newValue
The pattern is just a Gauss curve in two dimensions or any other filter pattern you like. You have to take care at the edges of the image because the filter pattern will be partialy outside of the image. You can just assume that this pixels are balck, or use a mirrored version of the image, or what ever seems reasonable.
As a final note, there are faster ways to calculate a convolution using Fourier transforms but this simple version should be sufficent for a first test.
|
1,326,824 | 1,327,147 | How can I find all permutations of a string without using recursion? | Can someone help me with this: This is a program to find all the permutations of a string of any length. Need a non-recursive form of the same. ( a C language implementation is preferred)
using namespace std;
string swtch(string topermute, int x, int y)
{
string newstring = topermute;
newstring[x] = newstring[y];
newstring[y] = topermute[x]; //avoids temp variable
return newstring;
}
void permute(string topermute, int place)
{
if(place == topermute.length() - 1)
{
cout<<topermute<<endl;
}
for(int nextchar = place; nextchar < topermute.length(); nextchar++)
{
permute(swtch(topermute, place, nextchar),place+1);
}
}
int main(int argc, char* argv[])
{
if(argc!=2)
{
cout<<"Proper input is 'permute string'";
return 1;
}
permute(argv[1], 0);
return 0;
}
| A stack based non-recursive equivalent of your code:
#include <iostream>
#include <string>
struct State
{
State (std::string topermute_, int place_, int nextchar_, State* next_ = 0)
: topermute (topermute_)
, place (place_)
, nextchar (nextchar_)
, next (next_)
{
}
std::string topermute;
int place;
int nextchar;
State* next;
};
std::string swtch (std::string topermute, int x, int y)
{
std::string newstring = topermute;
newstring[x] = newstring[y];
newstring[y] = topermute[x]; //avoids temp variable
return newstring;
}
void permute (std::string topermute, int place = 0)
{
// Linked list stack.
State* top = new State (topermute, place, place);
while (top != 0)
{
State* pop = top;
top = pop->next;
if (pop->place == pop->topermute.length () - 1)
{
std::cout << pop->topermute << std::endl;
}
for (int i = pop->place; i < pop->topermute.length (); ++i)
{
top = new State (swtch (pop->topermute, pop->place, i), pop->place + 1, i, top);
}
delete pop;
}
}
int main (int argc, char* argv[])
{
if (argc!=2)
{
std::cout<<"Proper input is 'permute string'";
return 1;
}
else
{
permute (argv[1]);
}
return 0;
}
I've tried to make it C-like and avoided c++ STL containers and member functions (used a constructor for simplicity though).
Note, the permutations are generated in reverse order to the original.
I should add that using a stack in this way is just simulating recursion.
|
1,326,845 | 1,356,258 | Dropdown height bug in CComboBox (common controls 6.0)? |
I've made a simple MFC application (Visual Studio 2008, dialog based) and added a CComboBox using the resource editor. I used the resource editor to specify the dropdown height. Then I added some code to add 100 texts to the combobox. If I run this simple application the dropdown height is ignored. If I disable the Microsoft.Windows.Common-Controls 6.0.0.0 style (disable the pragma that adds it to the manifest file) then everything works fine.
Has anyone noticed this behaviour (and knows a solution)? I've searched the web and msdn, but no luck so far.
| The only solution I've found (thx to someone on the Microsoft MFC newsgroup) is to use the CBS_NOINTEGRALHEIGHT flag that states that the combobox must look to the exact size specified by the user rather then adjusting it automatically (the reason this is a patch is that the flag is normally intended to disable the feature where the dropheight is adjusted so that no partial items are rendered).
|
1,327,157 | 1,327,169 | What's the C++ version of Guid.NewGuid()? | I need to create a GUID in an unmanaged windows C++ project. I'm used to C#, where I'd use Guid.NewGuid(). What's the (unmanaged windows) C++ version?
| I think CoCreateGuid is what you're after. Example:
GUID gidReference;
HRESULT hCreateGuid = CoCreateGuid( &gidReference );
|
1,327,231 | 1,581,189 | Is it possible to run C++ binded with SDL+OpenGL code on a web browser? | My client wants her website to have an application that renders 3D (light 3D stuff, we are drawing only flat squares in 3D world) but web programming is not my thing. So I am looking for something that can run a C++ program from a web browser. But I think, if this is the case, then the client side must download the program first, and that's not what I want. The client should only be able to use this application only on the website.
I came across Google Native Client, which claims that it can run x86 native code in web applications. I haven't decide whether it is worth it or not and I don't know whether this is what I want or not, so I decided to ask experienced people about this.
If I want to have something like this, is what I said above possible? Or I completely need other languages like Flex because it does not worth the trouble? Or is Google Native Client suitable for doing something like this?
| No, NativeClient is not what you want. It won't let you run SDL+OpenGL -- it may be C++ code, but it's run inside a sandbox.
Running SDL in a browser is difficult in general. OpenGL somewhat less so, but it's no cakewalk either. Any such native code solution is difficult if you want it to work across browsers and platforms -- you'll have to develop NPAPI plugins for multiple platforms (which will all be fairly different), as well as an ActiveX control. You are looking at four separate projects.
Almost assuredly, the correct answer here is to use Flash in one form or another.
|
1,327,485 | 1,328,028 | Proxy Authentication in POCO Net C++ library | I have been playing with the Poco Net library for some time, it is quite nice. Very convenient and easy to understand.
I was able to set a proxy address, and it is saying 407 Proxy authorization required, properly. I figured that
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
req.setCredentials(scheme, authInfo);
I tried values like "basic", "plaintext" in scheme, and "user:password" in authInfo. It doesn't seem to work. Google isn't helping.
Has anyone done this using Poco Net before? Or is the usage obvious and I'm not able to get it to work because of my ignorance towards proxy authentication in general? Please advice.
EDIT: After some more playing around, I think the setCredentials function is used when the remote server is expecting authentication information to login. I have not been able to find a way to do proxy authentication using Poco Net libraries. I was able to set the proxy server and port though. This is what I would have if there was just a proxy server without authentication:
HTTPClientSession session(uri.getHost(), uri.getPort());
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
session.setProxy("host", port);
session.sendRequest(req);
Need help.
EDIT: Based on the solution suggested by @StackedCrooked, I tried setting proxy authentication details to the request header before making the request, and in another approach found on the internet, I set proxy auth details only after making an initial request and a 407 error comes, and then making the request again. Both methods kept on giving the same 407 error. My current code looks like this:
HTTPClientSession session(uri.getHost(), uri.getPort());
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
session.setProxy("10.7.128.1", 8080);
req.set("Proxy-Authentication", "Basic bGVlbGE6bGVlbGExMjM=");
session.sendRequest(req);
| You probably need to add the Proxy Authorization field to the HTTP headers. Poco's HTTPRequest class doesn't have a dedicated method for this. However, since it inherits the NameValueCollection class publicly you can set it like this:
req.set("Proxy-Authorization" , "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
Where QWxhZGRpbjpvcGVuIHNlc2FtZQ== is the base64 encoded version of "Aladdin:open sesame".
A lot of these problems become easier once you learn a little about the HTTP protocol. I am now mostly preaching to myself :)
|
1,327,806 | 1,328,583 | Do all C++ compilers allow using a static const int class member variable as an array bound? | In VC++ when I need to specify an array bound for a class member variable I do it this way:
class Class {
private:
static const int numberOfColors = 16;
COLORREF colors[numberOfColors];
};
(please don't tell me about using std::vector here)
This way I have a constant that can be used as an array bound and later in the class code to specify loop-statement constraints and at the same time it is not visible anywhere else.
The question is whether this usage of static const int member variables only allowed by VC++ or is it typically allowed by other widespread compilers?
| Yes, it's 100% legal and should be portable. The C++ standard says this in 5.19 - Constant expressions" (emphasis mine):
In several places, C++ requires expressions that evaluate to an integral or enumeration constant: as array bounds (8.3.4, 5.3.4), as case-expressions (6.4.2), as bit-field lengths (9.6), as enumerator initializers (7.2), as static member initializers (9.4.2), and as integral or enumeration non-type template arguments (14.3).
constant-expression:
conditional-expression
An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type template parameters of integral or enumeration types, and sizeof expressions.
That said, it appears that VC6 doesn't support it. See StackedCrooked's answer for a good workaround. In fact, I generally prefer the enum method StackedCrooked mentions for this type of thing.
As an FYI, the "static const" technique works in VC9, GCC 3.4.5 (MinGW), Comeau and Digital Mars.
And don't forget that if you use a "`static const'" member, you'll need a definition for it in addition to the declaration strictly speaking. However, virtually all compilers will let you get away with skipping the definition in this case.
|
1,327,943 | 1,328,006 | When to use pointers, and when not to use them | I'm currently doing my first real project in C++ and so, fairly new to pointers. I know what they are and have read some basic usage rules. Probably not enough since I still do not really understand when to use them, and when not.
The problem is that most places just mention that most people either overuse them or underuse them. My question is, when to use them, and when not?.
Currently, in many cases i'm asking myself, should I use a pointer here or just pass the variable itself to the function.
For instance, I know that you can send a pointer to a function so the function can actually alter the variable itself instead of a copy of it. But when you just need to get some information of the object once (for instance the method needs a getValue() something), are pointers usefull in that case?
I would love to see either reactions but also links that might be helpfull. Since it is my first time using C++ I do not yet have a good C++ book (was thinking about buying one if I keep on using c++ which I probably will).
| For the do's and dont's of C++:
Effective C++ and More Effective C++ by Scott Meyers.
For pointers (and references):
use pass by value if the type fits into 4 Bytes and don't want to have it changed after the return of the call.
use pass by reference to const if the type is larger and you don't want to have it changed after the return of the call.
use pass by reference if the parameter can't be NULL
use a pointer otherwise.
dont't use raw pointers if you don't need to. Most of the time, a smart pointer (see Boost) is the better option.
|
1,328,062 | 1,328,101 | listening socket dies unexpectedly | I'm having a problem where a TCP socket is listening on a port, and has been working perfectly for a very long time - it's handled multiple connections, and seems to work flawlessly. However, occasionally when calling accept() to create a new connection the accept() call fails, and I get the following error string from the system:
10022: An invalid argument was supplied.
Apparently this can happen when you call accept() on a socket that is no longer listening, but I have not closed the socket myself, and have not been notified of any errors on that socket.
Can anyone think of any reasons why a listening socket would stop listening, or how the error mentioned above might be generated?
| Some possibilities:
Some other part of your code overwrote the handle value. Check to see if it has changed (keep a copy somewhere else and compare, print it out, breakpoint on write in the debugger, whatever).
Something closed the handle.
Interactions with a buggy Winsock LSP.
|
1,328,156 | 1,328,273 | Small example on getting Cairo graphics to work with MFC? | I have some legacy MFC apps, and I'd like to use the Cairo drawing engine to add some charts and graphs.
I'm searching for a small example of how to get that to work. Basically, once I've created a PNG or GIF file, how do I get that show up in an MFC CView window?
My google-fu is not finding any good clues.
| From my demo samples,
// cairo_surface_t *surface;
// cairo_t *cr;
// surface = call_win32_surface_create_with_dib_T(CAIRO_FORMAT_ARGB32, 240, 80);
// cr = call_create_T (surface);
// call_surface_write_to_png_T (surface, "hello.png");
HDC src = call_win32_surface_get_dc_T(surface); // <--------
BitBlt(dest, 0, 0, 240, 80, src, 0,0, SRCCOPY); // <--------
Assuming that you already have a surface you can use something like the above sample.dest is the HDC handle to the window you want to render the cairo surface.
Update: CView::OnDraw()
You should implement the OnDraw() method for your CView (inherited?) class.
You can use the pDC pointer to draw the cairo surface, ie:
pDC->BitBlt(0, 0, 240, 80, src, 0,0, SRCCOPY); // "HDC src" is mentioned above
|
1,328,223 | 1,328,246 | When a function has a specific-size array parameter, why is it replaced with a pointer? | Given the following program,
#include <iostream>
using namespace std;
void foo( char a[100] )
{
cout << "foo() " << sizeof( a ) << endl;
}
int main()
{
char bar[100] = { 0 };
cout << "main() " << sizeof( bar ) << endl;
foo( bar );
return 0;
}
outputs
main() 100
foo() 4
Why is the array passed as a pointer to the first element?
Is it a heritage from C?
What does the standard say?
Why is the strict type-safety of C++ dropped?
| Yes it's inherited from C. The function:
void foo ( char a[100] );
Will have the parameter adjusted to be a pointer, and so becomes:
void foo ( char * a );
If you want that the array type is preserved, you should pass in a reference to the array:
void foo ( char (&a)[100] );
C++ '03 8.3.5/3:
...The type of a function is determined using the following rules. The type of each parameter is determined from its own decl-specifier-seq and declarator. After determining the type of each parameter, any parameter of type "array of T" or "function returning T" is adjusted to be "pointer to T" or "pointer to function returning T," respectively....
To explain the syntax:
Check for "right-left" rule in google; I found one description of it here.
It would be applied to this example approximately as follows:
void foo (char (&a)[100]);
Start at identifier 'a'
'a' is a
Move right - we find a ) so we reverse direction looking for the (. As we move left we pass &
'a' is a reference
After the & we reach the opening ( so we reverse again and look right. We now see [100]
'a' is a reference to an array of 100
And we reverse direction again until we reach char:
'a' is a reference to an array of 100 chars
|
1,328,238 | 1,328,635 | How to hash and compare a pointer-to-member-function? | How can i hash (std::tr1::hash or boost::hash) a c++ pointer-to-member-function?
Example:
I have several bool (Class::*functionPointer)() (not static) that point to several diferent methods of the class Class and i need to hash those pointer-to-member-function.
How can i do that?
Also how can i compare (std::less) those member function pointers so i can store them in a std::set?
| All C++ objects, including pointers to member functions, are represented in memory as an array of chars. So you could try:
bool (Class::*fn_ptr)() = &Class::whatever;
const char *ptrptr = static_cast<const char*>(static_cast<const void*>(&fn_ptr));
Now treat ptrptr as pointing to an array of (sizeof(bool (Class::*)())) bytes, and hash or compare those bytes. You can use unsigned char instead of char if you prefer.
This guarantees no false positives - in C++03, pointers to member functions are POD, which means among other things that they can be copied using memcpy. This implies that if have the same byte-for-byte values, then they are the same.
The problem is that the storage representation of member function pointers could include bits which do not participate in the value - so they will not necessarily be the same for different pointers to the same member function. Or the compiler might, for some obscure reason, have more than one way of pointing to the same function of the same class, which are not byte-wise equal. Either way you can get false negatives. You'll have to look into how member function pointers actually work on your implementation. It must implement operator== for member function pointers somehow, and if you can find out how then you can probably figure out an order and a hash function.
That's potentially hard: member function pointers are awkward, and the storage is likely to include different amounts of non-participating "slack space" according to what kind of function is pointed to (virtual, inherited). So you'll probably have to interact quite significantly with your compiler's implementation details. This article might help get you started: http://www.codeproject.com/KB/cpp/FastDelegate.aspx
A cleaner alternative might be to do a linear search through an array in order to "canonicalise" all your function pointers, then compare and hash based on the position of the "canonical" instance of that function pointer in your array. Depends what your performance requirements are. And even if there are requirements, does the class (and its derived classes) have so many functions that the linear search will take that long?
typedef bool (Class::*func)();
vector<func> canon;
size_t getIndexOf(func fn_ptr) {
vector<func>::iterator it = find(canon.begin(), canon.end(), fn_ptr);
if (it != canon.end()) return it - canon.begin();
canon.push_back(func);
return canon.size() - 1;
}
|
1,328,410 | 1,329,545 | Include problems when using CMake with Gnu on Qt project | I am starting a multiplatform (Win Xp, Linux) qt project. I want to use an out of source build so my directory structure is as followed:
project/
CMakeLists.txt (global CMake file, includes other CMakeLists)
build/ (my build directory)
libA/
CMakeLists.txt
mystuff/
subprojectA/
CMakeLists.txt
subprojectB/
CMakeLists.txt
So when I use that on Windows with the Visual Studio generator everything builds fine.
If I use the same structure and CMakeLists on Linux or under Windows with the MinGW generator I get compile errors because the qt generated files (through moc and uic) lying under the build directory cannot find my header files in my subprojects. Some of the qt generated header/source files are dependent on my header/source files because I use promoted widgets in my .ui files which point to the implementation in my source. Again under Visual Studio / NMake everything compiles fine.
As a workaround I can use an in source build which runs fine or I can add the following on the global CMakeLists.txt:
include_directories(
mystuff/subprojectA
mystuff/subprojectB
)
But what is the right solution? Thank you very much!!
| I have a similar problem, with includes for out of source builds on unix (although I am not using QT), and in each effected projected I added:
include_directories( . )
Not the most elegant but I worked for me.
|
1,328,434 | 1,328,570 | Vectored exception handler and Microsoft C runtime error handling | I've recently implemented some vectored exception handling to catch errors in our software. This is especially useful as we've just converted from vc6 to vs2005. We're encountering a few problems with the use of the STL library (generally people doing things they shouldn't). I'm trying to catch these errors with my vectored exception handler.
However this doesn't seem to get called, instead these errors are internally processed by the Microsoft Visual Studio C Runtime library.
My question is;
Is there a way to turn off the runtime error checking and get the exceptions passed to the VE handler?
Thanks
Rich
| http://msdn.microsoft.com/en-us/library/aa985973%28VS.80%29.aspx
#define _SECURE_SCL 1
#define _SECURE_SCL_THROWS 1
The above allows me to throw exceptions.
|
1,328,492 | 1,328,659 | QTableView - not allow user to edit cell | I created a QTableView with a QSqlTableModel.
By standard, double-clicking on the cells will mark them and the user can edit them.
I want, that the user isn't allowed to do that. He is allowed to mark the whole row by clicking on a single cell, but not to edit the cell.
How can I do that?
| Depending on whether you are coding everything or doing things in the designer, set
editTriggers to QAbstractItemView::NoEditTriggers
selectionBehavior to QAbstractItemView::SelectRows
optionally set selectionMode to QAbstractItemView::SingleSelection if you want the user to select exactly one row
on the tableview object the appropriate calls will all be prefixed with set e.g setEditTriggers() in the Designer you can find these option in the AbstractItemView section
|
1,328,496 | 1,328,513 | Is there a way to typedef this? | Simplified version of the code:
Foo.h:
class Foo {
private:
class Bar {
// ...
};
typedef std::map<int, Bar> mapType;
mapType _map;
public:
void method(mapType::iterator it);
};
Foo.cpp:
void Foo::method(mapType::iterator it) {
// ...
notMethod(it);
}
void notMethod(mapType::iterator it) {
// ...
}
Unsurprisingly, I get the error 'mapType' is not a class or namespace name in VS2008 at notMethod's definition. Is there any (elegant) way that I can avoid having to type out std::map<int, Bar> everywere in notMethod's definition without turning notMethod into a method?
| Use
void notMethod(Foo::mapType::iterator it) {
// ...
}
and put the typedef in the public section of Foo's class declaration.
Edit:
If you want to avoid this, you can
make notMethod a friend (as suggested by DanDan),
use sbi's template solution, or
make notMethod a private static member function of Foo (which generates exactly the same code as if it was a free non-member function).
Which solution is the most appropriate really depends on what notMethod does.
If notMethod uses Bar and Bar really only makes sense in the context of Foo's internal implementation, I would make notMethod a private static member function, since it's part of Foo's internals.
If notMethod was an operator that needs to take a non-Foo as its first argument (meaning that it can't be a member of Foo), and if I wanted to keep Bar private, I would make the operator a friend.
If notMethod implements a generic operation on iterators, I would make it a template function.
If Bar is a class that might be of interest to Foo's clients, I would make Bar and the typedef public and use the solution I suggested originally.
|
1,328,568 | 1,328,742 | custom stream manipulator for class | I am trying to write a simple audit class that takes input via operator << and writes the audit after receiving a custom manipulator like this:
class CAudit
{
public:
//needs to be templated
CAudit& operator << ( LPCSTR data ) {
audittext << data;
return *this;
}
//attempted manipulator
static CAudit& write(CAudit& audit) {
//write contents of audittext to audit and clear it
return audit;
}
private:
std::stringstream audittext;
};
//to be used like
CAudit audit;
audit << "Data " << data << " received at " << time << CAudit::write;
I recognise that the overloaded operator in my code does not return a stream object but was wondering if it was still possible to use a manipulator like syntax. Currently the compiler is seeing the '<<' as the binary right shift operator.
Thanks for any input,
Patrick
| To make it work you have to add overload of operator << for functions,
than call the function from it:
class CAudit
{
//...other details here as in original question
CAudit& operator << (CAudit & (*func)(CAudit &))
{
return func(*this);
}
};
CAudit audit;
audit << "some text" << CAudit::write;
|
1,329,147 | 1,332,745 | How to extend listControl class in C++ and add new functions? | Hi I need to extend the CListControl class in C++/MFC, which will add several new features in the list control,
Any one have good sample code ?
Or could you please tell me how can i start it ?
Thanks in advance!
Or just write the new features and listControl into a ActiveX or COM ??
Which is better ?
| TO add functionality such as you suggest in your comments above I wouldn't even make a derivation of CListCtrl. It would make more sense, IMO, to create a CListCtrlManager class that handles things such as you suggest and then handles populating an associated CListCtrl.
Thing is if you wish to derive from a CListCtrl then it is USUALLY done for handling owner draw. There is very little functionality that REQUIRES a derivation. For example I have a derived list ctrl that provides row colouring based on certain information as well as a checkbox in the list view. To handle that I had to set the owener draw flag and handle list ctrl drawing directly, but you do not need to make a derivation to handle the functionality you desire.
|
1,329,163 | 1,329,178 | How to write an unsigned short int literal? | 42 as unsigned int is well defined as "42U".
unsigned int foo = 42U; // yeah!
How can I write "23" so that it is clear it is an unsigned short int?
unsigned short bar = 23; // booh! not clear!
EDIT so that the meaning of the question is more clear:
template <class T>
void doSomething(T) {
std::cout << "unknown type" << std::endl;
}
template<>
void doSomething(unsigned int) {
std::cout << "unsigned int" << std::endl;
}
template<>
void doSomething(unsigned short) {
std::cout << "unsigned short" << std::endl;
}
int main(int argc, char* argv[])
{
doSomething(42U);
doSomething((unsigned short)23); // no other option than a cast?
return EXIT_SUCCESS;
}
| You can't. Numeric literals cannot have short or unsigned short type.
Of course in order to assign to bar, the value of the literal is implicitly converted to unsigned short. In your first sample code, you could make that conversion explicit with a cast, but I think it's pretty obvious already what conversion will take place. Casting is potentially worse, since with some compilers it will quell any warnings that would be issued if the literal value is outside the range of an unsigned short. Then again, if you want to use such a value for a good reason, then quelling the warnings is good.
In the example in your edit, where it happens to be a template function rather than an overloaded function, you do have an alternative to a cast: do_something<unsigned short>(23). With an overloaded function, you could still avoid a cast with:
void (*f)(unsigned short) = &do_something;
f(23);
... but I don't advise it. If nothing else, this only works if the unsigned short version actually exists, whereas a call with the cast performs the usual overload resolution to find the most compatible version available.
|
1,329,181 | 1,329,319 | The behavior of overlapped vector::insert | Where does the C++ standard declare that the pair of iterators passed to std::vector::insert must not overlap the original sequence?
Edit: To elaborate, I'm pretty sure that the standard does not require the standard library to handle situations like this:
std::vector<int> v(10);
std::vector<int>::iterator first = v.begin() + 5;
std::vector<int>::iterator last = v.begin() + 8;
v.insert(v.begin() + 2, first, last);
However, I was unable to find anything in the standard, that would prohibit the ranges [first, last) and [v.begin(), v.end()) to overlap.
| 23.1.1/4 Sequence requirements has:
expression: a.insert(p,i,j)
return type: void
precondition: i,j are not iterators into a. inserts copies of elements in[i,j) before p.
So i and j cannot be iterators into your vector.
It makes sense, as during the insert operation, the vector may need to resize itself, and so the existing elements may first be copied to a new memory location (there by invalidating the current iterators).
|
1,329,191 | 1,329,232 | Is it legal C++ to use a typedef in a method declaration but the canonical type in the method definition? | The GNU C++ (g++ -pedantic -Wall) accepts this:
typedef int MyInt;
class Test
{
public:
MyInt foo();
void bar(MyInt baz);
};
int Test::foo()
{
return 10;
}
void Test::bar(int baz)
{
}
int main(void)
{
Test t;
t.bar(t.foo());
return 0;
}
Is it legal C++? Are other compilers likely to accept it?
| Yes it is legal:
7.1.3 The typedef specifier
A name declared with the typedef
specifier becomes a typedef-name.
Within the scope of its declaration, a
typedef-name is syntactically
equivalent to a keyword and names the
type associated with the identifier in
the way described in clause 8. A
typedef-name is thus a synonym for
another type. A typedef-name does not
introduce a new type the way a class
declaration (9.1) or enum declaration
does.
|
1,329,223 | 1,329,257 | Circular reference in C++ without pointers | Is there a way to define circular references without using pointers?
I need to have somthing like this:
struct A;
struct B {
A a;
};
struct A {
B b;
};
Thanks!
| You can use references instead
struct A;
struct B {
A& a;
};
struct A {
B b;
};
But no it's not possible to create a circular reference without some level of indirection. What your sample is doing is not even creating a circular reference, it's attempting to create a recursive definition. The result would be a structure of infinite size and hence not legal.
|
1,329,415 | 1,460,123 | how to pass a stl vector to a function which takes a const [] (c++) | i have a 3d stl vector,
vector<vector<vector<double> > > mdata;
i also have a function
myfun(const double ya[]);
to be more precise, it's a function from the GNU Scientific Library,
gsl_spline_init(gsl_spline * spline, const double xa[], const double ya[], size_t size);
but this is not related to my problem.
so now i want to pass the 'last' dimension of data to myfun. i've been trying this:
for (int s = 0; s < msize; s++) {
accelerators = new gsl_interp_accel*[msize];
splines = new gsl_spline*[msize];
for (int i = 0; i < msize; i++) {
accelerators[i] = gsl_interp_accel_alloc();
splines[i] = gsl_spline_alloc(gsl_interp_cspline_periodic, msize+1);
gsl_spline_init(splines[i], &(*mgrid.begin()), &(*mdata[s][i].begin()), msize+1);
}
}
But the compiler (g++, 64bit, Ubuntu), complains:
In member function
‘std::vector<std::vector<std::vector<double,
std::allocator<double> >,
std::allocator<std::vector<double,
std::allocator<double> > > >,
std::allocator<std::vector<std::vector<double,
std::allocator<double> >,
std::allocator<std::vector<double,
std::allocator<double> > > > > >
SimpleAmfCalculator::interp_m(int)’:
Calculator.cpp:100: error: cannot
convert ‘std::vector<double,
std::allocator<double> >*’ to ‘const
double*’ for argument ‘3’ to ‘int
gsl_spline_init(gsl_spline*, const
double*, const double*, size_t)’ make:
*** [Calculator.o] Error 1
Any help is greatly apprecitated!
| So, the following seems to work for me:
#include <vector>
void fun(const double data[])
{
}
int main()
{
std::vector<std::vector<std::vector<double> > > data3d;
....
fun(&(data3d[0][0].front()));
}
|
1,329,994 | 1,330,056 | MATLAB functions in C++ | Does anyone know a resource where we can obtain FREE C++ libraries for MATLAB functions? For example, linear algebra problems can be solved using LAPACK and BLAS.
Also, MATLAB in a .NET project is out of the question - I'm talking about direct C++ implementations of popular MATLAB functions (I don't know which functions I need in C++ yet but the functions used are not going to be esoteric).
Any suggestions about such resources?
| I've never heard of a comprehensive port of matlab functionality to C++. That being said, almost everything matlab does exists within a C/C++ library somewhere, some off the top of my head:
LAPACK, BLAS, you already mentioned these, and there are a few good implementations, the most notable (free) one being ATLAS.
FFT is implemented in matlab via the fftw library
There are loads of fast open-source image libraries out there, ie. interpolation, filtering.
There are really good OOP matrix libraries out there, boost has a nice one.
After that, well figure out what you need and there is a good chance someone has implemented it in C/C++.
|
1,330,074 | 1,330,096 | How does spy++ find out what is the window at a certain point on the screen? | I am curious how spy++ Finder Tool finds out the window handle for the window over which the mouse is.
Is there any WIN32 function for getting the handle of the topmost window that occupies a certain pixel on the display?
| There is a WindowFromPoint() function.
|
1,330,316 | 1,330,333 | what's the correct way of writing this code? | typedef boost::shared_ptr<config_value_c> config_value_ptr;
typedef std::vector<config_value_ptr> config_value_vec;
config_value_vec config;
typeof (config.iterator ()) it = config.iterator ();
I want to extract an iterator to an array of boost pointers to class config_value_c. I know I can specify the iterator as std::vector<config_value_ptr>::iterator but I want to do this in a type-agnostic fashion so if I ever change the vector to a list I don't have to go back and update the code. Is that possible? Thanks.
I know typeof is not a real keyword, and I know of typeid but it doesn't do what I want.
| I think you want:
config_value_vec::iterator it = config.begin();
The next edition of the C++ standard (C++0x) will allow you to do:
auto it = config.begin();
|
1,330,550 | 1,330,559 | C++ Compare char array with string | I'm trying to compare a character array against a string like so:
const char *var1 = " ";
var1 = getenv("myEnvVar");
if(var1 == "dev")
{
// do stuff
}
This if statement never validates as true... when I output var1 it is "dev", I was thinking maybe it has something to do with a null terminated string, but the strlen of "dev" and var1 are equal... I also thought maybe var1 == "dev" was comparing "dev" against the memory location of var1 instead of the value. *var1 == "dev" results in an error.... tried many things, probably a simple solution for the saavy c++ developer (I havent coded c++ in a looong time).
edit:
we've tried
if(strcmp(var1, "dev") == 0)
and
if(strncmp(var1, "dev", 3) == 0)
Thanks
edit: After testing at home I'm just going to suggest my co-worker changes the datatype to a string. I believe he was comparing a char array of a large size against a string. I put together a program that outputs sizeof, strlen, etc to help us work through it. Thanks to everyone for the help.
| Use strcmp() to compare the contents of strings:
if (strcmp(var1, "dev") == 0) {
}
Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char* to a char* using the equality operator won't work as expected, because you are comparing the memory locations of the strings rather than their byte contents. A function such as strcmp() will iterate through both strings, checking their bytes to see if they are equal. strcmp() will return 0 if they are equal, and a non-zero value if they differ. For more details, see the manpage.
|
1,331,292 | 1,331,377 | C++ rely on implicit conversion to bool in conditions? | I found the following rule in a coding standards sheet :
Do not rely on implicit conversion to bool in conditions.
if (ptr) // wrong
if (ptr != NULL) // ok
How reasonable/usefull is this rule?
How much overload on the compiled code?
| In the strictest sense, you can rely on implicit conversions to bool. Backwards compatibility with C demands it.
Thus it becomes a question of code readability. Often the purpose of code standards is to enforce a sameness to the code style, whether you agree with the style or not. If you're looking at someone else's standard and wondering if you should incorporate it into your own, go ahead and debate it - but if it's your company's long-standing rule, learn to live with it.
P.S. I just joined an organization that has the same rule. I'm actually fine with it because I've always believed that explicit is better than implicit. The one thing I can't abide though is bool condition; ... if (condition == true), which so redundant that it grates on my eyes.
Any decent compiler should generate the same code whether the check is implicit or explicit, so that shouldn't be a consideration.
|
1,331,318 | 1,331,325 | How an 'if (A && B)' statement is evaluated? | if( (A) && (B) )
{
//do something
}
else
//do something else
The question is, would the statement immediately break to else if A was FALSE. Would B even get evaluated?
I ask this in the case that B checking the validity of an array index say array[0] when the array is actually empty and has zero elements. Therefore throwing a segfault because we are trying to access something that is out of bounds of the array. Specifically
if( (array.GetElements() > 0) && (array[0]))
array[0]->doSomething();
else
//do nothing and return
This may be dangerous if array[0] actually gets evaluated because it segfaults without the first check to the left of the '&&'. Precedence tells me that the left side will definitely take precedence but it doesn't tell me that it won't evaluate the right side if the left is FALSE.
| In C and C++, the && and || operators "short-circuit". That means that they only evaluate a parameter if required. If the first parameter to && is false, or the first to || is true, the rest will not be evaluated.
The code you posted is safe, though I question why you'd include an empty else block.
|
1,331,696 | 1,331,708 | calling class name in the header file | I just stumbled a c++ code with a calling of a class name in the upper part of the header file for example
class CFoo;
class CBar
{
....
};
My question is, what is class CFoo for?
Thanks alot!
| This is called a forward declaration. It means that there IS a class named CFoo, that will be defined later in the file (or another include). This is typically used for pointer members in classes, such as:
class CFoo;
class CBar {
public:
CFoo* object;
};
It is a hint to the C++ compiler telling it not to freak out that a type name is being used without being defined, even though it hasn't seen the full definition for CFoo yet.
|
1,331,821 | 1,331,865 | Fixed-width Floating-Point Numbers in C/C++ | int is usually 32 bits, but in the standard, int is not guaranteed to have a constant width. So if we want a 32 bit int we include stdint.h and use int32_t.
Is there an equivalent for this for floats? I realize it's a bit more complicated with floats since they aren't stored in a homogeneous fashion, i.e. sign, exponent, significand. I just want a double that is guaranteed to be stored in 64 bits with 1 sign bit, 10 bit exponent, and 52/53 bit significand (depending on whether you count the hidden bit).
| According to the current C99 draft standard, annex F, that should be double. Of course, this is assuming your compilers meet that part of the standard.
For C++, I've checked the 0x draft and a draft for the 1998 version of the standard, but neither seem to specify anything about representation like that part of the C99 standard, beyond a bool in numeric_limits that specifies that IEEE 754/IEC 559 is used on that platform, like Josh Kelley mentions.
Very few platforms do not support IEEE 754, though - it generally does not pay off to design another floating-point format since IEEE 754 is well-defined and works quite nicely - and if that is supported, then it is a reasonable assumption that double is indeed 64 bits (IEEE 754-1985 calls that format double-precision, after all, so it makes sense).
On the off chance that double isn't double-precision, build in a sanity check so users can report it and you can handle that platform separately. If the platform doesn't support IEEE 754, you're not going to get that representation anyway unless you implement it yourself.
|
1,331,876 | 1,405,860 | Debugging shell extension in Windows 7 | I'm trying to debug shell extension (IContextMenu) in Windows 7 with Visual C++ 2008. I have set DesktopProcess=1 in the registry and set host app to explorer.exe. But when I start the debugger, it launches explorer.exe and then detaches from the process. DllMain of the shell extension isn't called.
The same code with exactly the same settings launched in debugger without any problems in Windows XP + Visual C++ 2008.
Any thoughts how to debug the shell extension in Win7?
| Try launching explorer and THEN attaching the debugger to it.
|
1,331,954 | 1,331,972 | Is it possible to kill a C++ application on Windows XP without unwinding the call stack? | My understanding is that when you kill a C++ application through Task Manager in Windows XP, the application is still "cleanly" destructed - i.e. the call stack will unwind and all the relevant object destructors will be invoked. Not sure if my understanding is wrong here.
Is it possible to kill such an application immediately, without unwinding the stack?
For example, the application may employ RAII patterns which will destroy or release resources when an object is destructed. If the traditional "kill process" through Task Manager is graceful, providing a way to kill the application immediately would allow me to test ungraceful shutdown (e.g. a power outage).
Edit:
Just to clarify, I was after an existing utility or program that would allow me to do this. I should be able to use the solution on programs that I don't have the source code for, meaning that a programmatic solution is not really acceptable.
Edit:
Just to provide more context, sometimes I have to work with 3rd party services which are very intrusive (e.g. nagging me to reboot every hour). Since I know that I don't need to reboot, I want to kill the process/service so it doesn't nag me anymore. Unfortunately some of the 3rd party developers were "smart" enough to prevent me from doing this, and when I kill the process through Task Manager, the system will reboot immediately (I'm guessing that are using RAII to achieve this).
| I believe task manager tries a "nice" shutdown by sending a WM_CLOSE message, then if the application doesn't respond it's killed.
This call should kill the process immediately with no warning:
TerminateProcess
e.g.:
TerminateProcess(GetCurrentProcess(), 1);
Update:
You may find this article interesting:
Quitting time: exiting a C++ program
Update 2:
I should be able to use the solution on programs that I don't have the source code for
Hmm, well this is undesirable behavior 99.9% of the time.
SysInternals has a utility called pskill:
http://technet.microsoft.com/en-us/sysinternals/bb896683.aspx
but I'm not sure how "nice" it is.
You might need to roll your own, but it should be pretty easy:
DWORD pid = <get pid from command line>;
TerminateProcess(OpenProcess(PROCESS_TERMINATE, FALSE, pid));
|
1,332,015 | 1,332,080 | using class specific set_new_handler | For class specific new_handler implementation, i came across the following example in book "effective c++". This looks problem in multithreaded environment, My Question is how to achieve class specific new_handler in multithreaded environment?
void * X::operator new(size_t size)
{
new_handler globalHandler = // install X's
std::set_new_handler(currentHandler); // handler
void *memory;
try { // attempt
memory = ::operator new(size); // allocation
}
catch (std::bad_alloc&) { // restore
std::set_new_handler(globalHandler); // handler;
throw; // propagate
} // exception
std::set_new_handler(globalHandler); // restore
// handler
return memory;
}
| You're right. This is probably not thread safe. You might want to consider an alternative approach like using the nothrow version of new instead:
void* X::operator new(std::size_t sz) {
void *p;
while ((p = ::operator new(sz, std::nothrow) == NULL) {
X::new_handler();
}
return p;
}
This will cause your class-specific handler to be called whenever memory allocation fails. I wouldn't do this until you really understand all of the headaches surrounding overloading operator new. In particular, read Herb Sutter's two part article To New, Perchance To Throw, Part 1 and Part 2. Interestingly enough, he says to avoid the nothrow version... hmmm.
|
1,332,031 | 1,332,490 | Linux Network Interface Usage Monitoring in C/C++ | I am in a situation where I am extremely bandwidth limited and must devote most of the bandwidth to transferring one type of measurement data. Sometimes I will be sending out lots of this measurement data and other times I will just be waiting for events to occur (all of this is over a TCP socket).
I would like to be able to stream out the full data capture file (different than the measurements) in the background at a speed that is inversely proportional to the amount of measurements that I am sending back.
I am looking for a way to monitor how many bytes are being sent out the network interface in much the same was as the system monitor on Ubuntu. The source code for the system monitor relies on gnome libraries and since my program is on an embedded device, I would like to reduce the number of external libraries that I use. Does anybody know of a way to do this in C/C++ without many additional libraries on a standard Linux distribution?
| One of the simplest ways is to parse the file: /proc/net/dev
Mine contains:
Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo: 44865 1431 0 0 0 0 0 0 44865 1431 0 0 0 0 0 0
eth0:150117850 313734 0 0 0 0 0 0 34347178 271210 0 0 0 0 0 0
pan0: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
You could then write a parser that uses nothing other than the C/C++ libraries.
|
1,332,067 | 1,332,101 | Problem using OpenProcess and ReadProcessMemory | I'm having some problems implementing an algorithm to read a foreign process' memory. Here is the main code:
System.Diagnostics.Process.EnterDebugMode();
IntPtr retValue = WinApi.OpenProcess((int)WinApi.OpenProcess_Access.VMRead | (int)WinApi.OpenProcess_Access.QueryInformation, 0, (uint)_proc.Id);
_procHandle = retValue;
WinApi.MEMORY_BASIC_INFORMATION[] mbia = getMemoryBasicInformation().Where(p => p.State == 0x1000).ToArray();
foreach (WinApi.MEMORY_BASIC_INFORMATION mbi in mbia) {
byte[] buffer = Read((IntPtr)mbi.BaseAddress, mbi.RegionSize);
foreach (IntPtr addr in ByteSearcher.FindInBuffer(buffer, toFind, (IntPtr)0, mbi.RegionSize, increment)) {
yield return addr;
}
}
Read() ... method
if (!WinApi.ReadProcessMemory(_procHandle, address, buffer, size, out numberBytesRead)) {
throw new MemoryReaderException(
string.Format(
"There was an error with ReadProcessMemory()\nGetLastError() = {0}",
WinApi.GetLastError()
));
}
Although generally it seems to work correctly, the problem is that for some memory values ReadProcessMemory is returning false, and GetLastError is returning 299. From what I've googled, it seems to happen on vista because some params of OpenProcess were updated. Anyone knows what this is about? And what values should I try? Notice that as they changed, I wouldn't want to know if it's VM_READ or so, I want to know exactly what the values are.
EDIT: maybe it has something to do with not calling VirtualProtect()/VirtualProtectEx()? as seen on this SO url: WriteProcessMemory/ReadProcessMemory fail
Edit2: That was it! ^^ That is the solution, calling to VirtualProtectEx() first and after ReadProcessMemory()!
| C:\Debuggers>kd -z C:\Windows\notepad.exe
0:000> !error 0n299
Error code: (Win32) 0x12b (299) - Only part of a ReadProcessMemory
or WriteProcessMemory request was completed.
This means you tried to read a block that was partially unmapped addresses (i.e. if the app itself did this, it'd AV)
|
1,332,071 | 1,332,125 | Is SeDebugPrivilege() api function the same as System.Diagnostics.Process.EnterDebugMode? | What the title says. Are they the same? I've noticed that the first does have arguments and such, but are they going to give the same end result?
| Yes.
At least according to the documentation which states:
"Puts a Process component in state to
interact with operating system
processes that run in a special mode
by enabling the native property
SeDebugPrivilege on the current
thread."
|
1,332,142 | 1,332,171 | Should I link sqlite3 as plain object code or as a static library in a C++ application? | I am building an application in C++ which uses sqlite3 as an embedded database. The source for sqlite3 is distributed as an amalgamated source code file sqlite3.c and two header files.
What are the relative advantages or disadvantages of linking the sqlite3 code directly into my program binary versus compiling sqlite3 as a static library and linking it in that way?
I have already decided against linking to the sqlite3 code as a dynamic library.
| It really doesn't make much difference.
Assuming you have some sort of makefile environment the sqlite.c will only be built once if you don't change anything and the linker will combine the object file in almost the same way as plugging in a static library.
|
1,332,146 | 1,332,524 | C++ game, class design and responsibilities | I've just read some related questions that came up when I typed the subject, so I'll try not to repeat those.
I've recently started revisiting a learning project I started about two or three years ago - a C++ port of a Mega Man engine. Yes I used ripped sprites. I also am using a game engine library for drawing, music, and input.
My original code was atrocious. While it could (but barely) be called OO, it missed the point entirely. I've starting adding things like interfaces and cut out a lot of repetitive code. There are some things I'm not sure about, because game design gets very complex at times.
The object that represents my game library is currently global (I know globals are usually bad) because many objects may rely on it here and there for things like loading their art or music. What's the best way to go about pulling that object out of global scope, without having to pass fifty parameters to everything that would otherwise use it directly?
Next question: As we all know, Mega Man shoots lots of little white projectiles. Currently, the Player object is responsible for the Projectile objects he fires, updating their position and such (literally, calling the Projectile::Update() method once for each shot, inside the Player::Update() method). Is this the wrong way to do it? My first improvement was have all of these objects implement a DrawnObject interface, so that my game can just draw everything. Doing the same thing for Updates would mean I take control of the projectiles away from Player and give it to some broader Game object. The reason I'm hesitant about this is that it feels like the God object antipattern. Or am I misunderstanding said antipattern? There is still additional complexity involved - the projectiles die if they leave the visible screen, so any call to update the projectile would require the caller to have access to the screen object.
That's all for now, I'll come back with more problems when I reach them. End of first post!
| As far as making a class global I would use a singleton, then just call Game::GetInstance() which would return a pointer to the global class.
As far as the particles, the way I've always handled games was to make a class that manages all the objects. In my games main loop I would call that classes UpdateObjects function which would go through a list of items it has stored and call each of there Update functions. Same thing with Render and Collision.
|
1,332,602 | 1,333,057 | How to serialize derived template classes with Boost.serialize? | I'd like to serialize/unserialize following classes:
class Feature{
...
virtual string str()=0;
};
template<typename T>
class GenericFeature : public Feature{
T value;
...
virtual string str();
};
I read boost.serialize docs and the sayed that you must register classes.
I can register them in constructor. But there will be problems with loading, as registration will be dynamic, not static(As I understood, you must register classes prior to serialization/deserialization).
How to save/load these type of classes?
| First tell boost that Feature is abstract, is not always needed:
BOOST_SERIALIZATION_ASSUME_ABSTRACT(Feature);
The serialization method should look more or less like this:
template<class Archive>
void Feature::serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(some_member);
}
template<typename T,class Archive>
void GenericFeature<T>::serialize(Archive & ar, const unsigned int version)
{
ar & boost::serialization::base_object<Feature>(*this); //serialize base class
ar & BOOST_SERIALIZATION_NVP(some_other_member);
}
Now the tricky point is to register class in serialize/deserialize:
boost::archive::text_iarchive inputArchive(somesstream);
boost::archive::text_oarchive outputArchive(somesstream);
//something to serialize
Feature* one = new GenericFeature<SomeType1>();
Feature* two = new GenericFeature<SomeType2>();
Feature* three = new GenericFeature<SomeType3>();
//register our class, must be all of posible template specyfication
outputArchive.template register_type< GenericFeature<SomeType1> >();
outputArchive.template register_type< GenericFeature<SomeType2> >();
outputArchive.template register_type< GenericFeature<SomeType3> >();
// now simply serialize ;-]
outputArchive << one << two << three;
// register class in deserialization
// must be the same template specification as in serialize
// and in the same correct order or i'm get it wrong ;-D
inputArchive.template register_type< GenericFeature<SomeType1> >();
inputArchive.template register_type< GenericFeature<SomeType2> >();
inputArchive.template register_type< GenericFeature<SomeType3> >();
Feature* another_one;
Feature* another_two;
Feature* another_three;
// and deserialize ;-]
inputArchive >> another_one >> another_two >> another_three;
If you need to hide explicit registering somewhere and make it more automatic, there is idea to make special functor template that register one derived class, create all avaible and put in a single list, that one static method of class Feature would register them all. However the problem will be that you need registration for all version of archive, right now i dont know if polymorphic archive will do the job or not.
|
1,332,632 | 1,332,657 | defining bunch of static methods in c++ | Which is appropriate:
class xyz {
static int xyzOp1() { }
static int xyzOp2() { }
};
OR
namespace xyz {
static int xyzOp1() {}
static int xyzOp2() {}
};
Is there something specific which we can get when we define using class tag in comparision with namespace tag?
Also is there any different in memory management, which we need to worry?
| Without seeing the body of these functions, I would say that namespaces are more appropriate. With namespaces, you can have using statements, so that you don't have to fully-qualify the function names when calling them.
The only case in which to use classes is when the static methods have any relationship with objects of the class, e.g. when they need to access private members of instances. From your description, it seems that you won't be creating any instances of xyz, so you shouldn't be using classes here.
From a memory management point of view, there is no difference between these approaches.
|
1,332,678 | 1,333,121 | Priority when choosing overloaded template functions in C++ | I have the following problem:
class Base
{
};
class Derived : public Base
{
};
class Different
{
};
class X
{
public:
template <typename T>
static const char *func(T *data)
{
// Do something generic...
return "Generic";
}
static const char *func(Base *data)
{
// Do something specific...
return "Specific";
}
};
If I now do
Derived derived;
Different different;
std::cout << "Derived: " << X::func(&derived) << std::endl;
std::cout << "Different: " << X::func(&different) << std::endl;
I get
Derived: Generic
Different: Generic
But what I want is that for all classes derived from Base the specific method is called.
So the result should be:
Derived: Specific
Different: Generic
Is there any way I can redesign the X:func(...)s to reach this goal?
EDIT:
Assume that it is not known by the caller of X::func(...) if the class submitted as the parameter is derived from Base or not. So Casting to Base is not an option.
In fact the idea behind the whole thing is that X::func(...) should 'detect' if the parameter is derived from Base or not and call different code.
And for performance reasons the 'detection' should be made at compile time.
| I found a VERY easy solution!
class Base
{
};
class Derived : public Base
{
};
class Different
{
};
class X
{
private:
template <typename T>
static const char *intFunc(const void *, T *data)
{
// Do something generic...
return "Generic";
}
template <typename T>
static const char *intFunc(const Base *, T *data)
{
// Do something specific...
return "Specific";
}
public:
template <typename T>
static const char *func(T *data)
{
return intFunc(data, data);
}
};
This works great and is very slim!
The trick is to let the compiler select the correct method by the (otherwise useless) first parameter.
|
1,332,754 | 1,332,965 | CMFCPropertyGridProperty numeric input | I'm using MFC feature pack and I have a dockable properties window. How do I restrict the user from typing any other characters but numbers alone in the values field?
Thanks...
| One of the constructors for the CMFCPropertyGridProperty class has a parameter lpszValidChars which you can use to limit the characters that can be input. e.g.
CMFCPropertyGridProperty* pProp = new CMFCPropertyGridProperty(_T("Numeric Value"),
(_variant_t) 250l, _T("A numeric value"), NULL, NULL, NULL,
_T("0123456789"));
The last parameter here limits the characters that can be entered.
|
1,332,762 | 1,332,862 | native win32 gui programming in c++ or choose wxWidgets? | i like to write GUI software ( i have no experience in GUI programming )
i need it to be small as possible and fast GUI and native Look and Feel in one self contained exe . only on windows from windows 2000 to windows 7 ( or what ever it called ) .
what will be the best choice ? win32 api or wxWidgets?
| You should take a look at the Windows Template Library (WTL).
|
1,332,928 | 1,332,944 | completely removing a vector c++ | I'm having problems removing a vector from a "multidimensional vector"
I would like to achieve this:
1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2
3 3 3 3 4 4 4 4
4 4 4 4
for example
vector<vector<int>>vec;
for i...//give vec values...
vec[3].erase(vec.begin(),vec.end());
It seems like using vector.erase() or vector.clear() leaves an empty vector at the "third row"
Is there a way to completetly remove that vector so that
vec[3]=4 4 4 4
Thanx for a great forum...
/Bux
| The following line removes the third element of vec. If it had four elements, it will have three after the line is executed.
vec.erase(vec.begin() + 2);
The following line, on the other hand, will leave the third vector empty.
vec[2].clear();
|
1,333,069 | 1,333,115 | pointer arithmetic on vectors in c++ | i have a std::vector, namely
vector<vector<vector> > > mdata;
i want pass data from my mdata vector to the GSL function
gsl_spline_init(gsl_spline * spline, const double xa[], const double ya[], size_t size);
as ya. i already figured out that i can do things like
gsl_spline_init(spline, &(mgrid.front()), &(mdata[i][j][k].front()), mgrid.size());
this is fine if i want to pass the data from mdata for fixed i,j to gsl_spline_init().
however, now i would need to pass along the first dimension of mdata, so for fixed j,k.
i know that for any two fixed indices, all vectors along the remaining dimensions have the same length, so my vector is a 'regular cube'. so the offset between all the values i need should be the same.
of course i could create a temporary vector
int j = 123;
int k = 321;
vector<double> tmp;
for (int i = 0: i < mdata.size(); i++)
tmp.push_back(mdata[i][j][k]);
gsl_spline_init(spline, &(mgrid.front()), &(tmp.front()), mgrid.size());
but this seems too complicated. perhaps there is a way to achieve my goal with pointer arithmetic?
any help is greatly appreciated :)
| You really can't do that without redesigning the array consumer function gsl_spline_init() - it relies on the data passed being a contiguous block of data. This is not the case with you three-level vector - not only it is a cube but also each level has a separate buffer allocated on heap.
|
1,333,176 | 1,333,193 | C++ and QT4.5 - is passing a const int& overkill? Does pass by reference helps in signals/slots? | Two questions rolled into one here...
I have a number of functions which are called multiple times per frame for a real-time video processing application. Taking advice about const and pass by reference, the functions have a signature somewhat like this
void processSomething(const int& value);
As I keep typing the few extra characters, I am wondering if this is overkill.
Second question, well, on the subject of pass by reference, within the slots/signals mechanism of QT, does pass by reference helps to prevent copying of objects as in a normal function call?
| Yes, this is overkill and will actually result in slower code than if you passed the int by value. An int is four bytes; a reference (essentially a memory address) is either also four bytes (on a 32-bit machine) or eight bytes (on a 64-bit machine). So you may actually need to pass more information to the function -- and additionally, you have the overhead of dereferencing that reference.
If you're passing something bigger than an int, however, it's more efficient to use a const reference, because you can pass just four or eight bytes instead of having to copy the whole object.
Edit Regarding Qt: Yes, if the slot takes a const reference to an object, then the reason for that is to save the overhead of copying the object.
|
1,333,296 | 1,333,328 | How virtual is this? | can you explain me why:
int main (int argc, char * const argv[]) {
Parent* p = new Child();
p->Method();
return 0;
}
prints "Child::Method()", and this:
int main (int argc, char * const argv[]) {
Parent p = *(new Child());
p.Method();
return 0;
}
prints "Parent::Method()"?
Classes:
class Parent {
public:
void virtual Method() {
std::cout << "Parent::Method()";
}
};
class Child : public Parent {
public:
void Method() {
std::cout << "Child::Method()";
}
};
Thanks,
Etam.
| Your second code copies a Child object into a Parent variable. By a process called slicing it loses all information specific to Child (i.e. all private fields partial to Child) and, as a consequence, all virtual method information associated with it.
Also, both your codes leak memory (but I guess you know this).
You can use references, though. E.g.:
Child c;
Parent& p = c;
p.Method(); // Prints "Child::Method"
|
1,333,339 | 1,337,834 | astyle formatting multiple line << | I'm using astyle which is great for applying standard style to existing code. However I've noticed that when it comes across this:
ostringstream myStream;
myStream << 1
<< 2;
it reformats to this:
ostringstream myStream;
myStream << 1
<< 2;
Here's my options file: (version 1.23)
--indent=spaces
--brackets=break
--indent-switches
--indent-namespaces
--min-conditional-indent=4
--break-closing-brackets
--pad-paren-in
--unpad-paren
--convert-tabs
Is there any way to make it line up the "<<" on the next line?
Edit:
I also tried version 1.22 with the following file (test.cpp):
void main()
{
ostringstream myStream;
myStream << 1
<< 2;
}
with the following options (format.txt):
--indent=spaces
--brackets=break-closing
--indent-switches
--indent-namespaces
--min-conditional-indent=4
--pad=paren-in
--unpad=paren
--convert-tabs
and the following command line:
astyle --options=format.txt test.cpp
which produced this:
void main()
{
ostringstream myStream;
myStream << 1
<< 2;
}
| Final Conclusion is it's a bug see bottom
I tried to replicate your problem and was unable to get the behavior you are talking about (OP question update negates this)
Edit: (deleted content to update)
Parameter names have changed between 1.22 and 1.23.
If neither solves your problem, try uploading more code as an example, or otherwise try to replicate your problem using only the code you pasted here. (Done by OP)
I've also found that the order of the options seems to have made a difference on occasion. For example:
astyle --indent=tab --style=ansi test.cpp
is not the same as:
astyle --style=ansi --indent=tab test.cpp
Specifying the "--style=ansi" second effectively negates the "--indent=tab".
I would not be surprised if this might be your issue.
...But after playing around with this for 20 min, I'm convinced it's an astyle bug.
Edit to include link to bug: bug Thanks Markh44
|
1,333,348 | 1,333,423 | Freeing in the destructor is causing a memory leak | I have to write a stack class template using arrays in C++ for my assignment.
Here is my code:
#include <iostream>
template <typename Type>
class Stack {
private:
int top;
Type items[];
public:
Stack() { top = -1; };
~Stack() { delete[] items; };
void push(Type);
bool isEmpty() const;
Type pop();
Type peek() const;
};
int main (int argc, char *argv[]) {
Stack<double> st;
return 0;
}
template<typename Type>
void Stack<Type>::push(Type item) {
top++;
if(top == sizeof(items) / sizeof(Type)) {
Type buff[] = new Type[top];
std::copy(items,items+top,buff);
delete[] items;
items = new Type[2*top];
std::copy(buff,buff+top,items);
delete[] buff;
}
items[top] = item;
}
template<typename Type>
bool Stack<Type>::isEmpty() const {
return top == -1 ? true : false;
}
template<typename Type>
Type Stack<Type>::pop() {
//TODO
return items[top--];
}
template<typename Type>
Type Stack<Type>::peek() const{
//TODO
return items[top-1];
}
It compiled fine using "g++ -Wall", however when I run the program, I got this error:
* glibc detected * ./lab3: munmap_chunk(): invalid pointer: 0x00007fff41a3cdf8
After trying out a bit with GDB, I found out the error arose from the line:
'free[] items' in the destructor.
I don't understand why freeing an array results in a memory leak? Any clues?
| You haven't new'd items, so you can't delete it in the destructor. Assuming you require 'Stack' to be a dynamically sized class then the items array must be dynamically allocated in which case the declaration for items should be
Type *items; (as hacker mentions above)
and the constructor should call 'items = new Type[ARRAY_SIZE]' to allocate the memory, or at the very least initially assign the 'items' pointer to NULL.
Edit based on comments -
To complete and secure the memory allocation responsibilities for this class you should also include a copy constructor and an assignment operator which allocates new memory and copies the values stored in items to the new object. This avoids the pointer simply being copied by the compiler generated copy constructor or assignment operator which would lead to multiple objects pointing to the same dynamically allocated memory. Upon destruction of the first of these objects this memory will be deleted. Further use of the now deleted memory by the other objects which share the pointer would be likely to result in a crash.
Rather than adding code here I refer you to the code in Martin's answer for this question.
|
1,333,451 | 1,333,899 | Locale-independent "atof"? | I'm parsing GPS status entries in fixed NMEA sentences, where fraction part of geographical minutes comes always after period. However, on systems where locale defines comma as decimal separator, atof function ignores period and whole fraction part.
What is the best method to deal with this issue? Long/latitude string in stored in character array, if it matters.
Example Code:
m_longitude = atof((char *)pField);
Where
pField[] = "01000.3897";
Cross-platform project, compiled for Windows XP and CE.
Comment to solution:
Accepted answer is more elegant, but this answer (and comment) is also worth knowing as a quick fix
| You could always use (modulo error-checking):
#include <sstream>
...
float longitude = 0.0f;
std::istringstream istr(pField);
istr >> longitude;
The standard iostreams use the global locale by default (which in turn should be initialized to the classic (US) locale). Thus the above should work in general unless someone previously has changed the global locale to something else, even if you're running on a non-english platform. To be absolutely sure that the desired locale is used, create a specific locale and "imbue" the stream with that locale before reading from it:
#include <sstream>
#include <locale>
...
float longitude = 0.0f;
std::istringstream istr(pField);
istr.imbue(std::locale("C"));
istr >> longitude;
As a side note, I've usually used regular expressions to validate NMEA fields, extract the different parts of the field as captures, and then convert the different parts using the above method. The portion before the decimal point in an NMEA longitude field actually is formatted as "DDDMM.mmm.." where DDD correspond to degrees, MM.mmm to minutes (but I guess you already knew that).
|
1,333,522 | 1,333,544 | Why does the code crash? | Looking on the internet for C++ brainteasers, I found this example:
#include <iostream>
using namespace std;
class A {
public:
A()
{
cout << "A::A()" << endl;
}
~A()
{
cout << "A::~A()" << endl;
throw "A::exception";
}
};
class B {
public:
B()
{
cout << "B::B()" << endl;
throw "B::exception"; // <- crashes here
}
~B()
{
cout << "B::~B()";
}
};
int main(int, char**) {
try
{
cout << "Entering try...catch block" << endl;
A objectA;
B objectB;
cout << "Exiting try...catch block" << endl;
}
catch (const char* ex)
{
cout << ex << endl;
}
return 0;
}
This is what I thought the program would do:
A::A() will be output to screen when the constructor of objectA is called. Object A is constructed successfully.
B::B() will be output to screen when the constructor of objectB is called.
The constructor of B then throws an exception. Object B is not constructed successfully.
Destructor of objectB is not called as the constructor never completed successfully.
Destructor of objectA will be called as the object goes out of scope when the try block is exited.
However, when I ran the program, it actually crashed at the line marked with <-. Could anybody explain what exactly was going on at that point?
| If you are really coding, not just brainteasing never ever throw exception from destructor. If an exception is thrown during stack-unwinding, terminate() is called. In your case destructor of A has thrown while processing exception that was thrown in B's constructor.
EDIT:
To be more precise (as suggested in comments) - never ever let exception escape destructor. Exceptions that are caught inside destructor make no problem. But if during stack unwinding program has to deal with two exceptions - the one that caused stack unwinding and the one that escaped destructor during unwinding, std::terminate() goes.
|
1,333,524 | 1,333,550 | Developing a facebook app with c++ | I'm a computer science student with experience in C/C++ and I want to have a go at developing
a simple facebook app. Can anyone recommend a good website and/or editor?
Is it doable with C++ or do I need to learn another language?
Thanks
| I assume that you are talking about an internet application.
For the front end (client side), you will need something to enhance your web pages (in Javascript, for example). For the back end (server side), you will need to make database queries so you will need to know SQL as well.
No, I don't think C/C++ is enough.
I would suggest that you investigate some other languages such as PHP or ASP.Net.
|
1,333,527 | 1,333,542 | How do I print to the debug output window in a Win32 app? | I've got a win32 project that I've loaded into Visual Studio 2005. I'd like to be able to print things to the Visual Studio output window, but I can't for the life of me work out how. I've tried 'printf' and 'cout <<' but my messages stay stubbornly unprinted.
Is there some sort of special way to print to the Visual Studio output window?
| You can use OutputDebugString. OutputDebugString is a macro that depending on your build options either maps to OutputDebugStringA(char const*) or OutputDebugStringW(wchar_t const*). In the later case you will have to supply a wide character string to the function. To create a wide character literal you can use the L prefix:
OutputDebugStringW(L"My output string.");
Normally you will use the macro version together with the _T macro like this:
OutputDebugString(_T("My output string."));
If you project is configured to build for UNICODE it will expand into:
OutputDebugStringW(L"My output string.");
If you are not building for UNICODE it will expand into:
OutputDebugStringA("My output string.");
|
1,333,658 | 1,397,402 | Need a Math Editor to write math formulas | Need a Math Editor to integrate to my application written on C# to be able to write math formulas. Can someone help me with this please? Some open source code will be great! Tell me steps, that integrate your suggested application to my application.
| I recommend you to use a MathML based editor. The formula description is a W3C standard.
A open source MathML editor is gNumerator. It's core component and rendering engine are almost complete.
What is gNumerator?
First and foremost, gNumerator is a collection of re-usable components that make up a computer math program. Much of the value will lie in these components, and their usefullness to other developers wishing to re-use them.
To the end user, gNumerator will be a computer math system, vaguely similar to Mathematica, nucalc or Matlab. The primary difference between gNumerator, is first, it is a collection of re-usable components, and second, the use of standard languages such as MathML and JScript for user interaction. As other math programs such as Mathematica or Matlab all use proprietary languages as their form of user input, gNumerator will allow users to input standard MathML or JScript.
But, you say these languages have weak numeric abilities. Well, the 'fitness' of a language for a particular task has relatively little to do with the language itself, and more to do with the libraries availible for that language. Yes, JScript does not ship with any good numerical libraries, that is where GSL, the GNU Scientific Library comes in. One of the libraries of gNumerator will be a .net binding to GSL, this allows it to used directly from and .net language such as c#, (the language gNumerator is written in), and JScript (the gNumerator scripting language) to use the power of GSL directly. The use of GSL will give gNumerator computational capabilities on par with many commercial math packages.
The gNumerator application is will be released under the GNU General Public License, and its' library components (MathML DOM, renderer, interpreter, etc..) will be released under the LGPL, which makes them usable in a commercial application
Libraries:
There are 2 libraries that you can download the source to:
1: MathML Rendering Control
This is a Windows.Forms (winforms) control that displays MathML. All the current published screenshots are only of this control.
2: MathML DOM
This is a faithfull and almost complete implementation in c# of the w3c recomended Document Object Model for MathML This is a core, key component on which most other gNumerator libraries are built.
Here are a screenshot showing it's capabilities
(source: sourceforge.net)
On the other side (the paid), there are great products that can integrate to your project and make it available to edit formulas. One of these is MathType. It's license price is reasonable, just USD$ 97.
|
1,333,660 | 1,356,774 | MFC: How to Identfy if Dialog was created using CPropertySheet or CTabCtrl | In reference to this question:Which is prefered CTabCtrl vs CPropertySheet
I have a DDK that uses MFC which I am new to. The basic example from the DDK implements a simple dialog box with 3 tabs with the "Ok" and "Cancel" button on the right side of the box.
Based on the question from the link above, seems like only CTabCtrl can have that kind of interface??(correct me if i'm wrong) However, looking at the classes involved, it seems like CTabCtrl is not used at all?? Need some explanation about this...
from Class Explorer:
CObject-->
CCmdTarget
CWnd
CDialog
CxxxDlg
CPropertyPage
CIntHelpPropertyPage
CxxxConfigPage
CWinThread
CWinApp
CWinDebugApp
CDriverApp
CxxxApp
CDrvCfg
CxxxDrvCfg
CSrvObj
CChannelObj
CDriverObj
CxxxObj
| There are 2 classes derived from CPropertyPage, which is always used with CPropertySheet. No wonder there is no CTabCtrl. I'd like to explain in detail if you email me the code.
|
1,333,801 | 1,336,179 | How to close dynamically created CDockablePane windows? | In my MFC (Feature Pack) application one can dynamically create docking panes to display charts/tables etc.
However, I don't want to let the user open the same thing twice.
I create a pane like this:
// Create CMyDockablePane pPane
pPane->Create(...);
pPane->EnableDocking(CBRS_ALIGN_ANY);
// Create CRect rcPane
pPane->FloatPane(rcPane);
This seems to work fine.
This is how I tried to check if a pane already exists. A pane is identified by its type (class) and a parameter.
BOOL CanOpenPane(const type_info & paneType, const CMyParameter & parameter) const
{
CMainFrame* pFrm = GetMainFrame();
CDockingManager* pDockMan = pFrm->GetDockingManager();
// Check if there already is a pane of the same type which also has the same parameter.
bool canOpen = true;
CObList panes;
pDockMan->GetPaneList(panes);
POSITION pos = panes.GetHeadPosition();
while (pos)
{
CMyDockablePane* pPane = dynamic_cast<CMyDockablePane*>(panes.GetNext(pos));
if (NULL == pPane) { continue; }
if (paneType == typeid(*pPane) &&
pPane->GetParameter() == parameter)
{
canOpen = false;
break;
}
}
return canOpen;
}
The problem with this is that when I close a pane, this is not recognized. The CDockingManager object still returns the pane in the GetPanes() call.
How can I tell the manager to not return panes that are closed?
or
How can I remove the pane from a pane list, when it's closed?
Update
I dived a bit deeper and found, that the CWnd objects are not actually closed, when clicking the 'x' button in the caption bar, but only their containers.
So the real problem seems to be to really close the panes.
I also changed the question to better reflect the problem.
| As described in my update, the problem for the docking manager giving me closed panes, was that the panes were not actually closed. Only their containers were closed; the panes themselves were just hidden.
So to really close the panes I overrode the following methods in my CMDIFrameWndEx derived main frame class:
BOOL CMainFrame::OnCloseMiniFrame(CPaneFrameWnd* pWnd)
{
if(0 == pWnd->GetPaneCount()) { return TRUE; } // No panes.. allow closing
// Close all child panes of the miniframe that is about to be closed.
//
// Panes are placed inside a mini frame when they have the "floating" status.
// Since I didn't find a way to iterate over the panes of a mini frame
// (CMultiPaneFrameWnd can have several panes), we iterate over all panes
// and close those whose parent frame is pWnd.
CDockingManager* pDockMan = GetDockingManager();
if(NULL != pDockMan)
{
CObList allPanes;
pDockMan->GetPaneList(allPanes, TRUE, NULL, TRUE);
for(POSITION pos = allPanes.GetHeadPosition(); pos != NULL;)
{
CDockablePane* pPane = dynamic_cast<CDockablePane*>(allPanes.GetNext(pos));
if (NULL == pPane) { continue; }
if(pWnd == pPane->GetParentMiniFrame())
{
pPane->PostMessage(WM_CLOSE); // Note: Post instead of Send
}
}
}
return TRUE; // Allow closing
}
And the second:
BOOL CMainFrame::OnCloseDockingPane(CDockablePane* pWnd)
{
CObList paneList;
// We can get CDockablePanes and CTabbedPanes here.
// The tabbed panes contain dockable panes.
CTabbedPane* pTabbed = dynamic_cast<CTabbedPane*>(pWnd);
CDockablePane* pDockable = dynamic_cast<CDockablePane*>(pWnd);
if(NULL != pTabbed)
{
pTabbed->GetPaneList(paneList);
}
else if(NULL != pDockable)
{
paneList.InsertAfter(paneList.GetHeadPosition(), pDockable);
}
// Whatever it was, we now have a list of dockable panes, which we will close.
for(POSITION pos = paneList.GetHeadPosition(); NULL != pos;)
{
CDockablePane* pPane = dynamic_cast<CDockablePane*>(paneList.GetNext(pos));
ASSERT(NULL != pPane);
// Let the window disappear and then recalculate the layout.
// Not doing this causes problems with panes grouped together in a tabbed pane.
pPane->ShowWindow(SW_HIDE);
RecalcLayout();
// Really close the window so the docking manager also doesn't know of it anymore.
pPane->Reset();
pPane->PostMessage(WM_CLOSE); // Note: Post instead of Send
}
return TRUE; // Allow closing
}
|
1,333,849 | 1,337,648 | How to generate a non-const method from a const method? | While striving for const-correctness, I often find myself writing code such as this
class Bar;
class Foo {
public:
const Bar* bar() const { /* code that gets a Bar somewhere */ }
Bar* bar() {
return const_cast< Bar* >(
static_cast< const Foo* >(this)->bar());
}
};
for lots of methods like bar(). Writing these non-const methods which call the const ones by hand is tedious; besides, I feel I am repeating myself – which makes me feel bad.
What can I do to alleviate this task? (Macros and code generators are not allowed.)
Edit: Besides litb's solution I also like my own. :)
| Another way could be to write a template that calls the function (using CRTP) and inherit from it.
template<typename D>
struct const_forward {
protected:
// forbid deletion through a base-class ptr
~const_forward() { }
template<typename R, R const*(D::*pf)()const>
R *use_const() {
return const_cast<R *>( (static_cast<D const*>(this)->*pf)() );
}
template<typename R, R const&(D::*pf)()const>
R &use_const() {
return const_cast<R &>( (static_cast<D const*>(this)->*pf)() );
}
};
class Bar;
class Foo : public const_forward<Foo> {
public:
const Bar* bar() const { /* code that gets a Bar somewhere */ }
Bar* bar() { return use_const<Bar, &Foo::bar>(); }
};
Note that the call has no performance lost: Since the member pointer is passed as a template parameter, the call can be inlined as usual.
|
1,334,055 | 1,335,389 | What Happens When Stack and Heap Collide | I am curious to know what happens when the stack and the heap collide. If anybody has encountered this, please could they explain the scenario.
| In a modern languages running on a modern OS, you'll get either a stack overflow (hurray!) or malloc() or sbrk() or mmap() will fail when you try to grow the heap. But not all software is modern, so let's look at the failure modes:
If the stack grows into the heap, the typically C compiler will silently start to overwrite the heap's data structures. On a modern OS, there will be one or more virtual memory guard pages which prevent the stack from growing indefinitely. As long as the amount of memory in the guard pages is at least as large as the size of the growing procedure's activation record, the OS will guarantee you a segfault. If you're DOS running on a machine with no MMU, you're probably hosed.
If the heap grows into the stack, the operating system should always be aware of the situation and some sort of system call will fail. The implementation of malloc() almost certainly notices the failure and returns NULL. What happens after that is up to you.
I'm always amazed at the willingness of compiler writers to hope that the OS puts guard pages in place to prevent stack overflow. Of course, this trick works well until you start having thousands of threads, each with its own stack...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.