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
2,006,744
2,006,770
What does "exposition only" mean? Why use it?
All over boost.org and also at other sites on the web I've seen code of this form: class whatever { ... private: std::vector<std::string> m_name; // exposition only }; What is the meaning of "exposition only"? What is the comment's purpose? What is it trying to tell me?
It's used to indicate one possible way to implement the particular item, but not necessarily the best or recommended way.
2,006,886
2,007,049
Can I link unresolved reference to abort?
I'm trying to write some small tests for a fairly small part of a fairly large project. Attempting to link this beast is unfortunately fairly impossible without linking the entire project together, which I don't want to do (it's a pretty complex system for finding all the dependencies and stuff, and I perfer not to med...
You can just tell linker to ignore unresolved symbols. I couldn't find option that links them to abort or something like that. The policy to ignore unresolved symbols in object files only is the most natural, I suppose: gcc -Wl,--unresolved-symbols=ignore-in-object-files obj.o another.o etc.o Other options include (...
2,007,274
2,008,479
a library forces global overloads of new/delete on me!
I'm maintaining a plugin (implemented as a dll) for a big closed source application. This has been working fine for years. However, with the latest update to it's SDK the vendor overloaded global operators new and delete. This causes lots of trouble for me. What happens is that my plugin allocates a string. I pass this...
If you're compiling in (via header inclusion) an overridden new/delete operator(s), then all calls in your code to new/delete will use them. There is no way to re-override it (link errors) or only partially override it, etc. It is bad form to override the global new/delete operators, at all. It's a bad idea. If you do...
2,007,736
2,013,671
Create GStreamer XUL element?
I would like to create a custom XUL element named 'video' for a video editing application based on XULRunner. In the XPCOM documentation it is explained how to access your component from Javascript, but I can't seem to find any documentation on how to declare a new XUL element. Where can I find this? Can anyone point m...
You can't implement a new XUL element using XPCOM. Your options are: Use an existing element like HTML5 <video> or <canvas>. Here's a demo of the two playing together. With the improved speed of JS engine it might be fast enough for your needs. implement a new element using XBL (its content can only be a combination o...
2,008,059
2,008,073
Socket select() works in Windows and times out in Linux
I'm porting a windows network application to linux and faced a timeout problem with select call on linux. The following function blocks for the entire timeout value and returns while I checked with a packet sniffer that client has already sent the data. int recvTimeOutTCP( SOCKET socket, long sec, long usec ) { struc...
I think the first parameter to select() should be socket+1. You really should use another name as socket also is used for other things. Usually sock is used.
2,008,135
2,008,219
Suspend and resume the main thread in C++ for Windows
I need to be able to suspend and resume the main thread in a Windows C++ app. I have used handle = GetCurrentThread(); SuspendThread(handle); and then where is should be resumed ResumeThread(handle); while suspending it works, resuming it does not. I have other threads that are suspended and resumed with no problems,...
Are you using the "handle" value you got from GetCurrentThread() in the other thread? If so that is a psuedo value. To get a real thread handle either use DuplicateHandle or try HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, GetCurrentThreadId());
2,008,362
2,097,008
dlmalloc + CPP + strdup + Mac OS X = crash
I am using the dlmalloc library on Mac OS X in a mixed C/C++ environment. The following simple code /// strdup-test.cpp /// #include <iostream> #include <string> int main(int argc, char **argv) { std::string s1("foo"); char *c1=strdup(s1.c_str()); std::cerr << c1 << std::endl; // segfault? free(c1); ...
I think I've figured out what's happening. It has to do with the way Mac OS X forces you to use dynamic libc. dlmalloc is compiled statically into the exe. But regular malloc is being used in the dynamic libc. When you call strdup, it uses regular malloc, but then when free is called it is using dlmalloc. Boom.
2,008,398
2,008,577
Is it possible to print out the size of a C++ class at compile-time?
Is it possible to determine the size of a C++ class at compile-time? I seem to remember a template meta-programming method, but I could be mistaken... sorry for not being clearer - I want the size to be printed in the build output window
If you really need to to get sizeof(X) in the compiler output, you can use it as a parameter for an incomplete template type: template<int s> struct Wow; struct foo { int a,b; }; Wow<sizeof(foo)> wow; $ g++ -c test.cpp test.cpp:5: error: aggregate ‘Wow<8> wow’ has incomplete type and cannot be defined
2,008,414
2,008,468
C++ interface for hdiutil on Mac
Does a system call or library exist that would allow my C++ code to use hdiutil on Mac OS X. My code needs to mount an available .dmg file and then manipulate what's inside.
If you can use Objective-C++, you can use NSTask to run command line tools: NSTask *task = [[NSTask alloc] init]; [task setLaunchPath: @"/usr/bin/hdiutil"]; [task setArguments: [NSArray arrayWithObjects: @"attach", @"/path/to/dmg/file", nil]]; [task launch]; [task waitUntilExit]; if (0 != [task terminationStatus]) ...
2,008,433
2,008,454
Cross-platform compiling of a Qt application
I have written a C++ application that uses the Qt framework. I would like to make this application available on different platforms. Since I use Linux, I have no problems compiling the code for Linux. The questions is: Can I compile my code in such a way that it will run on Windows, Mac, etc.? As said above, I'm worki...
You can kind of do this for Windows, but I don't think there is anything you can do for Mac. For Windows, see these two articles: Cross-compiling Qt4/Win on Linux Cross compiling Qt/Win Apps on Linux Also, see this prior stack overflow question.
2,008,487
2,008,751
Can I expand #include files inline and not expand directives?
I'm trying to simplify the deployment of an application. In order to build the final application on an end-user's machine, a couple of C files need to be compiled. This means that dozens of header files need to be shipped along with the application. I'd like to be able to pre-include the contents of the include file...
Due to double-include guards, a tool that inlines #includes may cause a giant file, where a lot of the headers are entirely inside #ifndefs that don't match. In extreme cases, it may even cause an infinite-size output file, if includes are recursive (which normally isn't a problem because of the double-include guards)....
2,008,585
2,008,998
Loading Preferences in to a Mac Kernel Extension
Greetings! I am working on a kernel extension driver for OSX. It is a simple keyboard filter. I have preferences that are set through a preference pane regarding how this filter will act. I need to take the preferences from this preference pane and load them in to the kernel extension. I have googled all over and haven...
Looks like this is exactly what I am looking for: Kext Controls and Notifications Excellent.
2,008,883
2,008,939
Using vb.net dll in unmanaged c++ project
I created a vb.net dll called "WSdll.dll". I compiled it, created a type library (tlb), and registered it globally(gacutil).. It includes a file called wsutils.vb, which includes a namespace called "wsutils". In the namespace, there's an interface (with attribute) called "IWSconnection", and a class called "WSconnecti...
You put no_namespace in the #import line - so your object is not in the wsutils namespace, it's in the global namespace. Remove either the no_namespace from the #import line, or the wsutils:: from the object creation line.
2,008,948
2,009,180
Double Buffering for Game objects, what's a nice clean generic C++ way?
This is in C++. So, I'm starting from scratch writing a game engine for fun and learning from the ground up. One of the ideas I want to implement is to have game object state (a struct) be double-buffered. For instance, I can have subsystems updating the new game object data while a render thread is rendering from th...
I recently dealt with a similar desire in a generalized way by "snapshotting" a data structure that used Copy-On-Write under the hood. An aspect I like of this strategy is that you can make many snapshots if you need them, or just have one at a time to get your "double buffer". Without sweating too many implementation...
2,009,287
2,009,337
How to determine if binary is stripped on Mac OS X?
On Linux if I do file foo, and assuming foo is a binary or shared library, the output will show me if the binary is stripped of symbols. When I try the same on Mac OSX, all I get "Mach-0 executable ppc". Is there another command I can use to check if files are stripped?
You could strip it and see if it gets any smaller.
2,009,295
2,009,342
In C++ can you extend a parameterized base class with different parameter value in the child class?
In all the languages that I understand this is not possible but someone was telling me it was possible in C++ but I have a hard time believing it. Essentially when you parameterize a class you are creating a unique class in the compilation stage aren't you? Let me know if I am not being clear with my question. Here is...
If you mean to ask whether you can do this in c++ : template <> class ParamClass<Type1> : public ParamClass<Type2> { }; then yes, it is possible. It is very often used, for example to define template lists or inherit traits from another type.
2,009,434
2,012,534
OOLua compile errors
Code #include <OOLua/oolua.h> class foo { public: int bar(); }; OOLUA_CLASS_NO_BASES(foo)//class has no bases OOLUA_NO_TYPEDEFS OOLUA_MEM_FUN_0(int,bar) OOLUA_CLASS_END Compiler output main.cpp(21) : error C2061: syntax error : identifier 'bar' main.cpp(22) : error C2143: syntax error : missing ';' before '...
I am sorry you are having problems with the library, there is a mailing list set up for problems such as you are seeing http://groups.google.com/group/oolua-user?pli=1 The problem is due to a typo in the cheat sheet where "OOLUA_MEM_FUN_0" should read "OOLUA_MEM_FUNC_0". Thank you for drawing attention to the matter I ...
2,009,531
2,009,551
c++ std::pair, std::vector & memcopy
is it safe to memcopy myvect.size()*sizeof(foo) bytes from the memoryadress of the first element of a std::vector<std::pair<T1, T2> > myvect into an array of struct foo{ T1 first; T2 second; } if the array is allocated with the same number of elements as the vector's size? thanks
No, a class containing T1 and T2 is not guaranteed the same layout or alignment as std::pair<T1, T2>, at least in C++98 (since std::pair is not a POD type). The story may be different in C++0x.
2,009,549
2,010,563
Compiler can't find structures, what should i be including
UPDATE: I thought it was Windsows.h i need to include and you have confirmed this, but when i do include it i get a bunch of messages like the following... 1>C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\objidl.h(5934) : error C2872: 'IDataObject' : ambiguous symbol 1> could be 'C:\Program Files\Microsof...
You'll get several nasty symbol name collisions when you #include windows.h in a C++/CLI Windows Forms app. But this is self-induced. Pumping your own message loop in a WF app is not appropriate. It already has one, Application::Run(). You can't write your own, you won't be able to preprocess the message appropriat...
2,009,584
2,009,855
Qt Application: Simulating modal behaviour (enable/disable user input)
I am currently working on an application that launches separate processes which display additional dialogs. The feature I am trying to implement is simulating modal behavior of these dialogs. More specifically, I need the application to stop processing all input, both mouse and keyboard, when the dialog is launched, an...
To get full access to the application wide events, use QObject::installEventFilter() or QCoreApplication::setEventFilter() on your application object. If your filter function returns true, Qt stops further processing of the event. To not get too platform specific with the forwarding of the events to your other applicat...
2,009,605
2,011,983
Is there a way to stop a boost::signal from calling its slots if one of them returns true?
I am using the boost library and my question is about boost::signals. I have a signal that might call many different slots but only one slot will match the call so I want this particular slot to return true and that the calling will stop. Is it possible? Is it efficient? Can you guys suggest me a better way to do it if...
After some research I've found that in boost documentation they write about Slots that return values. They suggest to use a different combiner like this: struct breakIfTrue { template<typename InputIterator> bool operator()(InputIterator first, InputIterator last) const { if (first == last) return fal...
2,009,623
2,009,878
Explanation required for BITCOUNT macro
Can someone explain how this works? #define BX_(x) ((x) - (((x)>>1)&0x77777777) \ - (((x)>>2)&0x33333333) \ - (((x)>>3)&0x11111111)) #define BITCOUNT(x) (((BX_(x)+(BX_(x)>>4)) & 0x0F0F0F0F) % 255) Clarificati...
The output of BX_(x) is the number of on bits in each hex digit. So BX_(0x0123457F) = 0x01121234 The following: ((BX_(x)+(BX_(x)>>4)) & 0x0F0F0F0F) shuffles the counts into bytes: ((BX_(0x0123457F)+(BX_(0x0123457F)>>4)) & 0x0F0F0F0F) = 0x01030307 Taking this result modulo 255 adds up the individual bytes to arrive at ...
2,009,625
2,009,736
undefined reference to `pthread_mutex_trylock'
I have the following test program. #include <iostream> #include <cstdlib> using namespace std; pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char *argv[]) { int iret; iret = pthread_mutex_trylock( & mymutex ); cout << "Test2 !!! " << endl; pthread_mutex_unlock( & mymutex ); ret...
If you use pthread functions you should link your object files with -lpthread and not worry about whether symbols are included in libc. The rationale behind this is said to be such: some time ago the stubs in libc were used when application that used threads was run on a system without threading support. On such syste...
2,009,924
2,012,923
specialize a member template without specializing its parent
I have a class template nested inside another template. Partially specializing it is easy: I just declare another template< … > block inside its parent. However, I need another partial specialization that happens to specify all its local template arguments. This makes it into an explicit specialization. Explicit specia...
It is illegal under C++ standard 14.7.3/18: .... the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.
2,009,996
2,010,017
std::string in struct - Copy/assignment issues?
Suppose I have a struct containing a std::string, like this: struct userdata{ int uid; std::string username; } Do I need to create a copy ctor or anything to return it from a function or to use it inside a STL container? Consider this function: userdata SomeClass::GetUserData(unsigned int uid) { ...
std::string is reference-counted, and its copy constructor takes place. So nothing to worry about. Everything is handled correctly.
2,010,123
2,010,292
Access iPhone from Windows
I've seen a couple programs running in Windows that could access the iPhone and iTouch with access to the photo library and music. What APIs are used for this kind of development?
Checkout Bonjour. It's a service discovery protocol by Apple and there is a windows implementation available. Apple has released various samples that you can use as a starting point. Checkout this sample game WiTap to get started. And for a broader overview, this tutorial might be good. Once you discover a network devi...
2,010,215
2,024,733
Boost shared_memory_object problem with types different from char
I have a problem with boost shared_memory_object and mapped_region. I want to write a set of objects (structures) in the memory object. If the structure contains just a char, everything is ok; if I just add an int to the structure, then if I put too many objects (let's say 70, so much less than the limit of the block) ...
pData += sizeof(Record); That line is the problem. Pointer arithmetic means changes are in "units" of the underlying pointer type, in this case Record. So if you want to increment to the next record, you should do pData++, rather than pData += sizeof(Record), which will increase the pointer by 64 bytes (assuming siz...
2,010,532
2,010,564
boost::bind with null function pointers
If the function pointer embedded in a boost::bind return object is NULL/nullptr/0, I need to take action other than calling it. How can I determine if the object contains a null function pointer? Addenda I don't believe I can use and compare boost::functions as the boost::bind return object is used with varying call s...
You can either bind to a dummy function: void dummy() { /* has differing behaviour */ } // ... boost::bind(&dummy)(); ... or, assuming you're using Boost.Bind together with Boost.Function, return a default constructed function object and check for empty() before calling it: typedef boost::function<void (void)> F; F cr...
2,010,835
2,010,940
Static class member declaration error
I am trying to find dynamically and statically instantiated objects number. I am getting errors that variable myheap is not declared. #include<iostream.h> #include<stdlib.h> class A { public: static int x; //To count number of total objects. incremented in constructor static int myheap; //To count number of he...
Your code is almost correct, but you're seeing errors about 'myheap' because the compiler was confused about earlier errors. Fix the first error first. About overloading operator new, there's more to it than a simple malloc. I have an previous example that may help, but that was global new instead of class-specific. ...
2,011,235
2,515,167
Windows Peer to Peer Global_ Group without third party ipv6 tunnel
I have been trying to develop a peer to peer application that uses Micosoft's Peer to Peer Group library. Basing my work on the Creating a Group Chat Application acrticle on msdn. This works fine for local groups and will also work for global groups if I have a thrid party tunnel adapter installed such as the gogo6 c...
Some Teredo clients are unreachable due to symmetric router problem. Teredo can work only behind 90% of routers. Gogo6 uses TSP which tunnels the packet to gogo6 infrastructure from where it reaches ipv6 internet.
2,011,272
2,013,890
Problem in calling a virtual function across Symbian DLLs
My IM application setup is like below: User Interface module (exe) Plugin module ( A polymorphic DLL that provides an abstract interface for different protocols to the UI module ) Several Protocol DLLs ( Shared library DLLs that implement the respective protocols, like Jabber, ICQ etc ) Now, I was asked to implement ...
Since File I/O cannot be done in the protocol DLLs ( it cannot access the applications private folder ) This is in fact not so. DLL code runs in the process (exe) context and can essentially do whatever the main exe can, including accessing its private directory data cage.
2,011,361
2,011,438
C++ Equivalent java.util.concurrent.ArrayBlockingQueue
May I know is there any C++ equivalent class, to Java java.util.concurrent.ArrayBlockingQueue http://download.java.net/jdk7/docs/api/java/util/concurrent/ArrayBlockingQueue.html
Check out tbb::concurrent_bounded_queue from the Intel Threading Building Blocks (TBB). (Disclaimer: I haven't actually had a chance to use it in a project yet, but I've been following TBB).
2,011,473
2,011,506
C++ Template specialisation issue
I have code that boils down to this: //Just a templated array class .. implementation doesn't matter template<int N> struct Array {}; //A simple Traits like class template<typename T> struct MyTraits {} //Specialization of the traits class template<int N> struct Foo< Array<N> > { static void monkey() {}; } int mai...
The following works for me: //Just a templated array class .. implementation doesn't matter template<int N> struct Array {}; //A simple Traits like class template<typename T> struct MyTraits {}; //Specialization of the traits class template<int N> struct MyTraits< Array<N> > { static void monkey() {}; }; int mai...
2,011,666
2,011,684
changes not reflected in the variable values passed between C# code and C++ code
I have an application which uses C# front end and a C++ DLL as the backend. I am trying to pass an array from C# code to the C++ code in the DLL which changes the values in that array. But when I try to retrieve the values of the array from C# code after the call is made to the C++ DLL function, the changes are not bei...
The array is being marshalled by value to the C++ DLL, which means your C++ DLL is working on a copy of the original array. The array needs to be marshalled by reference in order for your C++ code to manipulate the same array which your C# code is referring to. Rather than investigating methods of marhsalling the array...
2,011,863
2,011,915
Can i use boost::threadpool as a 'thread-safe queue'?
What I need is actually a thread-safe queue structure, where multiple clients keep dumping data into the queue and one working thread keeps processing and popping the queue is there any well-established solution existing in STL or Boost? I now think about using Boost::threadpool to do this. Simply set the number of par...
In boost there is a message queue class, that is what you need: a thread-safe queue. Message queues is a widely-used concept for interprocess communication. A message queue is thread-safe queue, which key feature is that it blocks on reading from empty queue and waits for data to appear in it. In that boost class, ti...
2,012,210
2,012,257
IPC between .NET and C++ applications
Are there any libraries for inter-process communication (IPC) between a .NET application and a native C++ application?
You can use Socket for simple communication. It's in the os so you don't need any new libraries. Detailed info in C++ Socket and C# Socket If the interprocess communication is always going to be done on the same machine, named pipes is the way to go because they are faster than other options.
2,012,268
2,012,314
cin.get() and omitting newline char
I have a small, simple program with menu and submenus. User choose from 1-9 and hits enter. I want the code to read ONLY numbers 1-9 removing "\n" from stdin. I've tried sth like this: #include <cstdio> #include <iostream> using std::cin; using std::cout; using std::endl; class cProgram { private: char W; pu...
I am not sure about your problem but I have a few tips for you. When you are using C++ then you should use std::cout and std::cin for input and output. They are stream from library <iostream>. You can also write using namespace std; and then you needn't write std::. Function printf() comes from C and is type unsafe so ...
2,012,375
2,012,438
Reading files multi-data-type (c++)
I want to read from one file that has several kinds of data-types. I utilize ifstream (C++ language) but it can't read strings. In fact, I have written a code that has too many options and input parameters. Now, I want to read these parameters and (bool) options from an input file, then I can run my program by editio...
std::ifstream can certainly read strings. Have you remembered to include <string> though?
2,012,379
2,012,564
Should the caller initialize "out" parameters?
Many Win32 API functions have parameters specified to be "out". For example, GetIconInfo() description says about the second parameter that The function fills in the structure's members. This implies that the function doesn't ever read the original values stored in the "out" parameter - only changes them - and therefor...
Well, in general I think initialisation is not needed, but good practice if you don't know exactly what the called function does with the values in the output variable. In this specific case, the ICONINFO structure has two HBITMAP members which are essentially pointers to bitmaps. In the general case I'd say that if yo...
2,012,476
2,012,522
Matrix multiplication using matrix template library (MTL 2)
Kindly give me some hint of matrix multiplication using MTL 2. Or any ref. or link for the documentation of MTL 2.
We're not supposed to post just links, but here you go. There is a choice of documentation in the sidebar of that page. http://www.osl.iu.edu/research/mtl/
2,012,510
2,012,535
Delete operator and arrays?
I have an abstract Base class and Derived class. int main () { Base *arrayPtr[3]; for (int i = 0; i < 3; i++) { arrayPtr[i] = new Derived(); } //some functions here delete[] arrayPtr; return 0; } I'm not sure how to use the delete operator. If I delete array of base class pointers as shown above,...
You have to iterate over the elements of your array, delete each of them. Then call delete [] on the array if it has been allocated dynamically using new[]. In your sample code, the array is allocated on the stack so you must not call delete [] on it. Also make sure your Base class has a virtual destructor. Reference: ...
2,012,552
2,013,079
process termination C++
I have the following problem: I have an application (server that never ends) written in C++ running as a service containing inside the main thread also 3 threads (mainly doing IO). In the main loop I CATCH all possible exceptions. The process terminated and nothing was printed either by the main loop or by the threads ...
Does Windows creates Core files like in unix ? it does not, automatically. however you can enable such a files by either implementing it in your code or by using external application as windbg, or Dr. Watson If from the event log I get a memory address, is there any way of knowing in which part in the application i...
2,012,602
2,013,194
Any reason to use SecureZeroMemory() instead of memset() or ZeroMemory() when security is not an issue?
This MSND article says SecureZeroMemory() is good for cases when sensitive data stored in memory for a while should be for sure overwritten as soon as possible when no longer needed. Answers to this SO question explain why this can make a difference. Now is there any sence in using SecureZeroMemory() for initializing j...
It makes no sense to use SecureZeroMemory to initialize an icon info structure. It can only overwrite bytes on the stack frame that should have been securely erased elsewhere. That horse already escaped the barn. It doesn't even make sense to initialize it at all, the return value of GetIconInfo() tells you that it ...
2,012,727
2,012,989
VS DataBreakpoints: difference between C and C++
when you set a databreakpoint in MSVS, then you put in the address and the number of bytes and finally it lets you choose betwenn "C" and "C++". this last part i dont know what it is about? what is the difference of picking C and C++ in this situation? thanks!
It only matters if you use an expression instead of entering the address directly. Parsing rules for 'C' expressions are different from those for C++. Can't think of a great example beyond a C++ member expression like "&this->member". The debugger can't figure it out for itself, mixing 'C' and C++ code in one proces...
2,012,847
2,012,861
Substituting 0A For \n
I'm at the time beginning the development of a simple hex editor(that only reads at the time). I want to substitute OA for "\n", I'm trying with this code: #include <iostream> #include <fstream> #include <iomanip> using namespace std; int main() { ifstream infile; int crtchar = (int)infile.get(); infile.open(...
You realize that you are only reading a character once, and before even opening the file, at that?
2,012,950
2,013,077
C++ class template of specific baseclass
Let's say I have the classes: class Base{}; class A: public Base{ int i; }; class B:public Base{ bool b; }; And now I want to define a templated class: template < typename T1, typename T2 > class BasePair{ T1 first; T2 second; }; But I want to define it such that only decendants of class Base can be...
More exactly: class B {}; class D1 : public B {}; class D2 : public B {}; class U {}; template <class X, class Y> class P { X x; Y y; public: P() { (void)static_cast<B*>((X*)0); (void)static_cast<B*>((Y*)0); } }; int main() { P<D1, D2> ok; P<U, U> nok; //error }
2,013,014
2,013,192
why std::cin in step 3 is omitted?
I don't understand, why cin >> W; in step 3 is omitted, if i input not a number (i.e. 's'). #include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { short W = -1; cout << "step 1) W = " << W << endl; cout << "give a number: "; cin >> W; if ( cin.fail() ) { cout ...
I'm assuming, you are puzzled by the case where you enter a non-number for step 1 and then the step 3 seems not to work. The problem is, that cin.clear() clears only the error flags of the stream. The wrong input is not taken out of the stream, so the next cin >> W just reads the same wrong input again. You can for exa...
2,013,052
2,013,207
Show other data in QTableView with QItemDelegate
I have a QTableView connected with an QSqlTableModel. In the first column, there are only dates at this format: 2010-01-02 I want this column to show the date at this format (but without changing the real data): 02.01.2010 I know that I have to create an QItemDelegate for this column, but I don't know how I can read th...
An item delegate doesn't necessarily change the data, it just renders the data. Also, if you're using Qt 4.4 or newer, look at QStyledItemDelegate instead--it's theme-aware and will look nicer. There's an example of item delegates in this article (which seems to be a mirror of official documentation that is now down or...
2,013,129
2,013,868
Bugs related to template-functions in GCC 3.4.6
I ran into a strange compile error at the office today and I'm suspecting it to be a bug in our version of GCC (3.4.6). I've been able to boil it down to a few lines of code (below). The compile error I get is: test.cpp:26: error: expected primary-expression before '>' token test.cpp:26: error: expected primary-express...
Try this instead: bar.value("yoyo").template doIt<T>(); As far as I can see, the problem is with dependent names, similar to how you sometimes need to prefix types with typename. The above specifies to the compiler that doIt is a template member method, and not a member variable doIt that is being compared using the ...
2,013,301
2,013,320
Can the struct padding be safely used by the user code?
Assuming I have a struct like the following: struct Struct { char Char; int Int; }; and sizeof( int ) is greater than one and the compiler adds padding for the Char member variable - is the compiler-generated code allowed to change the values of the padding bytes? I mean if I use pointer arithmetic and write s...
The following sentence is wrong: No, it would not overwrite the padding bytes. But it probably is not a good practice to use that. If you need it, add member variables there. I researched based on comments indicating (correctly) that I am stupid: The C Standard has an "Annex J" with section J.1 Unspecified behavior....
2,013,755
2,013,781
OpenGL: Best rendering method for terrain which texture coordinates changes in real time?
I need to render in real time rendered animations for my terrain textures; what is the best rendering method for doing this? the animation is done by adjusting the texture coordinates. I have a pre-built array for all of the animation frames texture coordinates, is there some way to make animations faster to render if ...
Display lists and other non-GPU methods will always be slow. You should try reading on Vertex Buffer Objects/Arrays. Already even this NeHe tutorial, will give you a significant speed boost. Generally a speed comparison would be : direct calls < display lists < vertex arrays < vertex buffer objects The second jump in ...
2,013,900
2,014,892
OpenGL: Adjusting LOD angle?
There must be some setting to adjust the angle when my textures miplevel changes... isnt there? It looks really ugly when the miplevel changes really early when my camera is looking at the road with angle of 10 or etc, or angle of 0 but looking straight forward to the road. What is the magical line of code? AND NO. not...
What do you mean by "mipmap changes". The mipmap level (and anisotropy, if enabled) will be selected per-texel during rendering. The typical trilinear filtering will blend between them. You're probably complaining about texture anisotropy. When viewing a surface edge-on, simple mipmapping can't get you a texture tha...
2,014,033
2,014,066
Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)
I would like to implement a client-server architecture running on Linux using sockets and C/C++ language that is capable of sending and receiving files. Is there any library that makes this task easy? Could anyone please provide an example?
The most portable solution is just to read the file in chunks, and then write the data out to the socket, in a loop (and likewise, the other way around when receiving the file). You allocate a buffer, read into that buffer, and write from that buffer into your socket (you could also use send and recv, which are socket-...
2,014,204
2,014,268
Basic C++ debugging question
Do I absolutely have to learn assembly language to be able to use the debugger optimally? I noticed that during debugging sessions, I see these cryptic codes and CPU registers... (eax... blah blah). I shall assume that that's assembly and I am supposed to somehow decipher the cause of the problem from it. Is there...
Although some asm knowledge might come very handy sometimes during debugging, a more valuable thing to do probably in your case is to get debugging symbols right. In case of gcc pass it a -g flag. In case of Visual Studio compiler, enable debugging symbols generation (yes, even for release builds) in project settings. ...
2,014,347
2,014,373
ASM-optimizations lost after compilation?
Not that I'm in that situation currently, but I'm just interested in the answer... Assuming you have some code written in C/C++ and you want to manually optimize it by modifying it in ASM. What happens if you alter the code in C/C++ and recompile from source. Sure, the optimization on the just compiled file is lost. Ho...
You write some functions in a separate ASM file and call those functions from your C/C++ code. Or you write inline assembly directly in your C/C++ code. In other words, you could start with some C/C++ code to get some basic ASM code, but after you start tweaking it, you delete the original C/C++ code and replace it wi...
2,014,391
2,014,425
Compute Arithmetic Sum to Communicate with Machine Over Serial
I am communicating with a machine over serial. Part of the protocol communication spec states that the control sum is an "arithmetic sum of bytes from <'PS'> (included), <'data'> to <'CS'>" The packet messages are structured as follows: <'PS'><'data'><'CS'>, where: <'PS'> - Packet Size Length: 1 Value: 0x02 to 0x63 Ma...
It looks like the checksum is a simple sum, modulo 256. int sum = 0; for (int j = 0; j < number_of_bytes_in_message; ++j) sum += message [j]; sum %= 256; // or, if you prefer sum &= 255;
2,014,447
2,014,929
C++ undeclared identifier - object from .net dll class
I have a vb.net dll which I imported in an unmanaged c++ project. I successfully created an object of the class object using: CComPtr< IWSconnection > pIWSconnection; pIWSconnection.CoCreateInstance( __uuidof(IWSconnection ) ); Then, when I tried to call a method from the dll: pIWSconnection.connect(...); I am...
Your pIWSconnection variable is probably out of the scope when you call connect. You need to use -> to call methods of the interface wrapped by CComPtr, by the way, . is for members of the CComPtr class.
2,014,593
2,014,626
Using a VB.NET DLL file in C++ - class is abstract
I created a VB.NET DLL file which I am using in an unmanaged C++ project. When I try to create an object of the class, I am getting an error: cannot instantiate abstract class Why would my class be abstract? How can I modify it so that it won't be abstract?
That's not how it works, you have to write COM code in C++ to use it. Take a good look at the #import directive and the smart pointers it creates.
2,014,617
2,014,732
Free / Open Source Windows Fortran Compiler Compatible with Visual Studio
I'm trying to link in some legacy Fortran code with a Visual Studio C++ project. I tried using the Windows build of gfortran to build my static library but Visual Studio complains about unresolved external symbols. I guessing this is because mixing mingw and visual studio compilers is a horrible, horrible idea. I'v...
You could go the old-school route and use f2c to translate your legacy Fortran to standard K&R C which you should be able to build with the MSFT toolchain. I have not used f2c in many moons and recall it being a tad picky and a pain to work with. As g77 and later gfortan became so much better, there was less and less n...
2,014,719
2,014,733
Declare class member to have internal linkage
Basically I have code which looks like this inside a header file: class Bar; class Foo { public: Bar GetBar(); }; class Bar { Foo CreateFoo() {} }; Bar Foo::GetBar() {...} The problem with this code is that as soon as the header is included in more then one file the linker will complain that there are multipl...
inline Bar Foo::GetBar() {...}
2,015,173
2,015,242
Tips for joining engine and GUI
I have a game playing engine written in C++. I have my own "development" GUI. The program is for sale in Japan and I have a Japanese publisher that has written an commercial GUI to join up with my game playing engine. We have had this arrangement for many years. Both my engine and his GUI are large, complex and undergo...
I would say it's actually somewhat surprising how sensitive all this code is to compiler settings. Do you know if your publisher in Japan compiles your code into a library, or directly compiles it into the main GUI? They certainly should not compile the two in the same project in Visual Studio if they require different...
2,015,176
2,015,297
issues with porting a DLL C++ class library to Visual Studio
I wrote a class library in C++ and successfully compiled it in Linux with g++ as a shared object, then created a few apps that use it. Now I have to port it to VS2008. I gave all the classes the required __declspec(dllexport) prefixes, then tried to compile it. I get a pile of warnings, which basically have to do with:...
I maintain a C++ class library that is typically used as DLL on Windows, so it can be done. Regarding your issues: That doesn't happen in my library. Perhaps you need to be using the /MD and /MDd build options? That way your C++ run-time-library comes from a DLL, too, which is the sort of picky thing VC++ is famous...
2,015,726
2,015,836
How do you populate an x86 XMM register with 4 identical floats from another XMM register entry?
I'm trying to implement some inline assembler (in C/C++ code) to take advantage of SSE. I'd like to copy and duplicate values (from an XMM register, or from memory) to another XMM register. For example, suppose I have some values {1, 2, 3, 4} in memory. I'd like to copy these values such that xmm1 is populated with {1,...
There are two ways: Use shufps exclusively: __m128 first = ...; __m128 xxxx = _mm_shuffle_ps(first, first, 0x00); // _MM_SHUFFLE(0, 0, 0, 0) __m128 yyyy = _mm_shuffle_ps(first, first, 0x55); // _MM_SHUFFLE(1, 1, 1, 1) __m128 zzzz = _mm_shuffle_ps(first, first, 0xAA); // _MM_SHUFFLE(2, 2, 2, 2) __m128 wwww = _mm_shuffl...
2,015,744
2,015,808
why using directive in C++ is not encouraged?
I read that using directive is not encouraged in C++ saying never put using directives in header files. Why is it like that? Any hint for me? Thanks!
using namespace x; is a very bad idea, since you have no idea what names you are importing, even with the standard library. However: using std::cout; and similar statements are a very good idea, because they import symbols explicitly, and make code more readable (though it still might not be a good idea to put them in ...
2,016,398
2,016,444
why does the derived class inherit the private members of the base class?
I know that the derived class can't access the private members of the base class, so why does the derived class inherit the private members of the base class? Is there any case that it is useful? Thanks!
The derived class needs the private members even though it can't access them directly. Otherwise it's behavior would not build on the class it is deriving from. For example, pretend the private stuff is: int i; and the class has a geti() and seti(). The value of i has to be put somewhere, even if it is private,
2,016,407
2,016,455
double precision C++
I think the precision of double is causing that problem, as it was described in similiar posts, but I would like to know if there is a way to achieve correct result. I'm using function template which compares two parameters and returns true if they are equal. template <class T> bool eq(T one, T two) { if (one == two)...
First you should read one (or both) of these articles: What Every Computer Scientist Should Know About Floating-Point Arithmetic and The Perils of Floating Point. If you are looking for a solution for your template, I would suggest using template specialization for the cases where T==double and T==float.
2,016,437
2,016,501
Does calling the constructor of an empty class actually use any memory?
Suppose I have a class like class Empty{ Empty(int a){ cout << a; } } And then I invoke it using int main(){ Empty(2); return 0; } Will this cause any memory to be allocated on the stack for the creation of an "Empty" object? Obviously, the arguments need to be pushed onto the stack, but I don't want to i...
Quoting Stroustrup: Why is the size of an empty class not zero? To ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects. Consider: class Empty { }; void f() { Empty a, b; if (&a == &b) cout << "impossible: report error to c...
2,016,608
2,016,927
why are concrete types rarely useful as bases for further derivation
I read "Concrete types are rarely useful as bases for further derivation"------------ Stroustrup p. 768 How to interpret this? Does it mean that we should get derived class from the base class with pure virtual function? However, I see a lot of code with derived class derived from concrete types. Can anyone help me out...
Suppose you created a derived class, then replaced every instance of the base class in your program with that derived class. Did the resulting program behave the same? If not, then you have introduced some gotchas. These gotchas will probably be accounted for in the case of a class designed for inheritance (e.g. I'v...
2,017,178
2,023,855
Customized Windows Save Dialog is no Longer Fancy -- Why?
In accordance with this question I am customizing a Win32 Save File dialog with a custom template description. Now I have a problem where the Save File dialog doesn't show the left-hand bar with my computer, recent places, etc. I can confirm that removing the custom template brings the left-hand sidebar back. What am I...
Adding to the answer from RED SOFT ADAIR-StefanWoe: Set WINVER and _WIN32_WINNT to a value >= 0x0500. The size of the OPENFILENAME structure grew for Windows 2000, and the extra space includes the FlagsEx member; apparently Windows assumes the flag OFN_EX_NOPLACESBAR if the structure is too small to contain it. Make su...
2,017,212
2,574,025
SQL Server catch error from extended stored procedure
Hello I have an extended stored procedure that sends an error message. srv_sendmsg(pSrvProc, SRV_MSG_ERROR, errorNum, SRV_FATAL_SERVER, 1, NULL, 0, (DBUSMALLINT) __LINE__, buff, SRV_NULLTERM); I've set the severity to SVR_FATAL_SERVER just as a test to see if I can cause the messag...
You can only test the result from an extended stored proc, and use that to throw an exception. ... EXEC @rtn = dbo.xp_somethingCool IF @rtn <> 0 RAISERROR ... ... In very simple terms, an extended stored proc is not SQL run by the database engine so you can't issue RAISERROR. See KB 190987 for some more info
2,017,318
2,017,634
xerces xinclude error
I am using Apache Xerces 3.0.1 XInclude. I want to use the xinclude mechanism to include XML files. I have three XML files all in the same directory. test_a.xml xincludes test_b.xml which xincludes test_c.xml. When I just have test_a.xml xinclude test_b.xml, it works. However, when I have test_b.xml xinclude test_c.xml...
As far as I can tell, your XML is OK, but I wouldn't claim to be the last word on this. It's my guess that you're hitting a bug in Xerces' XInclude processing. I note that while this code is almost three years old, it apparently wasn't released until Xerces 3.0, so it may be relatively untested. (And given the way that...
2,017,489
2,017,523
Should I use printf in my C++ code?
I generally use cout and cerr to write text to the console. However sometimes I find it easier to use the good old printf statement. I use it when I need to format the output. One example of where I would use this is: // Lets assume that I'm printing coordinates... printf("(%d,%d)\n", x, y); // To do the same thing ...
My students, who learn cin and cout first, then learn printf later, overwhelmingly prefer printf (or more usually fprintf). I myself have found the printf model sufficiently readable that I have ported it to other programming languages. So has Olivier Danvy, who has even made it type-safe. Provided you have a compile...
2,017,510
2,017,532
A Better Way To Build a Packet - Byte by Byte?
This is related to my question asked here today on SO. Is there a better way to build a packet to send over serial rather than doing this: unsigned char buff[255]; buff[0] = 0x02 buff[1] = 0x01 buff[2] = 0x03 WriteFile(.., buff,3, &dwBytesWrite,..); Note: I have about twenty commands to send, so if there was a bette...
You can initialize static buffers like so: const unsigned char command[] = {0x13, 0x37, 0xf0, 0x0d}; You could even use these to initialize non-const buffers and then replace only changing bytes by index.
2,017,581
2,017,645
Debugging parameter corruption in C++?
I've got a plugin system in my project (running on linux), and part of this is that plugins have a "run" method such as: void run(int argc, char* argv[]); I'm calling my plugin and go to check my argv array (after doing a bunch of other stuff), and the array is corrupted. I can print the values out at the top of the ...
How does translate_arguments get called? That is missing... Does it prepare an array of pointers to chars before calling the run function in the plugin, since the run function has parameter char *argv[]? This looks like the line that is causing trouble...judging by the code // Allocate array char** to_return = new cha...
2,017,623
2,017,783
"Forward-unbreakable" accessor class templates [C++]
Unless I am thoroughly mistaken, the getter/setter pattern is a common pattern used for two things: To make a private variable so that it can be used, but never modified, by only providing a getVariable method (or, more rarely, only modifiable, by only providing a setVariable method). To make sure that, in the future,...
Whilst the solution is neat from implementation point of view, architectually, it's only halfway there. The point of the Getter/Setter pattern is to give the clas control over it's data and to decrease coupling (i.e. other class knowing how data is stored). This solution achieves the former but not quite the latter. I...
2,017,866
2,017,885
C#: Workaround for Illegal Switch Statement?
Possible Duplicate: Switch statement fallthrough in C#? The following code is illegal in C# because control cannot fall through from one case label to another. However, this behaviour is perfectly legal in C++. So, how would you go about coding the same behaviour in C#? enum TotalWords { One = 1, Two, Three...
Eric Lippert, who works on the language, talks about it here: http://ericlippert.com/2009/08/13/four-switch-oddities/ Short version: the easiest fix is to use a goto: switch (totalWords) { case TotalWords.Four: phrase = "Fox" + phrase; goto case TotalWords.Three; case TotalWords.Three: ...
2,017,952
2,017,959
HTTP/S proxy starting point
I would like to make an HTTP/S proxy program to filter/deny certain http traffic based on how I parse the HTTP request in C++. Is there some kind of starting point code that I can use with an open license for commercial use? For example if I wanted to do a project on searching I would start with lucene.
nginx is a high performance HTTP/S server written in C that can be used as a proxy. It has a easy to use module system for which you can write plugins. You should consider using an existing parser like Ragel to help you on the filtering side. It is licensed under a BSD-like license which is fine for commercial use.
2,018,028
2,018,049
Definition of templated member function in templated class (C++)
I have the following templated class, declared in an .hpp file with the implementation in a .inl file included at the end of the .hpp file. It has a templated copy constructor, but I don't know nor can't find anywhere the correct syntax for implementing the templated copy constructor in the .inl file. Does anyone know ...
For the constructor you have two nested templates and you have to specify both when you define it in the .inl file: template <class X> template <class Y> Foo<X>::Foo(Foo<Y> const& other) : mBar(other.mBar) { assert(dynamic_cast<X>(mBar->someObject()) != NULL); //some more code }
2,018,108
2,018,130
Why must C# operator overloads be static?
Why does C# require operator overloads to be static methods rather than member functions (like C++)? (Perhaps more specifically: what was the design motivation for this decision?)
Take a look at this post. A couple of reasons, the primary seeming to be to preserve operator symmetry (such that the left hand side of a binary operation does not get special treatment, as being responsible for dispatching the operation).
2,018,201
2,018,972
VC++ Building directshow baseclasses
I am a newbie to DirectX SDK, Platfrom SDK and DirectShow. I downloaded latest Platform SDK and DirectX SDK August'09. I tried to build sample project in folder: Microsoft Platform SDK\Samples\Multimedia\DirectShow\Capture\PlayCap\ And had following building errors: LINK : fatal error LNK1181: cannot open input fi...
Microsoft has renamed Platfrom SDK to Windows SDK. The lastest Windows SDK is Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1. Windows SDK for Windows 7 has Visual Studio 2008 2005 project files for all DirectShow projects.
2,018,244
2,018,340
How to replace a string between two substrings in a string in VC++/MFC?
Say I have a CString object strMain="AAAABBCCCCCCDDBBCCCCCCDDDAA"; I also have two smaller strings, say strSmall1="BB"; strSmall2="DD"; Now, I want to replace all occurence of strings which occur between strSmall1("BB") and strSmall2("DD") in strMain, with say "KKKKKKK" Is there a way to do it without Regex. I cannot u...
The easiest way is probably to handle the replacement recursively. Search for the starting delimiter and the ending delimiter. If you find them, put together a new string consisting of the string up to the starting delimiter, followed by the replacement string, followed by the return from recursively doing the replacem...
2,018,425
2,018,438
How to turn pcm audio into text using some lib written entirely in the C\C++ programming language?
How to turn pcm audio into text using some lib written entirely in the C\C++ programming language? So I have pcm file. I want to turn it into text. how to do it? (with speech recognizer lib of your choise (BTW i need it to work extreamly fast) So what do I need? Open Source Libs. Tutorials and blog articles on How t...
check out http://www.faqs.org/docs/Linux-HOWTO/Speech-Recognition-HOWTO.html It gives some links to some libraries that use xwindows so they may well be written in c/c++
2,018,485
2,018,513
Is it possible to run Native C++ code in Windows Azure?
I have an application written in native C++ which intends intensive computation. In fact I'm interested only in result of computation, i.e. it can be done without GUI or be controlled by some .Net service/application. Can I run it in Microsoft's Cloud? How can I do it?
If you mean stuff like P/Invoke, it is definitely possible! You have to configure your worker role to enableNativeCodeExecution though, but that's fair, don't you think? ;) You can read more here.
2,018,744
2,018,757
Automatic Clustering With Hash/Map of Vectors in C++
I have the following values for example: 0 0 0 1 3 2 These values refers to cluster Ids, where the member of the cluster is the index of the vector. Hence we want to get this sort of output: Cluster 0 -> 0,1,2 Cluster 1 -> 3 Cluster 2 -> 5 Cluster 3 -> 4 I tried the following construct but it doesn't seem to work: W...
What you are doing wrong is rewriting the vectors in the map each time. Instead of: CCTagMap.insert(make_pair(CcId,Temp.push_back(TagId))); Try: if ( CCTagMap.find( CcId ) == CCTagMap.end() ) { CCTagMap.insert(make_pair(CcId,vector<int>())); } CCTagMap[CcId].push_back( TagId ); Or even better, map <int, vector<i...
2,018,980
2,019,011
How to draw & export a transparent image with Nokia Qt C++?
I have a piece of code intended for drawing & exporting a transparent image with Nokia Qt. However, it does not work. I always see black background with lots of noise. I must fill the background with White color but I want transparency, not white color. Please kindly advise. #include <QtGui/QApplication> #include <QtGu...
I found answer by myself: I just have to add one magic line right after declaration of the pix: pix.fill(Qt::transparent); References: http://techbase.kde.org/Development/Tutorials/Graphics/Performance http://www.informit.com/articles/article.aspx?p=1174421&seqNum=3
2,019,774
2,019,840
Linkage to/from non C++ code
I did used snippet found from Internet for this kind of linking, and it works. Now I would like to gain more understanding on this topic, i.e. what should I pay attention to if my C++ code is going to be export/linked by non-C++ code. Could somebody points me to any resources useful for this? Thanks.
The key concepts in native code interoperability are name mangling, and calling conventions. But the real point here is that in general, if you want your code to be callable from other languages (you don't specify any in your question), you have to adopt a lowest-common-denominator approach. Usually that means avoidin...
2,020,163
2,020,621
What's the best(easiest) way to transfer data on C/C++
Currently I'm working on a C/C++ cross-platform client/server software. I'm very experienced developer when it comes to low level socket development. The problem with Berkley sockets/Winsock, is that you always have to make some kind of parser to get things right on the receiver side. I mean, you have to interpret data...
I can highly recommend Google Protocol Buffers.
2,020,184
2,020,205
Preincrement faster than postincrement in C++ - true? If yes, why is it?
Possible Duplicate: Is there a performance difference between i++ and ++i in C++? I heard about that preincrements (++i) are a bit faster than postincrements (i++) in C++. Is that true? And what is the reason for this?
Post-increment usually involves keeping a copy of the previous value around and adds a little extra code. Pre-increment simply does it's job and gets out of the way. I typically pre-increment unless the semantics would change and post-increment is actually necessary.
2,020,223
2,020,248
generating 'random' number using modulo from a stream of odd numbers
i want to generate a pseudo-random bool stream based on a modulo operation on another stream of integers (say X), so the operation would be return ( X % 2); The only problem is that X is a stream of integers that always ends in 1, so for instance would be somehing like 1211, 1221, 1231, 1241 .... is there a way for me...
If you'd otherwise be happy to use the last bits, use the penultimate bits instead: return (x & 0x2) >> 1; So say the next number from your stream is 23: 1 0 1 1 1 // 23 in binary & 0 0 0 1 0 // 0x2 in binary ----------- 0 0 0 1 0 Shifting that right by one bit (>> 1) gives 1. With 25, the answer would be 0: ...
2,020,372
2,020,426
Matrix multiplication in GSL-GNU
Kindly tell me the function of matrix multiplication in GSL library. I have searched a lot but I am not be able to fine it. If any one know about that function kindly answer. Thanks in advance.
I think you'll want to use the gemm family of functions, such as gsl_blas_sgemm(). Just set the scalars to one and the added matrix to zero. An example is here.
2,020,451
2,020,478
glPolygonOffset() bugs with lines
I have the following code: glEnable(GL_POLYGON_OFFSET_LINE); glPolygonOffset(1,1); // or 40,40 etc... doesnt help at all But the lines are still z-fighting, is this common bug or something...? My lines are 1.0f thick and i draw the lines last in the scene. Also i have disable GL_ALPHA_TEST and GL_LINE_SMOOTH and enabl...
GL_POLYGON_OFFSET_LINE only works for polygon rendering with glPolygonMode(GL_FRONT_AND_BACK, GL_LINE). If you're drawing primitives with GL_LINES it doesn't work. In this case you'll have to manually offset the vertices.
2,020,463
2,021,454
How should i randomly call class member methods?
I am writing a small "quiz program". It looks similar to this: #include <cstdlib> #include <iostream> #include <time.h> using namespace std; using std::cout; class cQuestion { private: static short goodAnswers[20][2]; public: static void checkAnswer(int questNumber) { /* checking input, check...
Apart from all the OOP dilemmas, maintain an array of function pointers to your member functions and randomly select one of them.
2,020,520
2,020,578
my c++ client/server file exchange implementation is very slow...why?
Hi have implemented simple file exchange over a client/server connection in c++. Works fine except for the one problem that its so damn slow. This is my code: For sending the file: int send_file(int fd) { char rec[10]; struct stat stat_buf; fstat (fd, &stat_buf); int size=stat_buf.st_size; while(size > 0) { cha...
Skip the acknowledgement of buffers! You insert an artificial round trip (server->client+client->server) for probably each single packet. This slows down the transfer. You do not need this ack. You are using TCP, which gives you a reliable stream. Send the number of bytes, then send the whole file. Do not read after se...
2,020,568
4,988,902
Seeking code stub generator (from header files)
Imagine I have the header files to a subsystem, but no access to the source code. Now I want to generate stubs to match all functions declared in the header files (for testing purposes). I wrote some simple code to do this, but it's not perfect. Does anyone know of any freely available software which will do this? [Up...
I think stubgen may be what you're after.
2,020,869
2,021,007
Seeking a true "tool-chain"
I just posted this as part of a reply to a question about the "best" bug-tracking software... Well, a tool on its own is just a tool. And while all speak of a toolchain, most just mean a loose collection of tools. Why not look for a problem tracker that "plays well with other children"? That is to say, interfaces well...
G'day, In my experience, I have found that trying to come up with a "definitive" tool chain can cause problems. One of the worst is that it tends to force people into the "everything looks like a nail" approach to projects. That is, You've done the work to select the tools you think are suitable and you now have your t...
2,021,943
2,352,627
Setup DLL doesnt run when CAB installs under CE6
I have a CAB file that installs our program to Windows CE. I have a CAB (and platform configuration) for Windows CE 5 and 6. Both CABs have their CE Setup DLL property pointing to the Primary Output of a Setup project. Both CABs contain the exact same code (C++). When installing the CE5 CAB it works perfectly and the c...
The reason this didn't work was because you have to compile the setup DLL separately for CE5 and CE6 - the code isn't totally cross platform compatible.
2,022,112
2,022,130
Can g++ / minGW play nice with the Windows SDK? Is Visual Studio the only option?
Can g++ and minGW on Windows XP use the Windows SDK? Specifically, why does g++ fail to compile: #include <stdio.h> #include <windows.h> int main(void) { printf("!!!Hello World!!!"); return EXIT_SUCCESS; } I have tried compiling by by running: g++ -c -Wall Test.cpp -IC:/Program\ Files/Microsoft\ Platform\ SDK/Incl...
I use MinGW to compile Windows programs every day, with zero problems. There must be something wrong with your installation - try the version at Twilight Dragon Media. Edit: Just re-read your post - you do not need to specify the include directory as you are doing, and probably should not do so. Also, you may (or may n...
2,022,282
2,022,307
Why do pointers use -> instead of .?
Possible Duplicate: Why does C have a distinction between -> and . ? Lets say that I have this structure: struct movies { string title; int year; } my_movie, *ptrMovie; Now I access my_movie like this: my_movie.year = 1999; Now to access a pointer I must do this: ptrMovie->year = 1999; Why do pointers use t...
The . operator accesses a member of a structure and can operate only on structure variables. If you want to do this to a pointer, you first need to dereference the pointer (using *) and then access the member (using .). Something like (*ptrMovie).year = 1999 The -> operator is a shorthand for this.
2,022,408
2,022,413
Issue with char array of size one and strcat
Ok, I'm really confused by this behaviour in VS2008. This code.. char data[512] = ""; char c[1] = ""; c[0] = '1'; strcat(data, c); .. results in data being set to this string value: 1ÌÌÌÌhÿ Surely it should just be 1? How can I ensure data only contains the single char[] that I copy into it (i.e. 1)? Why does strcat...
The problem here is that you are passing an invalid value to strcat. It expects the second parameter to be a valid c string value. To be valid it must be an array / pointer of char values which ends with a null terminator (\0). The value your are passing does not contain a null terminator and is hence invalid. You...
2,022,462
2,022,621
Any way to read big endian data with little endian program?
An external group provides me with a file written on a Big Endian machine, and they also provide a C++ parser for the file format. I only can run the parser on a little endian machine - is there any way to read the file using their parser without add a swapbytes() call after each read?
Back in the early Iron Age, the Ancients encountered this issue when they tried to network primitive PDP-11 minicomputers with other primitive computers. The PDP-11 was the first little-Endian computer, while most others at the time were big-Endian. To solve the problem, once and for all, they developed the network by...