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,200,025
2,200,076
Declare types without implicit conversion in C++
I want to declare my own numeric types, exactly like unsigned int, but I do not want the types to be implicitly converted. I tried this first: typedef unsigned int firstID; typedef unsigned int secondID; but this is no good as the two types are just synonyms for unsigned int, so are freely interchangable. I'd like this to cause an error: firstID fid = 0; secondID sid = fid; // no implicit conversion error but this to be okay: firstID fid = 0; secondID sid = static_cast<secondID>(fid); // no error My reason is so that function arguments are strongly typed, eg: void f( firstID, secondID ); // instead of void f(unsigned int, unsigned int) What is the mechanism I am looking for? Thanks Si
Maybe BOOST_STRONG_TYPEDEF form boost/strong_typedef.hpp would help.
2,200,068
2,200,085
How can I control the order heap objects are destroyed?
Let's say I have 2 singletons, allocated on the heap, for which no delete is ever called. Let's call them A and B. Is there any way to make sure B will be the first one to be destroyed? I'm assuming the platform may matter on this one: Visual Studio 2005 Professional, Visual C++. Everything was built with cl.
If they are heap allocated to normal pointers, and if delete is never called on those pointers, then they will never be destroyed, so the order of destruction is moot. On the other hand, If you allocate them to static smart pointers, and if they are in the same translation unit, then the first one created will be the last one destroyed: static std::auto_ptr <AType> a( new AType ); // destroyed second static std::auto_ptr <BType> b( new BType ); // destroyed first And lets have no nitpicking about static being deprecated :-)
2,200,207
2,834,772
Objective-C++ Memory Problem
I'm having memory woes. I've got a C++ Library (Equalizer from Eyescale) and they use the Traversal Visitor Pattern to allow you to add new functionality to their classes. I've finally figured out how it works, and I've got a Visitor that just returns the properties from one of the objects. (since I don't know how they're allocated). so. My little code does this: VisitorResult AGLContextVisitor::visit( Channel* channel ) { // Search through Nodes, Pipes until we get to the right window. // Add some code to make sure we find the right one? // Not executing the following code as C++ in gdb? eq::Window* w = channel->getWindow(); OSWindow* osw = w->getOSWindow(); AGLWindow* aw = (AGLWindow *)osw; AGLContext agl_ctx = aw->getAGLContext(); this->setContext(agl_ctx); return TRAVERSE_PRUNE; } So here's the problem. eq::Window* w = channel->getWindow(); (gdb) print w 0x0 BUT If I do this: (gdb) set objc-non-blocking-mode off (gdb) print w=channel->getWindow() 0x300effb9 // an honest memory location, and sets w as verified in the Debugger window of XCode. It does the same thing for osw. I don't get it. Why would something work in (gdb) but not in the code? The file is completely a cpp file, but it seems to be running in objc++, since I need to turn blocking off. Help!? I feel like I'm missing some memory-management basic thing here, either with C++ or Obj-C. [edit] channel->getWindow() is supposed to do this: /** @return the parent window. @version 1.0 */ Window* getWindow() { return _window; } The code also executes fine if I run it from a C++-only application. [edit] No... I tried creating a simple stand-alone program since I was tired of running it as a plugin. Messy to debug. And no, it doesn't run in the C++ program either. So I'm really at a loss as to what I'm doing wrong. Thanks, -- Stephen Furlani
I suppose I should answer and close this out. The methods I was using were completely thread-unsafe. I was calling out across threads, Carbon/Cocoa, C++/ObjC. Needless to say, don't ever do that! I learned the hard way. -Stephen
2,200,257
2,200,306
How can I retrieve current terminate() handler without changing it?
Here's the problem. My application calls CoCreateInstance() to create a COM object implemented in a third-party DLL. That DLL calls set_terminate() to change the terminate() handler and passes an address of its own terminate() handler there. The initial terminate() handler address is not saved by that library - it doesn't care and simply changes the handler and never restores it. As soon as the DLL gets unloaded its code is no longer in the process memory, so if now terminate() is called the program runs into undefined behavior. I'd like to retrieve and store the address of initial terminate() handler to be able to restore it. How can I do it?
Standard C++ provides no built-in way. Of course you could just call terminate() twice: first time with whatever dummy handler you have (and then store handler that terminate() returned you); second -- to restore handler you've just stored ;) Simple trick.
2,200,277
2,200,786
Detecting debugger on Mac OS X
I am trying to detect whether my process is being run in a debugger or not and, while in Windows there are many solutions and in Linux I use: ptrace(PTRACE_ME,0,0,0) and check its return value, I did not manage to perform the same basic check on Mac OS X. I tried to use the ptrace(PT_TRACE_ME,0,0,0) call but it always returns 0 even when run under gdb. If I change the request to PT_DENY_ATTACH it correctly stops the debugging but that is not what I want to achieve. Any ideas?
You can just call the function AmIBeingDebugged() from Apple Technical Q&A QA1361, which is reproduced here because Apple sometimes breaks documentation links and makes old documentation hard to find: #include <assert.h> #include <stdbool.h> #include <sys/types.h> #include <unistd.h> #include <sys/sysctl.h> static bool AmIBeingDebugged(void) // Returns true if the current process is being debugged (either // running under the debugger or has a debugger attached post facto). { int junk; int mib[4]; struct kinfo_proc info; size_t size; // Initialize the flags so that, if sysctl fails for some bizarre // reason, we get a predictable result. info.kp_proc.p_flag = 0; // Initialize mib, which tells sysctl the info we want, in this case // we're looking for information about a specific process ID. mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); // Call sysctl. size = sizeof(info); junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0); assert(junk == 0); // We're being debugged if the P_TRACED flag is set. return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); }
2,200,394
2,200,401
Link error in C++ by g++
Please take a look at the program below. Why am I getting an error? #include <stdlib.h> #include <string> #include <string.h> #include <iostream> using namespace std; class serverData { public: static int serverTemp; static int server; }; int main(int argc, char** argv) { string s = "sajad bahmani"; serverData::server = 90 ; const char * a = s.data(); cout << a[0] << endl; return (EXIT_SUCCESS); } In conjunction, I get this error when trying to link: build/Debug/GNU-Linux-x86/main.o: In function `main': /home/sb23/pr/main.cpp:14: undefined reference to `serverData::server' collect2: ld returned 1 exit status
Static member variables must have storage allocated in one of your .CPP files: /* static */ int serverData::serverTemp; int serverData::server;
2,200,421
2,200,761
QT4 Memory Management
I come from a fairly strong C background, and have a rather solid foundation in C++. More recently I've been working with C# and other higher level languages. A project I'm looking at working on could really benefit from using QT4, but I have some questions on memory management I can't seem to understand. I've read the QT4 documentation and it hasn't helped me much. So that is why I'm here. 1) Okay so to start with, I understand that the easiest way to use QT4 objects is to declare them locally: void MyFunc() { QString foo; // do stuff to foo } This is simple enough, I can take that object, and pass it around and know that when it goes out of scope it will be destroyed. But here's my question. 1)If I create a QList and add objects to it, and then the QList goes out of scope, will it try to deallocate the child objects? 2)If a QT4 routine returns a pointer to an object, am I then responsible for the de-allocation of that object? 3)If I create a subclass of a QWidget, and add it to a QWindow, how do I insure that when the QWindow is destroyed, that it takes my widget with it? Thanks for the help.
If I create a QList and add objects to it, and then the QList goes out of scope, will it try to deallocate the child objects? QList is just like std::list. It will destroy the contained objects when it is destroyed. If a Qt4 routine returns a pointer to an object, am I then responsible for the de-allocation of that object? Usually no, the docs should specify what happens. An exception are the take* functions (e.g: QTableWidget::takeItem). If I create a subclass of a QWidget, and add it to a QWindow, how do I insure that when the QWindow is destroyed, that it takes my widget with it? It depends on how you create the subclass object. You could add it as a member of the window widget (there is no QWindow, by the way) and it will be destroyed just like any member variable. You could allocate it with new and pass it the window as parent and it will be deleted thanks to the Qt object tree implementation (as cake mentioned) You could do the memory management yourself. When a QWidget (or any QObject) is destroyed, it will remove itself from its parent's to-delete list so you can delete it yourself and not worry about double deletes.
2,200,528
2,200,726
C++ Manipulator not being executed
Well, I'm wondering why endd doesn't seem to execute (though it doesn't generate any error at compilation time). struct dxfDato { dxfDato(int c, string v = 0, int t = 0) { codigo = c; valor = v; tipo = t; } dxfDato() { } int tipo; int codigo; string valor; }; class dxfItem { private: std::ostringstream ss; typedef std::ostream& (*manip)(std::ostream&); public: int clase; string valor; vector<dxfDato> datos; vector<dxfItem> hijos; template <typename T> dxfItem& operator<<(const T& x) { ss << x; return *this; } dxfItem& operator<<(manip x) // to store std manipulators { ss << x; return *this; } static dxfItem& endd(dxfItem& i) // specific manipulator 'endd' { dxfDato dd; dd.valor = i.ss.str(); i.datos.push_back(dd); std::cout << "endd found!" << endl; return i; } }; /* blah blah blah */ dxfItem header; header << 9 << endl << "$ACADVER" << endl << 1 << endl << "AC1500" << endl << dxfItem::endd // this apparently doesn't execute anything << "other data" << endl ; This is the last problem that I found while trying to develop something. Last thing was exposed here: C++ Operator overloading example Thank you all!
You've defined type manip to be a function that takes a std::ostream by reference and returns a std::ostream by reference, but you've defined endd to take a dxfItem and return a dxfItem and dxfItem does not derive from std::ostream. Because of this type mismatch, the compiler is generating a call to the operator<< template, rather than the manip overload. Also, your manip overload needs to actually call the manipulator function passed into it: dxfItem& operator<<(manip x) { x(ss); return *this; }
2,200,530
2,200,633
Iterate Multiple std::vector
I've read here and other places that when iterating a std::vector using indexes you should: std::vector <int> x(20,1); for (std::vector<int>::size_type i = 0; i < x.size(); i++){ x[i]+=3; } But what if you are iterating two vectors of different types: std::vector <int> x(20,1); std::vector <double> y(20,1.0); for (std::vector<int>::size_type i = 0; i < x.size(); i++){ x[i]+=3; y[i]+=3.0; } Is it safe to assume that std::vector<int>::size_type is of the same type as std::vector<double>::size_type ? Would it be safe just to use std::size_t?
Yes, for almost any practical purpose, you can just use std::size_t. Though there was (sort of) an intent that different containers could use different types for their sizes, it's still basically guaranteed that (at least for standard containers) size_type is the same as size_t. Alternatively, you could consider using an algorithm, something like: std::transform(x.begin(), x.end(), x.begin(), std::bind2nd(std::plus<int>(), 3)); std::transform(y.begin(), y.end(), y.begin(), std::bind2nd(std::plus<double>(), 3.0));
2,200,646
2,200,684
How do you declare a const array of function pointers?
Firstly, I've got functions like this. void func1(); void func2(); void func3(); Then I create my typedef for the array: void (*FP)(); If I write a normal array of function pointers, it should be something like this: FP array[3] = {&func1, &func2, &func3}; I want to make it a constant array, using const before "FP", but I've got this error messages: error: cannot convert 'void ( * )()' to 'void ( * const)()' inialization PD: Sorry my bad English. EDIT: x.h typedef void (*FP)(); class x { private: int number; void func1(); void func2(); void func3(); static const FP array[3]; } x.cpp const FP x::array[3] = {&x::func1, &x::func2, &x::func3}; My code is more large and complex, this is a summary
Then I create my typedef for the array: void (*FP)(); Did you miss typedef before void? Following works on my compiler. void func1(){} void func2(){} void func3(){} typedef void (*FP)(); int main() { const FP ar[3]= {&func1, &func2, &func3}; } EDIT (after seeing your edits) x.h class x; typedef void (x::*FP)(); // you made a mistake here class x { public: void func1(); void func2(); void func3(); static const FP array[3]; };
2,200,912
2,201,715
Inheritance in Python C++ extension
I have c++ library that need communicate with Python plugged in modules. Communication supposes implementing by Python some callback c++ interface. I have read already about writing extensions, but no idea how to develop inheritance. So something about: C++: class Broadcast { void set(Listener *){... } class Listener { void notify(Broadcast* owner) = 0; } I need something like in Python: class ListenerImpl(Listener): ... def notify(self, owner): ... Note, I don't want use Boost.
Writing Python types in C that are inheritable is explained in PEP 253. It's not all that different from writing a normal builtin type as explained in the Extending/Embedding guide but you have to do certain things, like attribute access, through the Python API instead of accessing anything directly. Exposing the Python subclasses back to C++ code is a little more tedious. The Python classes won't be C++ subclasses, so you need a C++ wrapper class (that does inherit from Listener) that contains a PyObject* for the Python subclass instance, and that has a notify method that translates the arguments to Python objects, calls the notify method of the PyObject* (using, e.g., PyObject_CallMethod), translates the result back to C++ types, and returns.
2,201,012
2,201,196
In C++ how can I prevent a function from being called recursively
I have a function which makes use of memory on the heap and it will go badly wrong if it is called before another instance of the same function has completed. How can I prevent this from happening at compile time?
Detecting recursion with any amount determinism of at compile-time is going to be quite difficult. Some static code analysis tools might be able to do it, but even then you can get in to run-time scenarios involving threads that code analyzers won't be able to detect. You need to detect recursion at run-time. Fundamentally, it's very simple to do this: bool MyFnSimple() { static bool entered = false; if( entered ) { cout << "Re-entered function!" << endl; return false; } entered = true; // ... entered = false; return true; } The biggest problem with this, of course, is it is not thread safe. There are a couple of ways to make it thread safe, the simplest being to use a critical section and block the second entry until the first has left. Windows code (no error handling included): bool MyFnCritSecBlocking() { static HANDLE cs = CreateMutex(0, 0, 0); WaitForSingleObject(cs, INFINITE); // ... do stuff ReleaseMutex(cs); return true; } If you want the function to return an error when a function has been reentered, you can first test the critsec before grabbing it: bool MyFnCritSecNonBlocking() { static HANDLE cs = CreateMutex(0, 0, 0); DWORD ret = WaitForSingleObject(cs, 0); if( WAIT_TIMEOUT == ret ) return false; // someone's already in here // ... do stuff ReleaseMutex(cs); return true; } There are probably an infinite ways to skin this cat other than the use of static bools and critsecs. One that comes to mind is a combination of testing a local value with one of the Interlocked functions in Windows: bool MyFnInterlocked() { static LONG volatile entered = 0; LONG ret = InterlockedCompareExchange(&entered, 1, 0); if( ret == 1 ) return false; // someone's already in here // ... do stuff InterlockedExchange(&entered, 0); return false; } And, of course, you have to think about exception safety and deadlocks. You don't want a failure in your function to leave it un-enterable by any code. You can wrap any of the constructs above in RAII in order to ensure the release of a lock when an exception or early exit occurs in your function. UPDATE: After readong comments I realized I could have included code that illustrates how to implement an RAII solution, since any real code you write is going to use RAII to handle errors. Here is a simple RAII implementation that also illustrates what happens at runtime when things go wrong: #include <windows.h> #include <cstdlib> #include <stdexcept> #include <iostream> class CritSecLock { public: CritSecLock(HANDLE cs) : cs_(cs) { DWORD ret = WaitForSingleObject(cs_, INFINITE); if( ret != WAIT_OBJECT_0 ) throw std::runtime_error("Unable To Acquire Mutex"); std::cout << "Locked" << std::endl; } ~CritSecLock() { std::cout << "Unlocked" << std::endl; ReleaseMutex(cs_); } private: HANDLE cs_; }; bool MyFnPrimitiveRAII() { static HANDLE cs = CreateMutex(0, 0, 0); try { CritSecLock lock(cs); // ... do stuff throw std::runtime_error("kerflewy!"); return true; } catch(...) { // something went wrong // either with the CritSecLock instantiation // or with the 'do stuff' code std::cout << "ErrorDetected" << std::endl; return false; } } int main() { MyFnPrimitiveRAII(); return 0; }
2,201,131
2,201,183
Linker error with pointers
I am trying to build a program to Tolkinize a string (i'm trying to do this with out using the string class - so as to learn more about pointers and how chars work) - I have built a program that i think works (any suggestions would be great!) When i tried to compile the program I get these random errors: Error 1 error LNK2019: unresolved external symbol "public: char * __thiscall Tokenize::next(void)" (?next@Tokenize@@QAEPADXZ) referenced in function _main Driver Error 2 error LNK2019: unresolved external symbol "public: __thiscall Tokenize::Tokenize(char const * const,char)" (??0Tokenize@@QAE@QBDD@Z) referenced in function _main Driver Error 3 fatal error LNK1120: 2 unresolved externals C:\Users\Simmons 2.0\Documents\School\CS1410\project 5\Token\Debug\Token.exe I have showed this code to a couple of friends that code and none of them could figure out what is going on - or what i'm doing wrong... Note: I am running VS 2008 express edition - Windows 7 x64 Main.cpp #include <iostream> #include "tokenize.h" /// Tolkenize class using namespace std; int main ( ) { // create a place to hold the user's input // and a char pointer to use with the next( ) function char words[128]; char * nextWord; cout << "\nString Tokenizer Project"; cout << "Enter in a short string of words:"; cin.getline ( words, 127 ); // create a tokenizer object, pass in the char array // and a space character for the delimiter Tokenize tk( words, ' ' ); // this loop will display the tokens while ( ( nextWord = tk.next() ) != NULL ) { cout << nextWord << endl; } system("PAUSE"); return 0; } tokenize.h #include <iostream> #include <cassert> /// assert #include <cstdlib> /// system("cls") using namespace std; #ifndef TOKENIZE_H #define TOKENIZE_H #include <iostream> #include <cassert> #include "Tokenize.h" using namespace std; class Tokenize { private: char * current_ptr; char delimiter; public: Tokenize (); Tokenize (char); Tokenize (char const string [], char Delimiter); void setcurrent_ptr ( char * ptr ){ current_ptr = ptr; } void setdelimiter ( char Delimiter ) { delimiter = Delimiter; } char * getcurrent_ptr () { return current_ptr; } char getdelimiter () { return delimiter; } char * next (); }; #endif tokenize.cpp #include <iostream> #include <cassert> /// assert #include "Tokenize.h" using namespace std; Tokenize::Tokenize() { current_ptr = new char; *current_ptr = NULL; delimiter = ' '; }; Tokenize::Tokenize(char Delimiter) { current_ptr = new char; *current_ptr = NULL; delimiter = Delimiter; }; Tokenize::Tokenize(char const string [], char Delimiter) { current_ptr = string; delimiter = Delimiter; }; char * Tokenize::next() { char * ptr = current_ptr; If ( (*ptr) == NULL ) { return NULL; } else { while ((current_ptr)++ != ' ') {} if ( (*current_ptr) == NULL) { return NULL; } if ( *current_ptr == ' ' ) { *current_ptr = '/0'; (current_ptr)++; } return ptr; } }; From my testing (commenting out lines) I think one of the errors come from the tokinze.next()
It looks like you're not compiling/linking tokenize.cpp. It's probably not the code itself, but how you have it setup in Visual Studio. Is it possible that VS isn't including tokenize.cpp in your application? You can test that this is the problem by moving the functions from tokenize.cpp to main.cpp. If the errors go away, that's the problem.
2,201,220
2,220,253
Why is my MFC DLL deadlocking on a single thread near startup?
Using Visual Studio 2005, the debugger tells me that a deadlock has occurred just after startup of the app I'm writing - I'm well in to WinMain() at this point. The callstack shows that we are in a critical section, while calling AFX_MANAGE_STATE2 (for the 666th time, spookily enough) from within an MFC DLL. This has just started happening: the code worked fine yesterday. Weirdly, rolling back the code, rebooting the PC and rebuilding still yields the deadlock. When everything grinds to a halt, I hit pause on the debugger and this message (eventually) appears: Microsoft Visual Studio The process appears to be deadlocked (or is not running any user-mode code). All threads have been stopped. OK The call stack looks like this: ntdll.dll!_KiFastSystemCallRet@0() ntdll.dll!_ZwWaitForSingleObject@12() + 0xc bytes ntdll.dll!_RtlpWaitForCriticalSection@4() + 0x8c bytes ntdll.dll!_RtlEnterCriticalSection@4() + 0x46 bytes mfc80ud.dll!CThreadSlotData::GetThreadValue(int nSlot=1) Line 247 C++ mfc80ud.dll!CThreadLocalObject::GetData(CNoTrackObject * (void)* pfnCreateObject=0x7832e030) Line 419 + 0x11 bytes C++ mfc80ud.dll!CThreadLocal<_AFX_THREAD_STATE>::GetData() Line 177 + 0xd bytes C++ mfc80ud.dll!AFX_MAINTAIN_STATE2::AFX_MAINTAIN_STATE2(AFX_MODULE_STATE * pNewState=0x029a80d8) Line 57 + 0xa bytes C++ EmpireConsole.UnityDebug.dll!WIN_CON::SPOOL::BUFFER::overflow(unsigned short c=65) Line 979 + 0x13 bytes C++ Empire.UnityDebug.exe!UTILITYLIB::UniCharStreamBuf::sputc(CA::UniChar ch={...}) Line 113 + 0x68 bytes C++ Empire.UnityDebug.exe!UTILITYLIB::operator<<(UTILITYLIB::UniCharOStream & ucos={...}, const char * val=0x0888019c) Line 868 + 0x2f bytes C++ Empire.UnityDebug.exe!EMPIRE::ENVIRONMENT::auto_analyse() Line 319 + 0x2b bytes C++ Empire.UnityDebug.exe!EMPIRE::EMPIRE_APP_MODULE::run_vars(CA::UniString CmdLine={UniString [...] ...) Line 2531 C++ Empire.UnityDebug.exe!`anonymous namespace'::winmain_inner(HINSTANCE__ * hInstance=0x08440000, HINSTANCE__ * __formal=0x00000000, wchar_t * lpCmdLine=0x00020a92) Line 1981 C++ Empire.UnityDebug.exe!wWinMain(HINSTANCE__ * hInstance=0x08440000, HINSTANCE__ * hPrevInstance=0x00000000, wchar_t * lpCmdLine=0x00020a92, int __formal=1) Line 4808 + 0x11 bytes C++ Empire.UnityDebug.exe!__tmainCRTStartup() Line 589 + 0x35 bytes C Empire.UnityDebug.exe!wWinMainCRTStartup() Line 414 C kernel32.dll!_BaseProcessStart@4() + 0x23 bytes The threads tab looks like this: 1008|wWinMainCRTStartup|CThreadSlotData::GetThreadValue|Normal|0 Occasionally, this also appears in the thread tab: 1596|_MixerCallbackThread@4|_KiFastSystemCallRet@0|Time Critical|0 but in general, only one thread is active.
I discovered that another member of my team had called TerminateThread rather than CloseHandle in a function a few instructions earlier. Fixing that fixed the problem. I shall look in to WINDBG though. Thread problems do crop up now that we're living in a multi-core world.
2,201,263
2,201,410
Pure base class needs to be exported from DLL?
I have two DLLs: a.dll and b.dll and in each one I have one class AClass and BClass. I would like to have both AClass and BClass inherit and implement the same interface AbsBase which is a pure abstract class. In each class I set up the #defines for __declspec(dllimport) and __declspect(dllexport). When I'm trying to compile I get this: warning C4275: non dll-interface class 'AClass' used as base for dll-interface class 'AbsBase' which basically wants me to declare AbsBase as __declspec(dllexport) But if the compiler would have it his way, I would have to declare AbsBase to be exported from both a.dll and b.dll. Why does the interface of a class needs to be exported? Is there any way around it? Should I really export AbsBase from both DLLs? isn't there something inherently wrong with this? (I would need to define a new XXX_EXPORT macro..)
It looks like its a compiler warning and not an error, so it should still work. The compiler is just letting you know that you are doing something that makes it easy for you to screw up. It should be perfectly acceptable to do this as long as both DLLs and the core program agree on the definition of the base class. You should be able to use a pragma to supress the warning: http://forums.devx.com/archive/index.php/t-84785.html
2,201,296
2,201,377
How to create a resizable window with rounded-corners in win32
I'm trying to create a Win32 window that has rounded corners and is resizable both horizontally and vertically. My first approach was to create BITMAP of a rounded rectangle and draw it to the screen in conjunction with setting the windows style to WS_EX_LAYERED and setting the transparency key to the outside color of the rounded rectangle. This works, but it only looks good if the window is a fixed size. If I allow the user the resize the window and stretch the bitmap along with it, the rounded corners look stretched out, too. Is there a way to create a window that has nice, smooth rounded corners and is resizable in windows? Eventually, I would also like to add a drop shadow to the window as well.
I would try to mix the Windows API functions CreateRoundRectRgn and SetWindowRgn. A very simple example can be found at pInvoke.net web site.
2,201,420
2,201,498
A good place to learn about image processing in c/c++?
any websites, books etc. If someone would like to share their own experiences. thank you
This is a free book which runs through some recurring tasks in computer vision and image processing. Regarding the C++, you can take a look at OpenCV which is a computer vision library written in c/c++
2,201,493
2,201,509
Using default in a switch statement when switching over an enum
What is your procedure when switching over an enum where every enumeration is covered by a case? Ideally you'd like the code to be future proof, how do you do that? Also, what if some idiot casts an arbitrary int to the enum type? Should this possibility even be considered? Or should we assume that such an egregious error would be caught in code review? enum Enum { Enum_One, Enum_Two }; Special make_special( Enum e ) { switch( e ) { case Enum_One: return Special( /*stuff one*/ ); case Enum_Two: return Special( /*stuff two*/ ); } } void do_enum( Enum e ) { switch( e ) { case Enum_One: do_one(); break; case Enum_Two: do_two(); break; } } leave off the default case, gcc will warn you (will visual studio?) add a default case with a assert(false); add a default case that throws a catchable exception add a default case that throws a non-catchable exception (it may just be policy to never catch it or always rethrow). something better I haven't considered I'm especially interested in why you choose to do it they way you do.
I throw an exception. As sure as eggs are eggs, someone will pass an integer with a bad value rather than an enum value into your switch, and it's best to fail noisily but give the program the possibility of fielding the error, which assert() does not.
2,201,918
2,202,244
conversion of multiple ascii characters in a char array to single int using their ascii values --- c/c++
anyone know a good way for doing this conversion? for example, take the char array holding ascii charcters "ABC", the int conversion i'm looking for would change those characters to a single int with value 656667. any help would be very much appreciated. edit really appreciate the replies. as someone noted i did say char array, and specifically this is a byte array, so there could be multiple '\0' or NULL elements followed by additional ascii's. using methods like strlen, etc will cause problems. thanks again for the current input.
Most of the time, one got to look at the actual problem. Parsing a packet protocol may or may not be easy, depending on the specification, but you can usually do better than throwing it all in a string... If you don't know about them, look up Google Protocol Buffer, they can't be used as is, but the idea is there. class UdpPacket { public: UdpPacket(const char str[], size_t length); uint16_t sourcePort() const { return mSourcePort; } unit16_t destinationPort() const { return mDestinationPort; } // ... The 3 other getters private: uint16_t mSourcePort; uint16_t mDestinationPort; uint16_t mLength; uint16_t mCheckSum; std::string mData; }; // class UdpPacket UdpPacket::UdpPacket(const char str[], size_t length): mSourcePort(0), mDestinationPort(0), mLength(0), mCheckSum(0), mData() { if (length < 8) throw IncompleteHeader(str, length); memcpy(mSourcePort, str, 2); memcpy(mDestinationPort, str, 2); memcpy(mLength, str, 2); memcpy(mCheckSum, str, 2); mData = std::string(str+8, length-8); } // UdpPacket::UdpPacket Net advantage ? You now have structured data. Of course there might be some endianness issue going on with the memcpy... you'll have to check for it. Now, I don't know what your mData is supposed to be, but of course it would be better if it was structured too. Using a simple int to store what does not look like an int at all, really is a bad idea I think... unless it was an int to begin with of course.
2,202,179
2,202,321
Problem using yaml-cpp on OS X
So I'm having trouble compiling my application which is using yaml-cpp I'm including "yaml.h" in my source files (just like the examples in the yaml-cpp wiki) but when I try compiling the application I get the following error: g++ -c -o entityresourcemanager.o entityresourcemanager.cpp entityresourcemanager.cpp:2:18: error: yaml.h: No such file or directory make: *** [entityresourcemanager.o] Error 1 my makefile looks like this: CC = g++ CFLAGS = -Wall APPNAME = game UNAME = uname OBJECTS := $(patsubst %.cpp,%.o,$(wildcard *.cpp)) mac: $(OBJECTS) $(CC) `pkg-config --cflags --libs sdl` `pkg-config --cflags --libs yaml-cpp` $(CFLAGS) -o $(APPNAME) $(OBJECTS) pkg-config --cflags --libs yaml-cpp returns: -I/usr/local/include/yaml-cpp -L/usr/local/lib -lyaml-cpp and yaml.h is indeed located in /usr/local/include/yaml-cpp Any idea what I could do? Thanks
Your default target is "mac" and you have rule how to build it. It depends on object files and you do not have any rules how to build those, so make is using its implicit rules. Those rules do just that: g++ -c -o entityresourcemanager.o entityresourcemanager.cpp As you can see there is no -I/usr/local/... part here. The easiest way to fix that is to change CPPFLAGS and LDFLAGS value globally: YAML_CFLAGS := $(shell pkg-config --cflags yaml-cpp) YAML_LDFLAGS := $(shell pkg-config --libs yaml-cpp) SDL_CFLAGS := $(shell pkg-config --cflags sdl) SDL_LDFLAGS := $(shell pkg-config --libs sdl) CPPFLAGS += $(YAML_CFLAGS) $(SDL_CFLAGS) LDFLAGS += $(YAML_LDFLAGS) $(SDL_LDFLAGS) mac: $(OBJECTS) $(CXX) -o $(APPNAME) $(OBJECTS) $(LDFLAGS) CPPFLAGS value is used by implicit rules that build object files from cpp files, so now compiler should find yaml headers. Edit: LDFLAGS probably should go after OBJECTS
2,202,262
2,205,988
Map from integer ranges to arbitrary single integers
Working in C++ in a Linux environment, I have a situation where a number of integer ranges are defined, and integer inputs map to different arbitrary integers based on which range they fall into. None of the ranges overlap, and they aren't always contiguous. The "simplest" way to solve this problem is with a bunch of if-statements for each range, but the number of ranges, their bounds, and the target values can all vary, so if-statements aren't maintainable. For example, the ranges might be [0, 70], called r_a, [101, 150], call it r_b, and [201, 400], call it r_c. Inputs in r_a map to 1, in r_b map to 2, and r_c map to 3. Anything not in r_a, r_b, r_c maps to 0. I can come up with a data structure & algorithm that stores tuples of (bounds, map target) and iterates through them, so finding the target value takes linear time in the number of bounds pairs. I can also imagine a scheme that keeps the pairs ordered and uses a binary sort-ish algorithm against all the lower bounds (or upper bounds), finds the closest to the input, then compares against the opposing bound. Is there a better way to accomplish the mapping than a binary-search based algorithm? Even better, is there some C++ library out that does this already?
I would use a very simple thing: a std::map. class Range { public: explicit Range(int item); // [item,item] Range(int low, int high); // [low,high] bool operator<(const Range& rhs) const { if (mLow < rhs.mLow) { assert(mHigh < rhs.mLow); // sanity check return true; } return false; } // operator< int low() const { return mLow; } int high() const { return mHigh; } private: int mLow; int mHigh; }; // class Range Then, let's have a map: typedef std::map<Range, int> ranges_type; And write a function that search in this map: int find(int item, const ranges_type& ranges) { ranges_type::const_iterator it = ranges.lower_bound(Range(item)); if (it != ranges.end() && it->first.low() <= item) return it->second; else return 0; // No mapping ? } Main benefits: Will check that the ranges effectively don't overlap during insertion in the set (you can make it so that it's only in debug mode) Supports edition of the Ranges on the fly Finding is fast (binary search) If the ranges are frozen (even if their values are not), you may wish to use Loki::AssocVector to reduce the memory overhead and improve performance a bit (basically, it's a sorted vector with the interface of a map).
2,202,322
2,202,384
Calling a custom type from a DLL written in C++ from c#
I'm using a DLL written in c++ in my C# project. I have been able to call functions within the DLL using this code: [DllImport("hidfuncs", EntryPoint = "vm_hid_scan", ExactSpelling = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr VmHidScan(); Now I need to call a function that requres a custom type pointer. The Docs for the DLL layout the function like this: hid_get_info(int n,PDEV_INFO *pdi) I don't know how to use this custom pointer. Is this defined in the DLL? If so how can use it from C# project? If not do I need to include the header file in c#? Thanks in advance for your help.
Given the "P" prefix, it looks like the real declaration is hid_get_info(int n, DEV_INFO **pdi) where DEV_INFO is a structure. You'll need to find the declaration of this structure and add it to your C# code with the [StructLayout] attribute. You'd then declare the function like this in your C# code: [DllImport("blah.dll")] private static extern something hid_get_info(int n, out IntPtr pdi); and use Marshal.PtrToStructure() to obtain the structure value. Hopefully you don't have to free the structure, you'd be screwed. A second interpretation is that "pid" returns an array of pointers to DEV_INFO structures. Somewhat likely given the "n" argument, which could well mean the number of elements in the array you pass to be filled by the function. In that case, pass an IntPtr[] and set "n" to its Length.
2,202,460
2,202,467
CreateObject equivalent in C/C++? (COM Interop)
What would the equivalent in C/C++?
It's the CoCreateInstance() function. It is convenient to use CoCreateInstance when you need to create only a single instance of an object on the local machine. If you are creating an instance on remote computer, call CoCreateInstanceEx. When you are creating multiple instances, it is more efficient to obtain a pointer to the class object's IClassFactory interface and use its methods as needed. In the latter case, you should use the CoGetClassObject function. You'll need to #include <Objbase.h> and you'll need to link to ole32.lib
2,202,512
2,203,022
how do i turn my program into something i can install?
how do i turn my VC++ 2008 program into something i can get to run on other computers. i have tryed using the .exe it makes in the debug but it will say that im missing some files and lists all of my .cpp file names and .h files(if i use it on other computers). i wanted something so i could encrypt my files because one of them is about encrypting passwords/other stuff so i can't have someone just open my files. also i would very much like someway to make them accept the terms and conditions so they can't sue me if they lose something, that would be very very nice. ^^ i only have Microsoft virtual c++ 2008 express edition that i got from their web site. o also if i make something on windows 7 will it run in xp or vista?
You generally can't and almost never should distribute debug builds to client machines. At least three reasons. Client machines will not have the debug versions of your dependant libraries, like the VC runtime (msvcrtd.dll), so they won't be able to run your app. When compiling in debug, your code will in many ways run unoptimized. For one thing, you don't let an optimizing compiler optimize when you compile in debug, so it will run slower and/or fatter. For another, there are debug version of things like operator new which allocate much more than you ask for, which is used in runtime integrity checking etc. So your program runs fatter & slower once more. When you compile in debug it is easier to reverse-engineer your code. UPDATE: And to answer your question if a Win7-compiled app will run on XP/Vista, the answer is 'yes' so long as you don't use any Win7 features.
2,202,534
2,202,658
How to generate pseudo random in cuda
I am attempting to build a particle system utilizing CUDA to do the heavy lifting. I want to randomize some of the particles' initial values like velocity and life span. The random numbers don't have to be super random since it's just for visual effect. I found this post that addresses the same subject: Random Number Generation in CUDA That suggests a linear congruential is the way to go. It seems like it should be simple to implement, but I am having trouble getting anything useful of my implementation. Can anyone provide some code that will run in the device? I am using CUDA with VC++ on Windows 7 64bit.
CUDA pseudo random number generators are included in the NVidia SDK eg C/src/MersenneTwister/ and C/src/quasirandomGenerator available as separate papers and source: 2.a Langdon's paper and Langdon's source code 2.b Mersenne Twister on GPU
2,202,585
2,202,792
Does using a C++ namespace increase coupling?
I understand that a C++ library should use a namespace to avoid name collisions, but since I already have to: #include the correct header (or forward declare the classes I intend to use) Use those classes by name Don't these two parameters infer the same information conveyed by a namespace. Using a namespace now introduces a third parameter - the fully qualified name. If the implementation of the library changes, there are now three potential things I need to change. Is this not, by definition an increase in coupling between the library code and my code? For example, look at Xerces-C: It defines a pure-virtual interface called Parser within the namespace XERCES_CPP_NAMESPACE. I can make use of the Parser interface in my code by including the appropriate header file and then either importing the namespace using namespace XERCES_CPP_NAMESPACE or prefacing declarations/definitions with XERCES_CPP_NAMESPACE::. As the code evolves, perhaps there is a need to drop Xerces in favour of a different parser. I'm partially "protected" from the change in the library implementation by the pure-virtual interface (even more so if I use a factory to construct my Parser), but as soon as I switch from Xerces to something else, I need to comb through my code and change all my using namespace XERCES_CPP_NAMESPACE and XERCES_CPP_NAMESPACE::Parser code. I ran into this recently when I refactored an existing C++ project to split-out some existing useful functionality into a library: foo.h class Useful; // Forward Declaration class Foo { public: Foo(const Useful& u); ...snip... } foo.cpp #include "foo.h" #include "useful.h" // Useful Library Foo::Foo(const Useful& u) { ... snip ... } Largely out of ignorance (and partially out of laziness) at the time, the all of the functionality of useful.lib was placed in the global namespace. As the contents of useful.lib grew (and more clients started to use the functionality), it was decided to move all the code from useful.lib into its own namespace called "useful". The client .cpp files were easy to fix, just add a using namespace useful; foo.cpp #include "foo.h" #include "useful.h" // Useful Library using namespace useful; Foo::Foo(const Useful& u) { ... snip ... } But the .h files were really labour intensive. Instead of polluting the global namespace by putting using namespace useful; in the header files, I wrapped the existing forward declarations in the namespace: foo.h namespace useful { class Useful; // Forward Declaration } class Foo { public: Foo(const useful::Useful& u); ...snip... } There were dozens (and dozens) of files and this ended up being a major pain! It should not have been that difficult. Clearly I did something wrong with either the design and/or implementation. Although I know that library code should be in its own namespace, would it have been advantageous for the library code to remain in the global namespace, and instead try to manage the #includes?
It sounds to me like your problem is due primarily to how you're (ab)using namespaces, not due to the namespaces themselves. It sounds like you're throwing a lot of minimally related "stuff" into one namespace, mostly (when you get down to it) because they happen to have been developed by the same person. At least IMO, a namespace should reflect logical organization of the code, not just the accident that a bunch of utilities happened to be written by the same person. A namespace name should usually be fairly long and descriptive to prevent any more than the most remote possibility of a collision. For example, I usually include my name, date written, and a short description of the functionality of the namespace. Most client code doesn't need to (and often shouldn't) use the real name of the namespace directly. Instead, it should define a namespace alias, and only the alias name should be used in most code. Putting points two and three together, we can end up with code something like this: #include "jdate.h" namespace dt = Jerry_Coffin_Julian_Date_Dec_21_1999; int main() { dt::Date date; std::cout << "Please enter a date: " << std::flush; std::cin>>date; dt::Julian jdate(date); std::cout << date << " is " << jdate << " days after " << dt::Julian::base_date() << std::endl; return 0; } This removes (or at least drastically reduces) coupling between the client code and a particular implementation of the date/time classes. For example, if I wanted to re-implement the same date/time classes, I could put them in a different namespace, and switch between one and the other just by changing the alias and re-compiling. In fact, I've used this at times as a kind of compile-time polymorphism mechanism. For one example, I've written a couple versions of a small "display" class, one that displays output in a Windows list-box, and another that displays output via iostreams. The code then uses an alias something like: #ifdef WINDOWED namespace display = Windowed_Display #else namespace display = Console_Display #endif The rest of the code just uses display::whatever, so as long as both namespaces implement the entire interface, I can use either one, without changing the rest of the code at all, and without any runtime overhead from using a pointer/reference to a base class with virtual functions for the implementations.
2,202,731
2,202,906
Is there support in C++/STL for sorting objects by attribute?
I wonder if there is support in STL for this: Say I have an class like this : class Person { public: int getAge() const; double getIncome() const; .. .. }; and a vector: vector<Person*> people; I would like to sort the vector of people by their age: I know I can do it the following way: class AgeCmp { public: bool operator() ( const Person* p1, const Person* p2 ) const { return p1->getAge() < p2->getAge(); } }; sort( people.begin(), people.end(), AgeCmp() ); Is there a less verbose way to do this? It seems overkill to have to define a whole class just because I want to sort based on an 'attribute'. Something like this maybe? sort( people.begin(), people.end(), cmpfn<Person,Person::getAge>() );
Generic adaptor to compare based on member attributes. While it is quite more verbose the first time it is reusable. // Generic member less than template <typename T, typename M, typename C> struct member_lt_type { typedef M T::* member_ptr; member_lt_type( member_ptr p, C c ) : ptr(p), cmp(c) {} bool operator()( T const & lhs, T const & rhs ) const { return cmp( lhs.*ptr, rhs.*ptr ); } member_ptr ptr; C cmp; }; // dereference adaptor template <typename T, typename C> struct dereferrer { dereferrer( C cmp ) : cmp(cmp) {} bool operator()( T * lhs, T * rhs ) const { return cmp( *lhs, *rhs ); } C cmp; }; // syntactic sugar template <typename T, typename M> member_lt_type<T,M, std::less<M> > member_lt( M T::*ptr ) { return member_lt_type<T,M, std::less<M> >(ptr, std::less<M>() ); } template <typename T, typename M, typename C> member_lt_type<T,M,C> member_lt( M T::*ptr, C cmp ) { return member_lt_type<T,M,C>( ptr, cmp ); } template <typename T, typename C> dereferrer<T,C> deref( C cmp ) { return dereferrer<T,C>( cmp ); } // usage: struct test { int x; } int main() { std::vector<test> v; std::sort( v.begin(), v.end(), member_lt( &test::x ) ); std::sort( v.begin(), v.end(), member_lt( &test::x, std::greater<int>() ) ); std::vector<test*> vp; std::sort( v.begin(), v.end(), deref<test>( member_lt( &test::x ) ) ); }
2,203,093
2,203,124
Should C# or C++ be chosen for learning Games Programming (consoles)?
I've basic game programming knowledge in c and c++. I'm learning c# nowadays. If I want to make a career in console games programming, which one I should use to proceed? I've noticed that a lot of game companies are using C++/C (probably because of legacy reasons). Also probably C++ enjoys more number of supported libraries? In which languages modern game engines(unreal/crysis etc) are written in? Which language is a better bet? and why?
C++, for two reasons. 1) a lot of games are programmed in C++. No mainstream game is, as yet, programmed in a managed language. 2) C++ is as hard as it gets. You have to master manual memory management and generally no bounds checking (beyond the excellent Valgrind!). If you master C++, you will find this transferable to managed procedural languages. Less so the other way around. C++ has a level of complexity close to APL! You'll never get better by playing weaker opponents. Joel makes a very strong point about this. People who understand how the machine works make better programmers, because all abstractions are leaky.
2,203,159
2,203,694
Is there a C++ equivalent to getcwd?
I see C's getcwd via: man 3 cwd I suspect C++ has a similar one, that could return me a std::string . If so, what is it called, and where can I find it's documentation? Thanks!
Ok, I'm answering even though you already have accepted an answer. An even better way than to wrap the getcwd call would be to use boost::filesystem, where you get a path object from the current_path() function. The Boost filesystem library allows you to do lots of other useful stuff that you would otherwise need to do a lot of string parsing to do, like checking if files/directories exist, get parent path, make paths complete etcetera. Check it out, it is portable as well - which a lot of the string parsing code one would otherwise use likely won't be. Update (2016): Filesystem has been published as a technical specification in 2015, based on Boost Filesystem v3. This means that it may be available with your compiler already (for instance Visual Studio 2015). To me it also seems likely that it will become part of a future C++ standard (I would assume C++17, but I am not aware of the current status). Update (2017): The filesystem library has been merged with ISO C++ in C++17, for std::filesystem::current_path();
2,203,257
2,203,277
Effect on performance when using objects in c++
I have a dynamic programming algorithm for Knapsack in C++. When it was implemented as a function and accessing variables passed into it, it was taking 22 seconds to run on a particular instance. When I made it the member function of my class KnapsackInstance and had it use variables that were data members of that class, it started taking 37 seconds to run. As far as I know, only accessing member functions goes through the vtable so I'm at a loss to explain what might be happening. Here's the code of the function int KnapsackInstance::dpSolve() { int i; // Current item number int d; // Current weight int * tbl; // Array of size weightLeft int toret; tbl = new int[weightLeft+1]; if (!tbl) return -1; memset(tbl, 0, (weightLeft+1)*sizeof(int)); for (i = 1; i <= numItems; ++i) { for (d = weightLeft; d >= 0; --d) { if (profitsWeights.at(i-1).second <= d) { /* Either add this item or don't */ int v1 = profitsWeights.at(i-1).first + tbl[d-profitsWeights.at(i-1).second]; int v2 = tbl[d]; tbl[d] = (v1 < v2 ? v2 : v1); } } } toret = tbl[weightLeft]; delete[] tbl; return toret; } tbl is one column of the DP table. We start from the first column and go on until the last column. The profitsWeights variable is a vector of pairs, the first element of which is the profit and the second the weight. toret is the value to return. Here is the code of the original function :- int dpSolve(vector<pair<int, int> > profitsWeights, int weightLeft, int numItems) { int i; // Current item number int d; // Current weight int * tbl; // Array of size weightLeft int toret; tbl = new int[weightLeft+1]; if (!tbl) return -1; memset(tbl, 0, (weightLeft+1)*sizeof(int)); for (i = 1; i <= numItems; ++i) { for (d = weightLeft; d >= 0; --d) { if (profitsWeights.at(i-1).second <= d) { /* Either add this item or don't */ int v1 = profitsWeights.at(i-1).first + tbl[d-profitsWeights.at(i-1).second]; int v2 = tbl[d]; tbl[d] = (v1 < v2 ? v2 : v1); } } } toret = tbl[weightLeft]; delete[] tbl; return toret; } This was run on Debian Lenny with g++-4.3.2 and -O3 -DNDEBUG turned on Thanks
In a typical implementation, a member function receives a pointer to the instance data as a hidden parameter (this). As such, access to member data is normally via a pointer, which may account for the slow-down you're seeing. On the other hand, it's hard to do more than guess with only one version of the code to look at. After looking at both pieces of code, I think I'd write the member function more like this: int KnapsackInstance::dpSolve() { std::vector<int> tbl(weightLeft+1, 0); std::vector<pair<int, int> > weights(profitWeights); int v1; for (int i = 0; i <numItems; ++i) for (int d = weightLeft; d >= 0; --d) if ((weights[i+1].second <= d) && ((v1 = weights[i].first + tbl[d-weights[i-1].second])>tbl[d])) tbl[d] = v1; return tbl[weightLeft]; }
2,203,388
2,206,549
Templates polymorphism
I have this structure of classes. class Interface { // ... }; class Foo : public Interface { // ... }; template <class T> class Container { // ... }; And I have this constructor of some other class Bar. Bar(const Container<Interface> & bar){ // ... } When I call the constructor this way I get a "no matching function" error. Container<Foo> container (); Bar * temp = new Bar(container); What is wrong? Are templates not polymorphic?
I think the exact terminology for what you need is "template covariance", meaning that if B inherits from A, then somehow T<B> inherits from T<A>. This is not the case in C++, nor it is with Java and C# generics*. There is a good reason to avoid template covariance: this will simply remove all type safety in the template class. Let me explain with the following example: //Assume the following class hierarchy class Fruit {...}; class Apple : public Fruit {...}; class Orange : public Fruit {...}; //Now I will use these types to instantiate a class template, namely std::vector int main() { std::vector<Apple> apple_vec; apple_vec.push_back(Apple()); //no problem here //If templates were covariant, the following would be legal std::vector<Fruit> & fruit_vec = apple_vec; //push_back would expect a Fruit, so I could pass it an Orange fruit_vec.push_back(Orange()); //Oh no! I just added an orange in my apple basket! } Consequently, you should consider T<A> and T<B> as completely unrelated types, regardless of the relation between A and B. So how could you solve the issue you're facing? In Java and C#, you could use respectively bounded wildcards and constraints: //Java code Bar(Container<? extends Interface) {...} //C# code Bar<T>(Container<T> container) where T : Interface {...} The next C++ Standard (known as C++1x (formerly C++0x)) initially contained an even more powerful mechanism named Concepts, that would have let developers enforce syntaxic and/or semantic requirements on template parameters, but was unfortunately postponed to a later date. However, Boost has a Concept Check library that may interest you. Nevertheless, concepts might be a little overkill for the problem you encounter, an using a simple static assert as proposed by @gf is probably the best solution. * Update: Since .Net Framework 4, it is possible to mark generic parameters has being covariant or contravariant.
2,203,592
2,203,609
How can I link an .o file using g++
I am trying to use g++ to compile a .cc file, and I need it to link a .o file. So I tried: $g++ -o client -I../ipc -L../messages.o client.cc /usr/bin/ld: error: ../messages.o: can not read directory: Not a directory And I have tried: $g++ -o client -I../ipc -l../messages.o client.cc /usr/bin/ld: error: cannot find -l../messages.pb.o $$ ls -l ../messages.o -rw-r--r-- 1 hap497 hap497 227936 2010-02-03 22:32 ../messages.o Can you please tell me how to link in a .o file? Thank you.
$g++ -o client -I../ipc client.cc ../messages.o
2,203,695
2,203,720
What is the address of back() in an empty container?
I mistakenly took the address of the reference returned by the back() operator in an empty container and was surprised to see that the address wasn't zero. If a container e.g. std::deque is empty, what does back() return?
it returns the last element. on this page: http://www.sgi.com/tech/stl/BackInsertionSequence.html precondition: !a.empty() Equivalent to *(--a.end()). since the precondition is the deque is not empty, then it means it's undefined behavior.
2,203,831
8,869,865
hiphop PHP download?
Where can you download the HipHop Code? I would really like to test it. Interestingly enough if you go here: http://github.com/facebook/hiphop-php/wikis It must not exist or private because it redirects to github.com index.php page So you can not even see the wiki or anything
git clone git://github.com/facebook/hiphop-php.git
2,203,946
2,206,667
error while loading shared libraries
I'm trying to install Code::Blocks from source. There is an `anarchy' folder on my university's CS department's mainframe, where anyone can install anything, basically. wxwidgets is a dependency of Code::Blocks, and I'm trying to put wxGTK, as it's called, into my own folder on `anarchy', which works fine. I then compile Code::Blocks with the correct configure flags so that it recognizes wxwidgets 2.8 during the installation. But then, when I want to run `codeblocks', it says codeblocks: error while loading shared libraries: libwx_gtk2u-2.8.so.0 Obviously I don't have su access as I am only a student at the university. Is there a way to resolve this without su privileges? They are Debian 5.0 systems, I believe, with all dependencies but wxwidgets, so I had to build that on my own.
This is how I solved this: First I ran the configure script like this: $ ./configure --prefix=/pub/anarchy/<myname>/codeblocks --with-wx-config=/pub/anarchy/<myname>/wxGTK/bin/wx-config then: $ export LDFLAGS="-Wl,-R /pub/anarchy/<myname>/wxGTK/lib" $ make $ make install Now codeblocks finds libwx_gtk2u-2.8.so.0. An alternative solution (untested) according to comments would be: $ ./configure LDFLAGS="-Wl,-R /path/to/wxGTK/lib" # other configure flags omitted $ make $ make install
2,204,176
2,204,380
How to initialise memory with new operator in C++?
I'm just beginning to get into C++ and I want to pick up some good habits. If I have just allocated an array of type int with the new operator, how can I initialise them all to 0 without looping through them all myself? Should I just use memset? Is there a “C++” way to do it?
It's a surprisingly little-known feature of C++ (as evidenced by the fact that no-one has given this as an answer yet), but it actually has special syntax for value-initializing an array: new int[10](); Note that you must use the empty parentheses — you cannot, for example, use (0) or anything else (which is why this is only useful for value initialization). This is explicitly permitted by ISO C++03 5.3.4[expr.new]/15, which says: A new-expression that creates an object of type T initializes that object as follows: ... If the new-initializer is of the form (), the item is value-initialized (8.5); and does not restrict the types for which this is allowed, whereas the (expression-list) form is explicitly restricted by further rules in the same section such that it does not allow array types.
2,204,608
2,204,628
Does C++ call destructors for global and class static variables?
From my example program, it looks like it does call the destructors in both the cases. At what point does it call the destructors for global and class-static variables since they should be allocated in the data section of the program stack?
From § 3.6.3 of the C++03 standard: Destructors (12.4) for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling exit (18.3). These objects are destroyed in the reverse order of the completion of their constructor or of the completion of their dynamic initialization. If an object is initialized statically, the object is destroyed in the same order as if the object was dynamically initialized. For an object of array or class type, all subobjects of that object are destroyed before any local object with static storage duration initialized during the construction of the sub- objects is destroyed. Furthermore, § 9.4.2 7 states: Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3). However, if a destructor has no observable behavior, it may not be invoked. Terry Mahaffey details this in his answer to "Is a C++ destructor guaranteed not to be called until the end of the block?" .
2,204,941
2,213,245
How to determine whether an LSA session is active in Windows XP
I'm trying to get the list of users currently logged into a machine. On Windows 7, I can call LsaEnumerateLogonSessions, then WTSQuerySessionInformation with WTSConnectState. But on XP, each LSA session has 0 for the TS Session field (unless it's a Remote Desktop session), which always has WTSConnectState of WTSActive, and I end up listing all of the people who have logged out of the machine already. WTSQuerySessionInformation fails when the session is a Remote Desktop session.
I believe this codeproject article uses a workaround that might be what you are after, it enumerates all running processes, checking the AuthenticationId (TokenStatistics on the process token) against the list of LUID's LsaEnumerateLogonSessions gives you. This allows you to filter out stale LUID's
2,205,044
2,205,087
How to hardcode a value in a texbox in c++
I am using the below code to popup the authentication dialog. I want to hard-code the password in my code and make it a read-only text box. What should I do? IDD_LOGIN_AUTH_DIALOG DIALOG DISCARDABLE 0, 0, 148, 82 STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Authentication" FONT 8, "MS Shell Dlg" BEGIN LTEXT "Host:",IDC_STATIC_HOST,7,8,36,10,SS_CENTERIMAGE | NOT WS_GROUP EDITTEXT IDC_VNCHOST,46,7,95,12,ES_AUTOHSCROLL | ES_READONLY | NOT WS_TABSTOP CONTROL 108,IDC_STATIC_LOGO,"Static",SS_BITMAP,7,23,32,30 RTEXT "User name:",IDC_STATIC_LOGIN,41,25,39,10,SS_CENTERIMAGE EDITTEXT IDC_LOGIN_EDIT,84,24,57,12,ES_AUTOHSCROLL RTEXT "Password:",IDC_STATIC_PASSWD,41,42,39,10,SS_CENTERIMAGE EDITTEXT IDC_PASSWD_EDIT,84,41,57,12,ES_PASSWORD | ES_READONLY | NOT WS_TABSTOP DEFPUSHBUTTON "&OK",IDOK,20,61,50,14 PUSHBUTTON "&Cancel",IDCANCEL,77,61,50,14 END
You get full control over all fields if you use the CONTROL keyword rather than the EDITTEXT keyword, use CONTROL "mypassword", IDC_PASSWD_EDIT, "Edit", ES_LEFT | WS_BORDER | ES_PASSWORD | ES_READONLY, 84,41,57,12 instead of EDITTEXT IDC_PASSWD_EDIT,84,41,57,12,ES_PASSWORD | ES_READONLY | NOT WS_TABSTOP
2,205,152
2,205,238
automatically skipping/ignoring external code in gdb
Possible Duplicate: How to avoid entering library's source files while debugging in Qt Creator with gdb? anybody know how to tell gdb to only enter code that is in your project? I know it's hard for a debugger to know what is "in the project" and what is a library....but I thought some naive checks could help, eg don't look in any files that aren't in the users home directory. I frequently have code like this: MyFunction(complexVarable, complexvar); //passed by value and gdb insists on going through the copy constructors of the two passed values, but all I care about is MyFunction. Any tips? There are two parts to the question, ignore code that isn't mine (not in home dir) skip copies for function calls. thanks. EDIT: btw I use emacs, maybe there are some tools there I missed, but I'm open to using external gdb frontends.
As per my opinion this cannot be done. every project has a flow of data from one function to other. gdb is designed to work on the flow of data. so if your project is somewhere in the middle of the flow,gdb cant help you,since evry function has some purpose to do with the input it gets and output it gives. all you can do is create the same function separately and replicate the scenario as if its running in teh flow by giving the inputs it needs and output it gives.
2,205,211
2,205,219
Rounding with static_cast<int>?
I feel really silly asking this because I know how to do it 101 ways, but not the way it is defined in the book. (note, I know C++) So far, we have only gone over the very basics of C++. So basically, we know variables, assignment, and basic casting. In the book I am having trouble with this portion of the problem: prompt the user to input a decimal number Convert that number to the nearest integer and print it to the screen So I have the trivial code: double n; cout<<"Number: "; cin >> n; cout <<endl<<static_cast<int>(n)<<endl; But I realized this does not work for me. It will always truncate the decimal so that 1.9 -> 1 rather than the expected 1.9 -> 2 How do I fix this using only what I "know"? (as in, without round() or if statements and such) Is this a standards compliance problem? At school I thought I had something similar working with Visual C++ 2005 on Windows XP 32 bit, but now I'm at my home trying to do the same thing and it's not working. My home compiler is gcc 3.3.5 on OpenBSD 64bit. Or could this be a typo in the book?
static_cast<int>(n+0.5) Or static_cast<int>(n >= 0 ? n + 0.5 : n - 0.5) for more proper behavior on negative n.
2,205,239
2,206,241
Any useful suggestions to figure out where memory is being free'd in a Win32 process?
An application I am working with is exhibiting the following behaviour: During a particular high-memory operation, the memory usage of the process under Task Manager (Mem Usage stat) reaches a peak of approximately 2.5GB (Note: A registry key has been set to allow this, as usually there is a maximum of 2GB for a process under 32-bit Windows) After the operation is complete, the process size slowly starts decreasing at a rate of 1MB per second. I am trying to figure out the easiest way to quickly determine who is freeing this memory, and where it is being free'd. I am having trouble attaching a memory profiler to my code, and I don't particularly want to override the new/delete operators to track the allocations/deallocations (IOW, I want to do this without re-compiling my code). Can anyone offer any useful suggestions of how I could do this via the Visual Studio debugger? Update I should also mention that it's a multi-threaded application, so pausing the application and analysing the call stack through the debugger is not the most desirable option. I considered freezing different threads one at a time to see if the memory stops reducing, but I'm fairly certain this will cause the application to crash.
Ahh! You're looking at the wrong counter! Mem Usage doesn't tell you that memory is being freed. Only that the working set is being purged! This could mean some other application needs memory, or the VMM decided to mark some of your process's pages as Stand By for some other process to quickly use. It does not mean that VirtualFree, HeapFree or any other free function is being called. Look at the commit size (VM Size, Private Bytes, etc). But if you still want to know when memory is being decommitted or freed or what-have-you, then break on some free calls. E.g. (for Visual C++) {,,kernel32.dll}HeapFree or {,,msvcr80.dll}free etc. Or just a regular function breakpoint on the above. Just make sure it resolves the address. cdb/WinDbg let you do it via bp kernel32!HeapFree bp msvcrt!free etc. Names may vary depending on which CRT version you use and how you link against it (via /MT or /MD and its variants)
2,205,353
2,205,394
Why doesn't this reinterpret_cast compile?
I understand that reinterpret_cast is dangerous, I'm just doing this to test it. I have the following code: int x = 0; double y = reinterpret_cast<double>(x); When I try to compile the program, it gives me an error saying invalid cast from type 'float' to type 'double What's going on? I thought reinterpret_cast was the rogue cast that you could use to convert apples to submarines, why won't this simple cast compile?
Perhaps a better way of thinking of reinterpret_cast is the rouge operator that can "convert" pointers to apples as pointers to submarines. By assigning y to the value returned by the cast you're not really casting the value x, you're converting it. That is, y doesn't point to x and pretend that it points to a float. Conversion constructs a new value of type float and assigns it the value from x. There are several ways to do this conversion in C++, among them: int main() { int x = 42; float f = static_cast<float>(x); float f2 = (float)x; float f3 = float(x); float f4 = x; return 0; } The only real difference being the last one (an implicit conversion) will generate a compiler diagnostic on higher warning levels. But they all do functionally the same thing -- and in many case actually the same thing, as in the same machine code. Now if you really do want to pretend that x is a float, then you really do want to cast x, by doing this: #include <iostream> using namespace std; int main() { int x = 42; float* pf = reinterpret_cast<float*>(&x); (*pf)++; cout << *pf; return 0; } You can see how dangerous this is. In fact, the output when I run this on my machine is 1, which is decidedly not 42+1.
2,205,404
2,205,505
How to flush file buffers when using boost::serialization?
I'm saving a file on an USB drive and need to make sure that it's completely written to avoid corruption in case the USB drive is not removed properly. Well I've done some research and it seems this is possible via calling the FlushFileBuffers Win32 function. But the problem is, I'm saving using boost::serialization and thus don't have access to the actual file HANDLE. I wonder what is the proper way to flush the file? Thanks!
Call ostream::flush on the output stream you created your archive object with: // create and open a character archive for output std::ofstream ofs("filename"); boost::archive::text_oarchive oa(ofs); ... ofs.flush(); You could also just let the objects go out of scope which should flush everything: { // create and open a character archive for output std::ofstream ofs("filename"); boost::archive::text_oarchive oa(ofs); // going out of scope flushes the data } Note, you still need to properly unmount your USB device. Flushing the data just makes sure it gets from userland into the kernel, but the kernel can also do it's own buffering.
2,205,583
2,206,392
Iterate through struct variables
I want to get an iterator to struct variable to set a particular one on runtime according to enum ID. for example - struct { char _char; int _int; char* pchar; }; enum { _CHAR, //0 _INT, //1 PCHAR //2 }; int main() { int i = 1; //_INT //if i = 1 then set variable _int of struct to some value. } can you do that without if/else or switch case statements?
No, C++ doesn't support this directly. You can however do something very similar using boost::tuple: enum { CHAR, //0 INT, //1 DBL //2 }; tuple<char, int, double> t('b', 1, 3.14); int i = get<INT>(t); // or t.get<INT>() You might also want to take a look at boost::variant.
2,205,587
2,205,631
How to call unmanaged c++ function that allocates output buffer to return data in c#?
I have problems with marshalling output parameter of c++ function returning array of data to c#. Here is C++ declaration: #define DLL_API __declspec(dllexport) typedef TPARAMETER_DATA { char *parameter; int size; } PARAMETER_DATA; int DLL_API GetParameters(PARAMETER_DATA *outputData); The function allocates memory for char array, places the data there and returns the number of allocated bytes in "size" field. Here is my c# declaration: [StructLayout(LayoutKind.Sequential)] public struct PARAMETER_DATA { [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I1, SizeConst = 50000)] public byte[] data; // tried also SizeParamIndex = 1 instead of SizeConst [MarshalAs(UnmanagedType.I4)] public int size; } [DllImport("thedll.dll", SetLastError = true, ExactSpelling = true)] public extern static uint GetParameters(ref PARAMETER_DATA outputData); // tried also 'out' parameter When calling the function in c# I get empty structure (size=0, empty array). I tried passing outputData parameter with data feld initialized to new byte[50000] but no data is returned anyway. Every other function in this dll (some with complex input structures) are working fine, but this is the only function that allocates memory to return data. I tried many other C# marshalling declarations (with LPArray, LPString) with no luck - always empty data structure is returned or memory access exception is thrown. Am I missing something simple here? EDIT: I cannot change the c++ code - it's external library.
The problem you're facing is that a pointer is returned - not really a string or an array. There is no way for the marshaller to convert the pointer to an array or string, because the length is unknown. The solution might be to do the pointer handling in c#. You should also figure out if you're responsible for freeing the pointer, or that the library will do that for you. [StructLayout(LayoutKind.Sequential)] public struct PARAMETER_DATA { public IntPtr data; // tried also SizeParamIndex = 1 instead of SizeConst [MarshalAs(UnmanagedType.I4)] public int size; } [DllImport("thedll.dll", SetLastError = true, ExactSpelling = true)] private extern static uint GetParameters(ref PARAMETER_DATA outputData); public static uint GetParameters(out String result) { PARAMETER_DATA outputData = new PARAMETER_DATA(); result= Marshal.PtrToStringAnsi(outputData.data, outputData.size ); Marshal.FreeHGlobal(outputData.data); // not sure about this }
2,205,603
2,205,796
Conditional dependency with make/gmake
Is there a way to direct make/gmake to act upon conditional dependencies? I have this rule in place: $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(CPPC) -c $(FLAGS_DEV) $< -o $@ In the general case, every .cpp file has a corresponding .h file; however there are a few exceptions. Is there a way to achieve "depend on this if it exists" with gmake? Failing that, is there a best practice for this type of setup? Thanks in advance; Cheers! Update: I'm using GCC
A better way to do this, is to actually determine the dependencies of the cpp files with gcc -MM and include them in the makefile. SRCS = main.cpp other.cpp DEPS = $(SRCS:%.cpp=$(DEP_DIR)/%.P) $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(CPPC) -c $(FLAGS_DEV) $< -o $@ $(DEP_DIR)/%.P: $(SRC_DIR)/%.cpp $(CPPC) -MM $(FLAGS_DEV) -MT $(OBJ_DIR)/$*.o -MP -MF $@ $< -include $(DEPS)
2,206,050
2,206,082
How to convert a string literal to unsigned char array in visual c++
How to convert a string to Unsigned char in c++... I have, unsigned char m_Test[8]; I want to assign a string "Hello world" to m_Test. how to do it?
Firstly, the array has to be at least big enough to hold the string: unsigned char m_Test[20]; then you use strcpy. You need to cast the first parameter to avoid a warning: strcpy( (char*) m_Test, "Hello World" ); Or if you want to be a C++ purist: strcpy( static_cast <char*>( m_Test ), "Hello World" ); If you want to initialise the string rather than assign it, you could also say: unsigned char m_Test[20] = "Hello World";
2,206,165
2,271,200
Language codes in platform SDK 6.1
Language codes are in the form "en-US","de-DE" or "sl-SI" for English US, German and slovakian respectively. Whether there is any #define s present in PLATFORM SDK 6.1 for language codes. Its better if i got these values instead of using Hard coded strings in my program. Can anyone help me regarding this. Its better if i get the header file name to include. Thanks Santhosh
There are no # defines present for language codes. We can use the function LocaleNameToLCID() to get the language ID for given language code. Thanks all for help!!
2,206,366
2,206,408
Conditional operator in member-initialization list
Suppose I have this class: class foo { public: foo() { } foo(const std::string& s) : _s(s) { } private: std::string _s; }; Which is a member of another class: class bar { public: bar(bool condition) : _f(condition ? "go to string constructor" : **go to empty ctor**) { } private: foo _f; }; When initializing _f in bar's member initialization list I would like to choose which constructor of foo to invoke based on condition. What can I put instead of go to empty ctor to make this work? I thought of putting foo(), is there another way?
The result of a conditional operator is always a fixed type determined at compile time by finding a common type that both options can be converted to. (The exact rules are a little involved, but in common use it usually 'does the right thing'.) In your example the simplest thing to do is to let that type be a temporary foo and then use the copy constructor to intialize _f in bar. You can do this as follows. _f( condition ? foo("string") : foo() )
2,206,729
2,206,760
Returning reference to class with overloaded private & operator?
I got a class called Property (from external library == cannot be modified) that has private overloaded & operator. I use this class in another class as a property and (for sanity reasons) I'd like to return a reference to this property through the Get method. However I got the 'cannot access private member declared in class' error I cannot handle. Is there a way to walk around it - without making the Property public public. // Some external class. class Property { Property* operator&() const; }; class MyClass { protected: Property m_Property; public: // error C2248: 'Property::operator &' : cannot access private member declared in class 'Property' const Property& GetProperty() const { return *& this->m_Property; } };
I may be missing something, but why not simply say: const Property& GetProperty() const { return this->m_Property; } The fact that the operator& is private pretty clearly indicates that you are not supposed to call it.
2,206,742
2,206,863
Pass a variable number of arguments to an aliased function
Take a function like printf that accepts a variable number of arguments what I would like to do is pass these variable number of functions to a sub function without changing their order. An example of this would be aliasing the printf function to a function called console ... #include <stdio.h> void console(const char *_sFormat, ...); int main () { console("Hello World!"); return 0; } void console(const char *_sFormat, ...) { printf("[APP] %s\n", _sFormat); } If I did for example console("Hello %s", sName), I would want the name to be passed to the printf function also, but it has to be able to continue to accept a varable number of arguments like the printf already does.
Here's what you want: #include <stdio.h> #include <stdarg.h> void console(const char *_sFormat, ...); int main () { console("Hello World!"); return 0; } void console(const char *_sFormat, ...) { va_list ap; va_start(ap, _sFormat); printf("[APP] "); vprintf(_sFormat, ap); printf("\n"); va_end(ap); }
2,206,782
2,206,840
Should i override operators new/delete in my c++ WIn32 applications
I know Microsoft themselves used to recommend overriding operator new with calls to HeapCreate() and HeapAlloc(), but that was a while ago. See KB139638 for more details. Would i still benefit from overriding new/delete on Win32? What would be the recommended implementation? TIA.
The article says you can do it, not that you should. The code in it is so badly written it isn't funny, and it is not thread safe. In general, the implementation supplied new and delete will work well for all general programming needs. You should only consider re-implementing them if you have identified a specific problem that such a re-implementation would solve.
2,206,844
2,207,153
Should I use "this" to call class properties, members, or methods?
I've seen some guides or blogs that say using this to access a class's own members is bad. However, I've also seen some places where professionals are accessing with this. I tend to prefer explicitly using this, since it seems to make it clear that the thing I'm accessing is part of the class. this.MyProperty = this.GetSomeValue(); Is there some advantage or disadvantage to using this? Is it simply a stylistic preference?
Having gone from using this for years, to finding not many people (atleast in my experience) use it, I eventually changed. The benefits I can see of having this-less code: I use underscores: _myVar for private variables, which don't need a this as they're always member variables. For method calls it is very obvious that it's part of the class. You would prepend the type name if it wasn't. (C#) Private variables and parameters are always camel case. If your class is so big it's getting confusing you've got an issue with cohesion and separation of concerns anyway. (C#) Visual Studio color codes types, so you know if you're using a property or type: e.g. someclass.Method(1); SomeClass.StaticMethod(1); I can see that if you don't use the underscores naming convention, and have a large method with a weighty body it could lead to some confusion. Static methods or properties can occasionally confuse things, but very rarely. You will obviously always need the this keyword when passing references, for example: someclass.Method(this); var someclass = new SomeClass(this); (I write C#, but my answer relates to Java)
2,207,006
2,207,257
Modular Exponentiation for high numbers in C++
So I've been working recently on an implementation of the Miller-Rabin primality test. I am limiting it to a scope of all 32-bit numbers, because this is a just-for-fun project that I am doing to familiarize myself with c++, and I don't want to have to work with anything 64-bits for awhile. An added bonus is that the algorithm is deterministic for all 32-bit numbers, so I can significantly increase efficiency because I know exactly what witnesses to test for. So for low numbers, the algorithm works exceptionally well. However, part of the process relies upon modular exponentiation, that is (num ^ pow) % mod. so, for example, 3 ^ 2 % 5 = 9 % 5 = 4 here is the code I have been using for this modular exponentiation: unsigned mod_pow(unsigned num, unsigned pow, unsigned mod) { unsigned test; for(test = 1; pow; pow >>= 1) { if (pow & 1) test = (test * num) % mod; num = (num * num) % mod; } return test; } As you might have already guessed, problems arise when the arguments are all exceptionally large numbers. For example, if I want to test the number 673109 for primality, I will at one point have to find: (2 ^ 168277) % 673109 now 2 ^ 168277 is an exceptionally large number, and somewhere in the process it overflows test, which results in an incorrect evaluation. on the reverse side, arguments such as 4000111222 ^ 3 % 1608 also evaluate incorrectly, for much the same reason. Does anyone have suggestions for modular exponentiation in a way that can prevent this overflow and/or manipulate it to produce the correct result? (the way I see it, overflow is just another form of modulo, that is num % (UINT_MAX+1))
Exponentiation by squaring still "works" for modulo exponentiation. Your problem isn't that 2 ^ 168277 is an exceptionally large number, it's that one of your intermediate results is a fairly large number (bigger than 2^32), because 673109 is bigger than 2^16. So I think the following will do. It's possible I've missed a detail, but the basic idea works, and this is how "real" crypto code might do large mod-exponentiation (although not with 32 and 64 bit numbers, rather with bignums that never have to get bigger than 2 * log (modulus)): Start with exponentiation by squaring, as you have. Perform the actual squaring in a 64-bit unsigned integer. Reduce modulo 673109 at each step to get back within the 32-bit range, as you do. Obviously that's a bit awkward if your C++ implementation doesn't have a 64 bit integer, although you can always fake one. There's an example on slide 22 here: http://www.cs.princeton.edu/courses/archive/spr05/cos126/lectures/22.pdf, although it uses very small numbers (less than 2^16), so it may not illustrate anything you don't already know. Your other example, 4000111222 ^ 3 % 1608 would work in your current code if you just reduce 4000111222 modulo 1608 before you start. 1608 is small enough that you can safely multiply any two mod-1608 numbers in a 32 bit int.
2,207,053
2,207,188
What are app domains used for?
I understand roughly what an AppDomain is, however I don't fully understand the uses for an AppDomain. I'm involved in a large server based C# / C++ application and I'm wondering how using AppDomains could improve stability / security / performance. In particular: I understand that a fault or fatal exception in one domain does not affect other app domains running in the same process - Does this also hold true for unmanaged / C++ exceptions, possibly even heap corruption or other memory issues. How does inter-AppDomain communication work? How is using AppDomains different from simply spawning many processes?
The basic use case for an AppDomain is in an environment that is hosting 3rd party code, so it will be necessary not just to load assemblies dynamically but also unload them. There is no way to unload an assembly individually. So you have to create a separate AppDomain to house anything that might need to be unloaded. You can then trash and rebuild the whole AppDomain when necessary. By the way, native code corrupting the heap cannot be protected against by any feature of the CLR. Ultimately the CLR is implemented natively and shares the same address space. So native code in the process can scribble all over the internals of the CLR! The only way to isolate badly behaved (i.e. most) native code is actual process isolation at the OS level. Launch mutiple .exe processes and have them communicate via some IPC mechanism.
2,207,159
2,209,496
Alternative to Factory Pattern when creating templated objects - C++
I want to implement a Mesh class for a CG project, but have run into some problems. What I want to do is a Mesh class that hides implementation details (like loading to a specific API: OpenGL, DirectX, CUDA, ...) from the user. Additionally, since the Mesh class will be used in research projects, this Mesh class has to be very flexible. class Channel { virtual loadToAPI() = 0; } template <class T> class TypedChannel : public Channel { std::vector<T> data; }; template <class T> class OpenGLChannel : public TypedChannel<T> { loadToAPI(); // implementation }; class Mesh { template<class T> virtual TypedChannel<T>* createChannel() = 0; // error: no virtual template functions std::vector<Channel*> channels; }; class OpenGLMesh { template<class T> TypedChannel<T>* createChannel() { TypedChannel<T>* newChannel = new OpenGLChannel<T>; channels.push_back(newChannel); return newChannel; }; }; For flexibility, each Mesh is really a collection of channels, like one position channel, a normal channel, etc. that describe some aspects of the mesh. A channel is a wrapper around a std::vector with some added functionality. To hide implementation details, there is a derived class for each API (OpenGLMesh, DirectXMesh, CUDAMesh, ...) that handles API-specific code. The same goes for the Channels (OpenGLChannel, etc. that handle loading of the Channel data to the API). The Mesh acts as a factory for the Channel objects. But here is the problem: Since the Channels are template classes, createChannel must be a template method, and template methods cannot be virtual. What I would need is something like a Factory Pattern for creating templated objects. Does anyone have advice on how something similar could be accomplished? Thanks
It's an interesting problem, but let's discuss the compiler error first. As the compiler said, a function cannot be both virtual and template. To understand why, just think about the implementation: most of the times, objects with virtual functions have a virtual table, which stores a pointer to each function. For templates however, there are as many functions as combinations of type: so what should be the virtual table like ? It's impossible to tell at compilation time, and the memory layout of your class includes the virtual table and has to be decided at compilation time. Now on to your problem. The simplest solution would be to just write one virtual method per type, of course it can soon become tedious, so let's pretend you haven't heard that. If Mesh is not supposed to know about the various types, then surely you don't need the function to be virtual, because who would know, given an instance of Mesh, with which type invoking the function ? Mesh* mesh = ...; mesh.createChannel<int>(); // has it been defined for that `Mesh` ?? On the other hand, I will suppose that OpenGLMesh does know exactly which kind of TypedChannel it will need. If so, we could use a very simple trick. struct ChannelFactory { virtual ~ChannelFactory() {} virtual Channel* createChannel() = 0; }; template <class T> struct TypedChannelFactory: ChannelFactory { }; And then: class Mesh { public: template <class T> Channel* addChannel() { factories_type::const_iterator it = mFactories.find(typeid(T).name()); assert(it != mFactories.end() && "Ooops!!!" && typeid(T).name()); Channel* channel = it->second->createChannel(); mChannels.push_back(channel); return channel; } // addChannel protected: template <class T> void registerChannelFactory(TypedChannelFactory<T>* factory) { mFactories.insert(std::make_pair(typeid(T).name(), factory)); } // registerChannelFactory private: typedef std::map < const char*, ChannelFactory* const > factories_type; factories_type mFactories; std::vector<Channel*> mChannels; }; // class Mesh It demonstrates a quite powerful idiom known as type erasure. You probably used it even before you knew the name :) Now, you can define OpenGLMesh as: template <class T> struct OpenGLChannelFactory: TypedChannelFactory<T> { virtual Channel* createChannel() { return new OpenGLChannel<T>(); } }; OpenGLMesh::OpenGLMesh() { this->registerChannelFactory(new OpenGLChannelFactory<int>()); this->registerChannelFactory(new OpenGLChannelFactory<float>()); } And you'll use it like: OpenGLMesh openGLMesh; Mesh& mesh = openGLMesh; mesh.addChannel<int>(); // fine mesh.addChannel<float>(); // fine mesh.addChannel<char>(); // ERROR: fire the assert... (or throw, or do nothing...) Hope I understood what you needed :p
2,207,219
2,207,398
How do I define friends in global namespace within another C++ namespace?
I'd like to define a binary operator on in the global namespace. The operator works on a class that is defined in another namespace and the operator should get access to the private members of that class. The problem I have is that I don't know how to scope that global operator when making it a friend in the class definition. I tried something like: namespace NAME { class A { public: friend A ::operator * (double lhs, const A& rhs); private: int private_var; }; } A operator * (double lhs, const A& rhs) { double x = rhs.private_var; ... } The compiler (g++ 4.4) didn't know what to do with it. It seems that the line friend A ::operator * () is evaluated as something like (pseudo-code) (A::operator) instead of (A) (::operator) If I leave out the :: in the declaration of the operator the compiling works but the operator is then in namespace NAME and not in the global namespace. How can I qualify the global namespace in such a situation?
First, note that your operator declaration was lacking a namespace qualification for A: NAME::A operator * (double lhs, const NAME::A& rhs) and then the decisive trick is to add parentheses to the friend declaration like this, just as you proposed in your "pseudo-code" friend A (::operator *) (double lhs, const A& rhs); To make it all compile, you then need some forward declarations, arriving at this: namespace NAME { class A; } NAME::A operator * (double lhs, const NAME::A& rhs); namespace NAME { class A { public: friend A (::operator *) (double lhs, const A& rhs); private: int private_var; }; } NAME::A operator * (double lhs, const NAME::A& rhs) { double x = rhs.private_var; } Alexander is right, though -- you should probably declare the operator in the same namespace as its parameters.
2,207,309
11,960,349
Odd optimisation problem under MSVC
I've seen this blog: http://igoro.com/archive/gallery-of-processor-cache-effects/ The "weirdness" in part 7 is what caught my interest. My first thought was "Thats just C# being weird". Its not I wrote the following C++ code. volatile int* p = (volatile int*)_aligned_malloc( sizeof( int ) * 8, 64 ); memset( (void*)p, 0, sizeof( int ) * 8 ); double dStart = t.GetTime(); for (int i = 0; i < 200000000; i++) { //p[0]++;p[1]++;p[2]++;p[3]++; // Option 1 //p[0]++;p[2]++;p[4]++;p[6]++; // Option 2 p[0]++;p[2]++; // Option 3 } double dTime = t.GetTime() - dStart; The timing I get on my 2.4 Ghz Core 2 Quad go as follows: Option 1 = ~8 cycles per loop. Option 2 = ~4 cycles per loop. Option 3 = ~6 cycles per loop. Now This is confusing. My reasoning behind the difference comes down to the cache write latency (3 cycles) on my chip and an assumption that the cache has a 128-bit write port (This is pure guess work on my part). On that basis in Option 1: It will increment p[0] (1 cycle) then increment p[2] (1 cycle) then it has to wait 1 cycle (for cache) then p[1] (1 cycle) then wait 1 cycle (for cache) then p[3] (1 cycle). Finally 2 cycles for increment and jump (Though its usually implemented as decrement and jump). This gives a total of 8 cycles. In Option 2: It can increment p[0] and p[4] in one cycle then increment p[2] and p[6] in another cycle. Then 2 cycles for subtract and jump. No waits needed on cache. Total 4 cycles. In option 3: It can increment p[0] then has to wait 2 cycles then increment p[2] then subtract and jump. The problem is if you set case 3 to increment p[0] and p[4] it STILL takes 6 cycles (which kinda blows my 128-bit read/write port out of the water). So ... can anyone tell me what the hell is going on here? Why DOES case 3 take longer? Also I'd love to know what I've got wrong in my thinking above, as i obviously have something wrong! Any ideas would be much appreciated! :) It'd also be interesting to see how GCC or any other compiler copes with it as well! Edit: Jerry Coffin's idea gave me some thoughts. I've done some more tests (on a different machine so forgive the change in timings) with and without nops and with different counts of nops case 2 - 0.46 00401ABD jne (401AB0h) 0 nops - 0.68 00401AB7 jne (401AB0h) 1 nop - 0.61 00401AB8 jne (401AB0h) 2 nops - 0.636 00401AB9 jne (401AB0h) 3 nops - 0.632 00401ABA jne (401AB0h) 4 nops - 0.66 00401ABB jne (401AB0h) 5 nops - 0.52 00401ABC jne (401AB0h) 6 nops - 0.46 00401ABD jne (401AB0h) 7 nops - 0.46 00401ABE jne (401AB0h) 8 nops - 0.46 00401ABF jne (401AB0h) 9 nops - 0.55 00401AC0 jne (401AB0h) I've included the jump statetements so you can see that the source and destination are in one cache line. You can also see that we start to get a difference when we are 13 bytes or more apart. Until we hit 16 ... then it all goes wrong. So Jerry isn't right (though his suggestion DOES help a bit), however something IS going on. I'm more and more intrigued to try and figure out what it is now. It does appear to be more some sort of memory alignment oddity rather than some sort of instruction throughput oddity. Anyone want to explain this for an inquisitive mind? :D Edit 3: Interjay has a point on the unrolling that blows the previous edit out of the water. With an unrolled loop the performance does not improve. You need to add a nop in to make the gap between jump source and destination the same as for my good nop count above. Performance still sucks. Its interesting that I need 6 nops to improve performance though. I wonder how many nops the processor can issue per cycle? If its 3 then that account for the cache write latency ... But, if thats it, why is the latency occurring? Curiouser and curiouser ...
Well I had a brief chat with an intel engineer about exactly this problem and got this response: It's clearly something to do with which instructions end up in which execution units, how quickly the machine spots a store-hit-load problem, and how quickly and elegantly it deals with unrolling the speculative execution to cope with it (or if it takes multiple cycles because of some internal conflict). But that said - you'd need a very detailed pipetrace and simulator to figure this out. Predicting out-of-order instruction processing in these pipelines is way too hard to do on paper, even for the people who designed the machines. For laymen - no hope in hell. Sorry! Ao I thought I'd add the answer here and close this question once and for all :)
2,207,527
2,207,552
Changing a label in Qt
I'm trying to make a simple program consisting of a button and a label. When the button is pressed, it should change the label text to whatever is in a QString variable inside the program. Here's my code so far: This is my widget.h file: class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); private: Ui::WidgetClass *ui; QString test; private slots: void myclicked(); }; And here's the implementation of the Widget class: #include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::WidgetClass) { ui->setupUi(this); test = "hello world"; connect(ui->pushButton, SIGNAL(clicked()), ui->label, SLOT(myclicked())); } Widget::~Widget() { delete ui; } void Widget::myclicked(){ ui->label->setText(test); } It runs but when the button is clicked, nothing happens. What am I doing wrong? Edit: after i got it working, the text in the label was larger than the label itself, so the text got clipped. I fixed it by adding ui->label->adjustSize() to the definition of myclicked().
You are connecting the signal to the wrong object. myclicked() is not a slot of QLabel, it is a slot of your Widget class. The connection string should be: connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(myclicked())); Take a look at the console output of your program. There should be an error message saying something like: Error connecting clicked() to myclicked(): No such slot defined in QLabel
2,207,628
2,207,640
Calling in C++ a non member function inside a class with a method with the same
I have this class with an instance method named open and need to call a function declared in C also called open. Follows a sample: void SerialPort::open() { if(_open) return; fd = open (_portName.c_str(), O_RDWR | O_NOCTTY ); _open = true; } When I try to compile it (using GCC) I get the following error: error: no matching function for call to 'SerialPort::open(const char*, int)' I included all the required C headers. When I change the name of the method for example open2 I don't have not problems compiling. How can I solve this problem. Thanks in advance.
Call fd = ::open(_portName.c_str(), O_RDWR | O_NOCTTY ); The double colon (::) before the function name is C++'s scope resolution operator: If the resolution operator is placed in front of the variable name then the global variable is affected.
2,207,852
2,209,397
QtWebkit synchronous loading
I'm using a QWebPage without a QWebView because I want to render the contents of an HTML file onto a QPixmap/QImage. I want the loading of the page to be done synchronously, not asynchronously which is the default. The default way is to call QWebFrame::setHtml() or QWebFrame::setContent(), but this loads images asynchronously. What I want is some sort of blocking function call, something like QWebFrame::waitUntilLoadFinished() after which I could just call render() and be done with it. I can't find a way to do this. Am I missing something?
If anyone's interested, I implemented this using a special "PageRasterizer" class. The class creates a QWebPage in the constructor and sets a bool loading flag to false. A connect() call connects the loadFinished signal to a member slot that merely sets the loading flag to true. A special RenderPage() member function that returns an image does all the work: it accepts the HTML string and calls setHtml(). After that comes a while loop that waits on the flag; while the flag is false, qApp->processEvents() is called so signals get emitted and the flag setting slot is eventually called. When it is, the loop breaks and now you can render the page to a QImage (don't forget to set the flag back to false before returning). If you're interested in the rendering process, look at this Qt example (the Thumbnailer::render() function). For bonus points, you can make this class a functor.
2,207,881
2,211,255
Using a java socket from JNI / C++ code
I have a java app that creates a socket to talk to a server process, eg new java.net.Socket(String host, int port). This app includes a bunch of legacy c++ code that needs to suck gobs of data from that server and process it. This is currently implemented by having the native code create its own socket and connect to the server, eg: sock = socket(AF_INET, SOCK_STREAM, 0); struct hostent* hp = gethostbyname(host); if (!hp) { unsigned long addr = inet_addr(host); hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET); } struct sockaddr_in name; name.sin_family = AF_INET; memcpy(&name.sin_addr, hp->h_addr, hp->h_length); name.sin_port = htons(port); connect(sock, (sockaddr*)&name, sizeof(name)); On Windows vista/7 machines with multiple NICs (eg wired and wifi or vpn connections), these two sockets can end up with different local addresses. The java code appears to choose a "better" interface (the wired Gb enet = higher MTU?), the native (naive?) code gets the "default" interface (stick in a usb wifi device and it becomes your default - yuck). This causes some problems for me, I don't think the details are relevant. Two questions: Is is possible for me to re-use the java socket from the JNI code (portably? assume Sun JDK). This would avoid the issue completely, but so far I don't see any way to interact with the java.net.Socket stuff from JNI/native code. Since the answer to the first question is probably NO, how is java creating that socket (choosing the interface) ? Code snippets welcomed. I have looked around in the openjdk stuff and haven't found what I am looking for. Thanks, Chris
To answer your first question: if it's possible to reuse Java's socket from within the native code -- yes it is possible, but I would not recommend it (you would tie yourself to the internals of a specific implementation/version); but if you really must: use reflection to get access to java.io.FileDescriptor on the java.net.SocketImpl then use sun.misc. JavaIOFileDescriptorAccess's get method to get the native socket descriptor. Checkout DualStackPlainSocketImpl.java) To answer your second question: what's Java's algorithm to find the default interface on windows -- checkout getDefaultIPv6Interface method in net_util_md.c (don't let the v6 fool you -- i believe it's used for v4 as well). I would advise that you open and use the socket either from the C (JNI) code or from the Java code, preferably the later, as you'll find that cleanup and error handling is best handled in the code that manages the socket. The idea of opening the socket in Java and passing byte buffers from C (JNI) is perfectly sane, and you should not find any problems with the heap on reasonable buffer sizes and proper deallocation in the JNI code. Think Java application servers that handle huge amounts of data without a hitch.
2,208,047
2,208,093
MS Visual Studio Project header files
I am fairly new to developing C/C++ code in MSVS but one of the things that has already confused me is why, after adding a set of source and header files to my project such that they show up respectively under the MSVS folders 'Source Files' and 'Header Files', do I subsequently have to tell the compiler where my header files are under 'Project->properties->C/C++->General'. It seems to me that MSVS should already attempt to resolve any 'include "..."' statements by first looking thru the set of header files I have included in the project. Anybody care to comment on the logic being used here? Thanks, Travis
Actually, adding your header files in the so called "Header Files" folder is optional. Even without doing the same you can just specify the header path in "Project->Properties->...." and it will still work. You may be thinking from the perspective of only your project's header files which can be added in the "Header Files" folder, what about a big project having several third party libraries, you definitely cannot go and keep adding each every header file into your folder. So, to keep all the includes unified at one configuration, this way should have been selected. All the stuff quoted above is just my understanding. I don't have any evidence to support this. So, My apologies in advance is this is wrong. Don't bombard me with Downvotes please. : )
2,208,202
2,208,234
C++: Is there a way to define a static array inline?
I would like to define a simple template function which takes a runtime value and determines if it is a member of some set of possible values. Usage: int x; // <- pretend this came from elsewhere... if (isoneof(x, {5,3,9,25}) ... Something like: template <typename T, size_t size> bool isoneof(T value, T (&arr)[size]) { for (size_t i = 0; i < size; ++i) if (value == arr[i]) return true; return false; } I assume that this is doomed to failure, as I don't see how one can create a static array inline. I can use: int kPossibilities[] = {5,3,9,25}; if (isoneodf(6, kPossibilities)) ... With a minor change to isoneof: template <typename T1, typename T2, size_t size> bool isoneof(T1 value, const T2 (&arr)[size]) { for (size_t i = 0; i < size; ++i) if (value == arr[i]) return true; return false; } Which also makes it a tad more flexible. Does anyone have an improvement to offer? A better way to define a "set of static values inline"?
If you like such things, then you will be a very happy user of Boost.Assign. Boost.Assign actually proves that such semantics are possible, however one look at the source of assign will convince you that you don't want to do that by yourself :) You will be able to create something like this however: if (isoneof(x, list_of(2)(3)(5)(7)(11)) { ... ... the downside being you'd have to use boost::array as the parameter instead of a built-in array (thanks, Manuel) -- however, that's a nice moment to actually start using them :>
2,208,246
2,208,279
Using readv(), writev() and poll() from C++
There is a multiplayer card game which I had first programmed as a non-forking socket server in C (using poll() call). Then it was too difficult for me to add new features and I've switched to Perl (using IO::Poll module). As Perl doesn't support readv()/writev(), requires more memory/CPU and also isn't very commercial (I'd like to sell my game later), I would like to port my server back to C++ in future - once my features stabilize. (C++ this time because there are few objects in my server). Could anyone please supply me with an example, how to use readv(), writev() and poll() or select() under C++? I know how to use those under Perl and C, but I haven't found any examples for C++ yet. My environment: I'm using OpenBSD with its gcc/g++ and I'd like my server to run under Linux as well. I'd prefer not to use any unusual libraries (like libevent?) unless they work under Windows too - because maybe in the future I want to port my server to Windows too (for that I think I'll have to switch back from poll() to select() and add few Winsock functions?). Please let me add that I like both Perl and C and I respect C++ very much, so this question is not about which language or OS is better. My question is: how to use poll() with C++ Thank you! Alex
The functions readv(), writev(), and poll() work the same way in C++ as they do in C.
2,208,293
2,208,313
What is the most efficient way to append one std::vector to the end of another?
Let v1 be the target vector, v2 needs to be appended to the back of it. I'm now doing: v1.reserve(v1.size() + v2.size()); copy(v2.begin(), v2.end(), back_inserter(v1)); Is this the most efficient way? Or can it maybe be done just via copying a chunk of memory? Thanks!
After a lot of arguing (and a reasonable comment from Matthieu M. and villintehaspam), I'll change my suggestion to v1.insert( v1.end(), v2.begin(), v2.end() ); I'll keep the former suggestion here: v1.reserve( v1.size() + v2.size() ); v1.insert( v1.end(), v2.begin(), v2.end() ); There are some reasons to do it the latter way, although none of them enough strong: there is no guarantee on to what size will the vector be reallocated -- e.g. if the sum size is 1025, it may get reallocated to 2048 -- dependant on implementation. There is no such guarantee for reserve either, but for a specific implementation it might be true. If hunting for a bottleneck it might be rasonable to check that. reserve states our intentions clear -- optimization may be more efficient in this case (reserve could prepare the cache in some top-notch implementation). also, with reserve we have a C++ Standard guarantee that there will be only a single reallocation, while insert might be implemented inefficiently and do several reallocations (also something to test with a particular implementation).
2,208,411
2,208,418
easy way to randomize the entries of an array using stl?
I can sort a int* array using stl, plain and simple like std::sort(myarray, myarray + size); Is there any equal simple way to randomize it? thanks
std::random_shuffle(myarray, myarray + size);
2,208,529
2,208,602
"Read-Only Region" Visual Studio 2008 options
Extends In Tools/Options/Environment/Fonts and Colors, If you choose to "Show settings for" Text Editor and look in the Display items dialog it says there' a "Read-Only" region you can set the font for. I'm not sure what's that for? Where do you encounter the read-only regions this dialog wants to set the font for?
According to the help file: Read-Only Region: Code that cannot be edited. For example code displayed in the Code Definition View window or code that cannot be modified during Edit and Continue.
2,208,581
2,208,622
Socket listen doesn't unbind in C++ under linux
I have a socket that listens on some port. I send the SIGSTOP signal to the thread that waits on the port (using accept) and terminate it. then I close the fd of the socket that I waited on. But for the next run of my project it doe's not allow me to listen on that port again. My program is in C++ under linux. What should I do? Some parts of my code are: Thread 1: void* accepter(void *portNo) { int newsockfd; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("ERROR opening socket"); } struct sockaddr_in server; bzero((char *) & server, sizeof (server)); server.sin_family = AF_INET; server.sin_port = htons(*(int*) portNo); server.sin_addr.s_addr = INADDR_ANY; if (bind(sockfd, (struct sockaddr *) & server, sizeof (struct sockaddr_in)) < 0) { perror("ERROR on binding"); } listen(sockfd, 50); while (true) { struct sockaddr_in client; socklen_t clientLen = sizeof (struct sockaddr_in); newsockfd = accept(sockfd, (struct sockaddr *) & client, &clientLen); if (accepterFlag) { break; } if (getpeername(newsockfd, (sockaddr *) & client, &clientLen) == -1) { perror("getpeername() failed"); } sem_wait(setSem); FD_SET(newsockfd, &set); if (maxFd < newsockfd) { maxFd = newsockfd; } sem_post(setSem); } Thread 2: listenerFlag = true; accepterFlag = true; sleep(1); pthread_kill(listenerThread, SIGSTOP); pthread_kill(accepterThread, SIGSTOP); close(sockfd); sem_wait(setSem); for (int i = 1; i <= maxFd; i++) { if (FD_ISSET(i, &set)) { close(i); } } sem_post(setSem); Thank you.
Did you know that sockets are typically kept in a kind of limbo for a minute or two after you've finished listening on them to prevent communications intended for the previous process coming to yours? It's called the 'TIME_WAIT' state. If you want to override that behaviour use setsockopt to set the SO_REUSEADDR flag against the socket before listening on it.
2,208,834
2,225,010
Multiple definition of lots of std:: functions when linking
I am trying to integrate some external code into my application. My code was pure C, but the new code is C++, so I simply renamed my C files to .cc and compiled the whole thing with g++. It compiles fine, but I get a crapton of link errors : CMakeFiles/svrt.dir/svrtH_generator.cc.o: In function `operator new(unsigned long, void*)': svrtH_generator.cc:(.text+0x0): multiple definition of `operator new(unsigned long, void*)' CMakeFiles/svrt.dir/svrt_generator.cc.o:svrt_generator.cc:(.text+0x0): first defined here CMakeFiles/svrt.dir/svrtH_generator.cc.o: In function `operator new[](unsigned long, void*)': svrtH_generator.cc:(.text+0x10): multiple definition of `operator new[](unsigned long, void*)' CMakeFiles/svrt.dir/svrt_generator.cc.o:svrt_generator.cc:(.text+0x10): first defined here CMakeFiles/svrt.dir/svrtH_generator.cc.o: In function `operator delete(void*, void*)': svrtH_generator.cc:(.text+0x20): multiple definition of `operator delete(void*, void*)' CMakeFiles/svrt.dir/svrt_generator.cc.o:svrt_generator.cc:(.text+0x20): first defined here CMakeFiles/svrt.dir/svrtH_generator.cc.o: In function `operator delete[](void*, void*)': svrtH_generator.cc:(.text+0x30): multiple definition of `operator delete[](void*, void*)' CMakeFiles/svrt.dir/svrt_generator.cc.o:svrt_generator.cc:(.text+0x30): first defined here [you got the idea...] svrtH_generator.cc:(.text+0x1060): multiple definition of `std::fixed(std::ios_base&)' CMakeFiles/svrt.dir/svrt_generator.cc.o:svrt_generator.cc:(.text+0xe80): first defined here collect2: ld returned 1 exit status make[3]: *** [dev/svrt/libsvrt.so] Error 1 make[2]: *** [dev/svrt/CMakeFiles/svrt.dir/all] Error 2 make[1]: *** [dev/svrt/CMakeFiles/svrt.dir/rule] Error 2 make: *** [svrt] Error 2 I'm using Cmake to build the thing, but nothing really complicated. I don't know why I get all these errors, as my code is just a bunch of methods (I don't use anything from the std package) and the code I try to integrate is not much more complicated. Note that the warning comes from linking my own code, and not (yet) from the new C++ code. Anybody ? EDIT: after digging in the external code I try to integrate, I found some includes : #include <iostream> #include <cmath> #include <fstream> #include <cfloat> #include <stdlib.h> #include <string.h> Also, iostream is included in other headers, too, and all of them have include guards. UPDATE: I managed to clean a bit the external code and remove the unnecessary dependencies. I still have some linker errors, but much less : CMakeFiles/svrt.dir/svrtH_generator.cc.o: In function `std::abs(long)': svrtH_generator.cc:(.text+0x0): multiple definition of `std::abs(long)' CMakeFiles/svrt.dir/svrt_generator.cc.o:svrt_generator.cc:(.text+0x0): first defined here CMakeFiles/svrt.dir/svrtH_generator.cc.o: In function `__gnu_cxx::abs(long long)': svrtH_generator.cc:(.text+0x20): multiple definition of `__gnu_cxx::abs(long long)' CMakeFiles/svrt.dir/svrt_generator.cc.o:svrt_generator.cc:(.text+0x20): first defined here CMakeFiles/svrt.dir/svrtH_generator.cc.o: In function `__gnu_cxx::div(long long, long long)': svrtH_generator.cc:(.text+0x40): multiple definition of `__gnu_cxx::div(long long, long long)' CMakeFiles/svrt.dir/svrt_generator.cc.o:svrt_generator.cc:(.text+0x40): first defined here CMakeFiles/svrt.dir/svrtH_generator.cc.o: In function `std::div(long, long)': svrtH_generator.cc:(.text+0x350): multiple definition of `std::div(long, long)' CMakeFiles/svrt.dir/svrt_generator.cc.o:svrt_generator.cc:(.text+0x150): first defined here The code includes both cmath and cstdlib, and refers to abs and other functions using a default namespace. May this be the problem ?
Finally, I was able to make things compile. I found some hints saying that I should get rid of C-style includes (#include <stdlib.h>) and replace them with C++ style includes (#include <cstdlib>). This made things worse ! Putting the includes back to .h style (and correcting the inconsistencies about that in the exernal code) made the linker happy. That, and removing all unused code and includes from the xternal code, solved my problem. Thanks for your help guys !
2,209,134
2,214,057
getting started with log4cpp in windows
I need to do logging in a C++ application. After googling for a while, I decided to use log4cpp. is that a safe option to go with, or is there something better out there? How do I get started with installation and importing it to my application using Windows XP, Visual Studio 2005? TIA
I've used Log4cpp in the past and it does the job, though bear in mind the project has been inactive since 2007. There are also the following alternatives: Apache's log4cxx which is still active. Matthew Wilson's Pantheios library. Log4cplus. As for getting started, does the documentation not cover this?
2,209,135
2,209,148
Safely prompt for yes/no with cin
I'm in an intro to C++ class and I was wondering of a better method of checking if input was the desired type. Is this a good way of doing this? I come from a PHP/PERL background which makes me rather apprehensive of using while loops. char type; while (true) { cout << "Were you admitted? [y/n]" << endl; cin >> type; if ((type == 'y') || (type == 'n')) { break; } } Is this a safe way of doing this or am I opening myself up to a world of hurt, which I suspect? What would be a better way of making sure I get the input I want before continuing?
Personally I'd go with: do { cout << "Were you admitted? [y/n]" << endl; cin >> type; } while( !cin.fail() && type!='y' && type!='n' );
2,209,224
2,209,233
vector vs. list in STL
I noticed in Effective STL that vector is the type of sequence that should be used by default. What's does it mean? It seems that ignore the efficiency vector can do anything. Could anybody offer me a scenario where vector is not a feasible option but list must be used?
Situations where you want to insert a lot of items into anywhere but the end of a sequence repeatedly. Check out the complexity guarantees for each different type of container: What are the complexity guarantees of the standard containers?
2,209,257
2,209,269
What's the alternate character combination for the double quote character in C/C++?
I've not had the Kernighan and Ritchie C reference in years, but I remember that there was a page in there that talked about how to enter characters that were unavailable to you. (WAY back in the day, some keyboards lacked characters like ", ~, etc.) To be clear, let me give an example. I'm not looking for a way to get quotes in strings, but rather, I want to replace this: printf("foo"); with this: printf([alternate sequence]foo[alternate sequence]); For the curious, I have an automated process that involves generating C/C++ code, but the (closed source) commercial tool involved strips quotes in its data streams and the documentation is quite clear on the fact that they do not provide a way to escape them. EDIT: Wow, I hadn't expected such a heavy response. This might merit a little more detail on my process. I'm doing automated build systems, which means that I live with certain restrictions when it comes to changing the code I'm compiling. For now, we have to live with the assumption that I have to get a string, spaces and all, into a preprocessor definiton. I already went down the 'PreprocessorDefinition' road. This left me with my usual fallback: Define the string in the operating environment and have the project file set the definition from there: Preprocessor Definitions WIN32;_DEBUG;THINGIE=$(THINGIE) The hope was that I could get around MSVC's stripping of quotes in anything handed to the build with /D using a trigraph, by doing something like this in my build automation script: ENV['THINGIE'] = "??''Yodeling Monkey Nuggets??''" run_msbuild_command I guess it's time for a plan C.
You are looking for a trigraph for " character? I don't think one exists. Trigraphs don't exist for all characters. Only a few characters have trigraph sequences.
2,209,355
2,209,433
Is using Java the proper language/platform for developing a GUI based accounting app?
I know this is partially subjective, but hopefully with enough specifics I can get a good answer. I am looking to develop an accounting app targeted at a specific market segment (think Quickbooks, but tweaked). Most of the app will be editable tables that are linked with DB data and some basic reporting and graphic functionality. It must be cross-platform (OS X and Windows). It will interface with a local DB. (SQLite or Derby or whatever) Speed is not a "huge" issue. It needs to be reasonably responsive (I'm not familiar with Java speed in comparison to C/C++). I narrowed it down really to between C++ with QT and Java. I only know a very little amount of Java, but work with C++ regularly. However, Java so far appears to the best overall solution and the amount of books/documentation is enormous which is a plus. How easy is the integration with Java GUI's and a DB? Does NetBeans make this process easy or should I use Eclipse instead? I'm looking for an experience similar to C# with Visual Studio. Is the whole "Big Decimal" rounding issue in Java a major issue or is it easy to work around? (sorry if I sound uneducated on the topic, but I really am not familiar with Java) Is there any real showstopper with Java that I may not be thinking of here or any real strong reason I should use C++ with QT over it? If I eventually wanted to port some or all of it to the web, does Java on the desktop make it easier for porting later?
First thing I should say is "there is no right answer here". Java can do exactly what you want. The GUI toolkit, after years of reworking, is very advanced. There are also lots of tools, frameworks, and extensions you can use to make the GUI look very advanced. Java also has a great DB connection framework. With Object Relational Mapping (ORM) tools (Hibernate and others) it is pretty easy to get data out of a DB, put it in Objects, manipulate it, and put it back in the database. The ORM tools also make it easy to connect data objects directly to the GUI, and use the rules in those objects to protect the data from corruption. The cross-platform support will help you a lot. The only big sticking point is having a Java runtime on the machine for the files. There are ways around that (the best being have an installer put it there).
2,209,490
2,209,612
Win32API: How to request embedded windows event notifications out to a parent window
Scenario: I would like a window control which is a sub-window in my dialog (a subwindow of a subwindow) to propagate its notification messages out to the dialog window. e.g. A COMBOBOX contains an EDIT control. I have a circumstance where I would really like to know when the EDIT field gains and loses focus (mainly because the stupid COMBOBOX doesn't claim focus or give me notifications if it happens to its embedded EDIT). But I can see how this could be a general issue: a Control issues a message to its parent WM_NOTIFY... which the direct parent doesn't care about, but maybe its parent does. Is there a generic way to ask a windows window to propagate notification messages from its subwindows? e.g. if dialog D has a control C which has a sub-control C', then is there a way to ensure that D receives WM_NOTIFY messages from C'?
I believe you need to subclass the window, see http://msdn.microsoft.com/en-us/library/ms997565.aspx (Content has been removed!) .
2,209,571
2,209,599
Assignment to unions of members
Let's say I have a class with union members in it: class ClassX { public: union { StructA * A; StructB * B; }; } If I have pointers x1 and x2 to different ClassX objects, does this: x1->A = x2->A; Have the same effect as this: x1->B = x2->B; ? Thanks.
For most practical purposes, on most implementations, those two statements would have the same effect, however it's not guaranteed. If the member that you read from a union isn't the last member that was writted to the union the behaviour of the program is undefined. Because both members of the union are pointers to structs it is very likely that they occupy the same size and have analogous representations so assigning either union member is likely to correctly assign the other union member if that's what was actually stored in the source union.
2,209,603
2,209,831
Strange C++ performance difference?
I just stumbled upon a change that seems to have counterintuitive performance ramifications. Can anyone provide a possible explanation for this behavior? Original code: for (int i = 0; i < ct; ++i) { // do some stuff... int iFreq = getFreq(i); double dFreq = iFreq; if (iFreq != 0) { // do some stuff with iFreq... // do some calculations with dFreq... } } While cleaning up this code during a "performance pass," I decided to move the definition of dFreq inside the if block, as it was only used inside the if. There are several calculations involving dFreq so I didn't eliminate it entirely as it does save the cost of multiple run-time conversions from int to double. I expected no performance difference, or if any at all, a negligible improvement. However, the perfomance decreased by nearly 10%. I have measured this many times, and this is indeed the only change I've made. The code snippet shown above executes inside a couple other loops. I get very consistent timings across runs and can definitely confirm that the change I'm describing decreases performance by ~10%. I would expect performance to increase because the int to double conversion would only occur when iFreq != 0. Chnaged code: for (int i = 0; i < ct; ++i) { // do some stuff... int iFreq = getFreq(i); if (iFreq != 0) { // do some stuff with iFreq... double dFreq = iFreq; // do some stuff with dFreq... } } Can anyone explain this? I am using VC++ 9.0 with /O2. I just want to understand what I'm not accounting for here.
You should put the conversion to dFreq immediately inside the if() before doing the calculations with iFreq. The conversion may execute in parallel with the integer calculations if the instruction is farther up in the code. A good compiler might be able to push it farther up, and a not-so-good one may just leave it where it falls. Since you moved it to after the integer calculations it may not get to run in parallel with integer code, leading to a slowdown. If it does run parallel, then there may be little to no improvement at all depending on the CPU (issuing an FP instruction whose result is never used will have little effect in the original version). If you really want to improve performance, a number of people have done benchmarks and rank the following compilers in this order: 1) ICC - Intel compiler 2) GCC - A good second place 3) MSVC - generated code can be quite poor compared to the others. You may also want to try -O3 if they have it.
2,209,652
2,210,214
Fewer connections in a Qt calculator
I'm writing a simplified calculator using Qt with C++, for learning purposes. Each number is a QPushButton that uses the same slot to modify the text in a lineEdit widget being used as a display. The slot uses the sender() method to figure out which button was pressed, so the correct number would be written on the display widget. In order to have all the buttons working, I'd have to write a connection to each one of them, kinda like this: connect(ui->button1, SIGNAL(clicked()), this, SLOT(writeNum())); Since they all use the same slot, the only thing that changes is the button being used, so the next sender would be ui->button2, ui->button3, and so on. My question is, is there a way to reduce the number of defined connections? Edit: Here's a useful link discussing precisely about this problem, in detail.
If you use QtDesigner or the form editor of QtCreator you can just drag lines between the 2 and it will fill in the code for you. You could also keep all the buttons in a list structure, but I would use a QVector not a standard array. You might also want to reconsider using the sender() method, it violates OOP design. Instead connect all the buttons to a QSignalMapper and then connect mapped() to your text box.
2,209,875
2,210,102
C++: A way to declare a variable (or more than one) in an if statement that separates out the variable definition and the test?
One can do this: case WM_COMMAND: if (WORD wNotifyCode = HIWORD(wparam)) { ... } And one can do this: case WM_COMMAND: { WORD wNotifyCode = HIWORD(wparam); if (wNotifyCode > 1) { ... } } But one cannot do: case WM_COMMAND: if ((WORD wNotifyCode = HIWORD(wparam)) > 1) { ... } Using a for statement here I think is misleading: case WM_COMMAND: for (WORD wNotifyCode = HIWORD(wparam); wNotifyCode > 1; wNotifyCode = 0) { ... } Because it looks a lot like a loop is happening - and the poor schmuck who comes after me has to decipher this garbage. But is there no syntactic construct which combines the elegance of an if-statement that includes a local variable declaration with the ability to test its value for something other than zero?
Sometimes readability and maintainability is more important then a line of code saved. IF you need the local variable at all then by all means introduce it explicitly in this case and maybe introduce an additional scope if you want it limited - but you should also consider if maybe you can just live with using the HIWORD macro in a couple places - this way you don't need any tricks at all.
2,209,889
2,210,209
How to use C++ operators within python using boost::python (pyopencv)
I'm using the pyopencv bindings. This python lib uses boost::python to connect to OopenCV. Now I'm trying to use the SURF class but don't know how to handle the class operator in my python code. The C++ class is defined as: void SURF::operator()(const Mat& img, const Mat& mask, vector<KeyPoint>& keypoints) const {...} How can I pass my arguments to that class? Update: Thanks to interjay I can call the method but now I getting type errors. What would be the python boost::python::tuple ? import pyopencv as cv img = cv.imread('myImage.jpg') surf = cv.SURF(); key = [] mask = cv.Mat() print surf(img, mask, key, False) Gives me that: Traceback (most recent call last): File "client.py", line 18, in <module> print surf(img, mask, key, False) Boost.Python.ArgumentError: Python argument types in SURF.__call__(SURF, Mat, Mat, list, bool) did not match C++ signature: __call__(cv::SURF inst, cv::Mat img, cv::Mat mask, boost::python::tuple keypoints, bool useProvidedKeypoints=False) __call__(cv::SURF inst, cv::Mat img, cv::Mat mask)
You just call it as if it was a function. If surf_inst is an instance of the SURF class, you would call: newKeyPoints = surf_inst(img, mask, keypoints) The argument keypoints is expected to be a tuple, and img and mask should be an instance of the Mat class. The C++ function modifies its keypoints parameter. The Python version instead returns the modified keypoints. C++'s operator() is analogous to Python's __call__: It makes an object callable using the same syntax as a function call. Edit: For your second question: As you can see in the error, keypoints is supposed to be a tuple and you gave it a list. Try making it a tuple instead.
2,209,929
2,224,732
Linking different libraries for Debug and Release builds in Cmake on windows?
So I've got a library I'm compiling and I need to link different third party things in depending on if it's the debug or release build (specifically the release or debug versions of those libraries). Is there an easy way to do this in Cmake? Edit: I should note I'm using visual studio
According to the CMake documentation: target_link_libraries(<target> [lib1 [lib2 [...]]] [[debug|optimized|general] <lib>] ...) A "debug", "optimized", or "general" keyword indicates that the library immediately following it is to be used only for the corresponding build configuration. So you should be able to do this: add_executable( MyEXE ${SOURCES}) target_link_libraries( MyEXE debug 3PDebugLib) target_link_libraries( MyEXE optimized 3PReleaseLib)
2,209,935
2,209,970
Any gotchas in copy ctor and assignment operator having slightly different semantics?
Please look at the following code and tell me if it's going to cause problems in the future, and if yes, how to avoid them. class Note { int id; std::string text; public: // ... some ctors here... Note(const Note& other) : id(other.id), text(other.text) {} void operator=(const Note& other) // returns void: no chaining wanted { if (&other == this) return; text = other.text; // NB: id stays the same! } ... }; In short, I want the copy constructor to create an exact copy of an object, including its (database) ID field. On the other hand, when I assign, I want just to copy the data fields. But I have some concerns, since usually the copy ctor and the operator= have same semantics. The id field is used only by Note and its friends. For all other clients, the assignment operator does create an exact copy. The use case: When I want to edit a note, I create a copy using copy ctor, edit it, and then call save on the Notebook class which manages Notes: Note n(notebook.getNote(id)); n = editNote(n); // pass by const ref (for the case edit is canceled) notebook.saveNote(n); When on the other hand I want to create a completely new note with the same contents as an existing note, I can do this: Note n; n = notebook.getNote(id); n.setText("This is a copy"); notebook.addNote(n); Is this approach plausible? If not, please point out what the possible negative consequences are! Thanks a lot!
If you want semantics that don't match what's expected from the assignment operator, then don't use it. Instead, disable it by declaring a private operator= and define a function with a name that makes clear what's going on, like copyDataFields.
2,209,993
2,210,051
How to properly do threading in C++?
I have a rather large, dynamic sparse matrix object class to write, and I want to make the following happen: one thread to handle placing elements into the matrix, and one to handle reading from the matrix. The only time when these two would conflict would be when they would both want to access the same row/column at the same time. As such, I've decided that a simple mutex lock for each row/column is sufficient. Now this is the first time I've actually done threading in C/C++, and I'd like to do it by the books, so to speak. I have two concerns. How do I spawn these threads? This is a language question more than anything. How do I implement the locking itself as efficiently as possible? I figure if there is a conflict, then the requesting thread would place itself in line and wait until the resource is freed. However, how do I implement that waking? I can have a loop poll the memory location, but that's not elegant. Ideally, I figure an interrupt based approach would be best.
If this is your first time to do multi-threading, use the Boost.Threads library. Its semantics (including synchronization mechanisms) are very straightforward and your implementation will be portable. http://www.boost.org/doc/libs/1_42_0/doc/html/thread.html
2,210,118
2,210,540
http proxy javascript injection
I have a simple proxy source in C++. I'm trying to modify it to inject some html content into specific pages. I'v managed to get it working but whenever I inject something, part of the original html gets corrupted. I know for a fact that it's not my string handling functions because I have it printing out the result before sending and it's fine. The html is transmitted 1460 bytes at a time and there is a 3 character string followed newline at the top of each chunk and then at the very end there is a newline and a 0; Example: fef some html co7 some html 81f final html 0 Iv been searching and trying to figure out what those three characters represent. Remaining content length hexed? maybe some sort of hash? but I can't find anything. But I'm guessing they're the source of the problem. Any help/insight is appreciated.
Chunked Encoding? See RFC 2616, Section 3.6.1.
2,210,234
2,210,275
Search a large file for data in C/C++
I have a log file which has a format of this kind: DATE-TIME ### attribute1 ### attribute2 ###attribute3 I have to search this log file for a input attribute(entered from command line) and output the lines that match the entered attribute. A naive approach may be something like this: scan the entire file line by line search for the attribute print if found, else ignore. This approach is slow as it would require O(n) comparisons, where n is number of lines which may be very large. Another approach may be to use a hash-table but keeping such a in-memory hash-table for a big file may not be possible. So, what is the best feasible solution? How can I possibly index the entire file on various attributes? EDIT: The log file may be about 100K lines, almost like the system log files on linux. On One invocation, a user may search for multiple attributes, which is not known until the search on 1st attribute is completed like an interactive console. Thanks,
You can reduce the size of the hash table by only storing hash values and file offsets in it. If the attributes only have a fixed, relatively small number of values, you are more likely to be able to fit the whole hash table in memory. You assign an id to each possible value of the attribute, and then for each id value store a big list of file offsets. Of course the hash table is only going to be helpful if, within the same run of the program, you do several different searches. The obvious solution would be to stuff the data in a database, but I assume that the OP is smart enough to have realized that already and has other reasons for specifically requesting a non-database solution to the problem.
2,210,279
2,210,350
Manual alternative to message map?
I am trying to create a GUI to display information read from a file. So I will need some number of pushbuttons, text fields, and radio buttons - but I won't know how many I need until run-time. I am using Visual Studio 6.0. My toolset is fairly non-negotiable, so please refrain from suggesting Java, or any C++ toolkit that does not come pre-installed in Visual Studio. My problem is that most of the tutorials I have found online focus on using the WYSIWYG editor - which requires knowing what controls are needed up front. I found a code sample that allows me to add controls manually (exerpts below): class CalcApp : public CWinApp { ... }; class CWindow : public CFrameWnd { ... afx_msg void HandleButton2(); afx_msg HBRUSH OnCtlColor( CDC* pDC, CWnd* pWnd, UINT nCtlColor ); DECLARE_MESSAGE_MAP(); virtual BOOL PreTranslateMessage(MSG* msg); }; .cpp file: BEGIN_MESSAGE_MAP( CWindow, CFrameWnd ) ON_BN_CLICKED(IDC_BUTTON1, HandleButton1) ON_BN_CLICKED(IDC_BUTTON2, HandleButton2) END_MESSAGE_MAP() CWindow::CWindow() { Create(NULL, "Title", WS_OVERLAPPED | WS_MINIMIZEBOX | WS_SYSMENU, CRect(CPoint(50,50),CSize(180,300))); ... button2 = new CButton(); button2 -> Create("&Quit", WS_CHILD|WS_VISIBLE|WS_TABSTOP, CRect(CPoint(2,202),CSize(152,38)), this, IDC_BUTTON2); } void CWindow::HandleButton2() { DestroyWindow (); } BOOL CalcApp::InitInstance() { m_pMainWnd = new CWindow(); m_pMainWnd->ShowWindow(m_nCmdShow); m_pMainWnd->UpdateWindow(); return TRUE; } What I'm having trouble figuring out is how to handle the message processing without using the BEGIN_MESSAGE_MAP(), etc macros - which, again, require knowing how many handlers you need up front. The only solution I've been able to find looks like this: LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { ... WndClsEx.lpfnWndProc = WndProc; RegisterClassEx(&WndClsEx); hWnd = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, ClsName, WindowCaption, WS_OVERLAPPEDWINDOW, 100, 120, 640, 480, NULL, NULL, hInstance, NULL); ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); while( GetMessage(&Msg, NULL, 0, 0) ) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; } //--------------------------------------------------------------------------- LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { switch(Msg) { case WM_DESTROY: PostQuitMessage(WM_QUIT); break; default: return DefWindowProc(hWnd, Msg, wParam, lParam); } return 0; } Which is great, except.. I don't have a WinMain... My understanding is that you can either do a "Win32" application (the WinMain code above) or an "MFC" application (the CButton code above). But I can only find examples of manually adding controls for MFC, and I can only find examples of manually processing messages for Win32. Can you point me to one of the things I'm missing here? Ideally, I want a solution for handling my own messages with MFC, but I'd settle for a good tutorial on creating controls with Win32...
Once upon a time I did something like this. I allocated a rage of control ids (not used in resource.h). Added controls with these ids dynamically to the page. To handle the event I took over the OnCommand on the Windows and listened for controls with ids in the range I was looking for. (I need to search old code to be more specific)
2,210,388
2,213,027
Swap method with const members
I want to implement a Swap() method for my class (let's call it A) to make copy-and-swap operator=(). As far as I know, swap method should be implemented by swapping all members of the class, for example: class A { public: void swap(A& rhv) { std::swap(x, rhv.x); std::swap(y, rhv.y); std::swap(z, rhv.z); } private: int x,y,z; }; But what should I do if I have a const member? I can't call std::swap for it, so I can't code A::Swap(). EDIT: Actually my class is little bit more complicated. I want to Serialize and Deserialize it. Const member is a piece of data that won't change (its ID for example) within this object. So I was thinking of writing something like: class A { public: void Serialize(FILE* file) const { fwrite(&read_a, 1, sizeof(read_a), file); } void Deserialize(FILE* file) const { size_t read_a; fread(&read_a, 1, sizeof(read_a), file); A tmp(read_a); this->Swap(tmp); } private: const size_t a; }; and call this code: A a; FILE* f = fopen(...); a.Deserialize(f); I'm sorry for such vague wording.
After a good nights sleep I think the best answer is to use a a non-const pointer to a const value -- after all these are the semantics you are trying to capture.
2,210,460
2,210,507
Creating a simple program in C++ for windows. How to build GUI
For a school project, we need to create a fairly simple app using C++ and .NET framework. I only know C++, but we need to produce a working executable file for the project. The prof said we can use WYSIWYG editors for the GUI, but i can't seem to find one in Visual C++. I wanted to code with Visual C++ since i want to learn about Visual Studio. Is there a way I can use a GUI builder application for C++ and somehow connect it with my project in Visual C++? I'm very new to .NET and have spent the past 3 hours reading about .NET and the developer tools and what not, and i'm kinda lost..
1) Download Visual C++ 2008 Express for free here 2) Go to File->New->Windows Form Application. Done! You got the WYSIWYG editors for the GUI. Hope it helps Max
2,210,506
2,210,787
compile SQLite amalgamation for Windows Mobile device
How can I compile the SQLite amalgamation for Windows Mobile device? Then I want to use in a console to run some commands. I've created an empty VS project in C/C++ for Smart Device, then included the existing files into Sources and Headers. When I try to compile I get: Error 1 error LNK2019: unresolved external symbol wmain referenced in function mainWCRTStartup corelibc.lib sqlite3
The amalgamation file does not contain a main function because it's really just the sqlite library, and not a command-line interface program. You will have to implement the commands yourself and link against the sqlite library.
2,210,837
2,210,911
(Text-Based) Games for C++ practice
I'm currently learning C++ and so I thought it would be a good idea trying to (re)program some "common" text-based games. (Thinking of Hunt the Wumpus, Guess a (pseudo) random number generated by the computer,...) However, I can't find any good sources for such tasks. Which text-based games could be "educating" for me to program? Do you remember a special game you have programmed (written in C++ preferably), which taught you a lot? It would be nice if you could include: A general concept of the game What aspects of the C++ language programming this game would require/involve
I'm trying to remember some of the fun stuff I did way back when in my high school CS class. They're not all games but here it goes: Text based (ASCII) animation - Basically I animated an ASCII dragon coming into the terminal, saying something, and leaving. After "drawing" each frame it was cleared so basically it was a frame-by-frame ASCII animation generator. Maze - Used Unicode characters in kind of the same concept. I got keyboard input from the arrow keys and redrew your block going through the maze based on your input. Again, clearing the screen after each frame and printing out the text again. Snake - similar concept as the above but it was a snake game. Simple chat - this polled a shared text file on a central server in our school (that someone accidentally chmoded 0777) and facilitated basically a really simple chat room. The beeper - this program became infamous at my school. Up until XP apparently the sound buffer on Windows computers could easily get overloaded by text. Running this caused the computer to beep until you turned it off (and in most instances also caused it to get bogged down so much you had to do a hard reboot). Definitely pissed off the administration of our high school. Plus it's only a 2-liner. char o = 7; while(1) cout << o; Anyway, not sure if this helped you get any ideas but just use your imagination. You can have a lot of fun without having to know a lot about programming. Just be creative.
2,210,839
2,210,934
Conditional CXX_FLAGS using cmake based on compiler?
I've just started using CMake for some personal and school projects, and I've been stumped by a minor issue. Let's say I'm trying to get a C++ program compiling under multiple compilers (g++, cl, and bcc32 in this case). I have different command line switches for each compiler, and what I was attempting to do was to basically make a gnu/ms/borland directory and create CMake stuff in there (by entering the directories and doing a cmake -DCMAKE_CXX_COMPILER=g++ .. in the gnu, directory, for instance). In the CMakeLists.txt on the top level directory, I tried doing something along the lines of: if(CMAKE_CXX_COMPILER STREQUAL g++) set(CMAKE_CXX_FLAGS "-Wextra -Wall -ansi -pedantic") And so on with elsifs for the other compilers, but this doesn't seem to work correctly -- it drops the CXXFLAGS entirely. The line works if I make the file completely unconditional (ie, just assume g++ and use g++ flags.). What am I doing wrong here, or is there a better way to handle this sort of a problem?
There are a bunch of pre-defined CMake variables depending on the compiler you're using: if (MSVC) set ( CMAKE_CXX_FLAGS "/GLOBAL_FLAGS_GO_HERE") set ( CMAKE_CXX_FLAGS_DEBUG "/DEBUG_FLAGSS_GO_HERE") set ( CMAKE_CXX_FLAGS_RELEASE "/RELEASE_FLAGS_GO_HERE" ) endif () if (BORLAND) set ( CMAKE_CXX_FLAGS "/GLOBAL_FLAGS_GO_HERE") set ( CMAKE_CXX_FLAGS_DEBUG "/DEBUG_FLAGS_GO_HERE") set ( CMAKE_CXX_FLAGS_RELEASE "/RELEASE_FLAGS_GO_HERE" ) endif () if (CMAKE_COMPILER_IS_GNUCXX) set ( CMAKE_CXX_FLAGS "/GLOBAL_FLAGS_GO_HERE") set ( CMAKE_CXX_FLAGS_DEBUG "/DEBUG_FLAGS_GO_HERE") set ( CMAKE_CXX_FLAGS_RELEASE "/RELEASE_FLAGS_GO_HERE" ) endif () If you want your compiler options to override and persist in the generated CMakeCache: if (CMAKE_COMPILER_IS_GNUCXX) set ( CMAKE_CXX_FLAGS "/GLOBAL_FLAGS_GO_HERE" CACHE STRING "g++ Compiler Flags for All Builds" FORCE) set ( CMAKE_CXX_FLAGS_DEBUG "/DEBUG_FLAGS_GO_HERE" CACHE STRING "g++ Compiler Flags for Debug Builds" FORCE) set ( CMAKE_CXX_FLAGS_RELEASE "/RELEASE_FLAGS_GO_HERE" CACHE STRING "g++ Compiler Flags for Release Builds" FORCE) endif ()
2,210,928
2,210,949
How I do fibonaci sequence under 1000?
#include <iostream> using namespace std; void main() { int i = 0; while (i < 1000) { int TEMP = i * 2; cout << i << endl; TEMP = i; i = i +1; // ??? } return; } I'm so confused?? :(
First you should check that you understand the definition of the Fibonacci numbers. By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s. You need two variables to remember the state, not just one as you were trying to do. And you don't multiply by two, you just add the two variables. #include <iostream> using namespace std; int main() { int i = 0; int j = 1; while (i < 1000) { /* Print a number. */ cout << i << endl; /* Set j to the sum of i and j, and i to the old value of j. */ int TEMP = j; j += i; i = TEMP; } return 0; }
2,211,012
2,211,085
Working with enum-like data in C++
I am updating an old piece of C++ code and am stuck on a design issue and need advice on the best course of action. The code handles geometric data. Currently, the code defines many global constants to handle element types: #define TETRAHEDRON 0 #define HEXAHEDRON 1 Each constant has information associated with it that remains constant and which is currently handled by a class, in our case Topology. int Topology::nodesPerElement(int topType) { switch(topType) { case TETRAHEDRON: return 4; break; case HEXAHEDRON: return 8; break; } } The Topology class has many of these functions that simply switch on the global constant to figure out associated information. There are a lot of element types and many bugs are introduced by switch statements that don't consider all element types. If an element type is added all of these methods need to be fixed. I need a better way of doing this that keeps the associated information with the type. Enumerations are an improvement over this design, but it doesn't solve the problem of associating data with the enumeration. For simplicity, I would like to avoid needing to instantiate classes for each type, as each will contain only static data that doesn't change. What I really need is a "static class" that holds this information and performs like the pseudocode below: class Tetrahedron : public TopType { static const int nodesPerElement = 4; static const std::string name = "Tet"; etc... } Each method in Topology becomes trivial: int Topology::nodesPerElement(TopType topType) { return topType.nodesPerElement; } Is there a way to do this in C++? I've thought about just getting rid of the enumerations and having separate child Topology classes for each TopologyType, but the feedback I get from others is that it's too complicated of a solution. I hope that my question is clear enough.
Create a base class that contains all of the properties that your objects should support, and a private constructor to set those properties. You don't need derived classes, then: you can use static public objects to create the objects that you want with the desired properties. class TopologyObject { private: int numberVertices; int numberFaces; // etc. public: int getVertices() { return numberVertices; }; int getFaces() { return numberFaces; }; protected: TopologyObject(int vertices, int faces) : numberVertices(vertices), numberFaces(faces) {}; public: static TopologyObject Tetrahedron = new TopologyObject(4, 4); // etc. } You can access the Tetrahedron with all of its properties via TopologyObject::Tetrahedron. If you decide that you need more complex variable behavior based on the type of object, then you really do need derived classes and virtual methods for the overrideable behavior.
2,211,030
2,211,614
failing to compile a project, missing io.h file
I fail to compile a C++ project for mobile device with Windows Mobile (Windows CE-based) operating system and Visual C++ compiler from Visual Studio fails with: Error 1 fatal error C1083: Cannot open include file: 'io.h' EDIT I am trying to compile the SQLite amalgamation, the shell.c file includes the call to this io.h but the io.h is missing from the files. I googled and I couldn't locate how can I get this .h file. Can someone point me in the right direction?
The io.h file is not available in SDKs for Windows CE-based systems like Windows Mobile. In fact, io.h header has never been a part of ISO C nor C++ standards. It defines features that belongs POSIX compatibility layer on Windows NT, but not Windows CE. Due to lack of POSIX features on Windows CE, I developed a small utility library WCELIBCEX. It does include io.h but a very minimal version and which is likely insufficient for SQLite. However, as ctacke mentioned, you should use SQLite port for Windows CE because original version of SQLite is not compilable for this platform. p.s. Note, Your question does not specify explicitly that you're building for Windows Mobile. If one doesn't spot the .NET Compact Framework mentioned in tags, then the whole question is ambiguous.
2,211,097
2,211,140
dictionary library in C++
I have to use write a program in which the dictionary should be used to check whether one string is a valid word in it. Is there any dictionary library I could use? If not, how could I construct a dictionary for query? Thanks!
struct Dictionary { Dictionary() { // load _words, here's one possible implementation: std::ifstream input ("/usr/share/dict/words"); for (std::string line; getline(input, line);) { _words.insert(line); } } bool contains(std::string const& word) const { return _words.count(word); } std::set<std::string> _words; };
2,211,128
2,211,192
Why does g++ generate multiple (weak) similar symbols?
I'm looking at the output of nm -C 0804a86a W ForkMessageHandler::ForkMessageHandler() 0804a86a W ForkMessageHandler::ForkMessageHandler() 0804a6fa T ForkMessageHandler::~ForkMessageHandler() 0804a698 T ForkMessageHandler::~ForkMessageHandler() 0804a698 T ForkMessageHandler::~ForkMessageHandler() 0804a800 W MultiMessageHandler::MultiMessageHandler() 0804a800 W MultiMessageHandler::MultiMessageHandler() 0804a84c W MultiMessageHandler::~MultiMessageHandler() 0804a81c W MultiMessageHandler::~MultiMessageHandler() 0804a81c W MultiMessageHandler::~MultiMessageHandler() Why does g++ generate many similar symbols, and what's the purpose of weak symbols ? Edit: this is from the final executable, not a .o file. ForkMessageHandler is defined in a .cpp file, noone includes a header for it - but several includes headers for its base class.
Those are the default constructors and automatically generated destructors. They will be generated as weak symbols in every compilation unit that includes the class definition to guarantee that there is at least one available. The reason they are weak is to avoid conflicts in the linking process since the class definition will be present in every object file including the header file it's defined.
2,211,319
2,211,437
Can't get DLL to work on Visual Studio
I've been following the tutorial from msdn and it just doesn't work. First problem I have is that sometimes the .dll and .lib aren't built. Instead I only get .objs. Whenever I build the .dll project, it gives me a popup asking to "please specify the name of the executable file to be used for the debug session". I was told to change my startup project to one with a main function, but then the .dll doesn't get built. This happens both using the default VS configuration and simply adding some lines or following the step-by-step guide at msdn. When the .dll and .obj are built - God knows how - I can't get them to be recognized. I've tried putting them and the .h in the project folder, but then I get an error about the .dll function being undefined. Following the msdn link, at one point it says: To use the math routines that were created in the dynamic link library, you must reference the library. To do this, select References… from the Project menu. On the Property Pages dialog box, expand the Common Properties node, select References, and then select the Add New Reference… button. For more information about the References… dialog box, see Framework and References, Common Properties, Property Pages Dialog Box. The Add Reference dialog box is displayed. This dialog lists all the libraries that you can reference. The Project tab lists all the projects in the current solution and any libraries they contain. On the Projects tab, select MathFuncsDll. If I go Project > Test Properties > Common Properties I can only find the subitem "Framework and References". There is no "References..." There is an "Add new Reference..." button, but that doesn't let me add anything. The other button, "Add Path..." doesn't make any difference even when I set it with the directory with the files. The following steps don't work either. I've also tried to add the name of the file at the Linker, but then it says it couldn't find the .obj file. I have no idea where to go from here. I been stuck on this for hours and nowhere has a solution for this. Is there a step-by-step guide anywhere that actually works for VS2008?
firstly your description is mixing managed (.net) things with normal c++ stuff. I assume you are doing normal c++ stuff. DO you own (I mean have the source; are the author) both the DLL and the calling program? If so you should have 2 VS projects one for the DLL and one for the program. You should set the program as the startup project. This will make the debugger behave correctly IN order to get the build right you need to make the c++ program depend on the dll project. There is a Project | Project dependies dialog that will do this for you, set the program project to depend on the dll project If you only own the DLL then you need to go to the project properties | debug and tell it what binary to run to call your DLL. If this is managed c++ then its a whole different storty
2,211,656
2,213,166
validating numerical user input
I am creating a simple CLI calculator tool as an exercise. I need to make sure n1 and n2 are numeric in order for the functions to work; consequently, I would like to make the program quit upon coming across a predetermined non-numeric value. Can anyone give me some direction? Additionally, if anyone can offer any general tips as to how I could have done this better, I would appreciate it. I'm just learning c++. Thank you! The complete code is included below. #include <iostream> #include <new> using namespace std; double factorial(double n) { return(n <= 1) ? 1 : n * factorial(n - 1); } double add(double n1, double n2) { return(n1 + n2); } double subtract(double n1, double n2) { return(n1 - n2); } double multiply(double n1, double n2) { return(n1 * n2); } double divide(double n1, double n2) { return(n1 / n2); } int modulo(int n1, int n2) { return(n1 % n2); } double power(double n1, double n2) { double n = n1; for(int i = 1 ; i < n2 ; i++) { n *= n1; } return(n); } void print_problem(double n1, double n2, char operatr) { cout<<n1<<flush; if(operatr != '!') { cout<<" "<<operatr<<" "<<n2<<flush; } else { cout<<operatr<<flush; } cout<<" = "<<flush; } int main(void) { double* n1, * n2, * result = NULL; char* operatr = NULL; n1 = new (nothrow) double; n2 = new (nothrow) double; result = new (nothrow) double; operatr = new (nothrow) char; if(n1 == NULL || n2 == NULL || operatr == NULL || result == NULL) { cerr<<"\nMemory allocation failure.\n"<<endl; } else { cout<<"\nTo use this calculator, type an expression\n\tex: 3*7 or 7! or \nThen press the return key.\nAvailable operations: (+, -, *, /, %, ^, !)\n"<<endl; do { cout<<"calculator>> "<<flush; cin>>*n1; cin>>*operatr; if(*operatr == '!') { print_problem(*n1, *n2, *operatr); cout<<factorial(*n1)<<endl; } else { cin>>*n2; switch(*operatr) { case '+': print_problem(*n1, *n2, *operatr); cout<<add(*n1, *n2)<<endl; break; case '-': print_problem(*n1, *n2, *operatr); cout<<subtract(*n1, *n2)<<endl; break; case '*': print_problem(*n1, *n2, *operatr); cout<<multiply(*n1, *n2)<<endl; break; case '/': if(*n2 > 0) { print_problem(*n1, *n2, *operatr); cout<<divide(*n1, *n2)<<endl; } else { print_problem(*n1, *n2, *operatr); cout<<" cannot be computed."<<endl; } break; case '%': if(*n1 >= 0 && *n2 >= 1) { print_problem(*n1, *n2, *operatr); cout<<modulo(*n1, *n2)<<endl; } else { print_problem(*n1, *n2, *operatr); cout<<" cannot be computed."<<endl; } break; case '^': print_problem(*n1, *n2, *operatr); cout<<power(*n1, *n2)<<endl; break; default: cout<<"Invalid Operator"<<endl; } } } while(true); delete n1, n2, operatr, result; } return(0); }
No need for Boost or writing your own template or forcing yourself to use exceptions vs error codes. cin alone does everything you're asking for. You can test if ( cin ) or if ( ! cin ) to determine success or failure. One failure (eg, a letter in numeric input) will stop cin from accepting any more input. Then call cin.clear() to clear the error and resume getting input, starting with whatever text caused the error. Also, you can request that a stream throw exceptions on conversion errors: cin.exceptions( ios::failbit ). So, you can do this: for (;;) try { double lhs, rhs; char oper; cin.exceptions( 0 ); // handle errors with "if ( ! cin )" cin >> lhs >> oper; // attempt to do "the normal thing" if ( ! cin ) { // something went wrong, cin is in error mode string command; // did user enter command instead of problem? cin.clear(); // tell cin it's again OK to return data, cin >> command; // get the command, if ( command == "quit" ) break; // handle it. else cin.setstate( ios::failbit ); // if command was invalid, // tell cin to return to error mode } cin.exceptions( ios::failbit ); // now errors jump directly to "catch" // note that enabling exceptions works retroactively // if cin was in error mode, the above line jumps immediately to catch if ( oper != '!' ) cin >> rhs; // do stuff } catch ( ios::failure & ) { cin.clear(); cin.ignore( INT_MAX, '\n' ); // skip the rest of the line and continue } This is meant as a demonstration of error handling with iostreams. You can choose to use exceptions or manual testing or both.