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
3,854,992
3,855,370
Volatile classes in C++
I have a question concerning volatile keyword I can't seem to find an answer for. In my app I have data class that is shared as a state buffer between threads, and I need it to be updated regularly from multiple threads. Class looks like this: class CBuffer { //Constructor, destructor, Critical section initializati...
In portable code, volatile has absolutely nothing to do with multithreading. In MSVC, as an extension, volatile-qualified simple native types such as int can be used with simple read and store operations for atomic accesses, but this does not extend to read-modify-write accesses such as i++ or to objects of class type ...
3,855,010
3,855,118
ThreadPool and Producer - Consumer pattern design question
I want to implement a Producer - Consumers pattern using a ThreadPool for the Consumers. I will have 1 producer of requests and multiple consumers that will handle the incoming requests. When Implement the consumers using a threadpool my question if I should still have my own Queue for the producer to put requests on...
A queue between producer and threadpool requires 1 or 2 extra context switches: the threadpool waits on an empty queue and then needs to dispatch to a consumer thread. At the end the consumer must be presented back to the threadpool. Dispatching and handling the end can be managed by the message class. With all consum...
3,855,334
3,855,430
nested classes in c++
my question is how often do You really use nested classes in Your practice and in which cases? what is the real power of the nested classes, what can't be done without them? P.S. please don't explain what is it, I know it (from technical point of view)
I usually use nested classes to embed finders objects (to use with std::find_if) into my specific types. Something like: // Dummy example class Foo { public: class finder { public: finder(int value) : m_value(value) {}; bool operator()(const Foo& foo) { return (foo.m_int_value == value...
3,855,378
3,855,417
Change only parts of a type in a C++ template
Purpose and craziness aside, is there a way to achieve this in C++? template <typename P> void Q void_cast(P Q *p) const { return static_cast<P Q *>(p); } I'm effectively trying to cast a pointer to a void pointer type whilst keeping any const, restrict and other qualifiers (denoted by Q). I was under the impressi...
So, you want const X* -> const void*, volatile X* -> volatile void*, etc. You can do this with a set of overloads: template<typename P> void* void_cast(P* p) { return p; } template<typename P> void const* void_cast(P const* p) { return p; } template<typename P> void volatile* void_cast(P volatile* p) { re...
3,855,452
3,855,481
Generalizing / Refactoring the code
My code is something like this : if(country == china) { getCNData(); } else { getDefaultDataForallCountries(); } Now I need to add similar logic as CN for some other country say US . The option available to me is to add one more country check in if condition and make it like if(country ==china && country==US){ g...
This type of issue (overuse of "if" and "switch" statements) is neatly handled by implementing a strategy pattern with a abstract factory. Basically you want to change the algorithm without changing your implementation and duplicating the code over and over and over. Enjoy!
3,855,604
3,855,737
Can C++ compilers automatically eliminate duplicate code?
Code duplication is usually bad and often quite easy to spot. I suppose that compilers could detect it automatically in easiest cases - they already parse the text and get the intermediate representation that they analyze in various ways - detect suspicious patterns like uninitialized variables, optimize emitted code, ...
Some do, some don't. From the LLVM optimization's page: -mergefunc (MergeFunctions pass, how it works) The functions are separated in small blocks in the LLVM Intermediate Representation, this optimization pass tries to merge similar blocks. It's not guaranteed to succeed though. You'll find plenty of other optimizatio...
3,855,954
3,856,172
Differences between a shared object and an ordinary library in Linux
What are the main differences between binding to a shared object or to an ordinary object? Also how is this possible to share some variables between some programs and knowing that our variables are never changed by another program?
Variables are not shared between programs, ever. (Although specially-allocated shared memory can be shared, this is an "object" and not a "variable" in C terminology.) Where you're confused is that the on-disk backing is what's shared between processes, and this is the same whether it's the main program (static or dyna...
3,856,017
3,856,050
Do I have to use ->Release()?
I am working with a webbrowser host on c++, I managed to sink event and I am running this void on DISPID_DOCUMENTCOMPLETE: void DocumentComplete(LPDISPATCH pDisp, VARIANT *url) { READYSTATE rState; iBrowser->get_ReadyState(&rState); if(rState == READYSTATE_COMPLETE) { HRESULT hr; IDisp...
Yes, you do have to call Release() on those pointers, otherwise objects will leak. The same goes for BSTRs. You'll be much better off if you use smart pointers for that - ATL::CComPtr/ATL::CComBSTR or _com_ptr_t/_bstr_t.
3,856,072
3,856,696
Single Value Decomposition implementation C++
Who can recommend a stable and correct implementation Single Value Decomposition (SVD) in C++? Preferably standalone implementation (would not want to add large library for one method). I use OpenCV... but openCV SVD returns different decompositions(!) for a single matrix. I understand, that exists more than one decomp...
If you can't find a stand-alone implementation, you might try the eigen library which does SVD . It is pretty large, however it is template-only so you only have a compile-time dependency.
3,856,169
3,856,734
overloading the << operator in c++
hey, i got something that i cannot understand ,there are two types of solutions for overloading this operator 1 is including the friend at the start of the method and the other 1 goes without the friend. i would very much like if some1 explain whats the difference between them advantages / disadvantages. for example ov...
operator<< (for ostream) needs to be a free function (since the left-hand argument is a stream, not your class). The friend keyword makes it a free function (a free function that has access to the private members). However, if this functionality can be implemented in terms of the public interface, it is better to do so...
3,856,271
4,150,351
Running applications against a different SDK in OS X?
Summary I want to run my cross-compiled application against the 10.5 libraries. Is there an environmental variable that allows this to work? Longer version I cross-compiled my OS X C++ application for a 10.5 target, on a 10.6 host. It compiles fine. The compiled application is linked against libraries like /usr/lib/lib...
Use install_name_tool to change the path. You may not be able to squeeze in a longer path if the linker didn't add padding, but you can use an rpath instead. For example, I changing the load path for an app on my system to use the 10.5 SDK by doing: install_name_tool -change /usr/lib/libstdc++.6.dylib @rpath/libstdc++....
3,856,334
3,856,427
Does using atlbase.h makes my compiled app to have some extra dependencie?
I would like to know if including atlbase.h in my c++ project will make the compiled application to have a dll dependency or something like that.
It depends. The Project Configuration in the IDE has a setting to tell whether your ATL project should link to ATL statically or dynamically. This affects only a small part of ATL though -- most of it is templates, so including the header in your code is all that's needed. There are a few bits and pieces that can/do go...
3,856,389
3,857,850
Singletons destructors
I'm using boost's singletons (boost::serialization::singleton). I have to control the queue of class destructings. One singleton consist of the object whicn uses object from second singleton. And I have to delete second singleton, before the first one. Can I do this? p.s. please, don't say anything about singleton prog...
Yes: Read this: Finding C++ static initialization order problems
3,856,416
3,856,651
How to make sure iterators do not overpass end()?
I have been using advance on some iterators, but I am afraid of a possible leapfrog above end(). I would like to make sure my iterators stay between the bounds, I thought of the distance but it seems it does not return what I would be expecting (non-positive values when iterators overpass end()). How would you make sur...
advance() past end() results in undefined behaviour. You are going to have to test as you go per this snippet: template <class Iter, class Incr> void safe_advance(Iter& curr, const Iter& end, Incr n) { size_t remaining(std::distance(curr, end)); if (remaining < n) { n = remaining; } std:...
3,856,445
3,860,676
Can someone explain rvalue references with respect to exceptions?
Lets say I've this exception class: struct MyException : public std::exception { MyException(const std::exception &exc) : std::exception(exc) { cout << "lval\n"; } MyException(std::exception &&exc) : std::exception(std::forward<std::exception>(exc)) { cout << "rval\n"; } }; ... ...
Actually, exception handling has special rules with respect to lvalues and rvalues. The temporary exception object is an lvalue, see 15.1/3 of the current draft: A throw-expression initializes a temporary object, called the exception object, the type of which is determined by removing any top-level cv-qualifiers from ...
3,856,476
3,856,506
How to get records from MySQL in c/c++?
This is pretty easy in PHP: $con = mysql_connect("localhost:".$LOCAL_DB_PORT, $LOCAL_DB_USER, $LOCAL_DB_PASS); mysql_select_db("db", $con); mysql_query("set names utf8", $con); $result = mysql_query("select ..."); while($row = mysql_fetch_assoc($result)) { ... } But what's the easiest way to do it with c/c++ in windo...
MYSQL* mysql_connection_setup(struct connection_details mysql_details) { // first of all create a mysql instance and initialize the variables within MYSQL *connection = mysql_init(NULL); // connect to the database with the details attached. if (!mysql_real_connect(connection,mysql_details.server, mysq...
3,856,637
3,856,851
parse number from the string
Say I have the line in this format "word word 12 YR" or "word word 10 MO" and I want to convert it to char * containing either "12Y" or "10M" respectively. The format is two words followed by numerical followed by the word denoting the year or the month. words are space/tab separated. Currently, I am playing ar...
One way to do this is (no error checking, using boost): string s = "word word 10 MR"; string res; tokenizer<> tok(s); tokenizer<>::iterator iter = tok.begin(); while(iter != tok.end()) { try { int n = lexical_cast<int>(*iter); } catch(bad_lexical_cast& e) { ++...
3,856,712
3,856,965
template and what is created during compilation
if i have a template function: template<class T, class S> void foo(T t, S s){..//do something//} and then, inside the main i do this: string str = "something"; char* ch = "somthingelse"; double num = 1.5; foo(ch, num); foo(num, ch); foo(str, num); .. my question is in the compilation what code will be written at the ...
I think the following quote from the Standard clarifies this: $14.9.1/6- "Implicit conversions (Clause 4) will be performed on a function argument to convert it to the type of the corresponding function parameter if the parameter type contains no template-parameters that participate in template argument ...
3,856,729
3,856,751
How to use lock_guard when returning protected data
I have a question concerning the use of boost::lock_guard (or similar scoped locks) and using variables that should be protected by the lock in a return statement. How is the order of destroying local objects and copying the return value? How does return value optimization affect this? Example: Data Class::GetData() { ...
Just a straight return as in your first example is correct. The return value is constructed before the local variables are destroyed, and thus before the lock is released.
3,856,782
3,857,550
What are the recommended C++ parallelization libraries for large data processing
Can some one recommend approaches to parallelize in C++, when the data to be acted up on is huge. I have been reading about openMP and Intel's TBB for parallelization in C++, but have not experimented with them yet. Which of these is better for parallel data processing ? Any other libraries/ approaches ?
"large" and "data processing" cover a lot of ground here, and it's hard to give a sensible answer without more information. If the data processing is "embarrassingly parallel" -- if it involves doing lots and lots of calculations that are completely independant of each other -- then there's a million things that will w...
3,857,051
3,857,166
Does winbase::LoadLibrary() load .pdbs?
I have issues with debugging of a library loaded at runtime, and an unknown is: Does winbase::LoadLibrary() load the .pdb in debugging mode? Because if it doesn't, that would explain why I cannot use any debugging in my DLL, and if it does, that would at least tell me to search for the problem somewhere else. Obvious ...
The symbol file search is conducted whenever a DLL is loaded into your process space, independent of how that happens. Your problem must lie elsewhere.
3,857,229
3,857,264
Check if C++ Array is Null
how do i do that? well i want to check if the array is empty
Actually, when you have an array a[SIZE], you can always check: if( NULL == a ) { /*...*/ } But it's not necessary, unless you created a dynamic array (using operator new). See the other answers, I won't delete it just because it's accepted now. If other answer is accepted, I'll delete this "answer". EDIT (almost 4 y...
3,857,390
3,857,409
wfstream not writing
I have the following piece of code in C++: #include <iostream> #include <fstream> #include <string> using namespace std; int main(){ wstring ws1 = L"Infinity: \u2210"; wstring ws2 = L"Euro: €"; wchar_t w[] = L"Sterling Pound: £"; wfstream out("/tmp/unicode.txt"); out.write(ws1.c_str(), ws1.size(...
Always set the locale first… do locale::global( locale( "" ) );. Before that, you're in plain C mode which knows nothing about UTF-8. On Darwin, this is broken, so I need to do setlocale( LC_ALL, "" );, but then your program works for me. Edit Oops, you got bit by two gotchas at once. Opening a wfstream with the defaul...
3,857,503
3,857,551
How can a compiler differentiate between static data members having same name in different classes in C++?
I had a C++ interview recently where I was asked, how does the compiler differentiate static data members having the same name in two different classes? Since all static data variables are stored in the data segment, there has to be a way by which the compiler keeps track of which static data belongs to which class es...
The names are mangled with their class name in them. An example with the clang compiler class A { static int i; }; int A::i = 0; Output $ clang++ -cc1 -emit-llvm main1.cpp -o - ; ModuleID = 'main1.cpp' target datalayout = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:1...
3,857,716
3,857,767
can the functors called from algorithms acting on a map accept pair<K, V> instead of value_type?
I tried to write a short function to invert an std::map<K, V> (I know about boost.bimap, this is for self-education), and found, to my surprise, that the code that GCC 4.4 accepted with -pedantic -ansi settings was rejected as const-incorrect by SunCC (5.8, from 2005). Since value_type is std::pair<const K, V>, SunCC i...
Visual C++ and g++ are correct; this code (with flip_pair<K, V>() taking a const std::pair<K, V>&) is okay. Inside of transform, flip_pair<K, V> is being called. Since the object being passed to that function is a pair<const K, V>, a temporary object of type pair<K, V> is created (pair has a converting constructor tha...
3,857,728
3,857,848
Doubt on a C++ interview question
I have read Answers to C++ interview questions among which there is one that puzzles me: Q: When are temporary variables created by C++ compiler? A: Provided that function parameter is a "const reference", compiler generates temporary variable in following 2 ways. a) The actual argument is the correct type, but it is...
You are allowed to pass the results of an expression (including that of implicit casting) to a reference-to-const. The rationale is that while (const X & value) may be cheaper to use, depending on the copy-cost of type type X, than (X value), the effect is pretty much the same; value gets used but not modified (barring...
3,857,897
3,858,464
facet's get_time keeps failing
I have spend like one out in this example, and everytime I get the error Unable to read cin with an ios_base::iostate equal to failbit from this code: #include "dates.h" #include <iostream> #include <ctime> #include <locale> #include <sstream> #include <iterator> using namespace std; void trasnlateDate(istream&in, o...
I ran your sample code on a box, and until I entered the input 02/02/2005, it failed just like you said. It looks like those leading zeros in month and day fields are necessary.
3,858,251
3,859,400
Parsing positional arguments
Consider the following trivial program adopted from the boost program options examples #include <boost/program_options.hpp> #include <boost/version.hpp> #include <iostream> int main( int argc, char** argv ) { namespace po = boost::program_options; po::options_description desc("Options"); unsigned foo; ...
when I explicitly indicate no positional options are supported: const po::positional_options_description p; // note empty positional options po::store( po::command_line_parser( argc, argv). options( desc ). positional( p ). run(), ...
3,858,308
3,858,420
Using C Preprocessor to Determine Compilation Environment
I am building an application that consists of both a windows driver written in C and a user mode executable in C++. They both use a shared header file to define several macros, constants, enums, etc. In the C++ version, I want to include everything within a namespace, which a feature not supported by the C compiler. ...
For the specific example of distinguishing a C++ compiler from a C compiler, the sensible choice is the macro __cplusplus which is defined by the C++ standard to exist, and due to side effects of the reserved name rules a clause that says so in standard C, will never be predefined by the C compiler. Every compiler has ...
3,858,344
3,858,401
What does the C++ compiler do when coming ambiguous default parameters?
What does the C++ compiler do when coming ambiguous default parameters? For example, let's say there was a function such as: void function(int a = 0, float b = 3.1); void function(int a, float b =1.1, int c = 0); Is the above considered ambiguous? If not, what does the compiler do (how is the function matched exactly)...
The following is fine void function(int a = 0, float b = 3.1); void function(int a, float b =1.1, int c = 0); And the following is fine too function(); // calls first function But the following is ambiguous function(1); // second and first match equally well For overload resolution (the process that tells what funct...
3,858,470
3,858,485
C++ standard question
should the following result in undefined behavior? should value of pointer2 be NULL? double *pointer = 0; double &value = *pointer; double *pointer2 = &value;
Yes. double *pointer = 0; // init `pointer` to a NULL pointer value double &value = *pointer; // dereference it The standard specifically speaks to this situation - from 8.3.2/4 "References": A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference can...
3,858,889
3,907,973
Get schema data types from Xerces
I am using SAX2 in Xerces C++ and would like to get XML Schema data while I handle elements so that I know their type defined in the Schema. How can I accomplish this?
Okay, I figured out how to do this. Sparse documentation available on the subject. Apparently I need to cast the SAX2XMLReader that XMLReaderFactory::createXMLReader() returns, to a SAX2XMLReaderImpl. Then I can register an PSVIHandler implementation on that interface. I have to provide my own implementation of the PSV...
3,858,947
3,859,024
Choosing N random numbers from a set
I have a sorted set (std::set to be precise) that contains elements with an assigned weight. I want to randomly choose N elements from this set, while the elements with higher weight should have a bigger probability of being chosen. Any element can be chosen multiple times. I want to do this as efficiently as possible ...
You need to calculate (and possibly cache, if you think of performance) the sum of all weights in your set. Then, generate N random numbers ranging up to this value. Finally, iterate your set, counting the sum of the weights you encountered so far. Inspect all the (remaining) random numbers. If the number falls between...
3,858,978
3,859,003
convert string to integer in c++
Hello I know it was asked many times but I hadn't found answer to my specific question. I want to convert only string that contains only decimal numbers: For example 256 is OK but 256a is not. Could it be done without checking the string? Thanks
The simplest way that makes error checking optional that I can think of is this: char *endptr; int x = strtol(str, &endptr, 0); int error = (*endptr != '\0');
3,859,157
3,859,167
Splitting C++ Strings Onto Multiple Lines (Code Syntax, Not Parsing)
Not to be confused with how to split a string parsing wise, e.g.: Split a string in C++? I am a bit confused as to how to split a string onto multiple lines in c++. This sounds like a simple question, but take the following example: #include <iostream> #include <string> main() { //Gives error std::string my_val ="H...
Don't put anything between the strings. Part of the C++ lexing stage is to combine adjacent string literals (even over newlines and comments) into a single literal. #include <iostream> #include <string> main() { std::string my_val ="Hello world, this is an overly long string to have" " on just one line"; std:...
3,859,222
3,859,539
C++, Negative RGB values of pixels using OpenCV
I'm using OpenCV to iterate through an image and find the colour of each pixel, here's some of the code I'm using: IplImage* img = cvLoadImage("c:\\test.png"); int pixels = img->height * img->width; int channels = img->nChannels; for (int i = 0; i < pixels*channels; i+= channels) { unsigned char red = img->image...
Try this: IplImage* img = cvLoadImage("c:\\test.png"); for (int i = 0; i < img->height; i++) { for (int j = 0; j < img->width; j += img->nChannels) { unsigned char red = img->imageData[i * img->widthStep + j + 2]; unsigned char green = img->imageData[i * img->widthStep + j + 1]; unsigne...
3,859,238
3,859,262
Segfault in C++ calling virtual method on object created in pre-allocated buffer
Hmm... Title is a bit of a mouthful, but I'm really not sure which part of this is causing issues, I've run through it a ton of times, and can't pinpoint why... The idea is for a single Choice instance to be able to store any one value of any of the types passed in to it's template list... It's kind of like a union, ex...
You didn't post any code related to the actual crash, but I'm going to guess that you either return an instance of Choice<...> by value or invoke the copy constructor through some other means. Since you didn't define a copy constructor, you are probably double freeing the memory you allocated with Choice<...>::Choice.
3,859,340
3,860,170
Calling Haskell from C++ code
I'm currently writing an app in C++ and found that some of its functionality would be better written in Haskell. I've seen instructions on calling Haskell from C code, but is it possible to do the same with C++? EDIT: To clarify, what I'm looking for is a way to compile Haskell code into an external library that g++ ca...
Edit: You should also see Tomer's answer below. My answer here describes the theory of what's going on, but I may have some of the details of execution incomplete, whereas his answer is a complete working example. As sclv indicates, compiling should be no problem. The difficulty there is likely to be linking the C++ ...
3,859,362
3,859,392
How do I store value to string with RegOpenKeyEx?
I need to grab the path from the registry. The following code works except for the last part where I'm storing the path to the string. Running the debugger in Visual Studio 2008 the char array has the path, but every other character is a zero. This results in the string only being assigned the first letter. I've tried ...
You're getting back a Unicode string, but assigning it to a char-based string. You could switch path's class to being a 'tstring' or 'wstring', or use RegQueryValueExA (A for ASCII).
3,859,517
3,859,819
Type of pointer to member from base class
I have a problem regarding member pointers. The following code fails to compile using both Oracle Solaris Studio 12.2's CC and cygwin GCC 4.3.4 but works with Microsoft Visual C++ 2010: struct A { int x; }; struct B : public A { }; template<typename T> class Bar { public: template<typename M> void foo(M T::*p); }...
A conversion from int A::* to int B::* is allowed, and that's not the problem. The problem is in template argument deduction, as you can see if you try the following program which supplies a template argument <int> for B::foo and compiles, and a non-member function foo2 which produces the same error as B::foo did befo...
3,859,610
3,877,389
Custom icon not displayed in upper left corner or on task bar
I have created a basic application with with windows api. It just displays a small window. I am starting from main function, getting the instance, created my windows class, etc. Everything works out fine. The problem I have however is that my custom icon will not display in the top left corner of the window or on th...
My first suggestion would be to try loading a standard icon instead of your own icon: hMyIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_ERROR)); This should probably work, and you should see the red error message icon. The next thing to do is try to obtain the instance handle in a different way. Console windows are a stran...
3,859,668
3,859,682
In Linux using C++ and GCC, is it possible to convert the virtual address to a physical address?
Under Linux, C++, and GCC, can I get a physical address for a given virtual address? I know I won't be able to manipulate the physical address as a physical address.
Nope. There's no guarantee that a virtual address is based off a physical address (it may be a mapped file with no representation in RAM, for instance.) As well, the OS is free to move virtual addresses around in physical memory at any time, so there's no guarantee that a physical address will remain correct or valid. ...
3,859,944
3,859,980
Combining string literals and integer constants
Given an compile-time constant integer (an object, not a macro), can I combine it with a string literal at compile time, possibly with the preprocessor? For example, I can concatenate string literals just by placing them adjacent to each other: bool do_stuff(std::string s); //... do_stuff("This error code is ridiculous...
If BAD_EOF was a macro, you could stringize it: #define STRINGIZE_DETAIL_(v) #v #define STRINGIZE(v) STRINGIZE_DETAIL_(v) "My error code is #" STRINGIZE(BAD_EOF) "!" But it's not (and that's just about always a good thing), so you need to format the string: stringf("My error code is #%d!", BAD_EOF) stringstream ss; ...
3,860,109
3,860,159
is all the available swig+python+mingw compile information outdated?
I'm trying to build a C++ extension for python using swig. I've followed the instructions below and the others to a T and can't seem to get my extension to load. I ran across this article on the MinGW site under "How do I create Python extensions?" http://www.mingw.org/wiki/FAQ I also found these tutorials: http://boo...
Two things to verify: Check the C runtime library DLL bound to your python and to your extension DLL with dependency walker to make sure that they are using the same CRT. This is a common source of trouble when building extensions for other languages. (I see it often with Lua, for instance) and can cause interesting a...
3,860,152
3,860,157
How do hidden structures work?
I notice in several API's, that you may create a struct which is used internally and has nothing. ex: ALLEGRO_BITMAP *bmp; ... bmp->(intellesense shows nothing) how do these types of structures work? are they simply handled like this internally? REAL_ALLEGRO_BITMAP *realbmp = (REAL_ALLEGRO_BITMAP*)bmp; or is there a...
What you're looking at is an opaque pointer or opaque data type (link and link). Here's an SO thread discussing these: What is an opaque value?
3,860,195
3,860,416
Variant * to string throws unknown exception
I am using this code to sink events in a IWebBrowser2 webbrowser on c++: STDMETHODIMP AdviseSink::Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* p...
You are using the return value (an [out] parameter) as one of the event parameters. This will cause bstr_t to throw a com_error exception because the VARIANT doesn't contain a BSTR. See the MSDN documentation for the correct DocumentComplete signature. The event parameters are available from pDispParams not pVarResult...
3,860,271
3,860,388
Find and delete value in a vector
class Catalog { // string StationTitle; string StationLocation; public: string StationTitle; Catalog() { StationTitle = ""; StationLocation = ""; } Catalog(string Title, string Location) { StationTitle = Title; StationLocation = Location } void SetTitle(string Title) {...
Your error is here: if(Transit->StationTitle() == ToDelete) Change that line to this: if(Transit->StationTitle == ToDelete) OR if(Transit->GetTitle() == ToDelete)
3,860,316
3,860,334
How to parallelize reading lines from an input file when lines get independently processed?
I just started off with OpenMP using C++. My serial code in C++ looks something like this: #include <iostream> #include <string> #include <sstream> #include <vector> #include <fstream> #include <stdlib.h> int main(int argc, char* argv[]) { string line; std::ifstream inputfile(argv[1]); if(inputfile.is_ope...
Not a direct OpenMP answer - but what you are probably looking for is Map/Reduce approach. Take a look at Hadoop - it's done in Java, but there's some C++ API at least. In general, you want to process this amount of data on different machines, not in multiple threads in the same process (virtual address space limitatio...
3,860,528
3,860,565
Can't get Display List to Work
First of all, as usual, thanks to all for the great support from the SO community. So I wrote code to draw 6 gl_quads (to form a cube). Initially, this code was drawn immediately (explicitly made 24 vertex calls in the display function). I'd like to put these in a display list. I read a tutorial about display lists,...
You're almost there, you just need first to call glGenLists() to generate a contiguous set of empty display lists. GLuint listID; listID = glGenLists( 1 ); // generate 1 display list glNewList( listID, GL_COMPILE ); // whatever you want in the display list glEndList(); // call the display list glCallList( listID ); Y...
3,860,559
3,860,583
Rename function vs undef : conflicts with Windows API
This has actually occurred twice now. I'm writing a cross-platform application, and some of my function names conflict with the Windows API. What I did (for example with LoadObject) was... #undef GetObject Is this an okay approach, or should I rename my functions?
If you intend for your code to be used alongside of the Windows API, I'd recommend renaming the functions. Yes, that's a hassle, but it's (in my opinion) better than undefining parts of the Windows API, even if you don't use those parts (someone else using your code might need to use those parts).
3,860,584
3,860,607
Qt save a QImage to a relative location
I'm using QImage.save to save an image of my OpenGL framebuffer to disk. If I just call save("plot.jpg"), I have no idea where the image ends up. It's not in the application directory. I can call save("/Users/wallacer/desktop/plot.jpg") to save the file on my desktop, but obviously that's no good for running on anyo...
You could use QDir::homePath or QDir::home to get a relative (and IIRC, platform independent) path. ETA: Or the applcation's current path should be in QDir::currentPath.
3,860,608
3,860,672
Looking for good examples of tools with neat crash-reporting capabilities
The target platform is Windows. Sought-after languages: C++ (Native as well as CLI), C#. Java examples are al right as well. I am not too worried about security, but I am curios about the language agnostic design aspect of this as well - what is a good way to deliver a crash report? Something that I am looking for - co...
Take a look at breakpad. You also might be interested in the UnhandledExceptionHandler and its ilk for C#. Also take a look at minidumps.
3,860,640
4,044,240
C++ : convert date/time string to tm struct
Consider this somewhat of a follow up to this question. Essentially, the C++ date/time formatting facilities seem to be hopelessly broken - so much so that in order to do something as simple as convert a date/time string into an object, you really have to resort to either Boost.Datetime or good old C strftime/strptime...
Boost uses the standard locale(s) by default; you don't have to bypass anything: #include "boost/date_time/gregorian/gregorian.hpp" #include <iostream> #include <sstream> #include <ctime> int main(){ using namespace boost::gregorian; std::locale::global(std::locale("")); std::locale german("German_Germany"); ...
3,860,719
3,860,884
Copying a BSTR into a char[1024]?
I am working on a web browser with c++ using IWebBrowser2. Declared on the top, outside any scope, I have this: static char buf[1024]; In the documentcomplete event, I set the BSTR with: CComBSTR bstrHTMLText; X->get_outerHTML(&bstrHTMLText); What I want to do is to copy bstrHTMLText value into buf (if bstrHTMLText l...
A BSTR is secretly a pointer to a Unicode string, with a hidden length prefix sitting in front of the string data. So, you can just cast it to wchar_t* and then convert that wide-character string to an ANSI string, e.g. using WideCharToMultiByte: WideCharToMultiByte(CP_UTF8, 0, ...
3,860,963
3,868,332
'An invalid object handle was used' in FMOD 3D sound listener
I'm trying to set up 3D sounds with FMOD in a game which uses Ogre. The sound listener is attached to the camera which runs on a spline. I have footstep sounds attached to the player, and the volume should be determined by how far the player is from the camera. The foot step sounds are acting as though the sound liste...
An invalid handle error (FMOD_ERR_INVALID_HANDLE) is referring to the object you are calling functions on, in this case it means the m_system handle is invalid. Firstly I noticed you have omited the code to create the FMOD::System object, can you confirm you are doing the following: result = FMOD::System_Create(&m_syst...
3,860,985
3,861,260
How to output multiple byte characters normally in c/c++ console application?
printf("%s\n", multibytestring); By default the multi-byte characters will show up like ??? in console, how can I fix it?
I'm guessing Windows, and that you mean multi-byte characters and not wide characters. Make sure that _MBCS is defined. Try calling setlocale and then _setmbcp: setlocale(LC_ALL, "japanese"); _setmbcp(_MB_CP_LOCALE); After that it should hopefully work fine.
3,861,231
3,861,464
Testing performance of C++ code
What free tools could I use to test the performance of C++ code in Linux? Basically I want to identify the bottleneck of the code and improve on the performance. My application mainly involves computational code using the data from the network. So I would like to improve the speed of execution of the code. Thanks.
For typical performance benchmarking this is what i use. gprof/oprofile - for CPU intensive profiling of your code. netstat/ethereal - for network statistics iostat/sar - for I/O vmstat - for memory mpstat/sar - for cpu usage Now u can isolate the problems based on the output of these tools. For eg:- if I/O is c...
3,861,649
3,861,806
C++ typedef enum: Invalid conversion from int to enum
typedef enum{ Adjust_mode_None = 0, Adjust_mode_H_min, Adjust_mode_H_max, Adjust_mode_S_min, Adjust_mode_S_max, Adjust_mode_V_min, Adjust_mode_V_max }Adjust_mode; and at some point I want to do: adjust_mode_ = (adjust_mode_+1)%7; but I get Invalid conversion from int to Adjust_mode This is ok in other langu...
Yes, you can define an operator... Adjust_mode operator+(Adjust_mode lhs, int rhs) { return static_cast<Adjust_mode>( (static_cast<int>(lhs) + rhs) % 7); } Adjust_mode operator+(int lhs, Adjust_mode rhs) { return static_cast<Adjust_mode>( (lhs + static_cast<int>(rhs)) % 7); } Not...
3,861,744
3,861,883
How to pass Lambda expression parameter by Reference for C++0x
I am using a C++0x lambda expression to modify values of a map. However, having difficulty passing the map iterator by reference. If I just pass the iterator, by value such as: [](std::pair<TCHAR, int > iter) it compiles fine, but the values does not get updated in the map. If I try to pass the iterator by reference, s...
The problem is that you are not allowed to modify the key of the map. std::for_each(charToInt.begin(), charToInt.end(), [](std::pair<const TCHAR, int>& iter) Will work because it uses const TCHAR. Edit: As @David and the other posters have pointed out, you would be better off using Map::value_type& which is a typedef...
3,861,948
4,060,641
How do I read a FIFO/named pipe line by line from a C++/Qt Linux app?
How do I read a FIFO/named pipe line by line from a C++/Qt Linux app? Today I can open and read from a fifo from a Qt program, but I can't get the program to read the data line by line. Qt reads the entire file, meaning he waits until the "sender" closes his session. Let's take a example with some shell commands to s...
Use the low level c style and read one char at the time. FILE *fp; fp=fopen("MyPipe", "r"); char c; while((c=getc(fp)) != EOF) { printf("%c",c); } fclose(fp);
3,862,378
3,862,556
What is the meaning of "generic programming" in c++?
What is the meaning of generic programming in c++? Also, I am trying to figure out what container, iterator, and different types of them mean.
Generic programming means that you are not writing source code that is compiled as-is but that you write "templates" of source codes that the compiler in the process of compilation transforms into source codes. The simplest example for generic programming are container classes like arrays, lists or maps that contain a ...
3,862,793
3,862,864
Exposing an API for DLLs from an app
I am developing a plugin system for an application. The idea is to load some functions from plugins (loaded as DLLs) and use those functions in our scripting language hosted in app. I have to expose an API for the DLLs for them to interact with the app. The API may change overtime and the older DLLs should not be inval...
Here are some ideas: Make the API fully compatible with C. No classes, no STL types, all functions declared extern "C". For versioning, embed the API version number in the function and struct names. Once a version has been released, the function signatures and type definitions can not be changed without the risk of br...
3,862,819
3,864,324
Why doesn't scala have C++-like const-semantics?
In C++. I can declare most things as const, for example: Variables: const int i=5; Scala has val i=5, however this will only prevent reassigning, not changing the object as the following exampe shows: C++: const int i[]={1,2,3,4}; i[2]=5; //error Scala: val a=Array(1,2,3,4) a(2)=5 //a is now Array(1, 2, 5, 4) It gets e...
The thing I dislike about C++ const logic is that it is about the reference and not about the object that is referenced. If I have a "const T *" there is no guarantee that someone holding a non-const pointer will not modify the state of the object. As such, it does not help in any way to avoid race conditions in multi-...
3,862,900
3,863,105
How to disable Edit mode in the QTableView?
I am using QTableView. It's working fine. But the problem is that if I double click the cell then it changes into edit mode. I need to disable the edit option. How to do that?
Use the following: QTableView table(...); table.setEditTriggers(QAbstractItemView::NoEditTriggers);
3,863,036
3,863,052
Creating static library from C++ code and linking with iPhone SDK
I have written some code in C++ with a corresponding C interface (i.e C-function wrappers around the classes) that a friend wants to use in an iPhone application. Since I heard you can compile C++ for the plattform, but not use the iPhone sdk at the same time (sic) I thought that compiling all the code into a static li...
Xcode will happily compile C++ code along with C and Objective-C in a single iPhone project.
3,863,231
3,863,259
Easy way to invoke standard mail client from c++ with recipient adress and subject?
The answer from TcKs gave me an idea, thus i tried following: system("mailto:thomas.muster@domainname.com?subject=Test"); and STARTUPINFO info = {sizeof(info)}; PROCESS_INFORMATION processInfo = {0}; if (!::CreateProcess(NULL, "mailto:thomas.muster@domainname.com", NULL, NULL, FALSE, 0, NULL, NULL,...
Try the ShellExecute function: http://support.microsoft.com/kb/224816
3,863,265
3,864,076
Amount of physical memory increases as I free blocks
I have a piece of C++ code that deallocates memory as follows for (int i = Pages-1; i >= NewPages; i--) { LPVOID p = m_Pages[i]; free(p); } While the code works ok, when called from an exception handler, it runs very slowly. Looking at task manager while single stepping through the above loop, the amount of p...
Your process can use two megabytes of memory. When malloc fails, the used memory will be near that value. If your computer has less physical memory, a lot of memory pages of that process will have been paged out to the disk. While your exception handler frees back memory, the heap manager will touch all pages, bringing...
3,863,552
3,868,250
Base classes versus templates versus generated code versus macro's
I have to work out a small framwork that is going to be used by several of our applications. On top of this, the framework is going to be used multiple times within the same application, but with a slightly different configuration. The 'nature' of the configuration is more complex than just having some configuration ...
I would avoid runtime polymophism if peak performance really is an issue not only because the vtable lookup for virtual function calls but because: inlining virtual calls to allow efficient cross function boundary optimizations is sort of difficult to do (the same applies to generated code compiled to a shared library...
3,863,567
3,863,602
In C++ check if two instances of a base class are infact of the same subclass
The below code explains the problem. Fill in same_sub_class to detect if the two pointers to virtual base class A are in fact the same concrete class. struct A { ... }: struct B : public A { ... }: struct C : public A { ... } bool same_sub_class(A * a1, A * a2){ // Fill this in to return true if a1...
If you can use RTTI, typeid(*a1) == typeid(*a2) I think you also need to #include <typeinfo> And you must have a virtual function in your classes so that the vtable exists--a destructor should do fine. UPDATE: I'm not sure I completely understand what your requirements are for grouping (Do you need some kind of deter...
3,863,643
3,863,701
register for an event in Windows
Hi I want to do something when a memory stick attached to PC. Now I use a timer and check it in every tick whether any memory stick is plugged(use DriveInfo or with querying WMI) Is there any event driven model available to do? for example i use an event in my program that raise whenever a memory stick is plugged in to...
You want to handle the WM_DEVICECHANGE message in your wndproc. When you handle that, you can also call RegisterDeviceNotification to get notification that the stick is being cleanly ejected. When you recieve a WM_DEVICECHANGE, you want to check the wParam - DBT_DEVICEARRIVAL (0x800) is what you're looking for. In C...
3,863,656
3,864,503
How to cause an intentional division by zero?
For testing reasons I would like to cause a division by zero in my C++ code. I wrote this code: int x = 9; cout << "int x=" << x; int y = 10/(x-9); y += 10; I see "int =9" printed on the screen, but the application doesn't crash. Is it because of some compiler optimizations (I compile with gcc)? What could be the reas...
Make the variables volatile. Reads and writes to volatile variables are considered observable: volatile x = 1; volatile y = 0; volatile z = x / y;
3,863,820
3,863,908
How does linker know which symbols should be resolved at runtime?
How does linker know which symbols should be resolved at runtime? Particularly I'm interested what information shared object files carry that instruct linker to resolve symbols at runtime. How does the dynamic symbol resolution work at runtime, i.e. what executable will do to find the symbol and in case multiple symbol...
Check out this article from Linux Journal. For more information -- perhaps specifically related to Windows, AIX, OSx, etc -- I would recommend the Wikipedia article on Linker (computing) and the references therein.
3,863,855
3,863,936
Microsoft Visual C++ code optimization
In MSVC, there are four options for code optimization: No Optimization Minimize Size Maximize Speed Full Optimization The first three are self-explanatory, but I am unsure about Full Optimization. Does this try to find a balance between size and speed, or does it do better optimization than the other two options? Ple...
It appears to be speed optimization, with some extra optimizations turned on. It's fully explained online here. Using /Ox is the same as using the following options: /Obn, where n = 2 /Og (Global Optimizations) /Oi (Generate Intrinsic Functions) /Os, /Ot (Favor Small Code, Favor Fast Code) /Oy (Frame-Pointer Omis...
3,863,985
3,864,042
How do I create a pseudo-color image in C++?
I have an array of pixels with an associated intensity (as a float between 0 and 1) that I would like to convert to a RGB image. The easiest way would be to just multiply each value by 255 and assign it to R+G+B to obtain a greyscale image, but I think it would be better to use a whole range of colors to show finer dif...
You could use HSV or HSL instead. Try using your 0 to 1 value to set the Hue and use constants for saturation and value. You'll find plenty of example code for converting your HSV value to an RGB value. http://en.wikipedia.org/wiki/HSL_and_HSV When you see an "artificial colours" image, this is often what is used. The ...
3,864,153
3,864,622
On Windows, how do we convert a virtual key code to the shifted character?
I looked at MapVirtualKey() and ToAscii(). MapVirtualKey() gives me only the unshifted character. ToAscii() only works for vk codes that translate to ASCII values. I need to detect for example, "Ctrl + Shift + 3" as Ctrl active, Shift active and '#'. Any clues?
This is how I finally did it: case WM_KEYDOWN: GetKeyboardState(kbs); if(kbs[VK_CONTROL] & 0x00000080) { kbs[VK_CONTROL] &= 0x0000007f; ::ToAscii(p_wParam, ::MapVirtualKey(p_wParam, MAPVK_VK_TO_VSC), kbs, ch, 0); kbs[VK_CONTROL] |= 0x00000080; } ...
3,864,201
3,865,288
Using Doxygen with Visual Studio 2010
I have difficulties efficiently using Doxygen with Visual Studio 2010 and C++. Is there no other function for commenting than "un/comment lines"? For example generating comment stubs, and adding /// after a new line. Also, I wonder what is needed to display those Comments within the IntelliSense feature in VS2010?
According to the MSDN Documentation, any comments using // or /* delimiters will be displayed next to the associated member in the IntelliSense Members list. You can use doxygen's XML output or the XML documentation generated by Visual Studio as IntelliSense input. The /doc documentation explains how to use XML documen...
3,864,226
3,864,353
pass object by value to another thread
I am writing a little trial project and I need to pass and object of type QueuList by value to a thread pool thread. It is a Boost threadpool and I am using Bind to pass the args to the thread. For some reason I cannot seem to pass my item to the threadpool thread by value... Can anybody help what I'm doing wrong? voi...
You can solve this by using boost::shared_ptr<QueueList> in the queue and the threadpool scheduling. That best expresses the hand off of shared data that you want, in the absence of unique_ptr in some STLs.
3,864,264
3,864,297
extern "C" (C linkage) by default
Question Do GCC, MSVC, or Clang, or some combination support setting linkage to default to C? Background I have a large mixed C/C++ project, and while it's easy and logical to export symbols in the C++ sources with C linkage, those same sources are assuming the stuff in the rest of the project are under C++ linkage. Th...
The standard pattern in a header file is: #ifdef __cplusplus // C++ stuff extern "C" { #endif // C/C++ stuff #ifdef __cplusplus } #endif I'm not sure you've got any other options. The C/C++ stuff must be declared with C linkage everywhere. The C++-specific stuff must be declared with C++ linkage everywhere.
3,864,329
3,864,371
How does a C++ object access its member functions?
How does a C++ object know where it's member function definitions are present? I am quite confused as the Object itself does not contain the function pointers. sizeof on the Object proves this. So how is the object to function mapping done by the Runtime environment? where is a class's member function-pointer table ma...
If you're calling non-virtual functions, there's no need for a function-pointer table; the compiler can resolve the function addresses at compile-time. So: A a; a.func(); translates to something along the lines of: A a; A_func(&a); Calling a virtual function through a base-class pointer typically uses a vtable. So:...
3,864,386
3,880,987
Cross-compiler library communication
I need to develop a C++ front-end GUI using MSVC that needs to communicate with the bank-end library that is compiled with C++ Builder. How can we define our interfaces so that we don't run into CRT library problems? For example, I believe we will be unable to safely pass STL containers back and forth. Is that true? I ...
You might find this article interesting Binary-compatible C++ Interfaces. The lesson in general is, never pass STL container, boost or anything of the like. Like the two other answers your best bet is to stick with PODs and functions with a calling convention specified. Since implementations of the STL vary from compil...
3,864,410
3,872,681
Why wasn't yield added to C++0x?
EDIT, 11 years after I asked this question: I feel vindicated for asking! C++20 finally did something close enough. The original question follows below. -- I have been using yield in many of my Python programs, and it really clears up the code in many cases. I blogged about it and it is one of my site's popular pages. ...
They did it for lambdas, why didn't they consider it for supporting yield, too? Check the papers. Did anyone propose it? ...I can only guess that they consider macro-based implementations to be an adequate substitute. Not necessarily. I'm sure they know such macro solutions exist, but replacing them isn't enough ...
3,864,460
3,864,545
Accessing C++ classes based on list of strings
I am hoping this is possible in C++. I have a list of classes that inherit from a common base class (Base). All of these will be compiled as part of the library linked to my program. I could be adding more classes that derive from Base and will be recompiling everything after I do this. When my program starts it will ...
Well, if you have a preprocessed list of all classes then you can create a construction object that will "know" each of those classes and will construct (by manually searching through the list) them upon request.
3,864,593
3,865,241
Setting up Netbeans to compile wxWidgets projects under Windows
I'm trying to set up my Netbeans IDE so that it is capable of compiling wxWidgets projects. There is very similar question: Setup wxWidget in Netbeans 6.1 C++ On MS Windows? but the answer is not working for me. And the mentioned versions are a bit outdated. I use the mingw package for compilation. There is no proble...
I finally found the solution, and wrote a guide for anyone who might encounter the same problem in the future. wxWidgets wiki: Compiling using Netbeans
3,864,627
3,864,656
Turning remove_if into remove_not_if
How can I reverse a predicate's return value, and remove the elements that return false instead of true? Here is my code: headerList.remove_if(FindName(name)); (please ignore lack of erase) with FindName a simple functor: struct FindName { CString m_NameToFind; FindInspectionNames(const CString &nameToFind) ...
Check not1 in the <functional> header: headerList.remove_if( std::not1( FindName( name ) ) ); Oh, and this: if(header.Name == m_NameToFind) { return true; } return false; Please don't do that. return ( header.Name == m_NameToFind ); That's much better, isn't it?
3,864,948
3,864,992
How do you write a operator() or less-than-functor neater than a trivalue-compare-function
Writing an operator< () for a struct appears to be clearer than writing the classical trivalue compare. for example, to sort the following struct S { int val; }; you can write an operator< () bool operator< ( const S &l, const S &r ) { return l.val < r.val; } or, a trivalue function (usually in the followin...
The thing is that you are fine with just declaring one trivalue compare function if you autogenerate all operators using: http://en.wikipedia.org/wiki/Barton%E2%80%93Nackman_trick
3,865,011
3,865,098
Constructor for a no-named struct
I have a class something like that: template <class T> class bag { public: private: typedef struct{void* prev; struct{T item; unsigned int count;} body; void* next;}* node; typedef struct{ node operator->() { return current; } operator(){;} // <- i can not do that, right? private: node current; } iterator;...
Make some nice name for it :-) typedef struct NoName1 {void* prev; NoName1(){}; struct NoName2{T item; unsigned int count; NoName2() {}} body; void* next;}* node; EDIT: LOL sorry, wrote it for the wrong one, but the principle is the same :-)
3,865,072
3,865,121
Optimize Concurrent writes to a buffer
I am required to have multiple threads writing to a single buffer (contiguous chunk of memory). The brute force method will be as follow The thread that wants to write to buffer will acquire lock on the buffer Entire buffer is locked and therefore only the thread that acquired lock can modify the buffer. The thread wr...
Have your threads write their data to a queue instead. Then, let a dedicated thread write from the queue to the buffer. If that is not concurrent enough, sacrifice the fixed ordering and use multiple queues.
3,865,206
3,865,236
Why bother to write -> rather than .?
Possible Duplicate: Why does C have a distinction between -> and . ? What is the real reason for a programmer to have to differentiate between . and -> when accessing a member of an object? void foo( Point &p ) { p.x ; p->y; // syntax error } void foo( Point *p ) { p.x ; // syntax error p->y; } I...
Because p->d actually means (*p).d. It does a dereference and then a member access. References behave like objects thus they don't need dereferencing (they are also a C++ feature, while pointer are inherited from C); it has been kept that way for backwards compatibility. C++ is full of inconsistencies like this, but th...
3,865,432
3,865,489
Does hash_map automatically sort [C++]?
In the below code, hash_map is automatically sorting or maybe inserting elements in a sorted order. Any ideas why it does this?? Suggestions Please?? This is NOT a homework problem, trying to solve an interview question posted on glassdoor dot com. #include <iostream> #include <vector> #include <ext/hash_map> #include ...
Hash map will not automatically sort your data. In fact the order is unspecified, depending on your hash function and input order. It is just that in your case the numbers turns out are sorted. You may want to read about hash table for how this container stores the data. A clear counter example can be created by repla...
3,865,594
3,865,683
In which order does the linker process the library directories?
It is possible that more than one instance of the library exists in the search path during compilation. In what order will linker process directories included in the search path? The platform in question is Sun OS.
The directories are searched in the order in which they are specified on the command line. Directories specified on the command line are searched before the default directories. All -L options apply to all -l options, regardless of the order in which the options appear. LD_LIBRARY_PATH may also be used to supplement th...
3,865,653
3,865,977
Pass character stream to libxml2
I have a XML document which is received as a character stream. I wish to parse this using libxml2. Well one way would be to save it as an .xml and then open it using one of the libxml2 API's. Is there a way i can directly build a tree on this stream and parse it ? Env is purely c++/c. Cheers!
You can use xlmCtxtReadFd from parser.h. There's also xmlCtxtReadMemory, if you would rather use a block of memory than a stream.
3,865,713
3,865,871
Is va_start (etc.) reentrant?
While making an edit to a class with a long history, I was stymied by a particular habit of the architect of wrapping his va_start -> va_end sequence in a mutex. The changelog for that addition (which was made some 15 years ago, and not revised since) noted that it was because va_start et. all was not reentrant. I was...
As far as being serially-reentrant (ie., if foo() uses va_start is it safe for foo() to call bar() which also uses va_start), the answer is that's fine - as long as the va_list instance isn't the same. The standard says, Neither the va_start nor va_copy macro shall be invoked to reinitialize ap without an intervening...
3,865,737
3,865,816
2D Bounding box collission
i'm having some problems with collission in a small 2D game i'm writing. I'm currently working on a function that i want to find if the player character collides with a block, and which side of the block he collided with. Currently i have something like (psuedo-code): if(PLAYER_BOX IS WITHIN THE BLOCKS Y_RANGE) { i...
I'm guessing the issue is direction. What you really want to do is to take into account the "player" direction first and then do your checks. If you don't know what direction the player is moving in you could get a number for false hits depending on how "fast" your sprites are moving. For example if you have moveme...
3,865,814
3,865,849
Does && in c++ behave the same as && in Java?
my question is essentially in the title. Basically I've learned that in Java the && operator acts like a short circuit, so that if the first condition evaluates to false it doesn't look at the rest of the statement. I assumed this was the case in c++ but I'm writing a bit of code which first checks that an index has no...
Yes, in C and C++ the && and || operators short-circuit.
3,865,820
3,866,092
Size of class instance
I'm working with a class for which the new operator has been made private, so that the only way to get an instance is to write Foo foo = Foo() Writing Foo* foo = new Foo() does not work. But because I really want a pointer to it, I simulate that with the following : Foo* foo = (Foo*)malloc(sizeof(Foo)); *foo = Foo();...
Be careful about breaking the Concrete Data Type idiom. You are trying to circumvent the fact that the new operator has been made private, i.e. the Concrete Data Type idiom/pattern. The new operator was probably made private for specific reasons, e.g. another part of the design may depend on this restriction. Trying...
3,865,958
3,865,981
STL iterator into constructor
Id' like to know how to write a constructor for a custom class (a linked list in this case) that accepts any STL input iterator. I have already created a custom Iterator class which is tied to my List class. This works fine. template <typename T> List<T>::List(Iterator beg, Iterator end) : first_(0) { while (...
I think it's as simple as this: template <typename T, typename Iterator> List <T>::List(Iterator beg, Iterator end) : first_(0) { while (beg != end) insertLast(*beg++); }
3,866,075
3,866,104
Read and copy file with EOF indicator in the middle
I used the code below to copy from one binary file to another, but the first file contains some EOF indicators (0xFF) as part of it, so the copy function actually copies the file until its first EOF indicator. For example: if my file is {0x01, 0x02, 0x03, 0xFF, 0x01, 0x02, 0xFF, 0xFF} then only {0x01, 0x02, 0x03} will ...
fgetc returns an int, not a char , so you can tell the difference between EOF and a char with the same value as EOF. Change: char ch; to int ch And (usually not relevant if you're on *nix) fs = fopen(infile,"r"); to fs = fopen(infile,"rb");
3,866,215
3,866,268
What is POI and what does it mean?
What is POI? I have seen this term being used several times in context of C++ Templates. What does it mean?
POI means Point Of Instantiation. From C++ Templates : The Complete Guide 10.3.2 Points of Instantiation A point of instantiation (POI) is created when a code construct refers to a template specialization in such a way that the definition of the corresponding template needs to be instantiated to create that specializa...
3,866,344
3,866,385
Same nested selection
Is there any performance difference between: size.width += this->font->chars[*ch].advance + this->font->chars[*ch].offset.x; and char_data *chars = this->font->chars; while(...) { size.width += chars[*ch].advance + chars[*ch].offset.x; } In first example are always read vars( this->font, font->chars ) within loop,...
That would depend on your compiler and optimization settings. At the most basic level, the first one will be slower because you're doing extra dereferencing and access operations. But in reality, the optimizer can identify these repetitions and eliminate them. To definitively answer this, you should run a test and comp...
3,866,362
3,866,599
Is there a standard Windows dialog for obtaining the proxy username and password?
I'm using WinHTTP to write an an app that needs access to the internet, and is potentially behind a proxy. Everything works (almost) out of the box is the user is on a domain, but if he or she isn't then I need a way to ask for credentials. Is there a standard way of doing that, or should I write my own dialog? Ideally...
CredUIPromptForCredentials() (or one of its variants) is probably what you're looking for. This provides a consistent look and feel with the version of Windows your software is running on.