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 meddle with it). Now, I know for certain that the functions that the referenced functions won't be called during my test, the just happen to be part of functions which share file with stuff that I do test. Is there any way to simply link these unresolved references to, let's say, abort, or something? Or is there a tool which creates the appropriate stub object file where all calls result in abort, given the set of object files that I have? I use gcc (g++) for compiling/linking, version 3.4.4. Platform is unix (solaris/sparc if that's important).
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 (quoting man ld): --unresolved-symbols=method Determine how to handle unresolved symbols. There are four possi- ble values for method: ignore-all Do not report any unresolved symbols. report-all Report all unresolved symbols. This is the default. ignore-in-object-files Report unresolved symbols that are contained in shared libraries, but ignore them if they come from regular object files. ignore-in-shared-libs Report unresolved symbols that come from regular object files, but ignore them if they come from shared libraries. This can be useful when creating a dynamic binary and it is known that all the shared libraries that it should be referencing are included on the linker's command line. The behaviour for shared libraries on their own can also be con- trolled by the --[no-]allow-shlib-undefined option. Normally the linker will generate an error message for each reported unresolved symbol but the option --warn-unresolved-sym- bols can change this to a warning. On my Linux system attempts to call the unresolved function result in "Segmentation fault".
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 string into a statically linked library which modifies it (changes it's length thus reallocating it). My application crashes. The reason is of course, that the string lives on the vendor allocated custom heap. The statically linked library knows nothing about this heap and tries to use the default new/delete operators on that memory. Boom. Now the question is: how can I keep my code clean and avoid using the vendor's operators? There is no conditional preprocessor macro. I can not avoid including the offending header since it contains 2000 lines more code I need for the plugin. I cannot pass the provided allocator into the other library since it does not provide any mechanisms for that. I have already bugged the vendor about it. I don't know what else I could try? Addendum: After some heated debate I have managed to convince the vendor to remove the overloads again from the next version of the SDK. I have solved my immediate problem by simply hacking the current SDK and removing the overloads manually. Thanks for all the suggestions in this thread. They served as arguments and further "proof" of why the overloads were a bad idea in the first place.
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 don't realize why it's a bad idea, you're not qualified to do so. If you do realize why it's a bad idea, you're qualified to do so, but you'll generally choose not to. Defining a global new/delete is exponentially more evil in a component you expect people to include directly into their project. It is your job as a customer to help the vendor doing this understand the seriousness of the situation, or stop being their customer. You can define a custom allocator type (see this link for a good tutorial on how to do so, the interface needed, etc) and use that exclusively with your STL types (it's a template argument). For shared_ptr, you need to do something a little different: it takes a deleter object as a parameter to the constructor if you don't want the default "delete p" behavior. This isn't a custom allocator; it's just a regular unary functor.
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 me in the right direction? Clarification I want to be able to connect a GStreamer pipeline to a XUL widget. This needs to be done from the C++ part of my application. In essence it boils down to the call: gst_x_overlay_set_xwindow_id(GST_X_OVERLAY(mOverlay), (gulong)windowId); So what I need to achieve is a way to access a windowId (HWND on Windows) from a XUL widget. Does such a minimal requirement (accessing the window id for a XUL component) truly require me to create NPAPI plugin? Creating an NPAPI plugin seems somewhat daunting (but probably doable thanks to this project). I would like to avoid overkill, so if a XPCOM component would suffice then that would be great. Solved! I found a way to do it in an XPCOM plugin. I discovered that it's possible to obtain the native handle of the top-level XUL window. This requires some hackery because you need to inluclude some of the private XUL headers in order to crack open de XUL element and obtain the window handle. But once you have it, you can create a child window. The next challenge is to make the child window obey the layout manager of XUL. Since this window does not exists as a XUL element it won't be affected by the layout manager at all. The workaround is to create a XUL element that will serve as a placeholder to overlay the native window on. For this element you then need to register a callback for the "resize" event. In the event handler you can make the size and position of your custom window to be the same as the XUL element. I use XBL to define an element type with the name "video". It contains a XUL label as only sub-element. This element is used in my XPCOM plugin as for the layouting described above. This solution works pretty well. Credit goes to Michael Smith of the Songbird team. He answered my question on the GStreamer mailing list. If you are interested you can look at this code.
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 of other elements, plus custom APIs and style) implement an NPAPI plugin and embed it via <object>. This allows you to handle painting and events in your C code. Examples of such plugins include Flash and the editing component (scintilla) in Komodo Edit and IDE.
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 ) { struct timeval timeout; fd_set fds;. timeout.tv_sec = sec; timeout.tv_usec = usec; FD_ZERO( &fds ); FD_SET( socket, &fds ); // Possible return values: // -1: error occurred // 0: timed out // > 0: data ready to be read cerr << "Waiting on fd " << socket << endl; return select(1, &fds, 0, 0, &timeout); }
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, is there something that is different with the main thread. I have done a lot of threading working in C# and Java but this is the first time I have done any in C++ and I'm finding it to be quite a bit different.
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); return 0; } when compiled like this gcc -c malloc.c g++ strdup-test.cpp -o strdup-test malloc.o will crash like this $ ./strdup-test foo Segmentation fault but only on Mac OS X. If I try this same code in Ubuntu or Windows (Cygwin) it won't happen. What's going on here? If I use malloc directly rather than strdup it won't crash. My guess is that the default malloc and dlmalloc are being mixed. Possibly because strdup is using the default malloc while the free call is using dlmalloc's free. If so, why doesn't this happen on other platforms? How do I work around this on Mac OS X?
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]) NSLog(@"Mount failed."); [task release]; If you need to use "plain" C++, you can use system(): if (0 != system("/usr/bin/hdiutil attach /path/to/dmg/file")) puts("Mount failed."); or fork()/exec(). You'll need to double-check whether hdiutil actually returns 0 for success or not.
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 working on a Linux machine and can't possibly install all the different platforms out there. If it is possible, what steps are required (in simple terms)? If there is any documentation on this topic, I'm happy to read anything - please just point me in the right direction. Thanks!
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 files, but I also need to be able to control the directives (#if, etc.) after the includes are in-lined. I can't find a cpp option that lets me just include headers, without doing the rest of the preprocessing. What are my options? Example: File1.h void dummy_func() {return;} File2.h #if INCLUDE_FILE1 #include "file1.h" #endif In the end, I want a file that says: #if INCLUDE_FILE1 void dummy_func() {return;} #endif
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). I just confirmed that this code compiles successfully: main.cpp: #include "a.h" int main() { return 0; } a.h: #ifndef A_H_INCLUDED #define A_H_INCLUDED #include "b.h" #endif b.h: #ifndef B_H_INCLUDED #define B_H_INCLUDED #include "a.h" #endif Since you want to keep ifdefs untouched and unparsed, a tool that inlines #includes would cause infinite output.
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't found anything regarding how to do this. Is there a way to load a plist in to a preference pane? Perhaps into an OSDictionary or something? Or, what would be the best way to get preferences from my preference pane into my kext? Thanks!
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 "WSconnection". The interface and class are public, as are all methods and properties. I then tried to implement it in an unmanaged c++ project. I imported it: #import "..\WSdll\WSdll\bin\Debug\WSdll.tlb" \ raw_interfaces_only, \ named_guids, \ no_namespace Then tried to create an instance: CComPtr< IWSconnection > pIWSconnection; pIWSconnection.CoCreateInstance( __uuidof( wsutils::WSconnection ) ); I am getting 2 errors a)wsutils is not a class or namespace name b)wsconnection undeclared identifier What other steps do i have to do to get the dll working here? TIA
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 the old data by guaranteeing there is a consistent state stored within the game object (the data from last time). After rendering of old and updating of new is finished, I can swap buffers and do it again. Question is, what's a good forward-looking and generic OOP way to expose this to my classes while trying to hide implementation details as much as possible? Would like to know your thoughts and considerations. I was thinking operator overloading could be used, but how do I overload assign for a templated class's member within my buffer class? for instance, I think this is an example of what I want: doublebuffer<Vector3> data; data.x=5; //would write to the member x within the new buffer int a=data.x; //would read from the old buffer's x member data.x+=1; //I guess this shouldn't be allowed If this is possible, I could choose to enable or disable double-buffering structs without changing much code. This is what I was considering: template <class T> class doublebuffer{ T T1; T T2; T * current=T1; T * old=T2; public: doublebuffer(); ~doublebuffer(); void swap(); operator=()?... }; and a game object would be like this: struct MyObjectData{ int x; float afloat; } class MyObject: public Node { doublebuffer<MyObjectData> data; functions... } What I have right now is functions that return pointers to the old and new buffer, and I guess any classes that use them have to be aware of this. Is there a better way?
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 details, here's some pseudocode: snapshottable<Vector3> data; data.writable().x = 5; // write to the member x // take read-only snapshot const snapshottable<Vector3>::snapshot snap (data.createSnapshot()); // since no writes have happened yet, snap and data point to the same object int a = snap.x; //would read from the old buffer's x member, e.g. 5 data.writable().x += 1; //this non-const access triggers a copy // data & snap are now pointing to different objects in memory // data.readable().x == 6, while snap.x == 5 In your case, you'd snapshot your state and pass it to render. Then you'd allow your update to operate on the original object. Reading it with const access through readable() would not trigger a copy... while accessing with writable() would trigger a copy. I used some tricks on top of Qt's QSharedDataPointer to do this. They differentiate const and non-const access via (->), such that reads from a const object won't trigger the copy on write mechanics.
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 my attempt at explaning what I am trying to do ( pay attention to class L ): //; g++ ModifingBaseClassParameter.cpp -o ModifingBaseClassParameter;ModifingBaseClassParameter #include <iostream> using namespace std; template<typename T> class Base { public: Base() {} Base(T& t) : m_t(t) {} T& getMem() {return m_t;} private: T m_t; }; template<typename T> class F: Base<T> {}; template<typename T> class L: F<long> {}; int main() { Base<int> i; F<float> f; L<long> l; cout<<i.getMem()<<endl; // cout<<f.getMem()<<endl; // why doesn't this work // cout<<l.getMem()<<endl; // why doesn't this work } So as you can see (hopefully my syntax makes sense) class L is trying to redefine its parent's float parameter to be a long. It certainly doesn't seem like this is legal but I will differ to the experts.
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 '}' main.cpp(22) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int main.cpp(22) : warning C4183: 'OOLUA_MEM_FUN_0': missing return type; assumed to be a member function returning 'int' Using Visual Studio 2008 OOLua 1.2.1 (OOLua .lib has been built and linked to) Links http://code.google.com/p/oolua/ Question How can it be fixed? The code segment is from the 'Cheat Sheet' of OOLua's google code website. Solved -> but still has problems OOLua link errors
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 will correct this. Liam
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\Microsoft SDKs\Windows\v6.0A\include\objidl.h(251) : System::Windows::Forms::IDataObject IDataObject' 1> or 'c:\windows\microsoft.net\framework\v2.0.50727\system.windows.forms.dll : System::Windows::Forms::IDataObject I Don't know how to fix this, eik! I'm trying to call PeekMessage but when I try to compile I get the following errors. 'MSG' : undeclared identifier 'HWND' : undeclared identifier 'PM_REMOVE' : undeclared identifier my code is as below... MSG message; while(form->Created) { while( PeekMessage( &message, (HWND)form->Handle.ToPointer(), 0, 0, PM_REMOVE ) ) { TranslateMessage( &message ); DispatchMessage( &message ); if( !mainWindow->Created ) break; } } I know what these structures are but can get the compiler to recognise them. Am i missing a ref or are there VC++ alias' for the same? Cheers.
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 appropriately to make stuff like keyboard shortcuts work. Work through some C++/CLI programming tutorials before you try this.
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, and resume when it's closed. It is not so important for the dialog to remain on top of the application, although if you can suggest how to do that without resorting to Always-On-Top behavior, that would be nice as well. To note, the application is compiled under both Windows and Linux. Also, it is not an option to launch the dialogs directly. They are in separate executables. Also the application is a pretty complex piece of software, so disabling widgets individually is not an option, or at least a not very viable one. I found lock() and unlock() functions in QApplication class in Qt 3.3. We are currently using Qt 4.5, which doesn't seem to have that API. As a matter of fact, Qt 4.5 QApplication class doesn't seem to provide access to the Event Loop either. To summarize: How do I disable/enable user input in a Qt Application, both mouse and keyboard shortcuts?
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 applications, i'd go for a suitable IPC mechanism.
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 it's not efficient?
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 false; while (first != last) { if (*first) return true; ++first; } } }; boost::signal<bool(), breakIfTrue> sig; Now why is that the wrong thing to do?
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) Clarification: Ideally, the answer will start something along the lines of: The macro: "BX_" subtracts three values from the passed in number. These three values represent: XXXXX YYYYY ZZZZZ This allows the BITCOUNT() to work as follows... Cheers, David
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 the correct answer 14. To see that this works, consider just a two-byte integer, 256*X + Y. This is just 255*X + X + Y, and 255*X % 255 is always zero, so (256*X + Y) % 255 = (X + Y) % 255. This extends to four-byte integers: 256^3*V + 256^2*W + 256*X + Y Just replace each 256 with (255+1) to see that (256^3*V + 256^2*W + 256*X + Y) % 255 = (V + W + X + Y) % 255. The final observation (which I swept under the rug with the 2-digit example) is that V + W + X + Y is always less than 255, so (V + W + X + Y) % 255 = V + W + X + Y.
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 ); return EXIT_SUCCESS; } If I compile it without adding the pthread library I get the error for unresolved error for pthread_mutex_trylock , but only for function pthread_mutex_trylock. If I replace pthread_mutex_trylock with pthread_mutex_trylock the program is compiled and runnig well also without the -lpthread* option. If I add the -lpthraed option to the compile commands all runs well this run well : $ g++ test2.c -o test2 -lpthread this warn unresolved : $ g++ test2.c -o test2 Example error output: $ g++ test2.c -o test2 /tmp/ccU1bBdU.o: In function main': test2.c:(.text+0x11): undefined reference topthread_mutex_trylock' collect2: ld returned 1 exit status If I replace the instruction iret = pthread_mutex_trylock( & mymutex ); with iret = pthread_mutex_lock( & mymutex ); the program compiles and run without error also if didn't add the pthread libarry to the compile command I know that is right to have the unresolved error if I didn't use the -lpthread option , but why I have not the same unresolved error also for other pthread_ function ? I'm using gcc 4.4.2 on fedora 12 $ g++ --version g++ (GCC) 4.4.2 20091222 (Red Hat 4.4.2-20) Copyright (C) 2009 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Do some have some suggestion about the meaning of this unreference only for pthread_mutex_trylock ? thanks for the help, Enzo
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 system, pthread_* functions became linked to libc stubs that returned errors showing that there's no threading functionality. While on "threaded" systems they were linked to pthread library and worked correctly. Obviously, pthread_mutex_trylock function appeared after the policy changed to linking with -lpthread. So there's no stub for it.
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 specializations, for whatever reason, must be at namespace scope. To declare it outside its parent class, the parent must be nominated, which requires a non-empty template argument list. This implies partial specialization. Partial specialization is what I'm doing, and it's supposed to work at arbitrary outer scope. But both GCC and Comeau fail to identify the template parameter in the parent nomination with the partial specialization formal arguments. template< class X > struct A { template< class Y > struct B; // initial declaration OK template< class Z > struct B< A< Z > > {}; // partial OK as long as there's a local arg template<> // ERROR: this syntax triggers explicit specialization struct B< int > {}; }; template<> // ERROR: can't nest template<>s here (why?) template< class X > // ERROR: can't deduce X from type of A<X>::B<int> (why?) struct A< X >::B< int > {}; (I left all my non-working code in; comment it appropriately to attempt to make sense.)
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) { //do error checking and other stuff... //m_usermap is std::map<unsigned int, userdata> return m_usermap[uid]; } When I insert userdata structs into the std::map, a copy of the struct gets created, right? Does a new std::string get created using the value of the username field, or does some sort of bitwise copy happen (this would be bad)? Similarly, when I return a userdata struct from the GetUserData method, does it have an independent string holding the username or do I need to define a copy ctor and explicitly create a new string?
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 device or machine, you can use whatever data format is convenient such as XML, JSON, home-grown, or binary.
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) I get a segmentation fault when writing. So far I have just seen examples where simple chars are written to the shared memory, but I have not read anything about the kind of objects that can be used. I am wondering if I have to make the conversion between my objects and a byte stream, or if such a function already exists. Or if I am just doing something wrong in my code. The commented lines are the ones that give me a segfault when decommented... #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/interprocess/containers/string.hpp> #include <cstring> #include <cstdlib> #include <string> #include <vector> #include <iostream> #include <unistd.h> struct Record { char c; int i; // float f; // double d; // char cs[32]; // boost::interprocess::string is; // std::vector<int> v; Record() {} Record(int _k) { Init(_k); } void Init(int _k = 0) { c = _k + 65; i = _k; // f = _k + _k/100.0; // d = _k + _k/1000.0; // is = "interprocess string"; // for(int j = 0; j < _k; ++j) v.push_back(j); } }; int main(int argc, char *argv[]) { using namespace boost::interprocess; using std::cerr; using std::endl; int nObjects = 0; size_t blockSize = 1024; static std::string sharedObjName("MySharedMemory"); // why static? const int writer = 1, reader = 2, error = -1; int operation = error; if(argc >= 2) { if(argv[1][0] == 'w') operation = writer; if(argv[1][0] == 'r') operation = reader; } if(argc == 1) operation = writer; if(operation == writer) // Writer process { cerr << "Number of objects to write = "; std::cin >> nObjects; // Remove shared memory on construction and destruction struct shm_remove { shm_remove() { shared_memory_object::remove(sharedObjName.c_str()); } ~shm_remove(){ shared_memory_object::remove(sharedObjName.c_str()); } } remover; shared_memory_object shm(create_only, sharedObjName.c_str(), read_write); shm.truncate(blockSize); mapped_region region(shm, read_write); offset_t shmSize; shm.get_size(shmSize); // Produce and write data Record *pData0 = static_cast<Record*>(region.get_address()); Record *pData = pData0; for(int i = 0; i < nObjects; ++i) { if(pData0 + blockSize - pData < signed(sizeof(Record))) { cerr << "Error: memory block full!" << endl; break; } pData->Init(i); pData += sizeof(Record); } //Launch child process pid_t pId = fork(); if(pId == 0) { std::string s(argv[0]); s += " r"; if(std::system(s.c_str()) != 0) { cerr << "Error launching reader process." << endl; exit(1); } exit(0); } else if(pId > 0) { sleep(2); cerr << "Writer has finished!" << endl; } else // pId < 0 exit(-1); } else if(operation == reader) // Reader process { shared_memory_object shm (open_only, sharedObjName.c_str(), read_only); mapped_region region(shm, read_only); Record *pData = static_cast<Record*>(region.get_address()); for(int i = 0; i < nObjects; ++i) { // Print pData... pData += sizeof(Record); } } else exit(1); return 0; } Thank you for any hint! MacOS X 10.6.2 - gcc 4.2 - Boost 1.41.0
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 sizeof(Record) is 8 - 8*8 = 64). You've got a similar pointer arithmetic error in the size check: pData0 + blockSize - pData < signed(sizeof(Record)) You probably want something like: blockSize/sizeof(Record)-(pData-pData0) <= 0
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 signatures in a template function. Simplified example: template <typename BRO> Retval do_stuff(BRO func, enum Fallback fallback) { if (func == NULL) { return do_fallback(fallback); } else { return use_retval(func()); } } do_stuff(boost::bind(FuncPtrThatMightBeNull, var1, var2), fallback); Solution Since the arity of the function in the callee does not change, I can "cast" the bind return object into a boost::function and call .empty() Retval do_stuff(boost::function<Retval()> func, enum Fallback fallback) { if (func.empty()) return do_fallback(fallback); else return use_retval(func()); }
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 create() { return F(); } void use() { F f = create(); if(f.empty()) { /* ... */ } } Regarding the update: I still don't see what the problem with binding to a different function like the following would be: template <typename BRO> Retval do_stuff(BRO func) { return func(); } if(funcPtr) { do_stuff(boost::bind(&use_retval, boost::bind(funcPtr, a, b))); } else { do_stuff(boost::bind(&do_fallback, fallback)); } If you'd want to move that handling out of the calling code, you could emulate variadic template function to support variable arities: template<class R, class T1> boost::function<R (T1)> bind_wrap(R (*fnPtr)(), T1& t1, Fallback fallback) { if(fnPtr) return boost::bind(&use_retval, boost::bind(funcPtr, t1)); else return boost::bind(&do_fallback, fallback); } template<class R, class T1, class T2> boost::function<R (T1, T2)> bind_wrap(R (*fnPtr)(T1, T2), T1& t1, T2& t2, Fallback fallback) { if(fnPtr) return boost::bind(&use_retval, boost::bind(funcPtr, t1, t2)); else return boost::bind(&do_fallback, fallback); } // ... etc. for all needed arities do_stuff(bind_wrap(funcPtr, var1, var2, fallback)); ... or you use the approach above to generate boost::function<> objects or your own wrappers and check for functor.empty() or similar in do_stuff().
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 heap objects. Incremented in overloaded new void* operator new(size_t t) { A *p; p=(A*)malloc(t); myheap++; return p; } void operator delete(void *p) { free(p); myheap--; } A() { x++; } ~A() { x--; } }; int A::x=0; int A::myheap=0; int main() { A *g,*h,*i; A a,c,b,d,e;//Static allocations 5 g= new A();//Dynamic allocations 3 h= new A(); i= new A(); cout<<"Total"<<A::x<<'\n'; cout<<"Dynamic"; cout<<'\n'<<"HEAP"<<A::myheap; delete g; cout<<'\n'<<"After delete g"<<A::x; cout<<'\n'<<"HEAP"<<A::myheap; delete h; cout<<'\n'<<"After delete h"<<A::x; cout<<'\n'<<"HEAP"<<A::myheap; delete i; cout<<'\n'<<"After delete i"<<A::x; cout<<'\n'<<"HEAP"<<A::myheap; }
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. Here it is cleaned up: (this compiles and runs) #include <iostream> #include <memory> #include <new> #include <stdlib.h> struct A { static int count; static int heap_count; void* operator new(std::size_t t) { void* p = malloc(t); if (!p) throw std::bad_alloc(); heap_count++; return p; } void operator delete(void *p) { free(p); heap_count--; } A() { count++; } ~A() { count--; } }; int A::count = 0; int A::heap_count = 0; int main() { using namespace std; A a, b, c, d, e; auto_ptr<A> g (new A), h (new A), i (new A); cout << "Total: " << A::count << '\n'; cout << "Dynamic\nHeap: " << A::heap_count << '\n'; g.release(); cout << "After delete g: " << A::heap_count << '\n'; h.release(); cout << "After delete h: " << A::heap_count << '\n'; i.release(); cout << "After delete i: " << A::heap_count << '\n'; cout << "Heap: " << A::heap_count << '\n'; return 0; }
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 client. However from a few things I have read it seems like I should be able to get things working through the Teredo tunnel adapter that comes built into Windows. I have tried various things and can now access ipv6 only sites (eg ipv6.google.com) without the gogo6 tunnel running, but I can't seem to find any other peers in my global group through this method. I have added a rule allowing trafic (including edge traversal) for the application in the Windows Firewall and also opened the following ports to incoming and outgoing trafic. tcp 3587 udp 3540, 1900 From the samples I have read it seems like it should just work, but it doesn't. I did read that to use teredo in an application you had to specificaly enable it. The only way I have found to do this is when opening the socket, but the group api does all of that for you so I have no known way of controlling that.
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 contact list caching feature and that meant doing File I/O. Since File I/O cannot be done in the protocol DLLs ( it cannot access the applications private folder ) I implemented a class deriving from an abstract class interface in the user interface module. I then exposed the abstract interface to the Plugin module and protocol DLLs. Let that abstract interface be named MFileService. From the protocol DLL this is how I get an instance of MFileService derived class: Protocol DLL calls a virtual function on plugin object to get a pointer to MFileService derived object Plugin object calls a virtual function on the user interface module. The user interface module creates an instance of MFileService dervied class and returns it to the caller ( The plugin object ) The plugin object inturn returns it to the protocol DLL. The problem is my application is crashing with KERN-EXEC 3 at step 1 when its making a virtual function call to plugin object. HINTS: All the virtual function calls made to the plugin object from the protocol DLL succeeds except the one I recently added. The virtual function I newly added to the plugin and user interface modules return a pointer to MFileService. I have not exported any of the virtual functions since all are pure virtual.
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 main() { Foo< Array<3> >::monkey(); } Unfortunately the compiler doesn't like it... test.cpp: In function ‘int main()’: test.cpp|17| error: ‘monkey’ is not a member of ‘Foo<Array<3> >’ What am I doing wrong, and how do I fix it? Thanks
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 main() { MyTraits< Array<3> >::monkey(); } The way you have Foo is incorrect, as you can see I changed it to match the comment. Additionally, you had a missing semicolon after the declaration of Foo/MyTraits. Lastly, for an array class I would recommend you use size_t as the type of N.
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 being reflected. I want the changes to be reflected. Please help me in this regard. Thanks, Rakesh. The following are the signatures of the functions that I am using. In C#: testStruct(structs, len); structs is the array of structures that I am passing. In C++: extern "C" __declspec(dllexport) void __cdecl testStruct(structure1* arrStruct, int len) arrStruct is the array of structures which receives the ones passed from C#.
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 by reference you may want to consider changing your C++ interface so that the manipulated array is returned to your C# code as, for example, a return value.
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 parallel threads to be 1, the input parameter of task function is changed every time new message arrives from a client. Does this make sense, is there any limitation that I have not yet anticipated here?
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, timed waits are also supported, as well as blocking the writer if the queue is full.
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; public: char choice(void); void choice(int _W); void showSubeMenu1(void); void showSubeMenu2(void); void showMainMenu(void); }; char cProgram::choice() { return W; }; void cProgram::choice(int _W) { W = _W; }; void cProgram::showMainMenu(void) { cout << "MAIN MENU:" << endl << "[1] option 1" << endl << "[2] option 2" << endl << "<0> quit" << endl << "Your choice: "; choice(cin.get()); getchar(); } switch (choice()) { case '1': choice('n'); showSubeMenu1(); break; case '2': choice('n'); showSubeMenu2(); break; case '0': break; // EXITS the program default: choice('n'); showMainMenu(); break; } // choice('n'); sets W to neutral char (not 1,2 or 0) Everything works fine, until the user hits "\n" instead of normal key. By "normal" i mean not "\n". So, when the user hits enter, it is a must to hit enter again (twice in a row). Other way the program behaves weird.
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 you shouldn't use it in C++. Also streams offer many functions for getting information about successful or unsuccessful reading/writing etc. I really recommend it to you. Method cin.get() reads only 1 character and it also can be a white character ( '\n', '\t', ' ' ). If you would like read number and ignore white spaces ( in default they are used like separators ) then you can use this code: int x; cin >> x; if ( cin.fail() ) cout << "Reading error. It is not a number." << endl; // cin.eof() means end of file, in this case it is end of input stream I know when you want read something then user have to write requested data and '\n'. Character '\n' is important. I have never tried it but I think that it can be redefined. I read it somewhere. I hope that my tips are helpful
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 edition of input file and running makefile. I think I want something like this: ... Number of Groups = 3 Name of Groups = David Jack Jill ... Now, my code must allocate memory for "Groups" object. Group should have 3 member that their names are David, Jack and Jill. Can anyone help me, please? Thanks
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 therefore the caller is free to skip initialization. Yet in one project I see the following: ICONINFO ii; ::SecureZeroMemory(&ii, sizeof(ICONINFO)); if (::GetIconInfo(hIcon, &ii)) { //do stuff, then //release bitmaps if(ii.hbmMask) ::DeleteObject(ii.hbmMask); if(ii.hbmColor) ::DeleteObject(ii.hbmColor); } Is there any sense in that SecureZeroMemory() call? What could happen without it?
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 you are passing pointers to a function then you have to be certain that: You pass in pointers that point to nothing and the function you call creates the thing pointed to for you and makes sure your pointer points to it. (and probably leaves you to manage the newly allocated stuff) or You pass in a pointer that points to something (i.e. you allocated something for it) and the function uses what you allocated. The GetIconInfo() function fits the first case. So for clarity and perhaps even security it looks like a good idea to me to ensure the HBITMAP members of the ICONINFO structure are actually zero, rather than a random value that can lead to all kinds of nastiness further down the road. So my verdict in this case would also be: not necessary but good practice.
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, will this call derived class objects destructors and clean the memory?
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: When should my destructor be virtual.
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 themselves. I saw in the event log that the process stopped with code 1000. Does Windows creates Core files like in unix ? If from the event log I get a memory address, is there any way of knowing in which part in the application it occurred? Maybe this is a clue: at the same time that it happened I started another application (not the same type).
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 it occurred? There is no way if in general, if you don't keep debug information files (pdb) Maybe this is a clue: at the same time that it happened I started another application (not the same type). this is not helpful information, unless both of the applications are interacted each other
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 just every memory block? For example in one project I see code like the following: ICONINFO ii; ::SecureZeroMemory(&ii, sizeof(ICONINFO)); if (::GetIconInfo(hIcon, &ii)) { //do stuff, then //release bitmaps if(ii.hbmMask) ::DeleteObject(ii.hbmMask); if(ii.hbmColor) ::DeleteObject(ii.hbmColor); } why use SecureZeroMemory() here instead of ZeroMemory(), memset() or value initialization? I mean if the compiler decides initialization is unnecessary and wants to optimize it out - why would I enforce it? Is there any reason to use SecureZeroMemory() here?
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 got initialized. SecureZeroMemory() only makes sense after memory was filled with secure data.
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 process is quite permissible.
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("test.txt", ifstream::in); while(infile.good()) { if(crtchar != 0xA) cout << hex << setfill('0') << setw(2) << crtchar << ":"; else cout << endl; } cout << "\n=====================================\n"; infile.close(); return 0; } It compiles without errors, but when I try to execute it, I just got nothing: C:\Documents and Settings\Nathan Campos\Desktop>hex ===================================== C:\Documents and Settings\Nathan Campos\Desktop> This is happening just after I've added the feature to substitute OA for \n, because before it was working very nice. What is wrong?
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 used as templateparameters. How can I do that?
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 << "ERROR, bad number" << endl; W = -1; cout << endl << "step 2) W == " << W << endl; cin.clear(); } cout << endl << "step 3) W == " << W << endl; cout << "give a number: "; cin >> W; cout << endl << "step 4) W == " << W << endl; system("PAUSE"); return EXIT_SUCCESS; }
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 example fill a string from cin which takes everything or you can use cin.ignore() to ignore the following characters in the input stream. See http://www.arachnoid.com/cpptutor/student1.html for a more detailed explanation.
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 the existing data and overwrite it with something different. You have any idea how to manage that?
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 gone). Since all you really want to do is customize the text, have you considered using a proxy model instead and just returning your custom QString for the date column's DisplayRole?
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-expression before ')' token The error can be avoided by introducing a temporary variable to store the result of the first statement (bar.value("yoyo")). Can anyone tell me what causes this? Is it a bug in GCC 3.4.6 (it seems to work in GCC 4.x.x) and are there other similar template-related bugs in this version? class Foo { public: template<typename T> bool doIt() const { return true; } }; class Bar { public: Foo value(const char * key) { return Foo(); } }; template<typename T> void mytestfunc() { Bar bar; // Works fine: Foo foo = bar.value("yoyo"); foo.doIt<T>(); // Does not work on gcc 3.4.6: bar.value("yoyo").doIt<T>(); } int main(int argc, char * args[]) { return 0; }
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 'less than' operator.
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 some data into the padding bytes surrounding the Char member variable and later do variable.Char = assignment is it possible that the code generated by the compiler will also overwrite some of the padding bytes?
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. It says, "The value of padding bytes when storing values in structures or unions". The implication is that the compiler can generate whatever instructions it wants to write the data into the structure, which may allow it to overwrite padding after a member.
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 you let opengl know all the animation frames or smthing? Also the terrain polygon positions may change in almost real time... It's not a heightmap. and i would like to render only a part of the terrain at once with for loop or something. Currently im using display lists, and updating them is very slow... but rendering them is fastest what i tried so far.
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 speed (DL's vs. VA's) however is BIG.
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 the LOD BIAS thing, ive got that already... its not the way to fix this.
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 that simultaneously preserves detail (avoids "fuzzies") and prevents aliasing. This is because the pixel pitch along one direction is much higher than along the other. Take a look at the GL_TEXTURE_MAX_ANISOTROPY texenv setting (originally part of an extension, now in core, I think?) for details.
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-specific ways of writing and reading data). The outline would look something like this: while (1) { // Read data into buffer. We may not have enough to fill up buffer, so we // store how many bytes were actually read in bytes_read. int bytes_read = read(input_file, buffer, sizeof(buffer)); if (bytes_read == 0) // We're done reading from the file break; if (bytes_read < 0) { // handle errors } // You need a loop for the write, because not all of the data may be written // in one call; write will return how many bytes were written. p keeps // track of where in the buffer we are, while we decrement bytes_read // to keep track of how many bytes are left to write. void *p = buffer; while (bytes_read > 0) { int bytes_written = write(output_socket, p, bytes_read); if (bytes_written <= 0) { // handle errors } bytes_read -= bytes_written; p += bytes_written; } } Make sure to read the documentation for read and write carefully, especially when handling errors. Some of the error codes mean that you should just try again, for instance just looping again with a continue statement, while others mean something is broken and you need to stop. For sending the file to a socket, there is a system call, sendfile that does just what you want. It tells the kernel to send a file from one file descriptor to another, and then the kernel can take care of the rest. There is a caveat that the source file descriptor must support mmap (as in, be an actual file, not a socket), and the destination must be a socket (so you can't use it to copy files, or send data directly from one socket to another); it is designed to support the usage you describe, of sending a file to a socket. It doesn't help with receiving the file, however; you would need to do the loop yourself for that. I cannot tell you why there is a sendfile call but no analogous recvfile. Beware that sendfile is Linux specific; it is not portable to other systems. Other systems frequently have their own version of sendfile, but the exact interface may vary (FreeBSD, Mac OS X, Solaris). In Linux 2.6.17, the splice system call was introduced, and as of 2.6.23 is used internally to implement sendfile. splice is a more general purpose API than sendfile. For a good description of splice and tee, see the rather good explanation from Linus himself. He points out how using splice is basically just like the loop above, using read and write, except that the buffer is in the kernel, so the data doesn't have to transferred between the kernel and user space, or may not even ever pass through the CPU (known as "zero-copy I/O").
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 some shortcut to understanding the debugger without having to learn assembly language? PS: I saw an book on assembly that was almost 1000 pages and I don't have the stomach to go through it. Please help. Edited:****I am using codeBlocks ide. But i guess the question still stands even for MSVC++
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. If you're using other compiler read its documentation on the subject. And last, but not least, if you're on Windows, consider downloading debugging symbols for their binaries, as it might make your life a lot easier. Find those here: microsoft site
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. How do you avoid that these optimizations need to be redone each time the project is compiled? Do you create separate source files for the parts that need to be optimized to make it less complex? Or is there some kind of automatic tool to do this...? Guess you cannot use diff/patch for this... Please share your experiences, thanks
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 with your ASM code, using one of these 2 methods.
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 Max packet length is 99 bytes <'data'> - Data Length: 1...90 bytes Value: 0x00 - 0xFF The length of the data part depends on the command. <'CS'> - Check Sum Length - 1 byte Value: 0x00 - 0xFF Example: ACK Packet: 0x02 0x01 0x03 where 0x03 is the checksum. So how do I compute the checksum for these bytes in C++?
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 getting an error: pIWSconnection undeclared identifier. Why would the object work with 'CoCreateInstance', and not with 'connect'? TIA
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've googled a bit and I see my options are Intel's and Lahey's compilers but both carry a hefty price tag. Does anyone know of other options, or a different approach I can take? EDIT IN RESPONSE TO COMMENTS The error I'm getting is: Error 7 error LNK2019: unresolved external symbol ___chkstk referenced in function fmm Searching around led me to this, which just seems like a bad idea.
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 need to use it. That said, for your legacy needs it sounds like a good fit. The Wikipedia entry on f2c also contains a link to the f2c sources at Netlib. Edit: This may not free you from the run-time requirements though -- your C++ app may need to be linked to the f2c runtime.
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 multiple definitions of Foo::GetBar. However I can't put it inside the class definition where that would work, because Bar isn't defined at that point. I don't want to put it inside a seperate .cpp file, because the rest of the library I'm writing (which isn't that heavy weight anyway) is mostly templates I would have to place in a header anyway and it seems a bit anoying to require linking something else in only because I had to put one function outside the header. So is there anyway to solve this problem without creating another .cpp file?
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 regular changes between releases. When my publisher wants a new version I will send him my source files which he then compiles along with his GUI, and his GUI will call a set of prearranged functions within my engine. It seems that every time we go through this process we always get tripped up by a compiler flag or two being different at his end than mine. This would be a very small problem if we both spoke the same language and were in the same time zone, but as we don't it seems that even the smallest issue can cause major headaches and delays. Someone has suggested that if I sent him a library rather than the sources then this would reduce the chance of errors, whilst someone else said that I should send him the project files.... I'm not so sure of the pro's and con's of either. Does anyone have any tips or suggestions to minimize the risk of glitches in this process. Is there any way I could make a run-time/compile-time check to make sure all the compile and link options are as expected? EDIT: Just noticed this question about recording the compiler flags in GCC. It seems that GNU allows this. Is there an equivalent command for visual studio?
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 compiler flags. If this is C++, you can use boost's static assert to ensure that certain things are set, and you should probably also put a few #error macros in places if things are not set. Having said that, I would send them a DLL and header files. This should work regardless of how they set their compiler flags. Edit: in addition, depending on what your game is you would probably be well advised to replace deep calls into your engine with a protocol that you can define using JSON, XML, ASN.1, or your own grammar - if your game does not have hardcore realtime GUI requirements, that is. In that case, the interface becomes trivial and will be hard to break with things like wrong linking flags.
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: my custom exception classes, derived from std::runtime_error, which yield: "warning C4275: non dll-interface class 'std::runtime_error' used as base for dll-interface class 'cci::FileOperationException'". How am I supposed to make a standard library class dll-exportable? exception specifications in member functions' declarations, which cause "warning C4290: C++ exception specification ignored except to indicate a function is not __declspec(nothrow)". I read somewhere that VS doesn't support these, and that it does somewhere else. How very confusing. I read people saying that exporting classes in a DLL is generally a Bad Idea, that there's a myriad of things that can go wrong, and now I have my head full of concepts like binary incompatibility, dll hell, compiler version mismatches etc, and to be honest I can't really make heads or tails of it. What is the correct, safe and easy way to create a shared class library in Windows, then? Thanks.
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 for. Don't use throw-specs. They are evil. If you feel you must do it anyway, just put something like this in a header file that every module includes before it gets to code that uses throw-specs. #pragma warning(disable: 4290)
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, 1, 1, 1}, xmm2 with {2, 2, 2, 2}, and so on and so forth. Looking through the Intel reference manuals, I couldn't find an instruction to do this. Do I just need to use a combination of repeated MOVSS and rotates (via PSHUFD?)?
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_shuffle_ps(first, first, 0xFF); // _MM_SHUFFLE(3, 3, 3, 3) Let the compiler choose the best way using _mm_set1_ps and _mm_cvtss_f32: __m128 first = ...; __m128 xxxx = _mm_set1_ps(_mm_cvtss_f32(first)); Note that the 2nd method will produce horrible code on MSVC, as discussed here, and will only produce 'xxxx' as result, unlike the first option. I'm trying to implement some inline assembler (in C/C++ code) to take advantage of SSE This is highly unportable. Use intrinsics.
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 the global scope in header files).
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) return true; else return false; } It works with eq (0.8,0.8), but it doesn't work with eq (0.8*0.2,0.16). As I mentioned I assume it has to do with double precision as it also works fine with int eq(8*2,16).
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 incur any extra overhead. Basically I am using the constructor as a static member. The reason I want to do this is because of templates. The actual code looks like template <int which> class FuncName{ template <class T> FuncName(const T &value){ if(which == 1){ // specific behavior }else if(which == 2){ // other specific behavior } } }; which allows me to write something like int main(){ int a = 1; FuncName<1>(a); } so that I get to specialize one template parameter, while not having to specify the type of T. Also, I am hoping the compiler will optimize the other branches away inside the constructor. If anyone knows if this is true or how to check, that would be greatly appreciated. I assumed also that throwing templates into the situation does not change the "empty class" problem from above, is that right?
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 compiler supplier"; Empty* p1 = new Empty; Empty* p2 = new Empty; if (p1 == p2) cout << "impossible: report error to compiler supplier"; } There is an interesting rule that says that an empty base class need not be represented by a separate byte: struct X : Empty { int a; // ... }; void f(X* p) { void* p1 = p; void* p2 = &p->a; if (p1 == p2) cout << "nice: good optimizer"; } This optimization is safe and can be most useful. It allows a programmer to use empty classes to represent very simple concepts without overhead. Some current compilers provide this "empty base class optimization".
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've seen some classes designed for inheritance that actually have functions to check if other functions are implemented to allow for the case of them not even existing, e.g. file i/o classes that might be missing seek functionality). Since an abstract class is always going to have been designed with inheritance in mind but a concrete class might not, this could be unsafe. The explanation above talks about the case where the resulting derived class is not fully compatible with the base class, which is dangerous. But what if it is fully compatible? In this case, some of the potential justifications for using inheritance (instead of composition) fall apart. We don't have any virtual functions or protected members (if we do, then I assume the class was designed for inheritance). Still, using inheritance in this case is probably pretty safe, though ensuring it really is fully compatible is tough. I'd rather use composition and be safe. Edit: The term for what I was talking about above is the Liskov Substitution Principle. A shorter explanation would be that in most cases, a derived class of a class not designed for inheritance will either violate Liskov's Substitution Principle or will not be able to accomplish anything useful that could not have been accomplished using composition instead.
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 doing that warrants its removal? How do I get both? Update: Here's some of the code I have: info.hInstance = MyGetModuleInstanceRoutine(); info.lpfnHook = MyOFNHookProcRoutine; info.lpTemplateName = MAKEINTRESOURCEW(myCustomResourceID); info.Flags = OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_NOREADONLYRETURN | OFN_ENABLESIZING | OFN_ENABLEHOOK | OFN_EXPLORER | OFN_ENABLETEMPLATE; ::GetSaveFileNameW(&info); Notes: MyOFNHookProcRoutine always returns 0. I am aware of the extended flag OFN_EX_NOPLACESBAR and it is not set (i.e. FlagsEx is 0).
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 sure the lStructSize member is set correctly too.
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 message to throw an exception in the sql. In my SQL i'm doing: BEGIN TRY EXEC dbo.xp_somethingCool SET @Error = @@ERROR END TRY BEGIN CATCH PRINT 'AN Error occoured!' SELECT ERROR_NUMBER() AS ErrorNumber ,ERROR_MESSAGE() AS ErrorMessage; END CATCH I would think that when my xp sends the error message the tsql would catch the error and select the error_number and error_message. Instead what ends up happening is that the xp sends the message and the T-SQL continues on its way like nothing happened. The @@Error variable doesn't get set either. So I was wondering if there was any trick to getting SQL to catch an error from an XP ? Thanks, Raul
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 I get the following command line error: C:\digital_receiver\test>XInclude.exe test_a.xml test_z.xml Parse test_a.xml in progress ... Fatal Error at file C:\digital_receiver\test/test_a.xml, line 3, char 34 Message: no scheme found in URI finished. test_a.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <test_a xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:include href="test_b.xml"/> </test_a> test_b.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <test_b xmlns:xi="http://www.w3.org/2001/XInclude"> <ch>5</ch> <xi:include href="test_c.xml"/> </test_b> test_c:xml: <?xml version="1.0" encoding="ISO-8859-1"?> <test_c> <channel>1</channel> </test_c> Any help would be appreciated.
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 base URIs of included documents are handled in XInclude, the possibility of a bug here seems like it's greater than 0.) As a workaround, I'd suggest doing what the error message suggests: add a scheme to the URIs for the included files. Unfortunately, for file URIs, that also means you need to use an absolute URI. test_a.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <test_a xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:include href="file://path/to/directory/test_b.xml"/> </test_a> test_b.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <test_b xmlns:xi="http://www.w3.org/2001/XInclude"> <ch>5</ch> <xi:include href="file://path/to/directory/test_c.xml"/> </test_b> UPDATE: There is indeed a similar bug at apache.org. (I think it's describing the same issue, but the wording on the report makes it sound like even a single layer of inclusion would fail when using relative paths.)
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 as above using cout.... cout << "(" << x << "," << y << ")" << endl; I know I can format output using cout but I already know how to use the printf. Is there any reason I shouldn't use the printf statement?
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 compiler that is capable of type-checking calls to printf, I see no reason not to use fprintf and friends in C++. Disclaimer: I am a terrible C++ programmer.
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 better way to send these bytes to the serial device in a more concise manner rather than having to specify each byte, it would be great. Each byte is hexadecimal, with the last byte being the checksum. I should clarify that I know I will have to specify each byte to build the commands, but is there a better way than having to specify each array position?
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 function, and they're correct, but not later on in the execution. Clearly something is corrupting the heap, but I'm at a loss of how I can try to pin down exactly what's overwriting that memory. Valgrind hasn't helped me out much. Sample code by request: My plugin looks something like this: void test_fileio::run(int argc, char* argv[]) { bool all_passed = true; // Prints out correctly. for (int ii=0; ii < argc; ii++) { printf("Arg[%i]: %s\n", ii, argv[ii]); } <bunch of tests snipped for brevity> // Prints out inccorrectly. for (int ii=0; ii < argc; ii++) { printf("Arg[%i]: %s\n", ii, argv[ii]); } } This is linked into a system that exposes it to python so I can call these plugins as python functions. So I take a string parameter to my python function and break that out thusly: char** translate_arguments(string args, int& argc) { int counter = 0; vector<char*> str_vec; // Copy argument string to get rid of const modifier char arg_str[MAX_ARG_LEN]; strcpy(arg_str, args.c_str()); // Tokenize the string, splitting on spaces char* token = strtok(arg_str, " "); while (token) { counter++; str_vec.push_back(token); token = strtok(NULL, " "); } // Allocate array char** to_return = new char*[counter]; for (int ii=0; ii < counter; ii++) to_return[ii] = str_vec[ii]; // Save arg count and return argc = counter; return to_return; } The resulting argc and argv is then passed to the plugin mentioned above.
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 char*[counter]; You are intending to allocate a pointer to pointer to chars, a double pointer, but it looks the precedence of the code is a bit mixed up? Have you tried it this way: char** to_return = new (char *)[counter]; Also, in your for loop as shown...you are not allocating space for the string itself contained in the vector...? for (int ii=0; ii < counter; ii++) to_return[ii] = str_vec[ii]; // Should it be this way...??? for (int ii=0; ii < counter; ii++) to_return[ii] = strdup(str_vec[ii]); At the risk of getting downvoted as the OP did not show how the translate_arguments is called and lacking further information....and misjudging if my answer is incorrect... Hope this helps, Best regards, Tom.
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, if you happen to have a problem to which a good solution would be simply to treat the variable before it goes in and/or out of the class, you can treat the variable by using an actual implementation on the getter and setter methods instead of simply returning or setting the values. That way, the change doesn't propagate to the rest of the code. Question #1: Am I missing any use of accessors or are any of my assumptions incorrect? I'm not sure if I am correct on those. Question #2: Are there any sort of template goodness that can keep me from having to write the accessors for my member variables? I didn't find any. Question #3: Would the following class template be a good way of implementing a getter without having to actually write the accesor? template <class T> struct TemplateParameterIndirection // This hack works for MinGW's GCC 4.4.1, dunno others { typedef T Type; }; template <typename T,class Owner> class Getter { public: friend class TemplateParameterIndirection<Owner>::Type; // Befriends template parameter template <typename ... Args> Getter(Args args) : value(args ...) {} // Uses C++0x T get() { return value; } protected: T value; }; class Window { public: Getter<uint32_t,Window> width; Getter<uint32_t,Window> height; void resize(uint32_t width,uint32_t height) { // do actual window resizing logic width.value = width; // access permitted: Getter befriends Window height.value = height; // same here } }; void someExternalFunction() { Window win; win.resize(640,480); // Ok: public method // This works: Getter::get() is public std::cout << "Current window size: " << win.width.get() << 'x' << win.height.get() << ".\n"; // This doesn't work: Getter::value is private win.width.value = 640; win.height.value = 480; } It looks fair to me, and I could even reimplement the get logic by using some other partial template specialization trickery. The same can be applied to some sort of Setter or even GetterSetter class templates. What are your thoughts?
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. In fact the other class now has to know two things - the name of the variable and the method on the getter (i.e. .get()) instead of one - e.g. getWidth(). This causes increased coupling. Having said all that, this is splitting proverbial architectural hairs. It doesn't matter all that much at the end of the day. EDIT OK, now for shits and giggles, here is a version of the getter using operators, so you don't have to do .value or .get() template <class T> struct TemplateParameterIndirection // This hack works for MinGW's GCC 4.4.1, dunno others { typedef T Type; }; template <typename T,class Owner> class Getter { public: friend TemplateParameterIndirection<Owner>::Type; // Befriends template parameter operator T() { return value; } protected: T value; T& operator=( T other ) { value = other; return value; } }; class Window { public: Getter<int,Window> _width; Getter<int,Window> _height; void resize(int width,int height) { // do actual window resizing logic _width = width; //using the operator _height = height; //using the operator } }; void someExternalFunction() { Window win; win.resize(640,480); // Ok: public method int w2 = win._width; //using the operator //win._height = 480; //KABOOM } EDIT Fixed hardcoded assignment operator. This should work reasonably well if the type itself has an assignment operator. By default structs have those so for simple ones it should work out of the box. For more complex classes you will need to implement an assignment operator which is fair enough. With RVO and Copy On Write optimizations, this should be reasonably efficient at run time.
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, Four } public String SomeMethod(TotalWords totalWords) { String phrase = ""; switch (totalWords) { case TotalWords.Four: phrase = "Fox" + phrase; case TotalWords.Three: phrase = "Brown" + phrase; case TotalWords.Two: phrase = "Quick" + phrase; case TotalWords.One: phrase = "The" + phrase; break; default: break; } return phrase; }
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: phrase = "Brown" + phrase; goto case TotalWords.Two; case TotalWords.Two: phrase = "Quick" + phrase; goto case TotalWords.One; case TotalWords.One: phrase = "The" + phrase; break; default: break; } I think the rationale here is that 9 times out of 10 a missing break is a bug rather than intentional. Forcing you to use break and an explicit branch helps keep you from writing bugs and makes it clear to future maintainters that the fall-through is intentional.
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 the correct syntax for this? Contents of Foo.hpp template <class X> class Foo { public: explicit Foo(Bar* bar); //I would like to move the definition of this copy ctor to the .inl file template <class Y> explicit Foo(Foo<Y> const& other) : mBar(other.mBar) { assert(dynamic_cast<X>(mBar->someObject()) != NULL); //some more code } void someFunction() const; private: Bar* mBar; } #include Foo.inl Contents of Foo.inl template <class X> Foo<X>::Foo(Bar* bar) : mBar(bar) { //some code } template <class X> Foo<X>::someFunction() { //do stuff }
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 file 'D:\Program Files\ Microsoft Platform SDK\samples\multimedia\directshow\baseclasses\ WIN2000_DEBUG\strmbasd.lib' As far, as I understand, I need to build all sources in "Microsoft Platform SDK\Samples\Multimedia\DirectShow\BaseClasses\" directory to get necessary lib. I tried nmake in that dir and got following: D:\Program Files\Microsoft Platform SDK\Samples\Multimedia\DirectShow\ BaseClasses\ctlutil.h(278) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int. Here is code on that lines: 278: STDMETHODIMP 279: CMediaEvent::NonDelegatingQueryInterface(REFIID riid, void **ppv) What I do wrong? Just can't believe, that using Microsoft's libraries must be so hard.
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 use regex as adding another file to the project is prohibited. Is there a way in VC++/MFC to do it? Or any easy algorithm you can point me to?
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 replacement in the remainder of the string following the ending delimiter. That, of course, assumes you want to replace all the occurrences in the main string -- if you only want to replace the first one, John Weldon's solution (for one example) will work quite nicely.
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 to do/use it.
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: What's the way to do it? #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <map> using namespace std; int main ( int arg_count, char *arg_vec[] ) { if (arg_count !=2 ) { cerr << "expected one argument" << endl; return EXIT_FAILURE; } string line; ifstream myfile (arg_vec[1]); map <int, vector <int> > CCTagMap; if (myfile.is_open()) { // Skip First Line getline(myfile,line); while (getline(myfile,line) ) { stringstream ss(line); int CcId; int TagId = -1; vector <int> Temp; while (ss >> CcId) { TagId++; cout << CcId << "-" << TagId << endl; # this way to cluster doesn't seem to work CCTagMap.insert(make_pair(CcId,Temp.push_back(TagId))); } } myfile.close(); } else { cout << "Unable to open file\n";} return 0; }
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<int> >::iterator iter = CCTagMap.find(CcId); if ( iter == CCTagMap.end() ) { CCTagMap.insert(make_pair(CcId,vector<int>())).first->second.push_back( TagId ); } else { iter->second.push_back( TagId ); }
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 <QtGui> int main(int argc, char *argv[]) { QApplication app(argc, argv); { QImage pix(260, 50, QImage::Format_ARGB32_Premultiplied); QPainter painter(&pix); painter.setBackgroundMode(Qt::TransparentMode); painter.setRenderHint(QPainter::Antialiasing, true); painter.setRenderHint(QPainter::TextAntialiasing, true); painter.setPen(QColor(0x00, 0x00, 0x00, 0xff)); painter.setBrush(QColor(0x00, 0x00, 0x00, 0xff)); painter.setFont(QFont("AvantGarde Md BT", 32)); painter.setBackgroundMode(Qt::TransparentMode); // I don't like the white color, but I must put otherwise you'll see dumb & black background painter.fillRect(0, 0, pix.width(), pix.height(), QColor(0xff, 0xff, 0xff, 0xff)); QString text("My Text"); QFontMetrics fm(painter.font()); int w = fm.width(text); int h = fm.height(); painter.drawText((pix.width() - w)/2, (pix.height() + h/2)/2, text); pix.save(QString("mytext.png")); } }
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 avoiding objects and thinking functionally, wrapping your code in DLLs and using a C-style interface. You'll probably have to define your DLL's api functions using the STDCALL calling convention. Also, if you use structures in your interface, you have to worry about structure packing. To get proper interop with Delphi using packed records, for instance, I think you'd have to set the struct member alignment to 1 byte in your C compiler.
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, and concatenate packets in order to transmit correctly. (packets often get sliced) Have in mind that the communication is going to be bidirectional. Is pure socket the best way to transmit data nowadays? Would you recommend SOAP, Webservices or another kind of encapsulation to this application?
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 to disregard the last bit (without using string manip) so the test doesnt always pass or always fail?
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: 1 1 0 0 1 & 0 0 0 1 0 ----------- 0 0 0 0 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 enabled GL_BLEND and GL_COLOR_LOGIC_OP Edit: i have already tried GL_POLYGON_OFFSET_FILL, it doesnt help.
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, checking if answer is bad or good */ /* putting the answer to cQuiz::answArr */ }; static void question1(void) { cout << "this is question 1"; }; static void question2(void) { cout << "this is question 2"; }; static void question3(void) { cout << "this is question 3"; }; static void question4(void) { cout << "this is question 4"; }; static void question5(void) { cout << "this is question 5"; }; /*and so on to question 20*/ }; short cQuestion::goodAnswers[20][2] = {0,0}; class cQuiz { private: static short questArr[5]; static short answArr[5]; public: void drawRandom(void) { srand ( time(NULL) ); for (int i = 0; i < 5; i++ ) questArr[i] = rand() % 20 + 1; }; void askQuestions(void) { for (int i = 0; i < 5; i++ ) { /* call questions by question number from questArr */ /* HOW SHOULD I CALL CERTAIN cQuestion CLASS MEMBER ?? */ cQuestion::checkAnswer(questArr[i]); } }; }; short cQuiz::questArr[5] = {0}; short cQuiz::answArr[5] = {0}; int main(int argc, char *argv[]) { cQuiz quiz; quiz.drawRandom(); quiz.askQuestions(); system("PAUSE"); return EXIT_SUCCESS; } I am wondering, how can (or should) I call class cQuestion member methods ? I was thinking about using an array of pointers to these members (cQuestion::question1, cQuestion::question2, and so on) or overloading subscript operator[]. I am not sure if either way is good or bad. Should i consider different solution or somehow use both together? Or am I completely missing the point?
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) { char buffer[1024]; bzero(buffer,1024); bzero(rec,10); int n; if(size>=1024) { n=read(fd, buffer, 1024); // Send a chunk of data n=send(sockFile_, buffer, n, 0 ); // Wait for an acknowledgement n = recv(sockFile_, rec, 10, 0 ); } else // reamining file bytes { n=read(fd, buffer, size); buffer[size]='\0'; send(sockFile_,buffer, n, 0 ); n=recv(sockFile_, rec, 10, 0 ); // ack } size -= 1024; } // Send a completion string int n = send(sockFile_, "COMP",strlen("COMP"), 0 ); char buf[10]; bzero(buf,10); // Receive an acknowledgemnt n = recv(sockFile_, buf, 10, 0 ); return(0); } And for receiving the file: int receive_file(int size, const char* saveName) { ofstream outFile(saveName,ios::out|ios::binary|ios::app); while(size > 0) { // buffer for storing incoming data char buf[1024]; bzero(buf,1024); if(size>=1024) { // receive chunk of data n=recv(sockFile_, buf, 1024, 0 ); // write chunk of data to disk outFile.write(buf,n); // send acknowledgement n = send(sockFile_, "OK", strlen("OK"), 0 ); } else { n=recv(sockFile_, buf, size, 0 ); buf[size]='\0'; outFile.write(buf,n); n = send(sockFile_, "OK", strlen("OK"), 0 ); } size -= 1024; } outFile.close(); // Receive 'COMP' and send acknowledgement // --------------------------------------- char buf[10]; bzero(buf,10); n = recv(sockFile_, buf, 10, 0 ); n = send(sockFile_, "OK", strlen("OK"), 0 ); std::cout<<"File received..."<<std::endl; return(0); } Now here are my initial thoughts: Perhaps the buffer is too small. I should therefore try increasing the size from I dunno, 1024 bytes (1KB) to 65536 (64KB) blocks, possibly. But this results in file corruption. Ok, so perhaps the code is also being slowed down by the need to receive an acknowledgement after each 1024 byte block of data has been sent, so why not remove them? Unfortunately this results in the blocks not arriving in the correct order and hence file corruption. Perhaps I could split the file into chunks before hand and create multiple connections and send each chunk over its own threaded connection and then reassemble the chunks somehow in the receiver.... Any idea how I could make the file transfer process more efficient (faster)? Thanks, Ben.
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 send and so on. EDIT: As a second step, you should increase the buffer size. For internet transfer you can assume an MTU of 1500, so there will be space for a payload of 1452 bytes in each IP packet. This should be your minimal buffer size. Make it larger and let the operating system slice the buffers into packets for you. For LAN you have a much higher MTU.
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? [Update] Five years after asking, this question is still getting upvotes. It was closed as of-topic, which it is nowadays (althoguh it was not when it was originally posted). Fortunately, we can now ask for software recommendations at https://softwarerecs.stackexchange.com/
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 with your IDE, your build tool, your version control system ... In fact, I think I'll go now and ask a question about the best linked toolchain ... So, any comments? I would prefer replies for developing C/C++ on Linux and using FOSS (but don't let that prevent you posting Windows based answers if you think that it would help someone else). We don't need a complete chain, but maybe a few groups of linked tools are still better than totally separate "links" in the chain) I use Eclipse - for coding and debugging, also its plug-ins for Doxygen for auto code-documentation Splint and CppCheck for static code analysis CppUnit for automated testing Bugzilla, et all for bug tracking CVS, Subversion, etc, for version control Hudson - for automated builds, with plug-ins for Doxygen for auto code-documentation CppCheck for static code analysis CppUnit for automated testing Bugzilla, et all for bug tracking CVS, Subversion, etc, for version control I seem to be missing a tool for project management which interfaces with other "links" in the toolchain. How complete can we make it, end to end, and is there a "best" chain (or, at least, one with the most links)? Edit: Let's not forget requirements tracking and project planning & tracking - end Edit And has anyone every diagrammed the relationship between various tools (i.e., which interfaces to which, and in which direction; which can export in the import format of another, etc)?
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 tool suite. In my experience, it is very difficult to get people to change their "canonical set" of tools for other projects once that tool set has been selected and annointed as such. I've been doing this for over twenty years now in a variety of projects that ranged from on-board submarine sonar simulators to air-traffic control display systems to helicopter control systems. Even within the same company, different projects need different tool sets to address the various problems that are going to be encountered. You might think that once you've selected a tool for a particular purpose then you can re-use that tool for all projects, e.g. your selection of BugZilla for bug tracking. But what if there is no suitable SMTP server available because you've got a distributed team and your mail server is internal, locked down, secure, for example. I'd suggest that it would be better to establish a suite of possible tools from which you can select your project's tool suite from. For example, adding Trac or FogBuzz as a possible bug tracking mechanism. A lot of things can affect your choice of tools. Off the top of my head I've got: geographical distribution of teams, internal lock down, i.e. no public access, of servers e.g. email, source repository, test platform, etc, having to interface to some existing system because of a desire to reuse aspects of that system, e.g. previous teams had had VisualSourceSafe inflicted upon them, customer insistence on the use of a particular platform, the management team for a new project having requirements that differ from the previous management team for regular management type reports, etc. Having a suite of possibilities minimises the effect of "trying to squeeze a square peg into a round hole". Anyway, you might find that you're able to trim down your suite of possibilities after a while because you can demonstrate a successful approach and so get enough traction within the company for the support of doing things the way you've previously done them. HTH
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 custom setup actions are ran from the SetupDLL. When installing the CE6 CAB the setup is not ran, however all the other files are unpacked as expected. Can anyone shed any light to why this is happening? All code and projects have been created and built using VS2005 (with all the latest service packs etc) Thanks Chris
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/Include/ I get a litany of compile errors beginning with winnt.h:666:2: #error Must define a target architecture. I have installed the Windows Server 2003 SP1 Platform SDK Background I am working on a large real-time image processing software project that up until now has used g++, minGW and gnu make files (written by hand). For a new feature, I need to interface with a frame grabber that has an SDK which was designed for Visual Studio. The framegrabber SDK depends on header files from the Windows SDK. Do I need to learn Visual Studio or is there another way?
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 not) need the slightly mysterious -mwindows flag. I just compiled your program using MinGW (TDM build) g++ 4.4.1, with the command line: g++ main.cpp with absolutely no problems. More Info: Just so you know what the -mwindows flag does, the GCC docs say: This option is available for Cygwin and MinGW targets.It specifes that a GUI application is to be generated by instructing the linker to set the PE header subsystem type appropriately. Personally, I've never found it necessary, but then my Windows apps are all command line tools or servers.
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 the -> operator and normal data types use the . operator? Is there any reason they couldn't both use the . operator?
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() copy all that garbage? Why does c even contain that garbage? Thanks for any help Edit: Thanks all.
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 need to define a null terminator for the string value c to be valid. For example char c[2]; c[0] = '1'; c[1] = '\0';
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 byte order concept (always big-Endia), and the corresponding network byte order macros ntohs(), ntohl(), htons(), and htonl(). Code written with those macros will always "get the right answer". Lean on your external supplier to use the macros in their code, and the file they supply you will always be big-Endian, even if they switch to a little-Endian machine. Rewrite the parser they gave you to use the macros, and you will always be able to read their file, even if you switch to a big-Endian machine. A truly prodigious amount of programmer time has been wasted on this particular problem. There are days when I think a good argument could be made for hanging the PDP-11 designer who made the little-Endian feature decision.