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 di...
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>::...
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...
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 ...
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 tim...
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...
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; s...
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 ...
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 wa...
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 increme...
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 ...
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 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 movs...
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 f...
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 ...
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 ...
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 p...
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 r...
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...
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->m...
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 i...
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 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(RefC...
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 al...
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 o...
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 QSq...
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...
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_c...
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 o...
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...
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 err...
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 postf...
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...
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 c...
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, SlaveF...
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......
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 go...
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 ...
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 ...
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 ...
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...
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 downc...
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 manip...
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 fla...
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 com...
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 ...
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()’:...
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<arrayLe...
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 compil...
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 ab...
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 hear...
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 ...
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 th...
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 r...
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 muc...
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(ComInterface...
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 attribut...
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 syste...
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 ex...
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 h...
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 e...
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 a...
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 =...
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 compil...
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 fa...
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 yo...
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(); } ...
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.DoSometh...
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 ); Obvio...
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: ...
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 ...
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 depe...
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 wh...
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...
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) ...
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 ...
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 c...
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 spec...
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 sayin...
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 * cons...
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...
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 ...
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 on...
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 i...
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 w...
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 ...
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 i...
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 /...
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 ma...
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...
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...
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 ...
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)...
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 separa...
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 interpr...
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 bu...
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 l...
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 def...
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.m...
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; ...
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 ...
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 p...
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...
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...
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::vect...
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 ...
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 ...
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 shoul...
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() { text...
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 usabl...
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_o...
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 li...
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, t...
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) {} templat...
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 (...
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"); exi...
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.s...
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 de...
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 ...
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 reg...
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 h...
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...
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,...
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 funct...
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 ...
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...
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...
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 n...
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 thi...
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}; //...
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] ...
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: ...
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...
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 ...
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++...
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 a...
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 ...
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 Ardui...
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 f...
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 a...
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 me...
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 y...
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 =...
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 eval...