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,222,766
4,248,939
QT: simulated unit-testing
Is it possible to run an application and on top of that, you send keyPress events to the app and test the results using qtestlib? If yes, can somebody give me an example how to do it? If no, can somebody show me a better way accomplish the above requirement? Thanks...
Easy answer: No. There are tools to do this however. Ivo mentioned Squish, there's also "native" testing application called QtUiTest which can be found here: http://qt.gitorious.org/+qa-tools/qt-labs/qa-tools-qtuitest .. and TDriver here: http://gitorious.org/tdriver
4,222,869
4,222,903
How do I load and update a XML
I have tried with XML Lite which is pretty good with reading and writing a new xml , but when I try to add a new element to an existing XML , I am unable to figure out how to go about it. Is there any other way, I can do XML operation.
For simple XML work TinyXml is a good place to start.
4,223,095
4,244,615
QT unit-testing : qtestlib Segmentation fault
I'm writing a test app that would test if the displayed form is the correct form. This is after pressing a key on a menu. Here's a code block where I'm getting a segmentation fault. std::auto_ptr<MyForm> pForm(new MyForm(3,3)); QTest::keyPress(pForm.get(), Qt::Key_0); QWidget *pWin = QApplication::activeWindow();...
Frank was right. The window has not been acitivated synchronously. Adding a delay which is a parameter of keyPress did resolve the problem. Thanks Frank!
4,223,349
4,223,558
Python implementation for next_permutation in STL
next_permutation is a C++ function which gives the lexicographically next permutation of a string. Details about its implementation can be obtained from this really awesome post. http://wordaligned.org/articles/next-permutation Is anyone aware of a similar implementation in Python? Is there a direct python equivalent ...
itertools.permutations is close; the biggest difference is it treats all items as unique rather than comparing them. It also doesn't modify the sequence in-place. Implementing std::next_permutation in Python could be a good exercise for you (use indexing on a list rather than random access iterators). No. Python it...
4,223,470
4,224,513
C# not catching unhandled exceptions from unmanaged C++ dll
I've got an unmanaged C++ dll which is being called from a C# app, I'm trying to get the C# app to catch all exceptions so that in the event of the dll failing due to an unmanaged exception then the user will get a half-decent error message (the C# app is a web service implementing it's own http handler). The problem I...
Try catching using the ExternalException class: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.externalexception%28v=VS.100%29.aspx And, try compiling your unmanaged C++ DLL with asynchronous exception handling (/EHa). It looks like you're getting a Read Access Violation in your DLL which is a t...
4,223,603
4,223,855
Why is passing this kind of variable-size parameter by value impossible?
We have a structure like below: template<size_t size> class Container{ public: char characters[size]; }; And we have a function like below: template <size_t size> void function(Container<size> input,size_t Size){ //all instances do exactly same thing and with regard to Size that determines the size of object } No...
Generally, where you need an IN parameter, pass built-in types by value, and other types by reference to const, i.e., template< size_t size > void function( Container<size> const& input,size_t Size ) { //all instances do exactly same thing and with regard to Size that determines the size of object } With this definit...
4,223,617
4,223,652
standard conversions: Array-to-pointer conversion
This is the point from ISO :Standard Conversions:Array-to-pointer conversion: $4.2.1 An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to an rvalue of type “pointer to T.” The result is a pointer to the first element of the array. Can any one explain this, ...
In both C and C++, an array can be used as if it were a pointer to its first element. Effectively, given an array named x, you can replace most uses of &x[0] with just x. This is how subscripting is able to be used with array objects: int x[5]; x[2]; // this is the same as (&x[0])[2] This is also how an array can...
4,223,711
4,223,737
A more elegant way to use recv() and vector<unsigned char>
So far, I have this code sample: ... int nbytes =0; vector<unsigned char> buffer; buffer.resize(5000); nbytes = recv(socket, &buffer[0], buffer.size(),0); //since I want to use buffer.size() to know data length in buffer I do ... buffer.resize(nbytes); Is it some another way, to know data length in buffer without usin...
This technique is leak-safe, quite clean and preferable. Using std::vector is the recommended way of implementing a variable-length buffer in C++. If you find that not all data fits into the vector - no problem, just resize it to bigger size and pass the address of the section that follows the already-filled part. Usin...
4,223,766
4,224,478
Dropping video frames
my question is pretty simple, I think. And it's more about math than coding. I receive 15 frames per second from web-cam. But I have to drop some of these. For example, if client is requesting 8 fps - I do drop each second frame and it's ok. But how should I drop if 12 fps or 6 fps are requested? I think there's some ...
By dropping every 2nd frame for 8 fps, if you are having 15 fps, you are introducing an error. This is a very simple algorithm, that would work in all cases : #include <iostream> double t = 0.0; const double fps1 = 15.0; const double fps2 = 12.0; const double t1 = 1.0 / fps1; const double t2 = 1.0 / fps2; // true -...
4,223,797
4,228,957
What is your preferred pattern for using Qt Model-View Architecture?
how do you use MV in Qt? I've tried these two approaches: If there is an existing/legacy code "data"-classes, I use model as a facade. The Model-implementation class gets a reference to data, and calls its functions on model-item access calls. For new implementations I derive the data class from QAbstractModel. Is t...
The approach I ended up taking is similar to the one you suggest. I am currently using a facade to map between my legacy data model into the QAbstractModel. At first the facade was a bit too complicated, but slowly I am pulling functionality out of the facade model and pushing it into my data model. And then one da...
4,223,902
4,226,531
Rightclick Context Menu Position is getting Changed on right click of different objects
I have created a ShellExtension which add "Start N Application" to the windows right click menu. But the problem is that , the position of the context meny is not fixed. When I rightclick on a drive , it shows up in 3 rd position , or if I rightclick on a file then it starts in the 5th position. Can I make it to appear...
The position will not just vary depending on the "registration entry point" but is also affected by the number of installed extensions and the order they were installed in. The order can probably also change based on OS version and if shift is down etc. (XP added "Pin to Startmenu" and Vista added "Copy as Path") If yo...
4,224,027
4,224,099
Program stops after cin
Hi there I am writing this program but I can't get it to even start to see if the other code has problems. I have this: int main() { int answer; int test; cout << "Please Enter the number to be tested: "; cin >> test; //Gets number to be tested cout << "here"; answer = factor(test); ...
Maybe there is something wrong with the factor function? An infinite loop? Then cout << "here" << endl; (to flush the output) should at least print "here".
4,224,307
4,232,267
Stack Walking a debugged process
I'm opened opening a process (with C++/Windows) using if( CreateProcessA( NULL, // No module name (use command line) (LPSTR)path, //argv[1], // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inherita...
oops... I forget to call "ContinueDebugEvent" after receiving events from the debugged process - so it stayed paused and the StackWalk was infact correct. :)
4,224,326
4,224,393
why do we need to export a class in C++?
I am a beginner, so, please bear with me, if this sounds too trivial.When i searched over the net for this, i got results showing how to do it. My question is why we do it in the first place ?
This is specific to the Windows platform, when you're developping C++ DLLs. You have to use the __declspec(dllexport) modifier in order for your class and its methods to appear on the exported symbol list for your DLL. This way, executables using your DLL can instanciate and call methods in these classes. However you h...
4,224,490
4,224,593
Idea for resolving implicit includes in C, C++
I've just came up with an idea to solve a problem and wanted to share it. Sorry if too banal. So, a big C++ project I am reviewing, contains many includes which relies on symbols from other includes but which don't include the required includes. Any slight change in build-procedure results in "missing symbol" failures....
If every .cpp file includes it's own header-file first, and then other headers, you'll get this check without using external tools. This is actually part of Googles C++ Style Guide for the same reason: The preferred ordering reduces hidden dependencies. We want every header file to be compilable on its own. The ...
4,224,498
4,664,085
How to detect image loading in Internet Explorer (and don't display it)?
I'm writing a BHO add-on for Internet Explore (8 and 9). And I followed this tutorial explaining how to write add-on that hides all images on page. The problem is that these images are hid after the page is downloaded. So for a second there is the full page and then all images disappear. I have to make it that when an ...
You cannot do this properly with IE. The DWebBrowserEvents events are fired too late for you to modify the DOM before the images are downloaded. You'll see comments referring you to a Async Pluggable Protocol, a method of hooking into IE at a lower-level, but it's rather tricky and not recommended by Microsoft to do t...
4,224,577
4,224,626
Having one interface with lots of virtual methods? Or having many interfaces with only 1 virtual method?
I have a C++ module that needs to get information from other classes, without knowing those classes. The obvious approach is to use interfaces. Let me give you an example. Suppose I have a library that manages books, and all books have their own characteristics and functionalities, and to allow the library to get a c...
I'd have IBook to implement every method: class IBook { public: virtual ~IBook() {} virtual string getAuthor() { return ""; } // or some other meaningful default value virtual string getTitle() { return ""; } virtual string getISBNCode() { return ""; } virtual size_t getNofPages() {...
4,224,722
4,226,267
curl WRITEFUNCTION and classes
class Filter{ private: string contents; bool Server(void); public: void handle(void *, size_t, size_t, void *); }; i have a class header like this. i want to call curl WRITEFUNCTION inside the function Server which would use handle to write to the string contents. although it keeps giveng me the error ...
string temp; curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,handle); curl_easy_setopt(curl,CURLOPT_WRITEDATA,&temp); size_t Filter::handle(void *ptr, size_t size, size_t nmemb, string stream) { string temp(static_cast<const char*>(ptr), size * nmemb); stream = temp; return size*nmemb; } thats how i got it t...
4,224,758
4,224,819
Find never-called functions
I'm doing some refactoring in a project using Qt with Visual Studio 2008, and I'd like to know if there's a simple way to find the functions and methods that are never called?
You can try a static code analysis tool, like http://en.wikipedia.org/wiki/Cppcheck
4,224,807
4,226,014
c++. libxml2. < and > are replaced to &lt; and &gt; INSIDE tags
I'm writing a library that creates xml tree from given data. The problem is that the data contains tags inside nodes. for example <node> "this is a very <bold>huge</bold> text" </node> quotes - just to separate text given to me=) When I create an xml using libxml and then write it to console (using xmlDumpMEmeory) I ...
If you wish to embed special characters such as this in the element contents, they need to be wrapped as CDATA. A conformant XML implementation will always do what you noticed here. libxml should have some way to write element contents as CDATA that should fix this for you. This looks promising: Function: xmlTextW...
4,224,843
4,224,862
Confusion between "operator==" or "operator LPCTSTR"
I have this small piece of code: CString temp = _T("Temp"); if(_T("Temp") == temp) { .... } Now, here since there is a friend opeartor== function in CString class the operator== is getting invoked. But there is also a operator LPCTSTR defined for CString. So my question is why this operator is not used instead of ope...
Calling the overloaded operator== is an exact match, compared to operator LPCTSTR which requires a user defined conversion. An exact match is preferred over a user defined conversion. Yes, if operator== is not there, then the next best candidate (and of course viable) is operator LPCTSTR which will be called for compat...
4,224,878
4,849,883
Thread cancellation (pthread) & C++
I'm writing MT program for Linux in C++ and I want to know how thread cancellation is performed. As far as I understand when thread is cancelled cleanup functions are called inside thread's function and the thread's function is forced to exit. This mean two things: When thread is cancelled it still calls destructors ...
With any modern linux distribution using NPTL (which in practice means any running a 2.6 kernel), NPTL will call destructors and unwind the stack with a pseudo-exception. In fact NPTL insists on it, by implementing what it calls forced stack unwinding. You can catch the pseudo-exception with catch(...), but if you do ...
4,224,917
4,226,069
Qt - How to control the widget sizes in QLayout
I am trying to put some spinboxes,line edits in a layout. But the size extends more than the neccesity. Below is the figure Here I am adding a QScrollArea widget,and a QVBoxLayout into a QHBoxLayout. Then I am adding the line edits,spin boxes into the QVBoxLayout. But I want to reduce the width as 2/10 of the total wi...
It's easy. It can be done by giving the stretching factor. That means you have to initiate the value when you use the functions addWidget(widget,stretchfactor); or addLayout(layout,stretchfactor);
4,225,029
4,225,097
Is there an STL/boost algorithm to check all elements in a container match a value?
Is there an STL/boost algorithm that will test if all the elements between two iterators match a given value? Or alternatively that a predicate returns true for all of them? i.e. something like template<class InputIterator, class T> InputIterator all_match (InputIterator first, InputIterator last, const T& value) { ...
If you can negate the predicate you can use std::find / std::find_if and see if it returns the end element of your sequence. If not then it returns the one that does match. You can adapt an function with std::not1 or std::not_equal_to so by doing combined with std::find_if you can indeed do so using STL without writing...
4,225,087
4,225,109
C#-like properties in native C++?
In C# / .NET you can do something like this: someThing.text = "blah"; String blah = someThing.text; However, the above code does not actually interact with the someThing's text String directly, it uses a get and set property. Similarly, read-only properties can be used. Is there a way to do something similar in native...
In .NET properties are syntactic sugar for the real get and set functions which are emitted behind the scenes (in fact they are more than syntactic sugar because properties are emitted in the resulting IL and could be used with Reflection). So in C++ you would need to explicitly write those functions as there's no such...
4,225,202
4,225,228
String array, how do I use it? Implementation
So, I'm writing console game as my first project on C++ and what I want to do is to implement look function. Here is what it does: get current coordinate read description from 2d array of strings cout description But I can't make that 2d string array to work. string zoneid[100][100]; zoneid[1][1] = "text"; co...
OK here's the problem: int inventory_array[49]; int coordsX; int coordsY; std::string zoneid[100][100]; zoneid[1][1] = "Text"; This code is at file scope. That is, it's not in a function. But zoneid[1][1] = "Text" is executable code -- it needs to be in a function. You could put the initializer in main(): int main(...
4,225,484
4,226,589
c++ or java for robotics
I know embedded C is used for micro-controllers along with other languages. but what if the control was from a PC, well I had two possible candidates (java and c++) Java is simple and easy also Developer friendly when it comes to threading or GUI, but of course C++ is so much better performance (I know computers gettin...
Personally I would lean toward C++. Java has a garbage collector, which can put your app to sleep at random. In C++ I have to collect my own garbage, which gives me an incentive to generate less of it. Also C++ allows macros, which I know have been declared a bad thing by Java-nistas, but I use as a way of shortening t...
4,225,554
4,225,628
How to use GLEW with Qt?
I want to use GLEW with Qt under Windows (7 if that matters). What I did was go to the GLEW website, download the package for windows, then put the glew.dll in System32 folder. In my pro file, I referenced the .lib files with LIBS += .../path_to_the_libs/glew32.lib and the same for glew32s.lib (not sure what the latter...
You're not supposed to call glewInit() before you have your OpenGL context ready. Call it just before your first gl* calls, not at the beginning of main. That should do the trick. Also, don't use glew32.lib and glew32s.lib simultaneously - the former is to use along with the DLL file and the latter is static (your .exe...
4,225,706
4,237,701
CRTP fails w/ decltype
template<typename T> struct A { auto func() -> decltype(T::func()) { return T::func(); } }; class B : public A<B> { void func() { } }; Seems pretty simple to me. But MSVC fails to compile. visual studio 2010\projects\temp\temp\main.cpp(4): error C2039: 'func' : is not a member of 'B' visual stu...
You are trying to use T::func before it was declared. That's why the compiler shouts at you. Notice that when you derive from a class, the class is generated if it comes from a class template. And the implicit generation of the class (which is called implicit instantiation) necessiates the generation of declarations fo...
4,225,812
4,227,262
c++ mysql sqlstring crashes 0xC0000005 unable to read memory
I've been looking for this error in several places and the only thing I found is maybe is a wild pointer problem, but don't know how to solve. The question is c++ connector works fine (after hard working) connects to mysql database, retrieves information, but every time that uses string or sqlstring type it crashes, (s...
Change fld.assign(res->getString(fldName)); to fld = res->getString(fldName);
4,225,844
4,225,876
Mutual Inclusion of Header Files
Let's say I have a header file called inclusions.h that has all the #include <...>s for my project. inclusions.h includes another header file called settings.h, where various constants can be modified. If #include <math.h> in inclusions.h, will settings.h have access to the math library as well? Or do I have to #incl...
If math.h is included before settings.h, settings.h should also have access to math.h. But to ensure the access (and to indicate the dependencies), you should include the files where they are needed, so also in math.h.
4,226,163
4,226,211
return stack[--stp]; - Which happens first? Is stp decremented or is the element returned?
If I have code like: int pop() { return stack[--stp]; } I know that it is doing two things. It is returning the value contained in the one-dimensional array 'stack' in element 'stp'. It is also decrementing 'stp'. But which order does this happen in? Does it return the value of element stp, then decrement stp? O...
It will decrement stp, and then return the value from the array at the location of the new stp value. --stp is a "prefix decrement", and it is defined to decrement the argument (stp), and then return the new value. It has a counterpart called the "postfix decrement", stp--, which decrements stp and then returns the old...
4,226,308
22,755,542
MSVC equivalent of __attribute__ ((warn_unused_result))?
I'm finding __attribute__ ((warn_unused_result)) to be very useful as a means of encouraging developers not to ignore error codes returned by functions, but I need this to work with MSVC as well as gcc and gcc-compatible compilers such as ICC. Do the Microsoft Visual Studio C/C++ compilers have an equivalent mechanism ...
It's _Check_return_. See here for examples of similar annotations and here for function behaviour. It's supported since MSVC 2012. Example: _Check_return_ int my_return_must_be_checked() { return 42; }
4,226,343
4,226,358
ExitThread versus Allowing Thread Function to Exit Normally - C++
My application has a thread that is created using CreateThread. What is the difference between calling ExitThread from within said thread and allowing the thread to exit normally (i.e. reaching the end of the thread function)? I am using C++ and Visual Studio 2008. Thanks.
Actually, something very important: ..., in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed. Therefore, in C++ code, you should return from your thread function (Edit Source)
4,226,405
4,226,519
Console for input commands
I want to make some debug console for my application. It should output some data and take input commands. How can I do this? The best way is updating console like: drawing information and prompt for input after the data. I'm developing under Linux. For example, gdb could take input from console.
If you're familiar with socket programming (or actually, any other kind of IPC mechanism), you might want to enable some listener within your application, and develop an external application that will do all the "console" stuff for you, while communicating with the main application. Let's suppose you have an applicatio...
4,226,494
4,226,564
Proper Cleanup if Thread Fails to Close - C++
When my application is ready to close the tread it created using CreateThread the following algorithm is executed: _bCloseRequested = TRUE; dwMsThen = ::GetTickCount(); do { ::GetExitCodeThread( m_hThread, &dwExitCode ); dwMsNow = ::GetTickCount(); } while( (dwExitCode == STILL_ACTIVE) && ((dwMsNow - dwMsThen)...
First, don't wait for a thread to finish like this. You will eat up all available CPU time just waiting, which has also the disadvantage that your thread will take longer to finish! Use something like this instead: WaitForSingleObject(m_hThread, 50000); That said: whether you want to leave the thread running or not de...
4,226,548
4,226,582
Is there a plugin for Vim that would help me debugging like Visual Studio?
The reason why I'm asking this, is because I'm coding in C++, in putty/ssh and I like the fact that I can code from pretty much everywhere without having to install anything. So I'd like to have something that could help me debugging (viewing LIVE value of a variable, breakpoints, etc) If you think that there's no such...
I've used gdb for command line debugging in the past with success: http://www.gnu.org/software/gdb/ A decent tutorial can be found at: http://www.cs.cmu.edu/~gilpin/tutorial/
4,226,606
4,226,661
Inserting into a vector at the front
iterator insert ( iterator position, const T& x ); Is the function declaration of the insert operator of the std::Vector class. This function's return type is an iterator pointing to the inserted element. My question is, given this return type, what is the most efficient way (this is part of a larger program I am runn...
The efficiency of obtaining the insertion point won't matter in the least - it will be dwarfed by the inefficiency of constantly shuffling the existing data up every time you do an insertion. Use std::deque for this, that's what it was designed for.
4,226,829
4,226,856
C/C++ Char Pointer Crash
Let's say that a function which returns a fixed ‘random text’ string is written like char *Function1() { return “Some text”; } then the program could crash if it accidentally tried to alter the value doing Function1()[1]=’a’; What are the square brackets after the function call attempting to do that would make the p...
The string you're returning in the function is usually stored in a read-only part of your process. Attempting to modify it will cause an access violation. (EDIT: Strictly speaking, it is undefined behavior, and in some systems it will cause an access violation. Thanks, John). This is the case usually because the string...
4,227,328
4,227,337
FAQ: Why does dynamic_cast only work if a class has at least 1 virtual method?
This does not compile in C++: class A { }; class B : public A { }; ... A *a = new B(); B *b = dynamic_cast<B*>(a);
Because dynamic_cast can only downcast polymorphic types, so sayeth the Standard. You can make your class polymoprphic by adding a virtual destructor to the base class. In fact, you probably should anyway (See Footnote). Else if you try to delete a B object through an A pointer, you'll evoke Undefined Behavior. class...
4,227,468
4,227,495
static array in c# vs c/c++
this code is correct in C# int x = int.Parse(Console.ReadLine()); int[] t = new int[x]; but in c/c++ in wrong int n; scanf("%d",&n); int a[n]; how in c# static array allocate in runtime (or in c# array is dynamic?)
C# arrays are allocated at runtime on the heap. C arrays are allocated at compile-time on the stack. C can also allocate arrays at runtime using malloc. (Just remember to free them when you're done)
4,227,549
4,227,692
A nonblocking thread-safe memory-pool implementation
I needed a simple non-blocking static-block-size memory-pool. I didn't find such on the web. So everyone, who needs such a solution. This one is free... only works on Win32. Best regards, Friedrich #ifndef MEMPOOL_HPP_INCLUDED #define MEMPOOL_HPP_INCLUDED #include "atomic.hpp" #include "static_assert.hpp" #pragma war...
The problem with this approach is that there is a race condition in malloc: while(!CompareAndSwap((int*)&Root, (int)r, (int)r->Next)) Consider the following sequence of operations: Initially Root = A, A->next = B, ... One thread reads r = Root so r = A and (into a register) it reads ecx = r->Next = B Initial thread i...
4,227,659
4,227,686
Templated class method definition syntax
Class definition: template<class K, class V, unsigned hashFunc(const K&), int compFunc(const K&,const K&)=&_compFunc<K> > class X {}; I want to define a class method outside of the class code block. like so: template<class K, class V, unsigned hashFunc(const K&), int compFunc(cons...
You didn't declare or define a constructor for X. In addition, you had repeated the default template parameters in your attempted X::X definition. Here's the fixed code, main-ified: template<class K, class V, unsigned hashFunc(const K&), int compFunc(const K&,const K&)=&_compFunc<K> > class X { ...
4,227,763
6,830,354
HornetQ, consumer can't find queue
I'm trying to use ActiveMQ-CPP with HornetQ. I'm using the ActiveMQ-CPP bundled example, but I'm having a hard time with it. The producer works like a charm, but the consumer gives me the following message: * BEGIN SERVER-SIDE STACK TRACE Message: Queue /queue/exampleQueue does not exist Exception Class END SERVER-S...
Try to set the same Queue's address you defined on Hornetq as the destination. Probably your queue is defined on HornetQ like this <queue name="exampleQueue"> <address>jms.queue.exampleQueue</address> </queue> So, try to connect to this address via STOMP. See the following frames according to the protocol: Subs...
4,227,833
4,227,847
When should I use the keyword "typename" when using templates
I've been working lately on a small project, and I couldn't figure out something.. I've been given a .h file that was containing a class, using a typename template. Inside that class there was a private class. template <typename T> class Something { public: Something(); ~Something(); Node* Func...
template<typename T> typename Something<T>::Node * Something::Function1(int index) //Is the return type well written? { // returns the node at the specified index }
4,228,032
4,229,565
How to make a QTreeWidget that looks like the WidgetBoxTreeWidget from the designer?
I'd like a toolbox thing sort of like the widget tree in the designer. As far as I can tell, for the categories it simply adds a top level tree item to itself. Also afaict, it is a basic subclass of QTreeWidget, so I should be able to see what it's doing and make the same calls on a QTreeWidget to get the same behavio...
You'll want to look at Qt's View Delegates. These allow you to change how things are drawn in their item view classes.
4,228,043
4,228,571
MSVC Compiler Error C4315 - No Documentation Found
When compiling my app today, I encountered this warning (the code, I think, is irrelevant): warning C4315: 'MyClass' : 'this' pointer for member 'MyClass::my_data_' may not be aligned 8 as expected by the constructor I am not able to find any documentation about this warning, in either the online help, my locally-ins...
I'd look for something (buried in a header?) changing the structure packing from the default. The warning seems to be saying that whatever type MyClass::my_data_ is expects to be 8-byte aligned, but it's not being placed at that alignment inside MyClass. Search for #pragma pack(some-number) directives that aren't reset...
4,228,270
4,228,305
How to join 3 open cv IplImages into one?
So I have code like: IplImage* redchannel = cvCreateImage(cvGetSize(destination), 8, 1); IplImage* greenchannel = cvCreateImage(cvGetSize(destination), 8, 1); IplImage* bluechannel = cvCreateImage(cvGetSize(destination), 8, 1); cvSplit(source, bluechannel, greenchannel, redch...
void cvMerge(const CvArr* src0, const CvArr* src1, const CvArr* src2, const CvArr* src3, CvArr* dst); Here is the documentation. Edit: From the documentation: You will have to call: cvMerge(bluechannel, greenchannel, redchannel, NULL, target); Assuming that your target image also has only 3 channels.
4,228,336
4,228,363
Does a pointer to a virtual function still get invoked virtually?
Will a function pointer to a class member function which is declared virtual be valid? class A { public: virtual void function(int param){ ... }; } class B : public A { virtual void function(int param){ ... }; } //impl : B b; A* a = (A*)&b; typedef void (A::*FP)(int param); FP funcPtr = &A::function; (a->*(...
Yes. It also works with virtual inheritance.
4,228,436
4,228,535
Should I create .a or .so when packaging my code as a library?
I have a software library and I used to create .a files, so that people can install them and link against them: g++ foo.o -L/path/to -llibrary But now I often encounter third-party libraries where only .so files are available (instead of .a), and you just link against them without the -l switch, e.g. g++ foo.o /path/to...
Typically, libfoo.a is a static library, and libfoo.so is a shared library. You can use the same -L/-l linker options against either a static or shared. Or you can name the full path to the lib with static or shared. Often libraries are built both static and shared to provide application developers the choice of which ...
4,228,550
4,228,591
accumulator filling for Hough transform
I wrote a piece of code that needs to be optimized. Just felt like checking with community to see if that code is indeed optimal. It fills up the accumulator for the Hough transform. I actually just copy pasted most the code from the OpenCV library. Thanks! int i,j,n,index; for (i = 0;i<numrows;i++) { for (j = 0;j...
No it's not. Replace as many of the [] usages as you can by simple pointer arithmetic to iterate the arrays in question. Abstract out invariant expressions into local variables. However, the first question is, does your profiler show that this code is a bottleneck in the context of your entire app. If not, why bother...
4,229,080
4,229,544
Can't pass QMap through to SLOT
So, this works: .h public slots: void addMenu(QString passedName); signals: void clicked(const QString &text); .cpp signalMapper = new QSignalMapper(this); signalMapper->setMapping(button, QString("passed_value")); connect(button, SIGNAL(clicked()), signalMapper, SLOT(map())); connect(signalMapper, SIGNAL(mapped(QStr...
"Now, I am trying to pass a QMap < QString, QString > through to addMenu instead of just a QString, but I get the error: no matching function for call to 'QSignalMapper::setMapping'." That's not a general signal/slot or macro expansion problem, but a limitation of QSignalMapper. You can't pass a QMap to setMapping, onl...
4,229,156
4,230,153
How to combine two HICONs into one
I have one HICON which I want to use as an overlay on another HICON, to create a result HICON. The result HICON will then be used in an "owner draw" control (note: it doesn't use imagelists). The overlay icon has transparency color RGB(0, 255, 0). How do I go about doing this in Native C++ (I've only found sources th...
I generally agree with peterchen's answer, with some notes: There's no reason to work with DIBs (unless you're synthesizing the image directly by altering its bits, rather than drawing using GDI functions). You should keep in mind that GetIconInfo actually creates copies of the icon't bitmaps within your process. It's...
4,229,266
4,229,336
How do I compute the max of two size_t variables
I have this in my code. vector<unsigned int> import; vector<unsigned int> aquired; . . . size_t new_size = max(import.size(),aquired.size()); and I get this error: error: more than one instance of overloaded function "max" matches the argument list: function "max(int, int)" function "max(u...
#include <algorithm> size_t val1; size_t val2; size_t maxValue = std::max<size_t>(val1, val2);
4,229,343
4,230,006
OpenCV: how to fill rgb image having values for each of RGB colors for each pixel?
So having buffer with RGBRGBRGB... size of w*3 how to fill OpenCV Image with such data?
The easiest way is just to loop over the elements of the buffer using the at templated method. unsigned char buffer[] = {1, 2, 3, ..., 18}; // RGBRGB... cv::Mat image(2, 3); for (int i = 0; i < 18; ++i) { int row = i/9; int col = (i/3)%3; int rgb = i%3; // An index image.at<unsigned char>(row,col+rgb) = buffer...
4,229,489
4,229,813
Do C++ Standard Library types implement exception-safe copy-assignment?
I've recently come to appreciate the copy-and-swap idiom, and have been using it to implement copy-assignment for any class which manages a resource. So it got me thinking about Standard Library types: does the standard guarantee exception-safe behavior? For example, consider a class that contains one std::string data...
The standard specifies explicitely in 'verse' 21.4.1.2. that any other exceptions other than std::bad_length "shall have no effect".
4,229,521
4,229,763
C++: Using one type as another
I'm using the Chipmunk physics engine for my C++ project. Chipmunk has it's own vector, cpVect, which is nothing but a struct { double x, y; }; However I have my own operator overloaded Vector class in my project - and I'd like to use it just as a cpVect and vice-versa, without any conversions (my class Vector's only d...
So if I understand you, you have this: class Foo { double x, y; }; class Bar { double x, y; }; ...and you want pretened that a Foo is actually a Bar, right? You can't -- not without evoking Undefined Behavior. No matter what you try, you will fall in to the great UB black hole. if you try to use a union, you'll...
4,229,553
4,229,665
let user create their own instances of a class
I want to make it so a user of my Record creating program can create their own records. what is the best way to tackle this? can i use an array or vector for the variable name? int RecU[100]; class Record {...}; int main() { Record RecU[1]; } i tried it, and my program is crashing, so im not sure i...
If you want client code to be able to instantiate Record at will, all you have to do is ensure that at least one constructor is available to them (or a factory method). Normally this is the case. If you declare your class like this: class Record { }; ...then there's nothing to prevent client code from instantiating...
4,229,681
4,229,713
Creating Windows and Threading - C++
When a new window is created using CreateEx does its code execute in its own thread or that of its parent (i.e. the thread in which the its instantiating code was executed)? Thanks.
No, create window dont start new thread
4,229,748
4,235,272
Pattern for delegation to sub-component
In the product I am working, one of very basic scenario is serialization of classes. Typically a class to be serialized calls serialization on its sub-component e.g. if there is a class s.t. class A{B;C;D;} then A.Pack will call pack function on B,C,D. Since there are many such classes, same pattern of code has t...
The usual way of making a template do this is to use a type list: #include <iostream> // typelist definition struct Empty {}; template < typename H, typename T = Empty > struct Cons { typedef H head; typedef T tail; }; // interfaces all items support class IPack { public: virtual void Pack() = 0; }; // ...
4,229,849
4,230,892
Embed QT code into Visual Studio Project
This is a spin off from another question I have on here right now. Long story short is that I have Nokia's QT SDK downloaded (as well as the Visual Studio plug-in) and I was wondering what would be the best way to integrate some small QT functionality into a preexisting C++ Visual Studio project. I realize that this pr...
The QT Visual Studio add-in allows you to create a fresh QT-enabled Visual Studio project, but it doesn't provide functionality for converting a vanilla VS project to a QT enabled one. But you can do this manually by editing the vcproj file - I recently blogged about it here. Note that I wrote that for VS2008/Add-In 1...
4,229,949
4,229,972
How to catch boost asio boost::system::error_code connect exception separatly from other exceptions?
Boost asio has such socket connect api. I have such simple code: try { std::string addr; std::string port; sscanf(tcpUrl.c_str(), "tcp://%[^:]:%d", &addr, &port); boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(tcp::v4(), addr.c_str(), port.c_...
catch( const boost::system::system_error& ex ) { return -1; } Please catch by const reference.
4,229,969
4,230,186
C++ cin numbers ignores first line?
I've run into a really strange issue. I can reproduce on my win7 laptop as well as an ubuntu machine. I have a C++ program like so: #include <string> #include <sstream> #include <iostream> using namespace std; int main() { for (int i = 0; i < 9; i++) { string line; getline(cin, line); stringstream ss(lin...
It's a problem with the data (since the code looks OK). Most probably you've saved your text file with UTF-8 encoding with BOM. An UTF-8 BOM is three bytes at the start of the file, and trying to interpret those as a decimal number specification would fail. Second, third, fourth line etc. OK because you're creating new...
4,230,177
4,231,762
Unit Testing on Embedded C++ (ARM9)
I come from the world of Java and JUnit. I made a demonstration of Hudson and all what I achieve there with JUnit among other things. I would like to do the same with C++ code on an embedded device but can't find where to start. THe project is compiled with iccarm.exe (IAR compiler) Right now the output is converted in...
1) You could build a cross-compiler, and then instead of using iccarm.exe, use the cross compiler. There are lots of tutorials on the net how to build a cross compiler using gcc. Then instead of building for the target (using cross compiler) build for your host using normal compiler. 3) Whatever you like. cppunit, goog...
4,230,200
4,822,718
Redefine stdout in FastCGI and Octave
I'm working on implementing an Octave interpreter inside of an FastCGI session using C/C++ in Ubuntu Linux. The problem I'm running into is that FCGI redirects stdout to FCGI_stdout, but the precompiled Octave headers manage to still use the normal stdout which ends up in Apache's error.log instead of printed to the br...
To answer my own question if anybody else comes this way: Specifically setting stdout in octave doesn't seem to work, and neither do any attempts to temporarily redirect stdout at the system level. However, octave has the command dup2, used as described here: http://octave.1599824.n4.nabble.com/dup2-on-stdout-or-using-...
4,230,216
4,230,297
How to prevent console output from cin
How does one prevent cin from printing to a console screen in C++? Given this simple program: #include <iostream> using namespace std; int main() { cout << "Hello World..." << endl; cin.clear(); cout << "Press ENTER to Continue..." << endl; cin.ignore(); exit(0); } So if a user jams away at the...
On Windows, you need SetConsoleMode. There is no standard platform independent way, although of course you can write your own disable_echo() function and use #if _WIN32 and #if __LINUX__ to provide platform-specific implementations of a platform-independent interface.
4,230,223
4,230,342
valid char array (is this a valid string)
I am filling a char array using ReadProcessMemory and I am curious to know what is the 'correct/standard/best' way to determine if the returned char array contains a valid string. I'm not worried about the string, it can contain the a-zA-Z0-9 plus spaces and characters such as './_' and a few other things but really a...
It can be treated as a string if it contains a NUL character to terminate the string. If there is no NUL, treating it as a string will run off the end of the buffer and cause very bad things to happen. Thus: bool is_it_a_string = memchr(data, 0, char_read_length);
4,230,345
4,230,356
Declaring vectors in a C++ header file
I am having some trouble with vector declarations in the header file of a C++ class I am making. My entire header file looks like this: #ifndef PERSON_H #define PERSON_H #include "Message.h" #include <string> #include <vector> class Person { public: Person() {}; Person(std::string emailAddress); private: vect...
You're missing the namespace: std::vector
4,230,559
4,232,181
Inter-thread communication in C++
I have two threads (the applications main thread and another one). I am using OpenGL to draw some stuff and I am using the OpenGL keyboard and mouse callbacks. OpenGL blocks when I call glutMainLoop() and since I have to do some calculations in the background, I created another thread. Now, the OpenGL callbacks shall s...
Oh... No, no, no. Threads are NOT what you should use here. Seriously. Thread are NOT your solution in this particular case. Let's roll back a bit... You're using GLUT at the moment and you say you need threads to "avoid locking on glutMainLoop(). And you don't want locking because you want to do some calculations in t...
4,230,653
4,230,771
Pointer gets lost when allocated struct with pointer on allocated string gets passed as argument for pthread
I'm writing a server who starts a thread for each incomming request. I want to pass the arugments of the request and some other things to the thread. To do so Iam using a struct, which is allocated and contains a pointer which points onto an allocated string. I do so to keep the struct alive for the thread even when th...
You're passing the address of a pointer, i.e. a pointer to a pointer, to pthread_create, but what you want to pass is the address of your _thdata object. You need to pass the pointer to the object itself, like: pthread_create(&p_thread, NULL, thread_function, data); Also, there's no need to cast to void* here.
4,230,676
4,230,729
How to monitor streams in c++
Often when writing file writers or parsers in c++, I would like to monitor the writer/parser's progress through the file as it gets written/read. To this end, I was thinking of implementing something like: ostream_monitor my_monitor(&my_output_stream, &cout); my_monitor << my_variable; This would have the effect of ou...
Seems like boost.IOStreams' tee_device, and possibly tee_filter, can be used to quickly implement what I describe above: How can I compose output streams, so output goes multiple places at once?
4,230,901
4,231,822
AssociateColorProfileWithDevice, Where do you get the DeviceName?
http://msdn.microsoft.com/en-us/library/dd371799(v=VS.85).aspx So with a signature like this: BOOL WINAPI AssociateColorProfileWithDevice( PCTSTR pMachineName, PCTSTR pProfileName, PCTSTR pDeviceName ); pMachineName Reserved. Must be NULL. This parameter is intended to point to the name of the machine on wh...
You can use EnumDisplayDevices to all available display devices: http://msdn.microsoft.com/en-us/library/dd162609.aspx http://msdn.microsoft.com/en-us/library/dd183569.aspx
4,231,205
4,231,212
Generating a derived class instance from a string of its name. (i.e, reflection)
If I have a base class: class Base { public: virtual void Test()=0; }; and, in a dynamically loaded module (.so/.dll), I implemented a class derived from this: class SomethingFromBase : Base { ... }; and, the user, once this library is loaded, asks to create an instance of SomethingFromBase (let's say we get the na...
You typically achieve this by required that plugin libraries define some global variable of a struct type that contains pointers to various functions you can call. (Like setup, teardown, etc.) During the setup function, they would call back into your application to some "register" function where they could pass in a ...
4,231,307
4,231,308
Calling a Derived Class' method
Can I call a Derived Class's method from the base class in C++? If so, how can I do that? Thank you.
Attempting to call the method from within the base class will call the derived class's implementation, provided it is virtual. class Base { public: void do_stuff() { print_me(); } virtual void print_me() { std::cout << "Base" << std::endl; } }; class Child : public Base { virtual void print_me() { std::co...
4,231,427
4,232,008
How to declare a thread local static in a template
How can I define a static member variable that is also thread local inside a template class? I think I've figured out how to do it in GCC, but would like to confirm this will work correctly in terms of linking, initialization and resolution. Also the translation to another compiler would be helpful (like MSVC) so I can...
I believe your code is correct, and would translate in MSVC by replacing __thread by __declspec(thread) (see Thread Local Storage on MSDN) : template<typename T> class my_class { struct some_type { }; static __declspec(thread) some_type * ptr; }; template<typename T> __declspec(thread) typename my_class<T>::some_t...
4,231,648
4,231,716
C++ reverse_iterator Alternatives
I am attempting to write a two-pass algorithm incorporating some legacy code. I want to move through a particular container twice, once in order and once in reverse order. Obviously, my first thought was to use an iterator and a reverse_iterator, but strangely the designers of the container class I'm using did not see ...
If you need to iterate over the elements of a container in reverse order, you don't necessarily need to use a reverse iterator. If the container has bidirectional iterators, then you can use ordinary iterators and use --it to iterate from end() to begin() instead of using ++it to iterate from begin() to end(). Sinc...
4,231,819
4,231,861
Is there the possibility of having one version of machine code for all template arguments of a templated function?
Some people here told it's not possible and some people here told it might be possible to have one version of machine code for all different template arguments of a templated function, so I thought it would be profitable to open a thread regarding this specific matter, if there is not such possibility that's it, if the...
A smart linker can recognize when two different function bodies are identical and combine them together into one symbol. This is called "COMDAT folding" in MSVC and "duplicate stripping" most other places. For example, the following two functions might compile identically on PPC, although they take different types, bec...
4,231,828
4,231,843
Once a part of the standard - will boost library lose its boost namespace and will be moved to std?
Once a Boost library (I have read that ten Boost libs are considered to be a become a part of Standard Library) becomes a part of Standard Library - is it going to keep it's boost namespace or the code will end up in std namespace? If the latter is the case - how would you workaround that potential namespace clash in ...
The items from Boost libraries that made it to the standard will of course be included in namespace std. However, I don't think that their Boost counterpart will change in any way : if we take the example of bind, people compiling C++0x will use std::bind while people compiling C++03 will keep using boost::bind. I may ...
4,231,865
4,231,938
C++: Data alignment and efficient use of memory (in both time and space)
Cheers every! I want to store some data in memory in a structure, or in an array. My problem is data alignment. I cant really use a 8 byte data next to a char since they will take up 16 bytes together. Now I would live happy with a single 8 byte field, like a char and using the remaining 7 bytes to store other data. Ho...
You can automate the bit shifting math suggested by Arkku with bitfields: struct { uint64_t one_byte:8; uint64_t seven_byte:56; }; There will be slight access overhead but it's worth it if you plan to use so many of these that space is at a premium. Over so much memory the improved cache locality will easil...
4,231,942
4,231,966
How to swap map elements
In C++, how would I swap two elements of a map?
What do you mean by swap in a map? A normal plain vanila map doesn't have any particular order so speaking of swapping has no meaning in reference to order. If you are looking for C++ map implementation that preserves order, in which case ordering becomes meaningful then look here If however you are looking to swap the...
4,231,953
4,232,016
Trailing Array Idiom
What is Trailing Array Idiom ? P.S : Googling this term gives The vectors are implemented using the trailing array idiom, thus they are not resizeable without changing the address of the vector object itself.
If you mean the trailing array idiom mentioned in the GCC source code (where your quote comes from), it seems to refer to the old C trick to implement a dynamic array: typedef struct { /* header */ size_t nelems; /* actual array */ int a[1]; } IntVector; where an array would be created with IntVector ...
4,232,018
4,232,045
starting out in winsock cant get the first bit to compile
apologies for having to create a new thread for this but I'm starting out in winsock and have been following through madwizard and beej guides, and also some information on msdn. I'm stuck and I cant seem to compile the following (yeahp...big start..i know..:P ) #include <windows.h> #include <winsock2.h> #include <ws2t...
You have to link your project against the winsock library using -lws2_32 (if I remember correctly).
4,232,063
4,232,086
How to overload stream insertion operator with a template?
I am trying to overload the stream insertion operator so can I print std::vector to std::cout, but I'm having problem with syntax. This is what I tried: template<typename T> std::ostream & operator<<(std::ostream &os, std::vector<T> &v) { std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, ', ')); return...
The code is almost fine, however : The separator ', ' is incorrect : use ", " Your function could (and should) take a const reference to v : const std::vector<T> &v There is an unnecessary ; after the function close brace :) For the record, ', ' is a multi-character constant of type int so the compiler complains that...
4,232,093
4,232,212
Implement matlab code in C++?
I have a certain code written in Matlab. I wanted to obtain similar results using a c++ code. I wanted to know whether a c++ library exists for matrix manipulations? My current Matlab code consists of matrix multiplications,inverse and complements.
There are dozens of linear algebra libraries for C++. Here is another one not mentioned in the other links so far: http://www.alglib.net/
4,232,102
4,232,149
Am I coding for an OS or the Processor?
It is said that by using C/C++, one can write 'native' programs - that run on the platform. I am confused about what is considered native - the processor architecture or the OS version? For example: I have a 32 bit processor and Windows 7 ( 32 bit ), and I compile and generate and .exe file. Is it guaranteed to run on ...
Both; kind of. The actual instructions don't really differ across Windows and Linux as they are compiled down for a single CPU architecture (x86). However, a binary is more than just code that runs on bare hardware. For instance, it also contains information that tells the operating system how to load the executable a...
4,232,144
4,232,163
How is heap usually implemented?
Possible Duplicate: How is heap and stack memories managed, implemented, allocated? Hi, my question is about heap, not the data structure, but the area of memory that is used for dynamic memory allocation. Suppose we're writing a program in C (or maybe C++) and somewhere in the depths of its code a call to malloc()...
The OS allocates pages, which it returns to malloc/free, which then break those pages up into blocks of the requested size, from memory. The OS can allocate any pages in the user's address space that aren't already requested. There is no heap segment. The allocated memory is in whatever location the OS determines.
4,232,269
4,232,485
Library for cross-platform mapping of MIME types to file extensions and vice versa
TL;DR: The question is: Do you know of a cross-platform library that I can use from C++ to map MIME type(s) <-> file extension(s)? My application is supposed to handle image and video files alike. I try to be as platform agnostic as possible, so I chose to use Qt4 as my main library. The Phonon framework (for handli...
Like you already wrote on your question, I'd go for a mimefile from Apache or some Linux distribution and ship it with your application. Personally I think there is no point in having a "library" for that to "stay permanently up-to-date". MIME grew huge over the past years, but in reality you just need 1% or less of al...
4,232,272
4,233,981
How to implement a timed wait around a blocking call?
So, the situation is this. I've got a C++ library that is doing some interprocess communication, with a wait() function that blocks and waits for an incoming message. The difficulty is that I need a timed wait, which will return with a status value if no message is received in a specified amount of time. The most ele...
You could use sigaction(2) and alarm(2), which are both POSIX. You set a callback action for the timeout using sigaction, then you set a timer using alarm, then make your blocking call. The blocking call will be interrupted if it does not complete within your chosen timeout (in seconds; if you need finer granularity ...
4,232,400
4,232,440
boost::condition_variable wait without a lock
Is it possible to "wait" on a boost::condition_variable without having to acquire a mutex lock first? Failing that, can this be done using the pthread lib directly somehow? For simplicity I'd like to avoid going directly to the OS layer (such as futex on linux). But I also don't want the overhead of the mutex call. I'm...
The mutex must be acquired first in both case. From boost.threads documentation : void wait(boost::unique_lock& lock) Precondition: lock is locked by the current thread [...] From pthread_cond_wait man page : The pthread_cond_wait() and pthread_cond_timedwait() functions are used to block on a condition va...
4,232,409
4,234,173
How to solve Boost::BGL template<->class circular dependency?
I have a problem with using the adjacency-list of the Boost Graphics Library. It seems to be a circular dependency problem: I have a typedef T of a template which uses some class A. Additionally A stores a pointer to an object of type T. Now the compiler tells me, that T does not name a type. Here are excerptions of m...
You have circularly included headers. Lane includes graphdefinitions, which includes lane, which includes graphdefinitions, etc. This is the cause of your problem. Edit: I realized this was already mentioned in the OP. The solution to this problem is PIMPL. Edit: What I would actually do is put the typedef inside the L...
4,232,654
4,232,751
how to pass arrays and return array values of 2-d matrices?
call from main matrix_multiplication(arrayA,arrayB,row1,col1,col2); function definition float matrix__multiplication(float **arrayA,float **arrayB,int row1,int col1,int col2) { float result[row1][col2]; result[][]=.... return result; } I wanted to know how to pass 2d arrays in function call, how to receive in functi...
Using raw pointers for your arrays like this is more C style than C++. Use vector of vector (indexing is still very efficient). size_t rows(5); size_t columns(15); vector<float> row(columns); vector<vector<float>> matrix(rows, row); matrix[0][0] = 0.1f; Better yet wrap the underlying storage in a Matrix class that im...
4,232,843
4,232,882
Class design question - how to provide read only access to class member container
In my day-to-day work, I often find myself writing classes like in this simplified example: class CGarage { public: CGarage(); ~CGarage(); typedef std::vector<Car> CarCollection; private: CarCollection m_Cars; }; I want the users of CGarage to have read only access to the CarCollection. In order to ac...
How would you provide read-only access to the CarCollection? I don't see what's wrong with solution 4. It should be obvious to users of CGarage that a reference to its car collection is tied to the lifetime of the garage. If they need the car collection to outlive the garage then they can always take a copy if they l...
4,232,945
4,488,642
UDT server buffer size?
So here is my program for receiving UTD messages. I am planning to use it to receive 640*480 YUV images over wifi. How big buffer should I set? Is it possible to set buffer after receiving first image to find out the actual size? Bellow is my whole code but basically my question is related to this line: memset(&(my_add...
memset writes to a portion of memory, it doesn't allocate it. You can certainly call it after receiving an image, but it will have the effect of wiping 8 bytes of memory starting at the address of sin_zero. Perhaps you mean malloc, which would allocate memory, but requires use of free to prevent leaks and null-checks t...
4,232,994
4,233,045
Do existing libraries die when a new feature comes in as part of the language core?
** Please people, this question is not meant to begin any flame war. ** I am trying to understand what happens to existing libraries implementing some functionality when the same functionality that was not previously there in the language now comes in as part of the language? For e.g. C++ would soon have std::thread as...
C++ std::thread is in large parts based on boost threads. So boost threads will never really disappear, they will live on in the standard C++ library. Additionally, on many platforms boost threads use posix threads as backend, so they will never disappear too.
4,233,179
4,233,321
UDT::send in a for loop sends only once. No error
This sends data only once which seems irrational to me as it is in a for loop: char* hello; for (int i = 0; i < 10; i++) { hello = "Hello world!\n"; if (UDT::ERROR == UDT::send(client, hello, strlen(hello) + 1, 0)) { cout << "send: " << UDT::getlasterror().getErrorMessage(); } } Shouldn't it ...
Have you checked the server side code. Client is doing sends in a for loop, how is the server side receiving them? Edit: In reference to your post here. If your server code looks like this, it will receive only once. The server is getting the connection from the client then receives once then again waits for connection...
4,233,300
4,233,457
"run time templates"
I'm pretty sure the answer is "you can't use templates, you have to use virtual functions (dynamic polymorphism)", but it seems like I'd have to duplicate a lot of code if I went that route. Here is the setup: I currently have two classes, ColorImageSegmentation and GrayscaleImageSegmentation. They do essentially the s...
Maybe there are additional requirements you haven't told us about, but from what you have so far, you can pass the type down through the containing class: template<typename TImage> class MyMainClass { ImageSegmentation<TImage> MyImageSegmentation; }; Most likely you'll need some layer of dynamic dispatch, but only ...
4,233,360
4,233,418
Pointer to a object class throwing "does not name a type"
I have a hardware class having a pointer to a TLB class object, and initialising that in the constructor. However, Codeblocks (GNU GCC) is giving me the error "proj3_hardware.h|15|error: 'TLB' does not name a type" "proj3_hardware.h|15|error: expected ';' before '*' token" I just cannot see where is the error in the co...
Compiles for me. The error must be in other code; Check your other header files for: any suspicious #defines missing semicolons? wrong include guards (this one is my best guess)
4,233,460
4,233,507
Some confusions this tip about determining passing method of parameters to a function brings up for me
Here's a tip that makes some confusions for me:"to have the best passing method pass built-in types by value and other types by reference to constant" now I have some questions below: 1-first of all I think the reason behind suggesting passing by reference to constant is that if the referenced object is not volatile th...
a special syntax by which we could tell the compiler ok here determine the best passing method yourself Boost provides this, as boost::call_traits<T>::param_type. why it is this way that this is Probably because the rule of thumb works most of the time. If in doubt, you can pass by const reference and it's unli...
4,233,549
4,233,823
string::compare superfluous parameter?
In the C++ reference on string::compare, there is the following overload: int compare ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 ) const; which has two parameters n1 and n2 which in my eyes should always be equal or the function returns an int equal to true (string::compare return value of 0 (...
The n1 and n2 parameters are the maximum number of characters to compare. The std::compare function will trim the values if they exceed the length of the strings. Here is an example where the values aren't equal and the function returns 0. std::string a("AACAB"); std::string b("CAB"); std::cout << a.compare(2, 8, b, 0,...
4,233,649
4,516,909
SymFromAddr returns "The specified module could not be found."
I'm trying to get symbols from addresses I got from my stack, but SymFromAddr keeps failing with system error 126 (The specified module could not be found.) I'm initializing the symboling thing with SymInitialize(m_processHandle, NULL, TRUE); (the last parameter == true ==> It loads the PDB automatically) and I use ...
SymFromAddr is a little bit capricious. If any LoadLibrary occur between SymInitialize and SymFromAddr it may not work. If SymFromAddr you can perfom a SymInitialize again (hint: you can cache address to avoid a lot of SymInitialize which is a huge CPU consummer) 64 bits implementation of SymFromAddr (ie. SymFromAddr6...