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,494,716
1,494,818
C++ HashTable Object implementation
int hazmat::hashStr(char const * const str) { int count = 0; for ( unsigned i = 0; i < strlen( str ); i++ ) { count += str[i]; // get the ascii sum. } return count % maxSize; }
You are misunderstanding how hash tables work. You need to allocate a fixed-length array (in the simplest case) and then each entry must have a linked list so you can resolve duplicates. That is, two strings may result in the same hash value and you will need to walk the linked list and compare the keys. And yes, like ...
1,495,036
1,495,159
Simple C/C++ network I/O library
I have the following problem to solve. I want to make a number of requests to a number of "remote" servers (actually, a server farm we control). The connection is very simple. Send a line, and then read lines back. Because of the number of requests and the number of servers, I use pthreads, one for each request. Th...
I saw the comments and i think you can use boost::asio with boost::asio::deadline_timer Fragment of a code: void restart_timer() { timer_.cancel(); timer_.expires_from_now(boost::posix_time::seconds(5)); timer_.async_wait(boost::bind(&handleTimeout, MyClass::shared_from_this(), boost...
1,495,549
1,495,576
c++ std vector - invalidated iterator question
I have a standard vector of pointers. Under what circumstances might an iterator into this vector become invalidated? I have reason to believe that when an object is deleted, any vector iterator referencing it is thereby invalidated. This does not seem correct to me, however. I do believe this would be the standard beh...
It won't invalidate the iterator, it's actually the way you would delete heap allocated objects that are owned by the vector, the clear() method won't do that for you. This is pretty common: for (It = Vec.begin(); It != Vec.end(); It++) delete *It; Vec.clear(); Perfectly fine if you don't attempt to use what you ju...
1,495,649
1,495,698
What is the scope of a namespace alias in C++?
Does a C++ namespace alias defined inside a function definition have a block, function, file, or other scope (duration of validity)?
It's a block duration of validity. E.g If you define a namespace alias as below, the namespace alias abc would be invalid outside {...} block. { namespace abc = xyz; abc::test t; //valid } abc::test t; //invalid
1,495,776
1,514,976
Using pseudo tty with ssh results in warning
I am using ssh from my application and must pass "-t -t" to ssh in order for it to work correctly. Otherwise, the stdin of my application is interfered with by the call to ssh. Forcing a pseudo terminal to ssh via the -t -t avoids this issue, but instead results in the following obscure error message coming back from...
One may work around the issue by passing -n to ssh instead of -t -t. From the ssh man page: -n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. A common trick is to use this to run X11 programs on a remote ma...
1,495,778
1,495,788
Lambda Expressions and Script Parsing -- Is this a good design idea?
I've written a handful of basic 2D shooter games, and they work great, as far as they go. To build upon my programming knowledge, I've decided that I would like to extend my game using a simple scripting language to control some objects. The purpose is more about the general process of design of writing a script parser...
Not to discourage you, but I think you would get more out of embedding something like Squirrel or Lua into your project and learning to use the API and the language itself. The upside of this is that you'll have good performance without having to think about the implementation. Implementing scripting languages (even ba...
1,495,935
1,496,866
QTabWidget tab context menu
I need to display a context menu whenever a tab is clicked on and it needs to react to that specific tab. Is there any way to do this without subclassing it?
Easy way, but possibly not precisely what you need: Connect to the 'currentChanged' signal of your QTabWidget In the slot which is connected to the signal, create a QMenu and populate it as needed Finally, in the slot which is connected to the signal, call QMenu::exec( QCursor::pos() ) This will get a function called...
1,496,284
1,496,780
stepping into MACRO in VC++
I am debugging a source code that has a lot of big #define'd MACRO routines. I am interesting in stepping into them, but I guess, VC++ does not allow step-in functionality ... so, I am converting them into functions, but this is becoming hard for me Is there a way to step into MACRO routines? especially in VC++? PS: ...
In addition to all correct answers above: what I usually do is to show mixed display (C+assembly). This shows what really happens. Even if you are no expert in the underlying assembly, it gives an idea what happens (i.e. is it a trivial replacement or a complex loop). Also it will provide additional opportunities to st...
1,496,318
1,496,470
How to use C++ Classes exported by a dll in Delphi
is there a way to use C++ classes exported by a win32 dll in Delphi for win32? Are there other ways to archieve similar things (COM, .NET, ...)?
You can't import a class. You can only import functions. Rudy Velthuis has written at length on the topic. Although you can't directly use an exported C++ class, he describes a couple of techniques to achieve the same effect: "Flatten" the object, so on the calling side there is no object anymore, just a pointer that ...
1,496,453
1,496,703
Uploading to Amazon S3 using cURL/libcurl
I am currently trying to develop an application to upload files to an Amazon S3 bucket using cURL and c++. After carefully reading the S3 developers guide I have started implementing my application using cURL and forming the Header as described by the Developers guide and after lots of trials and errors to determine th...
Solved: was missing an CURLOPT for the file size in my code and now everything is working perfectly
1,496,469
1,496,746
Code coverage tools for Symbian C++ and Maemo
What code coverage tools have you used with Symbian C++ and Maemo? What are the pros and cons of the tool you are using?
On Symbian I've used BullseyeCoverage and Testwell CTC++. Cannot really describe the pros/cons of them in detail. Both got the job done, eventually. Both needed some effort with setup and integration with an automated test suite. Both contained bugs that e.g. crashed the downstream compiler with slightly broken instrum...
1,496,536
1,496,540
how to convert ascii to unsigned int
Is there a method that converts string to unsigned int? _ultoa exists but couldn't find the vise verse version...
std::strtoul() is the one. And then again there are the old ones like atoi().
1,496,731
3,412,249
How do I remove unnecessary resources from my project?
I am working with a very big project (a solution that contains 16 projects and each project contains about 100 files). It is written in C++/C# with Visual Studio 2005. One of the projects has around 2000 resources out of which only 400 are actually used. How do I remove those unused resources? I tried to accomplish ...
What I would do is write a custom tool to search your source code. If you remove a resource ID from a header file (i.e. possibly called resource.h) and then recompile and get no warnings: then that's a good thing. Here is how I would go about writing the app. Take as input the resource file (resource.h) you want to scr...
1,496,930
1,497,033
Using flyweight pattern to share bitmaps between bitmap objects
Hello stack overflowers, I have a desing that uses the flyweight pattern to share bitmaps that are shared between bitmap objects which manage drawing ops, etc. and integrate in the gui library. This is an embedded device so memory is at a premium. Currently I have done a working implementation with a std::vector of aut...
You could use a pool of boost weak pointers so that the pool does not count in the ownership. Only the bitmap objects have boost shared pointers, this way they decide when to release the bitmaps. The pool of weak pointers allows us to retrieve the already constructed bitmaps : When you create a bitmap object you either...
1,497,063
1,497,164
Reversing strings in a vector using for_each and bind
I was wandering how it's possible to reverese strings that are contained in a vector using a single for_each command just in one "simple" line. Yea, I know it is easy with a custom functor, but I can't accept, that it can't be done using bind (at least I couldn't do it). #include <vector> #include <string> #include <al...
std::for_each expects a unary function (or at least something with the typedefs of a unary function). std::reverse<> is a binary function. It takes two iterators. It would be possible to bind it all together using boost::bind, but it would be a pretty horrible mess. Something like: boost::bind( &std::reverse<s...
1,497,068
1,497,163
C++ & GCC: How Does GCC's C++ Implementation Handle Division by Zero?
Just out of interest. How does GCC's C++ implementation handle it's standard number types being divided by zero? Also interested in hearing about how other compiler's work in relation to zero division. Feel free to go into detail. This is not purely for entertainment as it semi-relates to a uni assignment. Cheers, Chaz...
It doesn't. What usually happens is that the CPU will throw an internal exception of some sort when a divide instruction has a 0 for the operand, which will trigger an interrupt handler that reads the status of the various registers on a CPU and handles it, usually by converting it into signal that is sent back to the ...
1,497,231
1,497,381
How to cast template class ptr to normal class ptr in C++
I have question regarding macros. How could I cast through macro a template class to normal class. In example: #define RUNTIME_CLASS(class_name) ((CRuntimeClass*)(&class##class_name)) template<typename T> A {}; if (RUNTIME_CLASS(A)); I know that this code wouldn't compile because it will not see template bit. But I ...
Maybe where you took the macro all the class names are starting with "class" and the macro expects only the second part of the name, what comes after "class".
1,497,278
1,497,318
std::vector and its iterator as single template typename
In order to get an "easier-to-remember" interface to the index-generating function std::distance(a,b), I came up with the idea of a better distinction of it's arguments (when used against the base of a vector: vec.begin() ) by calling a templated function with the vector and its iterator, like: std::vector<MyType> ve...
The fix is easy: add typename before T::const_iterator iter. This is needed because class templates may be specialized and using typename tells the compiler a type name is expected at T::const_iterator and not a value or something. You do the same in your less generic function, too.
1,497,325
1,497,354
structure in template class
sample code is as follow: struct TEMP { int j; TEMP() { j = 0; } }; template<typename T> class classA { struct strA { long i; strA():i(0) {} }; static strA obj_str; classA(); }; template<typename T> classA<T>::classA() {} template<typename T> classA<TEMP>::st...
In any case, your code doesn't make much sense in the following declaration. template<typename T> classA<TEMP>::strA classA<TEMP>::obj_str; Because the T parameter is used nowhere in the declaration. I think you either wanted to write one of the following things: // definition of static member of template template<ty...
1,497,552
1,497,565
A pointer to abstract template base class?
I cannot figure this out. I need to have an abstract template base class, which is the following: template <class T> class Dendrite { public: Dendrite() { } virtual ~Dendrite() { } virtual void Get(std::vector<T> &o) = 0; protected: std::vector...
Typically this is done by your template inheriting from an interface class, IE: template <class T> class Dendrite : public IDendrite { public: Dendrite() { } virtual ~Dendrite() { } void Get(std::ve...
1,497,753
1,497,884
Debugger Visualizer for non-managed C++ code?
Does anyone know of a C++ IDE or debugger that's supports debugger visualizers for unmanaged C++ code? The problem is that Visual Studio's debugger visaulizer supports only managed C++. Thanks, Olumide PS: I'm still open to using VS if I can find a technique for making the visualizer work with unmanaged C++.
Are the custom visualizers in Visual Studio 2005+ (basically editing autoexp.dat) what you need?
1,497,913
1,500,165
How different is Qt4 from Qt3?
I used to program in Qt3 a long time ago and I had read a great book that I still have by O'reilly on Qt3. I wanted to start using Qt4 again now several years later. Can I use my Qt3 book to get up to speed again, or has things changed so much that I should buy a Qt4 book?
In a nutshell: Qt 4 is (even) better -- and more powerful and flexible -- than Qt 3 you'll be fine! The Porting to Qt 4 documentation gives some idea of the many small changes to APIs. What's New in Qt 4 gives an overview of the big differences between Qt 3 and Qt 4. Some major changes that noone has mentioned so far...
1,498,211
1,594,732
overriding GetSecurityId in IInternetSecurityManager
I have built an executable which launches a dialog box in which is embedded the IE web browser active-x control (C++). I want this control to allow cross site scripting. One frame on the web page loads local html, the other loads from a server. I then want the server page to call a javascript function that lives in t...
By delegating these functions to the normal security manager and having a look at the structures the normal security manager fills in, I was able to determine that my issue was in GetSecurityId. For my purposes, I wanted to set the security domain to be a local file for all comers. #define SECURITY_DOMAIN "file:" if (...
1,498,283
1,498,355
How to obtain Windows special paths for a user account from a service
I want to be able to retrieve Windows "special paths" (e.g. temporary files folder, desktop) for user accounts, but from a service. I know the normal way to do this is by using SHGetFolderPath with the appropriate CSIDL for the folder type. Is there any way to get this type of info for each user without the service ha...
I'm no expert on this, but it seems you can use the hToken argument to SHGetFolderPath to pass in another user's token. I think you can create such a token using impersonation. If that does not work: these folders are in the registry under HKEY_USERS/<user's-sid>/Software/Microsoft/Windows/CurrentVersion/Explorer/Shell...
1,498,714
1,498,753
Why compiler provides default copy constructor
I wanted to know Why compiler provides default copy constructor..Whats the strategy behind that idea. Thanks in Advance.
From a related (but not same) question - Why don't C++ compilers define operator== and operator!=?: Stroustrup said this about the default copy constructor in "The Design and Evolution of C++" (Section 11.4.1 - Control of Copying): I personally consider it unfortunate that copy operations are defined by default and I ...
1,498,766
1,498,802
C++ call virtual method in child class
i have the following classes: class A { protected: A *inner; public: .... virtual void doSomething() = 0; .... } class B: public A { ... void doSomething() { if(inner != NULL) inner->doSomething(); } ... } When I use inner->doSomething() I get a segmentation fault. What ...
Without an explicit initialization of the member inner, it's possible for it to be both not NULL and point to invalid memory. Can you show us the code that explicitly initalizes inner? An appropriate constructor for A would be the following protected: A() : inner(NULL) { ... }
1,498,874
1,499,036
Why is this an "overloading ambiguity" in gcc?
Why is this an error : ie. arent long long and long double different types ? ../src/qry.cpp", line 5360: Error: Overloading ambiguity between "Row::updatePair(int, long long)" and "Row::updatePair(int, long double)". Calling code: . . pRow -> updatePair(924, 0.0); pRow -> updatePair(925, 0.0); .
$1 $2 Row::updatePair(int, long long) // #1 Row::updatePair(int, long double) // #2 // updatePair(924, 0.0); // int -> int (#1) // $1#1 // int -> int (#2) // $1#2 // // double -> long long // $2#1 // double -> long double // $2#2 In this case, both conversions in the first group are ...
1,498,949
1,499,377
Data structure for fast line queries?
I know that I can use a KD-Tree to store points and iterate quickly over a fraction of them that are close to another given point. I'm wondering whether there is something similar for lines. Given a set of lines L in 3D (to be stored in that data structure) and another "query line" q, I'd like to be able to quickly ite...
Another option - and the most commonly used one for spatial indexing in disk-based database systems - is the R-Tree. It's a bit more complicated to implement than a KD-Tree, but it's generally considered to be faster, and has no problem indexing lines and polygons.
1,499,024
1,499,061
How to create native DLL in Visual Studio from C# code?
I have the source code of a C# program. I want to create a DLL out of it which I want to use in C++. Is it possible to create a native DLL in Visual Studio 2008 which can be used in C++?
If you want the program to be native, and not managed, you'll need to port it to C++, instead of using C#. That being said, you can compile it in C# into a library, and use it from C++ by using C++/CLI. This just requires that you compile the files that use the C# library with the /clr flag. This provides C++ access ...
1,499,079
1,499,100
Communicate between AIR(Flex) and C++ Applications
I need to be able to communicate between two applications that reside on the same machine. One is using Flex and the other is in C++. I would like to be able to call functions and pass arguments to each other. What is the best way to communicate between them? I was thinking about using sockets.
As for now yes, you'll need to use sockets. AIR 2.0 will provide access to native processes, but that will require a native (per OS) installer. More info: http://www.mikechambers.com/blog/2009/09/22/fotb-slides-advanced-desktop-development-with-adobe-air/
1,499,086
2,686,833
POCO C++ - NET SSL - how to POST HTTPS request
How to correctly do a POST to HTTPS server and embed the login data correctly. Below code does not return any cookies (in Wininet it does). I wonder how POCO HTTP library handles HTTP redirections? MyApp() { try { const Poco::URI uri( "https://localhost.com" ); const Poco::Net::Context::Ptr cont...
You are setting content type like this: req.setContentType("Content-Type: application/x-www-form-urlencoded\r\n"); which should be: req.setContentType("application/x-www-form-urlencoded\r\n");
1,499,156
1,499,591
convert astronomically large numbers into human readable form in C/C++
My program prints out HUGE numbers - like 100363443, up to a trillion -- and it sort of hard to read them, so I would like to print any number in easy to read form. right now I use printf ("%10ld", number); format I would appreciate a resulting number using printf. Most of my code is c++ yet I don't want to introduc...
Use the non-standard apostrophe flag in the printf format string, if you have that option available and don't mind losing a little bit of portability. According to my documentation, the ' flag is available for POSIX systems since 1997. If you are on Unix, Linux, Mac, ... you should have no problem If you are on Windows...
1,499,182
1,499,256
Fastest way to share a connection and data from it with multiple processes?
I have multiple app processes that each connect to servers and receive data from them. Often the servers being connected to and the data being retrieved overlaps between processes. So there is a lot of unnecessary duplication of the data across the network, more connections than should be necessary (which taxes the ser...
I believe a dedicated service that exposes the data via shared memory is your best bet. Secondary from that would be a service that multicasts the data via named pipes, except that you're targeting a Unix variant and not Windows. Another option would be UDP multicast, so that the data replication occurs at the hardware...
1,499,217
1,501,077
Boost Graph as basis for a simple DAG Graph?
I'm looking at using Boost Graph Library as the basis for a dag graph. I haven't really used it all that much before, so not too familiar with how it works. Although I don't need edge weights and clever traversing algorithms, I would quite like to get the serialisation for free, plus the constraints enforcing dag graph...
Iteration over nodes in a graph is provided. There's an interface that returns a begin, end pair of iterators over the nodes (and a similar one over the edges): std::pair<vertex_iterator, vertex_iterator> vertices(const adjacency_list& g) From the documentation
1,499,293
1,569,705
Input Method Editor windows return FALSE for WM_QUERYENDSESSION - why?
We have a bizarre and very infrequent issue where people can't log off the Windows server when our product is running. The system is multi-application, all MFC/C++. The apps are run from a management service so they survive logoff. It's been running fine for donkeys years in loads of installations around the world. I ...
It would seem that Microsoft have encountered some of these problems with various versions of the IME. I found some relatively old updates. What OS is your customer running and do they have version(s) of Office installed? Is it possible to determine the filename and version of the module creating the IME window in y...
1,499,512
1,499,838
Installing Boost libraries on Snow Leopard
I have followed the directions on the boost website. I have put the boost dir in the path. I still cannot compile a C++ program using the boost libraries. I am specifically trying to use the filesystem library. Any help is greatly appreciated. --TJB
Did you compile the filesystem library? Many Boost libraries are header-only, but filesystem is one of the few that have to be compiled (and linked). Instructions on how to do that can be found at points 5 and 6 of the Getting Started on Unix Variants page. Instructions specific to the filesystem lib are at http://www....
1,499,569
1,510,406
How do I define a SWIG typemap for a reference to pointer?
I have a Publisher class written in C++ with the following two methods: PublishField(char* name, double* address); GetFieldReference(char* name, double*& address); Python bindings for this class are being generated using SWIG. In my swig .i file I have the following: %pointer_class(double*, ptrDouble); This lets me...
Here is a working solution that I came up with. Add a wrapper function to the swig.i file: %inline %{ double * GetReference(char* name, Publisher* publisher) { double* ptr = new double; publisher->GetFieldReference(name, ptr); return ptr; } %} Now from Python I can use the follow...
1,499,688
1,508,357
Utf-8 in c++: quick & dirty tricks
I am aware that there are been various questions about utf-8, mainly about libraries to manipulate utf-8 'string' like objects. However, I am working on an 'internationalized' project (a website, of which I code a c++ backend... don't ask) where even if we deal with utf-8 we don't acutally need such libraries. Most of ...
Well this dirty trick will not work. First, what is the value of mask after this: const unsigned char mask = 0x11000000; const unsigned char notUtf8Begin = 0x10000000; Perhaps you are mixing hex representation with binary. Second, as you correctly say in utf-8 encoding, a character may be several bytes long. std...
1,499,878
1,514,439
Use a Graph Library/Node Network Library or Write My Own?
I'm trying to decide between going with a pre-made graph/node network library or to roll my own. I'm implementing some graph search algorithms which might require some significant customization to the class structure of the node and/or edges. The reason I'm not sure what to do is that I'm unsure if customization of a ...
I can perhaps provide a little guidance on the BGL. The library is very flexible. The cost of this is that the syntax can be very baroque, in order to accommodate all the possibilities. However, it is sufficiently flexible that simple things can be done simply. Unfortunately the boost documentation goes at things ful...
1,499,884
1,500,006
Sphere online judge finds my code wrong although its working correct for hundreds of test cases
Question goes like this.. Input n [the number of multiplications <= 1000] l1 l2 [numbers to multiply (at most 10000 decimal digits each)] Text grouped in [ ] does not appear in the input file. Output The results of multiplications. My code.. #include<iostream> #include<vector> using namespace std; int main() { l...
Had to google your problem to understand what it was: here it is, please be considerate of your readers :x Your code cannot actually work: long int is not long enough (and this is implementation dependent anyway) You will have to read the integers 'char' by 'char' and roll your own implementation of BigInts which is th...
1,500,064
1,500,131
Renaming first and second of a map iterator
Is there any way to rename the first and second accessor functions of a map iterator. I understand they have these names because of the underlying pair which represents the key and value, but I'd like the iterators to be a little more readable. I think this might be possible using an iterator adaptor, but I'm not sur...
If you're just concerned about readability you could do something like this: typedef map<Vertex, Edge> AdjacencyList; struct adjacency { adjacency(AdjacencyList::iterator& it) : vertex(it->first), edge(it->second) {} Vertex& vertex; Edge& edge; }; And then: Vertex v = adjacency(it).vertex;
1,500,230
1,501,042
Is there a way to create a view in a CSplitterWnd without using (MFC) dynamic object creation?
I was previously using a CSplitterWnd in a MFC application, using it's CreateView function. Everything was working fine but now I would like to pass a parameter to the constructor of my views, so I cannot use MFC dynamic object creation (DECLARE_DYNCREATE and IMPLEMENT_DYNCREATE) because they require an empty construct...
After checking Javier De Pedro's answer I though I could override the creation function so I did (semi-pseudo-code): class ObjGetter { static CObject* obj; public: ObjGetter(CObject* obj_){obj = obj_;} static CObject* __stdcall getObj() { return obj; } }; CObject* ObjGetter::obj = NULL; BOOL CMyFrame::OnC...
1,500,349
1,500,358
Is there a faster and object orientated alternative to SDL for C++?
The current version of libsdl (1.2.x branch) is very, very slow with blending and per pixel alpha (as it uses software blending). Is there any other good alternative to it?
SFML is exactly what you need: http://sfml-dev.org/. Skim through the tutorials, you'll see that it's way easier and more powerful than SDL.
1,500,363
1,500,517
Compile time sizeof_array without using a macro
This is just something that has bothered me for the last couple of days, I don't think it's possible to solve but I've seen template magic before. Here goes: To get the number of elements in a standard C++ array I could use either a macro (1), or a typesafe inline function (2): (1) #define sizeof_array(ARRAY) (sizeof(A...
Try the following from here: template <typename T, size_t N> char ( &_ArraySizeHelper( T (&array)[N] ))[N]; #define mycountof( array ) (sizeof( _ArraySizeHelper( array ) )) int testarray[10]; enum { testsize = mycountof(testarray) }; void test() { printf("The array count is: %d\n", testsize); } It should print o...
1,500,495
1,544,722
How to build wxmathPlot for win32?
I downloaded the latest wxmathplot but the readme is a bit sparse with instructions on how to build on win32 platform. Has anyone used this library for win32? Can someone point me to the docs or give some hints/advice on how to build for win32 targets. We'll eventually use this for cross platform stuff, for now it is ...
I use wxMathPlot. I simply add mathplot.cpp and mathplot.h to the MSVS2008 C++ projects that need to use it. This compiles and links without my having to do anything special.
1,500,584
1,500,912
Performance difference between C++ and C# for mathematics
I would like to preface this with I'm not trying to start a fight. I was wondering if anyone had any good resources that compared C++ and C# for mathematically intensive code? My gut impression is that C# should be significantly slower, but I really have no evidence for this feeling. I was wondering if anyone here has...
I have to periodically compare the performance of core math under runtimes and languages as part of my job. In my most recent test, the performance of C# vs my optimized C++ control-case under the key benchmark — transform of a long array of 4d vectors by a 4d matrix with a final normalize step — C++ was about 30x fast...
1,500,653
1,500,693
C++ Templates type casting with derivates
I'm trying to cast from one generic to another, say: myClass<MoreAbstract> anItem = myclass<DerivateFromMoreAbstract> anotherObject; Or do something like aFunction(anotherObject); // myclass<DerivateFromMoreAbstract> anotherObject where aFunction signature is aFunction(myClass<MoreAbstract> item); In fact, myClass ...
You can't static cast, as they are incompatible types. You can sometimes create an operator to coerce the type instead #include <iostream> class A { }; class B : public A { }; template<typename T> struct holder { T* value; holder ( T*value ) : value ( value ) { } template < typename U > // class T : p...
1,500,689
1,500,741
dynamic linking woes using c++
main.cpp <- line 106 to 164 invoke dlopen/dlsym/dlclose basefilter.hpp <- naked abstract base class basefilter.cpp examplefilter.hpp <- a test plugin examplefilter.cpp everything <- the repository Running the whole thing will result in the following error: Cannot open library "./libexamplefilter.so" ./libexamplefilte...
You need to use the linker option "export-dynamic" when compiling your main executable. Normally, the main executable won't export its symbols for use by the dynamic linker (unless the symbol is used by some shared library participating in the link), which means that if your library calls back into the main exe, it wil...
1,500,715
1,500,854
Gnu Makefile - Handling dependencies
What approach do C++ programmers on Unix platform use to create and manage Makefiles? I was using hand made Makefiles for my projects but they don't handle header file changes and other dependencies. I googled around and found a good solution here. But I ran into a problem here in the sed command - sed -e 's/#.*//...
I use that approach too and can't praise it highly enough. And I write my makefiles by hand and reuse them a lot on new projects. .The expression "s/ *\\$//" will work outside the context of Make. Within a makefile it doesn't work because Make tries to interpret "$/" before handing the result to the shell. So you must...
1,501,085
1,501,166
Duplicating base-class constructors to subclass?
I have a large set classes which I need to "wrap" in a very thin subclass. The functionality of the base classes doesn't change, and their interface remains intact. The problem is, that in order to use the base classes's constructors (and most of them have more than one), I need to decalre an identical constructor in e...
You could add templated constructors for all possible parameters to your wrapper class: template<class Base> class wrapper : public Base { public: wrapper() : Base() {} template<typename T1> wrapper(T1 a1) : Base(a1) {} template<typename T1, typename T2> wrapper(T1 a1, T2 a2) : Base(a1, a2) {} // ... }; ...
1,501,111
1,501,297
Boost equivalent of ManualResetEvent?
I'm wondering if there is a boost equivalent of ManualResetEvent? Basically, I'd like a cross-platform implementation... Or, could someone help me mimic ManualResetEvent's functionality using Boost::thread? Thanks guys
It's pretty easy to write a manual reset event when you have mutexes and condition variables. What you will need is a field that represents whether your reset event is signalled or not. Access to the field will need to be guarded by a mutex - this includes both setting/resetting your event as well as checking to see i...
1,501,292
1,501,299
How do you decipher complex declarations of pointers+arrays?
Although I use std::vector almost all the time, I am interested in understanding as much as I can about pointers. Examples of what I am talking about: char* array[5]; // What does it mean? // 1) pointer to an array of 5 elements! // 2) an array of 5 pointers? I am interested in the precise definition of this declarati...
Not just pointers and arrays: How to interpret complex C/C++ declarations: Start reading the declaration from the innermost parentheses, go right, and then go left. When you encounter parentheses, the direction should be reversed. Once everything in the parentheses has been parsed, jump out of it. Continue...
1,501,338
1,501,458
What advantages can I get from learning C++ if I'm mainly a C# Programmer?
Recently I've started to notice a lot of smirks and generally rude comments whenever I mention C#. Everyone I talk to either says learn Python or learn C++. Python is a nice language, I get it. But I don't find much use for it right now (for my use cases), and C++ I heard is a faster language (not sure). So my questi...
I have been C++ developers for last 10 years and last two years, I have been using java for new product development. I have also done some programming on C# just to learn it. Based on my experience I would say C++ is a challenging and high performance language which is good for computer science students to understand p...
1,501,341
1,501,367
Reference type and pointer in disassembly
Why reference types and pointers are same in compiled code?(You can see in third and fourth line). I tried to figure it out but apparently I could not achieve. If a reference type variable must be initialized at declaration and can not be changed so is there any need to do indirection as in pointers? int x = 10; mov ...
If the referece is known by the compiler to always refer to a single particular object/item, then the compiler could certainly optimize away the indirection. However, most references are in fact bound at runtime. Even if a particular instance of a reference can't be rebound, different executions of a particular scope ...
1,501,446
1,501,830
Will splitting code into several .cpps decrease compilation time?
Suppose a have a fairly complex class I'm working on. Half the methods are done and tested, but I'm still devolping the other half. If I put the finished code in one cpp and the rest in another, will Visual Studio (or any other IDE for that matter) compile faster when I only change code that's in the "work-in-progress"...
It really depends. For a very large project, link time can often be considerably more expensive than the time to compile a single file. In our codebase at work (a game based on the Unreal Engine) we actually found that making "bulk.cpp" files that include many other files (effectively fewer translation units) decreas...
1,501,510
1,501,569
Linked list and copy constructor
I'm trying to write a basic, singly-linked list class in C++. I did it in my data structures class years back, but I can't remember the details. Should my Node class have a copy constructor? It has a Node* as a member variable, and as far as I know you're always supposed to write a copy constructor, destructor, and ass...
You could do worse than copy the design of sgi's slist -- sgi's template library ("stl") was the basis for the part of the C++ standard library that's often still (not technically correctly;-) referred to as "stl". Unfortunately slist didn't make it (its doubly-linked cousin list OTOH did make it, and became std::list)...
1,501,516
1,501,579
OpenGL / C++ - How do you fill an area surrounding a point on a mouse click?
I've got the mouseclick handler correctly set up. I have a drawing with some shapes. Is there any way for me to fill the surrounding part of a point until it hits a polygon boundary. Something like Microsoft Paint's "fill" command. Thanks!
Consider using OpenGL selection capabilities with glSelectBuffer. Refer to this chapter of the red book for explanation.
1,501,768
1,501,789
'variable name' cannot appear in a constant expression c++
Anyone have any clue what this error might actually mean? I'm tripping on a bit of code that can't seem to get around it. I've tried it with just h*2 instead of hprime, and just w*2 instead of wprime. Every time I get the same compiler (g++ compiler) error of : grid.cpp: In constructor ‘Grid::Grid(int, int)’: grid.cpp...
You can't use new to allocate a two-dimensional array, but you can change the offending line like this: grid = new int*[wprime]; for (int i = 0 ; i < wprime ; i++) grid[i] = new int[hprime]; If it doesn't have to be multidimensional, you can do: grid = new int[wprime*hprime]; and just index it like grid[A*...
1,501,803
1,502,065
Convert AES encrypted string to hex in C++
I have a char* string that I have encoded using AES encryption. This string contains a wide range of hex characters, not just those viewable by ASCII. I need to convert this string so I can send it through HTTP, which does not accept all of the characters generated by the encryption algorithm. What is the best way to...
A few problems. First, your characters are probably signed, which is why you get lots of FF's - if your character was 0x99, then it gets sign extended to 0xFFFFFF99 when printed. Second, strlen (or dStrlen - what is that?) is bad because your input string may have nulls in it. You need to pass around the string leng...
1,501,859
1,501,862
Why Size of Class with a member function is 1 byte..While member function is 4 bytes
I am not getting Why Size of Class with a member function is 1 byte..While member function is 4 bytes in the following example. class Test { public: Test11() { int m = 0; }; }; int main() { Test t1; int J = sizeof(t1); int K = sizeof(t1.Test11()); ...
The function itself is not actually stored in the class. Only the class's data members (and possibly its vtable pointer, if it has one) affect its size. The function itself lives in the executable code region, and all instances of the same type of class use that one definition of the function. The compiler does not ac...
1,501,920
1,501,970
Base Copy constructor not called
class Base { public: int i; Base() { cout<<"Base Constructor"<<endl; } Base (Base& b) { cout<<"Base Copy Constructor"<<endl; i = b.i; } ~Base() { cout<<"Base Destructor"<<endl; } void val() { ...
If you want to read actual rule you should refer to C++ Standard 12.8/8: The implicitly-defined copy constructor for class X performs a memberwise copy of its subobjects. The order of copying is the same as the order of initialization of bases and members in a user-defined construc- tor (see 12.6.2). Each subobj...
1,502,244
1,502,268
How can I use C++ code to interact with PHP?
I was reading somewhere that sometimes PHP is simply not fast enough and that compiled code has to sometimes "do the heavy lifting" What is the api in C++ to do this?
You can add functions/classes to PHP, programmed in C (and you can wrap a C++ class from C, if I remember correctly from an article I read some time ago), which might allow you to do some things faster -- if programmed well : no need for interpretation of PHP code ; only execution of machine code, which is generally wa...
1,502,629
1,502,641
Function declarations and an unresolved external
I am looking after a huge old C program and converting it to C++ (which I'm new to). There are a great many complicated preprocessor hacks going on connected to the fact that the program must run on many different platforms in many different configurations. In one file (call it file1.c) I am calling functionA(). And in...
You can pass a flag to the compiler (/P, I think) that causes it to output the complete preprocessed output that is passed to the compiler - you can then open this (huge) file, and search through it and the information you need will be in there, somewhere.
1,502,677
1,521,826
WinHTTP IWinHttpRequest iface - cookie handling - how to get cookies from response?
I'm using WinHTTP IWinHttpRequest object. I do POST to a https domain specyfying a request body with credentials. The site is expected to return cookies in HTTP response. The code works in Wininet - but I don't know how in WinHTTP to get cookies from the HTTP response? Can anybody help? Dominik
I would start with the Cookie Handling in WinHTTP article on MSDN. If you want to do things manually, here's an (ugly) VB code sample you can crib from: http://www.devnewsgroups.net/group/microsoft.public.exchange.development/topic58495.aspx)
1,502,791
1,502,912
Why check only certain values for errors? (C++?)
I recently started learning DirectX/Windows, and the book I'm learning from had the code d3d = Direct3DCreate9(D3D_SDK_VERSION); if(d3d == NULL) //catch error &c. My question is: What would cause an error in this line, that is different than what would cause an error in another line (say, for example, int num = 42...
d3d = Direct3DCreate9(D3D_SDK_VERSION); if (d3d == NULL) This is an error or not according to the meaning you give to the return value of Direct3DCreate9, i.e. depending on the specification of the function. I've written many pointer-returning functions for which NULL as a return value was not an erroneous situation. ...
1,502,888
1,502,894
C# - Executables decompilable (can be reverse engineered)?
Is that right that C# can be reverse engineered? How is easy to do that? Can we say the C# is not enough good from safety aspect? And what about C++ compared with C# against decompiling?
It's true! Take a look at one of your own executables using Reflector. Does this mean that C# is "not enough good from safety aspect"? No, it doesn't mean that. There's nothing wrong with the safety of C#. You just need to ensure that you don't put any secrets in your published executables if you don't want the world t...
1,503,006
1,503,023
unresolved external mystery
My linker is reporting an error as follows: unresolved external symbol "unsigned char __fastcall BD_CLC(int,int)"... But I maintain that all references to this function, as well as the definition of the function are of the form: __forceinline UBYTE BD_CLC(int swap,int elem); I even did a compilation with "Generate pr...
Since you've declared the function __forceinline, you need to make sure the definition - not just the declaration - is visible everywhere the function is called.
1,503,266
1,524,755
How do I change the lookup path for .NET libraries referenced via #using in Managed C++?
I developed a DLL in Managed C++ which loads some plugins (implemented in any .NET language) at runtime using System.Reflection.Assembly.LoadFile. The interface which is implemented by all plugins is implemented in C#. It's used by the Managed C++ code like this: #using <IMyPluginInterface.dll> // Make the 'IMyPluginI...
You can use several options - if you know in advance where the assembly will be located, you can add that path to your application's configuration file: <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="MyPath"/> </assemblyBinding> </runtime> </...
1,503,504
1,503,538
Using all overloads of the base class
When a subclass overrides a baseclass's method, all of the baseclass's overloads are not available from the subclass. In order to use them there should be added a using BaseClass::Method; line in the subclass. Is there a quick way to inheirt the baseclass's overloads for ALL of the overridden methods? (not needing to e...
No. It's only possible with a using declaration and that only works with the individual methods.
1,503,542
1,503,560
Variable-sized bitfields with aliasing
I have some struct containig a bitfield, which may vary in size. Example: struct BitfieldSmallBase { uint8_t a:2; uint8_t b:3; .... } struct BitfieldLargeBase { uint8_t a:4; uint8_t b:5; .... } and a union to access all bits at once: template<typename T> union Bitfield { T bits; uint8...
You could make the integral type a template parameter as well. template<typename T, typename U> union Bitfield { T bits; U all; } typedef Bitfield<BitfieldSmallBase, uint8_t> BitfieldSmall; typedef Bitfield<BitfieldLargeBase, uint16_t> BitfieldLarge;
1,503,716
1,504,679
Video in Qt S60 application?
Has anyone built a Qt S60 app (3rd edition, FP2) that plays (streaming or local) video? I want to play video 'in' a widget, not with (say) QDesktopServices. I know there's documentation about how to do this with Symbian, such as here and here but I'm still stuck. (Apologies in advance for cross-posting: I've asked else...
Qt 4 includes a suite of multimedia APIs called Phonon, which allow you to do just this. They are currently being implemented for Symbian - while the Qt for S60 "Tower" pre-release does not include support for Phonon on Symbian, Qt 4.6 will do. In the meantime, your only option is to use the Symbian MMF APIs directly....
1,503,764
1,513,060
The simplest code hacking
I have the following code: #include <iostream> #include <string> void main() { std::string str; std::cin>>str; if(str == "TheCorrectSerialNumber") std::cout<<"Hello world!!!"<<std::endl; } I need a decompilation or disassemblering tool which can help me by doing below listed steps find the "TheC...
It is very easy to do with disassembling. You need HIEW and W32DASM tools or OllyDbg (for example). Just look at some examples of using this tools in youtube (cracking). www.wasm.ru www.cracklab.ru Very helpful sites!!!!
1,503,770
1,503,935
Best method for requeing functions
We have a windows service in C++/ MFC which has to carry out a number of tasks on the host workstation some of which may be long running and may fail a few times before they are completed. Each task will only need to be completed once and sequentially. I was of thinking of some form of callback initially to retry t...
I'm doing quite the same thing in my professional project. My server component is getting runnable objects from different sources and execute them sequentially in a separated thread. All my runnable objects are using different parameters but they all have one function run(void* pUserParam). the void* parameters is a sp...
1,503,839
1,504,135
How to turn off pc via windows API?
I never programmed a winapi so i have a little problem here . I need turn off my pc from my application . I found this example link text then i found this example how to change privileges link text But i have problem how to get that parameter HANDLE hToken // access token handle I think i need to make it in the next ...
This is a bit much for the comments on Daniel's answer, so I'll put it here. It looks like your main issue at this point is that your process isn't running with the priveleges required to perform a system shutdown. The docs for ExitWindowsEx contain this line: To shut down or restart the system, the calling process ...
1,503,965
1,504,005
_beginthread in XPCOM Component error C2440
I want to start thread in XPCOM Component. Here is a code for creating thread nsresult rv = NS_OK; nsCOMPtr<Callback> obj = do_CreateInstance("@jscallback.p2psearch.com/f2f;1", &rv); NS_ENSURE_SUCCESS(rv, rv); char* str="Hello from C++"; _beginthread( (void(*)(nsCOMPtr<Callback> ))&P2P::test, 0,obj); ...
Make P2P::test static and add __cdecl calling convention.
1,504,205
1,504,252
How can I implement a 'main' method in a class in C++?
Consider: static class EntranceClass { public: static void RegisterSomething() { } static int main() { RegisterSomething(); return 0; } } // <-- Expected unqualified-id at the end I'm getting the following error: expected unqualified-id at end of input main.cpp Problem Is the...
The error is referring to the use of the static keyword before the class definition - the compiler expects a variable name after that (as in C++ there is no such thing as a static class). And if you want to use static int EntranceMain::main(void) as your program's entry point, then one way to do it is to tell that to y...
1,504,251
1,504,307
Heap corruption: What could the cause be?
I am investigating a crash due to heap corruption. As this issue is non-trivial and involves analyzing the stack and dump results, I have decided to do a code review of files related to the crash. To be frank, I don't have in-depth knowledge of when the heap could be corrupted. I would appreciate if you could suggest s...
Common scenarios include: Writing outside the allocated space of an array (char *stuff = new char[10]; stuff[10] = 3;) Casting to the wrong type Uninitialized pointers Typo error for -> and . Typo error when using * and & (or multiple of either) [EDIT] From the comments, a few more: Mixing new [] and new with delete...
1,504,323
1,505,009
Avoid reusing of the same fd number in a multithread socket application
I have an asynchronous application executing several threads doing operations over sockets where operations are scheduled and then executed asynchronously. I'm trying to avoid a situation when once scheduled a read operation over a socket, the socket gets closed and reopened(by possibly another peer in another operatio...
Ok, found the answer. The best way here is to call accept() and get the lowest fd available, duplicate it with a number known by you like dup2(6,1000) and close(6), you have now control of the fd range you use. Next accept will come again with 6 or similar, and we'll dup2(6,999); and keep decreasing like that and reset...
1,504,420
1,504,438
C++ What does the percentage sign mean?
I got this c++ macro and wonder what they mean by code%2 (the percentage sign) ? #define SHUFFLE_STATEMENT_2(code, A, B) switch (code%2) { case 0 : A; B; break; case 1 : B; A; break; }
It is for taking a modulus. Basically, it is an integer representation of the remainder. So, if you divide by 2 you will have either 0 or 1 as a remainder. This is a nice way to loop through numbers and if you want the even rows to be one color and the odd rows to be another, modulus 2 works well for an arbitrary numbe...
1,504,464
1,522,666
Windows socket WSACleanup C++
I am using sockets on my program. Due to I added the WSAStartup. My application runs fine (It is always up till it gets a signal to stop). After getting the signal it stops te problem that if I write the WSACleanup function at the end of my program it crashes and if I remove it it terminates fine. Thanks
Couldn't resovle and find the problem.The application is using more than just sockets. Although Microsoft reference sais that onevery WSAStartup you must use WSACleanup, well this is not true and the system is releasing things regards that.
1,504,752
1,504,782
C++ Output evaluation order with embedded function calls
I'm a TA for an intro C++ class. The following question was asked on a test last week: What is the output from the following program: int myFunc(int &x) { int temp = x * x * x; x += 1; return temp; } int main() { int x = 2; cout << myFunc(x) << endl << myFunc(x) << endl << myFunc(x) << endl; } The ans...
The C++ standard does not define what order the subexpressions of a full expression are evaluated, except for certain operators which introduce an order (the comma operator, ternary operator, short-circuiting logical operators), and the fact that the expressions which make up the arguments/operands of a function/operat...
1,505,318
1,505,397
C++ implicitly calling a function When? and How?
I have a couple questions. Are all functions inside of a class member functions? or only the ones preceded by the declaration "friend"? The significance of member functions are that they cannot be accessed by any other classes correct? What is the difference between an implicit and explicit call? Which functions can o...
Are all functions inside of a class member functions? or only the ones preceded by the declaration "friend"? Friend functions are not member functions. All what they differ from regular global functions is that they can access non-public area of the class. For example: class myclass { friend void fun(const my...
1,505,335
1,505,436
How do you use markers in vi?
I just discovered the existence of markers in vi. How do you use it, what do you know about them? are they useful, say for a C++ developer?
I use them all the time for: commenting out blocks of code, copying and moving blocks of code, yanking and deleting blocks of code into named buffers, and Edit: substituting in a block of test. Commenting out: go to the first line of the code you want to comment out, mark it, e.g. enter ma go to the end of the block...
1,505,489
1,520,632
memory leak when calling unmanaged code from managed code in Windows 7
When I call an unmanaged C++ code from my C# code, I seem to have some kind of a memory leak. The C++ reads data from a file using ifstream.read, and writes it to a Vector. This happens only after upgrading to Windows 7, doesn't happen on Vista, but if I use a version of the native dll that was compiled on Vista, it do...
I'm sure the problem is related to marshaling the C# data types to their C++ counter parts. Since you are marshaling the return value bool to a signed 1 byte value, maybe you should do the same to the function arguments? The C# bool type is 4 bytes, maybe you are leaking there? Also, specifying the unmanaged type for t...
1,505,582
1,505,631
Determining 32 vs 64 bit in C++
I'm looking for a way to reliably determine whether C++ code is being compiled in 32 vs 64 bit. We've come up with what we think is a reasonable solution using macros, but was curious to know if people could think of cases where this might fail or if there is a better way to do this. Please note we are trying to do thi...
Unfortunately there is no cross platform macro which defines 32 / 64 bit across the major compilers. I've found the most effective way to do this is the following. First I pick my own representation. I prefer ENVIRONMENT64 / ENVIRONMENT32. Then I find out what all of the major compilers use for determining if it's...
1,505,675
1,505,740
power of an integer in c++
I need to get the result from pow(a,b) as an integer (both a and b are integers too). currently the calculations where (int) pow( (double)a, (double)b) is included are wrong. Maybe someone can help with a function that does the pow(a,b) with integers and returns an integer too? But here is the odd part: I made my scrip...
A nice recursive approach you can show off: int myPow(int x, int p) { if (p == 0) return 1; if (p == 1) return x; return x * myPow(x, p-1); }
1,505,676
1,505,709
How do I increment an IP address represented as a string?
I have an IP address in char type Like char ip = "192.123.34.134" I want increment the last value (134). Does anyone how should i do it? I think, i should convert it to an integer, and then back, but unfortunately i don't know how? :( I'm using C++. Please help me! Thanks, kampi
You can convert the IP address from a string to an integer using inet_addr, then, after manipulating it, convert it back to a string with inet_ntoa. See the documentation for these functions for more info on how to use them. Here's a small function that will do what you want: // NOTE: only works for IPv4. Check out ...
1,505,704
1,510,111
How to launch process with limited memory?
How does one create and launch process (i.e. launch an .exe file) with RAM limitation using c++ and the win32 API? Which error code will be returned, if the proccess goes beyond the limit?
Job Objects are the right way to go. As for an error code, there really isn't one. You create the process (with CreateProcess) and the job (with CreateJobObject), then associate the process with the job object (with AssignProcessToJobObject). The parent process won't get an error message if the child allocates more ...
1,506,131
1,506,160
How to debug a multithreaded application in C++ which is hung (deadlock)?
In java debugging a hung application is easy. You can take the memory dump of the application and use and use eclipse jvm dump analyser to see the status of the threads and where each threads were blocked? Does something like this exists for C++?
You can do the exact same thing with C++; force a core dump and look into it after. Or, if you're using MSVC, you can simply attach the debugger to the application while it's running. Hit "break all" and poke around through the threads.
1,506,313
1,506,339
call back member function in c++
class scanner { private: string mRootFilePath; static int AddToIndex( const char *,const struct stat *,int); public: scanner(string aRootFilePath){ mRootFilePath = aRootFilePath; } string GetFilepath(){ ...
In your call to ftw, the first parameter is mRootFilePath.c_str. Perhaps you want mRootFilePath.c_str() instead?
1,506,456
1,506,541
Object files do not contain symbols that should be there
This is the specific error I am getting: libFoo.so: undefined reference to `IID_IFOOBAR' collect2: ld returned 1 exit status make: *** [/home/F.exe] Error 1 when I try to check the symbols in my object file A.o nm A.obj | grep IID_ I get no symbols listed in my object file of the 'IID_IFOOBAR' that should be there si...
[EDIT] Add the definition of the variable somewhere (without extern). Extern identifiers without initializers are not definitions - the definition must be somewhere else.
1,506,727
1,506,773
Assigning object to method call
I have a class whose name is YourClass. And my problem is WHY compiler do NOT generate an error for following code? YourClass AMethod(){ return YourClass();} AMethod() = YourClass(); [In this case IN MY OPINION AMethod just return a value (I mean it do not have a l-value).] EDIT: If I can do that above why I can not d...
EDIT1: I think I miss understood the question first time. The standard says: 3.10 Lvalues and rvalues The result of calling a function that does not return a reference is an rvalue. User defined operators are functions, and whether such operators expect or yield lvalues is determined by their parameter and r...
1,506,738
1,506,767
"corrupted double-linked list" on boost::function free()
I am going to try to ask this question without supplying too much source code because all the relevant bits add up to a bunch. The key (I think?) objects involved are using namespace o2scl; typedef MSMTModel<TASensor,PosModel,target2d,ovector,ovector_const_subvector> TA_MSMTModel; typedef MPC_funct_mfptr<MSMT_Initial...
Run the program through valgrind. That'll give you a stack trace when the memory gets corrupted (as well as a stack trace corresponding to the history of that piece of memory eg. where it was created or, if it was deleted, where it was destroyed).
1,506,835
1,506,951
What should be used to check identity in C++?
I have two pointers to objects and I want to test if they are the exact same object in the most robust manner. I explicitly do not want to invoke any operator == overloads and I want it to work no matter what base classes, virtual base classes and multiple inheritance is used. My current code is this: ((void*)a) == ((v...
If your classes are genuinely exactly as given then it's impossible as there's not enough information available at runtime to reconstruct the required information. If they're actually polymorphic classes, with virtual functions, it sounds like dynamic_cast<void *> is the answer. It returns a pointer to the most derived...
1,506,903
1,512,214
Custom front end and back end with Pantheios logging
Apologies if I'm missing something really obvious, but I'm trying to understand how to write a custom front end and back end with Pantheios. (I'm using it from C++, not C.) I can follow the purposes of the initialisation functions (I think) but I'm unsure about the others: pantheios_be_logEntry, pantheios_fe_getProcess...
Not sure I understand exactly what you don't understand, but maybe that's part of the problem. ;-) So I'll try my best and you let me know whether it's near or not. pantheios_fe_getProcessIdentity() is called once, when Pantheios is initializing. You need to return a string that identifies the process. (Actually, it id...
1,507,298
1,507,368
Solving An Equation in an Array
Im trying to figure out how i can solve an equation that has been stored in an array. I need some guidance on how to conquer such problem. here is my conditions i have an array int X[30]; and in there i have stored my desired equation: 5+6*20/4 as well, i couldnt store the operants (+ / - * ) so i used different ident...
Normally, you have to define the priority of each operation and process each of them one by one. First your expression is: '`[ 5,-1, 6,-4,20,-2, 4]`' Do all '/' first: '`[ 5,-1, 6,-4, 5,-1, 0]`' <- 20/ 4 = 5+0 Then, do all '*': '`[ 5,-1,30,-1, 0,-1, 0]`' <- 6* 5 = 30+0 Then, do a...
1,507,301
1,507,320
Getting FILEVERSION from Visual C++ Resource File
Are there some preprocessor keywords to use to access the FILEVERSION defined in my .rc file at compile time? I don't really want to add extra code to read the file information from the compiled product itself.
The preprocessor runs on the .RC file as well. Define the shared data in a header that is included by both the .RC and your source code. i.e., in foo.h: #define MY_PRODUCT_NAME Foo Then in the foo.rc: #include "foo.h" VS_VERSION_INFO VERSIONINFO // Many lines omitted VALUE "ProductName", MY_PRODUCT_NAME Then ...
1,507,743
1,507,755
What's the rationale behind headers?
I don't quite understand the point of having a header; it seems to violate the DRY principle! All the information in a header is (can be) contained in the implementation.
It simplifies the compilation process. When you want to compile units independently, you need something to describe the parts that will be linked to without having to import the entirety of all the other files. It also allows for code hiding. One can distribute a header to allow others to use the functionality with...
1,507,761
1,508,018
Preventing a complete rebuild using branches with GIT and Visual Studio 2005
One of the problem I faced when using branches in GIT was that it was very easy when switching branches to cause visual studio 2005 to cause a complete rebuild of the source because of the time/date being changed when switching branches. My typical layout is this. svn/remote master test When switch between either the t...
git only touches files which actually change when switching branches, so only translation units that include files that are different between the two branches should have their timestamp updated when switching between the two branches. Visual Studio 2005 is generally very good at incremental builds, but it is very easy...
1,508,327
1,508,760
Loading Qt plugins when linking to Qt statically?
I'm trying to use SVG graphics in QIcons. I have a static library that contains all my graphics resources, and a method in that static library that returns QIcons pre-loaded with the correct graphics. I'm trying to do this: QIcon icon(":/icons/find.svg"); I have verified that that resources has been loaded by listing ...
You need to use Q_IMPORT_PLUGIN. See the documentation here: https://doc.qt.io/qt-5/qtplugin.html#Q_IMPORT_PLUGIN