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
2,035,890
2,036,005
Unit Testing Concurrent Code
My weekend project consists of writing a cross-platform concurrency primitives library (critical sections, read/write mutexes, interlocked integers, events, etc) and was wondering how to unit test this stuff. I realize that testing concurrent code is hard in itself, but testing the primitives of said code couldn't be t...
Don't think about unit tests, think about the behaviour you want to specify. For example: Given_an_unlocked_lock It_should_be_possible_to_take_it Given_a_locked_lock It_should_not_be_possible_to_take_it_from_another_thread It_should_be_possible_take_it_from_the_same_thread Given_a_locked_lock_when_unlocked ...
2,036,104
2,036,121
Validity of the code
Consider the following code : void populate(int *arr) { for(int j=0;j<4;++j) arr[j]=0; } int main() { int array[2][2]; populate(&array[0][0]); } There was a discussion regarding this on a local community whether the code is valid or not(Am I supposed to mention its name?). One guy was saying that it i...
Your array is two arrays of int[2], while your function populate() treats it as a single array of int[4]. Depending on exactly how the compiler decides to align the elements of array, this may not be a valid assumption. Specifically, when j is 2 and you try to access arr[2], this is outside the bounds of main's array[0...
2,036,182
2,036,298
boost, shared ptr Vs weak ptr? Which to use when?
In my current project I am using boost::shared_ptr quite extensively. Recently my fellow team mates have also started using weak_ptr. I don't know which one to use and when. Apart from this, what should I do if I want to convert weak_ptr to shared_ptr. Does putting a lock on weak_ptr to create a shared_ptr affect my co...
In general and summary, Strong pointers guarantee their own validity. Use them, for example, when: You own the object being pointed at; you create it and destroy it You do not have defined behavior if the object doesn't exist You need to enforce that the object exists. Weak pointers guarantee knowing their own valid...
2,036,473
2,036,487
Know what references an object
I have an object which implements reference counting mechanism. If the number of references to it becomes zero, the object is deleted. I found that my object is never deleted, even when I am done with it. This is leading to memory overuse. All I have is the number of references to the object and I want to know the pl...
A huge part of getting reference counting (refcounting) done correctly in C++ is to use Resource Allocation Is Initialization so it's much harder to accidentally leak references. However, this doesn't solve everything with refcounts. That said, you can implement a debug feature in your refcounting which tracks what is...
2,036,503
2,036,723
Java, C++, NIO, mmaped buffer, synchronization
Exposition: I am on Linux / Mac. Part of my code is in Java, part of my code is in C++. They both have the same file mmapped for fast communication. I want to synchronize the Java & C++ code. I know the following: 1) given two threads in Java, I can use Locks / monitors. 2) given one piece of code in Java, one in C++, ...
You could write a small C/C++ library that only purpose is to sync with your C++ code (using conventional IPC sync objects). Then you could would this library from your java process using JNI.
2,036,592
2,036,613
how to convert decimal to binary in c++
I have a method to convert dec to bin QList<bool> widgetInput::decToBin(int number) { int remainder; QList<bool> result; if(number <= 1) { result << number; return result; } remainder = number%2; decToBin(number >> 1); result << remainder...
On each recursive step, you are creating a new QList result; which is local to that step, then inserting the remainder into it. You don't need recursion (and in general it should be avoided when iteration will do): QList<bool> result; while(number > 0) { result << number%2; number /=2; } // Edited to add: Just re...
2,036,745
2,037,079
My threadspool just make 4~5threads. why?
I use QueueUserWorkItem() function to invoke threadpool. And I tried lots of work with it. (about 30000) but by the task manager my application only make 4~5 thread after I push the start button. I read the MSDN which said that the default number of thread limitation is about 500. why just a few of threads are made in ...
It is important to understand how the threadpool scheduler works. It was designed to fine-tune the number of running threads against the capabilities of your machine. Your machine probably can run only two threads at the same time, dual-core CPUs are the current standard. Maybe four. So when you dump a bunch of thre...
2,036,892
2,036,902
STL containers fails to add a structure defined inside a function
I have enanoutered a problem with a code similar to this void aFuncion() { struct entry { std::string field1; int field2; int field3; entry(const entry& ent) { // copy constructor code } entry() { // de...
The current C++ standard does not allow the template arguments to be locally defined types. This is remedied in the upcoming version of the standard. 14.3.1/2: A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type...
2,036,913
2,036,934
auto_ptr baffling behaviour
#include<iostream> #include<memory> #include<stdio> using namespace std; class YourClass { int y; public: YourClass(int x) { y= x; } }; class MyClass { auto_ptr<YourClass> p; public: MyClass() //:p(new YourClass(10)) { p= (auto_ptr<YourClass>)new YourClass(10); } MyClass( const My...
What's happening is due to the strange (but only justifiable if you think about it) semantics of assigning or copying an auto_ptr, e.g. auto_ptr<T> a; auto_ptr<T> b(new T()); a = b; ... or ... auto_ptr<T> b(new T()); auto_ptr<T> a(b); These will set a to b as expected, but they will also set b to NULL (see http://ww...
2,036,985
2,037,002
How can I develop a virtual drive
I would like to create a virtual drive for windows. I'm not looking to map a drive or something like that, I'm looking to map it to my DLL functions or something of that sort. How can I get this accomplished? I read that I would have to develop a device driver, or a shell extension? I have a lot of experience with C++ ...
If you want to build it from scratch then yes, you have to build a driver. However, it would be much easier for you to use a proxy driver like Dokan, and create the file system in user mode. Take a look at the Wikipedia article on IFS, there are links to other useful tools at the bottom of the page.
2,037,155
2,037,242
std::string as C++ byte array
Google's Protocol buffer uses the C++ standard string class std::string as variable size byte array (see here) similar to Python where the string class is also used as byte array (at least until Python 3.0). This approach seems to be good: It allows fast assignment via assign and fast direct access via data that is no...
std::strings may have a reference counted implementation which may or may not be a advantage/disadvantage to what you're writing -- always be careful about that. std::string may not be thread safe. The potential advantage of std::string is easy concatenation, however, this can also be easily achieved using STL. Also, ...
2,037,209
2,037,215
What is a null-terminated string?
How does it differ from std::string?
A null-terminated string is a contiguous sequence of characters, the last one of which has the binary bit pattern all zeros. I'm not sure what you mean by a "usual string", but if you mean std::string, then a std::string is not required (until C++11) to be contiguous, and is not required to have a terminator. Also, a s...
2,037,212
2,037,338
Concatenating/Merging/Joining two AVL trees
Assume that I have two AVL trees and that each element from the first tree is smaller then any element from the second tree. What is the most efficient way to concatenate them into one single AVL tree? I've searched everywhere but haven't found anything useful.
Assuming you may destroy the input trees: remove the rightmost element for the left tree, and use it to construct a new root node, whose left child is the left tree, and whose right child is the right tree: O(log n) determine and set that node's balance factor: O(log n). In (temporary) violation of the invariant, the ...
2,037,315
2,037,322
Creating a simple scripted 'language' - VARIANT-like value type
For a rules engine developed in C++, one of the core features is the value type. What I have so far is a bit like a COM-style VARIANT - each value knows its type. There are some rules for type conversion but it's a bit messy. I wondered if there are nice drop-in value classes I could use which solve this, without requi...
Looking for boost::any or boost::variant? There are basically three types of variant implementations: A type that can be freely casted between types (think untyped languages) -- boost::lexical_cast is your friend here, or boost::variant... A type that can hold any type, but is typesafe -- e.g. initialized with an int,...
2,037,589
2,037,623
C++ special instance of template function for some type which is a template class itself
I got trouble in creating special instance of member template function of non-template class. I have, for example, class A with template member function F: class A {public: template <class T> int F (T arg) const; .... } and want to have a special instance of this template function F for type B: class...
You're attempting to create a partial specialization for a function template, which is illegal. What you can do is simply create an overload. To create a friend, you merely have to use the correct syntax. The following compiles without errors. template <typename T> struct B {}; struct A { template <typename T> ...
2,037,765
2,037,995
What is the optimal multiplatform way of dealing with Unicode strings under C++?
I know that there are already several questions on StackOverflow about std::string versus std::wstring or similar but none of them proposed a full solution. In order to obtain a good answer I should define the requirements: multiplatform usage, must work on Windows, OS X and Linux minimal effort for conversion to/fro...
Same as Adam Rosenfield answer (+1), but I use UTFCPP instead.
2,037,826
2,037,848
I need some C++ guru's opinions on extending std::string
I've always wanted a bit more functionality in STL's string. Since subclassing STL types is a no no, mostly I've seen the recommended method of extension of these classes is just to write functions (not member functions) that take the type as the first argument. I've never been thrilled with this solution. For one, it'...
As most of us "gurus" seem to favour the use of free functions, probably contained in a namespace, I think it safe to say that your solution will not be popular. I'm afraid I can't see one single advantage it has, and the fact that the class contains a reference is an invitation to that becoming a dangling reference.
2,037,863
2,037,873
Waiting on WaitForMultipleObjects
I'm trying to write a unit test for my FileWatcher class. FileWatcher derives from a Thread class and uses WaitForMultipleObjects to wait on two handles in its thread procedure: The handle returned from FindFirstChangeNotification A handle for an Event that lets me cancel the above wait. So basically FileWatcher is w...
There's no race, you don't have to wait for the FileWatcher to enter WaitForMultipleObjects. If you perform the change before the function is called, it will simply return immediately. Edit: I can see the race now. Why don't you move the following line _changeEvent = ::FindFirstChangeNotificationW(/*...*/); from the t...
2,037,867
2,038,101
Can I convert a reverse iterator to a forward iterator?
I have a class called Action, which is essentially a wrapper around a deque of Move objects. Because I need to traverse the deque of Moves both forward and backwards, I have a forward iterator and a reverse_iterator as member variables of the class. The reason for this is becuase I need to know when I have gone one pa...
This is exactly the sort of problem that prompted the design of STL to start with. There are real reasons for:Not storing iterators along with containersUsing algorithms that accept arbitrary iteratorsHaving algorithms evaluate an entire range instead of a single item at a time I suspect what you're seeing right now is...
2,038,200
2,038,215
Write a program that will print "C" if compiled as an (ANSI) C program, and "C++" if compiled as a C++ program
Taken from http://www.ocf.berkeley.edu/~wwu/riddles/cs.shtml It looks very compiler specific to me. Don't know where to look for?
Simple enough. #include <stdio.h> int main(int argc, char ** argv) { #ifdef __cplusplus printf("C++\n"); #else printf("C\n"); #endif return 0; } Or is there a requirement to do this without the official standard?
2,038,247
2,038,319
Integration of Python console into a GUI C++ application
I'm going to add a python console widget (into a C++ GUI) below some other controls: Many classes are going to be exposed to the python code, including some access to GUI (maybe I'll consider PyQt). Should I run the Python code in a separate thread? I think it's a good approach, because GUI won't be frozen while exe...
Since you're apparently wanting to embed a Python interpreter to use Python as a scripting language in a what seems to be a Qt application, I suggest you have a look at PythonQt. With the PythonQt module, Python scripts will be able to interact with the GUI of your host application. Unlike PyQt and Qt Jambi, PythonQt ...
2,038,302
2,038,869
Is storing iterators inside this class unwise? How else to iterate through this sequence?
Warning this is a long question! I am implementing a Solitaire card game in C++ on Win32, and after asking this question, it's becoming clear that I may need a bit of guidance regarding actual class design rather than implementation details. I am using a model view Controller pattern to implement the game. The model is...
I would create a function template to animate an entire Action, not just one Move at a time. Invoke that with beginning and ending iterators for the Action that needs to be animated: template <class iterator> void animate_action(iterator first, iterator last) { for (iterator i=first; i!=last; ++i) animate_...
2,038,453
2,038,534
C++ Standard: Unexpected const_iterator in multiset
I recently ran into an odd issue where I'd get a const_iterator instead of the expected iterator when iterating through a multiset. It turned out to be a non-issue for MSVC but g++ gave me an error: error: invalid initialization of reference of type 'myPtr&' from expression of type 'const boost::shared_ptr' Rel...
The iterators for set and multiset were changed from the standard iterator/const iterator pair to just being const iterators. The reason for this change was that they are ordered containers, and changing the element inside of an iterator can actually invalidate this ordering constraint. The version of GCC you're testin...
2,038,640
2,038,651
In C and C++, why is each .h file usually surrounded with #ifndef #define #endif directives?
Why does each .h file starts with #ifndef #define #endif? We can certainly compile the program without those directives.
It's a so-called "include guard". The purpose is to prevent the file from having to be parsed multiple times if it is included multiple times.
2,038,705
2,038,710
C++ Unit Testing Libraries
I've come across cppunit but it didn't look super-easy to use (maybe I didn't look hard, maybe because C++ doesn't work like Java/C#). Are there widely used, simple alternatives? In fact, is cppunit the standard unit testing framework for C++?
There is no standard unit testing library for C++. There are many choices to choose from; cppunit being one of them. At my company we use Google Test along with its partner Google Mock for unit testing and object mocking. I find them both combined easier to use and much more powerful than cppunit.
2,038,717
2,038,793
C++ object size with virtual methods
I have some questions about the object size with virtual. 1) virtual function class A { public: int a; virtual void v(); } The size of class A is 8bytes....one integer(4 bytes) plus one virtual pointer(4 bytes) It's clear! class B: public A{ public: int b; virtual void w(); } ...
This is all implementation defined. I'm using VC10 Beta2. The key to help understanding this stuff (the implementation of virtual functions), you need to know about a secret switch in the Visual Studio compiler, /d1reportSingleClassLayoutXXX. I'll get to that in a second. The basic rule is the vtable needs to be locat...
2,038,871
2,038,934
Copy-protecting a static library
I will soon be shipping a paid-for static library, and I am wondering if it is possible to build in any form of copy protection to prevent developers copying the library. Ideally, I would like to prevent the library being linked into an executable at all, if (and only if!) the library has been illegitimately copied ont...
I agree with other answers that a fool-proof protection is simply impossible. However, as a gentle nudge... If your library is precompiled, you could discourage excessive illegitimate use by requiring custom license info in the API. Change a function like: jeastsy_lib::init() to: jeastsy_lib::init( "Licenced to Fooba...
2,038,881
2,038,977
GPL and libmysqlclient
I have an application, it uses the libmysqlclient.so I wonder if I need GPL license on this application due to libmysqlclient be GPL or if I can continue the program in closed source EDIT: According to this site, I can use the libmysqlclient in a closed-source software. Just do not understand why the GPL "infects" the ...
libmysqlclient, the JDBC connector, and other libraries to interfacing to MySQL are GPL (GPLv2). Strict reading of the license would show that you need to distribute your source code under the GPL. There is the FLOSS exemption, which allows any open source license to include libmysqlclient, however this does not apply ...
2,039,152
2,039,176
C++ functions exposed to scripting system - self-describing parameter types
A C++ rules engine defines rules in XML where each rule boils down to "if X, then Y" where X is a set of tests and Y a set of actions. In C++ code, 'functions' usable in tests/actions are created as a class for each 'function', each having a "run(args)" method... each takes its own set of parameters. This works fine. B...
There's a 3rd way - IDL. Imagine you have a client-server app, and you have a code generator that produces wrapper classes that you can deploy on client and server so the user can write an app using the client API and the processing occurs on the server... this is a typical RPC scenario and is used in DCE-RPC, ONC-RPC...
2,039,444
2,039,453
Why are drivers and firmwares almost always written in C or ASM and not C++?
I am just curious why drivers and firmwares almost always are written in C or Assembly, and not C++? I have heard that there is a technical reason for this. Does anyone know this? Lots of love, Louise
Because, most of the time, the operating system (or a "run-time library") provides the stdlib functionality required by C++. In C and ASM you can create bare executables, which contain no external dependencies. However, since windows does support the C++ stdlib, most Windows drivers are written in (a limited subset of)...
2,039,529
2,039,547
C++ Exception Design Pattern
I'd like to encapsulate Win32 errors (those returned from GetLastError()) in some form of exception class. Rather than having a single Win32 exception, however, I'd like to be able to have a specialized exception catchable for common errors, such as ERROR_ACCESS_DENIED. For example, I'd have classes declared like this:...
Change int DangerousMethod() { throw WindowsAPI::WindowsException::Create(GetLastError()); } To int DangerousMethod() { WindowsAPI::WindowsException::Throw(GetLastError()); } Meaning, instead of returning the exception then throwing it (which will slice, as you observed), have your helper/factory method throw...
2,039,661
2,039,723
Fread skipping characters reading into object
I'm trying to read in a bitmap starting with its header, but fread is skipping characters for me. I'm using this typedef in my header: #include <windows.h> // Used for other #include <cstdio> typedef struct tagBITMAPHEADER{ WORD wFileType; DWORD dwFileSize; WORD dwReserved; WO...
In my opinion it is highly unwise to be using a struct in this way. Yes, you can get what you want in this case with a compiler specific pragma. I would consider that an acceptable solution if you were writing a Windows device driver or something else that was already very specific to a particular platform. But this ...
2,039,918
2,040,012
std::getline does not work inside a for-loop
I'm trying to collect user's input in a string variable that accepts whitespaces for a specified amount of time. Since the usual cin >> str doesn't accept whitespaces, so I'd go with std::getline from <string> Here is my code: #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace ...
You can see why this is failing if you output what you stored in local (which is a poor variable name, by the way :P): #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int main() { int n; cin >> n; for(int i = 0; i < n; i++) { string local; ...
2,040,210
2,040,287
Is Foo* f = new Foo good C++ code
Reading through an old C++ Journal I had, I noticed something. One of the articles asserted that Foo *f = new Foo(); was nearly unacceptable professional C++ code by and large, and an automatic memory management solution was appropriate. Is this so? edit: rephrased: is direct memory management unacceptable for new C++ ...
This example is very Java like. In C++ we only use dynamic memory management if it is required. A better alternative is just to declare a local variable. { Foo f; // use f } // f goes out of scope and is immediately destroyed here. If you must use dynamic memory then use a smart pointer. // In C++14 { ...
2,040,348
2,040,501
Glass Effect - Artistic Effect
I wish to give an effect to images, where the resultant image would appear as if we are looking at it through a textured glass (not plain/smooth)... Please help me in writing an algo to generate such an effect. Here's an example of the type of effect I'm looking for The first image is the original image and the second ...
Begin by creating a noise map with dimensions (width + 1) x (height + 1)that will be used displace the original image. I suggest using some sort of perlin noise so that the displacement is not to random. Here's a good link on how to generate perlin noise. Once we have the noise we can do something like this: Image nois...
2,040,355
2,040,386
Is it good practice to initialize array in C/C++?
I recently encountered a case where I need to compare two files (golden and expected) for verification of test results and even though the data written to both the files were same, the files does not match. On further investigation, I found that there is a structure which contains some integers and a char array of 64 ...
It is good practice to initialise memory/variables before you use them - uninitialised variables are a big source of bugs that are often very hard to track down. Initialising all the data is a very good idea when writing it to a file format: It keeps the file contents cleaner so they are easier to work with, less prone...
2,040,425
2,106,201
PostgreSQL : SQL timestamp to Unix timestamp using libpq
I know I can convert SQL timestamp to unix timestamp, using the following way. SELECT extract(epoch FROM now()); Now, I have a stored procedure function, which will directly return a table row to the caller. One of the row field is "timestamp" type. In my application, I am using libpq. I wish to use libpq functions (o...
boost::posix_time::ptime t(boost::posix_time::time_from_string(ts)); boost::posix_time::ptime start(boost::gregorian::date(1970,1,1)); boost::posix_time::time_duration dur = t - start; time_t epoch = dur.total_seconds(); long timestamp = static_cast<long>(epoch);
2,040,615
2,040,656
Show dialog/frame fullscreen on a second screen sing QT/c++
I have an application with a secondary view that should be shown fullscreen on the other monitor (the one the main app is not on). Displaying the frame works quite well with frame.showFullScreen(); But, how can I tell it which screen it should be on? Is there a way to detect if a second screen is avauilable, as well?
You can retrieve screen information from QDesktopWidget. To move a window to a specific screen, you can do something like this: QRect screenres = QApplication::desktop()->screenGeometry(screenNumber); widget->move(QPoint(screenres.x(), screenres.y()));
2,040,776
2,040,810
QtWebkit as a desktop application GUI
I was wondering if anyone knows about good tutorials or articles describing methods of creating an HTML GUI for an application using QTWebKit for a windows desktop application. I am mainly concerned about communicating messages, events and information between lets say a DLL(written in C++ for example) and the GUI (QtWe...
This won't be easy: Web browsers are fortresses because of security concerns. So it's pretty hard to get from JS in a web page to something outside of the browser. Also, QtWebKit isn't a very open API. The biggest obstacle in your case is that it doesn't offer you access to the DOM, so you can only replace the whole HT...
2,041,078
2,043,000
Why does my code result in "cannot instantiate abstract class"?
This is the line where the error occurs: this->_tbfCmdHandler.reset(new Bar()); facade_impl.cpp(202): error C2259: 'FOO::Bar' : cannot instantiate abstract class due to following members: 'void Subscriber::update(T)' : is abstract with T=char & observer.h(66) : see declara...
You are inheriting from an abstract class, so you need to implement the void update( const char& ) function inside class Facade::Implementation. You did define an update function, but it is not related in any way to Subscriber. You have to put it inside your implementation.
2,041,241
2,041,290
Convert CString to std::wstring
How can I convert from CString to std::wstring?
To convert CString to std::wstring: CString hi("Hi"); std::wstring hi2(hi); And to go the other way, use c_str(): std::wstring hi(L"Hi"); CString hi2(hi.c_str());
2,041,329
2,041,838
Migration from MSXML to Xerces
I am planning to port my application from Windows to Linux, currently my application uses MSXML for XML parsing. I have decided to use Xerces XML parser to provide a cross platform solution. My code size is too big and I do not want to touch all the internal part of the code for this porting purpose as it might break s...
depends on what you mean with 'the internal part'; one pretty extensible way to do this would go in some steps (having tests for your application would be beneficial so you can spot when something goes wrong): create an interface for all XML operations you use provide an implementation of that interface that uses MSXM...
2,041,336
2,041,626
access declaration can only be applied to a base class member
i'm using the observer pattern. I've a class that implements the publisher class: class foo : public Publisher<const RecoveryState &>, public Publisher<char &>, therin in try to bind the attach function: using Publisher<const RecoveryState &>::attach; using Publisher<const char &>::attach; the RecoveryState wo...
There is a discrepancy "char&" vs. "const char&".
2,041,355
2,041,372
C++: Constructor accepting only a string literal
Is it possible to create a constructor (or function signature, for that matter) that only accepts a string literal, but not an e.g. char const *? Is it possible to have two overloads that can distinguish between string literals and char const *? C++ 0x would kind-of allow this with a custom suffix - but I'm looking for...
No, you just can't do this - string literals and const char* are interchangeable. One workaround could be to introduce a special class to hold pointers to string literals and make a constructor only accepting that. This way whenever you need to pass a literal you call a constructor of that class and pass the temporary ...
2,042,416
2,042,490
TI DSP: interfacing C++ and assembly
I posted this Q to TI's 28xx DSP forum but haven't heard a response and figured maybe someone here might know. I know how to write functions in assembly so that they are C-callable; if the C-callable name is foo() then the assembly function is named _foo(). What if I want to use C++ and optimize a class method in asse...
The this pointer gets passed as an additional argument to the function, using the standard calling convention on your platform. On all the platforms I'm familiar with it is passed as the first argument, but I don't do a lot of C++ coding, so I'm not sure if this is guaranteed by the standard. You can always disassemb...
2,042,512
2,042,533
How do I let a program D read a memory location within the memory allocated to a program A?
So I'd like to let read D read this memory location and do some work on it. Any thoughts? Is writing a debugger extension the only way - if so, any recommendations? I considered executing a memory dump to file (still don't know how, AFAIK I can only view memory in a window) and letting D work on the file, but is there...
It is possible to read memory of another process. You should use ReadProcessMemory function.
2,042,516
2,042,590
Using C++ Boost memory mapped files to create disk-back data structures
I have been looking into using Boost.Interprocess to create a disk-backed data structure. The examples on Boost Documentation (http://www.boost.org/doc/libs/1_41_0/doc/html/interprocess.html) are all for using shared memory even though they mention that memory mapped files can also be used. I am wondering whether anyon...
You might take look at stldb project that's being actively discussed on boost mail list. It tries to build an ACID database on top of boost::interprocess.
2,042,582
2,042,619
Best way to create a string containing multiple copies of another string
I want to create a function that will take a string and an integer as parameters and return a string that contains the string parameter repeated the given number of times. For example: std::string MakeDuplicate( const std::string& str, int x ) { ... } Calling MakeDuplicate( "abc", 3 ); would return "abcabcabc". I ...
I don't see a problem with looping, just make sure you do a reserve first: std::string MakeDuplicate( const std::string& str, int x ) { std::string newstr; newstr.reserve(str.length()*x); // prevents multiple reallocations // loop... return newstr; }
2,042,748
2,091,165
Bjam: ignore specific library
Using Visual Studio, it is possible to 'Ignore Specific Library' (Project Properties > Configuration Properties > Linker > Input > Ignore Specific Library). We found this useful in a project. Now we want to build that project using boost-build (bjam), but we need to reproduce that linker behaviour. Is there any ignore ...
You could set it at the command line bjam linkflags=/NODEFAULTLIB:xxx Or from within a jamfile <linkflags>/NODEFAULTLIB:xxx Or use Visual Studio's pragma comment feature in your code itself #pragma comment(linker, "/NODEFAULTLIB:xxx")
2,042,780
2,043,239
How to raise warning if return value is disregarded?
I'd like to see all the places in my code (C++) which disregard return value of a function. How can I do it - with gcc or static code analysis tool? Bad code example: int f(int z) { return z + (z*2) + z/3 + z*z + 23; } int main() { int i = 7; f(i); ///// <<----- here I disregard the return value return 1; ...
You want GCC's warn_unused_result attribute: #define WARN_UNUSED __attribute__((warn_unused_result)) int WARN_UNUSED f(int z) { return z + (z*2) + z/3 + z*z + 23; } int main() { int i = 7; f(i); ///// <<----- here i disregard the return value return 1; } Trying to compile this code produces: $ gcc test.c t...
2,043,104
2,043,372
How to use boost lambda to populate a vector of pointers with new objects
I've recently started using boost lambda and thought I'd try and use it in places where it will/should make things easier to read. I have some code similar to the following std::vector< X * > v; for ( int i = 0 ; i < 20 ; ++i ) v.push_back( new X() ); and later on, to delete it... std::for_each( v.begin(), v.end()...
Here's a code snippet that does what you want: #include <algorithm> #include <vector> #include <boost/lambda/lambda.hpp> #include <boost/lambda/construct.hpp> typedef int X; int main() { std::vector<X*> v; std::generate_n( std::back_inserter(v), 20, boost::lambda::new_ptr<X>() ); std::for_each( v.begin(), v.en...
2,043,381
2,043,561
Ok to provide constructor for behaviorless aggregates (bundle-o-data) in C++?
Please refer to rule #41 of C++ Coding Standards or Sutter's Gotw #70, which states that: Make data members private, except in behaviorless aggregates (C-style structs). I often would like to to add a simple constructor to these C-style structs, for the sake of convenience. For example: struct Position { Position...
We regularly define constructors for our aggregate types, with no adverse effects. In fact the only adverse effects I can think of are that in performance critical situations you cannot avoid default initialisation and that you can't use the type in unions. The alternatives are the curly brace style of initialisation P...
2,043,823
2,043,831
Why is a C++ bool var true by default?
bool "bar" is by default true, but it should be false, it can not be initiliazied in the constructor. is there a way to init it as false without making it static? Simplified version of the code: foo.h class Foo{ public: void Foo(); private: bool bar; } foo.c Foo::Foo() { if(bar) { doSomethink()...
In fact, by default it's not initialized at all. The value you see is simply some trash values in the memory that have been used for allocation. If you want to set a default value, you'll have to ask for it in the constructor : class Foo{ public: Foo() : bar() {} // default bool value == false // OR to be c...
2,043,837
2,043,981
Detaching a native socket from Boost.ASIO's socket class
Is it possible to detach a native socket from Boost.ASIO's socket class? If so, how can it be done? I can't seem to find anything obvious in the documentation. As a quick overview of what I'm trying to accomplish: I have a class that makes a connection and does some negotiation using Boost.ASIO, then passes back a nati...
Answering my own question. Windows has a WSADuplicateSocket function, which can be used to duplicate the native socket. The underlying socket will remain open until all descriptors for this socket are deallocated. http://msdn.microsoft.com/en-us/library/ms741565(VS.85).aspx
2,043,974
2,044,050
Do C++ compilers optimize pass by const reference POD parameters into pass by copy?
Consider the following: struct Point {double x; double y;}; double complexComputation(const& Point p1, const Point& p2) { // p1 and p2 used frequently in computations } Do compilers optimize the pass-by-reference into pass-by-copy to prevent frequent dereferencing? In other words convert complexComputation into t...
I can't speak for every compiler, but the general answer is no. It will not make that optimization. See GOTW#81 to read about how casting to const in C++ doesn't affect optimization as some might think.
2,044,124
2,045,870
What happens in C++ when an integer type is cast to a floating point type or vice-versa?
Do the underlying bits just get "reinterpreted" as a floating point value? Or is there a run-time conversion to produce the nearest floating point value? Is endianness a factor on any platforms (i.e., endianness of floats differs from ints)? How do different width types behave (e.g., int to float vs. int to double)?...
Do the underlying bits just get "reinterpreted" as a floating point value? No, the value is converted according to the rules in the standard. is there a run-time conversion to produce the nearest floating point value? Yes there's a run-time conversion. For floating point -> integer, the value is truncated, provided tha...
2,044,486
2,044,513
Allocating an array of Derived without new[]: Pointer to Base vtable is bad
Basically, I have a pure virtual class Base, and a concrete class Derived which inherits from Base. I then allocate a piece of memory and treat it as an array of Derived via a simple cast. Then, I populate the array using =. Finally, I loop through the array, trying to call the virtual method GetIndex that is declared ...
If you allocate memory without new you always need to call the constructor manually with placement new and the destructor with x->~Derived();
2,044,512
2,044,534
hexadecimal value in input string needs to be checked
I am basically trying to get a user to input a hexadecimal input via getline into a string as i will do other operations on this. (using c++ .net stuff won't work) i do not want to break this into chars per say and then go through each char in the string and see if its in range from [0-9] or [Aa-Ff]. Instead, I wante...
Checking each char is the only way it can be done, period. However, you may be interested in isxdigit(int character) which returns 0 if the character passed isn't a valid hexadecimal character (note that x is not included as a valid character). You can test if it's a hex string in a single line using algorithms, though...
2,044,734
2,044,753
Reading data from hard drive into a class
Every time i try to read a file form the hard drive and cast the data into a structure, i end up with problems of the data not casting properly. Is there a requirement with the reinterpret_cast() function that requires the number of bytes in a structure be a multiple of 4 bytes? If not, what am I doing wrong? If so, ho...
Most likely, float has an alignment of four bytes on your system. This means that, because you use it in your structure, the compiler will make sure the start of the structure when allocated using normal methods will always be a multiple of four bytes. Since the raw size of your structure is 4*12+2 = 50 bytes, it needs...
2,044,999
2,045,050
What is private MFC and why are they not accessible through the normal interface?
I am using MFC for gui development and I stumbled upon a function that could be useful for what I'm trying to do. The function is _AfxCompareClassName. However, it is included in the file "afximpl.h" which is located in the directory "VC/altmfc/src/mfc/afximpl.h". Normal mfc includes are in the directory "VC/atlmfc/inc...
The 'private' MFC files are the implementation details of MFC. Just as you wouldn't want or expect users of your classes to get at the private: data or methods, you shouldn't rely on the MFC implementation-level utility code. Note that almost any cool thing you can find in the MFC implementation details is available ...
2,045,314
2,045,452
Why can't I cause a seg fault?
OK for whatever reason I'm having trouble causing a seg fault. I want to produce one so that I can use gdb to see how to debug one. I have tried both examples from the Wikipedia article yet neither work. The first one: char *s = "Hello World!"; *s = 'H'; And the second example: int main(void) { main(); } EDIT: I...
It impossible to try and reliable do it dereferencing pointers. This is because how the application handles memory can vary from compiler to compiler also across the same compiler with different options (debug/release mode handled differently). What you can do is explicitly raise the segfault using a signal: #include <...
2,045,396
2,045,411
How to initialise a std::map once so that it can be used by all objects of a class?
I have an enum StackIndex defined as follows: typedef enum { DECK, HAND, CASCADE1, ... NO_SUCH_STACK } StackIndex; I have created a class called MoveSequence, which is a wrapper for a std::deque of a bunch of tuples of the form <StackIndex, StackIndex>. class MoveSequence { public: voi...
You can make a std::map a static member of the class. What you can't do is initiliaze it within the class definition. Note that this is what the error is telling you: error C2864: 'MoveSequence::m' : only static const integral data members can be *initialized* within a class So, you want to have this in the header:...
2,045,509
2,045,532
How to save settings in gdb?
Does anyone know how to save gdb settings (like "set print pretty on" or "set print elements 0", both from here)? I don't want to set my configuration every time that I will use gdb :/ I searched in google and SO, but I found nothing.
Add any commands you want to auto run in the .gdbinit file in your home directory.
2,045,541
2,076,957
Discrete Wavelet Transform integer Daub 5/3 lifting issue
I'm trying to run an integer-to-integer lifting 5/3 on an image of lena. I've been following the paper "A low-power Low-memory system for wavelet-based image compression" by Walker, Nguyen, and Chen (Link active as of 7 Oct 2015). I'm running into issues though. The image just doesn't seem to come out quite right. I...
OK I can losslessly forward then inverse as long as I store my post forward transform data in a short. Obviously this takes up a little more space than I was hoping for but this does allow me a good starting point for going into the various compression algorithms. You can also, nicely, compress 2 4 component pixels a...
2,045,678
2,045,712
issues concerning a byte array to a long long(64 bit) array vs a long (32 bit)
I have a byte array that has hex values and I initially put those values in a unsigned long. I am using a 32 bit processor via Ubuntu at the moment. But, i might have to port this program to a 64 bit processor. now I am aware of strtoul function but since I was able to convert it would any issues via a direct assignme...
Instead of using long or long long you should use a typedef like uint32_t, or something similar, so it can be 32-bits on all platforms, unless this isn't what you want? It seems you do have a potential problem with endianness though, if you are simply doing: char bytes[4] = {0x12, 0x23, 0xff, 0xed}; long* p_long = rein...
2,045,735
2,045,768
Memoization in static Objective-C class
Say I have a class method like + (double)function:(id)param1 :(id)param2 { // I want to memoize this like... static NSMutableDictionary* cache = nil; // // test if (param1,param2) is in cache and return cached value, etc. etc // } Thanks!!
If you want to create the cache once and check against it, I generally use an +initialize method. This method is called before the first message sent to the class, so the cache would be created before +function:: (which, by the way, is a terrible selector name) could be called. In this case, I usually declare the cache...
2,045,774
2,045,860
Developing C wrapper API for Object-Oriented C++ code
I'm looking to develop a set of C APIs that will wrap around our existing C++ APIs to access our core logic (written in object-oriented C++). This will essentially be a glue API that allows our C++ logic to be usable by other languages. What are some good tutorials, books, or best-practices that introduce the concepts ...
This is not too hard to do by hand, but will depend on the size of your interface. The cases where I've done it were to enable use of our C++ library from within pure C code, and thus SWIG was not much help. (Well maybe SWIG can be used to do this, but I'm no SWIG guru and it seemed non-trivial) All we ended up doing w...
2,045,993
2,046,010
Abstract classes issue in C++ undo/redo implementation
I have defined an "Action" pure abstract class like this: class Action { public: virtual void execute () = 0; virtual void revert () = 0; virtual ~Action () = 0; }; And represented each command the user can execute with a class. For actual undo/redo I would like to do something like this: Undo Action a = ...
You should store actions as pointers, that will keep the compiler happy. std::vector<Action*> historyStack; /*...*/ historyStack.push_back(new EditAction(/*...*/)); Action* a = historyStack.pop(); a->revert(); undoneStack.push(a); There is another reason why std::vector<Action> historyStack; will not work and that's s...
2,046,331
2,046,509
Declaring pointer to base and derived classes
I just found that I am confused about one basic question in C++ class Base { }; class Derived : public Base { } Base *ptr = new Derived(); What does it mean? ptr is pointing to a Base class or Derived class? At this line, how many memory is allocated for ptr? based on the size of Derived or Base? What's the diffe...
To understand the type system of C++, its important to understand the difference between static types and dynamic types. In your example, you defined the types Base and Derived and the variable ptr which has a static type of Base *. Now when you call new Derived(), you get back a pointer with a static and dynamic type...
2,046,432
2,090,530
Using ZODB directly from C++. Examples and design hints
I'd like to use ZODB directly from C++ and don't want to write Python code for that. Have you had any experience doing so? If I were to use C++ for GUI and quering/writing data from/to ZODB, how the design should be?
seems like you have 2 choices a) work out how to call ZODB python module from c++ google shows boost has a library, and I am sure python.org will tell you too b) work out the file format and write the equivalent code in c++ Probably not impossible for reading, harder for writing. However you will eventually end up with...
2,046,515
2,046,550
from file object to file name
I wonder if we can get the file name including its path from the file object that we have created for the file name in C and in C++ respectively FILE *fp = fopen(filename, mode); // in C ofstream out(filename); // in C++ ifstream in(filename); // in C++ Thanks!
You can't, in general. The file may not ever have had a file name, as it may be standard input, output, or error, or a socket. The file may have also been deleted; on Unix at least, you can still read to or write from a file that has been deleted, as the process retains a reference to it so the underlying file itself i...
2,046,829
2,046,860
Write and read object of class into and from binary file
I try to write and read object of class into and from binary file in C++. I want to not write the data member individually but write the whole object at one time. For a simple example: class MyClass { public: int i; MyClass(int n) : i(n) {} MyClass() {} void read(ifstream *in) { in->re...
The data is being buffered so it hasn't actually reached the file when you go to read it. Since you using two different objects to reference the in/out file, the OS has not clue how they are related. You need to either flush the file: mm.write(&out); out.flush() or close the file (which does an implicit flush): mm.wr...
2,046,903
2,049,826
How might one create an extra worker thread for a single threaded GUI application?
I am currently developing new features for an existing VCL application. The application creates charts and static images using a thirdparty package called TeeChart. There is one instance where I have to load in 2 million data points to create a static image chart. However, this takes a while to load and the user can't ...
Since you are using the VCL, it might be a good idea to look at the TThread class. Create an inherited class from this, and use the Synchronize method when communicating with your main thread. You can try looking at: http://docwiki.embarcadero.com/VCL/en/Classes.TThread and http://docwiki.embarcadero.com/RADStudio/en/D...
2,046,952
2,046,986
Limit the confusion caused by undefined-behavior?
As I understand from my reading, undefined-behavior is the result of leaving the compiler with several non-identical alternatives at compile time. However, wouldn't that mean that if one were to follow strict coding practice (like putting each assignment and each equality in a separate statement, proper debugging and ...
Undefined behavior isn't necessarily leaving the compiler with multiple alternatives. Most commonly it is simply doing something that doesn't make sense. For example, take this code: int arr[2]; arr[200] = 42; this is undefined behavior. It's not that the compiler was given multiple alternatives to choose from. it's j...
2,047,030
2,047,125
Hackable scheme implementation with decent C++ FFI
I have tried: scheme48, chicken, gambit, clojure. I am looking for a scheme implementation that's readable (the implementation itself), and has a decent C++ ffi, and good debugging suport (so when I get an exception, I should get popped into a recursive repl). What suggestions do people have?
MzScheme. It can be embedded in C/C++ programs. It can be extended with C libraries, with no special interfacing code. Checkout "Inside PLT MZScheme" for detailed documentation.
2,047,072
2,048,346
Boost library for RTTI
which boost library should I use to implement RTTI in my project?? Is it Statechart library?
RTTI is built into the C++ language. However, you'll find a few RTTI-related, convenient tools in Boost, e.g. Boost.TypeTraits which enables you to checks such as is_base_of(), has_trivial_constructor() and loads of other stuff. Boost.FunctionTypes might also be worth checking out.
2,047,220
2,047,273
What is/are the Python equivalent(s) to the Java Collections Framework?
The Java Collections Framework is like the C++ Standard Template Library: "a unified architecture for representing and manipulating collections (objects that group multiple elements into a single unit)." http://java.sun.com/docs/books/tutorial/collections/intro/index.html
Other than the built-ins you might what to check out collections. >>> import collections >>> dir(collections) ['Callable', 'Container', 'Hashable', 'ItemsView', 'Iterable', 'Iterator', 'KeysView', 'Mapping', 'MappingView', 'MutableMapping', 'MutableSequence', 'MutableSet', 'Sequence', 'Set', 'Sized', 'ValuesView', '__a...
2,047,414
2,048,377
Advantages of std::for_each over for loop
Are there any advantages of std::for_each over for loop? To me, std::for_each only seems to hinder the readability of code. Why do then some coding standards recommend its use?
The nice thing with C++11 (previously called C++0x), is that this tiresome debate will be settled. I mean, no one in their right mind, who wants to iterate over a whole collection, will still use this for(auto it = collection.begin(); it != collection.end() ; ++it) { foo(*it); } Or this for_each(collection.begin(),...
2,047,563
2,047,599
Dependency on Derived class constructor problem
I am working on a legacy framework. Lets say 'A' is the base-class and 'B' is the derived class. Both the classes do some critical framework initialization. FWIW, it uses ACE library heavily. I have a situation wherein; an instance of 'B' is created. But the ctor of 'A' depends on some initialization that can only be ...
Probably the best thing you can do is refactoring. It does not make sense to have a base class depend on one of its derived types. I have seen this done before, providing quite some pain to the developers: extend the ACE_Task class to provide a periodic thread that could be extended with concrete functionality and acti...
2,047,987
2,051,279
How do I write shell extension context menu in C++ Builder 2010?
I'm looking for some examples for writing a shell extension in C++ Builder 2010 (2007 and 2009 would also probably be relevant) so I can right click a file in Explorer and get the file path in my VCL program. I have followed Clayton Todd's tutorial, but it's from 2001, and I have some trouble getting it to work. I can'...
For many years Delphi and C++ Builder have included a sample project (in ActiveX\ShellExt) that adds a "compile" item to project files' context menus. You should start with that. Also read the MSDN discussion on how to create a context menu handler. Overall, I recommend not using much of the VCL in your shell extension...
2,048,155
2,048,236
Java & memory management
I'm new to java world from C++ background. I'd like to port some C++ code to Java. The code uses Sparse vectors: struct Feature{ int index; double value; }; typedef std::vector<Feature> featvec_t; As I understood, if one makes an object, there will be some overhead on memory usage. So naive implementation of Feature...
If memory is really your bottleneck, try storing your data in two separate arrays: int[] index and double[] value. But in most cases with such big structures performance (time) will be the main issue. Depending on operations mostly performed on your data (insert, delete, get, etc.) you need to choose appropriate data ...
2,048,440
2,048,471
Giving up control: machine code generation vs memory layout?
This may be a bit off topic of "right answer, not discussion." However, I am trying to debug my thought process, so maybe someone can help me: I use compilers all the time, and the fact that I'm giving up control over machine code generation (the layout of my caches, and the flow of electrons) does not bother me. Howev...
Your feeling is, naturally, very subjective. You might feel comfortable managing your own memory space in C++. Others might appreciate the easiness of Java managing the heap for you, and reducing memory management overhead to a minimum. Programming domain has an influence as well. For example, in an embedded environmen...
2,048,561
2,048,633
adding win32 app icon to task bar
I want to add some simple win32 application's icon to task bar while app is running in background. During this time, i want to send some msgs to that icon so that it pops up as per my req. Unfortunately i know only c\c++ and i use visual studio8, is there a way or api to do this? example: outlook icon or wifi icon
Sure there is an api, Shell_NotifyIcon function does that. You have to fill a NOTIFYICONDATA Structure and then call the above function. What Shell_NotifyIcon will do depends on the flag that you'll set.
2,048,577
2,262,178
Displaying a cvMatrix containing complex numbers (CV_64FC2)
I'm new to OpenCV, and I would like to compare the results of a python program with my calculations in OpenCV. My matrix contains complex numbers since its the result of a cvDFT. Python handles complex numbers well and displays it with scientific notation. My C++ program is not effective when trying to use std::cout. I...
There is a dft example in OpenCV 2.0 code, which I am also studying right now. Here is a copy paste for you that might give you an idea. As you can see, it uses cvSplit to spilit to real and imaginary components. Hope that helps: im = cvLoadImage( filename, CV_LOAD_IMAGE_GRAYSCALE ); if( !im ) return -1; realInput...
2,048,664
2,048,688
Passing by reference [C++], [Qt]
I wrote something like this: class Storage { public: Storage(); QString key() const; int value() const; void add_item(QString&,int); private: QMap<QString,int>* my_map_; }; void Storage::add_item(QString& key,int value)//------HERE IS THE SLOT FOR ADDING { *my_map_[key] = value; } and when I'm ...
add_item should take a "const QString&" rather than a "QString&" as parameter.
2,048,967
2,049,011
Why does std::for_each(from, to, function) return function?
I just read the code for std::for_each: template<class InputIterator, class Function> Function for_each(InputIterator first, InputIterator last, Function f) { for ( ; first!=last; ++first ) f(*first); return f; } and could not see any good reasons for this template function to return the input function. Does anyon...
It's to allow you to accrue state in your function and then return it to your calling code. For instance, your function (as a functor class) could have a member int for counting the number of times it had been called. Here is a page with some examples : https://web.archive.org/web/20171127171924/http://xenon.arcticus.c...
2,049,190
2,049,264
Debugging a big double array
I am using a C++ library that provides an object that, for the sake of simplicity, is more or less like this: class ExampleSO { public double* narray; }; I have an instance of ExampleSO whose narray is about 200. Some other method ExampleSO::method() does a lot of arithmetic functions with this array and assigns i...
Rewrite it. The structure you describe is horrible beyond description. Write a python script to turn the #defines into gdb variable aliases, so that you can refer to them symbolically. Use array syntax in gdb: p narray[12] Add some debugging helper functions and call them from the debugger: p printMyFavoriteValues(nar...
2,049,238
2,049,292
Inherited class "invalid pointer error" when calling virtual functions
As you can see in the code below, I have an Abstract Base Class "HostWindow", and class that derives from it "Chrome". All the functions are implemented in Chrome. The issue is, I can't call functions in Chrome if they're virtual. class HostWindow : public Noncopyable { public: virtual ~HostWindow() { } // Pur...
Yes, the 'this' pointer is zero. Add 8 to get an offset, and there's your fault. You apparently don't have any actual object at all. Since you haven't posted enough code to really come to grips, I'm guessing. Either the entire this pointer is 0, or the virtual function table pointer is 0, perhaps because the object has...
2,049,291
4,490,785
Force deletion of slot in boost::signals2
I have found that boost::signals2 uses sort of a lazy deletion of connected slots, which makes it difficult to use connections as something that manages lifetimes of objects. I am looking for a way to force slots to be deleted directly when disconnected. Any ideas on how to work around the problem by designing my code ...
I ended up doing my own (subset) implementation of a signal, the main requirement being that a slot should be destroyed by a call to connection::disconnect(). The implementation goes along the lines of the signal storing all slots in a map from slot implementation pointer to a shared_ptr for a slot implementation inste...
2,049,793
5,514,417
MPI , Sungrid vs JPPF?
I have a little experience with SungridEngine and MPI (using OpenMPI). Whats the different between these frameworks/API and JPPF?
All three of these are somehow related to parallel computing, but on pretty different levels. The Sun Grid Engine (SGE) is a queueing system. It is usually set up by the system administrator of a big computing site, and allows users to submit long-running computing "jobs". SGE checks whether any computing nodes are un...
2,049,944
2,050,086
boost memorybuffer and char array
I'm currently unpacking one of blizzard's .mpq file for reading. For accessing the unpacked char buffer, I'm using a boost::interprocess::stream::memorybuffer. Because .mpq files have a chunked structure always beginning with a version header (usually 12 bytes, see http://wiki.devklog.net/index.php?title=The_MoPaQ_Arch...
How are you determining that your char* array is being 'truncated' as you call it? If you're printing it or viewing it in a debugger it will look truncated because it will be treated like a string, which is terminated by \0. The data in 'buffer' however (assuming libmpq_file_getdata() does what it's supposed to do) wil...
2,049,952
2,049,993
How to get Boost libraries binaries that work with Visual Studio?
Here's a question you may have seen around the 'nets in various forms...summed up here for you googling pleasure :-) I have a project that is built with Microsoft's Visual Studio and uses functionality from boost (http://www.boost.org/). I already have my project working with some of the libraries that are header only...
There are three different options for accessing the binary libraries: 1) Build them from source. Go into the boost directory and run: bootstrap .\bjam Or get more complicate and do something like: bjam --stagedir="c:\Program Files\Boost" --build-type=complete --toolset=msvc-9.0 --with-regex --with-date_tim...
2,050,369
2,314,650
Display image in second thread, OpenCV?
I have a loop to take in images from a high speed framegrabbger at 250fps. /** Loop processes 250 video frames per second **/ while(1){ AcquireFrame(); DoProcessing(); TakeAction(); } At the same time, I would like the user to be able to monitor what is going on. The user only needs to see images at around 30 ...
Ok. So embarrassingly my question is also its own answer. Using CreateThread(), CvShowImage() and CvWaitKey() as described in my question actually works-- contrary to some postings on the web which suggest otherwise. In any event, I implemented something like this: /** Global Variables **/ bool DispThreadHasFinished...
2,050,404
2,050,427
How to sprintf an unsigned char?
This doesn't work: unsigned char foo; foo = 0x123; sprintf("the unsigned value is:%c",foo); I get this error: cannot convert parameter 2 from 'unsigned char' to 'char'
Use printf() formta string's %u: printf("%u", 'c');
2,050,460
2,050,486
C++ retrieve exception information
I have a c++ dll which I need to debug. Due to the circumstances in which I am using the dll, I am unable to debug it via the calling application. So, I created a try -catch, where the catch writes the exception to a file. The line which needs to be debugged involves imported classes from a 3rd party dll, so I have no ...
If you don't use catch(KnownExceptionType ex) and use your knwoledge about KnownExceptionType to extract info, no you can't. When you catch with catch(...) you are pretty much lost, you know that you handled an exception but there is no type information there, there is little you can do. You are in the worse case, an e...
2,050,462
2,054,884
Prevent a QMenu from closing when one of its QAction is triggered
I'm using a QMenu as context menu. This menu is filled with QActions. One of these QActions is checkable, and I'd like to be able to check/uncheck it without closing the context menu (and having to re-open it again to choose the option that I want). I've tried disconnecting the signals emitted by the checkable QAction ...
Use a QWidgetAction and QCheckBox for a "checkable action" which doesn't cause the menu to close. QCheckBox *checkBox = new QCheckBox(menu); QWidgetAction *checkableAction = new QWidgetAction(menu); checkableAction->setDefaultWidget(checkBox); menu->addAction(checkableAction); In some styles, this won't appear exactly...
2,050,551
2,050,777
Qt 4.5.3 QEvent::EnterEditFocus
In Qt docs EnterEditFocus is a event about an editor widget gaining focus for editing but using Qt 4.5.3 the compilation fails with ‘EnterEditFocus’ is not a member of ‘QEvent’. What's wrong?
If Idan's suggestion doesn't work, note that QEvent::EnterEditFocus isn't defined unless you built Qt with QT_KEYPAD_NAVIGATION defined. Refer to the following documentation: http://doc.qt.io/archives/4.6/qapplication.html#keypadNavigationEnabled
2,050,766
2,051,695
How to run gdb against a daemon in the background?
I'm trying to debug a server I wrote with gdb as it segfaults under very specific and rare conditions. Is there any way I can make gdb run in the background (via quiet or batch mode?), follow children (as my server is a daemon and detaches from the main PID) and automatically dump the core and the backtrace (to a desi...
Why not just run the process interactively in a persistent screen session? Why must it be a daemon when debugging? Or just run gdb in the screen session and attach it to the running process (e.g. gdb /path/to/binary -p PID_of_binary) after it forks.
2,050,900
2,050,956
C++ templates: prevent instantiation of base template
I have an interface std::string get_string(Source const &s, std::string const &d); int get_int(Source const &s, int const &d); bool get_bool(Source const &s, bool const &d); which I'd like to change to template<class T> T get(Source const &s, T const &d); But there's no sensible base template, so the actual base defi...
Don't define the template, just declare it and define the three specializations. template <typename T> T get(Source const &, T const &); template<> std::string get(Source const &s, std::string const &d) { return d + s.stringval(); // or whatever } [Edit: removed stuff about overloads - just for once, template fun...
2,050,961
2,051,031
Is "argv[0] = name-of-executable" an accepted standard or just a common convention?
When passing argument to main() in a C or C++ application, will argv[0] always be the name of the executable? Or is this just a common convention and not guaranteed to be true 100% of the time?
Guesswork (even educated guesswork) is fun but you really need to go to the standards documents to be sure. For example, ISO C11 states (my emphasis): If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is n...