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
915,646
916,998
Blocking functions using OpenMP
I have a GUI application, which listens to a network port from a second thread. I was looking at OpenMP and I was wondering if there are easy ways to create threads like this. I was searching for documentation, but the OpenMP site is not very convenient to navigate. Could someone help?
As far as I understand OpenMP is a compiler-assisted parallelizing framework/library targeted to heavy computations. You hint the compiler which parts of your code (usually loops) can run in parallel. The compiler does its magic (inserting library calls, sharing/unsharing variables, etc.) and, poof, the program can now run faster (sometimes) on several cores. It might be possible to do what you want with OpenMP, I don't know, but I think you are looking at the wrong tool. Doing things directly with pthreads is one alternative.
915,778
915,817
lightweight C++ scripting library
I currently use QtScript for scripting functionality in my C++ application, but it's rather "heavy" on the cpu. When a thread evaluates all the scripts in a loop the cpu usage increases to 90%-100%. Even when i put it to sleep for 1 msec every 5 scripts it stays above 75% cpu usage. Are there any other, easy to implement, scripting frameworks which are much more lighter than QScript? edit: I now realize this is normal behavior and not some hogging bug in QtScript. Still it's interesting to hear what kinds of (lighweight) scripting libraries are available.
Have a look at Lua, it's frequently used in games so the performance must be pretty good.
915,914
915,992
is ipv6 backward compatible with ipv4?
I've got a little udp example program written using ipv4. If I alter the code to ipv6 would I still be able to communicate with anyone using the listener with an ipv4 address? I was looking at porting examples at http://ou800doc.caldera.com/en/SDK_netapi/sockC.PortIPv4appIPv6.html I'm not sure if simply altering the code would ensure that it worked or if I'd have to write it in duel-stack mode.
Yes and no... IPv6 does contain completely different addressing, so you'll have to recode your app to use the alternative headers and structure sizes. However, the IPv4 address range is available within IPv6, the syntax is to add two colons before the standard address (eg ::10.11.12.13). You can also embed IPv4 addresses within IPv6 packets.
916,282
917,710
Instrumentation (diagnostic) library for C++
I'm thinking about adding code to my application that would gather diagnostic information for later examination. Is there any C++ library created for such purpose? What I'm trying to do is similar to profiling, but it's not the same, because gathered data will be used more for debugging than profiling. EDIT: Platform: Linux Diagnostic information to gather: information resulting from application logic, various asserts and statistics.
You might also want to check out libcwd: Libcwd is a thread-safe, full-featured debugging support library for C++ developers. It includes ostream-based debug output with custom debug channels and devices, powerful memory allocation debugging support, as well as run-time support for printing source file:line number information and demangled type names. List of features Tutorial Quick Reference Reference Manual Also, another interesting logging library is pantheios: Pantheios is an Open Source C/C++ Logging API library, offering an optimal combination of 100% type-safety, efficiency, genericity and extensibility. It is simple to use and extend, highly-portable (platform and compiler-independent) and, best of all, it upholds the C tradition of you only pay for what you use.
916,455
917,079
C++ (Really) Safe Standard String Search?
Buffer overrun problems are well known. Thus we were blessed with standard library functions such as wcscat_s(). And the kind folks at Microsoft have created similar safe string functions such as as StringCbCat(). But I have a problem where I need to search a bit of memory for a string. The Standard library function: wcsstr( wchar_t* pMem, wchar_t* pStr ) seems great, but... Sometimes my memory contains garbage, sometimes strings. And when it is garbage I sometimes run off an allocated memory page, [=Access Violation]. I can write my own function yes. But my question is if there is any "standard" function to do safe string search such as: "wcsstr_s( wchar_t* pMem, size_t uiSize, wchar_t* pStr )" ? Thanx [EDIT] Thanks and kudos to Charles Bailey for a perfect answer to my question. Thanks to others for their efforts too. And to those of you who doubted the saneness of my scenario: Yes of course it would be good to not ever have garbage in my memory. But I can imagine several scenarios where this situation could occur. In my particular case it is reverse-engineering, and the memory I am serching is in fact not "my memory", it belongs to another process which I cannot control. (One other hypothetical scenario could be a tricky debugging situation where corrupted memory needs to be tracked down.)
Assuming that your pStr is null terminated and that uiSize is the number of wchar_t of readable memory at pMem: wchar_t* pSubStr = std::search( pMem, pMem + uiSize, pStr, pStr + std::wcslen( pStr ) ); // Optionally, change to the 'conventional' strstr return value if( pSubStr == pMem + uiSize) pSubStr = 0;
916,507
917,560
How to convert a user-defined unmanaged type to a managed type?
I have a test that I'm writing in MSTest, which is managed C++, and I'm trying to test an unmanaged class. Specifically, I'm trying to use the PrivateObject class to call a private method. This is the code that I have so far: CUnmanagedType foo; PrivateObject privateFoo = gcnew PrivateObject( foo ); CString strFromFoo = privateFoo.Invoke( "ARandomPrivateMethod" ); When I compile I get an error that foo is not convertable to System::Type^. I've tried doing the following: PrivateObject privateFoo = gcnew PrivateObject( (gcnew System::Type^(foo)) ); but that won't work because System::Type^ is an abstract type. Any ideas? I've looked at these questions, but they used pre-defined types, not user-defined ones: How to convert a unmanaged double to a managed string? Conversion between managed and unmanaged types in C++?
The PrivateObject constructor wants a typename, not an instance. To do this, you would need to do the following: PrivateObject privateFoo = gcnew PrivateObject( "CUnmanagedType" )
916,546
916,628
Waiting on multiple events C++
Is there a recommended way to wait on multiple inputs. For example I would like my program to be able to receive input from 3 sources: Listen on a thread condition e.g. pthread_cond_wait() Take data from Standard input e.g. getline() Listen on a socket e.g. accept() What is the best way to accomplish this? Do I need a thread for each different input source? Thanks
You can listen on multiple file descriptors without using multiple threads using the select(2) system call. You can use pthread_cond_timedwait to wait on a condition variable with a timeout, such that you don't wait more than a particular amount of time. I think it's highly unusual to want to simultaneously wait on either a condition variable or a file descriptor of some sort -- if you're absolutely sure that that's what you want to do, you'll have to use multiple threads, with one thread calling either pthread_cond_wait/pthread_cond_timedwait, and the other thread calling select or some other I/O function.
916,600
916,691
Can a C++ compiler re-order elements in a struct
Can a C++ compiler (specifically g++) re-order the internal elements of a struct? I'm seeing some strange behaviour where I have a structure that contains something like the following: Struct SomeStruct{ ... ... long someLong; long someLongArray[25]; unsigned long someUnsignedLong; unsigned long someUnsignedLongArray[8]; unsigned long int someUnsignedLongInt; ... ... }; When I write output this to file, the order of someUnsignedLongArray and someLongArray seem to be reversed (i.e. the elements in someLongArray[] appear after someUnsignedLong and the elements of someUnsignedLongArray[] appear after someLong). Is this possible?? Thanks Update: As requested, I am writing out the structure using the following: int fd = open(fspec,O_RDWR|O_CREAT|O_TRUNC,0666); int writeRes = write(fd,(char *)&someStruct,sizeof(SomeStruct)); For completeness, here is the full struct: struct SomeStruct{ byte someByte; byte someByteArray[6]; char someChar; char someCharArray[5]; char someCharArrayArray[3][5]; short someShort; signed short someShortArray[2]; unsigned short someUnsignedShort; unsigned short someUnsignedShortArray[8]; int someInt; int someIntArray[3]; int someIntArrayArrayArrayArray[4][3][2][6]; int *pSomeInt; unsigned int someUnsignedInt; unsigned int someUnsignedIntArray[9]; long someLong; long someLongArray[25]; unsigned long someUnsignedLong; unsigned long someUnsignedLongArray[8]; unsigned long int someUnsignedLongInt; long long someLongLong; long long someLongLongArray[5]; bool someBool; bool someBoolArray[3]; unsigned long long someUnsignedLongLong; unsigned long long someUnsignedLongLongArray[5]; unsigned long long someUnsignedLongLongArrayArray[5][2]; unsigned long long int *pSomeUnsignedLongLongInt; };
It normally can't reorder elements, no. An exception is if there's an access specifier separating them: struct Foo { A a; B b; C c; private: D d; E e; F f; }; a, b and c are guaranteed to be stored in this order, and d, e and f are guaranteed to be stored in order. But there is no guarantees about where a, b and c are stored relative to d, e and f. Another thing to keep in mind is that the compiler can insert as much padding as it likes, even if it doesn't reorder anything. Here's the relevant part of the standard: Section 9.2.12: Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1)"
916,790
916,813
How do I convert a CString to a double in C++?
How do I convert a CString to a double in C++? Unicode support would be nice also. Thanks!
A CString can convert to an LPCTSTR, which is basically a const char* (const wchar_t* in Unicode builds). Knowing this, you can use atof(): CString thestring("13.37"); double d = atof(thestring). ...or for Unicode builds, _wtof(): CString thestring(L"13.37"); double d = _wtof(thestring). ...or to support both Unicode and non-Unicode builds... CString thestring(_T("13.37")); double d = _tstof(thestring). (_tstof() is a macro that expands to either atof() or _wtof() based on whether or not _UNICODE is defined)
916,877
917,938
Map plugin for an MFC application
I want to display a map in a MFC application (Visual Studo 2008 with MFC Feature Pack). Off the top of my head I have the following requirements: I have to be able to add my own markers (plain lat/lon positions), preferrably with different colors/icons so one can distinguish between different types of markers. If the map data is fetched from an online source, it has to be cache-able, i.e. I can pre-load maps for an area at a certain (or several) zoom-level(s) and then switch to "offline mode". Alternatively all map data is installed together with the application. The standard operations like zoom in/out and pan should be possible for the user. The user has to be able to select my markers, preferably by dragging a rectangle around them. Since the whole app is written in C++/MFC I don't want to have to use the .NET runtime for this plugin. It shouldn't cost a fortune. I am currently using an ActiveX plugin called "ESRI MapObjects LT2" which can do all that in some way but it's very tedious to implement, the development seems to have stopped around the time when Visual Studio 6 was available and map material is either very basic or very expensive. I thought about using Google Maps or Google Earth but I think they don't really support being used by non-web based applications. I found ArcView to be some sort of successor of the plugin I use currently but I don't think I belong to the target audience since the functionality it offers is way more than what I need. Also I didn't find any information on pricing.
I have written an open-source Geocaching app ( it's in c++ ) that renders maps, the source is at: http://code.google.com/p/gpsturbo/ It uses my own custom rendering but you could rip out the map parsing if you want. It renders map using google tiles ( and caches the tiles for offline use), as well as Garmin format GPS maps, there is also an Openstreetmap format renderer as well.
916,973
916,986
Recursive file search using C++ MFC?
What is the cleanest way to recursively search for files using C++ and MFC? EDIT: Do any of these solutions offer the ability to use multiple filters through one pass? I guess with CFileFind I could filter on *.* and then write custom code to further filter into different file types. Does anything offer built-in multiple filters (ie. *.exe,*.dll)? EDIT2: Just realized an obvious assumption that I was making that makes my previous EDIT invalid. If I am trying to do a recursive search with CFileFind, I have to use *.* as my wildcard because otherwise subdirectories won't be matched and no recursion will take place. So filtering on different file-extentions will have to be handled separately regardless.
Using CFileFind. Take a look at this example from MSDN: void Recurse(LPCTSTR pstr) { CFileFind finder; // build a string with wildcards CString strWildcard(pstr); strWildcard += _T("\\*.*"); // start working for files BOOL bWorking = finder.FindFile(strWildcard); while (bWorking) { bWorking = finder.FindNextFile(); // skip . and .. files; otherwise, we'd // recur infinitely! if (finder.IsDots()) continue; // if it's a directory, recursively search it if (finder.IsDirectory()) { CString str = finder.GetFilePath(); cout << (LPCTSTR) str << endl; Recurse(str); } } finder.Close(); }
917,120
917,184
combining similar functions into one common function involving passing function pointers as parameters
I am trying to combine the following two functions into one portable function: void NeedleUSsim::FindIdxRho() { searchTmp = &ninfo->rho; double *p = std::find_if(tplRho_deg, tplRho_deg+sampleDim[2], &NeedleUSsim::GreaterThanOrEqualTo); while(p != tplRho_deg+sampleDim[2]) { idxRho = p - tplRho_deg; p = std::find_if(p+1, tplRho_deg+sampleDim[2], &NeedleUSsim::GreaterThanOrEqualTo); } } void NeedleUSsim::FindIdxDepth() { searchTmp = &ninfo->l; double *p = std::find_if(tplL, tplL+sampleDim[1], &NeedleUSsim::LessThanOrEqualTo); while(p != tplL+sampleDim[1]) { idxL = p - tplL; p = std::find_if(p+1, tplL+sampleDim[1], &NeedleUSsim::LessThanOrEqualTo); } } Ideally, I want the parameters of the function to have tpl member to be passed as a pointer, with the size and rho/l passed as value. searchTmp is a file scope double precision pointer. Is there any easy way of passing &NeedleUSsim::GreaterThanOrEqualTo function as a parameter of the function that I'm trying to write easily? Thanks in advance for the advice.
The simplest way to make your code a bit more generic is the following : template<typename ComparisonType> double* NeedleUSsim::FindIdx(double* containerBegin, double* containerEnd, ComparisonType comparison) { double* p = std::find_if(containerBegin, containerEnd, comparison); double* idx = 0; while(p != containerEnd) { idx = p - containerBegin; p = std::find_if(p+1, containerEnd, comparison); } return idx; } void NeedleUSsim::FindIdxRho() { searchTmp = &ninfo->rho; double* idx = FindIdx(tplRho_deg, tplRho_deg+sampleDim[2], &NeedleUSsim::GreaterThanOrEqualTo); if( idx != 0 ) { idxL = idx; } } void NeedleUSsim::FindIdxDepth() { searchTmp = &ninfo->l; double* idx = FindIdx(tplL, tplL+sampleDim[1], &NeedleUSsim::LessThanOrEqualTo); if( idx != 0 ) { idxRho = idx; } }
917,134
922,167
Delete a node from the middle of a C++ queue
I have a linked list with a c-style ctor and dtor. I just got too frustrated when this if statement decided not to test true, putting me in an infinite loop. I dont understand why it will never test true. I am trying to delete a node (the address of a class object) from my LinkedList. Maybe someone could help me out? Node *Current = first_; // I want this to be my only Node Ptr Varaible Declaration. if ( NULL == first_ ) std::cout << "Cannot delete from an empty list: \n"; while ( Current != NULL ) { if ( first_->data_ == node->data_ ) { //check to see if we are deleteing the head. first_ = first_->next_; --listLen_; delete Current; std::cout << "Head Deleted!\n"; } if ( Current->data_ == node->data_ ) // FOR SOME REASON this is never true? { --listLen_; node->data_ = NULL; Current = Current->next_; node->data_ = Current; } else // we must not of found it. // else should match previous i { Current->prev_ = Current;// since we are not deleting the first node we are OK here. Current = first_->next_; if ( Current->next_ == NULL ) // see if we are at the end of the list. { first_ = NULL; last_ = Current->prev_; } } } return;
Keep your loops small, it easier to figure out what went wrong. Assuming your data compare makes sense, look at this the following: curr = first_; while( curr && (curr->data_ != node->data_) ) { curr = curr->next_; } if (!curr) return // didnt find it, nothing to remove if ( curr == first_ ) first_ = curr->next_ else curr->prev_->next_ = curr->next_ curr->next_->prev_ = curr->prev_ // always fix next's prev delete curr
917,391
917,548
QPainter colored text (syntax coloring)
I have a custom Qt widget which I used to display disassembly and I am looking to add syntax coloring to it. Currently, I simply set the QPen to a solid color, construct the text I want to display, and render it to the QPainter at the appropriate coordinates. The question is, what is the best approach to adding syntax coloring? I've thought of a few: I could simply divide the coloring into logical blocks, each preceded by setting the QPen to the desired color. I could have special escape characters which represent a change in the color palette, and render 1 character at a time. I could do a modification of #1 and create a list of std::pair<QColor, QString>, then I could simply iterate the list setting the color and drawing the text as I pop items off the front of the list. Something entirely different? I know that each of the 3 approaches I've listed will technically work, but I'm looking for a very efficient solution. This code will be called a lot. And since this is an interactive debugger, if this code is slow, someone rapidly stepping or tracing will see a visible slowdown. EDIT: I'm aware of QSyntaxHighlighter and QTextDocument. The main issue is that these don't generally suite my purposes very well. I have several columns which all have dividers and can be slid back and forth. To give you an idea, Here's a link to a screenshot of my debugger. As you can see it isn't really like a text document at all. In fact it is closer to a list or table. But there is already a bunch of custom drawing going on making a normal QTextDocument somewhat impractical. EDIT: I was incorrect, It seems that QTextDocument can render directly to a QPainter. Looks like what I need! EDIT: It is unclear how to control where and how QTextDocument or QTextLayout will draw on a QPainter. I've attempted to use them to no avail. So if someone could provide a rudimentary example, that would be very helpful. EDIT: I was eventually able to get what I wanted using something like this: painter.setPen(default_color); QTextDocument doc; doc.setDefaultFont(font()); doc.setDocumentMargin(0); doc.setPlainText(text); highlighter_->setDocument(&doc); painter.save(); painter.translate(x, y); QAbstractTextDocumentLayout::PaintContext context; context.palette.setColor(QPalette::Text, painter.pen().color()); doc.draw(&painter, context); painter.restore();
Qt provides a QSyntaxHighlighter that is probably exactly what you want. QSyntaxHighlighter uses a QTextDocument to mark each block of code with a specific state which can be associated with a specific presentation format. The documentation on QSyntaxHighlighter provides a sample demonstrating how this may be accomplished and does some nice things: Separates the model from presentation Separates the formatting into different reusable classes (if implemented as such) Supports the State design pattern if useful to your language
917,643
917,667
Using floats in Windows DLL function parameters
I am writing an unmanaged DLL in C++. Is using float as a function parameter in a Windows DLL a good idea? I'd like my DLL to be usable from as many languages as possible (VB6, .NET, etc). To this end, I've used STDCALL and avoided C++ types. Will most languages handle float correctly? If not, what should I use?
The float type used in most compilers is even standardized in some IEEE format, so go ahead.
917,963
922,267
IMovieControl::Run fails on Windows XP?
Actually, it only fails the second time it's called. I'm using a windowless control to play video content, where the video being played could change while the control is still on screen. Once the graph is built the first time, we switch media by stopping playback, replacing the SOURCE filter, and running the graph again. This works fine under Vista, but when running on XP, the second call to Run() returns E_UNEXPECTED. The initialization goes something like this: // Get the interface for DirectShow's GraphBuilder mGB.CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER); // Create the Video Mixing Renderer and add it to the graph ATL::CComPtr<IBaseFilter> pVmr; pVmr.CoCreateInstance(CLSID_VideoMixingRenderer9, NULL, CLSCTX_INPROC); mGB->AddFilter(pVmr, L"Video Mixing Renderer 9"); // Set the rendering mode and number of streams ATL::CComPtr<IVMRFilterConfig9> pConfig; pVmr->QueryInterface(IID_IVMRFilterConfig9, (void**)&pConfig); pConfig->SetRenderingMode(VMR9Mode_Windowless); pVmr->QueryInterface(IID_IVMRWindowlessControl9, (void**)&mWC); And here's what we do when we decide to play a movie. RenderFileToVideoRenderer is borrowed from dshowutil.h in the DirectShow samples area. // Release the source filter, if it exists, so we can replace it. IBaseFilter *pSource = NULL; if (SUCCEEDED(mpGB->FindFilterByName(L"SOURCE", &pSource)) && pSource) { mpGB->RemoveFilter(pSource); pSource->Release(); pSource = NULL; } // Render the file. hr = RenderFileToVideoRenderer(mpGB, mPlayPath.c_str(), FALSE); // QueryInterface for DirectShow interfaces hr = mpGB->QueryInterface(&mMC); hr = mpGB->QueryInterface(&mME); hr = mpGB->QueryInterface(&mMS); // Read the default video size hr = mpWC->GetNativeVideoSize(&lWidth, &lHeight, NULL, NULL); if (hr != E_NOINTERFACE) { if (FAILED(hr)) { return hr; } // Play video at native resolution, anchored at top-left corner. RECT r; r.left = 0; r.top = 0; r.right = lWidth; r.bottom = lHeight; hr = mpWC->SetVideoPosition(NULL, &r); } // Run the graph to play the media file if (mMC) { hr = mMC->Run(); if (FAILED(hr)) { // We get here the second time this code is executed. return hr; } mState = Running; } if (mME) { mME->SetNotifyWindow((OAHWND)m_hWnd, WM_GRAPHNOTIFY, 0); } Anybody know what's going on here?
Never got a resolution on this. The production solution was to just call IGraphBuilder::Release and rebuild the entire graph from scratch. There's a CPU spike and a slight redraw delay when switching videos, but it's less pronounced than we'd feared.
918,236
918,288
Interesting Scope Problem, Explanation?
I just discovered a bug where the code looked something like this: char *foo = malloc(SOME_NUM * sizeof(char)); if (!processReturnsTrueOrFalse(foo)) { free(foo); char *foo = malloc(SOME_NUM * sizeof(char)); // More stuff, whatever } This compiles, but it's weird that I am allowed to define two variables within the same function, but the compiler appears to scope them differently. If this were the case, how do I differentiate the inner foo with the outer one? How did the compiler know that in the free before my second declaration, I was trying to free the outer foo, but then when I redeclared the inner foo, it didn't give me an error? Thanks for any info. This is probably a pretty obvious, newbie question.
C++ defines a new scope for variables every time you use { }. Take a look at this example here. const char *foo = "global"; int main(int argc, char* argv[]) { const char *foo = "hello"; { cout << foo << endl; const char *foo = "world"; cout << foo << endl; cout << ::foo << endl; } cout << foo << endl; } When you run this, you get: hello world global hello When you open a new scope and declare a variable with the same name as a variable in an enclosing scope, you hide the variable in the outer scope as long as you remain in the current scope. Once you leave the inner scope, the outer variable becomes visible again. If the outer variable happens to be a globabl variable, you can access with the global namespace ::foo. If the outer variable is a class variable, you can use className::foo. If the outer variable is just a local variable, there is no way to access it until you leave the scope where you declared the variable that hid it. I haven't used C in a while, so C99 will likely be different, but in the older C, there is no way to access a hidden name. const char *foo = "global"; int main(int argc, char* argv[]) { const char *foo = "hello"; { char *foo = "world"; printf("%s\n", foo); } printf("%s\n", foo); return 0; } When you run this, you get: world hello
918,405
918,564
QDBusAbstractAdaptor vs. QDBusAbstractInterface
When exposing some code to D-Bus using Qt D-Bus bindings, when should one use a Qt Adaptor over a Qt Interface? I'm having a difficult time understanding how exactly they differ since it seems like they provide the same functionality.
Per http://doc.trolltech.com/4.3/qdbusabstractinterface.html, "QDBusAbstractInterface class is the base class for all D-Bus interfaces in the QtDBus binding", while, per http://doc.trolltech.com/4.3/qdbusabstractadaptor.html, "QDBusAbstractAdaptor class is the starting point for all objects intending to provide interfaces to the external world using D-Bus". So, the former is used in the interface itself, the latter is used to provide the interface, i.e., for "exposing some code to D-Bus" you'd write a class inheriting the adaptor and "define the D-Bus interface it is implementing using the Q_CLASSINFO macro in the class definition" (also a quote from the second of the above URLs).
918,567
918,574
'size_t' vs 'container::size_type'
Is there is a difference between size_t and container::size_type? What I understand is size_t is more generic and can be used for any size_types. But is container::size_type optimized for specific kinds of containers?
The standard containers define size_type as a typedef to Allocator::size_type (Allocator is a template parameter), which for std::allocator<T>::size_type is typically defined to be size_t (or a compatible type). So for the standard case, they are the same. However, if you use a custom allocator a different underlying type could be used. So container::size_type is preferable for maximum generality.
918,668
920,128
How can I redefine a built in keyboard shortcut's behavior?
I am attempting to re-implement the Copy behavior for a QTextEdit object. The custom context menu I create works as expected when the 'Copy' button is clicked, but Ctrl + C isn't being handled correctly. Since the context menu doesn't have any issues, I'll omit that portion of the code. // Create a text edit box for text editing QTextEdit text_edit_box = new QTextEdit(getBaseWidget()); text_edit_copy_action = new QAction(QString("Copy"), getBaseWidget()); text_edit_copy_action->setShortcut(QKeySequence::Copy); // Add custom copy action to the text edit box to ensure Ctrl+C uses our copy // implementation text_edit_box->addAction(text_edit_copy_action); When I set the shortcut to be an unused key combination (e.g., Ctrl + Q) it works fine. It seems Ctrl + C is being handled differently since it's "built in".
Copy is not virtual so this might be problematic. Copying is handled via the private text control API, and is not easily accessible. The best approach is probably to install an event handler for the text edit and intercept the copy key event before it's delivered to the text control processEvent handler - which should allow your own action to correctly trigger.
918,702
918,712
Linkedlist Node in C+
I am learning a book on data structures, and complied their node in linked list example, and I receive this error: and Everything.cpp|7|error: expected unqualified-id before "int"| and Everything.cpp|7|error: expected `)' before "int"| ||=== Build finished: 2 errors, 0 warnings ===| The code for the node is: typedef struct Node { struct Node(int data) //Compile suggest problem is here { this-> data = data; previous = NULL; next = NULL; } int data; struct Node* previous; struct Node* next; } NODE; I am not familiar with structs and I am using Code::blocks to compile. Does anyone know whats wrong?
The code sample is wrong. There should not be the keyword struct in front of the constructor declaration. It should be: typedef struct Node { Node(int data) // No 'struct' here { this-> data = data; previous = NULL; next = NULL; } int data; struct Node* previous; struct Node* next; } NODE;
918,736
918,827
Random number generator that produces a power-law distribution?
I'm writing some tests for a C++ command line Linux app. I'd like to generate a bunch of integers with a power-law/long-tail distribution. Meaning, I get a some numbers very frequently but most of them relatively infrequently. Ideally there would just be some magic equations I could use with rand() or one of the stdlib random functions. If not, an easy to use chunk of C/C++ would be great. Thanks!
This page at Wolfram MathWorld discusses how to get a power-law distribution from a uniform distribution (which is what most random number generators provide). The short answer (derivation at the above link): x = [(x1^(n+1) - x0^(n+1))*y + x0^(n+1)]^(1/(n+1)) where y is a uniform variate, n is the distribution power, x0 and x1 define the range of the distribution, and x is your power-law distributed variate.
918,841
918,848
Error installing Windows SDK v6.1 with windowssdkver command: Input string was not in a correct format
When installing Windows SDK v6.1, following the chromium instructions (http://dev.chromium.org/developers/how-tos/build-instructions-windows) I run the following command: windowssdkver -version:v6.1 -legacy I get the following error: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Version..ctor(String version) at WindowsSdkVer.Utility.GetInstalledProducts(String rootKey, String productVersionKey, String installationFolderKey) at WindowsSdkVer.VersionSelector.GetInstlledSdkVersions() at WindowsSdkVer.ConsoleSelectionManager.get_InstalledSdkVersions() at WindowsSdkVer.Program.Main(String[] args)
The solution i find is to do this: Reboot first (just to be safe) Go into Regedit -> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v6.0A Rename the key 'ProductVersion' to '-ProductVersion' Run the windowssdkver command, it seems to work then Go back into regedit, and rename the key back to its original name.
919,406
919,509
What is the difference between accessing vector elements using an iterator vs an index?
What advantages are there in accessing vector elements using an iterator vs an index?
Why are iterators better than indexes? In the cases where index is not available (like with std::list, for example). In the case where a generic function accepting an iterator is called. When writing a function template that is supposed to work with more than one container type. They exist to create uniformity among all containers and ability to use all containers' iterators as well as regular pointers in all standard algorithms. Iterators can point to sequences that don't exist except as a concept. For instance, you can make an iterator class that steps through prime numbers without actually having to build a container of primes. However, if ignoring container types that do not support random access (list, set, etc.), iterators still offer Pointer like semantics (think of string::iterator vs. char *). Generalized concept usable beyond iteration over elements inside a container. Better performance than container member functions in a few cases.
919,695
919,797
Moving heavily templatized C++ code to Java
I have an application written in C++ (makes heavy use of templates) that I need to take to the Java ME platform. I have two questions: Are there any good tools to convert C++ code to Java - do some basic stuff so I have a platform to start with. I found this - http://tangiblesoftwaresolutions.com/Product_Details/CPlusPlus_to_Java_Converter_Details.html. It would at least eliminate the need for simple but time-consuming stuff like moving classes to different files, namespaces to packages, etc. Has anyone tried it? Or knows of any better ones? The bigger problem is how to deal with templates - the code makes very heavy use of them. Any suggestions on how to go about this? Are there any tools to expand templates for instance so I have a rudimentary base and then I could work on writing the modules in Java? Any help would be appreciated.
For all of Sun's marketing, Java is not simply a better C++, and in fact does not support many of the idioms and paradigms C++ supports. This makes automated translation difficult. How should you automatically turn a multi-inheritance hierarchy into Java's single inheritance hierarchy? (Note, I am not saying that a multi-inheritance hierarchy is a good thing, only that it is explicitly allowed in C++). More fundamentally, how would you represent a pointer-to-member function in Java? Or handle the differences between Java and C++ overload resolution? Java added generics a few years ago, but purposely made them less powerful than C++ templates. Regardless of whether that was a good idea, it limits what automated translation can do with heavily templatized code. Aside from using some research compiler that can turn C++ into Java bytecode, I'm afraid you may be stuck doing the translation by hand.
919,701
920,118
Why is the copy ctor used in this code?
class A { public: A(const int n_); A(const A& that_); A& operator=(const A& that_); }; A::A(const int n_) { cout << "A::A(int), n_=" << n_ << endl; } A::A(const A& that_) // This is line 21 { cout << "A::A(const A&)" << endl; } A& A::operator=(const A& that_) { cout << "A::operator=(const A&)" << endl; } int foo(const A& a_) { return 20; } int main() { A a(foo(A(10))); // This is line 38 return 0; } Executing this code gives o/p: A::A(int), n_=10 A::A(int), n_=20 Apparently the copy constructor is never called. class A { public: A(const int n_); A& operator=(const A& that_); private: A(const A& that_); }; However, if we make it private, this compile error occurs: Test.cpp: In function ‘int main()’: Test.cpp:21: error: ‘A::A(const A&)’ is private Test.cpp:38: error: within this context Why does the compiler complain when it doesn't actually use the copy constructor? I am using gcc version 4.1.2 20070925 (Red Hat 4.1.2-33)
Core defect 391 explains the issue. Basically, the current C++ standard requires a copy constructor to be available when passing a temporary of class type to a const reference. This requirement will be removed in C++0x. The logic behind requiring a copy constructor comes from this case: C f(); const C& r = f(); // a copy is generated for r to refer to
920,033
920,050
How can I check if a combobox is a dropdown or a drop list?
Is there a way to retrieve the type of a CComboBox? I need to know if it is a "Dropdown" or a "Drop List". I've tried the following: if (m_MyComboBox.GetStyle() & CBS_DROPDOWN) // do some stuff and if (m_MyComboBox.GetStyle() & CBS_DROPDOWNLIST) // do some stuff But both expressions seem to evaluate to TRUE regardless of the CComboBox being a dropdown or a drop list.
From winuser.h: #define CBS_DROPDOWN 0x0002L #define CBS_DROPDOWNLIST 0x0003L You need: switch(m_MyComboBox.GetStyle() & CBS_DROPDOWNLIST) { case CBS_SIMPLE: // do stuff break; case CBS_DROPDOWN: // do stuff break; case CBS_DROPDOWNLIST: // do stuff break; }
920,312
920,369
std::multimap compile errors
I am trying to use multimap for the first time but my app will not compile. TIA Paul.. // file dept.h typedef std::multimap <CString, std::map< CString, CString> > _DeparmentRecord; // also tryied replacing CString with LPCWSTR _DeparmentRecord DeparmentRecord; // file dept.cpp DWORD CIni::AddNameValue(LPCWSTR Section, LPCWSTR Name, LPCWSTR Value) { DeparmentRecord.insert(std::make_pair ( Section, std::make_pair(Name, Value)) ); <-- error here } c:\program files\microsoft visual studio 9.0\vc\include\utility(57) : error C2664: 'std::map<_Kty,_Ty>::map(const std::less<_Ty> &)' : cannot convert parameter 1 from 'const std::pair<_Ty1,_Ty2>' to 'const std::less<_Ty> &' 1> with 1> [ 1> _Kty=CString, 1> _Ty=CString 1> ] 1> and 1> [ 1> _Ty1=LPCWSTR, 1> _Ty2=LPCWSTR 1> ] 1> and 1> [ 1> _Ty=CString 1> ] 1> Reason: cannot convert from 'const std::pair<_Ty1,_Ty2>' to 'const std::less<_Ty>' 1> with 1> [ 1> _Ty1=LPCWSTR, 1> _Ty2=LPCWSTR 1> ] 1> and 1> [ 1> _Ty=CString 1> ] 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 1> c:\dev\projects\migrator\jobbuilder\jobbuilder\ini.cpp(55) : see reference to function template instantiation 'std::pair<_Ty1,_Ty2>::pair>(const std::pair> &)' being compiled 1> with 1> [ 1> _Ty1=const CString, 1> _Ty2=std::map 1> ] ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Change the function as follows. DWORD AddNameValue(LPCWSTR Section, LPCWSTR Name, LPCWSTR Value) { std::map<CString, CString> aTemp; aTemp.insert(std::make_pair (Name, Value)); DeparmentRecord.insert(std::make_pair (Section, aTemp)) ; }
920,500
920,524
What is the purpose of __cxa_pure_virtual?
Whilst compiling with avr-gcc I have encountered linker errors such as the following: undefined reference to `__cxa_pure_virtual' I've found this document which states: The __cxa_pure_virtual function is an error handler that is invoked when a pure virtual function is called. If you are writing a C++ application that has pure virtual functions you must supply your own __cxa_pure_virtual error handler function. For example: extern "C" void __cxa_pure_virtual() { while (1); } Defining this function as suggested fixes the errors but I'd like to know: what the purpose of this function is, why I should need to define it myself and why it is acceptable to code it as an infinite loop?
If anywhere in the runtime of your program an object is created with a virtual function pointer not filled in, and when the corresponding function is called, you will be calling a 'pure virtual function'. The handler you describe should be defined in the default libraries that come with your development environment. If you happen to omit the default libraries, you will find this handler undefined: the linker sees a declaration, but no definition. That's when you need to provide your own version. The infinite loop is acceptable because it's a 'loud' error: users of your software will immediately notice it. Any other 'loud' implementation is acceptable, too.
920,511
920,534
How to visualize bytes with C/C++
I'm working my way through some C++ training. So far so good, but I need some help reinforcing some of the concepts I am learning. My question is how do I go about visualizing the byte patterns for objects I create. For example, how would I print out the byte pattern for structs, longs, ints etc? I understand it in my head and can understand the diagrams in my study materials, I'd just like to be able to programaticially display byte patterns from within some of my study programs. I realize this is pretty trivial but any answers would greatly help me hammer in these concepts. Thanks. Edit: I use mostly XCode for my other development projects, but have VMs for Windows7 and fedora core. At work I use XP with visual studio 2005. ( I can't comment as I am still a n00b here :D) I used unwind's solution which is about what I am looking for. I am also thinking that maybe I could just use the dos DEBUG command as I'd also like to look at chunks for memory too. Again, this is just to help me reinforce what I am learning. Thanks again people!
You can use a function such as this, to print the bytes: static void print_bytes(const void *object, size_t size) { #ifdef __cplusplus const unsigned char * const bytes = static_cast<const unsigned char *>(object); #else // __cplusplus const unsigned char * const bytes = object; #endif // __cplusplus size_t i; printf("[ "); for(i = 0; i < size; i++) { printf("%02x ", bytes[i]); } printf("]\n"); } Usage would look like this, for instance: int x = 37; float y = 3.14; print_bytes(&x, sizeof x); print_bytes(&y, sizeof y); This shows the bytes just as raw numerical values, in hexadecimal which is commonly used for "memory dumps" like these. On a random (might even be virtual, for all I know) Linux machine running a "Intel(R) Xeon(R)" CPU, this prints: [ 25 00 00 00 ] [ c3 f5 48 40 ] This handily also demonstrates that the Intel family of CPU:s really are little endian.
920,615
920,637
Why do some const variables referring to some exported const variables get the value 0?
Consider the following. I have two exported constants as follows: // somefile.h extern const double cMyConstDouble; extern const double cMyConstDouble2; and // somefile.cpp const double cMyConstDouble = 3.14; const double cMyConstDouble2 = 2.5*cMyConstDouble; These constants are now referenced some place else to define two static (locally visible) constants: // someotherfile.cpp #include "somefile.h" static const double cAnotherDouble = 1.1*cMyConstDouble; static const double cAnotherDouble2 = 1.1*cMyConstDouble2; printf("cAnotherDouble = %g, cAnotherDouble2 = %g\n", cAnotherDouble, cAnotherDouble2); Which yields the following output: cAnotherDouble = 3.454, cAnotherDouble2 = 0 Why is the second double 0? I'm using .NET 2003 C++ compiler (13.10.3077).
Because cMyConstDouble is declared as extern, compiler is not able to assume its value and does not generate a compile time initialization for cMyConstDouble2. As the cMyConstDouble2 is not compile time initialized, its order of initialization relative to cAnotherDouble2 is random (undefined). See static initialization fiasco for more information.
920,731
920,915
C++, removing #include<vector> or #include<string> in class header
I want to remove, if possible, the includes of both <vector> and <string> from my class header file. Both string and vector are return types of functions declared in the header file. I was hoping I could do something like: namespace std { template <class T> class vector; } And, declare the vector in the header and include it in the source file. Is there a reference covering situations where you must include in the header, and situations where you can pull the includes into the source file?
You cannot safely forward declare STL templates, at least if you want to do it portably and safely. The standard is clear about the minimum requirements for each of the STL element, but leaves room for implemtation extensions that might add extra template parameters as long as those have default values. That is: the standard states that std::vector is a template that takes at least 2 parameters (type and allocator) but can have any number of extra arguments in a standard compliant implementation. What is the point of not including string and vector headers? Surely whoever is going to use your class must have already included it since it is on your interface. When you ask about a reference to decide when to include and when to forward declare, my advice would be: include everything that is part of your interface, forward declare internal details. There are more issues here that plain compilation performance. If you push the include of a type that is in your public (or protected) interface outside of the header you will be creating dependencies on the order of includes. Users must know that they must include string before including your header, so you are giving them one more thing to worry about. What things should be included in the implementation file: implementation details, loggers, elements that don't affect the interface (the database connectors, file headers), internal implementation details (i.e. using STL algorithms for your implementation does not affect your interface, functors that are created for a simple purpose, utilities...)
920,740
920,962
App Verifier reporting "Thread cannot own a critical section."
So App Verifier is throwing this exception. From what I gather, the text of this message is a little misleading. The problem appears to be that the the critical section was created by a thread that is being destroyed before the critical section is destroyed. It's a relatively simple fix but does anyone know what the ramifications are for having a thread other than the creating one destroy the crticial section? How dangerous is it? Is the concern only that the critical section handle will "leak" or is there a more insidious side-effect? Some other info: App written in C++ (on Windows, of course) Critical section created with InitializeCriticalSelection Critical section is eventually deleted with DeleteCriticalSection
I believe you are correct on the interpretation of the message. The only reference I can find is as follows. The stack trace is a good clue as the author suggests http://jpassing.wordpress.com/2008/02/18/application-verifier-thread-cannot-own-a-critical-section/ I dug around for a bit and cannot find any specific reason why you cannot create and delete a critical section on different threads. However I do wonder why it is that you want to do so? It seems like best practice to have one thread own a critical section so to speak. Handing off the critical section between threads introduces another means of communication and potential error (can be done, just more fun).
920,829
921,074
Asynchronous screen update to gameplay logic, C++
I am programming a game using Visual C++ 2008 Express and the Ogre3D sdk. My core gameplay logic is designed to run at 100 times/second. For simplicity, I'll say it's a method called 'gamelogic()'. It is not time-based, which means if I want to "advance" game time by 1 second, I have to call 'gamelogic()' 100 times. 'gamelogic()' is lightweight in comparison to the game's screen rendering. Ogre has a "listener" logic that informs your code when it's about to draw a frame and when it has finished drawing a frame. If I just call 'gamelogic()' just before the frame rendering, then the gameplay will be greatly affected by screen rendering speed, which could vary from 5fps to 120 fps. The easy solution that comes to mind is : calculate the time elapsed since last rendered frame and call 'gamelogic()' this many times before the next frame: 100 * timeElapsedInSeconds However, I pressume that the "right" way to do it is with multithreading; have a separate thread that runs 'gamelogic()' 100 times/sec. The question is, how do I achieve this and what can be done when there is a conflict between the 2 separate threads : gamelogic changing screen content (3d object coordinates) while Ogre is rendering the screen at the same time . Many thanks in advance.
If this is your first game application, using multi-threading to achieve your results might be more work than you should really tackle on your first game. Sychronizing a game loop and render loop in different threads is not an easy problem to solve. As you correctly point out, rendering time can greatly affect the "speed" of your game. I would suggest that you do not make your game logic dependent on a set time slice (i.e. 1/100 of a second). Make it dependent on the current frametime (well, the last frametime since you don't know how long your current frame will take to render). Typically I would write something like below (what I wrote is greatly simplified): float Frametime = 1.0f / 30.0f; while(1) { game_loop(Frametime); // maniuplate objects, etc. render_loop(); // render the frame calculate_new_frametime(); } Where Frametime is the calculcated frametime that the current frame took. When you process your game loop you are using the frametime from the previous frame (so set the initial value to something reasonable, like 1/30th or 1/15th of a second). Running it on the previous frametime is close enough to get you the results that you need. Run your game loop using that time frame, then render your stuff. You might have to change the logic in your game loop to not assume a fixed time interval, but generally those kinds of fixes are pretty easy. Asynchoronous game/render loops may be something that you ultimately need, but that is a tough problem to solve. It involves taking snapshops of objects and their relevant data, putting those snapshots into a buffer and then passing the buffer to the rendering engine. That memory buffer will have to be correctly partitioned around critical sections to avoid having the game loop write to it while the render loop is reading from it. You'll have to take care to make sure that you copy all relevant data into the buffer before passing to the render loop. Additionally, you'll have to write logic to stall either the game or render loops while waiting for one or the other to complete. This complexity is why I suggest writing it in a more serial manner first (unless you have experience, which you might). The reason being is that doing it the "easy" way first will force you to learn about how your code works, how the rendering engine works, what kind of data the rendering engine needs, etc. Multithreading knowledge is defintely required in complex game development these days, but knowing how to do it well requires indepth knowledge of how game systems interact with each other.
921,693
921,772
How to speed up c++ linking time
Is there any way, to optimalize linking time in MS Visual studio C++ (2005) ? We're using Xoreax Incredibuild for compilation speed up, but nothing for link. Currently every linking takes about 30seconds. When I turn on incremental linking, takes abou 35-40 seconds. ( No matter if i compile project with or without incredibuild ) Is there any way, how to profile linker and watch how long what takes ? Or any tool for paralel linking ? Or any tips for code optimalization to speed up linker ? Thanks for reply Ludek Vodicka Edit: Thanks for first replies, and additional info: Whole Program Optimization and link-time code generation is already off. PIMPL idiom is already used when possible other static libraries are already included via #pragma comment(lib, "pathToLib"). (also because of easier maintenance] HW : quad core q6600, 8GB ram, 3x WD raptor raid 0. Windows Vista 64bit
I'm not aware of any parallel linking tools; I do know that Incredibuild does not allow it. The biggest tool in your toolbox for avoiding link times is the appropriate level of abstraction. If your link times are long, it may be because objects know too much about other objects. Decoupling them is then the key -- through abstract interfaces (perhaps using the PIMPL paradigm), or though other methods such as event passing. The overhead for linking projects through Project Dependencies is also quite high. If your target platform is Win32 only, or primarily, you may consider using a header to link your dependent libraries via #pragma comment(lib, "pathToLib").
921,806
922,419
What's the point of this pattern: using a struct to contain a single method
In our code we have quite a few cases of this pattern: class outerClass { struct innerStruct { wstring operator()( wstring value ) { //do something return value; } }; void doThing() { wstring initialValue; wstring finalValue = innerStruct()( initialValue ); } }; What's the advantage of this over: class outerClass { wstring changeString( wstring value ) { //do something return value; } void doThing() { wstring initialValue; wstring finalValue = changeString( initialValue ); } };
It's an optimization step for templated predicates. It's not a matter of a functor being easier to use than a function. Both work pretty much the same way in boost and STL contexts. How they differ is in template instantiation. Imagine a trivial template function that requires a predicate template< typename Predicate > void DoSomething( Predicate func ) { func(); } Using a function will instantiate a template instance with a function pointer. void changeString(); DoSomething( &changeString ); // This creates a template instantiation expecting a pointer to a function. // The specific pointer may be evaluated at runtime. // void DoSomething( void(func*)() ); Using a functor will instantiate a template instance with a specific functor type. struct changeString { void operator() (); } DoSomething( changeString() ); // This creates a template instantiation expecting an instance of the struct. // The exact function being called is now known at compile time. // void DoSomething( changeString ); With the functor, the specific functionality is now well defined and the struct being passed in is likely not used and can be optimized out.
921,847
923,125
how to check if a directory is writeable in win32 C/winapi?
I know of two methods which are not reliable: _access() - doesn't work on directories (only checks existence) CreateFile() - gives false positives in the presence of virtual store (AFAIK) Most useful would be a code sample, because the win32 ACL access functions are extremely complicated. Please don't post links to msdn, I've been there and can't for the life of me figure out what I'm supposed to do with all those DACLs, SACLs and security descriptors - I work on a cross-platform app which needs this particular piece of functionality, but otherwise is platform-agnostic. Solutions simpler than accessing Windows ACLs more than welcome. Edit: you can safely assume that directory permissions won't change while the app is running.
you can disable location virtualization for your application in a manifest file (http://www.codeguru.com/csharp/csharp/cs_misc/designtechniques/article.php/c15455/) - this should make CreateFile reliable enough for your purposes.
922,068
922,113
Image Arithmetic functions in C++
I'm trying to find/write a function that would perform the same operation as imlincomb(). However, I am having trouble finding such functions in C++ without using any Matlab API functions other than Intel Performance Primitiives library, and I don't really want to purchase a license for it unless my application really has to take advantage of it. What would be any easy method of implementing it, or perhaps if there are any standard functions that make the job a lot easier? Thanks in advance.
There's definitely nothing of the sort in any standard C++ package. You might be able to use something in LAPACK, but I think you'd be better off writing your own. It's a fairly simple function: each output pixel is independent and depends only on the input pixels at the same coordinates. In pseudocode: for each row y in [0, height-1] for each column x in [0, width-1] for each color channel c in (R, G, B) output[y][x][c] = 0 for each input i output[y][x][c] += weight[i] * input[i][y][x][c] Of course, the exact formulation depends on how exactly your images are stored (3D array, 2D array, or 1D array, and be careful about the order of your dimensions!).
922,204
1,035,095
GetOpenFileName() does not refresh when changing filter
I use GetOpenFilename() to let the user select a file. Here is the code: wchar_t buffer[MAX_PATH] = { 0 }; OPENFILENAMEW open_filename = { sizeof (OPENFILENAMEW) }; open_filename.hwndOwner = handle_; open_filename.lpstrFilter = L"Video Files\0*.avi;*.mpg;*.wmv;*.asf\0" L"All Files\0*.*\0"; open_filename.lpstrFile = buffer; open_filename.nMaxFile = MAX_PATH; open_filename.lpstrTitle = L"Open media file..."; open_filename.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; ::GetOpenFileNameW(&open_filename); The file dialog shows up, but when I change the Filter or click on "My Computer" the file list turns empty. Pressing [F5] does not help, but if I switch to the parent folder and return to the original folder (in the case of the Filter change) the filtering works fine and files show up in the list. EDIT: My system is Windows XP (SP3) 32-bit - nothing special. It happens on other machines - with the same config - as well.
Okay, I have figured out the problem, or at least, I have a solution that is working for me. Earlier in the code, I had the following call to initialize COM... ::CoInitializeEx(NULL, COINIT_MULTITHREADED); Well, changing this to... ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); ...solves the problem for me! Now the file dialog is filtering again. I searched the web for this and it seems that a very few people faces the same problem, but no one published the aforementioned solution. Can anyone verify my findings?
922,358
922,385
Consistent pseudo-random numbers across platforms
I am looking for a way to generate pseudo random number sequences that will yield identical sequence results for a given seed across any platform. I am assuming that rand() / srand() is not going to be consistent (I could easily be wrong about this assumption).
Something like a Mersenne Twister (from Boost.Random) is deterministic.
922,368
922,388
Removing map element by value
I'll keep this brief. I am trying to keep a map between strings and object pointers, and as such, I use std::map. I have a manager that's a global class that keeps track of the map, and whenever an object's destructor is called, it tells the manager that it has been deleted. The only way I can think of is to search through the map for the object. Is there an efficient STL solution to this problem? Does a map that is efficient at searching by key as well exist?
No there is not an efficient way of doing this with std::map other than iterating through comparing the values. However most of the time the key for a value is computable from the value itself. For example using the Name property of a Person object as the key. Is it possible for the manager to store a list of key / value pairs as opposed to the value itself. This would solve your problem without having to rewrite a new algorithm. Or alternatively you could keep a reverse map on the manager class. Essentially value to key. That way you could use it to compute the key to remove later on.
922,442
927,603
Unique class type Id that is safe and holds across library boundaries
I would appreciate any help as C++ is not my primary language. I have a template class that is derived in multiple libraries. I am trying to figure out a way to uniquely assign an id int to each derived class. I need to be able to do it from a static method though, ie. template < class DERIVED > class Foo { public: static int s_id() { // return id unique for DERIVED } // ... }; Thank you!
Here's what I ended up doing. If you have any feedback (pros, cons) please let me know. template < class DERIVED > class Foo { public: static const char* name(); // Derived classes will implement, simply // returning their class name static int s_id() { static const int id = Id_factory::get_instance()->get_id(name()); return id; } // ... }; Essentially the id will be assigned after doing a string comparison rather than a pointer comparison. This is not ideal in terms of speed, but I made the id static const so it will only have to calculate once for each DERIVED.
922,829
923,212
C++ :: Boost :: posix_time (elapsed seconds. elapsed fractional seconds)
I'm trying to come up with an answer to two questions that didn't seem hard at first. Q1 : How do I obtain the number of elapsed seconds between UTC.Now() and a given date? A1 : Just like in the code below! Q2 : How do I determine how many fractional seconds have elapsed since the last "full" second ? I'd like to print the "total_elapsed_seconds.fractional_seconds" -> "1234124.45". How do I do that? A2 : ??? #include <iostream> #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace std; using namespace boost::gregorian; using namespace boost::posix_time; void main() { ptime Jan1st1970(date(1970, 1, 1)); for(int i = 0; i < 10; i++) { ptime Now = second_clock::universal_time(); time_duration diff = Now - Jan1st1970; cout << Now << " : " << diff.total_seconds() << "." << diff.fractional_seconds() << endl; } }
You are using the second_clock to get the current time. As the name implies, it is accurate only to the nearest second. Since your reference time has no fractional seconds the duration fractional seconds always ends up being 0. Use the microsec_clock instead: ptime Now = microsec_clock::universal_time(); Also, in such a tight loop, I wouldn't expect the clock to update on every iteration, so you may also want to add a sleep from boost::thread: boost::this_thread::sleep(boost::posix_time::milliseconds(25));
923,288
923,309
Guides to help learn C++ specifically from a C# background
Is there a guide/reference anyone would recommend to pick up C++ specifically if you have strong experience of C#? There are C++ guides, but a lot start with the absolute basics and I feel I've covered a lot with my C# learnings. But the absolute basics may be a good thing and I may be barking up the wrong tree - I imagine some people might say "you should just consider it completely different and learn it separately otherwise you'll miss bits" I actually used to be "fairly OK" at C++, but it's all gone...
Useful info on a C# to C++ (Win32) project port. Might be a good starting point. http://blogs.cozi.com/tech/2008/03/index.html
923,458
923,496
Running a separate process or thread in Qt
I'm writing my first proper useful piece of software. Part of it will involve the user viewing an image, and choosing to accept or reject it. Doing this will cause the image to be saved to an accepted or rejected folder, and possibly rotated and/or resized. At the moment, my rotate/resize/save operation is pausing execution of my program, but I'd like it to happen in the background so the next image is displayed instantly. Is the only way to do this in Qt to process the image in a separate thread, or is there another way? I'm still getting my head round C++ and Qt, so I don't want to confuse myself by diving into a new field!
Qt has thread support. You might find this example application interesting since it's somewhat similar to what you describe. Also, here is the full Qt thread documentation.
923,649
923,667
Copying an integer to a Buffer memcpy C++
Basically I would like to store the address of a pointer in a buffer. Don't ask me why char * buff = "myBuff"; char * myData = (char*)malloc(sizeof(char*)); int addressOfArgTwo = (unsigned int)buff; memcpy(myData, &addressOfArgTwo, sizeof(char*)); cout << "Int Val: " << addressOfArgTwo << endl; cout << "Address in buffer:" << (unsigned int)*myData << endl; I can't see why the above code doesn't work. It outputs: Int Val: 4472832 Address in buffer:0 When the Int Val & Address in Buffer should be the same. thanks
You dereference a char *, resulting in a char, and then cast that 1-byte char to an int, not the entire 4 bytes of address (if this is a 32-bit machine, 8 bytes on 64-bit). 4472832 is 444000 in hexadecimal. On a little-endian machine, you grab that last 00. *((unsigned int*)myData) should result in the correct number being displayed.
923,688
923,692
Some questions about special operators i've never seen in C++ code
I have downloaded the Phoenix SDK June 2008 (Tools for compilers) and when I'm reading the code of the Hello sample, I really feel lost. public ref class Hello { //-------------------------------------------------------------------------- // // Description: // // Class Variables. // // Remarks: // // A normal compiler would have more flexible means for holding // on to all this information, but in our case it's simplest (if // somewhat inelegant) if we just keep references to all the // structures we'll need to access as classstatic variables. // //-------------------------------------------------------------------------- static Phx::ModuleUnit ^ module; static Phx::Targets::Runtimes::Runtime ^ runtime; static Phx::Targets::Architectures::Architecture ^ architecture; static Phx::Lifetime ^ lifetime; static Phx::Types::Table ^ typeTable; static Phx::Symbols::Table ^ symbolTable; static Phx::Phases::PhaseConfiguration ^ phaseConfiguration; 2 Questions : What's that ref keyword? What is that sign ^ ? What is it doing protected: virtual void Execute ( Phx::Unit ^ unit ) override; }; override is a C++ keyword too? It's colored as such in my Visual Studio. I really want to play with this framework, but this advanced C++ is really an obstacle right now. Thank you.
It's not standard C++, it's C++/CLI.
923,922
923,964
Event / Task Queue Multithreading C++
I would like to create a class whose methods can be called from multiple threads. but instead of executing the method in the thread from which it was called, it should perform them all in it's own thread. No result needs to be returned and It shouldn't block the calling thread. A first attempt Implementation I have included below. The public methods insert a function pointer and data into a job Queue, which the worker thread then picks up. However it's not particularily nice code and adding new methods is cumbersome. Ideally I would like to use this as a base class which I can easy add methods (with a variable number of arguments) with minimum hastle and code duplication. What is a better way to do this? Is there any existing code available which does something similar? Thanks #include <queue> using namespace std; class GThreadObject { class event { public: void (GThreadObject::*funcPtr)(void *); void * data; }; public: void functionOne(char * argOne, int argTwo); private: void workerThread(); queue<GThreadObject::event*> jobQueue; void functionOneProxy(void * buffer); void functionOneInternal(char * argOne, int argTwo); }; #include <iostream> #include "GThreadObject.h" using namespace std; /* On a continuous loop, reading tasks from queue * When a new event is received it executes the attached function pointer * It should block on a condition, but Thread code removed to decrease clutter */ void GThreadObject::workerThread() { //New Event added, process it GThreadObject::event * receivedEvent = jobQueue.front(); //Execute the function pointer with the attached data (*this.*receivedEvent->funcPtr)(receivedEvent->data); } /* * This is the public interface, Can be called from child threads * Instead of executing the event directly it adds it to a job queue * Then the workerThread picks it up and executes all tasks on the same thread */ void GThreadObject::functionOne(char * argOne, int argTwo) { //Malloc an object the size of the function arguments int argumentSize = sizeof(char*)+sizeof(int); void * myData = malloc(argumentSize); //Copy the data passed to this function into the buffer memcpy(myData, &argOne, argumentSize); //Create the event and push it on to the queue GThreadObject::event * myEvent = new event; myEvent->data = myData; myEvent->funcPtr = &GThreadObject::functionOneProxy; jobQueue.push(myEvent); //This would be send a thread condition signal, replaced with a simple call here this->workerThread(); } /* * This handles the actual event */ void GThreadObject::functionOneInternal(char * argOne, int argTwo) { cout << "We've made it to functionTwo char*:" << argOne << " int:" << argTwo << endl; //Now do the work } /* * This is the function I would like to remove if possible * Split the void * buffer into arguments for the internal Function */ void GThreadObject::functionOneProxy(void * buffer) { char * cBuff = (char*)buffer; functionOneInternal((char*)*((unsigned int*)cBuff), (int)*(cBuff+sizeof(char*))); }; int main() { GThreadObject myObj; myObj.functionOne("My Message", 23); return 0; }
There's Futures library making its way into Boost and the C++ standard library. There's also something of the same sort in ACE, but I would hate to recommend it to anyone (as @lothar already pointed out, it's Active Object.)
924,257
924,259
C++ Programming Book Example on Stack
In this book, I am learning how the book writes a stack, but when I compile it, it reaches a compile error: #define DEFAULT_SIZE = 10 class Stack { private: int size; int top; int *value; public: Stack( int size = DEFAULT_SIZE ); virtual ~Stack(); bool isFull(); bool isEmpty(); void push(int); int pop(); }; and the errors indicates: C:\Documents and Settings\Eddy\Desktop\C++ Playground\Data Structures\stack.h|14|error: expected primary-expression before '=' token| ||=== Build finished: 1 errors, 0 warnings ===| I am using Code::Blocks as my IDE, and I believe that you cant initlize inside a class, and to create a "DEFAULT_SIZE" would be commonly in a default constructor. Do I have the right idea? or did I do something wrong?
Do this: #define DEFAULT_SIZE 10 The = sign is not needed in the preprocessor definition.
924,354
925,008
URL escaping MFC strings
How do you URL escape an MFC CString?
InternetCanonicalizeUrl()
924,360
924,431
Difference between C++ reference type argument passing and C#'s ref?
I always thought they were about the same thing but someone pointed me out in one of my answers that such ain't quite true. Edit: Here is what I said and the comment I got. Edit2: What's the difference between C++'s: public: void foo(int& bar); and C#'s public void foo(ref int bar){ }
In C#, you have primitive types (ints, structs, etc.) and reference types (objects). These are built in to the language. In C++, you have to be explicit. Here is a set of equivalent ways of referring to objects in C# and C++, based on whether they are reference types or primitives, and whether or not you're using ref: C# type | C++ Type ----------------------------+--------- Primitive type, with no ref | Normal parameter passing Reference type, with no ref | Pointer (*) Primitive type, with ref | Reference (&) Reference type, with ref | Reference of a pointer (&*)
924,485
924,495
What's the difference between a header file and a library?
One of the things I'm having a hard time understanding is how the compiler works. I'm having a lot of difficulties with it, but in particular I keep getting headers and libraries mixed up. If somebody could clear things up a bit, that'd be great.
Think of both like this (Disclaimer: this is a really high-level analogy ;) .. The header is a phone number you can call, while... ...the library is the actual person you can reach there! It's the fundamental difference between "interface" and "implementation"; the interface (header) tells you how to call some functionality (without knowing how it works), while the implementation (library) is the actual functionality. Note: The concept is so fundamental, because it allows you flexibility: you can have the same header for different libraries (i.e. the functionality is exactly called in the same way), and each library may implement the functionality in a different way. By keeping the same interface, you can replace the libraries without changing your code. And: you can change the implementation of the library without breaking the calling code!
924,642
924,672
boost spirit headers deprecated
I am following the quickstart guide for boost::spirit, and I get this compiler warning when I include : "This header is deprecated. Please use: boost/spirit/include/classic_core.hpp" Should I be worried about this? (quick start guide: http://spirit.sourceforge.net/distrib/spirit_1_8_5/libs/spirit/doc/quick_start.html , with full source of the program I am trying to compile here: http://spirit.sourceforge.net/distrib/spirit_1_8_5/libs/spirit/example/fundamental/number_list.cpp) edit: Additionally, when I try to compile with the recommended classic_core.hpp and classic_push_back_actor.hpp headers, I get the following compiler errors: test7.cpp: In function 'bool parse_numbers(const char*, __gnu_debug_def::vector<double, std::allocator<double> >&)': test7.cpp:18: error: 'real_p' was not declared in this scope test7.cpp:18: error: 'push_back_a' was not declared in this scope test7.cpp:23: error: 'space_p' was not declared in this scope test7.cpp:23: error: 'parse' was not declared in this scope
[EDIT:] The original answer is badly out of date; in particular the link is broken. The current version of Boost (since 2012-02-24) is 1.49.0. The warning mentioned is a result of #include <boost/spirit.hpp> which is a deprecated header; however old examples on the web use this form. To get started, try the boost tutorials. Once you see the correct includes and namespaces, most old examples can easily be converted. [OLD ANSWER:] You must be using boost 1.39 or later (via SVN). This presentation should help: http://www.boostcon.com/site-media/var/sphene/sphwiki/attachment/2009/05/07/SpiritV2.pdf In short, there's a brand new way of doing thing and these are the namespaces to use: boost::spirit:qi (for the parser) boost::spirit::karma (for the generator lib) The official release is 1.40 so probably by that time the doc will be updated. EDIT: the doc in the boost SVN repository is being worked on and probably reflect the new architecture in a more faithful manner.
924,830
924,854
what is difference btw /MD and /MDD in VisualStudio C++?
What is difference betwwen /MD and /MDD( multi threaded debug dll ) in c/c++->code generation propertis of visual studio ....
They specify which runtime to use. Both use mmulti-threaded dynamic (DLL) runtimes, but the /MDD version uses the debug version and also defines the _DEBUG symbol for you. See this MSDN page for details.
925,084
925,153
POD low dimensional vector in boost
I'm looking for POD low dimension vectors (2,3 and 4D let say) with all the necessary arithmetic niceties (operator +, - and so on). POD low dimension matrices would be great as well. boost::ublas vectors are not POD, there's a pointer indirection somewhere (vector are resizeable). Can I find that anywhere in boost? Using boost::array along with boost.operator lib is an options but maybe I'm missing something easier elsewhere? Apart boost, does anybody know any good library around? PS: POD <=> plain old data EDIT: Otherwise, here are some other links I gathered from another thread: http://www.cgal.org/ http://geometrylibrary.geodan.nl http://www.cmldev.net http://www.openexr.com/index.html http://project-mathlibs.web.cern.ch/project-mathlibs/sw/html/SMatrix.html
There is a nice Vector library for 3d graphics in the prophecy SDK: Check out http://www.twilight3d.com/downloads.html
925,487
925,863
Is there a way to detect an alphanumeric Unicode symbol?
I have a Unicode string consisting of letters, digits and punctuation marks. Ho can I detect characters that are digits and letters (not necessarily ASCII) with a C++ standard library or Win32 API?
iswdigit(), iswalpha() and iswalnum() are the functions you are looking for. Cheers !
925,513
925,569
C++ empty String constructor
I am a C++ beginner, so sorry if the question is too basic. I have tried to collect the string constrcturs and try all them out (to remember them). string strA(); // string(); empty string // incorrect string strB("Hello"); // string( const char* str) string strC("Hello",3); // string( const char* str, size_type length) string strD(2,'c'); // string( size_type lenght, const char &c) string strE(strB); // string( const string& s) cout << strA << endl; cout << strB << endl; cout << strC << endl; cout << strD << endl; cout << strE << endl; All of them works except for the strA. It prints "1". Why? Whats the type of the strA in this case? How can I check the type of stuff when I am unsure? I have noticed that the correct way is this (which by the way seems to be inconsistent with the other constructors, sometimes parens sometimes no parens): string strA; ps: question in bold, usual irrelevant answers will be downvoted.
This is a very popular gotcha. C++ grammar is ambiguous. One of the rules to resolve ambiguities is "if something looks like declaration it is a declaration". In this case instead of defining a variable you declared a function prototype. string strA(); is equivalent to string strA(void); a prototype of a no-arg function which returns string. If you wish to explicitly call no-arg constructor try this: string strA=string(); It isn't fully equivalent - it means 'create a temporary string using no-arg constructor and then copy it to initialize variable strA', but the compiler is allowed to optimize it and omit copying. EDIT: Here is an appropriate item in C++ FAQ Lite
926,010
926,031
Helper library for distributed algorithms programming?
When you code a distributed algorithm, do you use any library to model abstract things like processor, register, message, link, etc.? Is there any library that does that? I'm thinking about e.g. self-stabilizing algorithms, like self-stabilizing minimum spanning-tree algorithms.
There's a DVM system that can be used for implementing different distributed algorithms. It works on top of MPI. However it is more for matrix-oriented scientific algorithms where distribution is done in terms of data blocks. I had a brief experience using it - it's much more convenient than direct usage of MPI and allows for much more readable and maintainable code.
926,097
926,186
Replace strings in native .exe using c#
how can I catch all strings from a native windows .exe file and replace them later with others using c# ? Background: I want to create a c# tool to extract and replace strings from a simple .exe file. Is this possible somehow?
What you need to start is a PE/COFF parser. If your strings are stored in a resource section in the PE, then it's pretty easy. For instance, you can load an exe into Visual Studio as a resource file and use its resource editor to change icons and strings and such in the exe. If on the other hand the strings are stored in a data section or are immediate in the machine code you have a much more complex problem. Overwriting the strings as is, leaving them the same length will probably work, but making them longer starts moving things around, messing up relocations and offsets. Rewriting the exe is really not the way to achieve what you want. Moved up from my comment: PE/COFF is the exe format of windows programs. If you just want to edit the resources, you shouldn't need a parser. You might start by using LoadLibraryEx() with flags LOAD_LIBRARY_AS_IMAGE_RESOURCE|LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE to load the exe to just use the resource and so that it's writable. Then start looking at LoadString(). These are all native API calls. I don't really know how you do it in C#.
926,172
926,192
How to hide strings in a exe or a dll?
I discovered that it is possible to extract the hard-coded strings from a binary. For example the properties view of Process Explorer displays all the string with more than 3 characters. Here is the code of a simple executable that I wrote to simply test it: #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #include <stdio.h> #include <tchar.h> #include <Windows.h> int _tmain(int argc, _TCHAR* argv[]) { _TCHAR* hiddenString1 =_T("4537774B-CC80-4eda-B3E4-7A9EE77991F5"); _TCHAR* hiddenString2 =_T("hidden_password_or_whatever"); for (int i= 0; i<argc; i++) { if (0 == _tcscmp(argv[i],hiddenString1)) { _tprintf (_T("The guid argument is correct.\n")); } else if (0 == _tcscmp(argv[i],hiddenString2)) { _tprintf (_T("Do something here.\n")); } } _tprintf (_T("This is a visible string.\n")); //Keep Running Sleep(60000); return 0; } The strings can clearly be extracted from the corresponding executable: I think that it is a little too easy to find the strings. My questions are: How to simply hide hiddenString1 or hiddenString2 in the executable? Is there a more secure way to use "cheat code" than with some obscure hidden input?
Welcome to the wider world of defensive programming. There are a couple of options, but I believe all of them depend on some form of obfuscation; which, although not perfect, is at least something. Instead of a straight string value you can store the text in some other binary form (hex?). You can encrypt the strings that are stored in your app, then decrypt them at run time. You can split them across various points in your code, and reconstitute later. Or some combination thereof. Bear in mind, that some attacks go further than looking at the actual binary. Sometimes they will investigate the memory address space of the program while it's running. MS came up with something called a SecureString in .Net 2.0. The purpose being to keep the strings encrypted while the app is running. A fourth idea is to not store the string in the app itself, but rather rely on a validation code to be submitted to a server you control. On the server you can verify if it's a legit "cheat code" or not.
926,187
926,339
Difference between two DLL declarations
I have a simple but subtle question. Below you see two different declaration variants of the same class from a DLL header file. Can anybody tell me the difference of this class declaration; class __declspec(dllexport) Car { public: Car(); void drive(void); typedef enum { None, Indented } Formatting; } from this one? class Car { public: __declspec(dllexport) Car(); __declspec(dllexport) void drive(void); __declspec(dllexport) typedef enum { None, Indented } Formatting; } In the first declaration, the class itself is gets __declspec(dllexport), whereas in the latter case each class element is declared individually so. Are they different or do they have anything in common?
A brief test using depends showed that the first example exports one additional symbol compared to the second (btw you don't export an enum, it's not legal). If I'm not wrong I believe it was the default assignment operator. The first approach exports the entire class, the second one just the methods that are prefixed with the declspec (no surprise here I guess). So I'd say that the proper way of exporting a class is obviously the first one, personally I haven't seen any exported class using the second approach.
926,551
926,578
Where to install SDK DLLs on a system so that they can be found by apps that need them
I've got an SDK I'm working on and the previous developer just dropped the DLLs in System32 (Apparently a serious offense: see here) So assuming I move them out into \Program Files\\SDK (or whatever), how do I make sure that all the apps that needs those DLLs can access them? And to clarify, all apps that access these are doing early (static) binding to the DLLs at compile time so I can't pass the full path to them or anything. They need to be able to find it just given the DLL filename only. Along the same lines, what about including a particular version of MSVCR80.dll? They all depend on this but I need to make sure they get a specific version (the one I include). Any ideas?
An SDK is by definition a development kit. It's not a deployment patch... What this means is that the applications that depend on those assemblies should ship with them and install them into their local \program files.. directories. The reason for this is let's say you decide to do a breaking change by eliminating an entry point for example. By installing your "SDK", it has the potential to stop older programs from functioning. You could take a play from the Java handbook and update the PATH environment variable. Whenever a program makes a call to an external assembly it searches along that environment variable until it finds it. Of course, this could still result in the problem showing up. So your best bet is to just install the SDK into Program Files and let the developers of the products that depend on your toolkit decide whether they want to update their versions or not. UPDATE As I'm thinking about this, one last possibility is to GAC your assemblies. In the event you do so, bear in mind that they should be strongly named and properly versioned so as not to step on each other. I don't recommend this route because it hides the actual locations of the assemblies and makes uninstalling a little more difficult then simply hitting delete on your directory.
926,728
928,659
Will my iPhone app take a performance hit if I use Objective-C for low level code?
When programming a CPU intensive or GPU intensive application on the iPhone or other portable hardware, you have to make wise algorithmic decisions to make your code fast. But even great algorithm choices can be slow if the language you're using performs more poorly than another. Is there any hard data comparing Objective-C to C++, specifically on the iPhone but maybe just on the Mac desktop, for performance of various similar language aspects? I am very familiar with this article comparing C and Objective-C, but this is a larger question of comparing two object oriented languages to each other. For example, is a C++ vtable lookup really faster than an Obj-C message? How much faster? Threading, polymorphism, sorting, etc. Before I go on a quest to build a project with duplicate object models and various test code, I want to know if anybody has already done this and what the results where. This type of testing and comparison is a project in and of itself and can take a considerable amount of time. Maybe this isn't one project, but two and only the outputs can be compared. I'm looking for hard data, not evangelism. Like many of you I love and hate both languages for various reasons. Furthermore, if there is someone out there actively pursuing this same thing I'd be interesting in pitching in some code to see the end results, and I'm sure others would help out too. My guess is that they both have strengths and weaknesses, my goal is to find out precisely what they are so that they can be avoided/exploited in real-world scenarios.
Mike Ash has some hard numbers for performance of various Objective-C method calls versus C and C++ in his post "Performance Comparisons of Common Operations". Also, this post by Savoy Software is an interesting read when it comes to tuning the performance of an iPhone application by using Objective-C++. I tend to prefer the clean, descriptive syntax of Objective-C over Objective-C++, and have not found the language itself to be the source of my performance bottlenecks. I even tend to do things that I know sacrifice a little bit of performance if they make my code much more maintainable.
926,752
926,795
Why should I prefer to use member initialization lists?
I'm partial to using member initialization lists with my constructors... but I've long since forgotten the reasons behind this... Do you use member initialization lists in your constructors? If so, why? If not, why not?
For POD class members, it makes no difference, it's just a matter of style. For class members which are classes, then it avoids an unnecessary call to a default constructor. Consider: class A { public: A() { x = 0; } A(int x_) { x = x_; } int x; }; class B { public: B() { a.x = 3; } private: A a; }; In this case, the constructor for B will call the default constructor for A, and then initialize a.x to 3. A better way would be for B's constructor to directly call A's constructor in the initializer list: B() : a(3) { } This would only call A's A(int) constructor and not its default constructor. In this example, the difference is negligible, but imagine if you will that A's default constructor did more, such as allocating memory or opening files. You wouldn't want to do that unnecessarily. Furthermore, if a class doesn't have a default constructor, or you have a const member variable, you must use an initializer list: class A { public: A(int x_) { x = x_; } int x; }; class B { public: B() : a(3), y(2) // 'a' and 'y' MUST be initialized in an initializer list; { // it is an error not to do so } private: A a; const int y; };
926,915
927,041
How do text differencing applications work?
How do applications like DiffMerge detect differences in text files, and how do they determine when a line is new, and not just on a different line than the file being checked against? Is this something that is fairly easy to implement? Are there already libraries to do this?
Here's the paper that served as the basis for the UNIX command-line tool diff.
927,043
927,104
Is there a way to determine if a top level Qt window has been moved?
I am trying to determine when the main window of my application has been moved. The main window is a standard QMainWindow and we've installed an eventFilter on the QApplication to look for moveEvents for the QMainWindow, but none are being triggered. For a variety of reasons, subclassing the QMainWindow isn't really an option. Any thoughts on this, aside from starting a QTimer tto constantly check the position, would greatly be appreciated.
I guess it's better to install the event filter at the top-level window, instead of the application. However, if you still do not get QMoveEvents and you're working on Windows, you probably can override winEventFilter() and wait for WM_MOVE. Similar functionality might be available for Linux and Mac. I usually do not recommend to break the platform-independence, but sometimes it might make sense.
927,063
927,287
Building C++ source code as a library - where to start?
Over the months I've written some nice generic enough functionality that I want to build as a library and link dynamically against rather than importing 50-odd header/source files. The project is maintained in Xcode and Dev-C++ (I do understand that I might have to go command line to do what I want) and have to link against OpenGL and SDL (dynamically in SDL's case). Target platforms are Windows and OS X. What am I looking at at all? What will be the entry point of my library if it needs one? What do I have to change in my code? (calling conventions?) How do I release it? My understanding is that headers and the compiled library (.dll, .dylib(, .framework), whatever it'll be) need to be available for the project - especially as template functionality can not be included in the library by nature. What else I need to be aware of?
I'd recommend building as a statc library rather than a DLL. A lot of the issues of exporting C++ functions and classes go away if you do this, provided you only intend to link with code produced by the same compiler you built the library with. Building a static library is very easy as it is just an collection of .o/.obj files - a bit like a ZIP file but without compression. There is no need to export anything - just include the library in the list of files that your application links with. To access specific functions or classes, just include the relevant header file. Note you can't get rid of header files - the C++ compilation model, particularly for templates, depends on them.
927,574
927,591
Compiling C++ Program Causes "Fatal Error LNK1104"
I am trying to compile a c++ application using the following command in command prompt: cl -I"c:\Program files\Java\jdk1.5.0_07\include" -I"c:\program files\java\jdk1.5.0_07\include\win32" -MD -LD HelloWorld.cpp -FeHelloWorld.dll However, this produces the following error: LINK : fatal error LNK1104: cannot open file 'MSVCRT.lib' Have you any ideas of what is causing this and how to fix it? I have visual studio 2005 installed on windows. Thanks, -Pete
LINK : fatal error LNK1104: cannot open file 'MSVCRT.lib' Any ideas of what is causing this and how to fix it? The linker needs to be pointed to the location of MSVCRT.lib, as it doesn't seem to be in your LIBPATH. It should be here: C:\Program Files\Microsoft Visual Studio 7\VC\lib Add -link -LIBPATH:"C:\Program Files\Microsoft Visual Studio 8\VC\lib"
927,631
9,523,724
Is there a heap class in C++ that supports changing the priority of elements other than the head?
I have a priority queue of events, but sometimes the event priorities change, so I'd like to maintain iterators from the event requesters into the heap. If the priority changes, I'd like the heap to be adjusted in log(n) time. I will always have exactly one iterator pointing to each element in the heap.
I'm happy to report that Boost has now added a Boost.Heap library with some stellar data structures. The advantage of this is that Fibonacci heaps support changing priority in constant amortized time. Unfortunately, all of the mutable heaps are node-based (in other words, they have extra indirection as suggested by @wilx). @Feruccio's answer of Boost's “mutable heaps” has code that allows one to write vector-based mutable heaps if you're willing to have pointers to handles contained in your value type.
927,901
927,934
Weird way to write "hello world"
Possible Duplicates: Changing c++ output without changing the main() function How to assign a method's output to a textbox value without code behind How to write hello world without modifying main function? Thanks int main(){return 0;}
#include<iostream> int hello() { cout<<"Hello World"<<endl; } static int foo = hello(); int main(){return 0;}
927,945
927,950
Deleting a heap then dereferencing a pointer to that memory
This is code from an exercise: #include <iostream> using namespace std; int main() { int n = 13; int* ip = new int(n + 3); int* ip2 = ip; cout << *ip << endl; delete ip; cout << *ip2 << endl; cout << ip << tab << ip2 << endl; } When the space allocated to the int on the heap is deleted, I thought that dereferencing the pointer would give some sort of memory error. Instead, it returns 0. Why is this?
Dereferencing an invalid pointer leads to undefined results per spec. It's not guaranteed to fail. Usually (CPU/OS/compiler/... dependent), the compiler doesn't really care about it at all. It just gives what's currently at that memory address. For example, in x86 architecture, you just see an error only when the address is in a memory page that's not mapped to your process (or your process doesn't have permission to access that), thus an exception will be thrown by the CPU (protection fault) which the OS would handle appropriately (and probably, making your process fail). A trick is sometimes used to make accessing the address 0 always cause an access violation: The OS sets the read/write bits of the first page of the address space in the page table to 0 so that any access to that page will always generate an exception.
928,568
928,732
Creating multiple instances of global statics in C++?
One of the libraries we are using for our product uses a singleton for access to it. I'm pretty sure it's implemented as a static instance (it isn't open source). This works well for a single document application, but our app may have more than one document loaded. I'm assuming access to the instance is written something like this: Instance* getInstance() { static Instance* inst = new Instance(); return inst; } In situations like this, is there some way to robustly create more than one instance? The only thing I can think of is to have more than process and use some type of IPC to tie it all together. I can't think of anything less hacky. I have asked the vendor to implement some type of session token so I can have multiple concurrent instances, but they are big and we are small. Cory Edit: the machine is a Windows machine the global static is basically a big factory. I want a session token of some type so I can easily say "release all the resources from this session" (there's no way to re-initialize the global statics that I know of) Rather than try some dodgy shenanigans to get what I want, I'm going to wrap the whole thing with my own class and add a session key to every getter. Internally I'll keep track of what has been allocated add my own release method to return resources. This is suboptimal for lots of reasons, but I can't think of a better idea. Thanks to everybody for the great feedback.
The only thing that I can think of is to sub-class it if you are lucky enough to have the singleton class defined like: class Document { public: static Document* getInstance() { static Document inst; return &inst; } virtual ~Document(); protected: Document(); private: struct Impl; Impl *pImpl; }; If you can subclass it and the subclass will have access to the constructor, then you can create an instanceable subclass like: class MyDocument: public Document { public: MyDocument(): Document() { } }; This might not be completely safe since the implementer may have made some nasty assumptions. But it is an idea or some approach that might have some chance of working. With any luck the vendor might be amenable to this option if you mention it... good luck.
928,613
928,620
Is this the correct way to overload the left-stream operator? (C++)
This function declaration gives me errors: ostream& operator<<(ostream& os, hand& obj); The errors are: error C2143: syntax error : missing ';' before '&' error C4430: missing type specifier error C2065: 'os' : undeclared identifier error C2065: 'obj' : undeclared identifier error C2275: 'hand' : illegal use of this type as an expression see declaration of 'hand' error C4430: missing type specifier hand is a class I made, display is a public data member of type char*. Can anybody tell me what I'm doing wrong?
The declaration looks right. But the error message suggests that ostream is not known as a type. Try including the iostream header and say std::ostream instead. Another thing you should consider is making the parameter 'hand' a const reference. So you could also accept temporaries and print them out.
928,662
928,679
What does "cannot convert 'this' pointer from 'const hand' to 'hand &' mean? (C++)
The error occurs when I try to do this friend std::ostream& operator<<(std::ostream& os, const hand& obj) { return obj.show(os, obj); } where hand is a class I've created, and show is std::ostream& hand::show(std::ostream& os, const hand& obj) { return os<<obj.display[0]<<obj.display[1]<<obj.display[2]<<obj.display[3]<<obj.display[4]; } where display is declared as char display[6]. Does anyone know what the error means?
You need to make hand::show(...) a const method; and it doesn't make sense to pass it obj reference -- it already receives that as the 'this' pointer. This should work: class hand { public: std::ostream& show(std::ostream &os) const; ... }; friend std::ostream& operator<<(std::ostream& os, const hand& obj) { return obj.show(os); }
928,694
928,701
What does "warning: not all control paths return a value" mean? (C++)
The exact warning I get is warning C4715: 'hand::show' : not all control paths return a value and hand::show is std::ostream& hand::show(std::ostream& os) const { if(side == left) { return os<<display[0]<<display[1]<<display[2]<<display[3]<<display[4]; } if(side == right) { return os<<display[4]<<display[3]<<display[2]<<display[1]<<display[0]; } } where side is a variable of type orientation orientation{ left = -1, right = 1 }; What does the warning mean, and what would be the best solution to get rid of it?
Your compiler isn't smart enough to take into account that the only two options for side are left and right, so it thinks it's possible for neither return statement to be executed. When side is neither left nor right, your function doesn't say which value to return.
928,751
928,761
declare a array of const ints in C++
I have a class and I want to have some bit masks with values 0,1,3,7,15,... So essentially i want to declare an array of constant int's such as: class A{ const int masks[] = {0,1,3,5,7,....} } but the compiler will always complain. I tried: static const int masks[] = {0,1...} static const int masks[9]; // then initializing inside the constructor Any idea on how this can be done? Thanks!
class A { static const int masks[]; }; const int A::masks[] = { 1, 2, 3, 4, ... }; You may want to fixate the array within the class definition already, but you don't have to. The array will have a complete type at the point of definition (which is to keep within the .cpp file, not in the header) where it can deduce the size from the initializer.
928,758
928,765
How can I fix an int-to-bool warning in C++?
I get a warning in MSVC++ when I try to read an integer from a file and make a bool variable equal it. accessLV[i] = FileRead(file1, i + 1); (accessLV is an array of bools, FileRead is a function I made to decrease the syntax involved in reading from a file, i is because the statement is within a for loop) I've tried using a static_cast: accessLV[i] = static_cast<bool>(FileRead(file1, i + 1)); But I still get the warning. I've tried doing this (I'm not sure the exact term): accessLV[i] = (bool)FileRead(file1, i + 1)); And the warning is still there. Is there anyway to get rid of the warning without making accessLV an array of ints? NB: this is the syntax of FileRead, if it helps: int FileRead(std::fstream& file, int pos) { int data; file.seekg(file.beg + pos * sizeof(int)); file.read(reinterpret_cast<char*>(&data), sizeof(data)); return data; }
How about accessLV[i] = FileRead(file1, i + 1) != 0;
928,777
929,369
C++ code to get line of file and read the second word of the line?
#include <iostream> #include <string> #include <fstream> using namespace std ; string strWord( int index , string line) { int count = 0; string word; for ( int i = 0 ; i < line.length(); i++) { if ( line[i] == ' ' ) { if ( line [i+1] != ' ') { count ++; if ( count == index) { return word; } word =""; } } else { word += line[i]; } } } int main ( ) { ifstream inFile ; inFile.open("new.txt"); string line , id; cout <<"Enter id : "; cin >>id; while(!inFile.eof() ) { getline ( inFile , line ); if ( strWord ( 1, line ) == id ) { cout <<strWord ( 2 , line ) <<endl; break; } } system("pause"); } Question is : Can someone explain this to me I do not get what it is doing i mean i get the concept but what is each line doing?
You wanted a comment of each line // function that returns a word from 'line' with position 'index' // note that this is not a zero based index, first word is 1, // second is 2 etc .. string strWord(int index, string line) { int count = 0; // number of read words string word; // the resulting word for (int i = 0 ; i < line.length(); i++) { // iterate over all characters in 'line' if (line[i] == ' ') { // if this character is a space we might be done reading a word from 'line' if (line[i+1] != ' ') { // next character is not a space, so we are done reading a word count++; // increase number of read words if (count == index) { // was this the word we were looking for? return word; // yes it was, so return it } word =""; // nope it wasn't .. so reset word and start over with the next one in 'line' } } else { // not a space .. so append the character to 'word' word += line[i]; } } } int main( ) // main function of the program, execution starts here { ifstream inFile; // construct input file stream object inFile.open("new.txt"); // associate the stream with file named "new.txt" string line, id; // cout << "Enter id : "; // write "Enter id :" to console cin >> id; // read input from console and put the result in 'id' while (!inFile.eof()) { // do the following as long as there is something to read from the file getline(inFile, line); // read a line from the file and put the value into 'line' if (strWord(1, line) == id) { // if the first word in 'line' equals 'id' .. cout << strWord(2, line) << endl; // prints the second word in 'line' break; // exits the while loop } } system("pause"); // pause the program (should be avoided) }
928,992
929,015
Nested functions are not allowed but why nested function prototypes are allowed? [C++]
I was reading the linked question which leads me to ask this question. Consider the following code int main() { string SomeString(); } All says, compiler takes this as a function prototype and not as a string object. Now consider the following code. int main() { string Some() { return ""; } } Compiler said this is invalid as I guess nested function definition is not allowed. If it is not allowed, why nested function prototypes are allowed? It is not giving any advantage rather than making confusion (or am I missing some valid points here?). I figured out the following is valid. int main() { string SomeFun(); SomeFun(); return 0; } string SomeFun() { std::cout << "WOW this is unexpected" << std::endl; } This is also confusing. I was expecting the function SomeFun() will have a scope only in main. But I was wrong. Why compiler is allowing to compile code like the above? Is there any real time situations where code like the above makes sense? Any thoughts?
Your prototype is just 'Forward Declaration'. Please check out the Wikipedia article. Basically, it tells the compiler "don't be alarmed if the label 'SomeFun' is used in this way". But your linker is what's responsible for finding the correct function body. You can actually declare a bogus prototype, e.g. 'char SomeFun()' and use it all over your main. You will only get an error when your linker tries to find the body of your bogus function. But your compiler will be cool with it. There are lots of benefits. You have to remember the function body is not always in the same source code file. It can be in a linked library.Also, that linked library may be have a specific 'link signature'.Use conditional defines you may even select the correct link signature at build time using your scoped prototypes.Although most people would use function pointers for that instead. Hope this helps.
929,016
936,439
msvc9, iostream and 2g/4g plus files
Doing cross platform development with 64bit. Using gcc/linux and msvc9/server 2008. Just recently deployed a customer on windows and during some testing of upgrades I found out that although std::streamoff is 8 bytes, the program crashes when seeking past 4G. I immediately switched to stlport which fixes the problem, however stlport seems to have other issues. Is STL with msvc9 really that broken, or am I missing something? Since the code is cross platform I have zero interest in using any win32 calls. Related iostream and large file support Reading files larger than 4GB using c++ stl.
I ended up using STLport. The biggest difference with STLport being that some unit tests which crashed during multiplies of double precision numbers now work and those unit tests pass. There are some other differences with relative precision popping up but those seem to be minor.
929,976
929,986
C++: Assigning values to non-continuous indexes in vectors?
If I want to declare a vector of unknown size, then assign values to index 5, index 10, index 1, index 100, in that order. Is it easily doable in a vector? It seems there's no easy way. Cause if I initialize a vector without a size, then I can't access index 5 without first allocating memory for it by doing resize() or five push_back()'s. But resize clears previously stored values in a vector. I can construct the vector by giving it a size to begin with, but I don't know how big the vector should. So how can I not have to declare a fixed size, and still access non-continuous indices in a vector? (I doubt an array would be easier for this task).
Resize doesn't clear the vector. You can easily do something like: if (v.size() <= n) v.resize(n+1); v[n] = 42; This will preserve all values in the vector and add just enough default initialized values so that index n becomes accessible. That said, if you don't need all indexes or contigous memory, you might consider a different data structure.
930,138
930,141
Is clrscr(); a function in C++?
I've looked everywhere for this function and cannot find the header files to make this work. It says clrscr() undeclared which brings me to the question. Is clrscr(); a function in C++?
It used to be a function in <conio.h>, in old Borland C compilers. It's not a C++ standard function.
930,323
930,344
«F(5)» and «int x; F(x)» to call different functions?
I'd like to write two distinct functions to handle a constant value and a variable of a given type (viz., int). Here is the example test case: int main(void) { int x=12; F(5); // this should print "constant" F(x); // this should print "variable" } I thought it would be enough to define: void F(int v) { cout << "constant\n"; } void F(int& v) { cout << "variable\n"; } This assumes that the compiler will choose int& for variables as "better specialized" and int for constants as the only choice). However, G++ this is the result: test.cc: In function ‘int main()’: test.cc:13: error: call of overloaded ‘F(int&)’ is ambiguous // for line: F(x); test.cc:4: note: candidates are: void F(int) test.cc:5: note: void F(int&) G++ does choose F(int) for constants but does not know which function to choose for variables. Does anyone have any idea why this happens? Background: I am experimenting with prolog-like unification methods in C++. Being able to know the difference between constants and variables would help me choosing desired unification behavior (assignment or comparison) in cases such as functor(x,5) <=> functor(3,5).
If what you want is to differentiate between a compile time constant and a non-compile time constant - then you have no chance. That's not possible. But if you want to differentiate between a non-constant variable and between a constant variable (and everything else included - like literals), then you can overload a function with a const-reference and non-const reference parameter. For this scenario, the C++ Standard introduces extra rules that make this otherwise ambiguous case not ambiguous. void f(int const&); // #1 void f(int&); // #2 In this matter, the following decisions are done int x = 0; int const y = x; int const z = 1; f(1); // #1 f(x); // #2 f(y); // #1 f(z); // #1 Note how it can't differentiate between y and z, even though value of z is a compile time constant (termed integral constant expression, or ICE), while y is not. What you can do is to only accept compile time values then. Overload the function so that one is a template and the other isn't template<int N> void f(); // #1 void f(int n); // #2 It behaves like this then: int x = 0; int const y = x; int const z = 1; f<1>(); // #1 f(1); // #2 f<y>(); // error, y not an ICE f<z>(); // #1 f(x); // #2
930,334
931,004
Processing Escapes using the Spirit Parser Framework
I'm trying to parse a string similar to the following using a spirit parser: <junk> -somearg#this is a string with a literal ## in it# <junk> What I'm looking for is a grammar which can extract the portion inside the # marks, but is smart to skip over the double ## in the middle, which is an escape meaning a literal #. This was what I had in mind: confix_p(L'#', *anychar_p, L'#' >> ~ch_p(L'#')) However this returns: #this is a string with a literal ## I'd like it to skip over the ## characters .... is this possible? Billy3
I solved this by adding a kleene star to the confix parser. Thanks anyway! *confix_p(L'#', *anychar_p, L'#' >> ~ch_p(L'#')) works as expected.
930,622
930,866
Does there exist a "wiki" for editing doxygen comments?
I'm working on a fairly big open source RTS game engine (Spring). I recently added a bunch of new C++ functions callable by Lua, and am wondering how to best document them, and at the same time also stimulate people to write/update documentation for a lot of existing Lua call-outs. So I figured it may be nice if I could write the documentation initially as doxygen comments near the C++ functions - this is easy because the function body obviously defines exactly what the function does. However, I would like the documentation to be improved by game developers using the engine, who generally have little understanding of git (the VCS we use) or C++. Hence, it would be ideal if there was a way to automatically generate apidocs from the C++ file, but also to have a wiki-like web interface to allow a much wider audience to update the comments, add examples, etc. So I'm wondering, does there exist a web tool which integrates doxygen style formatting, wiki-like editing for those comments (preferably without allowing editing any other parts of the source file) and git? (to commit the comments changed through the web interface to a special branch) We developers could then merge this branch every now and then to add the improvements to the master branch, and at the same time any improvements by developers to the documentation would end up on this web tool with just a merge of the master branch into this special branch. I haven't found anything yet, doubt something this specific exists yet, so any suggestions are welcome!
This is a very cool idea indeed, and a couple of years ago I also had a very strong need for something like that. Unfortunately, at least back then, I wasn't able to find something like that. Doing a quick search on sourceforge and freshmeat also doesn't bring up anything related today. But I agree that such a wiki frontend to user-contributed documentation would be very useful, I know for a fact that something like this was recently being discussed also within the Lua community (see this). So, maybe we can determine the requirements in order to come up with a basic working draft/prototype? Hopefully, this would get us going to initiate such a project with a minimum set of features and then simply release it into the wild as an open source project (e.g. on sourceforge), so that other users can contribute to it. Ideally, one could use unified patches to apply changes that were contributed in such a fashion. Also, it would probably make sense to restrict modifications only to adding/editing comments, instead of allowing arbitrary modifications of text, this could probably be implemented by using a simple regex. Maybe, one could implement something like that by modifying an existing (established) wiki software such as mediawiki. Or preferably something that's already using git as a backend for storage purposes. Then, one would mainly need to cater for those Doxygen-style comments, and provide a simple interface on top of it. Thinking about it some more, DoxyGen itself already provides support for generating HTML documentation, so from that perspective it might actually be interesting to see, how DoxyGen could possibly be extended, so that it is well integrated with such a scripted backend that allows for easy customization of embedded source code documentation. This would probably mainly boil down to providing a standalone script with doxygen (e.g. in python, php or perl) and then optionally embed forms in the automatically created HTML documentation, so that documentation fixes/augmentations can be sent to the corresponding script via a browser, which in turn would write any modifications back to a corresponding branch. In the long term, it would be cool if such a script would support different types of backends (CVS, SVN or git), or at least be implemented generically enough, so that it is easily extendible. So, if we can come up with a good design, it might even be possible that such a modification would be generally accepted as a contribution to doxygen itself, which would also give the whole thing much more exposure and momentum. Even if the idea doesn't directly materialize into a real project, it would be interesting to see how many other users actually like the idea, so that it could possibly be mentioned in the doxygen issue tracker (https://github.com/doxygen/doxygen/issues/new). EDIT: You may also want to check out this article titled "Documentation, Git and MediaWiki".
930,897
930,970
C++ atomic operations for lock-free structures
I'm implementing a lock-free mechanism using atomic (double) compare and swap instructions e.g. cmpxchg16b I'm currently writing this in assembly and then linking it in. However, I wondered if there was a way of getting the compiler to do this for me automatically? e.g. surround code block with 'atomically' and have it go figure it out how to implement the code as an atomic instruction in the underlying processor architecture (or generate an error at compile time if the underlying arch does not support it)? P.S. I know that gcc has some built-ins (at least for CAS) http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Atomic-Builtins.html#Atomic-Builtins
Already kindof answered here. The C++0x standard will provide some atomic datatypes, mainly integer and void types using std::atomic<> template. That article mentions Boehm's atomic_ops project which you can download and use today. If not, can't you implement your assembler inline in the compiler? I know MSVC has the __asm keyword for inline assembler routines. Google says yes, gcc can do it too.
930,932
930,940
Returning different data type depending on the data (C++)
Is there anyway to do something like this? (correct pointer datatype) returnPointer(void* ptr, int depth) { if(depth == 8) return (uint8*)ptr; else if (depth == 16) return (uint16*)ptr; else return (uint32*)ptr; } Thanks
No. The return type of a C++ function can only vary based on explicit template parameters or the types of its arguments. It cannot vary based on the value of its arguments. However, you can use various techniques to create a type that is the union of several other types. Unfortunately this won't necessarily help you here, as one such technique is void * itself, and getting back to the original type will be a pain. However, by turning the problem inside out you may get what you want. I imagine you'd want to use the code you posted as something like, for example: void bitmap_operation(void *data, int depth, int width, int height) { some_magical_type p_pixels = returnPointer(data, depth); for (int x = 0; x < width; x++) for (int y = 0; y < width; y++) p_pixels[y*width+x] = some_operation(p_pixels[y*width+x]); } Because C++ needs to know the type of p_pixels at compile time, this won't work as-is. But what we can do is make bitmap_operation itself be a template, then wrap it with a switch based on the depth: template<typename PixelType> void bitmap_operation_impl(void *data, int width, int height) { PixelType *p_pixels = (PixelType *)data; for (int x = 0; x < width; x++) for (int y = 0; y < width; y++) p_pixels[y*width+x] = some_operation(p_pixels[y*width+x]); } void bitmap_operation(void *data, int depth, int width, int height) { if (depth == 8) bitmap_operation_impl<uint8_t>(data, width, height); else if (depth == 16) bitmap_operation_impl<uint16_t>(data, width, height); else if (depth == 32) bitmap_operation_impl<uint32_t>(data, width, height); else assert(!"Impossible depth!"); } Now the compiler will automatically generate three implementations for bitmap_operation_impl for you.
931,093
931,165
How do I make my program watch for file modification in C++?
There are a lot of programs, Visual Studio for instance, that can detect when an outside program modifies a file and then reload the file if the user wants chooses. Is there a relatively easy way to do this sort of thing in C++ (doesn't necessarily have to be platform independent)?
There are several ways to do this depending on the platform. I would choose from the following choices: Cross Platform Trolltech's Qt has an object called QFileSystemWatcher which allows you to monitor files and directories. I'm sure there are other cross platform frameworks that give you this sort of capability too, but this one works fairly well in my experience. Windows (Win32) There is a Win32 api called FindFirstChangeNotification which does the job. There is a nice article which a small wrapper class for the api called How to get a notification if change occurs in a specified directory which will get you started. Windows (.NET Framework) If you are ok using C++/CLI with the .NET Framework then System.IO.FileSystemWatcher is your class of choice. Microsoft has a nice article on how to monitor file system changes using this class. OS X The FSEvents API is new for OS X 10.5 and very full-featured. Linux Use inotify as Alex mentioned in his answer.
931,195
931,205
How do you make a prototype of a function with parameters that have default values?
A have a function with a prototype of: void arryprnt(int[], string, int, string, string); And a definition of: void arryprnt(int[] a, string intro, int len, string sep=", ", string end=".") { // stuff } And I'm calling it like this: arryprnt(jimmy, "PSEUDOJIMMY: ", 15); ...When I make that call to arryprnt, I get a compiler error saying that I've used too few arguments, based off what the prototype says. "Okay," I'm thinking, "The compiler doesn't know that some of arryprnt's parameters have default values. I'll just copy the parameters from the definition into the prototype." And I did, however, I got a compiler error telling me that I was calling arryprnt with too many arguments! I could just explicitly specify all the arguments, but is there any way to call it without specifying all the arguments?
You should put the default arguments in the prototype, not the definition like this: void arryprnt(int[] a, string intro, int len, string sep=", ", string end="."); and the make the definition without them: void arryprnt(int[] a, string intro, int len, string sep, string end) { // ... } BTW: on another note. It is considered good practice to pass objects which larger than an int by const reference. While this isn't appropriate for all situations, it is appropriate for most and avoids copying things unnecessarily. For example: void func(const std::string &s) { // do some read-only operation with s. } func("hello world");
931,293
931,364
linking c++ sources in iPhone project
I have a single cpp file added to my iPhone project with a .cpp extension, but I'm seeing errors when linking like: operator new[](unsigned long)", referenced from: ___gxx_personality_sj0", referenced from: I thought as long as I named the cpp files with .cpp or .mm it would do the right thing, do I need to add some linker flags?
Select the file in the project browser, and press cmd-i to bring up the info window for the file in question. Set File Type to sourcecode.cpp.cpp should do it. Alternatively right click on your project, add new file, select C++ source, then copy and paste the content. In light of the build log, try adding the following linker flags: -cclib -lstdc++ This might be because gcc is being used to link, not g++.
931,301
931,318
Which is more readable (C++ = )
int valueToWrite = 0xFFFFFFFF; static char buffer2[256]; int* writePosition = (int* ) &buffer2[5]; *writePosition = valueToWrite; //OR * ((int*) &buffer2[10] ) = valueToWrite; Now, I ask you guys which one do you find more readable. The 2 step technique involving a temporary variable or the one step technique? Do not worry about optimization, they both optimize to the same thing, as you can see here. Just tell me which one is more readable for you. or DWORD PTR ?buffer2@?1??main@@9@4PADA+5, -1 or DWORD PTR ?buffer2@?1??main@@9@4PADA+10, -1
int* writePosition = (int* ) &buffer2[5] Or *((int*) &buffer2[10] ) = valueToWrite; Are both incorrect because on some platforms access to unaligned values (+5 +10) may cost hundreds of CPU cycles and on some (like older ARM) it would cause an illegal operation. The correct way is: memcpy( buffer+5, &valueToWrite, sizeof(valueToWrite)); And it is more readable.
931,476
931,490
finding a function name and counting its LOC
So you know off the bat, this is a project I've been assigned. I'm not looking for an answer in code, but more a direction. What I've been told to do is go through a file and count the actual lines of code while at the same time recording the function names and individual lines of code for the functions. The problem I am having is determining a way when reading from the file to determine if the line is the start of a function. So far, I can only think of maybe having a string array of data types (int, double, char, etc), search for that in the line and then search for the parenthesis, and then search for the absence of the semicolon (so i know it isn't just the declaration of the function). So my question is, is this how I should go about this, or are there other methods in which you would recommend? The code in which I will be counting will be in C++.
Three approaches come to mind. Use regular expressions. This is fairly similar to what you're thinking of. Look for lines that look like function definitions. This is fairly quick to do, but can go wrong in many ways. char *s = "int main() {" is not a function definition, but sure looks like one. char * /* eh? */ s ( int /* comment? // */ a ) // hello, world /* of confusion { is a function definition, but doesn't look like one. Good: quick to write, can work even in the face of syntax errors; bad: can easily misfire on things that look like (or fail to look like) the "normal" case. Variant: First run the code through, e.g., GNU indent. This will take care of some (but not all) of the misfires. Use a proper lexer and parser. This is a much more thorough approach, but you may be able to re-use an open source lexer/parsed (e.g., from gcc). Good: Will be 100% accurate (will never misfire). Bad: One missing semicolon and it spews errors. See if your compiler has some debug output that might help. This is a variant of (2), but using your compiler's lexer/parser instead of your own.
931,502
931,516
gaming with c++ or c#?
What is the best language for programming a game project and why? Why is the game programing world dominated by c++?
This is kind of a difficult question to answer. For the most part, C++ is a "better" language for programming games in that it gives you so much direct control over memory management that you have more options to fine tune your performance. That, along with the fact that C++ has been around ages longer than C#, have lead to its current dominance in the game industry. However, these days, with the .NET platform and C# becoming so much more mature, its not easy to rule it out as a very strong contender in the game programming arena. I think this is especially true for the near future, as .NET 4.0 and C# 4.0 will bring in a whole new era of multi-threaded and concurrent programming that could bring some massive performance gains to their platform. With multicore CPU's taking the desktop computing world by storm, and massively-cored CPU's only a short step behind .NET/C# 4.0, I think the ease of developing multi-threaded applications with .NET and C# 4.0 will give C++ a run for its money. In the end, it will entirely depend upon how much control you think you need over memory management, and whether that control is worth the effort in the arena of massively parallel games. If you need that control, and think you can deal with the effort of writing a highly parallel game in C++, then you'll probably gain something from it. Otherwise, I would say C# 4.0 would be the better option. 2011 Update: It should probably be noted that, now two years on from when I originally wrote this, Silverlight games, particularly Silverlight on Windows Phone 7, have become a large and rapidly growing platform upon which games, often quite advanced games, are being developed. Gaming on WP7 has exploded since the platform first launched in Nov. 2010, and already WP7 has more games developed for it than competing platforms. Given the ubiquity of mobile devices and the popularity of playing games on them, I think that is a strong indication of C#'s power and capability as a game development language. Quite a few WP7 games are fully 3D, graphics intensive games.
931,713
931,781
Reading from a socket 1 byte a time vs reading in large chunk
What's the difference - performance-wise - between reading from a socket 1 byte a time vs reading in large chunk? I have a C++ application that needs to pull pages from a web server and parse the received page line by line. Currently, I'm reading 1 byte at a time until I encounter a CRLF or the max of 1024 bytes is reached. If reading in large chunk(e.g. 1024 bytes at a time) is a lot better performance-wise, any idea on how to achieve the same behavior I currently have (i.e. being able to store and process 1 html line at a time - until the CRLF without consuming the succeeding bytes yet)? EDIT: I can't afford too big buffers. I'm in a very tight code budget as the application is used in an embedded device. I prefer keeping only one fixed-size buffer, preferrably to hold one html line at a time. This makes my parsing and other processing easy as I am by anytime I try to access the buffer for parsing, I can assume that I'm processing one complete html line. Thanks.
If you are reading directly from the socket, and not from an intermediate higher-level representation that can be buffered, then without any possible doubt, it is just better to read completely the 1024 bytes, put them in RAM in a buffer, and then parse the data from the RAM. Why? Reading on a socket is a system call, and it causes a context switch on each read, which is expensive. Read more about it: IBM Tech Lib: Boost socket performances
931,827
931,873
std::string comparison (check whether string begins with another string)
I need to check whether an std:string begins with "xyz". How do I do it without searching through the whole string or creating temporary strings with substr().
I would use compare method: std::string s("xyzblahblah"); std::string t("xyz") if (s.compare(0, t.length(), t) == 0) { // ok }
931,890
931,915
What is more efficient a switch case or an std::map
I'm thinking about the tokenizer here. Each token calls a different function inside the parser. What is more efficient: A map of std::functions/boost::functions A switch case
STL Map that comes with visual studio 2008 will give you O(log(n)) for each function call since it hides a tree structure beneath. With modern compiler (depending on implementation) , A switch statement will give you O(1) , the compiler translates it to some kind of lookup table. So in general , switch is faster. However , consider the following facts: The difference between map and switch is that : Map can be built dynamically while switch can't. Map can contain any arbitrary type as a key while switch is very limited to c++ Primitive types (char , int , enum , etc...). By the way , you can use a hash map to achieve nearly O(1) dispatching (though , depending on the hash table implementation , it can sometimes be O(n) at worst case). Even though , switch will still be faster. Edit I am writing the following only for fun and for the matter of the discussion I can suggest an nice optimization for you but it depends on the nature of your language and whether you can expect how your language will be used. When you write the code: You divide your tokens into two groups , one group will be of very High frequently used and the other of low frequently used. You also sort the high frequently used tokens. For the high frequently tokens you write an if-else series with the highest frequently used coming first. for the low frequently used , you write a switch statement. The idea is to use the CPU branch prediction in order to even avoid another level of indirection (assuming the condition checking in the if statement is nearly costless). in most cases the CPU will pick the correct branch without any level of indirection . They will be few cases however that the branch will go to the wrong place. Depending on the nature of your languege , Statisticly it may give a better performance. Edit : Due to some comments below , Changed The sentence telling that compilers will allways translate a switch to LUT.
932,092
1,304,488
Default HTML style for controls in the Qt library
This is a question about Qt library, not about Web design. For QLabel and other controls I can set HTML text, for example "<h3>Some Text</h3>". The question is: where is the default HTML style is defined? How can I find out what a font would be used for <h3> tag? The next question: can I change the default HTML style? Edit: I want to specify in one place in my code how my controls would be displayed. To specify css style in all the labels doesn't seem to be an elegant solution to me. Edit2: It seems people don't get the question. I'll try again. Suppose I do the following: QLabel* label = ... label->setText("This <b>is</b> a <h3>Header</h3>"); The question: what fonts will be used for label text rendering? How can I control them? Is there a way to specify, say, default font size for <h3> headers? Edit3: Thomi have suggested to use QTextDocument::setDefaultStyleSheet. But this is just a workaround. I have to manually apply css style to all the QTextEdits (and not QLabels) in the interface. And the question was: how to find out the default style sheet? QTextDocument::setDefaultStyleSheet just overrides it for a single QTextDocument object. Maybe QTextDocument::defaultStyleSheet returns it? I don't have a computer with Qt insatlled right now so I can't check it.
What you want cannot be done with a QLabel. The QLabel is designed to hold primative text labels - it's HTML support is rather... ropey. However, You can achieve this using a QTextEdit & QTextDocument. Try something like this (I'm writing this from memory, so it may not compile or be 100% correct): QTextDocument *doc = new QTextDocument(this); doc->setDefaultStyleSheet("h3 { font-color: red; }"); QTextEdit *edit = new QTextEdit(this); edit->setDocument(doc); edit->setHTML("this is a red <h3>heading</h3>"); The important thing is to use a QTextDocument, which allows you to change the HTML stylesheet. From the QT documentation: The default style sheet is applied to all newly HTML formatted text that is inserted into the document, for example using setHtml() or QTextCursor::insertHtml(). The style sheet needs to be compliant to CSS 2.1 syntax. Note: Changing the default style sheet does not have any effect to the existing content of the document. see here for more info Edit: To get the default stylesheet, you can call QTextDocument::DefaultStyleSheet() - however, this only applies to QTextDocuments, and may or may not apply to all Qt controls (including QLabel).
932,114
933,925
Total beginner looking for tutorials programming outlook add ins in c++
I'm an absolute beginner in Outlook programming and Windows GUI programming in general. But I have lots of years experience in C++ programming in general (not GUI) I need to develop a Outlook plug-in and my question is where to start? What do I need to know to let me start? Can you please give me some useful links to learn ?
OutlookCode.com and it's forums are always my first point of call with Outlook related programming. Also see the Office Developer Centre. For your specific scenario the COM Add-ins page links to the following ATL/C++ sample.
932,237
932,362
How to run a dictionary search against a large text file?
We're in the final stages of shipping our console game. On the Wii we're having the most problems with memory of course, so we're busy hunting down sloppy coding, packing bits, and so on. I've done a dump of memory and used strings.exe (from sysinternals) to analyze it, but it's coming up with a lot of gunk like this: ''''$$$$ %%%% ''''$$$$%%%%####&&&& ''''$$$$((((!!!!$$$$''''((((####%%%%$$$$####(((( ''))++.-$$%&'')) '')*>BZf8<S]^kgu[faniwkzgukzkzkz '',,..EDCCEEONNL I'm more interested in strings like this: wood_wide_end.bmp restroom_stonewall.bmp ...which mean we're still embedding some kinds of strings that need to be converted to ID's. So my question is: what are some good ways of finding the stuff that's likely our debug data that we can eliminate? I can do some rx's to hack off symbols or just search for certain kinds of strings. But what I'd really like to do is get a hold of a standard dictionary file and search my strings file against that. Seems slow if I were to build a big rx with aardvaark|alimony|archetype etc. Or will that work well enough if I do a .NET compiled rx assembly for it? Looking for other ideas about how to find stuff we want to eliminate as well. Quick and dirty solutions, don't need elegant. Thanks!
First, I'd get a good word list. This NPL page has a good list of word lists of varying sizes and sources. What I would do is build a hash table of all the words in the word list, and then test each word that is output by strings against the word list. This is pretty easy to do in Python: import sys dictfile = open('your-word-list') wordlist = frozenset(word.strip() for word in dictfile) dictfile.close() for line in sys.stdin: # if any word in the line is in our list, print out the whole line for word in line.split(): if word in wordlist: print line break Then use it like this: strings myexecutable.elf | python myscript.py However, I think you're focusing your attention in the wrong place. Eliminating debug strings has very diminishing returns. Although eliminating debugging data is a Technical Certification Requirement that Nintendo requires you to do, I don't think they'll bounce you for having a couple of extra strings in your ELF. Use a profiler and try to identify where you're using the most memory. Chances are, there will be a way to save huge amounts of memory with little effort if you focus your energy in the right place.
932,384
932,404
gdb says "cannot open shared object file"
I have one binary and one shared library. The shared library is compiled with: all: g++ -g -shared -fpic $(SOURCES) -o libmisc.so the binary is compiled with: LIBS=-L../../misc/src LDFLAGS=-lmisc all: g++ -g -o mainx $(INCLUDE) $(SOURCE) $(LIBS) $(LDFLAGS) I set in ~/.bashrc export LD_LIBRARY_PATH=/mnt/sda5/Programming/misc/src/ to the libmisc.so output path. Debugging from console works fine: gdb mainx However from Emacs22, launching gdb fails with the following message: Starting program: /mnt/sda5/Programming/main/src/mainx /mnt/sda5/Programming/main/src/mainx: error while loading shared libraries: libmisc.so: cannot open shared object file: No such file or directory This looks very tricky for the moment, and I couldn't solve it. I am not sure if this a emacs's problem, or I should pass a parameter in gdb's command line.
Emacs probably does not read your .bashrc before it invokes gdb. Try to put 'set solib-search-path' and 'set solib-absolute-path in your .gdbinit file instead