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
4,125,956
4,126,005
Why is VisualStudio looking for this lib file? LNK1104 error
We have a large project using VS2008 and boost 1_42. I'm trying to upgrade to VS2010 and boost 1_44. I installed VS2010 and boost 1_44 and converted the project. Now I am trying to build, and everything compiles, but fails when linking: LINK : fatal error LNK1104: cannot open file 'libboost_thread-vc90-mt-1_42.lib' ...
Along with changing the lib directory, you need to change the name of the boost library. That's in the Linker | Input section of the project settings. Your added comment makes it clear that the dependency on the Boost 1.42 library was being created indirectly by another library that hadn't been rebuilt. For this you ba...
4,125,971
4,156,038
Setting the global LUA_PATH variable from C++/C?
I'm trying to set my global LUA_PATH variable directly from C/C++, I'm using Lua from my iPhone applications, so my path tends does change between applications ( each iPhone app has a separate folder in the device ). I know I could set the LUA_PATH by recompiling lua with a "fixed" path, but that's quite far from idea...
In C++: int setLuaPath( lua_State* L, const char* path ) { lua_getglobal( L, "package" ); lua_getfield( L, -1, "path" ); // get field "path" from table at top of stack (-1) std::string cur_path = lua_tostring( L, -1 ); // grab path string from top of stack cur_path.append( ";" ); // do your path magic h...
4,126,009
4,127,755
what happens function stack memory and control of the function from where you invoke the signal
A quick question as to what happens to the local function while, if you are binding some other function to a local function, the called function is still running. Is the signal-invoker waiting for the later function to finish to resume control? e.g. //if we have a signal declared as : typedef boost::signal0<void> SendA...
I'm not sure I understand your question. Triggering the signal (CallAbortFunction) will sequentially call every slot, then return (your local clean ups won't run concurrently). It is essentially identical to iterating over a sequence of functions and calling them one after another.
4,126,130
4,126,148
Will a base destructor always be called when a derived object is deleted?
say I have the following: class Foo { public: void destroy(); ~Foo() { destroy(); } }; class Bar : public Foo { public: ~Bar() {} }; If I have a Bar object, will Foo's destructor be called when the Bar objected is deleted? Thanks
Yes. But the above code is dangerous; if you don't declare ~Foo() as virtual, then ~Bar() won't be called if you invoke delete on a Bar object via a Foo *.
4,126,368
4,126,388
What happens when writing to a socket from different threads at the same time?
I have two threads, each with a buffer with some data. I have a function that writes to a TCP socket. (I use ffmpeg for it.) How will the data packets arrive at the server — in some crazy mixed up way, or in some other order, or will the OS (Windows, in my case) make one thread wait until the other has finished?
That depends entirely upon which implementation of "sockets" you are using. If your implementation is synchronized, you'll get the first thread's data, followed by the second thread's data (The second thread will block while the first sends). If your implementation is not synchronized, you'll get gibberish.
4,126,588
4,126,608
c++: How do I safely cast a const double** to a const void**
The following code gives a compiler error in C++: const double** x; const void** y = x; How do you get a const-safe equivalent? Of course, you can get this to work with a simple cast: const void** y = (const void**) x; But surely the compiler should know that this ok? Why does it complain?
Why should the compiler know that that is OK? I think you want the following instead void *y = x; x = static_cast<const double**>(y); // casting back needs static_cast or c-style cast A void** doesn't have the special properties that a void* has (that of being an universal data pointer).
4,126,616
4,126,652
C++ to C call: argument of type 'void (MyClass::)(u_char*,)' does not match 'void (*)(u_char*)'
my rusty C++ skills got a fail after: #include <pcap.h> ... void Sniff::pcap_listen() { pcap_t *loc; char *dev; dev = pcap_lookupdev(errbuf); loc = pcap_open_live(dev,BUFSIZ,0,-1,errbuf); pcap_loop(loc,-1,pcap_callback,NULL); } error: argument of type ‘void (Sniff::)(u_char*, const pcap_pkthdr*, const u_char...
You can't pass a pointer to a member function to something that's expecting a function pointer. Fundamentally a pointer to a member function is a completely different type than a function pointer. There is no trivial conversion between the two and can never be one as there's no this pointer, which is required to call a...
4,126,730
4,126,748
C++ What .lib file should I include
I am doing a firewall application. For that I tried some codes from codeproject HERE But the problem is the code is not compiling, giving linking error. I am using SDK 2008. Can anyone please tell me what .lib file should I use for WFP and where can I find it ? Thanks.
Fwpuclnt.lib is the one you need - check out the reference for the functions you are using on MSDN, they tell you in the 'Requirements' section what lib exports a given API. You need the correct SDK to use this.
4,127,041
4,127,070
WM_KEYDOWN, getting values from the lparam?
On MSDN, for the WM_KEYDOWN defition it says the bits of lparam contain: Bits Meaning 0-15 The repeat count for the current message. The value is the number of times the keystroke is autorepeated as a result of the user holding down the key. If the keystroke is held long enough, multiple messages are sent. Howev...
Well, for one thing 0-15 is 16 bits, not 15.
4,127,333
4,127,346
Should mutexes be mutable?
Not sure if this is a style question, or something that has a hard rule... If I want to keep the public method interface as const as possible, but make the object thread safe, should I use mutable mutexes? In general, is this good style, or should a non-const method interface be preferred? Please justify your view.
[Answer edited] Basically using const methods with mutable mutexes is a good idea (don't return references by the way, make sure to return by value), at least to indicate they do not modify the object. Mutexes should not be const, it would be a shameless lie to define lock/unlock methods as const... Actually this (and ...
4,127,461
4,127,712
MFC Serial Communications
I need to add serial port (e.g. COM8) communications to my MFC application. Which APIs should I be looking at to do this? I need it to be able to wait for n bytes to be in the receive queue before triggering (event, message, callback, etc.). Is there a relatively simple way to do this? All the examples I have looke...
Overlapped I/O in Win32 works really well: http://www.codeproject.com/KB/system/serial_com.aspx Also AFAIK, there are no official MFC class(es) for serial communications. (These could be easily wrapped though).
4,127,511
4,127,619
Boost threads and FFmpeg: Such simple code gives me error C2064. What I do wrong way?
I have some class file.h where public: bool frameSendingFinished; is defined. So in class logic i create and encode video frame, now I want to send it to some server using ffmpeg. I want to send in separate thread so in one of my classes function (in file.cpp) I do: if (frameSendingFinished) { boost::thread U...
When you write: boost::thread UrlWriteFrame(url_context, (unsigned char *)pb_buffer, len); you create a boost::thread object named UrlWriteFrame, and pass url_context, pb_buffer and len the the boost::thread constructor. One of boost::thread's ctors expects something callable (function pointer, function object) as the...
4,127,567
4,127,696
Linux C++ run and communicate with new process
I need to make a program that runs a process (my another programm) and can communicate with this process (sending stdin and recieving stdout). I have read about functions like popen() and CreateProcess() but I don't really understand how to work with them. Would be great, if you show me some sample code (how to start p...
The interface for POSIX functions C language only. But you can use them in C++. Basically: #include <unistd.h> // Include some other things I forgot. See manpages. int main() { // Open two pipes for communication // The descriptors will be available to both // parent and child. int in_fd[2]; int ou...
4,127,592
4,127,627
How to parse text-based table in C++
I am trying to parse a table in the form of a text file using ifstream, and evaluating/manipulating each entry. However, I'm having trouble figuring out how to approach this because of omissions of particular items. Consider the following table: NEW VER ID NAME 1 2a 4 "ITEM ONE" (2001) 1 7 "2 ITE...
If the column offsets are truly fixed (no tabs, just true space chars a la 0x20) I would read it a line at a time (string::getline) and break it down using the fixed offsets into a set of four strings (string::substr). Then postprocess each 4-tuple of strings as required. I would not hard-code the offsets, store them...
4,127,600
4,127,695
Checking if memory had been initialized
If I have allocated some amount of memory via ::operator new(nbytes) and later I have constructed in this pool via "new (where) what" some number (but lesser than nbytes) of objs of appropriate type, is there a way to check where is the uninitialized memory starts? Example struct T{}; short noOfObj = 10; T* p = stat...
wow... ok, trying to battle through this question... It seems like you are on about doing your own memory management... such as requesting a huge array of chars to get a big block of memory under control of your program then using this to initialise your own variables, but you want to know what you have given to variab...
4,127,771
4,135,697
Cocoa-track the menu of/inject options into itunes
Is there a way I can inject menu items into itunes or detect when menu items are pressed. I have an itunes plugin that executes code when iTunes launches, but how can I use that to detect menu item clicks or possibly inject new menu item options? For example adding a new contextual menu item when you right click on a l...
Whatever functionality is not provided by an app's scripting bridge would only be accessible by hackery. iTunes a Carbon app, not Cocoa, so that's more for you to learn about. iTunes even uses a call to ptrace(), passing PT_DENY_ATTACH to prevent you attaching a debugger to snoop around at runtime as well. In other wo...
4,127,924
4,127,951
Check if input is a correct integer
I have a little problem with checking my input. I know that there a already similar questions but sincerly it does not solve my problem. I'm already using one of the suggestions from the other questions and it does not work. #include <iostream> #include <stdio.h> #include <ctype.h> int main () { int a; printf("Ple...
a is already an integer variable. std::isdigit only checks whether a character corresponds to a digit, i.e. the characters '0' to '9'. Try not to mix C libraries (printf, scanf etc.) with C++ libraries (cout and cin). Stick to either one. As for how to actually check whether the user entered a number or not, see this ...
4,128,113
4,128,234
What's the point of IsA() in C++?
I'm trying to figure out why some code bases use IsA() to determine object polymorphism if in C++ you can already safely upcast and down cast (using dynamic_cast) ? So far the only case I see useful is when you are integrating a a scripting environment that is linked to the c++ codebase? Thanks!
In modern C++ there is no point. Frameworks dating from before the 1998 standardization may offer an IsA function. E.g. as I recall there is such functionality in MFC. Also, as you note, when dealing with objects implemented in other languages (with types not represented by C++ types) it may conceivably be useful. Chee...
4,128,539
4,128,600
Qt/C++ QTableWidget: Doing something when a header is doubleclicked
I have a QTableWidget in my form and I want to do something when a user doubleclicks on the header of a row or column. I am using the following connect statement: connect(ui->tblResults->horizontalHeader(),SIGNAL(doubleClicked(QModelIndex)),this,SLOT(tableDoubleClicked(QModelIndex))); Where this is the window class an...
http://doc.qt.nokia.com/latest/qheaderview.html#sectionDoubleClicked You can get the QHeaderView via QTableWidget::horizontalHeader() or QTableWidget::verticalHeader().
4,128,776
4,128,816
How to pass std::map as a default constructor parameter
I haven't been able to figure this out. It's easy to create two ctors but I wanted to learn if there's an easy way to do this. How can one pass a std::map as the default parameter to a ctor, e.g. Foo::Foo( int arg1, int arg2, const std::map<std::string, std::string> = VAL) I've tried 0, null, and NULL as VAL, none of ...
The correct expression for VAL is std::map<std::string, std::string>(). I think that looks long and ugly, so I'd probably add a public typedef member to the class: class Foo { public: typedef std::map<std::string, std::string> map_type; Foo( int arg1, int arg2, const map_type = map_type() ); // ... }; And by th...
4,128,920
4,128,944
how do you split an array in c++?
Im trying to do a simple string splitting function, but im having a problem returning the split string. i got the string into strings s1, s2, s3. how do i return {s1,s2,s3}? im using brackets but the compiler is telling me expected primary-expression before '{' token expected `;' before '{' token expected `;' befor...
You probably want to return type vector<string>. Then in your function create a vector and return it as a value.
4,128,942
4,128,978
Recursive function that returns a bool?
I want to make a recursive function that iterates through a tree and the first time the condition hits, I want it to return. Would this be proper? bool nodeExists(Node *root, Node *target) { if(root == target) { return true; } for(int i = 0; i < root->nodes.size(); ++i) { ...
It's good, but I'd rather use a different identifier than "nodes". "children" is nice because it's clear and unambiguous.
4,128,974
4,377,014
Sharing Pre-compiled Headers efficiently
I have a framework which is being used by several projects (which includes several samples to show how the framework works). The framework has components such as the core, graphics, physics, gui etc. Each one is a separate library. There are several configurations as well. A main solution file compiles the complete pr...
It sounds like the size problem is coming from using headers you don't actually need, but that it still makes sense to use these headers when developing because of the faster turn around. On using #ifndefs: Precompilation is crude. You lose the ability to share the precompilation work at the point where there is a d...
4,129,023
4,129,077
How useful would Inheriting Constructors be in C++?
As I sit in the C++ Standards committee meetings, they are discussing the pros and cons of dropping Inheriting Constructors since no compiler vendor has implemented it yet (the sense being users haven't been asking for it). Let me quickly remind everyone what inheriting constructors are: struct B { B(int); }; str...
2) Are there any technical reasons you can think of that would preclude "perfect forwarding constructors" from being an adequate alternative? I have shown one problem with that perfect forwarding approach here: Forwarding all constructors in C++0x . Also, the perfect forwarding approach can't "forward" the explicite...
4,129,056
4,130,590
static objects in visual studio build
I have a problem with my visual studio - 08 build. some of the static objects are not getting instantiated. its wierd, i have a couple of files which create similar static objects. some are created some are not. when i tried to break point in the file for uncreated objects, my breakpoint is disabled. how do i make sure...
Are these files directly in your main project, or are they in a static library? When you make a static library, the linker only pulls in global variables (and calls their constructors) from object files that are somehow used. If you do have a static library, you'll have to make sure each of the files is used by a func...
4,129,110
4,129,146
Operator overloading "operator T * ()" produces a comparison operator?
class Test { public: operator Test * () { return NULL; }; }; int main() { Test test; if (test == NULL) printf("Wtf happened here?\n"); return 0; } How is it that this code compiles? How did Test get a comparison operator? Is there some implicit casting going around? What does that overloaded ...
The overloaded operator adds a conversion from Test to Test *. Since there is no comparision operator defined that takes Test and NULL as arguments, any conversion operators that exists are tried. operator Test * returns a type which is comparable with NULL, so it is used.
4,129,225
4,129,234
how do i include multiple class with the same includes?
How do i include two .h/class files that both have #include "h_file.h"? both require the .h file definitions, and both are included in the main program. how do i prevent the redefinition of the .h definitions (which causes the compiler to not compile)? i have: main.cpp class1.h/class1.cpp class2.h/class2.cpp h_file.h
Use include guards: #ifndef INCLUDE_GUARD_IDENTIFIER_GOES_HERE #define INCLUDE_GUARD_IDENTIFIER_GOES_HERE // code for header #endif The second time it's included, it's effectively an empty file. There are many different ways of choosing the identifier INCLUDE_GUARD_IDENTIFIER_GOES_HERE, with rationales for each. Pe...
4,129,239
4,129,339
Undefined behavior or false positive
I've (essentially) come across the following in the wild x = x = 5; which apparently compiles cleanly under earlier version of gcc (generates a warning under gcc 4.5.1). As far as I can tell the warning is generated by -Wsequence-point. So my question is does this violate the wording in the standard about manipulati...
Assuming x is of built-in type, it assigns to x twice without an intervening sequence point, which is all you need to know. The fact that both assignments are of the same value (5), and could in theory be optimized into a single assignment (if x is not volatile), is neither here nor there. At least, that's how I interp...
4,129,261
4,129,313
c++ breaks on class function
i have created this class for mesh loading it works but i added this new function to help speed up the loading. when i call the function my program breaks/stops. here is my function bool CXFileEntity::LoadXFile(const std::string &filename, int startAnimation, CXFileEntity *entity, LPDIRECT3DDEVICE9 d3ddev) { // We...
EDIT: Wait... I hadn't realized that this function is a member of the CXFileEntity class. It doesn't look like it's a static method, either. So in order to call this function, you already need to have instantiated a CXFileEntity object! Therefore, it's likely that you absolutely do not want to be either deleting or cre...
4,129,284
4,129,349
Native C++ Systray application questions
I have been writing a program to ping three different sites and then it informs the user if they have internet or not. I have had a lot of success on getting this program to work, in no small part due to the awesomeness of the community here. My code is written in native c++ due to the fact that I know the language th...
Native C++ systray applications are based on the Win32 Shell API Shell_NotifyIcon. To add your icon to the sys tray you want something like this: memset(&iconData, 0, sizeof(NOTIFYICONDATA)); iconData.hIcon = ::LoadIcon(hResourceModule, MAKEINTRESOURCE(IDR_MAINFRAME)); iconData.hIcon = ::LoadIcon(hResourceModule, MAKEI...
4,129,374
4,129,419
Link Error, even though everything is there
I'm working on a (C++) program that has to process a lot of information associated with a file/directory (so more or less I have a path as a key). Currently I've attempted a implementation using hash tables. This seem to work reasonably well given the volume of data but after profiling I find they are still the slowest...
You're mixing C and C++. When you include datatrie/trie.h in your C++ code the compiler assumes it's a C++ header, howeever libdatatrie is a C library and its headers arn't C++ friendly. Include the header like: extern "C" { #include <datrie/trie.h> }
4,129,430
4,129,513
Qt automated testing
http://www.automatedqa.com/products/testcomplete/testing-qt-apps/ How would they have been able to do that? Is there a Qt inspection library? Standard window spy tools work in some areas, but other important areas (such as list items in a list view) are not inspectable through Windows messages. I know there's the QtT...
Found the answer: http://www.ranorex.com/support/user-guide-20/qt-accessible-plugin.html http://doc.qt.io/archives/4.3/accessible.html Exactly what is needed to automate a UI. Will then work with any UI automation software, which I've now learned apparently uses the accessibility API.
4,129,536
4,129,551
Webserver in C++, how to send an image
I am making my own simple webserver and I have gotten text files and html files to send perfectly, but when I try to send images, I am having some issues, and I can't figure it out. Here is what I have. I know sending one byte at a time is inefficient but it was for testing. char buffer[1]; send_header(new_fd, get_fil...
strlen(buffer) is going to count up to the first null character ('\0'), which is a very common byte in image data. You need to, instead, figure out how many bytes were actually read (ifstream.read() does not supply this information) and use that in place of your strlen call. EDIT: You can obtain this with ifstream.gco...
4,129,736
4,129,938
How does this line-intersection work?
I'm building an Asteroids Game for a class assignement. To finish it I need a line-intersection algorithm/code. I found one that works, but i do not understand the math behind it. How does this work? point* inter( point p1, point p2, point p3, point p4) { point* r; //p1-p2 is the first edge. //p3-p4 is the second ed...
point* inter( point p1, point p2, point p3, point p4) { point* r; //p1-p2 is the first edge. //p3-p4 is the second edge. r = new point; As others have already commented, the above can/will leak memory. Better use a smart pointer, e.g. std::auto_ptr. float x1 = p1.x, x2 = p2.x, x3 = p3.x, x4 = p4....
4,130,044
4,130,092
What does _ITERATOR_DEBUG_LEVEL = 1 mean?
In VS2010, C++ project I get this error when linking in x64/Release: error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '1' All other configuration/platform combinations link just fine. So a static library is built with _ITERATOR_DEBUG_LEVEL set to 0 and the .dll that depends o...
Well, after struggling with this for an hour I figured it out right after I asked the question... for posterity: _ITERATOR_DEBUG_LEVEL = 0 (in release mode) _ITERATOR_DEBUG_LEVEL = 1 (in release mode if _SECURE_SCL is defined) _ITERATOR_DEBUG_LEVEL = 2 (in debug mode) Somehow I had _SECURE_SCL defined as a preprocesso...
4,130,050
4,130,202
Why does my string get empty values appended to it when subtracting characters?
I am attempting to solve a problem from topcoder.com and it's driving me crazy. I am learning C++ after a long break from C and am having trouble with strings. The purpose of the program is to decode a string of 0s and 1s that has gone through an encryption algorithm that consists of adding each adjacent digit to the d...
A character is an 8-bit integral type. It has the special property that, when printed, it will appear as the character that matches the ASCII value that it contains. For example: int valueAsInt = 65; char valueAsChar = valueAsInt; std::cout << valueAsChar << "\n"; valueAsInt = 'A'; std::cout << valueAsInt << "\n"; ...
4,130,175
4,130,253
C++ memory allocation: 'new' throws bad_alloc?
In my application I save voxel-data (compressed byte array) and trying to load it back again into memory. But my application crashes in Windows 7 machine (64 bit ,12 GB) giving bad_alloc . This works fine on Linux ,and even runs on some other Windows 7 machine with 4 GB memory. Compressed bye size is about 200Mb and u...
If you are building the program as a 32-bit binary on Windows, you only get 2GB of available address space (the upper half is reserved). When you consider that the address space can be fragmented by lots of different things being allocated (DLLs getting loaded, thread stacks, dynamic allocation), it's likely that you'l...
4,130,180
4,130,267
How to use VS C++ GetEnvironmentVariable as cleanly as possible?
(This is not so much a problem as an exercise in pedantry, so here goes.) I've made a nice little program that is native to my linux OS, but I'm thinking it's useful enough to exist on my Windows machine too. Thus, I'd like to access Windows' environment variables, and MSDN cites an example like this: const DWORD buff_...
DWORD bufferSize = 65535; //Limit according to http://msdn.microsoft.com/en-us/library/ms683188.aspx std::wstring buff; buff.resize(bufferSize); bufferSize = GetEnvironmentVariableW(L"Name", &buff[0], bufferSize); if (!bufferSize) //error buff.resize(bufferSize); Of course, if you want ASCII, replace wstring with ...
4,130,201
4,131,235
Overload Resolution/Ambiguity in name lookup(which one)
$7.3.3/14 (C++03) struct A { int x(); }; struct B : A { }; struct C : A { using A::x; int x(int); }; struct D : B, C { using C::x; int x(double); }; int f(D* d) { return d->x(); // ambiguous: B::x or C::x } The comment in the code in 'f' indicates that one can expect ambiguity between 'B::x' or 'C::x'. ...
This is caused by a twist in name-lookup in C++03: Checking for an unambiguous subobject was part of class member name lookup in C++03. Lookup in C++03 will find D::X and C::x and A::x, where A::x matches, but is associated with two distinct subobjects of type A. In C++0x, the checking for an unambiguous subobject is n...
4,130,222
4,130,284
Qt/C++: Having an MDI child call a function of its parent?
I have a Qt Designer Class called MainWindow which is a QMainWindow. This class creates an MDI Area and has children windows, as MDI should. One of these MDI children, we'll call wndChild which is also a QMainWindow, needs to spawn a "sibling" (that is, an MDI child of its parent, not an MDI child of its own). I figu...
Use qobject_cast to get a pointer to MainWindow : MainWindow *mdiparent = qobject_cast<MainWindow*>(this->parentWidget()); mdiparent->spawnOtherChild();
4,130,250
4,130,299
Is it possible to solve this?
Recently I encountered this puzzle : int main(){ int arr[7]; int b,c,d,a; a=4; printf("%d",arr[?]); return 0; } The question is to Replace "?" with a integer so that output is 4. I am not sure but I don't think this is solvable in a standard way ?! (Not invoking Undefined Behavior or depending ...
Assuming there is no answer that conforms to the standard, could you use an operation (obviously not an integer) like arr[&a-arr]? Edit: Made cleaner thanks to Ben and others in the comments.
4,130,257
4,130,802
Netbeans print debug value C / C++
I am interested in displaying a struct / class object in a specific way using Netbean's default GDB debugger for C and C++ projects so I can step through the code quicker. For Java there is an easy way to do this using the "Variable Formatters" section under Tools -> Options -> Misc -> Variable Formatters. I am looki...
I don't know Netbeans enough to help you with a macro to do that but there is an easier solution, either: let the debugger access a variable (made 'public' instead of private in your C++ class) or add this code in your program: int height = MyObject.getHeight(); so you can display the variable in the debugger. Thi...
4,130,301
4,130,311
Overloading postfix increment operator
I am trying to overload the postfix increment operator as a member function for a class which stores large numbers as an array of ints. But it keeps getting returned as 0. Any tips on why this doesn't work? This is a homework question, so I would like more of a tip than straight code. Thanks. The member data looks like...
Your comment disagrees with your code. operator++(int) is postfix increment, operator++() is prefix.
4,130,335
4,131,193
Built-in operator candidates
C++03 $13.6/1- "[...]If there is a user-written candidate with the same name and parameter types as a built-in candidate operator function, the built-in operator function is hidden and is not included in the set of candidate functions." I am not sure about the intent of this quote from the Standard. Is it...
Just pick one of those in 13.6. Like For every pointer or enumeration type T, there exist candidate operator functions of the form bool operator<(T, T); bool operator>(T, T); bool operator<=(T, T); bool operator>=(T, T); bool operator==(T, T); bool operator!=(T, T); So enum Kind { Evil, Good }; bool operator<(Kind ...
4,130,434
4,130,454
C++ undefined reference to defined function
I cannot figure out why this is not working. I will put up all three of my files and possibly someone can tell me why it is throwing this error. I am using g++ to compile the program. Program: #include <iostream> #include "h8.h" using namespace std; int main() { char sentence[MAX_SENTENCE_LENGTH]; char writeTo[...
The declaration and definition of insertLike are different In your header file: void insertLike(const char sentence[], const int lengthTo, const int length, const char writeTo[]); In your 'function file': void insertLike(const char sentence[], const int lengthTo, const int length,char writeTo[]); C++ allows function o...
4,130,457
4,130,483
Dictionary/hash_map key size
The hash value for key is caculated and is divided by a prime number. In general, Is there any standard prime number (say for 32/64 bit) for this? My understanding is the hashtable is not resizable/adjustable and its internal array depends on this. If I have a hashtable for only 5 elements will there be waste in key s...
In fact, hash tables sizes can be adjustable automatically. What you might do is allocate an array of size N, using a hash modulo N (some prime number) for indexing into the array. If you keep track of the density of your allocation, then when it increases beyond some threshold you can allocate a new array of size N1 (...
4,130,518
4,132,069
Displaying RGB Image in GTK+-2.2
I'm writing a class that can take my own RGB images and display them to windows using GTK+-2.2. My Image class stores the images as packed 24-bit RGB bytes, so the conversion should be trivial. I'm using the gdk_draw_rgb(...) method to draw to my window, but nothing gets drawn at all - the window just shows up gray. I...
gdk_draw_rgb_image( gtk_widget_get_root_window(window), There's your problem. In X terminology (which GTK+ borrows from heavily), the "root window" refers to the desktop background. You want gtk_widget_get_window which will get you the GdkDrawable which represents your window. However... I haven't walked very far...
4,130,540
4,130,614
Create stack where the elements are arrays
In my Qt project i have enum: enum Field {EMPTY=0, WHITE=1, BLACK=2}; And array of this enum: Field field[8][8]; Now i need create Stack of this array. Ever element of stack must be field[8][8]. How can i make it?
struct FieldMatrix { Field fields[8][8]; }; // not familiar with Stack, but here's the standard library stack type std::stack<FieldMatrix> foo;
4,130,547
4,130,560
Can a static member variable call non-static member functions?
I saw the following code: http://sourcemaking.com/design_patterns/singleton/cpp/1 class GlobalClass { private: int m_value; static GlobalClass *s_instance; GlobalClass(int v = 0) { m_value = v; } public: int get_value() { return m_value; } void set_value(int v) { ...
Variables don't call anything (This doesn't really address the sample code, but it corrects a misconception in the two "rules" listed beneath the code) A static member function is a member, and can access all public, protected, and private members of its class, both static and instance. However, static member functions...
4,130,613
4,130,662
Default arguments and variadic functions
Is there any way to specify a default parameter in a variadic function?(Applies to templates also)
In C++ you can replace the variadic function with one based on the Named Parameter Idiom. See the C++ FAQ item 10.20 What is the "Named Parameter Idiom"?. That gives you default functionality & convenient notation. Cheers & hth.,
4,130,632
4,586,033
Saving a web page as image
As a hobby project I am exploring the ways to save a web page (HTML) as image, mostly programatically using c/c++/javascript/java. Till now I have come across the following ways: Get the IHTMLElement of page body and use it to query for IHTMLElementRender and then use its DrawToDC method (Ref: http://www.codeproject.c...
Well finally able to crack it by going through these two articles: http://www.codeproject.com/KB/GDI-plus/WebPageSnapshot.aspx [c# code - IE] http://www.codeproject.com/KB/graphics/IECapture.aspx [c++ & GDI - IE] Can't share the code, but the above two articles will give you the best possible solution. Also hav...
4,130,693
4,130,810
how do i write assembly in C++ for adding (time test)
I want to time how much slower it is if i were to do a simple operation like 1+1 and plus(int l,int r) which does l+r and throws an exception on overflow heres some example code with _C and _V being carry and overflow. The exception code can be written differently if you like. How do i write it so i can quickly test fo...
Do you want C/C++ code to perform these operations, or do you want to know how to do it in x86 assembly language? In C/C++, determining the carry is easy: int _C = (v < l); // "v < r" works too The overflow is a bit more complicated. Normally overflow is flagged when the two operands have the same sign yet the result ...
4,130,755
4,131,355
C++ event system design
I need to use an event system in C++. I have mainly four requirements : Speed Ease of use Type Safety Friendly Destruction By "Friendly Destruction" I mean the event and the subscriber need to manage their disconnection when one of them get destroyed : An event shouldn't call a subscriber that has been destroyed. ...
Use boost::signals or boost::signals2 if you want thread safety.
4,130,757
4,130,794
How to get multiple return values when calling c++ from lua scripts?
//c++ funciton definition int LS_SomeFucntion(LuaState* state) { LuaStack args(state); //.. set<int>::iterator it = mySet.begin(); for(; it != mySet.end(); ++it) { state.pushInteger(*it); } return mySet.size(); } state->GetGlobals().Register("SomeFunction",LS_SomeFunction); //lua scripts ??? = SomeFunction() H...
You can capture all the return values in a table: local rv = { SomeFunction() } print('SomeFunction returned', #rv, 'values') for i,val in ipairs(rv) do print(i,val) Or process them using a variable parameter list: function DoSomething(...) local nargs = select('#', ...) print('Received', nargs, 'arguments'...
4,130,785
4,130,824
Converting c++ vb6 COM object into dot net
I have a COM object in C++ and VB6 and everything is compiled and packaged using Visual Studio 2003. The C++ generates the DLL, and VB6 the EXE, so from the legacy code I can call the EXE that calls the DLL and so on. I need to migrate these to Visual Studio 2008. However, I have some questions 1) I can compile the C++...
You have not clarified if the VB code is an out-of-process COM server, or a client consuming the C++ inproc COM object. If the VB code is a client, you can use build it as a VB.Net executable, with either a COM reference to the coclass, or if you don't want the C++ object to be registered during the build, you can use ...
4,130,806
4,130,816
concurrent modification of bits in a integer
I want to know if i attempt to set bits inside a char/integer from multiple threads, will i lose any modification? I will have all zeros initially and the threads will only set it to 1. The system architecture is x64. Thanks, Gokul.
On x64 (and x86) operations on ints are atomic. This means that reads and writes are independently atomic, not in combination. (E.g. If you have two threads write an int at the same time, you won't see one half of one and one half of the other -- you will always see one full int or the other.) However, reading and wr...
4,130,895
4,130,940
Can i write Cocoa Touch[iPhone] applications in C++ language
1) Can i write iPhone applications in pure C++ language, i know that we can use Objective-C++, i just want to know if we can also write it in pure C++ language. 2) while creating MAC OX application inXCode, we have an option to create C/C++ application, will the same options work for me to write iPhone applications?
You cannot use pure C++ only - at least a portion of the UI must be written in Objective C/Objective C++, as all applications must provide a delegate and a main view. Once you have the application running and do not wish to use the UI libraries (such as a game), you can proceed to use Core Graphics or OpenGL to handle ...
4,131,054
4,131,127
C++ Beginner game programming: Keeping track of objects, inventory lists, arrays of different amnts of object/characters, etc
I was just playing an old SNES RPG (Secret of Mana, if anyone cares) and was wondering a few general things about game programming. Sorry for some of the brain-dead questions, I'm really a beginner. :) These questions are quite general, but use SNES-style RPGs as a "template" to get an idea of what I mean: How do game...
In a very basic manner your answers are not too far off, things could be done the way that you mention them. However space and processing power can come into play so instead of an array of bools to track which treasure chests or how far along the chain of events you are you may want to slim it down to bits being on and...
4,131,091
4,131,099
dynamic_cast from "void *"
According to this, void* has no RTTI information, therefore casting from void* is not legal and it make sense. If I remember correctly, dynamic_cast from void* was working on gcc. Can you please clarify the issue.
dynamic_cast works only on polymorphic types, i.e. classes containing virtual functions. In gcc you can dynamic_cast to void* but not from: struct S { virtual ~S() {} }; int main() { S* p = new S(); void* v = dynamic_cast<void*>(p); S* p1 = dynamic_cast<S*>(v); // gives an error }
4,131,220
4,220,487
Data structure to store huge amount of data?
In my application,I have to load volumedata from set of images (MRC images) and keep the pixel data in memory.(images are grayscaled ,so one byte per pixel). My development environment is QT framework ,MinGW for Windows and GCC for Linux. At the moment,I use a simple data structure to store volumedata as : unsigned cha...
The simplest solution to your problem would be to use 64-bit address spaces - modern Macs support this out of the box, on Windows and Linux you will need to install the 64-bit version of the OS. I believe Qt can be used to build 64-bit apps quite nicely. 32-bit systems won't be able to support single allocations of the...
4,131,512
4,131,608
Naming a cyclic buffer class for timed samples?
Given: class Buf { // has fixed buffer size, forming a cyclic buffer tor t->v pairs void add(time_type t, value_type v); // adds value v at time t, overwriting the oldest buffered value value_type get(time_type t); // returns the value at time t1 for t1 <= t < t2 (for t1 and t2 datapoints in the buffer) ... }; ...
You should ask yourself if the user of the class needs to know, or care, that the internal implementation is a circular buffer. If not, name it something that makes it clear what the purpose of the class is: maybe something like TimeMap since it seems to be mapping values to discrete points in time. Then you can always...
4,131,817
4,134,180
How should I do this template function explicit instantiation for DLL use?
I've got following class and template function: template <size_t num> class String{ public: char charArray[num]; }; template <size_t num,typename T> void getString(String<num> & string,T number){ cout <<string.charArray<<' '<<number<<'\n'; } then I tried to do an explicit instantiation as following to export that...
What it is, is a wrong design from the beginning, What I've done is not an explicit instantiation at all because even for different values of "size_t num" different instances of the function are generated opposite to what I was thinking at first so my kind of intended explicit instantiation is impossible with this desi...
4,131,920
4,132,552
Encapsulation v Performance
Simple question: I really like the idea of encapsulation, but I really don't know if it is worth it is a performance critical situation. For example: x->var; is faster than x->getVar(); because of the function calling overhead. Is there any solution that is both fast AND encapsulated?
"There's no overhead if the getVar function is inlined" "If getVar() is simply return var; and is inline and non-virtual the two expressions should be optimized to the same thing" "getVar() in all possibility could be inlined" Can Mr Rafferty make the assumption that the code will be inlined? Not "should be" or "coul...
4,132,161
4,132,465
need tutorials on boost's synchronizations objects
well the docs on boost's thread lib isn't as good as the asio lib... And after reading this: http://www.boost.org/doc/libs/1_44_0/doc/html/thread/synchronization.html I got the main idea but there is no codes and examples, that I could find, using that. I would be happy for a link or explanations on how using that..
These two tutorials might help as they have code examples. this has a section on multithreading which gives an intro to synchronization objects Another one from Dr. Dobb's has an intro.
4,132,290
4,133,770
WxWidgets: Simple math formula hands wrong results?
I am greatly liking WxWidgets, and started with C++ programming in it. My sample program converts Celsius into Fahrenheit from a text form. Here is my basic code: //get "100" from textbox wxString szCelsius = TextCtrl1->GetValue(); long lCelsius; //attempt to cast into long szCelsius.ToLong(&lCelsius, 10); //formula ...
The value 1.8 (which is 9/5) cannot be exactly represented as a binary floating point number - in binary, it is an recurring series of digits (1.1100110011001100110011001100...) - similar to the way 1/3 is recurring in decimal. The closest representation as a single-precision floating point value is just under 1.8 - it...
4,132,314
4,132,340
Would this be considered good C++ code
I have a vector with raw pointers (no, I cannot use smart pointers) and I want to add items to the list in a for loop. I've made a little trial project, and I wondered if this is considered good C++ code in terms of pointer management. Please only consider raw pointer management, I am not interested in smart pointer...
Well, this leaks memory, so it is bad. Can you use a Pointer Container? The reason this code leaks is because you create objects on the heap using new, but you never call delete on them. As for you comment, if you have an object that manually manages some resource, you need The Big Three.
4,132,558
4,132,645
Compile-Time container of functors for controlling an algorithm?
Suppose i want something simple like the following: I have an core-algorithm, which randomly selects one of the specialized algorithms (specialized at compile-time) and process this algorithm. These specialized algorithms are implemented trough functors. The question is now: how to implement a container, which is bui...
If you want your core-algorithm to execute a specialized algorithm, there should be some kind of contract between the core-algorithm and the specialized algorithm. If you define this contract as an interface, your container is simply a container containing pointers to these interfaces, e.g.: class IAlgorithm { pu...
4,132,586
4,132,648
Am I abusing `const`?
These last weeks, I found myself using a lot of const everywhere. Not only in methods or arguments declarations, but even for temporary variables. Let me illustrate with a simple function. I used to write: // A dummy function that sums some computation results unsigned int sum_results(const Operation& p1, const Operati...
Using const on local variables improves code clarity, so it's a good idea. You see const and you immediately know that the variable is never changed later in scope. It's from the same series as making functions short and returning early. Developers are lazy - they often think that it's a useless word that doesn't chang...
4,132,635
4,132,724
Problem with Boost::Test
Why this (copied from boost site ) gives me an error?! in VS 2010 Ultimate: #include <boost\test\unit_test.hpp> #define BOOST_TEST_MODULE MyTest int add( int i, int j ) { return i+j; } BOOST_AUTO_TEST_CASE( my_test ) { // seven ways to detect and report the same error: BOOST_CHECK( add( 2,2 ) == 4 ); ...
Try defining BOOST_TEST_MODULE before you include the header.
4,132,908
4,132,936
Turn a multimap into set of sets
I have a multimap and I would like to get a set of sets - which would group together all the items of type A in the multimap that share the same key. Is there a built-in way to do this in STL?
I don't think there is a built-in way. However it is easy to do manually: std::multimap<key, value> mm; // ... std::multimap<key, value>::const_iterator i = mm.begin(); while (i != mm.end()) { std::multimap<key, value>::const_iterator end = mm.upper_bound(i->first); // construct a set from the values in [i, end...
4,132,949
4,133,034
stringstream operator << for a template type
I have the following code: template <class T> static std::string ToString(const T& t) { stringstream temp; temp << t; return temp.str(); } It compiles with no problems with Visual C++ on Windows, but when trying to compile it with GCC on Linux I get the following error: no match for 'operator<<' in 'temp << t' ...
That depends on the type T as Space_C0wb0y said. Check out the following code #include <sstream> #include <iostream> template<typename T> static std::string ToString(const T& t){ std::stringstream temp; temp << t; return temp.str(); } struct empty{}; struct non_empty{ std::string str; non_empty(std::string o...
4,132,983
4,133,254
C++ code compiles but dies problem (Having a line (queue), a buffer, and if not empty problem)
So I have a class. .h file with some variables like: struct AudioSample { const unsigned char * buffer; int len; }; //... const unsigned char * VideoFrameBuffer; int VideoFrameLen; std::queue<AudioSample> AudioSamples; bool sampleSendingFinished; bool frameSendingFinished;...
There is a thread-safe producer-consumer queue using soon-to-be standard threading mechanisms here. This would be a good intro to the threading concepts you have to understand to make this design work. The producer(s) are the functions that add to your queue, and the consumer(s) are the function(s) that read and (usua...
4,132,986
4,133,009
Does a std::vector constructor not call object constructors for each element?
My code resembles something along these lines. class A { public: A(int i) { printf("hello %d\n", i); } ~A() { printf("Goodbye\n"); } } std::vector(10, A(10)); I notice that hello prints out once. It seems to imply that the vector only allocates space for the element but doesn't construct it. How do I m...
The object is constructed only once, as you pass it to std::vector. Then this object is copied 10 times. You have to do a printf in the copy constructor to see it.
4,133,307
4,133,363
here different instances are generated for this template function or not?
Considering following struct and template function, does each use of the function with a different value for "num" build a new instance of the function or since const numbers<num> & nums parameter is a reference and would be implemented as a pointer all uses with different values for "num" can be directed to one instan...
As far as you (the programmer) are concerned, print<2>() and print<3>() are separate functions. Whilst the compiler may theoretically be able to make this optimisation, it probably won't happen in pratice. The best way to find out for sure is to look at the generated assembler.
4,133,353
4,133,382
c++ function name not found if it overloads a c function name?
I was trying to override a C-style function (func) in a library with a C++ style function accepting different arguments, as the code below demonstrates. I compiled test.cpp into a shared library libtest.so, and compiled main.cpp and linked it with the libtest.so library. This all works, upto the linking step, where I g...
You've declared the function in test.h as int func(std::string), but defined it in test.cpp as int func(std::string &). See the difference?
4,133,385
4,133,486
Why is this calling the copy constructor so many times?
I have a class that resembles this: However, after the initial constructor, the copy constructor is being called 10 times. If I don't do the thread creation step. It gets called 4 times which is what I'd expect. Why is that, and how do I avoid it? Should I avoid using std::vector in this case and just do new delete in...
Take a look at Boost.Ref for (int i = 0; i < a.size(); i++){ threads_.create_thread(boost::bind(&A::Thread, boost::ref(a[i]) )); } this is from the Boost.Bind : The arguments that bind takes are copied and held internally by the returned function object. For example, in the following code: int i = 5; bind...
4,133,406
4,133,520
Does setting a bit collide with concurrent sets of other bits on the same word?
Say I have a bitmap, and several threads (running on several CPUs) are setting bits on it. No synchronization is used, and no atomic operations. Also, no resets are done. To my understanding, when two threads are trying to set two bits on the same word, only one operation would eventually stick. The reason is that for...
In short, it's very CPU and compiler dependent. Say you have a 32-bit value containing zero, and thread A wants to set bit 0 and thread B wants to set bit 1. As you describe, these are read-modify-write operations, and the synchronization issue is 'what happens if they collide'. The case you need to avoid is this: A: R...
4,133,422
4,133,504
Why the allocation succeeds for size zero bytes?
This is similar to What does zero-sized array allocation do/mean? I have following code int *p = new int[0]; delete []p; p gets an address and gets deleted properly. My question is: Why allocation of zero bytes is allowed by c++ Standard in the first place? Why doesn't it throw bad_alloc or some special exception ? I...
3.7.3.1/2: [32. The intent is to have operator new() implementable by calling malloc() or calloc(), so the rules are substantially the same. C++ differs from C in requiring a zero request to return a non-null pointer.] Compare dynamically allocated array to std::vector for example. You can have a vector of size 0, so w...
4,133,602
4,134,238
Disable Windows XP File Caching
Background: I have an application which plays video files from disc. When I play these files the first time the file reading sometimes lags. However, the second time it is played there is never any lag, I suspect this is because the file is put into the windows file cache the first time it is played. The requirements ...
In general, you can't just force FILE_FLAG_NO_BUFFERING. It requires aligned buffers, and typically these aren't provided. Besides, it's the wrong thing. You don't care whether Windows reads 32KB ahead. The only thing that you'd like Windows to do is discard file contents from cache after you've read them. The correct ...
4,133,692
4,133,790
Disallow taking pointer/reference to const to a temporary object in C++ (no C++0X)
I am faced with the following issue. Consider the following class: //Will be similar to bost::reference_wrapper template<class T> class Ref { public: explicit Ref(T& t) : m_ptr(&t) {} private: T* m_ptr; }; and this function returning a double double fun() {return 1.0;} If we now have double x = 1.0; const double ...
You might not like the syntax to use it, but make the constructor take a pointer instead of a reference. You can't take even a const pointer to a temporary. At least, not without smuggling it through another wrapper that hopefully makes the code Obviously Wrong(TM): template <typename T> T *reftoptr(T &t) { return &t; ...
4,133,696
4,135,750
Compilation error - Makefile logs
I'm executing command make -dwp all to compile a C++ S/W. On the logs I'm facing the following error message: EDIT: Preceding lines Finished prerequisites of target file `/export/home/bcmsa/nba/DLPRTER_CAA/bin/RPG3/default/DLPRAER.rpc'. Prerequisite `/export/home/bcmsa/nba/DLPRTER_CAA/bin/RPG3/default...
I executed the command make clean and then I tried again make -dwp and no errors messages so far. The problem was DLPRAER.rpc
4,133,866
4,133,970
Will std::queue front take front element out of the line?
Will std::queue::front take front element out of the line? And if not how to delete it?
There is a function for getting the element, another for deleting it: typedef queue<MyClass> MyQueue; MyQueue q; q.push(MyClass(42)); // ... MyClass const& rx = q.front(); rx.print(); MyClass x = q.front(); // Copies the front element to a fresh object q.pop(); // From this point, rx is a dangling reference assert(x =...
4,134,053
4,134,140
When boost thread is recycled temp variables created in it are erased from memory?
So I have a struct and a queue (modified, taken from here) in .h file of my class like: struct VideoSample { const unsigned char * buffer; int len; }; concurrent_queue<VideoSample * > VideoSamples; In .cpp file I have a function I run each time in a new thread, sending into some arguments: void V...
No. The OS will not delete that dynamically allocated VideoSample. You'll have to do it when the thread ends. It's hard to tell the lifetime of your objects from your post. If your VideoSamples is a member of the VideoEncoder class, and your VideoEncoder class is destroyed when the thread ends you could do it in the...
4,134,195
4,134,355
How do I call the original "operator new" if I have overloaded it?
Suppose I need to overload global ::operator new() for storing extra data with each allocated object. So basically it would work this way: for each call to global ::operator new() it will take the object size passed and add the size of extra data it will allocate a memory block of size deduced at previous step it will...
You can't access them because it isn't really overloading, it's replacement. When you define your own ::operator new, the old one goes away. That's pretty much that. Essentially, you need to call malloc from a custom ::operator new. Not only that, but also follow the directions in 18.4.1.1/4 to properly handle errors: ...
4,134,323
4,134,343
C++ how to delete a structure?
Structure I created: struct VideoSample { const unsigned char * buffer; int len; }; VideoSample * newVideoSample = new VideoSample; newVideoSample->buffer = buf; newVideoSample->len = size; //... How now to delete it now?
delete newVideSample; This won't free any memory you allocated to newVideoSample->buffer though - you have to free it explicitly before deleting. //Free newVideSample->buffer if it was allocated using malloc free((void*)(newVideSample->buffer)); //if it was created with new, use `delete` to free it delete newVideSamp...
4,134,392
4,134,448
Why is a function not defined in the .o file for this C++ class?
I have a C++ class that I'm using, and there's a function in it that's not showing up when I look at the .o file with `nm --demangle', and the function is missing when the program tries to run, even though everything builds fine. The header looks like: #ifndef __COLLECTION_H #define __COLLECTION_H #include <vector> #...
The compiler needs to have access to the entire template definition (not just the signature) of addItem in order to generate code for each instantiation of the template, so you need to move its definition to your header i.e follow the inclusion model. Infact modern C++ compilers do not easily support the separate compi...
4,134,525
4,134,555
Input function & Symbol?
My friend showed me this code, he asked me what is the & sign in the input parameter? #include<iostream> using namespace std; void f(int & i, int j) { i++; j++; } int main() { int i=1, j=2; f(i, j); cout << ( i + j ); system ("pause"); return 0; } p.s What is the & sign?
i in f() is a reference parameter. Thank you!
4,134,562
4,134,773
Does Qt Linguist offer the ability to add new entries to the editable .ts file?
I didn't find a way to do this - only to edit the translations to the existing fields. If there is no way to achieve this - how should this be done (somehow automatically, because right now I was manually adding <message> <source>x</source> <translation>xx</translation> </message> blocks to my .ts file and I ...
No, that's not the correct way :) Use tr() in the code to mark strings for translation. For example label->setText( tr("Error") ); The you run lupdate for your project to extract them to a .ts. See here for more details. Or do you need to translate strings that are not in the source code?
4,134,563
4,134,623
Having a class static method with same name as another class
Here is the example : struct A { A(const int a ):b(a) { } int b; }; struct B { B() : a(5) { } static void A() { } A a; }; int main() { B::A(); } And the compiler error is : a9.cpp:19: error: ‘A’ does not name a type a9.cpp: In constructor ‘B::B()’: a9.cpp:24: error:...
This works: struct B { B() : a(5) { } static void A() { } ::A a; }; Since you've used A as a member name in B, that member's definition shadows the A type from the outer namespace. Using :: you can get to that namespace. This behavior is specified in the (draft) standard as: 3.3.7 (1) "A name can be hidd...
4,134,579
4,152,412
WMV media streams appear more pixelated on Windows 7 than on XP
Our streaming media player is an in house C++/DirectShow application and runs on XP and greater. One of our most widely used streaming codecs is WMV, as it's widely supported. We've noticed that output from WMV media streams looks different on Windows 7 clients than on Windows XP. Windows 7 output looks much more pixel...
From communication with Chris P, a Microsoft MVP: The VMR9 renderer on Windows 7 appears not to support the texture smoothing properties, as such all video looks like crap. The only viable solution that I've found is to use the EVR or a custom renderer It doesn't implement any of these features (but gives no error if ...
4,134,624
4,134,999
How should I integrate with and package this third-party library in a Win32 C++ app?
We have a (very large) existing codebase for a custom ActiveX control, and I'd like to integrate libkml into it for the sake of interacting with KML mapping data, rather than reinventing the wheel. The problem is, I'm a relatively new Windows developer, and coming from the Linux world, I'm really not sure what the righ...
Typing six file names, or using the declarative style with #pragma comment(lib, "foo.lib") is small potatoes compared to the work you'll have to do to turn this into a DLL or COM server. The distribution is heavily biased towards using this as a static link library. There are only spotty declarations available to turn...
4,134,691
4,135,128
cURL CONNECTTIMEOUT alert
i am doing this project in which a small part is to connect to a server and do some things and if it fails to connect to the server within a time, then give an error message.. i know the curl code looks something like this curl_easy_setopt(c,CURLOPT_CONNECTTIMEOUT,1L); and also that it has a MilliSecond option. What i ...
Have you tried this? char* pErrorBuffer = NULL; pErrorBuffer = (char*)malloc( 512 ); memset( pErrorBuffer, 0, 512 ); curl_easy_setopt( curlHandle, CURLOPT_ERRORBUFFER, pErrorBuffer ); curl_easy_setopt( curlHandle, CURLOPT_CONNECTTIMEOUT, 1 ); // 1 s connect timeout if( CURLE_OK != curl_easy_perform( curlHandle ) ) { ...
4,134,700
4,134,807
how to use std::wifstream for reading its content as a std::wstring
I am trying this: std::wstringstream wstrStream; std::wifstream wifStream(str.c_str()); wifStream >> wstrStream; but I got this compilation error: error C2664: 'std::basic_istream<_Elem,_Traits>::_Myt &std::basic_istream<_Elem,_Traits>::operator >> (std::basic_istream<_Elem,_Traits>::_Myt &(__cdecl *) (std::basic...
Operator >> isn't defined for two streams. If you want to read a whitespace-delimited string from the file, use std::wstring s; wifStream >> s; If you mean that you want to copy the entire file into the stringstream, use wstrStream << wifStream.rdbuf();
4,134,703
4,136,058
Understanding boost::disjoint_sets
I need to use boost::disjoint_sets, but the documentation is unclear to me. Can someone please explain what each template parameter means, and perhaps give a small example code for creating a disjoint_sets? As per the request, I am using disjoint_sets to implement Tarjan's off-line least common ancestors algorithm, i.e...
What I can understand from the documentation : Disjoint need to associate a rank and a parent (in the forest tree) to each element. Since you might want to work with any kind of data you may,for example, not always want to use a map for the parent: with integer an array is sufficient. You also need a rank foe each elem...
4,134,764
4,134,781
How to define several include path in Makefile
New to C++; Basic understanding of includes, libraries and the compile process. Did a few simple makefiles yet. My current project involves using an informix DB api and i need to include header files in more than one nonstandard dirs. How to write that ? Havent found anything on the net, probably because i did not use ...
You have to prepend every directory with -I: INC=-I/usr/informix/incl/c++ -I/opt/informix/incl/public
4,134,840
4,134,868
Automatically inserted Template arguments?
A few days I literally discovered a behaviour of C++, where template arguments are automatically inserted, as shown in this example (nonsensical, only used to show what I mean): #include <iostream> template<typename Type> void setVar(Type& subj, const Type& in) { subj = static_cast<Type>(in); } int main() { i...
What is this behaviour called? Template argument deduction. are there special rules when and why templates can be automatically inserted? You cannot say like templates are inserted. Rather the types of parameters are automatically deduced from the arguments. When and how? That's what TAD is all about. Check out sec...
4,134,896
4,134,969
Designing my program to avoid having to cast from base to derived class
Ok, I seem to be requiring forward casting from base to derived and I think it might be a design problem so I will explain what I’m doing and you can tell me what I need change. XML file defines a bunch of objects that are similar. They share the same base class. The main function is defined in the base class DoWork()...
There are two different approaches that you can take here. The first one is providing a virtual method that generates the XML corresponding to the element. The second approach is providing a visitor interface: basically you define a virtual method that accepts a visitor type. The visitor type will be called with the c...
4,134,992
4,135,830
How to get std::string from command line arguments in win32 application?
So now I have a int main (int argc, char *argv[]){} how to make it string based? will int main (int argc, std::string *argv[]) be enough?
If you want to create a string out of the input parameters passed, you can also add character pointers to create a string yourself #include <iostream> #include <string> using namespace std; int main(int argc, char* argv[]) { string passedValue; for(int i = 1; i < argc; i++) passedValue += argv[i]; // ... re...
4,135,109
4,142,425
converting HBITMAP to byte array
I'm working with some scanner api which returns a HANDLE to an image in BMP format(so it is said so in documentation). I'm trying to somehow get BITMAP from this handle, but for example this code doesn't work: HANDLE handle = getHandleFromScanner(); BITMAP bitmap; int u = GetObject(handle, sizeof(BITMAP), &bitmap); u ...
Thanks guys. The handle appeared to be the image itself, so the following code solved the problem: char* pImage = NULL; HANDLE hImage= getHandleFromScanner(); pImage = (char *)GlobalLock(hImage); // pImage now contains the bytes of the image If someone will ever need it, the Scanner is Olivetti PR2 plus scanner.
4,135,177
4,135,242
How to Free Resources when DLL is Unloaded or Process Terminates
When my MFC DLL is loaded a class is instantiated in dllmain. How do I free the resources allocated for this when the DLL is unloaded or its process completes? Will this be done automatically by the system? I am using Visual Studio 2008. Thanks.
in you dll main function just handle a case for the DLL_PROCESS_DETACH. BOOL WINAPI DllMain( HMODULE hDll, DWORD dwReason, PVOID pvReserved ) { switch ( dwReason ) { case DLL_PROCESS_DETACH: // the dll is being detached, do you clean up here break; } } Keep in mind that some things are not possible...