question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,136,981
1,137,503
How to iterate over a boost::fusion sequence?
I'm trying to initialise a list of args to use with fusion::invoke. The args are all of the form: template <typename Type> struct ArgWrapper { inline ArgWrapper(){} inline void Setup(lua_State*L,int idx) { //setup this value from the lua state... //in reality this class is specialised for different lua types } operator Type(){return value;} Type value; }; So I can do, for example int add(int a,int b){return a+b;} fusion::vector<ArgsWrapper<int>,ArgsWrapper<int> > v; fusion::at_c<0>(v).value=1; fusion::at_c<1>(v).value=2; std::cout<<fusion::invoke(add,v)//prints 3 But if I have a fusion sequence of type FusionListType, where I know each type in the sequence is an ArgWrapper of some type, how can I iterate through that list and call the Setup function on each element (I have just one lua_State pointer and want to use it as the first argument for Setup, and I want to use the position in the sequence as the second argument). So for a vector of size 3 I want the resultant logic to be: lua_State*L; fusion::at_c<0>.Setup(L,1); fusion::at_c<1>.Setup(L,2); fusion::at_c<2>.Setup(L,3); I have tried: template<typename ArgWrapperType,int N> void FillArgWrapper(ArgWrapperType arg,lua_State*L) { fusion::at_c<N>(arg).Setup(L,N+1); } template<typename ArgWrapperType> void FillArgWrapper<ArgWrapperType,0>(ArgWrapperType arg,lua_State*L) { fusion::at_c<0>(arg).Setup(L,1); } But this fails to compile, saying function template partial specialisation ‘FillArgWrapper<ArgWrapperType, 0>’ is not allowed. Thanks in advance.
Ok, I figured it out. I need to be using a struct: template <typename ArgWrapperList,u32 N=mpl::size<ArgWrapperList>::value-1> struct ArgWrapperListFiller { static inline void Setup(ArgWrapperList &args,lua_State*L) { fusion::at_c<N>(args).Setup(L,N+1); ArgWrapperListFiller<ArgWrapperList,N-1>::Setup(args,L); } }; template <typename ArgWrapperList> //base case, do not recurse struct ArgWrapperListFiller<ArgWrapperList,0> { static inline void Fill(ArgWrapperList &args,lua_State*L) { fusion::at_c<0>(args).Setup(L,1); }; };
1,137,116
1,137,434
Storing iterators inside containers
I am building a DLL that another application would use. I want to store the current state of some data globally in the DLL's memory before returning from the function call so that I could reuse state on the next call to the function. For doing this, I'm having to save some iterators. I'm using a std::stack to store all other data, but I wasn't sure if I could do that with the iterators also. Is it safe to put list iterators inside container classes? If not, could you suggest a way to store a pointer to an element in a list so that I can use it later? I know using a vector to store my data instead of a list would have allowed me to store the subscript and reuse it very easily, but unfortunately I'm having to use only an std::list.
Yes, it'll work fine. Since so many other answers go on about this being a special quality of list iterators, I have to point out that it'd work with any iterators, including vector ones. The fact that vector iterators get invalidated if the vector is modified is hardly relevant to a question of whether it is legal to store iterators in another container -- it is. Of course the iterator can get invalidated if you do anything that invalidates it, but that has nothing to do with whether or not the iterator is stored in a stack (or any other data structure).
1,137,155
1,137,194
Why does windows let you draw on the whole screen?
I've been playing a big with the DC obtained with CreateDC(L"DISPLAY",NULL,NULL,NULL) and I've been wondering why does windows let you draw on the whole screen that easily, cause I think you could do some pretty evil stuff with that like putting a TIMER at 1ms and drawing a black rectangle on the whole screen every time the timer ticks.
The fact that you could do some pretty evil stuff doesn't mean windows shouldn't let you do it. Just think of all the other evil things you could do: Run in an infinite loop and eat up all the cpu time. Write random bits to a file until you fill up the whole hard disk. Delete random files all over the place. Allocate memory like crazy until the computer slows to a crawl. Just because you CAN do those things doesn't mean windows should prevent you from writing to the hard drive or allocating memory or deleting files. The purpose of Windows is to provide an environment in which programs can run. The more flexible they make that environment, the more interesting (and, unfortunately, devious) programs it makes possible for developers to create. If they started putting in arbitrary restrictions on what you can do because you might abuse it... well, then it wouldn't be windows, it would be an iPhone :)
1,137,228
1,137,338
generic lookup method?
I'd like a generic method for retrieving the data from a vector. I have a the following class and vector: class myClass { public: myClass(int myX, float myZ, std::string myFoo) : x ( myX ) , z ( myZ ) , foo ( myFoo ) { } myClass() { } int x; float z; std::string foo; } ; std::vector < myClass > myVector; (The complete code can be seen here: http://codepad.org/iDD1Wme5 ) In this example I would like to be able to retrieve objects in the vector based on the "z" or "foo" members without having to write another 2 functions similar to "FindDataById". Is that possible?
You can use a template and pointer to member. typedef vector<myClass> myVector; template<typename T> bool FindDataById(const T &id, T myClass::* idMember, myClass &theClass, const myVector &theVector) { for(myVector::const_iterator itr = theVector.begin(); itr != myVector.end(); ++itr){ if((*itr).*idMember == id){ theClass = *itr; return true; } return false; } Then call using, e.g., FindDataById(string("name"), &myClass::foo, theClass, theVector) FindDataById(5, &myClass::x, theClass, theVector) FindDataById(5.25f, &myClass::z, theClass, theVector) Or, go with the find_if idea: template<typename T> struct Finder { T val_; T myClass::* idMember_; Finder(T val, T myClass::* idMember) : val_(val), idMember_(idMember) {} bool operator()(const myClass &obj) { return obj.*idMember_ == val_; } }; And use: find_if(theVector.begin(), theVector.end(), Finder<string>("name", &myClass::foo)) find_if(theVector.begin(), theVector.end(), Finder<int>(5, &myClass::x)) find_if(theVector.begin(), theVector.end(), Finder<float>(3.25f, &myClass::z)) See the answer of MSalters for a way to deduce the template argument automatically.
1,137,265
1,137,752
Build two interdependent dll
I have to interdependent dll here that i would like to build without having to build them twice (force build both of them and rebuild them again to allow linking). Here is an exemple : **DLL A** void fooA() { fooBB(); } void fooAA() { fooB(); } **DLL B** void fooB() { fooA(); } void fooBB() { } Is there a way to build those two DLL without mayor refactoring?
Do you actually rebuild both DLLs each time you compile ? If not, the import libraries should be created the first time - even if the link phase fails because of unresolved externals - and allow subsequent builds to link without error... edit: we actually have that kind of dependencies in my shop. Our build is incremental indeed, and clean builds need some projects to be built several times in order to link succesfully.
1,137,323
1,138,361
Qt/mingw32 undefined reference errors... unable to link a .lib
I am new to Qt and have one error I am unable to fix. I have a bunch of windows (VS2005) static library file (.lib). And I am testing if they work well with Qt. So I took the most simple library that I have. (Called MessageBuffer). So I added MessageBuffer.h to the main.cpp, and added the location of those file in the INCLUDEPATH of the .pro. Until then everything seem fine, I can use the class and Qt IDE show all method and everything. So to me it look like it found the .h file. Now I added the MessageBuffer.lib (VS2005/Debug build) in the .pro like this: LIBS += E:/SharedLibrary/lib/MessageBufferd.lib I have also tried the following: win32:LIBS += E:/SharedLibrary/lib/MessageBufferd.lib LIBS += -LE:/SharedLibrary/lib -lMessageBufferd win32:LIBS += -LE:/SharedLibrary/lib -lMessageBufferd Here is the content of my .pro file: QT += opengl TARGET = SilverEye TEMPLATE = app INCLUDEPATH += E:/SharedLibrary/MessageBuffer SOURCES += main.cpp \ silvereye.cpp HEADERS += silvereye.h FORMS += silvereye.ui OTHER_FILES += win32:LIBS += E:/SharedLibrary/lib/MessageBufferd.lib They all give me the same errors: (and I get the same even if I don't include the .lib) Running build steps for project SilverEye... Configuration unchanged, skipping QMake step. Starting: C:/Qt/2009.03/mingw/bin/mingw32-make.exe -w mingw32-make: Entering directory `C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye' C:/Qt/2009.03/mingw/bin/mingw32-make -f Makefile.Debug mingw32-make[1]: Entering directory `C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye' g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -Wl,-subsystem,windows -o debug\SilverEye.exe debug/main.o debug/silvereye.o debug/moc_silvereye.o -L"c:\Qt\2009.03\qt\lib" -lopengl32 -lglu32 -lgdi32 -luser32 -lmingw32 -lqtmaind E:/SharedLibrary/lib/MessageBufferd.lib -lQtOpenGLd4 -lQtGuid4 -lQtCored4 mingw32-make[1]: Leaving directory `C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye' mingw32-make: Leaving directory `C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye' debug/main.o: In function `Z5qMainiPPc': C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye/main.cpp:12: undefined reference to `MessageBuffer::MessageBuffer()' C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye/main.cpp:13: undefined reference to `MessageBuffer::Append(char*, int)' C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye/main.cpp:17: undefined reference to `MessageBuffer::~MessageBuffer()' C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye/main.cpp:17: undefined reference to `MessageBuffer::~MessageBuffer()' collect2: ld returned 1 exit status mingw32-make[1]: *** [debug\SilverEye.exe] Error 1 mingw32-make: *** [debug] Error 2 Exited with code 2. Error while building project SilverEye When executing build step 'Make' Can anyone help please?
Based on the question Use libraries compiled with visual studio in an application compiled by g++ (mingw) and the MSDN forum post I can't mix VC & GCC it does not appear you can link a gcc application with visual c++ compiled libraries. The solution would be to recompile everything with the same compiler.
1,137,341
1,137,515
Make compiler copy characters using movsd
I would like to copy a relatively short sequence of memory (less than 1 KB, typically 2-200 bytes) in a time critical function. The best code for this on CPU side seems to be rep movsd. However I somehow cannot make my compiler to generate this code. I hoped (and I vaguely remember seeing so) using memcpy would do this using compiler built-in intrinsics, but based on disassembly and debugging it seems compiler is using call to memcpy/memmove library implementation instead. I also hoped the compiler might be smart enough to recognize following loop and use rep movsd on its own, but it seems it does not. char *dst; const char *src; // ... for (int r=size; --r>=0; ) *dst++ = *src++; Is there some way to make the Visual Studio compiler to generate rep movsd sequence other than using inline assembly?
Using memcpy with a constant size What I have found meanwhile: Compiler will use intrinsic when the copied block size is compile time known. When it is not, is calls the library implementation. When the size is known, the code generated is very nice, selected based on the size. It may be a single mov, or movsd, or movsd followed by movsb, as needed. It seems that if I really want to use movsb or movsd always, even with a "dynamic" size I will have to use inline assembly or special intrinsic (see below). I know the size is "quite short", but the compiler does not know it and I cannot communicate this to it - I have even tried to use __assume(size<16), but it is not enough. Demo code, compile with "-Ob1 (expansion for inline only): #include <memory.h> void MemCpyTest(void *tgt, const void *src, size_t size) { memcpy(tgt,src,size); } template <int size> void MemCpyTestT(void *tgt, const void *src) { memcpy(tgt,src,size); } int main ( int argc, char **argv ) { int src; int dst; MemCpyTest(&dst,&src,sizeof(dst)); MemCpyTestT<sizeof(dst)>(&dst,&src); return 0; } Specialized intrinsics I have found recently there exists very simple way how to make Visual Studio compiler copy characters using movsd - very natural and simple: using intrinsics. Following intrinsics may come handy: __movsb __movsw __movsd
1,137,357
1,137,365
Producing a list of all classes in a C++ project
I'm using Visual Studio 2008 (C++) and would like to produce a list of all classes that are defined in that project. Does anyone know tools that extract those easily? A simple 'Find in files' will not be sufficient, of course. Edit: The list of classes should be created automatically and the result should be a simple file of class names (one class each line).
Doxygen will do that and loads more. Its a really good tool for producing all sorts of documentation
1,137,480
1,137,577
(Visual) C++ project dependency analysis
I have a few large projects I am working on in my new place of work, which have a complicated set of statically linked library dependencies between them. The libs number around 40-50 and it's really hard to determine what the structure was initially meant to be, there isn't clear documentation on the full dependency map. What tools would anyone recommend to extract such data? Presumably, in the simplest manner, if did the following: define the set of paths which correspond to library units set all .cpp/.h files within those to belong to those compilation units capture the 1st order #include dependency tree One would have enough information to compose a map - refactor - and recompose the map, until one has created some order. I note that http://www.ndepend.com have something nice but that's exclusively .NET unfortunately. I read something about Doxygen being able accomplish some static dependency analysis with configuration; has anyone ever pressed it into service to accomplish such a task?
This link leads to: CppDepend
1,137,575
1,137,627
Inline functions vs Preprocessor macros
How does an inline function differ from a preprocessor macro?
Preprocessor macros are just substitution patterns applied to your code. They can be used almost anywhere in your code because they are replaced with their expansions before any compilation starts. Inline functions are actual functions whose body is directly injected into their call site. They can only be used where a function call is appropriate. Now, as far as using macros vs. inline functions in a function-like context, be advised that: Macros are not type safe, and can be expanded regardless of whether they are syntatically correct - the compile phase will report errors resulting from macro expansion problems. Macros can be used in context where you don't expect, resulting in problems Macros are more flexible, in that they can expand other macros - whereas inline functions don't necessarily do this. Macros can result in side effects because of their expansion, since the input expressions are copied wherever they appear in the pattern. Inline function are not always guaranteed to be inlined - some compilers only do this in release builds, or when they are specifically configured to do so. Also, in some cases inlining may not be possible. Inline functions can provide scope for variables (particularly static ones), preprocessor macros can only do this in code blocks {...}, and static variables will not behave exactly the same way.
1,137,634
1,138,116
How to draw rows on the bottom of the DataGridView?
I am using a DataGridView with a DataTable as a stack for some values. Something gets recorded into the DataTable rows and then I send them somewhere in a FIFO fashion - it would be very nice to draw the rows in a bottom->up(to stack them up) direction instead of a up->down direction. How can I achieve this since the paint events are only usefull for painting cells/single rows?
Write a custom stack that uses dummy object for empty slots in the stack. The dummy object can be a static object with empty properties. As you fill the stack remove the dummy object and add your new item there. Then use this stack as binding source. The dummy objects at the end of the stack ensure that the first/top rows in the DataGridView Cells are empty. This way you don't need to bother modifying DataGridView behavior.
1,137,732
1,139,014
Setting the model to a QTableWidget
I want to write an application that can access a table in the database. I took QSqlTableModel as model component for the table. The problem with the QTableView is that it seems to have no method that returns the currently selected record in the table so i took the QTableWidget class which interhits QTableView. But when i try to set the model to this table widget with ->setModel() i get the following error message: c:/Qt/qt/include/QtGui/../../src/gui/itemviews/qtablewidget.h:337: error: `virtual void QTableWidget::setModel(QAbstractItemModel*)' is private. The message says that the method "setModel" is private. Looking into the documentation tells me that it is public. What can I do?
As others have noted, it's not QTableWidget that you want. It's indeed QTableView. Getting the records is then done like this: static QList<QSqlRecord> selected_records( const QTableView * tv ) { // make sure we're really dealing with what we think we're dealing with: assert( static_cast<QSqlTableModel*>( tv->model() ) == qobject_cast<QSqlTableModel*>( tv->model() ); const QSqlTableModel * const tm = static_cast<QSqlTableModel*>( tv->model() ); const QModelIndexList mil = tv->selectionModel()->selectedRows(); QList<QSqlRecord> result; Q_FOREACH( const QModelIndex & mi, mil ) if ( mi.isValid() ) result.push_back( tm->record( mi.row() ) ); return result; } If, OTOH, you are working in a slot connected to the - say - clicked(QModelIndex) signal of QTableView (really: QAbstractItemView), then this code is what you want: void slotClicked( const QModelIndex & mi ) { // make sure we're really dealing with what we think we're dealing with: assert( static_cast<QSqlTableModel*>( tableView->model() ) == qobject_cast<QSqlTableModel*>( tableView->model() ); const QSqlRecord rec = static_cast<QSqlTableModel*>( tableView->model() ) ->record( mi.row() ); // use 'rec' } Yes, Qt could have that built-in, and esp. QSqlTableModel could have a more convenient way to map a QModelIndex back to a QSqlRecord, but there you go.
1,137,765
1,159,110
What is the best library to manage a wiimote?
There are many libraries that manage the wiimote but I am looking for the "best" one, or at least that has the following features: open-source portable (at least Win32 and Linux) written and usable in c or c++ good coverage of wiimote devices I rely on people that already used such library. Google is good source of information but it doesn't know which one is best library.
if you will use multiple wiimotes, don't use wiiuse library. i am working on a stereo system with two wiimotes using wiiuse library but wiiuse made me crazy( it gives delayed ir tracking data ) and i decided to change my library wiiuse from wiiyourself
1,137,966
1,138,045
Displaying the #include hierarchy for a C++ file in Visual Studio
Problem: I have a large Visual C++ project that I'm trying to migrate to Visual Studio 2010. It's a huge mix of stuff from various sources and of various ages. I'm getting problems because something is including both winsock.h and winsock2.h. Question: What tools and techniques are there for displaying the #include hierarchy for a Visual Studio C++ source file? I know about cl /P for getting the preprocessor output, but that doesn't clearly show which file includes which other files (and in this case the /P output is 376,932 lines long 8-) In a perfect world I'd like a hierarchical display of which files include which other files, along with line numbers so I can jump into the sources: source.cpp(1) windows.h(100) winsock.h some_other_thing.h(1234) winsock2.h
There is a setting: Project Settings -> Configuration Properties -> C/C++ -> Advanced -> Show Includes that will generate the tree. It maps to the compiler switch /showIncludes
1,138,023
1,138,032
C++: Multi threading and reference counting
Currently ive got some reference counted classes using the following: class RefCounted { public: void IncRef() { ++refCnt; } void DecRef() { if(!--refCnt)delete this; } protected: RefCounted():refCnt(0){} private: unsigned refCnt; //not implemented RefCounted(RefCounted&); RefCounted& operator = (RefCounted&}; }; I also have a smart pointer class that handles reference counting , all though its not uniformly used (eg in one or two bits of performance critical code, where I minimised the number of IncRef and DecRef calls). template<class T>class RefCountedPtr { public: RefCountedPtr(T *p) :p(p) { if(p)p->IncRef(); } ~RefCountedPtr() { if(p)p->DecRef(); } RefCountedPtr<T>& operator = (T *newP) { if(newP)newP->IncRef(); if(p) p ->DecRef(); p = newP; return *this; } RefCountedPtr<T>& operator = (RefCountedPtr<T> &newP) { if(newP.p)newP.p->IncRef(); if(p) p ->DecRef(); p = newP.p; return *this; } T& operator *() { return *p; } T* operator ->() { return p; } //comparison operators etc and some const versions of the above... private: T *p; }; For the general use of the classes themselves I plan to use a reader/writer locking system, however I dont really want to have to get a writer lock for every single IncRef and DecRef call. I also just thought of a scenario where the pointer may be invalidated just before the IncRef call, consider: class Texture : public RefCounted { public: //...various operations... private: Texture(const std::string &file) { //...load texture from file... TexPool.insert(this); } virtual ~Texture() { TexPool.erase(this); } freind CreateTextureFromFile; }; Texture *CreateTexture(const std::string &file) { TexPoolIterator i = TexPool.find(file); if(i != TexPool.end())return *i; else return new Texture(file); } ThreadA ThreadB t = CreateTexture("ball.png"); t->IncRef(); ...use t... t2 = CreateTexture("ball.png");//returns *t ... thread suspended... t->DecRef();//deletes t ... ... t2->IncRef();//ERROR So I guess I need to change the ref counting model entirely, the reason I added a ref after the return in the design was to support things like the following: MyObj->GetSomething()->GetSomethingElse()->DoSomething(); rather than having to: SomeObject a = MyObj->GetSomething(); AnotherObject *b = a->GetSomethingElse(); b->DoSomething(); b->DecRef(); a->DecRef(); Is there a clean way for fast reference counting in c++ in a multi threaded environment?
Make the reference counting atomic and you won't need any lock. In Windows ::InterlockedIncrement and ::InterlockedDecrement can be used. In C++ 0x, you have atomic<>.
1,138,071
1,138,094
Can you make autocompletion kick in automatically for C++ in VS2008?
I'm using Visual Studio 2008 and I have been wondering why doesn't the autocompletion of Visual Studio kicks in automatically every time I start typing something in C++, unlike C#. It does show me the list member box when I use the "." or "->" operator but not when I start typing randomly. I can make it appear using alt + right arrow but it's not nearly as efficient as just displayer the list member box automatically. Could it be because of something I did or is it like this for C++? Thanks in advance! P.S. It's for a WIN32 console application. Edit : Basically, I'm wondering if there is a way to make the list member box appear right when I start typing instead of having to do alt + right arrow.
Autocompletion in C++ is much more complicated to achieve, and Microsoft, despire improvement with each new versions, didn't nail it. Use a plugin like Visual Assist X to get a nice working autocompletion in VC++.
1,138,170
1,138,299
Use libraries compiled with visual studio in an application compiled by g++ (mingw)
Is it possible to use a library compiled by visual studio in an application compiled by g++ (mingw) on Windows?
If the library is written in C++ and exposes a C++ interface: no (because the name-mangling differs between g++ and VC++). If the library is a static library written in C (or with an extern "C" interface): yes, but certain caveats apply. If the library is a DLL with a C interface: yes, but you'll have to create your own import library.
1,138,503
1,138,516
Good C/C++ connector library for PostgreSQL
My application is a commercial GIS C++ application, and I'm looking for a robust/easy to use connector for Postgresq. (Side note: I also plan to use PostGIS) Does anyone have any recommendations based on your experience? A plus would be if you have tried out various ones. I have looked at: Postgres's C client pqxx QSql EDIT Also, does anyone know what's a good admin GUI tool? I see a community list here. But there are so many! I'm developing on Windows, and dont mind paying for commercial tools. Someone in another Stackoverflow post suggested Maestro.
libpq++ is one provide very good connector for PostgreSQL SQLAPI++ is a C++ library for accessing multiple SQL databases (Oracle, SQL Server, DB2, Sybase, Informix, InterBase, SQLBase, MySQL, PostgreSQL and ODBC, SQLite). Abstract Database Connector is a C/C++ library for making connections to several databases (MySQL, mSQL, PostgreSQL, Interbase, Informix, BDE, ODBC). It runs on Linux, UNIX, BeOS, and Windows, and a dynamic driver loader for ELF OSes is under development Navicat is Nice GUI tool for PostgrSQL
1,138,724
1,138,738
How to set a range of elements in an stl vector to a particular value?
I have a vector of booleans. I need to set its elements from n-th to m-th to true. Is there an elegant way to do this without using a loop? Edit: Tanks to all those who pointed out the problems with using vector<bool>. However, I was looking for a more general solution, like the one given by jalf.
std::fill or std::fill_n in the algorithm header should do the trick. // set m elements, starting from myvec.begin() + n to true std::fill_n(myvec.begin() + n, m, true); // set all elements between myvec.begin() + n and myvec.begin() + n + m to true std::fill(myvec.begin() + n, myvec.begin() + n + m, true);
1,138,843
1,143,244
GLib-GObject-CRITICAL warnings
I'm confused by these two warnings. Can anyone explain how I might have come about triggering them, and how they would be able to be debugged in gdb? (gtkworkbook:24668): GLib-GObject-CRITICAL **: g_cclosure_new: assertion `callback_func != NULL' failed (gtkworkbook:24668): GLib-GObject-CRITICAL **: g_signal_connect_closure_by_id: assertion `closure != NULL' failed
I found the problem. This code was ported from an original implementation in C, and I had a requirement before to use an array of function pointers to call the functions inside of a shared library. Although this [seemed] to work at the time once I actually started using them it was not the case. I am a little stumped on why its not working, but I was able to centralized the problem to the following piece of code. gtk_signal_connect (GTK_OBJECT (plugin()->workbook()->gtk_workbook), "switch-page", (GtkSignalFunc)this->signals[NOTEBOOK_SWITCHPAGE], plugin->workbook()); Was changed to the following: gtk_signal_connect (GTK_OBJECT (plugin()->workbook()->gtk_workbook), "switch-page", (GtkSignalFunc)signal_gtknotebook_switchpage, plugin->workbook()); Now, the code compiles and I am not getting any nasty errors. I think this is the answer!
1,138,930
1,138,933
Error ping sound using Visual C++ and MFC
Is there a basic function call in MFC that simply plays the input error ping? I am looking for something analogous to the AfxMessageBox() call that simply plays the ping that is frequently heard when an error is made.
Look for MessageBeep.
1,138,980
1,142,504
Native API window designer
Why isn't there a designer for native api forms in Visual Studio? Similar to Delphi? If there exist some programs, tools etc, please advice. What is the best approach to design complex windows in pure API?
That's probably because there is no standard way of doing control layouts in WinAPI, you have to manage it by yourself. There is no base "Control" class in WinAPI - everything is a Window of some sort, so no way to support their differences with a common layout editor/designer. You can however create your window layout in a dialog and make it resizable by yourself or using methods published on codeproject (this or this - both are MFC-related, but that's fairly easy to translate). Or adapt ScreenLib to your desktop needs.
1,139,063
1,139,083
Namespace Clashing in C++
I cannot understand why this piece of code does not compile: namespace A { class F {}; // line 2 class H : public F {}; } namespace B { void F(A::H x); // line 7 void G(A::H x) { F(x); // line 9 } } I am using gcc 4.3.3, and the error is: s3.cpp: In function ‘void B::G(A::H)’: s3.cpp:2: error: ‘class A::F’ is not a function, s3.cpp:7: error: conflict with ‘void B::F(A::H)’ s3.cpp:9: error: in call to ‘F’ I think that because in line 9 there is no namespace prefix, F(x) should definitively mean only B::F(x). The compiler tries to cast x into its own superclass. In my understanding it should not. Why does it do that?
That's because compiler will search function in the same namespace its arguments from. Compiler found there A::F identifier but it is not a function. In result you'll get the error. It is standard behaviour as far as I can remember. 3.4.2 Argument-dependent name lookup When an unqualified name is used as the postfix-expression in a function call (5.2.2), other namespaces not considered during the usual unqualified lookup (3.4.1) may be searched, and namespace-scope friend function declarations (11.4) not otherwise visible may be found. These modifications to the search depend on the types of the arguments (and for template template arguments, the namespace of the template argument). For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero or more associated classes to be considered. The sets of namespaces and classes is determined entirely by the types of the function arguments (and the namespace of any template template argument). Typedef names and using-declarations used to specify the types do not contribute to this set. The sets of namespaces and classes are determined in the following way... This rule allows you to write the following code: std::vector<int> x; // adding some data to x //... // now sort it sort( x.begin(), x.end() ); // no need to write std::sort And finally: Because of Core Issue 218 some compilers would compile the code in question without any errors.
1,139,067
1,139,281
pdCurses use in Windows, messes with 3 gcc macros
I am making a very simple platform independent(at least that's the plan) console app. I changed from conio.h to pdCurses to make it happen. The problem with that is that in Windows, using Codeblocks and gcc I have a problem. When I include I get tons of errors. They all concern 3 macros all located in different source files inside: CodeBlocks\MinGW\bin..\lib\gcc\mingw32\3.4.5........\include\c++\3.4.5\bits\ If I undef those 3 macros like this: #include <curses.h> #undef move #undef erase #undef clear then all compiles well. If I don't undef then I get tons of errors about these macros. Example errors are: macro "move" passed 3 arguments, but takes just 2| \bits\char_traits.h|185|error: invalid function declaration| \bits\basic_string.h|604|error: expected `)' before '->' token| \bits\basic_string.h|1039|macro "erase" passed 2 arguments, but takes just 0| Anyone has any idea why this happens? And any not so damn ugly way to correct the problem? Thanks in advance for your input. Edit: I am also getting undefined references to various things whenever I invoke any pdcurses functions. I can not understand why. I definitely linked the library correctly. For example by trying to echo a char on the screen I get: main.cpp|74|undefined reference to `__imp__SP'| main.cpp|74|undefined reference to `__imp__stdscr'| main.cpp|74|undefined reference to `__imp__stdscr'| Can it be anything other than bad linking of the library? And how can I see what's wrong with the linking of pdcurses fromthe above errors? -Lefteris
For the macro problem, do a search for "STL" in the curses.h file and you should find: #ifdef __cplusplus #ifndef NCURSES_NOMACROS /* these names conflict with STL */ #undef box #undef clear #undef erase #undef move #undef refresh #endif /* NCURSES_NOMACROS */ Maybe you can find a work around with that. EDIT: In my copy if you #define NCURSES_NOMACROS it will skip defining all the macros. As far as I looked all of them are just convenience macros for the standard screen so you really don't lose any functionality but you have to use the functions that explicitly require the screen variable. Or, I suppose, use your own macros that don't have name clashes.
1,139,345
1,139,420
C++ vector manipulation optimization
I'm trying to optimize the following code below to avoid having to copy and paste and just use SlaveForce and SlavePos properly, which are float[6] type, and baseForce and basePos are vector type: typedef struct _NodeCoord { float coords[6]; } NodeCoord; int main() { ... memcpy(tempNodeCoord.coords, SlaveForce, 6*sizeof(float)); baseForce.push_back(tempNodeCoord); memcpy(tempNodeCoord.coords, SlavePos, 6*sizeof(float)); basePos.push_back(tempNodeCoord); ... } I have tried some test codes. Only this appear to work: std::vector<NodeCoord> tallon; NodeCoord m; memset(m.coords, 0, sizeof(m.coords)); tallon.push_back(m); while this is along the lines of what I want to accomplish, but it doesn't work: std::vector<float[6]> ed; float e[6]; tallon.push_back(e); I also tried writing a "typedef float[6] mytype;" line before the main function, but it doesn't work well either. Is there anything that I can do to eliminate the memcpy function calls (or rather push_back the float[6] variables directly)? Thanks in advance.
In order to be storable in a vector, a type must be copyable and assignable, and C-style arrays are neither. You should instead use another vector, or possibly wrap the array in a struct.
1,139,424
1,139,519
C/C++ rounding up decimals with a certain precision, efficiently
I'm trying to optimize the following. The code bellow does this : If a = 0.775 and I need precision 2 dp then a => 0.78 Basically, if the last digit is 5, it rounds upwards the next digit, otherwise it doesn't. My problem was that 0.45 doesnt round to 0.5 with 1 decimalpoint, as the value is saved as 0.44999999343.... and setprecision rounds it to 0.4. Thats why setprecision is forced to be higher setprecision(p+10) and then if it really ends in a 5, add the small amount in order to round up correctly. Once done, it compares a with string b and returns the result. The problem is, this function is called a few billion times, making the program craw. Any better ideas on how to rewrite / optimize this and what functions in the code are so heavy on the machine? bool match(double a,string b,int p) { //p = precision no greater than 7dp double t[] = {0.2, 0.02, 0.002, 0.0002, 0.00002, 0.000002, 0.0000002, 0.00000002}; stringstream buff; string temp; buff << setprecision(p+10) << setiosflags(ios_base::fixed) << a; // 10 decimal precision buff >> temp; if(temp[temp.size()-10] == '5') a += t[p]; // help to round upwards ostringstream test; test << setprecision(p) << setiosflags(ios_base::fixed) << a; temp = test.str(); if(b.compare(temp) == 0) return true; return false; }
I wrote an integer square root subroutine with nothing more than a couple dozen lines of ASM, with no API calls whatsoever - and it still could only do about 50 million SqRoots/second (this was about five years ago ...). The point I'm making is that if you're going for billions of calls, even today's technology is going to choke. But if you really want to make an effort to speed it up, remove as many API usages as humanly possible. This may require you to perform API tasks manually, instead of letting the libraries do it for you. Specifically, remove any type of stream operation. Those are slower than dirt in this context. You may really have to improvise there. The only thing left to do after that is to replace as many lines of C++ as you can with custom ASM - but you'll have to be a perfectionist about it. Make sure you are taking full advantage of every CPU cycle and register - as well as every byte of CPU cache and stack space. You may consider using integer values instead of floating-points, as these are far more ASM-friendly and much more efficient. You'd have to multiply the number by 10^7 (or 10^p, depending on how you decide to form your logic) to move the decimal all the way over to the right. Then you could safely convert the floating-point into a basic integer. You'll have to rely on the computer hardware to do the rest. <--Microsoft Specific--> I'll also add that C++ identifiers (including static ones, as Donnie DeBoer mentioned) are directly accessible from ASM blocks nested into your C++ code. This makes inline ASM a breeze. <--End Microsoft Specific-->
1,139,430
1,139,448
Accessing Parent Namespace in C++
I've got a scenario like the following: class criterion { // stuff about criteria... }; namespace hex { class criterion : public criterion //does not compile { //This should inherit from the //A hex specific criterion //criterion class in the global namespace }; }; My question is -- how does one inherit from a class in a namspace which is the parent of another namespace? Billy3
Start with "::" For example class criterion : public ::criterion {};
1,139,480
1,139,555
Regex to detect anything that comes after a typedef/class keyword?
I've been playing around with GEdit's syntax highlighting. I love the way that Visual Studio highlight's user created types. I would like to do this for my user created types in C/C++ (eg. typedef's/classes). For example (in C): typedef struct Node *pNode; And an example in C++: class BigNumber { // Class stuff here. }; See the way Node is highlighted differntly from typedef struct (keywords) and *pNode isn't highlighted at all. How can I write a regex to detect that, and highlight all occurrences of Node and BigNumber throughout my current document?
While Regex's will give you good results, they won't ever give you perfect results. Most regex engines do not support the notion of recursion. That is, it cannot match any type of expression which requires counting (matched braces, parens, etc ...). This means it will not be able to match a typedef which points to a function pointer in a reliable fashion. To get perfect matches you really need to write a parser. I think a better approach is to pick the scenarios you care about the most and write regex's which target those specific scenarios. For instance here is a regex which will match typedefs of structs which point to a single name and may or may not have a pointer. "^\s*typedef\s+struct\s+\w+\s+((\*?\s*)\w+)\s*;\s*$"
1,139,510
1,139,736
Can I get proper IDispatch from DISPPARAMS?
I want to get a proper IDispatch pointer then cast it to CMyDispatch pointer and have my way with it later. i.e. in javascript I want to do something like this: var x = external.obj.x; var y = external.obj.y; external.obj.x = y; where x and y are instances of CMyDispatch. CMyDispatch is returned to javascript this way: STDMETHODIMP CMyDispatch::Invoke(DISPID dispIdMember, REFIID, LCID, WORD wFlags, DISPPARAMS* pDispParams, VARIANT* pVarResult, EXCEPINFO*, UINT*) { if( pVarResult ) { CMyDispatch* pDisp = new CMyDispatch(); CComVariant val( pDisp ); val.Detach( pVarResult ); } return S_OK; } In CMyDispatch.Invoke() with DISPATCH_PROPERTYPUT flag I want to get CMyDispatch instance that holds y value. When using the following code, pDispatch is set to some garbage: STDMETHODIMP CMyDispatch::Invoke(DISPID dispIdMember, REFIID, LCID, WORD wFlags, DISPPARAMS* pDispParams, VARIANT* pVarResult, EXCEPINFO*, UINT*) { ASSERT( pDispParams->cArgs == 1 ); ASSERT( VT_DISPATCH == pDispParams->rgvarg[0].vt ); IDispatch* pDisp = ( pDispParams->rgvarg[0].pdispVal ); // <-- garbage CMyDispatch* pDispatch = (CMyDispatch*) pDisp; // <-- garbage return S_OK; } What should I do to get proper CMyDispatch pointer? Thank you.
You really shouldn't, downcasting from an interface to a concrete implementation is the first step on the road to doom. That said, what you are doing should work, unless the javascript and the COM object run in different apartments, and you get a proxy passed to you, instead of the real object. Why do you need to downcast?
1,139,546
1,140,409
An overloaded operator takes function pointer as parameter, how do i retrieve arguments of function pointer
i have an overloaded operator << trying to make it work like this mystream<<hex<<10; i have overloaded method mytream& operator<<(ios_base& (*m) ios_base&) This gets called whenever hex is encountered cause the parameter passed in the method is a function pointer of type same as hex or like some other output manipulators like dec, oct. i have two problems 1) how do i retrieve the parameter the hex would be operating on, in this example 10 2) how do i know that the << operator is being called for hex and not other manipulator function like oct and dec Thanks
1) hex is not operating on the parameter 10. << operators associate left-to-right, which means your code is the same as: (mystream<<hex)<<10; So your overload has to return an object which, when 10 is shifted into it, prints in hex (or if not prints, writes data somewhere). As everyone says, this is done by saving flags in the stream object itself, then returning *this. The reason flags are used is precisely because the "10" is not available yet, since the second << has not been evaluated yet. The first << operator call cannot print anything - it just has to get ready for when the second one is called. 2) hex is a function. It can be compared with other functions: ostream &operator<<(ostream &s, ios_base& (*m)(ios_base &)) { if (m == hex) { } else if (m == oct) { } else if (m == dec) { } } Except you don't normally want to do that, you want the default behaviour, which is something like: ostream &operator<<(ostream &s, ios_base& (*m)(ios_base &)) { return m(s); } (I may be wrong on that, I've never looked at the implementation, but the general idea is that the operator calls the manipulator function, and the manipulator (the clue's in the name) manipulates the stream). std::hex sets the std::ios::hex format flag on its parameter. Then in your operator<<(int) override, if you have one, check the format flags by calling flags(). 3) Manipulators which take paramers are functions too, but their return types are unspecified, meaning it's up to the implementation. Looking at my gcc iomanip header, setw returns _Setw, setprecision returns _Setprecision, and so on. The Apache library does it differently, more like the no-args manipulators. The only thing you can portably do with parameterized manipulators is apply them to an iostream with operator<<, they have no defined member functions or operators of their own. So just like hex, to handle setw you should inherit from std::ios_base, rely on the operator<< implementation provided by your library, then when you come to format your data, examine your own width, precision, etc, using the width(), precision(), etc, functions on ios_base. That said, if for some bizarre reason you needed to intercept the standard operator<< for these manipulators, you could probably bodge something together, along these lines: template <typename SManip> mystream &operator<<(mystream &s, SManip m) { stringstream ss; // set the state of ss to match that of s ss.width(s.width()); ss.precision(s.precision()); // etc ss << m; // set the state of s to match that of ss s.width(ss.width()); s.precision(ss.precision()); // etc return s; } I do consider this a bodge, though. You're not really supposed to interfere with stream manipulators, just let your base class do the work and look up the results.
1,139,793
1,139,882
C++ Template preprocessor tool
Is there a compiler or standalone preprocessor which takes C++ files and runs a template expansion pass, generating new C++ code with expanded template instantiations? I remember such a tool in the mid-90s when templates were still new and experimental, and the preprocessor was a way to do template programming with compilers without native template support. This is a lot more complicated than a macro-processing step since it would likely require parsing and tokenizing the code to understand the contexts. My hope is to use such a tool when writing OpenCL code. OpenCL is C++, but does not support templates. I'm hoping I can write templates, even simple ones like with integer or bool only arguments, and have some tool pre-parse the file and go through and find the use of the templates and expand the invocations and give me new C++ code that the OpenCL compiler can understand. Even a very limited tool could be useful, it does not need to support every template quirk, nor even support multiple modules or anything. The alternative: #define macros everywhere.. uglier, unsafe, less efficient, and less versatile.
Comeau C++ can "compile" C++ to C. This would seem to be close to your goal, as OpenCL does not support C++ – it's much closer to C.
1,140,509
1,140,556
How to Find All Callers of a Function in C++?
I'm refactoring some code in C++, and I want to deprecate some old methods. My current method for finding all of the methods looks like this: Comment out the original method in the source file in which I'm working. Try to compile the code. If a compiler error is found, then make a note comment out the call and try to recompile. Once the compile has completed successfully, I've found all of the calls. This totally sucks. I've also tried grepping source for the name of the function calls, but I sometimes run into problems with functions of the same name with different arguments, so my compilation makes the C++ compiler resolve the names for me. I've found this question for C#, but my code base is entirely implemented in C++. Is there a better way to find all of the callers of a class method or function in C++? I'm using GCC on Unix systems, but cross-platform solutions would be superlative.
GCC allows you to decorate variables, functions, and methods with __attribute__((deprecated)), which will cause a warning on all callsites (unless -Wno-deprecated-declarations is given). class A { public: A() __attribute__((deprecated)) {} }; int main() { A a; } $ g++ test.c test.cc: In function ‘int main()’: test.cc:6: warning: ‘A::A()’ is deprecated (declared at test.cc:3)
1,140,630
1,140,635
Is there any way to pass an anonymous array as an argument in C++?
I'd like to be able to declare an array as a function argument in C++, as shown in the example code below (which doesn't compile). Is there any way to do this (other than declaring the array separately beforehand)? #include <stdio.h> static void PrintArray(int arrayLen, const int * array) { for (int i=0; i<arrayLen; i++) printf("%i -> %i\n", i, array[i]); } int main(int, char **) { PrintArray(5, {5,6,7,8,9} ); // doesn't compile return 0; }
If you're using older C++ variants (pre-C++0x), then this is not allowed. The "anonymous array" you refer to is actually an initializer list. Now that C++11 is out, this can be done with the built-in initializer_list type. You theoretically can also use it as a C-style initializer list by using extern C, if your compiler parses them as C99 or later. For example: int main() { const int* p; p = (const int[]){1, 2, 3}; }
1,140,693
1,140,733
Setup Gedit For C++ Development
I'm starting in C++ development, but i like to use Gedit for writing the files, but like for Ruby on Rails and many other languages, are some tools and configurations for Gedit that makes develop more easy and comfortable, and another question, what is the best for C++, SVN, CVS, Git and others...? Thanks, and sorry about my english!
For editing you can choose: just an editor - vi(m), emacs, etc. Here I prefer vim. But if you're not familiar with it you may be shocked at the begging. These give posibility also run make from within the editor itself. IDE - KDevelop, Eclipse (+ CDT - plugin for C++), Code::Blocks. I didn't used by these, but heard from colleagues that KDevelop is ok, while Eclipse is too have ans slow. As for source control the choice is between SVN (this is right successor of CVS) and git. If you develop alone or it's not big team of developers SVN should be fine. It uses central repository to store the data. git in contrast is distributed source control tool. I found it pretty complicated to used to. So if you don't need "distributed" feature of git, choose SVN.
1,140,714
1,210,018
Is there a way to get non-locking stream insertion/extraction on basic_iostream in Windows?
I'm a C++ developer who has primarily programmed on Solaris and Linux until recently, when I was forced to create an application targeted to Windows. I've been using a communication design based on C++ I/O stream backed by TCP socket. The design is based on a single thread reading continuously from the stream (most of the time blocked in the socket read waiting for data) while other threads send through the same stream (synchronized by mutex). When moving to windows, I elected to use the boost::asio::ip::tcp::iostream to implement the socket stream. I was dismayed to find that the above multithreaded design resulted in deadlock on Windows. It appears that the operator<<(std::basic_ostream<...>,std::basic_string<...>) declares a 'Sentry' that locks the entire stream for both input and output operations. Since my read thread is always waiting on the stream, send operations from other threads deadlock when this Sentry is created. Here is the relevant part of the call stack during operator<< and Sentry construction: ... ntdll.dll!7c901046() CAF.exe!_Mtxlock(_RTL_CRITICAL_SECTION * _Mtx=0x00397ad0) Line 45 C CAF.exe!std::_Mutex::_Lock() Line 24 + 0xb bytes C++ CAF.exe!std::basic_streambuf<char,std::char_traits<char> >::_Lock() Line 174 C++ CAF.exe!std::basic_ostream<char,std::char_traits<char> >::_Sentry_base::_Sentry_base(std::basic_ostream<char,std::char_traits<char> > & _Ostr={...}) Line 78 C++ CAF.exe!std::basic_ostream<char,std::char_traits<char> >::sentry::sentry(std::basic_ostream<char,std::char_traits<char> > & _Ostr={...}) Line 95 + 0x4e bytes C++ > CAF.exe!std::operator<<<char,std::char_traits<char>,std::allocator<char> >(std::basic_ostream<char,std::char_traits<char> > & _Ostr={...}, const std::basic_string<char,std::char_traits<char>,std::allocator<char> > & _Str="###") Line 549 + 0xc bytes C++ ... I would be fine if the istream and ostream components were locked separately, but that is not the case. Is there an alternate implementation of the stream operators that I can use? Can I direct it not to lock? Should I implement my own (not sure how to do this)? Any suggestions would be appreciated. (Platform is Windows 32- and 64-bit. Behavior observed with Visual Studio 2003 Pro and 2008 Express)
This question has languished for long enough. I'm going to report what I ended up doing even though there's a chance I'll be derided. I had already determined that the problem was that two threads were coming to a deadlock while trying to access an iostream object in separate read and write operations. I could see that the Visual Studio implementation of string stream insertion and extraction operators both declared a Sentry, which locked the stream buffer associated with the stream being operated on. I knew that, for the stream in question for this deadlock, the stream buffer implementation was boost::asio::basic_socket_streambuf. I inspected the implementation to see that read and write operations (underflow and overflow) actually operate on different buffers (get vs. put). With the above verified, I chose to simply circumvent the locking for this application. To do that, I used project-specific pre-processor definitions to exclude the locking code in the basic_istream implementation of the locking sentry: class _Sentry_base { // stores thread lock and reference to input stream public: __CLR_OR_THIS_CALL _Sentry_base(_Myt& _Istr) : _Myistr(_Istr) { // lock the stream buffer, if there #ifndef MY_PROJECT if (_Myistr.rdbuf() != 0) _Myistr.rdbuf()->_Lock(); #endif } __CLR_OR_THIS_CALL ~_Sentry_base() { // destroy after unlocking #ifndef MY_PROJECT if (_Myistr.rdbuf() != 0) _Myistr.rdbuf()->_Unlock(); #endif } Upside: It works Only my project (with the appropriate defines) is affected Downside: Feels a little hacky Each platform where this is built will need this modification I plan to mitigate the latter point by loudly documenting this in the code and project documentation. I realize that there may be a more elegant solution to this, but in the interest of expediency I chose a direct solution after due diligence to understand the impacts.
1,140,909
1,140,916
Error When Compiling C++ File In GCC
I'm using Linux Ubuntu Intrepid Ibex and using as compiler the gcc, but when I try to compile a C++ project file, the compiler give me this error: ubuntu@ubuntu-laptop:~/C++$ gcc ClientFile.cpp gcc: error trying to exec 'cc1plus': execvp: No such file or directory What is wrong?
Do you have the build suite installed? sudo apt-get --reinstall install build-essential and compile C++ code with g++ command, not gcc.
1,140,968
1,141,431
std::auto_ptr Compile Issue in Visual Studio 6.0
Update: Edited code example to use AutoA for the workaround (which was the original intention). Realized this after seeing rlbond's answer. I am trying to incorporate the usage of auto_ptr in my code based on recommendations from this thread: Express the usage of C++ arguments through method interfaces However, I am receiving some unexpected compile errors when compiling with Visual Studio 6.0. It has a problem when dealing with assignments/copies of a std::auto_ptr of a derived type to a std::auto_ptr of the base type. Is this an issue specific to my compiler? I know there's a strong recommendation to use Boost, but on my project it is not an option. If I still want to use auto_ptr, am I forced to use the workaround of calling std::auto_ptr::release()? From what I have encountered so far, this issue results in a compiler error, so it's easy enough to catch. However, could adopting the convention of calling release to assign to a 'auto_ptr' of base type throughout expose me to any maintenance issues? Especially if built with a different compiler (assuming other compilers don't have this issue). If the release() workaround is not good due to my circumstances, should I fall back on using a different convention for describing transfer of ownership? The following is an example illustrating the problem. #include "stdafx.h" #include <memory> struct A { int x; }; struct B : public A { int y; }; typedef std::auto_ptr<A> AutoA; typedef std::auto_ptr<B> AutoB; void sink(AutoA a) { //Some Code.... } int main(int argc, char* argv[]) { //Raws to auto ptr AutoA a_raw_to_a_auto(new A()); AutoB b_raw_to_b_auto(new B()); AutoA b_raw_to_a_auto(new B()); //autos to same type autos AutoA a_auto_to_a_auto(a_raw_to_a_auto); AutoB b_auto_to_b_auto(b_raw_to_b_auto); //raw derive to auto base AutoB b_auto(new B()); //auto derive to auto base AutoA b_auto_to_a_auto(b_auto); //fails to compile //workaround to avoid compile error. AutoB b_workaround(new B()); AutoA b_auto_to_a_auto_workaround(b_workaround.release()); sink(a_raw_to_a_auto); sink(b_raw_to_b_auto); //fails to compile return 0; } Compile Error: Compiling... Sandbox.cpp C:\Program Files\Microsoft Visual Studio\MyProjects\Sandbox\Sandbox.cpp(40) : error C2664: '__thiscall std::auto_ptr<struct A>::std::auto_ptr<struct A>(struct A *)' : cannot convert parameter 1 from 'class std::auto_ptr<struct B>' to 'struct A *' No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called C:\Program Files\Microsoft Visual Studio\MyProjects\Sandbox\Sandbox.cpp(47) : error C2664: 'sink' : cannot convert parameter 1 from 'class std::auto_ptr<struct B>' to 'class std::auto_ptr<struct A>' No constructor could take the source type, or constructor overload resolution was ambiguous Error executing cl.exe. Sandbox.exe - 2 error(s), 0 warning(s)
The first one is easy: AutoA b_auto_to_a_auto(b_auto); //fails to compile This fails on VC6 since it requires member function templates, something VC6's standard library doesn't support. It compiles on standard-compliant compilers, though. Workaround: AutoA b_auto_to_a_auto( b_auto.release() ); The second one is much more subtle :) sink(b_raw_to_b_auto); //fails to compile This one shouldn't compile on a standards-compliant compiler, because there's an implicit conversion going on. The compiler turns the above into sink( std::auto_ptr<A>( b_raw_to_b_auto ) ); however, sink takes std::auto_ptr<A> by value, so the temporary std::auto_ptr<A> created implicitly by the compiler needs to be copy-constructed into the argument to sink. Now, temporaries like that are rvalues. Rvalues don't bind to non-const references, but std::auto_ptr's "copy constructor" takes it's argument by non-const reference. There you go - compile error. AFAICS this is standards-conforming behaviour. C++-0x "move semantics" will fix that by adding a "copy constructor" that takes an rvalue reference, though I'm not sure how much love std::auto_ptr will still receive in the future, what with std::shared_ptr and all. Workaround for the second one: AutoA tmp( b_raw_to_b_auto/*.release() for VC6*/ ); sink( tmp );
1,140,984
1,141,075
C# component events?
I am attempting to write a C# component which will expose events. The component is to be imported by an unmanaged C++ application. According to a few tutorials I have come up with this code (for the C# side): namespace COMTest { [ComVisible(true), Guid("02271CDF-BDB9-4cfe-B65B-2FA58FF1F64B"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface ITestEvents { void OnTest(); } [ComVisible(true), Guid("87BA4D3A-868E-4233-A324-30035154F8A4")] public interface ITest { void RaiseTest(); } // End of ITest [ComVisible(true), Guid("410CD174-8933-4f8c-A799-8EE82AF4A9F2"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(ITestEvents))] public class TestImplimentation : ITest { public TestImplimentation() { } public void RaiseTest() { if (null != OnTest) OnTest(); } public delegate void Test (); //No need to expose this delegate public event Test OnTest; } } Now my c++ code has a simple: #import "COMTest.tlb" named_guids raw_interfaces_only Which generates a tlh file. This tlh file contains everything but my event (OnTest). What am I doing incorrectly?
COM Event Sinks are pretty evil to the uninitiated. The steps basically are create an outgoing (source) interface Implement an IConnectionPointContainer and IConnectionPoint Interfaces, use these to pass a client implementation of the source Interface The good news is that in the interop namespace there are attributes to help you do this (mostly) automatically (ComSourceInterfacesAttribute) There is a decent example of its usage here.
1,140,995
1,141,006
Build a Linux executable using GCC
I'm using Ubuntu 8.10 (Intrepid Ibex) and compiling C++ files with GCC, but when I compile, gcc makes an a.out file that is the executable. How can I make Linux executables?
That executable is a "Linux executable" - that is, it's executable on any recent Linux system. You can rename the file to what you want using rename a.out your-executable-name or better yet, tell GCC where to put its output file using gcc -o your-executable-name your-source-file.c Keep in mind that before Linux systems will let you run the file, you may need to set its "executable bit": chmod +x your-executable-name Also remember that on Linux, the extension of the file has very little to do with what it actually is - your executable can be named something, something.out, or even something.exe, and as long as it's produced by GCC and you do chmod +x on the file, you can run it as a Linux executable.
1,141,228
1,141,909
Javadoc-like Documentation for C++
Are there similar documentation generation systems like Javadoc, for C++? Javadoc produces nice output; It would be great if you could use something like it in other languages.
There are several tools that works like JavaDoc for C++ The most popular tool is probably doxygen. It can handle JavaDoc-like comments, and also several languages (e.g., C++, C, Java, Objective-C, Python, PHP, C#). It has pretty good support for tweaking the style of the HTML output using CSS (see the users list for example documentations). Two important issues when choosing the documentation system is to make sure that it allows you to Document the entities that you are interested in. Do you want to document the system following the code structure or according to some other module division. Getting the output formatted as you want. It is preferable when the documentation fits in with your general project style. Our experience with doxygen is that it is pretty easy to set up and use, and the resulting output is fairly easy to tweak. Unfortunately, doxygen is not perfect, so in some cases it is necessary to work around quirks or bugs where the doxygen parser breaks down. Be sure to inspect all of your generated documentation carefully.
1,141,270
1,142,748
Using Mono for developing in C++
I am starting to use Mono to develop applications in C# and C++. I wanted to ask you, how is Mono compiling the C++ code? is it using GCC? It is amazing to see that it has the STL containers... Also, can I use the Boost libraries and GSL libraries with Mono? Thanks in advance!!!
I think you must be using MonoDevelop, the IDE, as opposed to Mono itself. Yes, MonoDevelop uses gcc/g++ to compile C/C++ source code, but it is not compiled to CIL - it is compiled to a native binary. If I am understanding correctly, then you should be able to use boost just fine. If, however, you are asking if Mono has support for Mixed-Mode assemblies or executables (e.g. assemblies/exe's that contain both native and .NET CIL), then I am sorry to inform you that this feature is not supported, nor is compiling C++ to pure CIL by Mono.
1,141,408
1,141,438
Runtime error, possible input problem?
I have a book class that takes title, author, copyright, ISBN number, and checkout for a book object. However, I'm getting a runtime error when the program runs. After the user inputs the title and presses enter, the program skips down, showing the rest of the outputs, and then terminates the program giving a runtime error. I tried to catch an exception, but I didn't get anything. Code: #include "std_lib_facilities.h" class Book{ public: string what_title(); string what_author(); int what_copyright(); void store_ISBN(); void is_checkout(); private: char check; int ISBNfirst, ISBNsecond, ISBNthird; char ISBNlast; string title; string author; int copyright; }; string Book::what_title() { cout << "Title: "; cin >> title; cout << endl; return title; } string Book::what_author() { cout << "Author: "; cin >> author; cout << endl; return author; } int Book::what_copyright() { cout << "Copyright Year: "; cin >> copyright; cout << endl; return copyright; } void Book::store_ISBN() { bool test = false; cout << "Enter ISBN number separated by spaces: "; while(!test){ cin >> ISBNfirst >> ISBNsecond >> ISBNthird >> ISBNlast; if((ISBNfirst || ISBNsecond || ISBNthird)<0 || (ISBNfirst || ISBNsecond || ISBNthird)>9) error("Invalid entry."); else if(!isdigit(ISBNlast) || !isalpha(ISBNlast)) error("Invalid entry."); else test = true;} } void Book::is_checkout() { bool test = false; cout << "Checked out?(Y or N): "; while(!test){ cin >> check; if(check = 'Y') test = true; else if(check = 'N') test = true; else error("Invalid value.");} } int main() { Book one; one.what_title(); one.what_author(); one.what_copyright(); one.store_ISBN(); one.is_checkout(); keep_window_open(); } Not sure what the problem could be. Any help is appreciated, thanks. Output example: Title: One Flew Over the Cuckoo's Nest (next lines aren't actually spaced in between and all output at once) Author: Copyright Year: Enter ISBN number separated by spaces: This application has requested the Runtime to terminate it in an unusual way. Please contact support for more information. Also don't worry about the keep_window_open and error functions. They are part of the std_lib_facilities.h and are most likely not causing the problem. Error just outputs an error message if a problem is encountered.
The problem here is that the C++ input streams do not remove malformatted input that they encounter. In other words if you try to read in a number and the stream contains, for example the character 'x' (not a number), that character isn't removed from the input stream. Additionally, if I remember correctly, that will also put the input stream in an error state causing well-formatted input to also fail. Although there is a mechanism for testing the state of the input stream and removing malformattted input and clearing the error flags, I have personally found it simpler to always read into a string (using ">>" or "getline") and then to parse the string. In the case of a number, for example, you can use the "strtol" or "strtoul" functions.
1,141,514
1,141,552
use operators in templates in c++
I am trying to implement a List class using pointers and am trying to implement a function LOCATE(T x) where T is for the template and returns the first position of the element x if found, else returns last position + 1. My functions code is template<class T> int List<T>::locate(T n) const { int size = end(); Node<T> * p = head_; for (int i = 0; i < size; i++) { if (p->data() == n) // fails on this line return i; p = p->link(); } return size; // if no match found } I initialise my list with T as string as List<string> myList; but I get an error message 'bool std::operator ==(const std::istreambuf_iterator<_Elem,_Traits> &,const std::istreambuf_iterator<_Elem,_Traits> &)' : could not deduce template argument for 'const std::istreambuf_iterator<_Elem,_Traits> &' from 'std::string Why is the error coming up even though the '==' operator is defined for the string class? ' The code for Node is template<typename T> class Node { public: // Constructors Node(); Node(T d, Node<T> * l = NULL); //Inspectors T data() const; Node<T> * link() const; // Mutators void data(T d); // assigns new value to Node void link(Node<T> * l); // points this Node to a different one // Destructor ~Node(); private: Node<T> * link_; T data_; }; template<typename T> T Node<T>::data() const { return data_; } template<typename T> Node<T>* Node<T>::link() const { return link_; } The calling code is List<string> test; test.add("abc"); cout << test.locate("abc") << endl;
Try : if( n.compare(p->data()) == 0 ) string::compare documentation As the comments below have noted, operator== should work. Please double check that you have #include <string> using std::string;
1,141,570
1,141,836
Is comeau compiler worth it compared to gcc?
I have been using gcc, g++ for my C, C++ application development till now and have found it to be amazing. But browsing through Stack Overflow I found many members stating that error reporting in Comeau compiler is much more than any other compiler. Is this true? I haven't invested in any commercial release of a compiler. Is it really worth spending money on a commercial release of a C/C++ compiler when gcc, g++ are doing the trick?
My experience with writing C++ is that compiling your code with more than one compiler is a great way to find odd corner-cases in your code. In our case, we've used gcc, Apple gcc, and the Visual Studio compiler cl (which is free). When on Windows, I prefer the cl compiler since it compiles faster (around five times faster for us) and it produces better code (around 30% faster last time I checked). Which compiler produces the fastest code is always dependent on the application though. In our particular case the Intel compiler is not so good at producing fast code contrary to popular opinion, so there is no real incentive to use it. If we had the money to spend, compiling with Comeau would be nice to help with additional checking for standards conformance. Apart from that, I'm happy with the compilers we use.
1,141,652
1,141,663
How can I make only a part of the window transparent? (WIN32)
How can I make for example only a rectangle inside the window have opacity like 50% or something like that and for that part to have the effect of WS_EX_TRANSPARENT so that mouse clicks will go through it?
I do not think it is possible simply by setting WS_EX_TRANSPARENT, but it can be accomplished using two windows, create a window with a hole, using SetWindowRgn, and inside that hole put another transparent window using WS_EX_LAYERED and WS_EX_TRANSPARENT styles.
1,141,887
1,141,896
Routine to check if a given date is summertime or wintertime
Do you know if an API exists for that checking?
GetTimeZoneInformation is what you need. You can call it and inspect the returned value to detect whether daylight saving is on at the moment of call. It also fills a structure that contains rules for switching to daylight saving and from daylight saving. Having this structure filled and any given time in UTC format you can relatively easily compute whether that time corrspongs to daylight saving time or standard time.
1,142,103
1,142,169
How do I load a shared object in C++?
I have a shared object (a so - the Linux equivalent of a Windows dll) that I'd like to import and use with my test code. I'm sure it's not this simple ;) but this is the sort of thing I'd like to do.. #include "headerforClassFromBlah.h" int main() { load( "blah.so" ); ClassFromBlah a; a.DoSomething(); } I assume that this is a really basic question but I can't find anything that jumps out at me searching the web.
There are two ways of loading shared objects in C++ For either of these methods you would always need the header file for the object you want to use. The header will contain the definitions of the classes or objects you want to use in your code. Statically: #include "blah.h" int main() { ClassFromBlah a; a.DoSomething(); } gcc yourfile.cpp -lblah Dynamically (In Linux): #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> int main(int argc, char **argv) { void *handle; double (*cosine)(double); char *error; handle = dlopen ("libm.so", RTLD_LAZY); if (!handle) { fprintf (stderr, "%s\n", dlerror()); exit(1); } dlerror(); /* Clear any existing error */ cosine = dlsym(handle, "cos"); if ((error = dlerror()) != NULL) { fprintf (stderr, "%s\n", error); exit(1); } printf ("%f\n", (*cosine)(2.0)); dlclose(handle); return 0; } *Stolen from dlopen Linux man page The process under windows or any other platform is the same, just replace dlopen with the platforms version of dynamic symbol searching. For the dynamic method to work, all symbols you want to import/export must have extern'd C linkage. There are some words Here about when to use static and when to use dynamic linking.
1,142,209
1,142,225
What if the default parameter value is defined in code not visible at the call site?
I've found some strange code... //in file ClassA.h: class ClassA { public: void Enable( bool enable ); }; //in file ClassA.cpp #include <ClassA.h> void ClassA::Enable( bool enable = true ) { //implementation is irrelevant } //in Consumer.cpp #include <ClassA.h> .... ClassA classA; classA.Enable( true ); Obviously since Consumer.cpp only included ClassA.h and not ClassA.cpp the compiler will not be able to see that the parameter has a default value. When would the declared default value of ClassA::Enable in the signature of the method implementation have any effect? Would this only happen when the method is called from within files that include the ClassA.cpp?
Default values are just a compile time thing. There's no such thing as default value in compiled code (no metadata or things like that). It's basically a compiler replacement for "if you don't write anything, I'll specify that for you." So, if the compiler can't see the default value, it assumes there's not one. Demo: // test.h class Test { public: int testing(int input); }; // main.cpp #include <iostream> // removing the default value here will cause an error in the call in `main`: class Test { public: int testing(int input = 42); }; int f(); int main() { Test t; std::cout << t.testing() // 42 << " " << f() // 1000 << std::endl; return 0; } // test.cpp #include "test.h" int Test::testing(int input = 1000) { return input; } int f() { Test t; return t.testing(); } Test: g++ main.cpp test.cpp ./a.out
1,142,253
1,142,271
Waiting for ShellExecuteEx (Setting access rights on Windows process)
I'm using the ShellExecuteEx function in a C++ program to launch an Uninstall.lnk file. In my program, I'd like to wait for the uninstaller to finish. My first attempt was to set the SEE_MASK_NOCLOSEPROCESS flag in the SHELLEXECUTEINFO structure and then call WaitForSingleObject on the hProcess handle available in the SHELLEXECUTEINFO structure passed to ShellExecuteEx, but that still seemed to return way too early. My current suspicion is that this is because the process launched by ShellExecuteEx (does it launch a new shell?) creates new child processes, but doesn't wait for them. So I'm trying to create a "wait for my child process and all the children it launches" function. To do so, I'm trying to use job objects. I created a job object using CreateJobObject, assigned the process handle returned by ShellExecuteEx to the job and then attempted to wait for the job object. Unfortunately assigning the process to the job failed, and I think this is due to insufficient access rights. Does anybody know how to set the PROCESS_SET_QUOTA and PROCESS_TERMINATE access rights (which are required for AssignProcessToJobObject to succeed, according to the MSDN) on a process handle, or another way to wait for the process launched by ShellExecuteEx to finish? UPDATE: I should point out that I'm also launching other applications, not just Uninstall.lnk. One of them is e.g. a ClickOnce application, which is effectively a simple XML file with the file extension .application.
Vista uses job objects for launching links. Therefor the process you try to assign to another job object might already be assigned. See: this question
1,142,352
1,142,420
is there a way to have midl generate each interface in a separate .h?
I have a bunch of objects that inherit abstracts interfaces generated from an idl file. Each object that use of theses interfaces include the same file interfaces.h which contain all the c++ generated abstract classes that map to the idl interface. Each time I change anything into interfaces.idl every classes that depend on this have to be rebuild since interfaces.h change. Is there a flag or something to tell midl to generate each abstract class in its own .h ?
The only way I can think of is to put each interface in its own IDL file, or divide them into multiple IDLs according to rate-of-change. Then include (or is it #import -- I forget) these interface IDLs into the main library IDL, which will produce the type library, if you need that.
1,142,405
1,142,427
C++ : Will compiler optimize &Variable; away?
In C++ a statement like this is valid: &Variable; IMO it doesn't make any sense, so my question is, if you do this, will it affect the compiled result in any way, or will the compiler optimize it away? Thanks!
It's worth remembering that operator&() might be overloaded for the variable type, have some side effects and optimizing away such statement would change program behaviour. One example is a smart pointer used for controlling the non-C++ objects - _com_ptr_t. It has an overloaded _com_ptr_t::operator&() which checks whether the pointer inside already stores some non-null address. If it turns out that the stored address is non-null it means that the pointer is already attached to some object. If that happens the _com_ptr_t::operator&() disconnects the object - calls IUnknown::Release() and sets the pointer to null. The side effect here is necessary because the typical usage is this: _com_ptr_t<Interface> pointer; // some other code could be here CoCreateInstance( ..., &pointer, ...);// many irrelevant parameters here CoCreateInstance() or other object retrieval code has no idea about C++ and _com_ptr_t so it simply overwrites the address passed into it. That's why the _com_ptr_t::operator&() must first release the object the pointer is attached to if any. So for _com_ptr_t this statement: &variable; will have the same effect as variable = 0; and optimizing it away would change program behaviour.
1,142,502
1,142,555
Saving QPixmap to JPEG failing (Qt 4.5)
I have the following code. QString fileName = QFileDialog::getSaveFileName( this, tr("Output Image file"), (""), tr("PNG (*.png);;JPEG (*.JPEG);;Windows Bitmap (*.bmp);;All Files (*.*)") ); if(fileName != "") { QwtPlot* pPlot = ... QSize size = pPlot->size(); QRect printingRect(QPoint(0, 0), size); QPixmap pixmapPrinter(size); pixmapPrinter.fill(Qt::white); { QPainter painter(&pixmapPrinter); pPlot->print(&painter, printingRect); } bool isOk = pixmapPrinter.save(fileName); if(!isOk) { QString msgText = tr("Failed to write into ") + fileName; QMessageBox::critical(this, tr("Error Writing"), msgText); } } So, the path is like this: - File dialog pops up - users selects format and file - the system draws plot onto QPixmap - Saves QPixmap into the file. It works for PNG and BMP without a problem, but for JPEG, jpg, JPG, etc it fails. I was all over Qt documentation but could not find any details. It should just work. Any ideas? I am using Qt commercial edition, 4.5.1 for Windows. I am using dlls, Qt is not on the path. I just realised that I am linking statically to a classical 3rd party jpeg.lib (The Independent JPEG Group's JPEG software), which is used by other library. Is it possible that a conflict or something arises because of this? Or it is simply that plugin is not loaded properly.
probably it cant find the plugin... you can add library path to project or you can simply put imageformats folder near your binary. imageformats folder is in plugins.. (probably you cant display jpeg images too)
1,142,607
1,142,632
If an operator is overloaded for a C++ class how could I use a default operator instead?
_com_ptr_ has an overloaded operator&() with a side effect. If I have a variable: _com_ptr_t<Interface> variable; How could I retrieve its address (_com_ptr_t<Interface>* pointer) without calling the overloaded operator and triggering the side effect?
I've seen this case pop up in an ISO meeting as it broke some offsetof() macro implementations (LWG 273). The solution: &reinterpret_cast<unsigned char&>(variable)
1,142,643
1,142,696
How do use a std::auto_ptr in a class you have to copy construct?
I have class foo that contains a std::auto_ptr member that I would like to copy construct but this does not appear to be allowed. There's a similar thing for the assignment. See the following example: struct foo { private: int _a; std::string _b; std::auto_ptr< bar > _c; public: foo(const foo& rhs) : _a(rhs._a) , _b(rhs._b) , _c(rhs._c) // error: Cannot mutate rhs._c to give up ownership - D'Oh! { } foo& operator=(const foo& rhs) { _a = rhs._a; _b = rhs._b; _c = rhs._c; // error: Same problem again. } }; I could just declare _c as mutable but I'm not sure this is correct. Does anyone have a better solution? EDIT OK, I'm not getting the kind of answer that I was expecting so I'll be a little more specific about the problem. An object of type foo is created on the stack and passed by value into a container class (not stl) and then goes out of scope. I don't have any control over the container code. (It's actually an active queue implementation, with bugs.) The bar class is a fairly heavyweight parser. It has very poor performance on new and delete so even if it was copy constructable, it would be way too expensive. We can guarantee that when a bar object is created, it will only ever need to be owned in 1 place at a time. In this case it is being passed between threads and deleted when the transaction is completed. This is why I was hoping to use a std::autp_ptr. I am very willing to consider boost smart pointers but I was hoping to guarantee this uniqueness if there is an alternative.
You might want to try following code: foo(const foo& rhs) : _a(rhs._a) , _b(rhs._b) , _c(_rhs._c.get() ? new bar(*_rhs._c.get()) : 0) { } (Assignment operator is similar.) However this will only work if bar is CopyConstructible and if this indeed does what you want. The thing is that both foo objects (_rhs and constructed one) will have different pointers in _c. If you want them to share the pointer then you must not use auto_ptr as it does not support shared ownership. Consider in such case use of shared_ptr from Boost.SmartPtr for example (which will be included in new C++ standard). Or any other shared pointer implementation as this is such a common concept that lots of implementations are available.
1,142,658
1,142,712
C++ template function that uses field present in only some data-types?
Is it possible to have a C++ template function which can access different fields in its input data depending on what type of input data was passed to it? e.g. I have code of the form: typedef struct { int a; int b; }s1; typedef struct { int a; }s2; template <class VTI_type> void myfunc(VTI_type VRI_data, bool contains_b) { printf("%d", VRI_data.a); if(contains_b) // or suggest your own test here printf("%d", VRI_data.b); // this line won't compile if VTI_type is s2, even though s2.b is never accessed } void main() { s1 data1; data1.a = 1; data1.b = 2; myfunc <s1> (data1, true); s2 data2; data2.a = 1; myfunc <s2> (data2, false); } So we want to use field A from many different data types, and that works fine. However, some data also has a field B that needs to be used - but the code which accesses field B needs to be removed if the template knows it's looking at a data type that doesn't contain a field B. (in my example, the structures are part of an external API, so can't change)
To elaborate the suggested use of template specialization: template <class T> void myfunc(T data) { printf("%d", VRI_data.a); } // specialization for MyClassWithB: template <> void myfunc<MyClassWithB>(MyClassWithB data) { printf("%d", data.a); printf("%d", data.b); } However, that requires a specialization per-class, there is no "auto-detection" of b. Also, you repeat a lot of code. You could factor out that "having b" aspect into a helper template. A simple demonstration: // helper template - "normal" classes don't have a b template <typename T> int * GetB(T data) { return NULL; } // specialization - MyClassWithB does have a b: template<> int * GetB<MyClassWithB>(MyClassWithB data) { return &data.b; } // generic print template template <class T> void myfunc(T data) { printf("%d", VRI_data.a); int * pb = GetB(data); if (pb) printf("%d", *pb); }
1,143,115
1,229,647
ReadDirectoryChangesW thinks shortcut is being deleted right after creation
I am using this implementation of ReadDirectoryChangesW to monitor changes to the desktop. My program plans to run some small program when a file is created on the desktop. Now the problem I am running into is when I create a new shortcut via the right click context menu ReadDirectoryChangesW gets a notification saying the file has been created, but right after it gets another notification saying the file has been deleted. I have been running into this problem since Windows Vista. Anyone have any idea what could be wrong? Is there another function I should be using to monitor directory changes specific to Vista and 7? Thanks, Krishna
I managed to resolve this issue. I still don't know why I am getting all those strange ReadDirectyChangesW events but I got my end result so I am leaving this question be. Thanks for all the help.
1,143,262
1,143,272
What is the difference between const int*, const int * const, and int const *?
I always mess up how to use const int*, const int * const, and int const * correctly. Is there a set of rules defining what you can and cannot do? I want to know all the do's and all don'ts in terms of assignments, passing to the functions, etc.
Read it backwards (as driven by Clockwise/Spiral Rule): int* - pointer to int int const * - pointer to const int int * const - const pointer to int int const * const - const pointer to const int Now the first const can be on either side of the type so: const int * == int const * const int * const == int const * const If you want to go really crazy you can do things like this: int ** - pointer to pointer to int int ** const - a const pointer to a pointer to an int int * const * - a pointer to a const pointer to an int int const ** - a pointer to a pointer to a const int int * const * const - a const pointer to a const pointer to an int ... And to make sure we are clear on the meaning of const: int a = 5, b = 10, c = 15; const int* foo; // pointer to constant int. foo = &a; // assignment to where foo points to. /* dummy statement*/ *foo = 6; // the value of a can´t get changed through the pointer. foo = &b; // the pointer foo can be changed. int *const bar = &c; // constant pointer to int // note, you actually need to set the pointer // here because you can't change it later ;) *bar = 16; // the value of c can be changed through the pointer. /* dummy statement*/ bar = &a; // not possible because bar is a constant pointer. foo is a variable pointer to a constant integer. This lets you change what you point to but not the value that you point to. Most often this is seen with C-style strings where you have a pointer to a const char. You may change which string you point to but you can't change the content of these strings. This is important when the string itself is in the data segment of a program and shouldn't be changed. bar is a constant or fixed pointer to a value that can be changed. This is like a reference without the extra syntactic sugar. Because of this fact, usually you would use a reference where you would use a T* const pointer unless you need to allow NULL pointers.
1,143,270
1,143,455
How to concat two or more gzip files/streams
I want to concat two or more gzip streams without recompressing them. I mean I have A compressed to A.gz and B to B.gz, I want to compress them to single gzip (A+B).gz without compressing once again, using C or C++. Several notes: Even you can just concat two files and gunzip would know how to deal with them, most of programs would not be able to deal with two chunks. I had seen once an example of code that does this just by decompression of the files and then manipulating original and this significantly faster then normal re-compression, but still requires O(n) CPU operation. Unfortunaly I can't found this example I had found once (concatenation using decompression only), if someone can point it I would be greatful. Note: it is not duplicate of this because proposed solution is not fits my needs. Clearification edit: I want to concate several compressed HTML pices and send them to browser as one page, as per request: "Accept-Encoding: gzip", with respnse "Content-Encoding: gzip" If the stream is concated as simple as cat a.gz b.gz >ab.gz, Gecko (firefox) and KHTML web engines gets only first part (a); IE6 does not display anything and Google Chrome displays first part (a) correctly and the second part (b) as garbage (does not decompress at all). Only Opera handles this well. So I need to create a single gzip stream of several chunks and send them without re-compressing. Update: I had found gzjoin.c in the examples of zlib, it does it using only decompression. The problem is that decompression is still slower them simple memcpy. It is still faster 4 times then fastest gzip compression. But it is not enough. What I need is to find the data I need to save together with gzip file in order to not run decompression procedure, and how do I find this data during compression.
Look at the RFC1951 and RFC1952 The format is simply a suites of members, each composed of three parts, an header, data and a trailer. The data part is itself a set of chunks with each chunks having an header and data part. To simulate the effect of gzipping the result of the concatenation of two (or more files), you simply have to adjust the headers (there is a last chunk flag for instance) and trailer correctly and copying the data parts. There is a problem, the trailer has a CRC32 of the uncompressed data and I'm not sure if this one is easy to compute when you know the CRC of the parts. Edit: the comments in the gzjoin.c file you found imply that, while it is possible to compute the CRC32 without decompressing the data, there are other things which need the decompression.
1,143,395
1,143,453
File corruption detection and error handling
I'm a newbie C++ developer and I'm working on an application which needs to write out a log file every so often, and we've noticed that the log file has been corrupted a few times when running the app. The main scenarios seems to be when the program is shutting down, or crashes, but I'm concerned that this isn't the only time that something may go wrong, as the application was born out of a fairly "quick and dirty" project. It's not critical to have to the most absolute up-to-date data saved, so one idea that someone mentioned was to alternatively write to two log files, and then if the program crashes at least one will still have proper integrity. But this doesn't smell right to me as I haven't really seen any other application use this method. Are there any "best practises" or standard "patterns" or frameworks to deal with this problem? At the moment I'm thinking of doing something like this - Write data to a temp file Check the data was written correctly with a hash Rename the original file, and put the temp file in place. Delete the original Then if anything fails I can just roll back by just deleting the temp, and the original be untouched.
You must find the reason why the file gets corrupted. If the app crashes unexpectedly, it can't corrupt the file. The only thing that can happen is that the file is truncated (i.e. the last log messages are missing). But the app can't really jump around in the file and modify something elsewhere (unless you call seek in the logging code which would surprise me). My guess is that the app is multi threaded and the logging code is being called from several threads which can easily lead to data corrupted before the data is written to the log.
1,143,936
1,143,958
#pragma once vs include guards?
I'm working on a codebase that is known to only run on windows and be compiled under Visual Studio (it integrates tightly with excel so it's not going anywhere). I'm wondering if I should go with the traditional include guards or use #pragma once for our code. I would think letting the compiler deal with #pragma once will yield faster compiles and is less error prone when copying and pasting. It is also slightly less ugly ;) Note: to get the faster compile times we could use Redundant Include Guards but that adds a tight coupling between the included file and the including file. Usually it's ok because the guard should be based on the file name and would only change if you needed to change in the include name anyways.
I don't think it will make a significant difference in compile time but #pragma once is very well supported across compilers but not actually part of the standard. The preprocessor may be a little faster with it as it is more simple to understand your exact intent. #pragma once is less prone to making mistakes and it is less code to type. To speed up compile time more just forward declare instead of including in .h files when you can. I prefer to use #pragma once. See this wikipedia article about the possibility of using both.
1,144,042
1,144,104
Declare and initialise an array of struct/class at the same time
1. I know that it is possible to initialise an array of structures in the declaration. For example: struct BusStruct { string registration_number; string route; }; struct BusStruct BusDepot[] = { { "ED3280", "70" }, { "ED3536", "73" }, { "FP6583", "74A" }, }; If the structure is changed into a class, like this: class BusClass { protected: string m_registration_number; string m_route; public: // maybe some public functions to help initialisation }; Is it possible to do the same as for the structure (i.e. declare and initialise an array of classes at the same time)? 2. Am I correct to think that it is not possible to declare and initialise vector<BusStruct> or vector<BusClass> at the same time?
Is it possible to do the same as for the structure (i.e. declare and initialise an array of classes at the same time)? Not unless you create a suitable constructor: class BusClass { protected: string m_registration_number; string m_route; public: // maybe some public functions to help initialisation // Indeed: BusClass(string const& registration_number, string const& route) :m_registration_number(registration_number), m_route(route) { } }; Or you make all members public and omit the constructor, in which case you can use the same initialization syntax as for the struct. But i think that's not what you intended. Am I correct to think that it is not possible to declare and initialise vector<BusStruct> or vector<BusClass> at the same time? No it's not possible with current C++. You can however use libraries that make this possible. I recommend Boost.Assign for that. For that, however, your class has to have a constructor, and likewise your struct too - Or you need to create some kind of factory function BusStruct make_bus(string const& registration_number, string const& route) { ... } If you want to keep the struct initializable with the brace enclosed initializer list in other cases.
1,144,088
1,144,159
Buffer Overflow (vs) Buffer OverRun (vs) Stack Overflow
Possible Duplicate: What is the difference between a stack overflow and buffer overflow ? What is the difference between Buffer Overflow and Buffer Overrun? What is the difference between Buffer Overrun and Stack Overflow? Please include code examples. I have looked at the terms in Wikipedia, but I am unable to match with programming in C or C++ or Java.
Think of a buffer as just an array. People often use "overflow" and "overrun" interchangeably for any time you try to reference an index beyond the end of the array, and that's fine. Personally, I make a distinction: A buffer overflow is when you try to put more items in the array than the array can hold. They flow out of the end of the buffer. In other words, it comes from writing. A buffer overrun is when you are iterating over the buffer and keep reading past the end of the array. Your iterator is running through the buffer and keeps going. In other words, it comes from reading. A stack overflow is much different. Most modern programming environments are stack-based, where they use a stack data structure to control program flow. Every time you call a function, a new item is placed on the program's call stack. When the function returns, the item is popped from the stack. When the stack is empty, the program stops. The thing is, this stack has a limited size. It is possible to call too many functions at one time and fill up the stack. At this point you have a stack overflow. The most common way to do this is when a function calls itself (recursion).
1,144,162
1,144,276
unresolved external symbol ...QueryInterface
I have an unmanaged C++ class which has a com map inside of it. EX: BEGIN_COM_MAP (MyClass) COM_INTERFACE_ENTRY(...) END_COM_MAP But now from within the class if I try calling this->QueryInterface I get the following error: unresolved external symbol "public: virtual long __stdcall CTest::QueryInterface(struct _GUID const &,void * *)" (?QueryInterface@CTest@@UAGJABU_GUID@@PAPAX@Z) referenced in function "public: __thiscall CTest::CTest(void)" (??0CTest@@QAE@XZ) But now, if I try and implement a QueryInterface method I get the following error: error C2535: 'HRESULT CTest::QueryInterface(const IID &,void **) throw()' : member function already defined or declared What am I doing wrong?
Thanks for the answers, but the issue in the end seems to of been that I was trying to QueryInterface from the constructor. Once I moved it to a separate method everything worked fine. Does anyone have any docs on why you cannot call QueryInterface from a constructor?
1,144,264
1,144,404
C++: member pointer initialised?
Code sample should explain things: class A { B* pB; C* pC; D d; public : A(int i, int j) : d(j) { pC = new C(i, "abc"); } // note pB is not initialised, e.g. pB(NULL) ... }; Obviously pB should be initialised to NULL explicitly to be safe (and clear), but, as it stands, what is the value of pB after construction of A? Is it default initialised (which is zero?) or not (i.e. indeterminate and whatever was in memory). I realise initialisation in C++ has a fair few rules. I think it isn't default initialised; as running in debug mode in Visual Studio it has set pB pointing to 0xcdcdcdcd - which means the memory has been new'd (on the heap) but not initialised. However in release mode, pB always points to NULL. Is this just by chance, and therefore not to be relied upon; or are these compilers initialising it for me (even if it's not in the standard)? It also seems to be NULL when compiled with Sun's compiler on Solaris. I'm really looking for a specific reference to the standard to say one way or the other. Thanks.
Here is the relevant passage fromt he standard: 12.6.2 Initializing bases and members [class.base.init] 4 If a given nonstatic data member or base class is not named by a mem- initializer-id in the mem-initializer-list, then --If the entity is a nonstatic data member of (possibly cv-qualified) class type (or array thereof) or a base class, and the entity class is a non-POD class, the entity is default-initialized (dcl.init). If the entity is a nonstatic data member of a const-qualified type, the entity class shall have a user-declared default constructor. --Otherwise, the entity is not initialized. If the entity is of const-qualified type or reference type, or of a (possibly cv-quali- fied) POD class type (or array thereof) containing (directly or indirectly) a member of a const-qualified type, the program is ill- formed. After the call to a constructor for class X has completed, if a member of X is neither specified in the constructor's mem-initializers, nor default-initialized, nor initialized during execution of the body of the constructor, the member has indeterminate value.
1,144,399
1,144,427
first function input being skipped after loop
The title is self explanatory. For some reason in the loop in int main(), if the user wants to input another book, the loop skips the input of the first function and goes straight to asking for the author's name. For example: Title: The Lord of the Rings Author: J.R.R. Tolkien Copyright: 1954 Enter ISBN numbered separated by spaces: 1 2 3 x Checked out?(Y or N): Y Are you finished?(Y or N): N // this starts loop over, Y will issue a break Title: // there is actually no space between this line and the next, which there should be Author: // it skips down to this line, not allowing the user to input the title, this cycle continues if the user continues inputting information - always skipping the input for title Code: #include "std_lib_facilities.h" class Book{ public: vector<Book> books; // stores book information Book() {}; // constructor string what_title(); string what_author(); int what_copyright(); void store_ISBN(); void is_checkout(); private: char check; int ISBNfirst, ISBNsecond, ISBNthird; char ISBNlast; string title; string author; int copyright; }; string Book::what_title() { cout << "Title: "; getline(cin,title); cout << endl; return title; } string Book::what_author() { cout << "Author: "; getline(cin,author); cout << endl; return author; } int Book::what_copyright() { cout << "Copyright Year: "; cin >> copyright; cout << endl; return copyright; } void Book::store_ISBN() { bool test = false; cout << "Enter ISBN number separated by spaces: "; while(!test){ cin >> ISBNfirst >> ISBNsecond >> ISBNthird >> ISBNlast; if((ISBNfirst<0 || ISBNfirst>9) || (ISBNsecond<0 || ISBNsecond>9) || (ISBNthird<0 || ISBNthird>9)) error("Invalid entry."); else if(!isdigit(ISBNlast) && !isalpha(ISBNlast)) error("Invalid entry."); else test = true;} cout << endl; } void Book::is_checkout() { bool test = false; cout << "Checked out?(Y or N): "; while(!test){ cin >> check; if(check == 'Y') test = true; else if(check == 'N') test = true; else error("Invalid value.");} cout << endl; } int main() { Book store; char question = '0'; while(true){ store.what_title(); store.what_author(); store.what_copyright(); store.store_ISBN(); store.is_checkout(); store.books.push_back(store); cout << "Are you finished?(Y or N): "; cin >> question; if(question == 'Y') break; else if(question == 'N') cout << endl; else error("Invalid value."); } cout << endl; keep_window_open(); } The header information can be found here if you're interested in functions like keep_window_open() and error(), but it doesn't really pertain to this issue. - http://www.stroustrup.com/Programming/std_lib_facilities.h Any help would be appreciated - thanks.
The following line: cin >> question; reads in the 'Y' or the 'N' character. When you enter the input, you also type a 'return' or 'enter'. That return/enter is still in the buffer. When you get to getline(cin,title); the second time through the loop, that return/enter that is still in the buffer is read in and interpreted as the entire line. What you need to do is either clear the input buffer with cin.flush(); or you need to read in question as a string and not as a character. Here is what your code should look like int main() { Book store; char question = '0'; while(true){ store.what_title(); store.what_author(); store.what_copyright(); store.store_ISBN(); store.is_checkout(); store.books.push_back(store); cout << "Are you finished?(Y or N): "; cin >> question; if(question == 'Y') break; else if(question == 'N') { cout << endl; cin.flush(); } else error("Invalid value."); } cout << endl; keep_window_open(); }
1,144,570
1,147,286
Description of datamodule in dll?
I created a costumer's database program. I have a problem in which I create a data module in a DLL and I compile it but then get some error below. My concept is The data module created in DLL and I insert ADO components in the data module. This data module is used in another form. I created a db grid in the form but it doesn't show the records in db grid. I compile it but get an error below. I very thanks to solve my problem... My English is not good but you try to understand........
The main difference between dll usage and packages is the shared memory model. You can simply put a dbconnection in a package. a datamodule in another one. and the best of all is you can load & unload them at your convenience. Then you have access to this elements by unit usage.
1,144,609
1,145,114
Displaying a video in DirectX
What is the best/easiest way to display a video (with sound!) in an application using XAudio2 and Direct3D9/10? At the very least it needs to be able to stream potentially larger videos, and take care of the fact that the windows aspect ratio may differ from the videos (eg by adding letter boxes), although ideally Id like the ability to embed the video into a 3D scene. I could of course work out a way to load each frame into a texture, discarding/reusing the textures once rendered, and playing the audio separately through XAudio2, however as well as writing a loader for at least one format, ive also got to deal with stuff like synchronising the video and audio components, so hopefully there is an eaier solution available or even a ready made free one with a suitable lisence (commercial distribution in binary form, dynamic linking is fine in the case of say LGPL).
In Windows SDK, there is a DirectShow example for rendering video to texture. It handles audio output too. But there are limitations and I can't honestly call it easy.
1,144,990
1,145,705
__OBJC__ equivalent for Objective-C++
I'm compiling a .mm file (Objective-C++) for an iPhone application, and the precompiled header fails to include the base classes. I tracked it down to the following: #ifdef __OBJC__ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #endif Turns out, __OBJC__ is undefined for mm files, whereas it is defined for standard m files. Is there any other flag I can use instead?
If you invoke gcc with -dM -E it will stop after preprocessing, and list all #defines . This normally how I check what built-in defines are set; however I just tried this with a test .mm file and __OBJC__ is defined for me, so I'm not sure why it isn't defined for you. $ echo "int foo() {};" > tmp.mm $ gcc -dM -E tmp.mm|grep OBJ #define __OBJC__ 1 #define OBJC_NEW_PROPERTIES 1
1,145,022
1,145,058
difference between global operator and member operator
Is there a difference between defining a global operator that takes two references for a class and defining a member operator that takes only the right operand? Global: class X { public: int value; }; bool operator==(X& left, X& right) { return left.value == right.value; }; Member: class X { int value; bool operator==( X& right) { return value == right.value; }; }
One reason to use non-member operators (typically declared as friends) is because the left-hand side is the one that does the operation. Obj::operator+ is fine for: obj + 2 but for: 2 + obj it won't work. For this, you need something like: class Obj { friend Obj operator+(const Obj& lhs, int i); friend Obj operator+(int i, const Obj& rhs); }; Obj operator+(const Obj& lhs, int i) { ... } Obj operator+(int i, const Obj& rhs) { ... }
1,145,048
1,145,056
C/C++ Thread-safety of tmpnam?
I need to use the tmpnam function in C++, but I need to know about its thread safety. Namely, If I have several threads which will each need to acquire a different name for a temporary file, am I guaranteed that each thread will receive a file with a different name?
tmpnam only guarantees that the file did not exist at the time - but it may be created before you can do so yourself. To use it safely, you will ALWAYS need to then attempt to create the file with open (filename, O_CREAT | O_EXCL | O_NOFOLLOW). If this fails due to EEXIST or ELOOP, go back and try a new name. This is particularly important to protect against symlink attacks, where another program creates a symlink from your temp file name to /etc/passwd or some other important file. Also, make sure you do not pass NULL to tmpnam, as the buffer used then is the same for all threads. Another approach which combines these is to use mkstemp() or mkostemp(), which will create the file safely for you. Finally, if you don't need the filename, you can use tmpfile(), which will create a temporary file that will be deleted on close.
1,145,268
1,145,321
STL algorithm for merge with addition
I was using stl::merge to put two sorted collections into one. But my object has a natural key; and a defined addition semantic, so what I am after is a merge_and_sum that would not just merge the two collections into a single N+M length collection, but if the operator== on the object returned true, would then operator+ them. I have implemented it thus template<class _InIt1, class _InIt2, class _OutIt> _OutIt merge_and_sum(_InIt1 _First1, _InIt1 _Last1, _InIt2 _First2, _InIt2 _Last2, _OutIt _Dest ) { // copy merging ranges, both using operator< for (; _First1 != _Last1 && _First2 != _Last2; ++_Dest) { if ( *_First2 < *_First1 ) *_Dest = *_First2, ++_First2; else if ( *_First2 == *_First1) *_Dest = *_First2 + *_First1, ++_First1, ++_First2; else *_Dest = *_First1, ++_First1; } _Dest = copy(_First1, _Last1, _Dest); // copy any tail return (copy(_First2, _Last2, _Dest)); } But was wondering if I have reinvented something that is composable from the other algorithms.
It sounds like your collections are like multisets with duplicates collapsed by your + operator (maybe just summing the multiplicities instead of keeping redundant copies). I assume so, because you're not changing the sorting order when you +, so + isn't affecting your key. You should use your implementation. There's nothing in STL that will do it as efficiently. The closest semantic I can think of is standard merge followed by unique_copy. You could almost get unique_copy to work with a side-effectful comparison operator, but that would be extremely ill advised, as the implementation doesn't promise to only compare things directly vs. via a value-copied temporary (or even a given number of times). Your type and variable names are unpleasantly long ;)
1,145,482
1,145,616
should C++ class "helper functions" be members, free, or anon-namespace free?
So, I have a class. It's a useful class. I like a lot. Let's call it MyUsefulClass. MyUsefulClass has a public method. Let's call it processUsefulData(std::vector<int>&). Now suppose processUsefulData really does two things and I want to refactor it from this: std::vector<int> MyUsefulClass::processUsefulData(std::vector<int>& data) { for (/*...*/) { for (/*...*/) { // a bunch of statements... } } for (/*...*/) { for (/*...*/) { // a bunch of other statements... } } return data; } Now, I want to split these responsibilities and rewrite the code as std::vector<int> MyUsefulClass::processUsefulData(std::vector<int>& data) { doProcessA(data, dataMember_); doProcessB(data, otherDataMember_); return data; } So, I don't know if I should make the two helper functions free functions or member functions, and when each would be appropriate. I also don't know if it's better to make them in an anonymous namespace or not. Does anyone know good times to do this?
Free function / member function I would make them free functions is possible (they do not need access to the internals of the class). If they work on a set of attributes or need access to other members then make it a member function. Access If the code only has sense in this scope, and will not be used from other code then make them private: private if it is a member, or implemented in an unnamed namespace if it is a free function. If other code will benefit from using the code then publish it in the interface. That means making it protected if it is a member or having the free function accessible through a header in a named namespace (or global namespace).
1,145,714
1,145,819
How to catch Ctrl+C key event with Qt when Ctrl is released before 'C'?
I would like to call some custom copy code when the user releases Ctrl+C. When C is released before Ctrl, Qt sends a key event that matches with QKeySequence::Copy. When Ctrl is released before C, the release event does not match. When the key release event comes in with Ctrl, is there a way to see if C is still being held down? When I don't handle Ctrl being released first, the event gets passed along and it does a regular copy, which is exactly what I don't want to happen. bool MyWidget::eventFilter(QObject* object, QEvent* event) { // the text edit box filters its events through here if (object == m_text_edit_box) { if (event->type() == QEvent::KeyPress) { QKeyEvent *key_event = static_cast<QKeyEvent*>(event); if (key_event->matches(QKeySequence::Copy)) { // don't do anything and don't pass along event return true; } } else if (event->type() == QEvent::KeyRelease) { QKeyEvent *key_event = static_cast<QKeyEvent*>(event); if (key_event->matches(QKeySequence::Copy)) { // we only get in here if 'c' is released before ctrl callCustomCopy(); return true; } } } // pass along event return false; }
You could query the letter 'C' and the meta key Ctrl specifically and not rely on key_even->matches(). you can of course in the object where you located the eventfilter on the keydown event store the fact wether the keydown sequence did match copy. This (untested) might work for you, note that the static variable should be a member variable of the class that this is contained in, this just seemed clearer in the context of this example. The exact logic of what you want to accomplish might need more state information to be carried between events. bool MyWidget::eventFilter(QObject* object, QEvent* event) { // Remember state between events static foundCopy = false; // the text edit box filters its events through here if (object == m_text_edit_box) { if (event->type() == QEvent::KeyPress) { QKeyEvent *key_event = static_cast<QKeyEvent*>(event); if (key_event->matches(QKeySequence::Copy)) { foundCopy = true; // don't do anything and don't pass along event return true; } else { foundCopy = false; // This is another sequence, ignore and pass event // Note that this will trigger with ctrl+c+a and others } } else if (event->type() == QEvent::KeyRelease) { QKeyEvent *key_event = static_cast<QKeyEvent*>(event); if (foundCopy) { callCustomCopy(); foundCopy = false; return true; } // This should keep the system copy from triggering if (key_event->matches(QKeySequence::Copy)) { return true; } } } // pass along event return false; } Another way would be to collect the actual state of all the keys pressed at the current time and then when one is released see which ones are still pressed. From a UI point of view please bear in mind that all keyboard actions are performed on press, (e.g. typeing, windows paste), performing actions on release in general might confuse the user, especially when there is a visible result to the action. I can't tell from your example what you are trying to accomplish.
1,145,762
1,145,770
Segfault when calling Gtkmm textBuffer->insert
I'm just learning about gtkmm for c++. I'm having trouble getting a simple TextBuffer to add a new line of text. I have a class called OutputBox which is an HBox with a TextViewer (called messages) and a TextBuffer (called textBuffer) in it. Here is a small chunck of the OutputBox class: OutputBox::OutputBox() { textBuffer = messages.get_buffer(); }; void OutputBox::addText( string newText) { textBuffer->insert(textBuffer->begin(), newText); }; Now I expect that when I pass a string into addText, the new string will be added to the buffer, but instead I get a seg fault. After running it through gdb, I see that the error comes from the gtkmm libraries here: template <class T_CppObject> inline T_CppObject* RefPtr<T_CppObject>::operator->() const { return pCppObject_; } I'm not really sure what this is telling me either. I assume that I'm incorrectly using the class.
I would advise attaching a debugger to see where the fault occurs. If it occurs within GTKmm libraries, then you are probably using the API incorrectly. If it occurs in your code then it will point you in the right direction :)
1,145,768
41,273,028
How can I easily use a COM component in Native Visual C++
I am trying to build an app that uses a COM component in VisualStudio ´05 in native C++. The mix of native and managed desciptions of things in the MSDN totally wrecked my brain. (I think the MSDN is a total mess in that respect) I need a short and simple native C++ sample of code to load my Component and make it usable. I am ok with the compiler creating wrappers and the like. Please don't advise me to use the dialog based MFC example, because it does not work with this component and is in itself a huge pile of c... code. Can this be an issue native com vs managed com? I am totally lost, please give me some bearings... EDIT: Thanks for all the help. My problem is that all I have is a registered dll (actually the OCX, see below) . I (personally) know what the Interface should look like, but how do I tell my program? There are no headers that define IDs for Interfaces that I could use. But I read that the c++ compiler can extract and wrap it up for me. Anyone know how this is done? CLARIFICATION: I have only the OCX and a clue from the documentation of the component, what methods it should expose.
Fully working example (exactly what you need) from my blog article: How to Call COM Object from Visual Studio C++? // https://helloacm.com/how-to-call-com-object-from-visual-studio-c/ #include <iostream> #include <objbase.h> #include <unknwn.h> #include <Propvarutil.h> #import "wshom.ocx" no_namespace, raw_interfaces_only using namespace std; int main() { HRESULT hr; CLSID clsid; CoInitializeEx(nullptr, COINIT_MULTITHREADED); CLSIDFromProgID(OLESTR("WScript.Shell"), &clsid); IWshShell *pApp = nullptr; hr = CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWshShell), reinterpret_cast<LPVOID *>(&pApp)); if (FAILED(hr) || pApp == nullptr) { throw "Cannot Create COM Object"; } int out; VARIANT s; InitVariantFromInt32(0, &s); VARIANT title; InitVariantFromString(PCWSTR(L"title"), &title); VARIANT type; InitVariantFromInt32(4096, &type); BSTR msg = ::SysAllocString(L"Hello from https://helloacm.com"); pApp->Popup(msg, &s, &title, &type, &out); CoUninitialize(); cout << "Out = " << out; return 0; }
1,145,831
1,145,842
get list of numbers from stdin and tokenize them
How would I get a list of numbers from the user and then tokenize them. This is what I have but it doesn't get anything except for the first number: #include <iostream> #include <sstream> #include <vector> #include <string> using namespace std; int main() { string line = ""; cin >> line; stringstream lineStream(line); int i; vector<int> values; while (lineStream >> i) values.push_back(i); for(int i=0; i<values.size(); i++) cout << values[i] << endl; system("PAUSE"); return 0; } Related Posts: C++, Going from string to stringstream to vector Int Tokenizer
I believe cin >> breaks on whitespace, which means you're only getting the first number entered. try: getline(cin, line);
1,145,932
1,146,654
How to override Py_GetPrefix(), Py_GetPath()?
I'm trying to embed the Python interpreter and need to customize the way the Python standard library is loaded. Our library will be loaded from the same directory as the executable, not from prefix/lib/. We have been successful in making this work by manually modifying sys.path after calling Py_Initialize(), however, this generates a warning because Py_Initialize is looking for site.py in ./lib/, and it's not present until after Py_Initialize has been called and we have updated sys.path. The Python c-api docs hint that it's possible to override Py_GetPrefix() and Py_GetPath(), but give no indication of how. Does anyone know how I would go about overriding them?
You could set Py_NoSiteFlag = 1, call PyInitialize and import site.py yourself as needed.
1,146,048
1,146,079
Omitting arguments in C++ Templates
Is it ok to omit the type after the function name when calling a template function? As an example, consider the function below: template<typename T> void f(T var){...} Is it ok to simply call it like this: int x = 5; f(x); Or do I have to include the type? int x = 5; f<int>(x);
Whenever the compiler can infer template arguments from the function arguments, it is okay to leave them out. This is also good practice, as it will make your code easier to read. Also, you can only leave template arguments of the end, not the beginning or middle: template<typename T, typename U> void f(T t) {} template<typename T, typename U> void g(U u) {} int main() { f<int>(5); // NOT LEGAL f<int, int>(5); // LEGAL g<int>(5); // LEGAL g<int, int>(5); // LEGAL return 0; }
1,146,132
1,146,162
How can I read keyboard input to character strings? (C++)
getc (stdin) reads keyboard input to integers, but what if I want to read keyboard input to character strings? #include "stdafx.h" #include "string.h" #include "stdio.h" void CharReadWrite(FILE *fin); FILE *fptr2; int _tmain(int argc, _TCHAR* argv[]) { char alpha= getc(stdin); char filename=alpha; if (fopen_s( &fptr2, filename, "r" ) != 0 ) printf( "File stream %s was not opened\n", filename ); else printf( "The file %s was opened\n", filename ); CharReadWrite(fptr2); fclose(fptr2); return 0; } void CharReadWrite(FILE *fin){ int c; while ((c=fgetc(fin)) !=EOF) { putchar(c);} }
Continuing with the theme of getc you can use fgets to read a line of input into a character buffer. E.g. char buffer[1024]; char *line = fgets(buffer, sizeof(buffer), stdin); if( !line ) { if( feof(stdin) ) { printf("end of file\n"); } else if( ferror(stdin) ) { printf("An error occurerd\n"); exit(0); } } else { printf("You entered: %s", line); } Note that ryansstack's answer is a much better, easier and safer solution given you are using C++.
1,146,160
1,146,336
Use a macro to specialize std::swap
So, I have a macro. // swap_specialize.hpp #include <algorithm> #ifndef STD_SWAP_SPECIALIZE #define STD_SWAP_SPECIALIZE( CLASSNAME ) \ namespace std { \ template<> inline \ void swap( CLASSNAME & lhs, CLASSNAME & rhs ) \ { lhs.swap(rhs); } } #endif So then I have a class // c.hpp #include <vector> #include "swap_specialize.hpp" class C { public: C(); void swap(C& rhs) { data_.swap(rhs.data_); } C& operator=(C rhs) { rhs.swap(*this); return *this; } private: std::vector<int> data_; } STD_SWAP_SPECIALIZE(C) Does the usage of a macro to specialize std::swap in this way follow coding conventions?
I would say it's OK if it increases readability. Judge yourself. Just my two cents: Specializing std::swap isn't really the right way to do this. Consider this situation: my_stuff::C c, b; // ... swap(c, b); // ... This won't find std::swap if you haven't done using std::swap or something similar. You should rather declare your own swap in C's namespace: void swap(C &a, C &b) { a.swap(b); } Now, this will work also in the above case, because argument dependent lookup searches in the namespace of the class. Code swapping generic things where the type isn't known should do it like this: using std::swap; swap(a, b); Regardless of the type, this will use the best matching swap, and fall-back to std::swap if there wasn't a better matching one in the namespaces of a. Hard-coding the call to std::swap will cut too short on types that don't specialize std::swap but rather decide to provide their own swap in their namespace. This is superious in another way: Imagine C is a template. You cannot specialize std::swap in this case. But just defining your own swap, that's perfectly fine. template<typename T> void swap(C<T> &a, C<T> &b) { a.swap(b); } This is the way how the swap for std::string and other classes is implemented too.
1,146,574
1,146,580
How do I code a progress bar for Windows 7 to also update itself on the taskbar?
Windows 7 has an AWESOME new feature that applications can report the progress of the current activity through the status bar. For example, when copying file(s) using Windows Explorer, a progress bar is layered on top of the application icon in the task bar and the progress is shown as it updates. What is the API for exposing the progress bar? Is there MSDN documentation on it?
There's a good article in MSDN magazine about the new taskbar APIs. And yes, the feature is awesome :-) Essentially, it's all about implementing IFileOperation. There's a good article about using it in managed code here.
1,147,053
1,158,598
How to check whether the tlb file is registered in registry using C++?
I have created a class library using c#.And i have registered the class library using regasm.. RegAsm.exe Discovery.dll /tlb: Discovery.dll /codebase Now i want to know whether the assembly is registered or not using c++. I need because I have to check the registry for this dll if it is not registered I have to registered it programatically if it is registered then i simply skip it. so How can i know whether the assembly registered or not using c++...
Why do you need to bother at all? There is no harm to registering it again if it IS already there.
1,147,199
1,147,206
C++ Compiling first time
I will you show my misinterpretation. it says there must be del *.obj in the bat file it says there must be an obj file it says the obj file must actually be a cpp file Please, show me your interpretation. http://computerprogramming.suite101.com/article.cfm/the_borland_win32_compiler_guide Thanks!
Your question's a little confusing but I'll try it out. Typically, you have a group of C++ source files, for example, x.cpp and y.cpp. The compile phase will take these and create, for example, x.obj and y.obj. The link phase will take these and create a single executable, for example, xy.exe. 1/ The reason you would have a "del *.obj" in the batch file is to delete all object files so that the make can recreate them. Make (if you're using intelligent rules in the makefile) will only rebuild things that are needed (an example being that the cpp file will not be compiled to an obj file if the current obj file has a later date than it). Deleting the object file will force a new one to be created. 2/ There doesn't have to be an object file, these are typically created from the c or cpp source files. In addition, you can combine compile and link phases so that no object files are created (or are destroyed pretty quickly once they're finished with). 3/ The object file doesn't have to be a cpp file, but it's usually built from a cpp file with the same base name. Update based on comment: If you want to only specify your application name once, your comments have it like this (I think, the format's not that great as you pointed out): PATH=C:\BORLAND\BCC55\BIN;%PATH% APP=MyApp del *.exe del *.obj del *.res make -f$(APP).mak >err.txt if exist $(APP).exe goto RUN_EXE :EDIT_ERR call notepad.exe err.txt :RUN_EXE call $(APP).exe if exist err.txt delete err.txt :END I think what you need is: PATH=C:\BORLAND\BCC55\BIN;%PATH% set APP=MyApp del *.exe del *.obj del *.res make -f%APP%.mak >err.txt if exist %APP%.exe goto :RUN_EXE :EDIT_ERR call notepad.exe err.txt goto :END :RUN_EXE call %APP%.exe if exist err.txt delete err.txt :END What you have with your "$(APP)" substitutions is something that will work inside a makefile, but not inside a cmd file. There you need to use the %APP% variant to get what you want.
1,147,249
1,147,811
Connecting Catmull-Rom splines together and calculating its length?
I'm trying to create a class which takes in any number of points (position and control) and creates a catmull-rom spline based on the information given. What I'm doing - and I'm really unsure if this is the right way to do it - is storing each individual point in a class like so: class Point { public: Vector3 position; Vector3 control; } Where obviously position is the position of the point and control is the control point. My issue is connecting up the splines - obviously given the above class holding a point in the spline array indicates that any given position can only have one control point. So when having three or more points in a catmull rom spline the various individual catmull-rom splines which are being connected share one position and one control with another such spline. Now with position being the same is required - since I want to create splines which are continuous between themselves. However I really wonder, should the control points also be the same between the two splines? With a bit of fiddling of the control points I can make it appear to be transitioning smoothly from one spline to another however I must emphasize that I'm not sure if the way they are transitioning is consistent with how catmull-rom splines form their shape. I'd much rather do it correctly than sit on my hands and rationalize that it's good enough. Obviously the second part of my question is self explanatory: Given two control and position points how do I calculate the length of a catmull-rom spline?
To define the spline between two control points, the Catmull-Rom spline needs the control points and the tangent vector at each control point. However, the tangent vector at internal (i.e. non-endpoint) control points is defined by the control points on either side of it: T(Pn) = (Pn+1 - Pn-1) / 2. For closed curves, the spline is completely defined by the set of control points. For non-closed curves, you need to also supply the tangent vector at the first and last control point. This is commonly done: T(P0) = P1 - P0 and T(Pn) = Pn - Pn-1. Thus, for closed curves, your data structure is just a list of control points. For general splines, it's a list of points plus the first and last normal vector. If you want to have a cardinal spline, then you can add a weighting factor to the tangent vector calculation as in the Wikipedia article. To calculate the length of such a spline, one approach would be to approximate it by evaluating the spline at many points and then calculating the linear distance between each neighboring pair of points.
1,147,337
1,147,382
Borland Can't Compile, what is going on, I can't even get started
C:\BORLAND\BCC55\BIN>bcc32 hello.cpp Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland hello.cpp: Error E2209 hello.cpp 2: Unable to open include file 'iostream' Error E2090 hello.cpp 6: Qualifier 'std' is not a class or namespace name in fun ction main() Error E2379 hello.cpp 6: Statement missing ; in function main() *** 3 errors in Compile *** I'm veeery sad, you see! :-( @oggy: I read the instructions at Embarcadero. Now, it says... #include <iostream.h> int main(void) { cout << "Hello." << endl; return 0; } C:\Borland\BCC55\Bin\MySource>bcc32 hello.cpp Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland hello.cpp: Error E2209 hello.cpp 1: Unable to open include file 'iostream.h' Error E2451 hello.cpp 4: Undefined symbol 'cout' in function main() Error E2451 hello.cpp 4: Undefined symbol 'end' in function main() Error E2379 hello.cpp 4: Statement missing ; in function main() *** 4 errors in Compile ***
Seriously, you're going to keep having troubles if you continue to use Borland's compiler. It's free from their computer museum for a reason - it's ancient. The copyright line itself should be proof enough of that: Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland Do you really want a compiler that hasn't been updated in decades, one that the standard has long since left behind? It's the compiler you get if you're interested in vintage computing stuff, in the same league as people with TRS-80 and Apple II emulators :-) Download Microsoft Visual C++ Express and install it. It's as free (as in cost) as the Borland one and substantially more up to date. See here for the product page. Or there are many other more up-to-date development tools you can get for free as well, such as gcc, Code::Blocks and so forth.
1,147,455
1,147,533
Is there a tool that enables me to insert one line of code into all functions and methods in a C++-source file?
It should turn this int Yada (int yada) { return yada; } into this int Yada (int yada) { SOME_HEIDEGGER_QUOTE; return yada; } but for all (or at least a big bunch of) syntactically legal C/C++ - function and method constructs. Maybe you've heard of some Perl library that will allow me to perform these kinds of operations in a view lines of code. My goal is to add a tracer to an old, but big C++ project in order to be able to debug it without a debugger.
Try Aspect C++ (www.aspectc.org). You can define an Aspect that will pick up every method execution. In fact, the quickstart has pretty much exactly what you are after defined as an example: http://www.aspectc.org/fileadmin/documentation/ac-quickref.pdf
1,147,601
1,147,622
Show Process In Linux Using C++
I am starting in C++, reading a good book of it and I want to build a program that shows the user all the process that the Linux of he is doing, using C++.
Using the library http://procps.sourceforge.net/ For reading proc entries would be useful. This is how top and others gain access to a list of running process. Also see a similar question: Linux API to list running processes You can also link to the libproc library rather than copying source from procps.
1,147,616
2,967,416
Free SVN repo server without requiring a project
I want to know if there are any free Subversion repository hosting servers where you don't need to have a 'project' to host your C++ files in. I don't have a actual project, but I want to store my C++ in an SVN repository. I am looking for something like OpenSVN where you can upload your C++ files, but it requires you to have a project. Can you recommend a Subversion hosting service where you can upload your files to an account, rather than a project. Something like: http://www.test-svn.com/~nathanpc/
Have you tried Assembla? It's free and you don't need to have a project.
1,147,903
1,147,920
Anonymous Namespace Class Definition
I was looking over some (C++) code and found something like this: //Foo.cpp namespace { void SomeHelperFunctionA() {} void SomeHelperFunctionB() {} void SomeHelperFunctionC() {} //etc... class SomeClass //<--- { //Impl }; } SomeHelperFunction[A-Z] are functions that are only needed in that translation unit, so I understand why they're in an anonymous namespace. Similarly, SomeClass is also only required in that translation unit, but I was under the impression that you could have classes with identical names in different translation units without any sort of naming collisions provided that you didn't have a global class declaration (e.g., in a commonly included header file). I should also mention that this particular translation unit does not include any headers that might declare a class with an identical name (SomeClass). So, given this information, could someone please shed some light on why the original programmer might have done this? Perhaps just as a precaution for the future? I'll be honest, I've never seen classes used in anonymous namespaces before. Thanks!
An anonymous namespace is like the static keyword when it is applied at the global level. An anonymous namespace makes it so you can't call anything inside the namespace from another file. Anonymous namespaces allow you to limit the scope of what's within to the current file only. The programmer would have done this to avoid naming conflicts. No global names will conflict in this way at linking time. Example: File: test.cpp namespace { void A() { } void B() { } void C() { } } void CallABC() { A(); B(); C(); } File: main.cpp void CallABC();//You can use ABC from this file but not A, B and C void A() { //Do something different } int main(int argc, char** argv) { CallABC(); A();//<--- calls the local file's A() not the other file. return 0; } The above will compile fine. But if you tried to write an CallABC() function in your main you would have a linking error. In this way you can't call A(), B() and C() functions individually, but you can call CallABC() that will call all of them one after the other. You can forward declare CallABC() inside your main.cpp and call it. But you can't forward declare test.cpp's A(), B() nor C() inside your main.cpp as you will have a linking error. As for why there is a class inside the namespace. It is to make sure no external files use this class. Something inside the .cpp probably uses that class.
1,147,995
1,147,997
Possible to declare function of enumerated type?
Just wondering if it is possible to declare a function of an enumerated type in C++ For example: class myclass{ //.... enum myenum{ a, b, c, d}; myenum function(); //.... }; myenum function() { //.... }
yes, it is very common to return an enum type. You will want to put your enum outside of the class though since the function wants to use it. Or scope the function's enum return type with the class name (enum must be in a public part of the class definition). class myclass { public: enum myenum{ a, b, c, d}; //.... myenum function(); //.... }; myClass::myenum function() { //.... }
1,148,309
1,148,405
Inverting a 4x4 matrix
I am looking for a sample code implementation on how to invert a 4x4 matrix. I know there is Gaussian eleminiation, LU decomposition, etc., but instead of looking at them in detail I am really just looking for the code to do this. Language ideally C++, data is available in array of 16 floats in column-major order.
here: bool gluInvertMatrix(const double m[16], double invOut[16]) { double inv[16], det; int i; inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10]; inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10]; inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9]; inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9]; inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10]; inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10]; inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9]; inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9]; inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6]; inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6]; inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5]; inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5]; inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6]; inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6]; inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5]; inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5]; det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12]; if (det == 0) return false; det = 1.0 / det; for (i = 0; i < 16; i++) invOut[i] = inv[i] * det; return true; } This was lifted from MESA implementation of the GLU library.
1,148,315
1,148,356
Standard POSIX read shadowed by a read method with different signature
I have a C++ File class with read function, that is supposed to read whole contents of a file (just like Python does) into a buffer. However, when I tried to call read function from unistd.h, I get: file.cpp:21: error: no matching function for call to ‘File::read(int&, char*&, int)’ file.cpp:17: note: candidates are: char* File::read() What am I doing wrong? These have completely different signatures, why can't I simply call it?
Have you tried being explicit about scope; char* File::read() { // Double-colon to get to global scope ::read(...); // .. } ?
1,148,328
1,148,338
Why does this code only print 42?
Could somebody please explain to me why does this code only print "42" instead of "created\n42"? #include <iostream> #include <string> #include <memory> using namespace std; class MyClass { public: MyClass() {cout<<"created"<<endl;}; int solution() {return 42;} virtual ~MyClass() {}; }; int main(int argc, char *argv[]) { auto_ptr<MyClass> ptr; cout<<ptr->solution()<<endl; return 0; } BTW I tried this code with different values in solution and I always get the "right" value, so it doesn't seem to be a random lucky value.
Because it exhibits undefined behaviour - you dereference a null pointer. When you say: auto_ptr<MyClass> ptr; you create an autopointer which doesn't point to anything. This is equivalent to saying: MyClass * ptr = NULL; Then when you say: cout<<ptr->solution()<<endl; you dereference this null pointer. Doing that is undefined in C++ - for your implementation, it appears to work.
1,148,523
1,148,526
Visual C++ Development
I'm learning C++, and know a little bit of Visual Basic and an Delphi. But I want to know, is there some program like Delphi, but for C++. Something where you can drag a button to a form, double click it, the like in Delphi and VB: opens a code editor and you edit the code of the button, but with a similar code of C++? I'm using Windows Vista.
Yes, if you use MFC within Visual Studio. MFC is Visual Studio's C++ class library for writing Windows programs, and for an MFC form Visual Studio behaves exactly as you describe. As of Visual Studio 2008 with an upgrade pack you can create Office 2007 style applications, and Visual Studio style applications, using MFC.
1,148,636
1,148,646
C/C++ an int value that isn't a number?
Can this ever happen ? 3 asserts, where one should activate. int nr = perform_calc(); assert( nr == 0); assert( nr > 0); assert( nr < 0); Can there be a case when the program doesn't activate the asserts on g++ 3.4.4. And no I don't have the possibility to change the code in order to print the number out in case the asserts don't activate. Any ideas? Edit: After reading several comments I was forced to edit. Show the code? why are you doing this stupid thing ? I don't believe it ! Where is it used ? From my question it should have been obvious that I will not post/change the code because of several possible reasons: I'm a total beginner and is ashamed of the code (no crime there, sure it makes answering to the question much easier if I did post it) I was asked to help out a friend with only little information (and no I did not ask him why can't you check the number returned, or why can't he just add a breakpoint). I am writing my code in emacs without any compiler and is sending it to a remote server that compiles it, runs it and only can return failed asserts if something goes wrong. If you believed that I was making a prank or a hoax you should have voted for a closure of the thread instead. I would have been perfectly fine with that. But adding unnecessary comments like this only made me want an "attitude" flag to be implemented. I want to thank others for their comments and answers that actually tried to explain and answered my question.
As I've seen so ugly things in my life, it could be explained if perform_calc() has a buffer overrun that overwrites the return address in the stack. When the function ends, the overwritten address is recovered from the stack and set to the current PC, leading to a jump maybe in another area of the program, apparently past the assertion calls. Although this is a very remote possibility, so it's what you are showing. Another possibility is that someone did an ugly macro trick. check if you have things like #define assert or some colleague put something like this in a header while you were at the restroom #define < == #define > == As suggested in another answer, check with gcc -E to see what code is actually compiled.
1,148,818
1,217,804
Standard or common Arduino library for parsing HTTP requests?
I'm trying to get my Arduino with Arduino Ethernet Shield set up as a server to understand GET and POST requests. I found "Web Server well structured", and could modify it to meet my needs, but does something already exists in C++ that is extremely lightweight and might already be commonly used for Arduinos with Arduinos Ethernet Shields?
I've used Webduino with my Arduino ethernet shield. It handles GET and POST requests, and reads query string parameters.
1,148,885
1,148,905
64-bit library limited to 4GB?
I'm using an image manipulation library that throws an exception when I attempt to load images > 4GB in size. It claims to be 64bit, but wouldn't a 64bit library allow loading images larger than that? I think they recompiled their C libraries using a 64 bit memory model/compiler but still used unsigned integers and failed upgrade to use 64 bit types. Is that a reasonable conclusion? Edit - As an after-thought can OS memory become so fragemented that allocation of large chunks is no longer possible? (It doesn't work right after a reboot either, but just wondering.) What about under .NET? Can the .NET managed memory become so fragmented that allocation of large chunks fails?
It's a reasonable suggestion, however the exact cause could be a number of things - for example what OS are you running, how much RAM / swap do you have? The application/OS may not over-commit virtual memory so you'll need 4GB (or more) of free RAM to open the image. Out of interest does it seem to be a definite stop at the 4GB boundary - i.e. does a 3.99GB image succeed, but a 4GB one fail - you say it does which would suggest a definite use of a 32bit size in the libraries data structures. Update With regards your second question - not really. Pretty much all modern OS's use virtual memory, so each process gets it's own contiguous address space. A single contiguous region in a processes' address space doesn't need to be backed by contiguous physical RAM, it can be made up of a number of separate physical areas of RAM made to look like they are contiguous; so the OS doesn't need to have a single 4GB chunk of RAM free to give your application a 4GB chunk. It's possible that an application could fragment it's virtual address space such that there isn't room for a contiguous 4GB region, but considering the size of a 64-bit address space it's probably highly unlikely in your scenario.
1,149,109
1,149,112
Why does a quoted string match bool method signature before a std::string?
Given the following methods: // Method 1 void add(const std::string& header, bool replace); //Method 2 void add(const std::string& name, const std::string& value); It would appear that the following code will end up calling method 1 instead of method 2: something.add("Hello", "World"); I ended up creating another method that looks like this: //Method 3 void MyClass::add(const char* name, const char* value) { add(std::string(name), std::string(value)); } It worked. So it would seem that when a method accepts a "quoted string" it will match in the following order: const char* bool std::string Why would a quoted string be treated as a bool before a std::string? Is this the usual behavior? I have written a decent amount of code for this project and haven't had any other issues with the wrong method signature being selected...
My guess is the conversion from pointer to bool is an implicit primitive type conversion, where the conversion to std::string requires the call of a constructor and the construction of a temporary.
1,149,244
1,149,302
Using a friend class vs. adding accessors for unit testing in C++?
Is it better to add functions that return the internal state of an object for unit testing, as opposed to making the testing class a friend? - especially, when there is no use for the functions except for the case of unit testing.
Unit tests should 95% of the time only test the publicly exposed surface of a class. If you're testing something under the covers, that's testing implementation details, which is inherently fragile, because you should be able to easily change implementation and still have the tests work. Not only is it fragile, but you could also be tempted into testing things that aren't actually possible in planned usage scenarios, which is a waste of time. If the point of the accessors you want to add is just to test whether the function had the desired effect, your class design may violate another principle, which is that a state-machine-like class should always make it clear what state its in, if that affects what happens when people interact with the class. In that case, it'd be right to provide those read-only accessors. If it doesn't affect the class's behavior, refer back to my previous bit about implementation details. And as you rightly said, cluttering up the public surface of a class with unused stuff is also undesirable for its own reasons. If I had to pick between accessors and friending in your case, I would choose friending, simply because you own your test and can change it in a pinch. You may not own the code by the clown who finds a way to use your extra accessors, and then you'll be stuck.
1,149,543
1,149,562
Explain the following from Accelerated C++ please
I don't understand the following excerpt from Accelerated C++: Starting at Because || is left-associative, and because of the relative precedence of ||,== ,and -, r == 0 || r == rows - 1 || c == 0 || c == cols - 1 means the same as it would if we were to place all of its subexpressions in parentheses: ((r == 0 || r == (rows - 1)) || c == 0) || c == (cols - 1) and going until Otherwise, it does something else, which we must now define. I don't understand this. How would you tell me the same with your own words?
If you have a series of conditions you want to evaluate, let's say "if x is 1 or y is 2, then call function foo()" then there is no point in performing the second test (y is 2) if you already know that x is 1. The || operator works like that: i( x == 1 || y == 2 ) { foo(); } The expression y == 2 will not be evaluated if x == 1, because it is not necessary. This is called short circuited evaluation, and can save a lot of time if evaluation is expensive. If this isn't what you are asking about, please make your question more explicit.