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,790,291
1,790,337
Using Boost on Windows (Visual Studio)
I want to get started using Boost. I'm programming a C++ program in Visual Studio (obviously on a Windows machine). Boost's Getting Started Guide says: The easiest way to get a copy of Boost is to use an installer. The Boost website version of this Getting Started guide will have undated information on installers as t...
A good way to make sure everyone has everything configured properly is to use svn externals. You can create something like /trunk/boost1.35 and then you can point to that with an svn external. That way as new versions of boost come out, you can just repoint your svn external to /trunk/boost1.40 In your repository, you...
1,790,704
1,790,720
Difference between [square brackets] and *asterisk
If you write a C++ function like void readEmStar( int *arrayOfInt ) { } vs a C++ function like: void readEmSquare( int arrayOfInt[] ) { } What is the difference between using [square brackets] vs *asterisk, and does anyone have a style guide as to which is preferrable, assuming they are equivalent to the compiler? ...
When you use the type char x[] instead of char *x without initialization, you can consider them the same. You cannot declare a new type as char x[] without initialization, but you can accept them as parameters to functions. In which case they are the same as pointers. When you use the type char x[] instead of char *...
1,790,932
1,790,952
Get Directory from User
I'm looking for a function to get a directory path from the user; I need to solicit a place to put things. I tried using GetOpenFileName() with .dir as a filter but no joy. I found something called GetDirectoryViaBrowse() that sounds like it might do what I want but it's part of some wizard making package and my Visu...
You are looking for the Win32 Shell API: SHBrowseForFolder
1,790,949
1,790,972
external vs internal linkage and performance
let's say i have 3 functions inside a class : class Foo { inline void FooInline() { /* bla bla */ } static void fooStatic(); void foo(); }; as i understand the last two have external linkage while the first have internal. i want to know which function will be the fastest to call to , and what's the tradeof...
No, all three have external linkage. Member functions of a non-local class always have external linkage in C++. Moreover, inline has no effect on linkage, even if it is a non-member function. Linkage has no effect on efficiency. Inlining might have, but it depends on too many variables.
1,791,447
1,795,071
Copying between VARIANT and _variant_t
I'm fairly certain that I can safely do: void funcA(VARIANT &V,_variant_t &vt) { vt = V; } But what about the other way around: void funcB(VARIANT &V,_variant_t &vt) { V = vt; } I've been seeing some REALLY weird behaviour in my app which I put down to COM-related threading issues. But then I got wondering if...
First of all, yes, by using the assignment operator the way you do in funcB() you invoke shallow copying only (you might want to look into oaidl.h to see the VARIANT definition - it has no user-defined assignment operator and therefore shallow copying is done by the compiler). This gets you into undefined behaviour if ...
1,791,578
1,791,609
How do I convert a char string to a wchar_t string?
I have a string in char* format and would like to convert it to wchar_t*, to pass to a Windows function.
Does this little function help? #include <cstdlib> int mbstowcs(wchar_t *out, const char *in, size_t size); Also see the C++ reference
1,791,783
1,794,458
Assembler and C++ relation
Is there any tutorial or explanation anywhere on how C++ objects translate into assembler instructions moving data between registers... I don't really understand how we are manipulating object in higher level languages where in Assembler you're essentially moving data between registers? Plus doing some basic operati...
Disclaimer: I will use IA-32 assembly for samples. Typically, each object is a structure residing block of memory allocated either on heap (via new call) or on stacK (basically, by moving esp to reserve memory for it). After memory is allocated, pointer is passed to object constructor for initialization (note that ctor...
1,792,147
1,792,176
Comparing character arrays and string literals in C++ without cstring
In my programming class we currently have a project that requires us to take arguments into the program. I then need to be able to check one of the arguments to see which value was passed to the program so that I can choose the appropriate behavior for the program to follow. In a previous homework assignment I did this...
Try this: if (argv[1] == std::string("yes")) { stuff } If the intent of the exercise is to teach how string comparisons work, then implement a for loop like other answers suggest. However, in C++ you are not supposed to use strcmp - there is a string class for a reason.
1,792,253
1,792,410
Default template parameters with forward declaration
Is it possible to forward declare a class that uses default arguments without specifying or knowing those arguments? For example, I would like to declare a boost::ptr_list< TYPE > in a Traits class without dragging the entire Boost library into every file that includes the traits. I would like to declare namespace boos...
Any compilation unit that uses your facility that forward-declares boost stuff will need to include the boost headers anyway, except in the case that you have certain programs that won't actually use the boost part of your facility. It's true that by forward-declaring, you can avoid including the boost headers for su...
1,792,275
1,792,330
Difference between WinMain and wWinMain
The only difference is that Winmain takes char* for lpCmdLine parameter, while wWinMain takes wchar_t*. On Windows XP, if an application entry is WinMain, does Windows convert the command line from Unicode to Ansi and pass to the application? If the command line parameter must be in Unicode (for example, Unicode file...
On Windows XP, if an application entry is WinMain, does Windows convert the command line from Unicode to Ansi and pass to the application? Yes. If the command line parameter must be in Unicode (for example, Unicode file name, conversion will cause some characters missing), does that mean that I must use wWinMain as ...
1,792,360
1,793,767
What are the limits of Python?
I spent a few days reading about C++ and Python and I found that Python is so much simpler and easy to learn. So I wonder does it really worth spending time learning it? Or should I invest that time learning C++ instead? What can C++ do and Python can't ?
Some Python limits : - Python is slow. It can be improved in many ways (see other answers) but the bare bone cPython is 100 times slower that C/C++. This problem is getter more and more mitigated. With Numpy, Pypy and asyncio, most performance problems are not covered, and only very specific use cases are a bottleneck...
1,792,380
1,792,431
How I can use mysql in C++?
I have searched a lot, all I found is a "mysql++" but I don't know how to install it. I don't have knowledge about libraries in C++!
Searching google for "c++ mysql tutorial" brings back the following Developing Database Applications Using MySQL Connector/C++ and A Tiny MySQL++ Tutorial; C++ and MySQL; MySQL++ Example Which in turn links to... Installing MySQL++; How to install MySQL++ on Linux-CentOS And looking through the first article I found th...
1,792,520
1,792,766
slightly weird C++ code
Sorry if this is simple, my C++ is rusty. What is this doing? There is no assignment or function call as far as I can see. This code pattern is repeated many times in some code I inherited. If it matters it's embedded code. *(volatile UINT16 *)&someVar->something; edit: continuing from there, does the following addi...
This is a fairly common idiom in embedded programming (though it should be encapsulated in a set of functions or macros) where a device register needs to be accessed. In many architectures, device registers are mapped to a memory address and are accessed like any other variable (though at a fixed address - either poin...
1,792,521
1,792,565
What does this warning message mean?
Product.cpp:34: warning: the address of ‘QTextStream& endl(QTextStream&)’, will always evaluate as ‘true’ Product.cpp: In member function ‘void Product::setProductToSold()’: Product.cpp:45: warning: the address of ‘QTextStream& endl(QTextStream&)’, will always evaluate as ‘true’ #include <string> #include <iostream> ...
Are you (or Qt) redefining endl? try putting std::endl
1,792,578
1,792,591
Benefits of exporting a class from a dll vs. static library
I have a C++ class I'm writing now that will be used all over a project I'm working on. I have the option to put it in a static library, or export the class from a dll. What are the benefits/penalties for each approach. The only one I can think of is compiled code size which I don't really care about. Thanks!
Advantages of a DLL: You can have multiple different exe's that access this functionality, so you will have a smaller project size overall. You can dynamically update your component without replacing the whole exe. If you do this though be careful that the interface remains the same. Sometimes like in the case of LG...
1,792,581
1,792,735
C++ from C#: C++ function (in a DLL) returning false, but C# thinks it's true!
I'm writing a little C# app that calls a few functions in a C++ API. I have the C++ code building into a DLL, and the C# code calls the API using DllImport. (I am using a .DEF file for the C++ DLL so I don't need extern "C".) So far the API has one function, which currently does absolutely nothing: bool Foo() { retur...
Try [return: MarshalAs (UnmanagedType.I1)]. By default, C# interop marshals C# bool as the Win32 BOOL, which is the same as int, while C++ bool is one byte AFAIR. Thus, C#'s default marshaling expects the return value to be a BOOL in the eax register, and picks up some non-zero garbage because C++ bool is returned in a...
1,792,678
1,979,344
Wrapping a Lua object for use in C++ with SWIG
Currently I know how to have C++ objects instantiated and passed around in Lua using SWIG bindings, what I need is the reverse. I am using Lua & C++ & SWIG. I have interfaces in C++ and objects in lua, that implement methods which do the same job and have the same structure. I would like to be able to instantiate these...
What I seem to gather from your examples and the discussions is that you are expecting Lua to be the primary language, and C++ to be the client. The problem is, that the Lua C interface is not designed to work like that, Lua is meant to be the client, and all the hard work is meant to be written in C so that Lua can ca...
1,793,037
1,798,973
How do I add a header with data to a QTableWidget in Qt?
I'm still learning Qt and I am indebted to the SO community for providing me with great, very timely answers to my Qt questions. Thank you. I'm quite confused on the idea of adding a header to a QTableWidget. What I'd like to do is have a table that contains information about team members. Each row for a member should ...
At the request of the person who steered me toward the right place, I am posting the way I accomplished this as an answer and I am accepting it. m_ui->teamTableWidget->setColumnCount(m_ui->teamTableWidget->columnCount()+1); QTableWidgetItem* qtwi = new QTableWidgetItem(QString("Last"),QTableWidgetItem::Type); ...
1,793,082
1,793,127
How to dynamically create a union instance in c++?
I need to have several instances of a union as class variables, so how can I create a union instance in the heap? thank you
The same as creating any other object: union MyUnion { unsigned char charValue[5]; unsigned int intValue; }; MyUnion *myUnion = new MyUnion; Your union is now on the heap. Note that a union is the size of it's largest data member.
1,793,123
1,796,766
Map functions of a class while declaring the functions
My previous question about this subject was answered and I got some tests working nice. Map functions of a class My question is now, if there is a way to while declaring the function, be able to register it in a map, like I realized in this question about namespaces and classes: Somehow register my classes in a list th...
What is your problem here ? The problem is that, unfortunately, in C++ functions are not considered first class members. Oh sure there are those pointers to functions that work pretty well, but there is no generic function type or anything like that. There are however ways to work around this, the simplest I think bein...
1,793,257
1,793,293
How can I solve this median programming problem in C++
Formulate the steps of identifying the median from five unique numbers and visualize them in flow chart. Develop an application that shows the median after getting five unique numbers from users. Extend the feature for allowing six unique numbers input and computing the median. Example: Input: 5 4 2 1 10 Output: Medi...
Trying to give homework-friendly advice: 1) Make sure you know how to get a Median. Can you, in your head or on paper, figure it out? Now, how do you write a program to do this for you? Make a flowchart. 2) Write the program to do it. A user gives your program 5 numbers, your program gives the median as an answer. ...
1,793,413
1,793,431
Distribute C++ application as .exe or .msi?
I am looking for a program that can take the program I made in Visual C++ 2008 and distribute it in a mature installer for Windows. I want an application that is FREE (or trial). The setup and deployment folder is not there when a select File-->Add-->New Project
You can try NSIS (Nullsoft Scriptable Install System), which is free, but can be confusing because it's lots of scripts. That said, it can do anything you might want to do. Install Creator from ClickTeam is very simple to use and is my preferred application but it does cost money.
1,793,439
1,793,464
Heap Implementations
In a heap implementation of the ADT priority queue, the item with the highest priority value is always in the front or root of the array? Or is it, where the ADT priority queue that has the highest priority value is in the n-1 slot of the array?
The way Priority Queues are implemented, the highest priority value is always at the first (zeroth) position of the array. They are typically implemented as a heap: index 0 1 2 3 4 5 6 7 8 9 parent / 0 0 1 1 2 2 3 3 4 This is because the parent is easily found by (index - 1) / 2 (when using integer division)
1,793,577
1,793,615
Overloading Default Construction with Initializer List
I need to know how to get something to work. I've got a class with a constructor and some constants initialized in the initializer list. What I want is to be able to create a different constructor that takes some extra params but still use the initializer list. Like so: class TestClass { const int cVal; int new...
There's no way for one constructor to delegate to another constructor of the same class. You can refactor common code into a static member function, but the latter cannot initialize fields, so you'll have to repeat field initializers in every constructor you have. If a particular field initializer has a complicated exp...
1,793,590
1,796,116
C++ dynamic allocated array
I'm doing some assignment and got stuck at one point here. I am trying to write an list_add() function. The first functionality of it is to add values to the array. The second functionality for it is to increase the size of the array. So it works much like a vector. I dunno if I get it right though. What I tried is to ...
There four problems with the implementation of your code: It doesn't copy the elements of the list. It doesn't assign the value of new_list to the list variable in main It inserts values from the back to the front, instead of after the last value max_size doesn't get updated. It's easy to miss this, because you only i...
1,793,691
1,793,711
std::time(0) performance
I was wondering what the performance implications are of using std::time(0) to seed random number generators. I assume that it's a system call (if not please correct me), which generally isn't the best option regarding performance. Assuming std::time(0) is used many times throughout a program, will there be severe perf...
Reseeding the RNG should be a rather rare event, so I don't think you need to be concerned about performance. If you are reseeding frequently enough to cause a performance issue, you might want to rethink your approach -- you may be doing more harm than good.
1,793,800
1,794,089
Can I redefine a C++ macro then define it back?
I am using both the JUCE Library and a number of Boost headers in my code. Juce defines "T" as a macro (groan), and Boost often uses "T" in it's template definitions. The result is that if you somehow include the JUCE headers before the Boost headers the preprocessor expands the JUCE macro in the Boost code, and then...
As greyfade pointed out, your ___T___ trick doesn't work because the preprocessor is a pretty simple creature. An alternative approach is to use pragma directives: // juice includes here #pragma push_macro("T") #undef T // include boost headers here #pragma pop_macro("T") That should work in MSVC++ and GCC has ad...
1,793,807
1,793,825
Declaring a variable in an if-else block in C++
I'm trying to declare a variable in an if-else block as follows: int main(int argc, char *argv[]) { if (argv[3] == string("simple")) { Player & player = *get_Simple(); } else if (argv[3] == string("counting")) { Player & player = *get_Counting(); } else if (argv[3] == string("competitor")) ...
Your problem is that player falls out of scope in each if / else if block. You need to declare your variable above all of the if statements. But you can't use a reference for that because you must initialize a reference right away. Instead you probably want something like this: int main(int argc, char *argv[]) { ...
1,793,884
1,794,063
QComboBox with single value: Select this value
I have a QComboBox which changes its selection possibilities depending on certain conditions. Because of special combinations, it might have only one selection left over, which has to be "confirmed" by the user, preferably by looking at all possible selections, seeing that there is only one, and then selecting this. M...
Use SIGNAL(highlighted(...)) instead of SIGNAL(activated(...)). Or do a setCurrentIndex(-1) before, this should work with activated().
1,794,069
1,794,082
Why do I get an EXC_BAD_ACCESS here and how can I make it work?
I'm trying to make my code be able to separate a file into a customer database (it's delimited by many spaces and not tabs). I try to use strtok, but I get an EXC_BAD_ACCESS error. Here is my main.cpp code: #include <iostream> #include <fstream> #include <string> #include <sstream> #include "Cust.h" using namespace std...
It is illegal to attempt to modify the string returned by std::string::c_str() method. strtok will make such an attempt (the fact that you had to cast away the constness of the returned string is a dead giveaway). In other words, you can't use strtok on the result of std::string::c_str(). Either get rid of strtok (bett...
1,794,223
1,794,580
Ideas for computer science project with CORBA or ICE
We have to perform a semester project with distributed computing using CORBA or ICE. It is a single-person project and we have a couple of months of time. For the programming language I'd like to focus on c# for it may be any other like C++. I don't want to write the one millionth prime generator, maybe there is someth...
If I were you, ....what I would do is go to your prof and ask to work outside the lines. Ask to be released from the CORBA or ICE requirement. Ask if you can use something that is NOT Corba. Ask if you can use REST, or XML Web services, or even protobufs. CORBA is not irrelevant, as far as the principles go, but i...
1,794,233
1,794,389
Is there any good tree manipulation (template) libraries for C++ out there?
Is there any good tree manipulation (template) libraries for C++ out there that can do basic things like binary tree. Though it is not difficult to write a binary tree all from scratch, but I'm really surprised that it is not so easy to find one ready-for-use.
What do you need the tree for? There may already be something in the STL or Boost that satisfies your need. For example: the STL std::map<key,value> is usually implemented as a balanced binary tree. There is also tree.hh which implements an STL-like n-way tree.
1,794,271
1,794,462
Could not deduce template argument for T[]
Now I'm getting another error. error C2065: 'temp' : undeclared identifier I know that for temp I need to declare the type of the array like int temp[], but what if I don't know what it is? It could be int or string or double. How can I create a temp array without specifying its type? I added my Mergesort function. H...
T a[] means you expect an array of T as the parameter type - but thats a C array, not a class type. Your class template Array is just that - a class template that only happens to provide convenience access to its contents via operator[](). To fix the first error change Quicksort()s signature to: template<class T> void ...
1,794,418
1,798,312
Boost Property Tree and Xml parsing Problems
I'm using boost::property_tree. The documentation is very vague and overall unhelpful for the most part. Looking at the source/examples didn't help that much, either. What I'm wondering is the following: <VGHL> <StringTable> <Language>EN</Language> <DataPath>..\\Data\\Resources\\Strings\\stringtable...
ParseEntry receives a reference to each of the children nodes of the current level. So, you cannot ask the values using the node name, because you already have a child node. The node name is stored in v.first. You can iterate over all the elements at a given level using get_child to select the level and then BOOST_FOR...
1,794,640
1,794,926
Function Template Specialization on Function Pointers
I have a sanitization function that I want to run on (traditional) pointer types only. My problem is with function templates I can get as far as limiting the function to only pointers, however because of casting rule differences between function pointers and regular pointers, I run into problems. The Sanitize() func...
While this problem could be solved manually, its easiest to utilize Boosts type traits and SFINAE helper to selectively disable the overload for pointers if T* is a function pointer: template<typename T> typename boost::disable_if<boost::is_function<T>, T*>::type Sanitize(T* value) { // ... }
1,794,689
1,794,768
Code smell in this switch statement?
I'm wondering where a switch statement of this style should be changed to an if else statement. switch (foo) // foo is an enumerated type { case barOne: if (blahOne) { DoFunction(//parameters specific to barOne); break; } case barTwo: if (blahTwo) {...
It seems like this might do strange things in some cases. What if foo == bar1, and blahOne is false, but blahTwo is true? Then you'll fall through and call the function under the foo == bar2 case, even though foo doesn't equal bar2. That might be unexpected in practice, but if it ever did occur it might be tough to d...
1,794,818
1,794,830
Measuring absolute time taken by a process
I am measuring time taken by my process using QueryPerformanceCounter and QueryPerformanceFrequency. It works fine. As my system is a single processor based system. So many process sharing it.Is it possible to measure CPU time allotted to my process. SO that i can measure absolute time taken. Platform : Windows Langua...
GetProcessTimes is probably the call you're looking for.
1,794,919
2,119,338
Finding the index of an entry in a linked list in better than O(n) time
I have a scenario where I'm pushing change-lists to another system. Each list contains zero or more inserted, updated or deleted notifications. Inserting is easy; the notification contains the target index and a pointer to the item. Updating is easy; I pass a pointer to the item. Deleting seems straight-forward; I ...
Skip List is the correct solution.
1,795,013
1,795,041
C++: how to use std::less<int> with boost::bind and boost::lambda?
I am trying to lean boost::bind, boost::lambda libraries and how they can be used with STL algorithms. Suppose I have vector of int-string pairs which is sorted by int key. Then a place to insert a new pair while keeping the vector sorted can be found as follows: std::vector<std::pair<int, string> > entries; ... int k ...
All you're missing is another bind (and the template parameters on pair): std::lower_bound(entries.begin(), entries.end(), k, boost::bind(comparator, boost::bind(&std::pair<int, string>::first, _1), k)) You don't have to do that on the less-th...
1,795,020
1,811,399
C++ and C# COM Event Performance. Help
Good day. CppApp and CsApp Event Handle Design Changed. For Industry application. Old design. CsApp pull event from CppApp. There are a lot of events from CppApp. So we created two threads in CsApp to handle the events from CppApp. It worked very well. New design. CsApp and CppApp com event (fire event method) design...
It isn't clear to me what the difference is between "we tested and it on simulation mode and it worked very well" and "real machine online testing at industry online production envrionment": What are the differences between the simulation machine and the production machine? Can you simulate these differences? When you...
1,795,021
1,795,126
Writing a C++ DLL, then wrapping it in C#
I am a bit confused about wrapping a c++ dll in c#. What kind of dll should i create? A normal dll or an mfc dll? Should i prefix every proto with "extern..." ? Should i write the functions in a def file? My last effort was in vain, c# would crash with an error like "bad image format", which means that the dll format i...
Are you using a 64-bit PC? "Bad image format" will occur on an x64 system if you try to mix x64 code and x86 code. This will happen if you write C# code (targeted to "Any CPU", so it'll jit-compile to x64 code) that calls an unmanaged DLL (that will probably be x86 by default). Two solutions to this are: (Proper solut...
1,795,658
1,858,689
Looping over the non-zero elements of a uBlas sparse matrix
I have the following sparse matrix that contains O(N) elements boost::numeric::ublas::compressed_matrix<int> adjacency (N, N); I could write a brute force double loop to go over all the entries in O(N^2) time like below, but this is going to be too slow. for(int i=0; i<N; ++i) for(int j=0; j<N; ++j) std::co...
You can find the answer in this FAQ: How to iterate over all non zero elements? In your case it would be: typedef boost::numeric::ublas::compressed_matrix<int>::iterator1 it1_t; typedef boost::numeric::ublas::compressed_matrix<int>::iterator2 it2_t; for (it1_t it1 = adjacency.begin1(); it1 != adjacency.end1(); it1++) ...
1,795,784
1,795,858
Copy to Program Files under Windows Vista/7
I have written a wizard in C++ which installs some files to the program files folder under windows. As I understand, I need Admin rights to write to program files under Vista/7. So my question is: Is there a way to turn on Admin rights while the application is running respectively only for one wizard page? Or do I have...
Typically you have a shield logo'd button and then shell out to another process whose manifest requests elevation. But really it sounds like you're writing an installer so you should use something designed for that like WiX. See also this similar question and this cited article from one of the answers thereof
1,795,816
1,795,950
Can a C++ Class Constructor Know Its Instance Name?
Is it possible to know the object instance name / variable name from within a class method? For example: #include <iostream> using namespace std; class Foo { public: void Print(); }; void Foo::Print() { // what should be ????????? below ? // cout << "Instance name = " << ?????????; } int ma...
Not with the language itself, but you could code something like: #include <iostream> #include <string> class Foo { public: Foo(const std::string& name) { m_name = name;} void Print() { std::cout << "Instance name = " << m_name << std::endl; } private: std::string m_name; }; int main() { Foo a("a"...
1,796,030
1,796,849
What kind of message can be transported through ActiveMQ?
We are building a distributed system, maybe a c# app will talk to a c++ app, and maybe some jpeg image will ben send between, is this possible with Activemq?
As far as I know, you can transport any XML message, and also binary messages (blob messages, see http://activemq.apache.org/blob-messages.html). Since ActiveMQ won't try to interpret the binary message, you can safely send JPEGs or other stuff around.
1,796,046
1,796,154
Can a reference type be used as the key type in an STL map
Can I construct an std::map where the key type is a reference type, e.g. Foo & and if not, why not?
According to C++ Standard 23.1.2/7 key_type should be assignable. Reference type is not.
1,796,193
1,798,058
Mysql++ "undefined reference to __imp___ZN7mysqlpp10ConnectionC1Eb"
I am trying to install the mysql++ in Code::Blocks, but When I try to run the example code I get this error: undefined reference to __imp___ZN7mysqlpp10ConnectionC1Eb What I am doing wrong?
You must build MySQL++ with the exact same compiler and compiler options as you're using to build your program. What you're seeing is a name mangling and/or ABI mismatch due to mixing compilers and/or build options. This can be anything from a drastic error like trying to use a Visual C++ DLL with MinGW, to something...
1,796,225
1,796,845
Get stack trace from uncaught exception?
I realise this will be platform specific: is there any way to get a stack trace from an uncaught C++ exception, but from the point at which the exception is thrown? I have a Windows Structured Exception Handler to catch access violations, etc. and generate a minidump. But of course that won't get called in the event of...
We implemented MiniDumps for unhandled exceptions in our last title using the information from this site: http://beefchunk.com/documentation/sys-programming/os-win32/debug/www.debuginfo.com/articles/effminidumps.html And to catch the unhandled exceptions on windows have a look at: SetUnhandledExceptionFilter (http://ms...
1,796,353
1,796,857
CMake linking problem
I am trying to use CMake to compile a C++ application that uses the C library GStreamer. My main.cpp file looks like this: extern "C" { #include <gst/gst.h> #include <glib.h> } int main(int argc, char* argv[]) { GMainLoop *loop; GstElement *pipeline, *source, *demuxer, *decoder, *conv, *sink; GstBus *bus; /...
Doh, just needed to replace CMAKE_LINKER_FLAGS with CMAKE_EXE_LINKER_FLAGS.
1,796,524
1,796,548
Member assignment in a const function
I have a class member myMember that is a myType pointer. I want to assign this member in a function that is declared as const. I'm doing as follows: void func() const { ... const_cast<myType*>(myMember) = new myType(); ... } Doing this works fine in VC++, but GCC gives an error with the message "lvalue ...
The code wont actually work in VC++ - you're not updating the value (or at least it shouldnt), hence the warning from GCC. Correct code is const_cast<myType*&>(myMember) = new myType(); or [from other response, thanks :P]: const_cast<ThisType*>(this)->myMember = new myType(); Making it mutable effectively means you g...
1,796,587
1,796,617
How to use std::wstring with std::istringstream?
I am trying to write a template function which will extract the value of the given datatype from the given string. I came up with something like this: template<class T> static T getValue(const CString& val_in) { std::wstring value = val_in; std::istringstream iss; iss.str(value); ...
My compiler has wistringstream -- this is all it is: typedef basic_istringstream<wchar_t> wistringstream;
1,796,629
1,797,860
Compile issues based on different platforms
I'm compiling a solution which runs fine on the PC but when trying to compile it for a different platform I get the following error: "Unhandled Exception: System.ArgumentException: An item with the same key has already been added." Anyone know what it could mean?
This is a .NET exception message. Hmm, you definitely tagged it as C++. I'd guess you found a bug in your IDE or whatever tool you use to build your project.
1,796,829
1,796,865
Is there any C++ code beautifuler plug-in for eclipse?
I found a very tempting function in Netbeans, which is to re-factor or 'beautiful-ize' the c++ code according to some parameters, such as tab length, {'s position, etc is there anything similar in Eclipse, which keyword should I google?
Go to your code window Right click Select "Source" then "Format" This should reformat your code according to the options given in the Preferences => "C/C++" => "Code Style
1,797,128
1,797,813
Programmatically differentiating between USB Floppy Drive and USB Flash Drive in Windows
On Windows (XP-7), is there a reliable way of programatically differentiating between USB floppy drives and USB flash drives in C++? At the moment, I'm using WMI to get updates when new Win32_LogicalDisk instances are detected, and then using the DriveType attribute of the LogicalDisk object to figure out a basic type....
Did you try Win32_LogicalDisk.MediaType? It has specific enumerations for floppy disks. Make sure you try it when there's no disk in the drive.
1,797,240
1,797,317
Implementing a File Object (C++)
I've been looking over the Doom 3 SDK code, specifically their File System implementation. The system works (the code I have access to at least) by passing around an 'idFile' object and I've noticed that this class provides read and write methods as well as maintaining a FILE* member. This suggests to me that eithe...
You can open a FILE* in read-write mode. If you do that, you should flush and seek to a known location when changing between reading and writing, but you don't have to reopen the file.
1,797,287
1,797,464
virtual function - vtable
Let's say I have class A who inherits from class B and C (multiple inheritance). How many vtable members class A would have ? What's the case in single inheritance ? In addition, suppose: Class A : Public B {} and: B* test = new A(); Where does test gets its vtable from? What's assignment? I assume it gets B's par...
First, vtable's are implementation specific. In fact, nowhere in the standard is specified that vtable's must exist at all. Anyway, in most usual cases, you would get one vtable pointer per base class with virtual functions. And, as Yuval explained, nobody "fills" the vtable's when an object is constructed; you have ...
1,797,351
1,797,760
virtual derived class of a non-virtual base class
I have a virtual class that has been derived from a non virtual class. But when I c-style cast the derived class to base class, the class is corrupted. I am looking at the member variables using the debugger and the member variables are all corrupted when I do that cast. I see there is a 4 byte discrepency when I do th...
When you cast pointers across the hierarchy, actual numerical pointer values might change. There's nothing wrong with the fact that it changes. There's noting wrong with such a cast. How the numerical pointer values change depend on the physical layout of the class. It is an implementation detail. In your example, the ...
1,797,380
1,797,539
Template specialization with a templatized type
I want to specialize a class template with the following function: template <typename T> class Foo { public: static int bar(); }; The function has no arguments and shall return a result based on the type of Foo. (In this toy example, we return the number of bytes of the type, but in the actual application we want ...
Partitial specialization is valid only for classes, not functions. Workaround: template <typename U, typename V> class Foo<std::pair<U, V> > { public: static int bar() { return Foo<U>::bar() + Foo<V>::bar(); } }; If you does not want to specialize class fully, use auxiliary struct template<class T> struct aux { st...
1,797,769
1,869,231
Recoloring an image based on current theme?
I want to develop a program which recolors the input image based on the given theme the same way as ms-powerpoint application does. I am giving following link that shows what exactly i want to do. I want to generate images same as images in below link under the Dark Variations and light Variations title based on the c...
I must say thanks to Mark and Patrice for ur guidance which helped me achieved it. For light variation, I have done it by converting the theme colors to HSV colorspace and found relation between output color and theme color for black color (input) . The relation was found to be linear for saturation and value and hue ...
1,798,112
1,798,170
Removing leading and trailing spaces from a string
How to remove spaces from a string object in C++. For example, how to remove leading and trailing spaces from the below string object. //Original string: " This is a sample string " //Desired string: "This is a sample string" The string class, as far as I know, doesn't provide any methods ...
This is called trimming. If you can use Boost, I'd recommend it. Otherwise, use find_first_not_of to get the index of the first non-whitespace character, then find_last_not_of to get the index from the end that isn't whitespace. With these, use substr to get the sub-string with no surrounding whitespace. In response to...
1,798,538
1,798,637
Looking for some refactoring advice
I have some code that I had to write to replace a function that was literally used thousands of times. The problem with the function was that return a pointer to a static allocated buffer and was ridiculously problematic. I was finally able to prove that intermittent high load errors were caused by the bad practice. ...
If you really do mean "no impact on the callers", your choices are very limited. You can't return anything that needs to be freed by the caller. At the risk of replacing one bad solution with another, the quickest and easiest solution might be this: instead of using a single static buffer, use a pool of them and rotate...
1,798,631
1,798,671
c++ vector of class object pointers
What I am trying to do is essentially create two vectors of objects, where some objects are entered into both lists and some are just entered into one. The first problem I found was that when I used push_back() to add an object into both lists the object was copied so that when I changed it from one list the object did...
There's some details missing, but at a guess. nurbsMesh goes out of scope between the push_back and the absorbList[0]->receivedPower. So now your vector of pointers contains a pointer to an object that doesn't exist anymore. Try adding a copy constructor to your AbsorbMesh class and adding to your vector like this. a...
1,798,978
1,799,104
How to check if a file is a DLL?
Given a file, I want to check if this is a DLL, or a shared object (Linux) or a dylib (Mac OS X), or something different. My main interest is differentiating executable and DLL on Linux and Mac OS X. For windows, the extension should be enough for my problem. I already checked that the magic number technique doesn't wo...
The Unix (Linux and Mac OS X) command file knows how to identify file types. man file tells you about the 'magic' information used to do this, and in particular where the file with that information is to be found. man 5 magic describes the file in detail and should also tell you where it lives. You can take a look in t...
1,799,063
1,799,310
How can I display unicode characters in a linux terminal using C++?
I'm working on a chess game in C++ on a linux environment and I want to display the pieces using unicode characters in a bash terminal. Is there any way to display the symbols using cout? An example that outputs a knight would be nice: ♞ = U+265E.
To output Unicode characters you just use output streams, the same way you would output ASCII characters. You can store the Unicode codepoint as a multi-character string: std::string str = "\u265E"; std::cout << str << std::endl; It may also be convenient to use wide character output if you want to output a single ...
1,799,070
1,799,293
What might cause OpenGL to behave differently under the "Start Debugging" versus "Start without debugging" options?
I have written a 3D-Stereo OpenGL program in C++. I keep track of the position objects in my display should have using timeGetTime after a timeBeginPeriod(1). When I run the program with "Start Debugging" my objects move smoothly across the display (as they should). When I run the program with "Start without debuggi...
The most common thing that causes any program to behave differently while being debugged and not being debugged is using uninitialized variables and especially reading uninitialized memory. Check that you're not doing that. Something more OpenGL specific - You might have some problems with flushing of commands. Try ins...
1,799,072
1,799,077
C++ short-circuiting of booleans
I'm new to c++ and am curious how the compiler handles lazy evaluation of booleans. For example, if(A == 1 || B == 2){...} If A does equal 1, is the B==2 part ever evaluated?
No, the B==2 part is not evaluated. This is called short-circuit evaluation. Edit: As Robert C. Cartaino rightly points out, if the logical operator is overloaded, short-circuit evaluation does not take place (that having been said, why someone would overload a logical operator is beyond me).
1,799,157
1,799,165
Implicit type conversions in expressions int to double
I've been trying to reduce implicit type conversions when I use named constants in my code. For example rather than using const double foo = 5; I would use const double foo = 5.0; so that a type conversion doesn't need to take place. However, in expressions where I do something like this... const double halfFoo = foo...
The 2 is implicitly converted to a double because foo is a double. You do have to be careful because if foo was, say, an integer, integer division would be performed and then the result would be stored in halfFoo. I think it is good practice to always use floating-point literals (e.g. 2.0 or 2. wherever you intend for...
1,799,445
1,799,531
Function template in non-template class
I'm sure that it is possible but I just can't do it, which is: How can I define function template inside non-template class? I tryied something like this: class Stack_T { private: void* _my_area; static const int _num_of_objects = 10; public: // Allocates space for objects added to stac...
Don't put the <T> after the function name. This should work: template<class T> void Stack_T::put(const T& obj) { } This still won't work if the function definition is not in the header file. To solve this, use one of: Put the function definition in the header file, inside the class. Put the function definition in th...
1,799,497
1,799,503
C++ overloaded function issue
Why does the compiler not find the base class function signature? Changing foo( a1 ) to B::foo( a1 ) works. Code: class A1 ; class A2 ; class B { public: void foo( A1* a1 ) { a1 = 0 ; } } ; class C : public B { public: void foo( A2* /*a2*/ ) { A1* a1 = 0 ; foo( a1 ) ; } } ; int main() { A2...
The name C::foo shadows the name B::foo. Once the compiler finds the matching foo in class C, it stops searching any further. You can resolve your problem by adding: using B::foo; to the body of class C, or by renaming the function in class B.
1,799,507
1,799,532
Combo box inside of list control? (Unmanaged C++)
I'm using unmanaged C++ and I was wondering if I could embed a combo box inside a column of my List View. I have tried googling for information, however I keep finding C# articles on the subject. It seems like the LVCOLUMN's mask can support text and images but I am not finding anything about controls. Any ideas on the...
You can create a floating combo box and position it over the selected row and column of the list control. You'll need to trap all selection related operations on the list control and show, hide, or move and update the contents of the combo box.
1,799,664
1,799,906
Passing Exception Types down through a menu
So I've come across this problem and I can't seem to solve it. Basically I've got a menu of tests, it can be of arbitrary depth, it's just a way of organizing tests and at the lowest level has specific test-cases. As it stands right now everything seems to work, however I'd like to implement a system where you can spec...
I'm not sure if I understand your question well. However as far as I understood your problem is that now add creates an object depending on the specified exception type and thous you cannot store it in internal vector. You might try to use a common base class. Make the vector store a pointer to non-template base class ...
1,799,697
1,799,720
New not allocating enough memory?
Well, I'm taking packets straight off the wire and extracting TCP streams from them. In the short, this means stripping off the various headers (eg, eth->IP->TCP->stream data). In the function that is called when I've finally gotten through all the headers, I am experiencing a strange error. /*Meta is a pointer...
stream->streamData = new u_char(len); This allocates a single character, intialized to len. To allocate an array, use: stream->streamData = new u_char[len]; And where-ever you deallocate it: delete [] stream->streamData; Edit: stream->streamData[len] = offset(pkt)[0]; //Fails, scary That would be undefined behavi...
1,799,733
1,799,744
foreach algorithm in C++
Is there a way to have a return value from the function that I pass to foreach. For ex: I have, void myfunction (int i) { cout << " " << i; } vector<int> myvector; myvector.push_back(10); for_each (myvector.begin(), myvector.end(), myfunction); Lets say, I want to count the number of elements in the vector u...
No. But you can make myfunction a functor, pass it a pointer to some memory, and store your return value through that pointer. struct MyFunctor { int *count; MyFunctor(int *count_) : count(count_) { } void operator()(int n) { if (n > 5) (*count)++; } }; int main() { vector<int> vec; for...
1,799,737
1,799,804
Benefits of opening a file for read and write
Can anyone point me to some discussion covering the pro's and con's of opening a file for read and write as opposed to (for example) opening a file for read, closing it and then reopening for write. I've tried searching for in-depth information without joy. Many thanks
It depends on what you're doing. Opening for read and write can be harder to get correct and consistent as it's very easy to accidentally truncate the file or overwrite parts of the data unintentionally. If reading and then writing (presumably a complete replacement) is actually an option, then two separate file opens ...
1,800,138
1,800,193
Given a start and end point, and a distance, calculate a point along a line
Looking for the quickest way to calculate a point that lies on a line a given distance away from the end point of the line: void calculate_line_point(int x1, int y1, int x2, int y2, int distance, int *px, int *py) { //calculate a point on the line x1-y1 to x2-y2 that is distance from x2-y2 *px = ??? *py =...
I think this belongs on MathOverflow, but I'll answer since this is your first post. First you calculate the vector from x1y1 to x2y2: float vx = x2 - x1; float vy = y2 - y1; Then calculate the length: float mag = sqrt(vx*vx + vy*vy); Normalize the vector to unit length: vx /= mag; vy /= mag; Finally calculate the n...
1,800,250
1,800,466
Is there a better way to create this game loop? (C++/Windows)
I'm working on a Windows game, and I have this: bool game_cont; LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_QUIT: case WM_CLOSE: case WM_DESTROY: game_cont = false; break; } return DefWindowProc(hWnd, msg, wParam, lParam); } int WINAPI WinMain(...
Yes, use PeekMessage, it's the standard in game development. This is the best approach, I believe: int Run() { MSG msg; while(true) { if(::PeekMessage(&msg,0,0,0 PM_REMOVE)) { if(msg.message == WM_QUIT || msg.message == WM_CLOSE || ...
1,800,423
1,800,464
What is the performance penalty of operator overloading STL
I like STL a lot. It makes coding algorithms very convenient since it provides you will all the primitives like parition, find, binary_search, iterators, priority_queue etc. Plus you dont have to worry about memory leaks at all. My only concern is the performance penalty of operator overloading that is necessary to get...
When using stl algortithms on generic types, you have to supply the comparison logic in some way. Operator overloading has no performance penalty over any other function and may (like any other function) be inlined to remove any function call overhead. Many standard containers and algorithms also use std::less and henc...
1,800,544
1,803,799
Are there well-defined size limits in FormatMessage?
I am having a problem when arguments passed to FormatMessage are too long. void testMessage(UINT id, ...) { va_list argList; va_start(argList, id); LPTSTR buff = NULL; const char* str = "The following value is invalid: %1"; DWORD success = FormatMessage(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_A...
Are you calling FormatMessageA or FormateMessageW ? If you call FormatMessageA, your 32K ASCII message will be marshalled to a 64K Unicode message. Windows today is internally Unicode, and the "A" series of functions are just wrappers around the "W" functions.
1,800,875
1,800,890
Convert single char to int
How can I convert char a[0] into int b[0] where b is a empty dynamically allocated int array I have tried char a[] = "4x^0"; int *b; b = new int[10]; char temp = a[0]; int temp2 = temp - 0; b[0] = temp2; I want 4 but it gives me ascii value 52 Also doing a[0] = atoi(temp); gives me error: invalid conversion from ‘c...
You need to do: int temp2 = temp - '0'; instead.
1,800,886
1,826,446
Strange error with hardware picking in directx
i am trying to get pickigng working in directx 9 and i am having some trouble. it works fine when i am rendering my mesh in software however i do get errors when rendering with a shader. i can be off of a mesh but it still detects it as a hit (see image for more detail) i am stopping animation controllers and updating...
not to worry i found out that i was missing a clone function that i was doing in software mode but not hardware
1,800,983
1,801,055
c++ server htons to java ntohs client conversion
I am creating a small TFTP client server app where server is developed using c++ and client using java. Here i am sending "block count" value using htons conversion. But i am not able to convert it back to its original value at client. For example if am sending block count ntohs(01) (2 bytes) from server to clie...
I take it you meant that you use ntohs to decode the values read from the network, and htons to encode the values sent over the network. Look into ByteBuffer#getShort() in concert with ByteBuffer#order(ByteOrder). Network byte order is big endian, so use the value ByteOrder#BIG_ENDIAN to configure your ByteBuffer prope...
1,801,220
1,801,234
C tokenize polynomial coefficients
I'm trying to put the coefficients of polynomials from a char array into an int array I have this: char string[] = "-4x^0 + x^1 + 4x^3 - 3x^4"; and can tokenize it by the space into -4x^0 x^1 4x^3 3x^4 So I am trying to get: -4, 1, 4, 3 into an int array int *coefficient; coefficient = new int[counter]; p = strtok(...
This: strncpy(temp[z], p, z); Needs to be: strncpy(temp, p, z); But remember that strncpy doesn't always null-terminate the string. Also, z will be the length of the coefficient, but you need an extra byte in the buffer for the null terminator. Update: examining your link, I still see several serious problems: You c...
1,801,251
1,801,280
Modifying contents of vector in BOOST_FOREACH
This is a question that goes to how BOOST_FOREACH checks it's loop termination cout << "Testing BOOST_FOREACH" << endl; vector<int> numbers; numbers.reserve(8); numbers.push_back(1); numbers.push_back(2); numbers.push_back(3); cout << "capacity = " << numbers.capacity() << endl; BOOST_FOREACH(int elem, numbers) { c...
Under the covers, BOOST_FOREACH uses iterators to traverse the element sequence. Before the loop is executed, the end iterator is cached in a local variable. This is called hoisting, and it is an important optimization. It assumes, however, that the end iterator of the sequence is stable. It usually is...
1,801,258
1,836,063
Does using __declspec(novtable) on abstract base classes affect RTTI in any way?
Or, are there any other known negative affects of employing __declspec(novtable)? I can't seem to find references to any issues.
MSCV uses one vptr per object and one vtbl per class to implement OO mechanism such as RTTI and virtual functions. So RTTI and virtual functions will work fine if and only if the vptr has been set correctly. struct __declspec(novtable) B { virtual void f() = 0; }; struct D1 : B { D1() { } // after the...
1,801,363
1,801,402
C/C++: any way to get reflective enums?
I've encountered this situation so many times... enum Fruit { Apple, Banana, Pear, Tomato }; Now I have Fruit f; // banana and I want to go from f to the string "Banana"; or I have string s = "Banana" and from that I want to go to Banana // enum value or int. So far I've been doing this.. Assuming the enum i...
This one requires the fruits to be defined in an external file. This would be the content of fruit.cpp: #define FRUIT(name) name enum Fruit { #include "fruit-defs.h" NUM_FRUITS }; #undef FRUIT #define FRUIT(name) #name const char *Fruits [] = { #include "fruit-defs.h" NULL }; #undef FRUIT And this would be fruit-defs....
1,801,389
1,801,395
Why no compiler enforcement in const_iterator
Consider the following code : #include <vector> #include <iostream> class a { public: int i; void fun() { i = 999; } void fun() const { std::cout << "const fun" << std::endl; } }; const a* ha() { return new a(); } int main() { std::vector<a *> v; v.push_back(new a()); // cannot convert f...
The const_iterator says that you can't modify the element in the container; that is, if you have a container of pointers, you can't change the pointer. You aren't changing the pointer, you're changing the object pointed to by the pointer. If you try to assign a new pointer to that element in the container, it will fail...
1,801,459
1,801,471
Algorithm - How to delete duplicate elements in a list efficiently?
There is a list L. It contains elements of arbitrary type each. How to delete all duplicate elements in such list efficiently? ORDER must be preserved Just an algorithm is required, so no import any external library is allowed. Related questions In Python, what is the fastest algorithm for removing duplicates from a l...
Assuming order matters: Create an empty set S and an empty list M. Scan the list L one element at a time. If the element is in the set S, skip it. Otherwise, add it to M and to S. Repeat for all elements in L. Return M. In Python: >>> L = [2, 1, 4, 3, 5, 1, 2, 1, 1, 6, 5] >>> S = set() >>> M = [] >>> for e in L: ... ...
1,801,509
1,804,937
Speeding up self-similarity in an image
I'm writing a program that will generate images. One measurement that I want is the amount of "self-similarity" in the image. I wrote the following code that looks for the countBest-th best matches for each sizeWindow * sizeWindow window in the picture: double Pattern::selfSimilar(int sizeWindow, int countBest) { ...
Your problem strongly reminds me of the calculations that have to be done for motion compensation in video compression. Maybe you should take a closer look what's done in that area. As rlbond already pointed out, counting the number of points in a window where the colors exactly match isn't what's normally done in comp...
1,801,834
1,801,888
STL container's read-only operations
Need advice here: which of the STL container's operations are considered read-only? Take vector<int> as example, would it be safe to say that any operation that does not alter the underlying int data is read-only? I am writing a multi-threaded program, but not too sure if it is thread-safe to pass container by referenc...
Methods declared const most likely won’t modify the container, although you can’t be sure. When using STL containers in a multithreaded application you will need an external synchronization mechanism. The C++ standard library is not thread safe, and any use from multiple threads without synchronization will result in u...
1,801,880
1,801,977
Selection between ACE & Boost for learning
I am an intermediate c++ programmer and done some work using ACE, now I want to learn one of those Libraries thoroughly to progress in to my career. That why I need your kind help to make a decision, that what should I learn first. And also please consider my destinations are to be an expert network programmer and Prot...
This might not be the answer you're looking for, but I would strongly suggest that you don't artificially restrict yourself too much when it comes to career goals. Figure out how long you do expect your career as a programmer to continue and then ask yourself if you (a) can really see yourself doing network programming...
1,801,892
1,801,913
How can I make the map::find operation case insensitive?
Does the map::find method support case insensitive search? I have a map as follows: map<string, vector<string> > directory; and want the below search to ignore case: directory.find(search_string);
It does not by default. You will have to provide a custom comparator as a third argument. Following snippet will help you... /************************************************************************/ /* Comparator for case-insensitive comparison in STL assos. containers */ /**************************************...
1,801,949
1,801,955
How can a C++ base class determine at runtime if a method has been overridden?
The sample method below is intended to detect whether or not it has been overridden in a derived class. The error I get from MSVC implies that it is simply wrong to try to get the function pointer to a "bound" member, but I see no logical reason why this should be a problem (after all, it will be in this->vtable). Is t...
There is no way to determine if a method has been overridden, except for pure virtual methods: they must be overridden and non-pure in a derived class. (Otherwise you can't instantiate an object, as the type is still "abstract".) struct A { virtual ~A() {} // abstract bases should have a virtual dtor virtual void ...
1,802,059
1,802,081
Why does this pointer to C++ function code generate a compile error?
Can anyone solve this? I can’t seem to find the solution anywhere, but I see no logical reason why the line below (with the comment showing the compile error) should be a problem. Note: This question is a derivative of How can a C++ base class determine at runtime if a method has been overridden? class MyClass { ...
ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. This takes care of name mangling. So what you are trying to do will not work in a standards compliant C++ compiler.
1,802,185
1,802,205
Common Practice for Template Function Defination - Mix with Function Declaration?
Most of the time, I "avoid" to have the following style in my single header file. class a { void fun(); }; void a::fun() { } In order to avoid the following error. I try to separate class definition in cpp file and class declaration in h file. For example, the below is the wrong example : main.cpp #include "b.h"...
You can eliminate the LNK2005 error by declaring the definition of a::fun() as inline. For example: // a.h // ... inline int a::fun() { int t; std::cout << "a" << std::endl; return t; } With templates, the problem doesn't occur because the compiler/linker take care of ensuring that there is only one def...
1,802,342
1,802,986
Please show me a situtation which shows `need` for Delegates (or) function pointers
I'm going take a class on "Delegates and Callbacks" to students who are learning level programmers. They have basic c/c++ & c# background. Instead of directly showing how to use them. I want to show "Why Function Pointers?" first. I want to start with an example situation and ask them "How will you do this"? and make t...
You can show them an example of filtering a list of items in several places in your software. For example, you might have public List<Person> GetMale(List<Person> people) { List<Person> results = new List<Person>(); foreach (Person p in people) { if (p.IsMale) results.Add(p); } return re...
1,802,418
1,802,602
Race between virtual function and pthread_create
When I try to create a class instance with a virtual method and pass it to pthread_create, I get a race condition, causing the caller to sometimes call the base method instead of the derived method like it should. After googling pthread vtable race, I found out this is fairly well-known behavior. My question is, what...
The only problem here is that you are deleting the objects before the spawned thread executes the method, so by that time the child destructor already fired and the object is not there anymore. So it has nothing to do with pthread_create or whatever, its your timing, you can't spawn a thread, give it some resources an...
1,802,471
1,802,501
Suppress console when calling "system" in C++
I'm using the system command in C++ to call some external program, and whenever I use it, a console window opens and closes after the command finishes. How can I avoid the opening of a console window? I would be happy if the solution could be platform-independent. I would also like for my program to wait until the co...
It sounds like you're using windows. On Linux (and *nix in general), I'd replace the call to system with calls to fork and exec, respectively. On windows, I think there is some kind of spawn-a-new-process function in the Windows API—consult the documentation. When you're running shell commands and/or external programs...
1,802,528
1,816,724
Netbeans re produce Makefile when change options in c/c++ developing
I create new c/c++ project in Netbeans and change Makefile and add -lpthread for work with pthread and run my project .also I need to add some runtime argument from project properties/Run/Arguments . when I change runtime Arguments Makefiles that place at /'project folder'/nbproject/private/Makefile-Debug.mk & Makefile...
It is not feature, :( Makefiles are generated automatically so any your changes will be lost every time Makefile change (eg when you add new files to project) Solution is to use Netbean's Makefile Wizard! project properties->Linker->Libraries->Add Standard Library->Posix Threads or Add Option->Other Option-> -lpthread...
1,802,556
1,802,578
#define TheVLM(x) VLM::Global()->x TheVLM(Run());
What does this mean in C++: #define TheVLM(x) VLM::Global()->x TheVLM(Run());
Are you sure it's not on two lines, like : #define TheVLM(x) VLM::Global()->x TheVLM(Run()); In that case, it's nothing specfic to C++, it is a standard use of Macro. The second line will generate the following call after macro substitution: VLM::Global()->Run();
1,802,899
1,802,916
Supporting multiple human languages
I am thinking about my final year project and the possibility of supporting multiple languages, e.g. English, Welsh, German etc.. Is there a standard way of supporting multiple human languages in a program? What is the recommended file format for storing the different languages? It is something I am clueless on but is ...
If you wanted to browse on StackOverflow for ideas you could try the internationalization, i18n, localization and l10n tags. ("i18n" == "internationalisation" because "nternationalizatio" is 18 letters. Same for localization and l10n.)