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
6,368,463
6,368,498
Is epoll a bad idea for udp client?
I have created a linux server using epoll. And I realized that the clients will use udp packets... I just erased the "listen" part from my code and it seems like working. But I was wondering any hidden issues or problems I might face. Also, is this a bad idea using epoll for server if clients are sending udp packets?
If the respective thread does not need to do anything else but receive UDP packets, you can as well just block on recvfrom, this will be the exact same effect with one less syscall and less code complexity. On the other hand, if you need to do other things periodically or with some timely constraints that should not de...
6,368,473
6,368,909
Is it possible to implement polling with QThread without subclassing it?
I have a class, which is an abstraction of some device. class Device { public: ... void Start(); void Stop(); void MsgLoop(); signals: void sMsgArrived(); } Start() and Stop() are called from GUI thread. Start() begins new thread, which runs MsgLoop(). It looks like this: void MsgLoop() { ...
Generally you have to decide who will be responsible for managing the thread. Is it the Device or the main window? Or possibly some device manager. In your case the Device should probably manage its own thread, so if you don't want to subclass it, use composition: class Device : QObject { Q_OBJECT public: Devic...
6,368,499
6,370,180
How to map optical flow field (float) to pixel data (char) for image warping?
I've been playing with the optical flow functions in OpenCV and am stuck. I've successfully generated X and Y optical flow fields/maps using the Farneback method, but I don't know how to apply this to the input image coordinates to warp the images. The resulting X and Y fields are of 32bit float type (0-1.0), but how d...
The flow vectors are velocity values. If the pixel in image 1 at position (x, y) has the flow vector (vx, vy) it is estimated to be at position (x+vx, y+vy) (so the values aren't really in the [0, 1] range - they can be bigger, and be negative too). Easiest way to do the warping is to create floating point images with ...
6,368,503
6,368,768
Generate unique sequence ID
how to Generate a unique sequence ID to be stored in unsigned long ? Getting seconds elapsed after 1970 would have been good idea but requirement is within a second the id might be updated , so second wont be unique !
If your requirements are to pick something pseudo random, fast, reliably unique, and not used for requirement for crytographic security purposes, I offer up the following On Windows X86: __rdtsc() - is about as good of a sequential number as it gets. XOR the upper 32-bits of the return value with the lower 32-bits. ...
6,368,614
6,368,723
When is it required to return a reference from a function?
My question is when does any one need to return an object by reference? Well this comes from the fact that we can as well pass the object to be filled through the parameter list itself. Are there any particular scenarios where it mandates the return by reference. I'm asking this with respect to non member functions. E...
You need to return as reference when you want the reveiving end to have access to the referred object. Consider operator[] in a map and the use case: std::map<std::string, int> word_count; std::string word; while ( std::cin >> word ) { word_count[ word ]++; } You do not want to extract the value from the map, but r...
6,368,690
6,373,792
rvalue function overloading
I want to overload a function so that it manipulates its argument in some way and then returns a reference to the argument – but if the argument is not mutable, then it should return a manipulated copy of the argument instead. After messing around with it for ages, here's what I've come up with. using namespace std; s...
I would get rid of the references all together and just write one function that passes and returns by value: std::string foo(std::string in) { in.insert(0, "hello "); return in; } If you pass an lvalue, the input string will be copied. If you pass an rvalue, it will be moved. When leaving the function, named r...
6,368,849
6,369,365
output of the structure size using bitfields
#pragma pack(2) struct a{ unsigned a:1; unsigned b:1; int c; unsigned d:4; unsigned :4; unsigned e:1; unsigned :0; unsigned f:1;} ; int main() { printf("%d",sizeof(struct a)); } The output of the following program comes to be 16 when pragma pack is not used but is 10 when pragma pack is used.pleas...
First, #pragmas are compiler-specific so without you specifying your compiler and CPU (and perhaps compiler version and commandline options) we can only speculate. But, a plausible explanation is that, for the "pack(2)" version: #pragma pack(2) struct a{ unsigned a:1; // at byte offset 0, could be least- or mo...
6,368,927
6,368,953
LNK2019 Using untemplated classes
I'm getting linker errors when using Classes that reference other classes in them. 1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall MovePattern::~MovePattern(void)" (??1MovePattern@@QAE@XZ) referenced in function "public: __thiscall Enemy::Enemy(int,int,class MovePattern,char)" (??0Enemy@@QAE@...
You've not defined the default constructor and the destructor, as listed below: MovePattern(); //default constructor ~MovePattern(); //destructor You've to define them IF you declare them. Declaration must have definition. Or else you'll get linker error when using them, either implicitly or explicitly.
6,369,096
6,395,941
How to Read the certificates file from the PKCS7.p7b certificate file using openssl?
I am getting PKCS7 file (p7b). I want to read the content of the file and extract certificate in X509 structure. How can I access individual Certificate from the PKCS container using openssl library?
I've used the following program: #include <stdio.h> #include <openssl/pkcs7.h> #include <openssl/x509.h> #include <openssl/bio.h> #include <openssl/pem.h> int main(int argc, char **argv) { PKCS7 *p7 = NULL; BIO *in = BIO_new(BIO_s_file()); BIO *out = BIO_new(BIO_s_file()); int der = 0; /* Input from DE...
6,369,142
6,369,367
Can epoll receive udp packet?
I am a newbie of network programming and I've hear about epoll. I read a couple of tutorials and now I got some basic idea of what epoll does and how I can implement this. The question is that can I use epoll even if client will using udp connection? All the tutorials I read used tcp connection. Also is there a good tu...
There is no problem to use epoll with UDP, the epoll just notifies if there is any data to read in the file descriptor. There are some implications in the read/write... operations related to the UDP socket behaviour (from the man page of epoll): For stream-oriented files (e.g., pipe, FIFO, stream socket), the c...
6,369,264
6,374,752
Is boost::io_service::post thread safe?
Is it thread safe to post new handlers from within a handler? I.e. Can threads that called the io_service::run() post new Handlers to the same io_service? Thanks
It is safe to post handlers from within a handler for a single instance of an io_service according to the documentation. Thread Safety Distinct objects: Safe. Shared objects: Safe, with the exception that calling reset() while there are unfinished run(), run_one(), poll() or poll_one() calls results in undefined...
6,369,363
6,369,406
Stackoverflow not happening while trying to figure out if memory is being allocated on stack or heap
I wanted to try out a more complex example of allocating memory with new in an object and allocating further inside it, but needed to know for sure when a stackoverflow will happen. So decided to try this example. I called the foo() function from main() and expected it to give a stackoverflow error. It didn't. In foo, ...
Make foo call itself recursively, and have some counter increment with each call. You'll get your fault soon enough.
6,369,380
6,369,457
Erase parts of drawings in OpenGL
I would like to know if it is possible to erase parts of any drawing in OpenGL? Lets say I have drawn two lines with my mouse and those lines are overlapping at some points. Is it possible to erase just one line? Is there a more or less simple approach?
OpenGL does not store what you draw. If you draw a line in OpenGL, then OpenGL will take that line, perform various math operations on it, and write pixels into a framebuffer that makes the shape of a line. OpenGL does not remember that you drew a line; all OpenGL can do is write pixels to the framebuffer. The general ...
6,369,402
6,369,811
How to move data from java InputStream to a char * in c++ with jni?
How can I move the data stored in a java InputStream to a char * in c++ using JNI? Thanks, Carlos.
From java: { InputStream inputStream = rcvStream; byte[] inData = new byte[1024]; int bytesRead = inputStream.read(); byte[] actualData = new byte[bytesRead]; System.arraycopy(inData, 0, actualData, 0, bytesRead); jni.setByteArray(inData, bytesRead); } Fr...
6,369,591
6,369,685
What is the easiest C++ IDE for students, non-programmers?
I teach programming at secondary school: this is our current status and I would appreciate any suggestions: We have programmers club for advanced students. We develop in MSVC# (even commercially) and NetBeans, everything works fine However, two thirds of the class are not developers: they are otherwise oriented, their...
Visual C++ Express does support native C++ developement. I would strongly urge you to upgrade to the 2010 version to gain some C++0x support; C++0x makes it much easier to program in C++ without touching the nasty bits. However, C++ as a first language sounds daunting. Particularly for those without any further progr...
6,369,595
6,369,724
Why cant i access subtype via templates?
Here is an example. I get an error on typename T::SubType* inside of the template but not outside. using gcc0x i get prog.cpp: In instantiation of 'TemplateBase<A>': prog.cpp:8:36: instantiated from here prog.cpp:4:22: error: invalid use of incomplete type 'class A' prog.cpp:8:7: error: forward declaration of 'class ...
A class is fully defined at the closing brace, not at the point where you're listing its parent classes. Therefore, in class A : public TemplateBase< A > {, you're instantiating TemplateBase with an incomplete class A.
6,369,776
6,377,706
DirectX collision test. - Is it worth to make your own engine?
I'm trying to learn game programming with Visual C++\DirectX. At the moment I can load XMeshes, move them around, turn the camera around them, make collision test for only a box world etc.(I made some short of classes for these things) Now, I made a 3D model for terrain and I want to make my character move on it. There...
You can use this: http://msdn.microsoft.com/en-us/library/bb172882(v=vs.85).aspx There was a sample on it in some old DX9 SDK, but I can't seem to find it over the net... For the second question: if you're learning, try to do everything yourself first. That will give you reliable understanding of how 3D-engines work, h...
6,369,874
6,370,505
Writing browser plugin in QT
I would like to try writing a browser plugin in QT. What browsers will it support? I couldn't find an updated documenatation (for QT 4.7.0) how to do it. Can someone provide a link to documentation\tutorial\example? Thanks!
Qt has no native support for browser plugins. There is a set called Qt Solutions, here is git repo for it , you need qtbrowserplugin solution. it has some docs provided with it, which says it supports FireFox, Safari, Opera, Google Chrome, QtWebKit and any other web browser that supports the "Netscape Plugin API"
6,369,962
6,372,363
Read problem with epoll
I have this while loop and this code is working. The problem is that if I have reduced the buffer size and send bigger data than the buffer size it receive the data separately. For example, if I send 170 bytes(100 byte buffer) then it reads first 100 bytes and again it reads 70bytes. What is the best way to handle this...
Well, though it's unlikely, it is possible that your 170-byte client send could arrive at your server and be presented as 170 read() returns with a str_len of 1. That's just how TCP is - it streams bytes. If you have to concatenate bytes into some sort of protocol-unit, then you will have to explicitly do this in you...
6,370,158
6,370,440
Is there any shortcut key to switch between .cc and .h in Eclipse CDT?
Is there any shortcut key to switch between .cc and .h in Eclipse CDT? I was using visual stdio , I can switch between .cc and .h using alt+o, Can I do it in Eclipse CDT? Many thanks!
Ctrl+Tab is the default shortcut in eclipse for switching the editor view from viewing a .cpp file to a corresponding .h file, and vice versa. YES, You can change it to alt+o In Window->Preferences->General->Keys - Toggle Source/Header
6,370,171
6,370,262
Shadowing functions of C stdlib/stdio
I am writing a game and for now i was able to implement a filesystem via sqlite with a class and its methods. To make life more easy i have planned to write some functions like fopen,fclose,fread,rename, etc. to be able to shadow the base functions and to direct my calls to my filesystem rather than to the original one...
And what is the reason that you cannot simply use your own functions by any other name? If the whole conflict is with overload resolution, you should simply just shadow the actual prototypes; You can make them forwards to your own functions. However, I recommend against the general approach here: even with that 'fix' ...
6,370,201
6,370,499
How to copy data in buffer to somewhere in memory (char *)
int str_len = read(m_events[i].data.fd, buf, BUF_SIZE); I have this and I read data into the buf declared like char buf[BUF_SIZE]; What I am trying to do is that I am trying to get the data and hand it to the WorkHanndler which I defined and nothing more than just a thread pool. And the function is void ServerManage...
Only possible flaw I see right now could be inside the Work class: Ensure it creates its own copy of the buffer contents immediately in the constructor as it will be overwritten once new data arrives. Other than that it should work as expected (hard to judge without specific work to be done, etc.). Also there shouldn't...
6,370,301
6,370,356
How to clear the buffer of a streamstring?
I have a streamstring in two loops and it is burning my RAM. So how to clear properly the buffer of a steamstring? It is like that to simplify : stringstream ss (stringstream::in | stringstream::out); for() { for() { val = 2; ss << 2; mystring = ss.str(); // my stuff } /...
The obvious solution is to use a new stringstream each time, e.g.: for (...) { std::stringstream ss; for (...) { // ... } } This is the way stringstream was designed to be used. (Also: do you really want a stringstream, or just an ostringstream?)
6,370,447
6,370,556
Is my approach eligible for a Thread Pool approach?
I have win 32 C++ application . I have to load 330,000 objects into memory . If I use sequential approach it takes around 16 min . In the threading approach I divide the 330,000 objects equally among 10 containers . I create 10 threads and I assign each thread one container of size 33000 objects to load them in memory...
As always without specifics, it depends. Are you loading objects from disk or creating them in memory? If you're loading them from disk then it's probably IO bound so increasing the number of threads probably won't help very much. In the comment you mentioned you are loading from a database. I presume when you use ...
6,370,780
6,376,952
OpenGL glViewport() (resetting coordinates)
I have a problem with glViewport. In my liitle programm i have two viewports. I can draw a form (with the motionfunc) in one of those viewports and in the other a line is automatically drawn. So far so good.. When i try to draw something with mousefunc the viewport is in a total different place. And it is very difficul...
You should check your modelview/projection matrices and see if they are what you expect them to be in each function. Also, as Christian's commented, it is not necessary, nor recommended, to draw in the motion func. Update your application state per the input and call glutPostRedisplay to signal that you want to redraw ...
6,370,848
6,371,145
Recursive template definition
I have a recursive template definition (I just made up that term). I think code explains it better. template<typename X> class Domain { public: X begin; X end; Domain( X _begin, X _end) : begin(_begin) , end(_end) { // ......
Add something like: template<typename X, typename Y> class NthOrderFunction<X, Y, 1> : public IFunction<X, Y> { public: double coeffs[n+1]; public: NthOrderFunction( const Domain<X>& dom, ... ) : IFunction(dom) { } virtual Y ...
6,370,894
6,371,098
Converting a four character string to a long
I want to convert a four character string (i.e. four characters) into a long (i.e. convert them to ASCII codes and then put them into the long). As I understand it, this is done by writing the first character to the first byte of the long, the second to the adjacent memory location, and so on. But I don't know how to d...
Here's your set of four characters: const unsigned char buf[4] = { 'a', '0', '%', 'Q' }; Now we assemble a 32-bit unsigned integer: const uint32_t n = (buf[0]) | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24); Here I assume that buf[0] is the least significant one; if you want to go the other way round, just swap th...
6,370,897
6,370,952
XOR higher 32 bits with lower 32 bits in a 64 bit number
In a 64 bit number How to XOR Higher order 32 bits with lower order 32 bits. Thank you
(v & 0xffffffff) ^ ((v >> 32) & 0xffffffff)
6,371,004
6,412,109
Is there a lightweight approach in producing XML with Xerces-C++?
This application runs on an embedded platform with low processing power and memory. I want to produce huge XML from the application. Currently I am constructing DOM and serializing into XML using Xerces-C++ 3.1.1. But the DOM construction takes long time and consumes lot of memory. I know SAX is lightweight approach of...
What you are looking for is normally called streaming serialization where parts of the document are written out as they become available instead of accumulation them all and writing them out at the end (which is what the DOM approach entails). Xerces-C++ does not currently have streaming serialization support. But it i...
6,371,048
6,371,168
c & c++ default global variable linkage, multiple declaration & definition problem
For example: code1.c / .cpp int a; // ... and so on code2.c / .cpp int a; int main(void) { return 0; } go to compile: $gcc code1.c code2.c # this is fine $ $g++ code1.cpp code2.cpp # this is dead /tmp/ccLY66HQ.o:(.bss+0x0): multiple definition of `a' /tmp/ccnIOmPC.o:(.bss+0x0): first defined here collect...
It's not strictly legal. int a; is a tentative definition in C. You are allowed multiple tentative definitions and at most one non-tentative definition per translation unit of each object with external linkage in C, but only one definition across all translation units in a program. It is a commonly implemented extensio...
6,371,713
6,371,740
C++ STL map , std::pair as the key
This is how I have defined by map. std::map<std::pair<std::string,std::string>, int> edMap; I am confuse on how to insert values , I am getting compilation error always. This is how I am trying to insert. std::pair<std::string,std::string> key; edMap.insert(key,d); Compilation error is 1>------ Build started...
Let's try: typedef std::pair<std::string, std::string> my_key_type; typedef std::map<my_key_type, int> my_map_type; my_map_type m; m.insert(my_map_type::value_type(my_key_type("A", "B"), 43)); Observe that the map's value_type is always std::pair<const key_type, mapped_type>, so in your case it's std::pair<...
6,371,779
19,490,481
Changing Windows DLL load order? (load order, not search order)
Say I have one executable: app.exe I use 2 different 3rd party DLLs in this executable: foo.dll bar.dll and the Application must link implicitly to these DLLs, that is I cannot use ::LoadLibrary to load them. (Note: It's not that I cannot call LoadLibrary, but these DLLs require static linking (C++ DLLs with __declspec...
What I haven't found out yet is how to influence this load order ... I have no clue why I hadn't tried this, but it seems the import section order of the resulting module does depend on the order in which the lib files are provided to the linker. Configuration Properties -> Linker -> Additional Dependencies ... The ...
6,371,793
6,372,491
Component-based game entities and type checking
I'm writing a game and it's going to use a component-based entity system. The first two components that I'm implementing are EntityRepresentation and EntityState. The representation holds the animations, and the state decides how the entity should react to game events (examples of EntityStates: standing, jumping, attac...
Use typeid(), that's what it's for. You could use a const type_info* as the key type. Alternatively, you know, you could just use actual inheritance, like, calling a virtual function to get the current animation, which would be much smarter.
6,371,929
6,372,328
Why base class function is called instead of derived one?
I have a class: class ProjectService : public CProjectT<CSoapMSXMLInetClient> { ... } I have implemented HRESULT ConnectToServer(); function in this derived class. Then I instantiated an object and called a function: ProjectService project; project.f1(); now, f1() calls f2() and f2() calls ConnectToServer(). All of t...
As said, you need the keyword virtual. Why? Because in your function f2(), defined only in CProjectT, you call the function CProjectT<CSoapMSXMLInetClient>::ConnectToServer(). Without the virtual keyword, there is no way to know for f2() that the derived method should be called. If you want to test : #include <iostrea...
6,371,989
6,372,075
G++ flags to disable "temporary to non-const reference" error
I am looking for some command-line flags (should they exist) that disable the GCC error for this type of C++ code: #include <string> void m(std::string& s) { } int main() { m(std::string("")); } G++ gives this error: error: invalid initialization of non-const reference of type 'std::string&' from a temporar...
It is not conforming to the standard & there is no way to disable this through flags in GCC. Vc++ wrongly supports this through an non-standard extension. Try with /Za (disable language extension) flag, and you should see the errors. Or use can the /W4 flag to get maximum warnings, and it will show you: warning C4239:...
6,372,032
6,374,353
Dynamic initialization phase of static variables
The standard specifically states that dynamic initialization of static duration variables (namespace scope and class static members) does not have to occur before main is executed: "It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done b...
I believe the intention here is to allow dynamic load libraries. Static variables defined in the libraries are not guaranteed to be initialized before main, but must happen before anything in the specific library is used.
6,372,259
6,372,292
Is there any cross-platform gzip processor library for C or C++?
I want some library (API) to open, seek, read, write ... (in one word to process) gzip files. Is there any open-source cross-platform ones for C or C++?
Yes. Zlib is the one. There is also this related question on how to process gzip files more easily and conveniently in C++. The most notable and up to date suggestion seems to be the GZip filters in Boost.IOStreams, which I have good experience with myself.
6,372,342
6,372,615
how to pass Extended ASCII characters through JNI via C++
I am trying to use JNI via VC++ and pass a custom directory in the classpath as a UTF-8 string -Djava.class.path=c:\myDir\my.jar This works well and I could find the methods in the jar using FindClass But when the directory name contains any extended ASCII characters then FindClass returns NoClassDefFound exception. I ...
The documentation suggests that the option string must be in "the default platform encoding". That probably means you'd need to use CP_ACP. If your characters can't be represented in that encoding then I'm not sure there's much you can do. (Would the file's short name be usable instead?)
6,372,383
6,373,131
Get list of folders protected by UAC
How to get the list of protected from write folders with UAC enabled? The process that needs this information is launched with admin rights (installer).
UAC does not protect folders. UAC strips the administrator SID from a user's access token reducing him to a regular restricted ("normal") user. Applications can request elevation via manifests - then the entire process runs with the admin token. If folders are not writeable with UAC enabled that means that NTFS securit...
6,372,431
6,389,226
gcov and global destructors
MWE #include <iostream> struct Foo { Foo() { std::cout << "Constructing Foo " << this << std::endl; } ~Foo() { std::cout << "Destructing Foo " << this << std::endl; } }; Foo global_foo; int main () { std::cout << "Entering and exiting main()" << std::endl; return 0; } The problem Compile the ab...
First off, note that that bug report hasn't been reconfirmed since 2005; you should probably add a note saying that you're still seeing the bad behavior in g++-4.2.1. Even if no one acts on your message, it's useful to have that information out there. Short term, if you want to go on using gcov you have to live with i...
6,372,561
6,372,648
Big O Notation for string matching algo
What would the big O notation of the function foo be? int foo(char *s1, char *s2) { int c=0, s, p, found; for (s=0; s1[s] != '\0'; s++) { for (p=0, found=0; s2[p] != '\0'; p++) { if (s2[p] == s1[s]) { found = 1; break; } } if (!found) c...
It is O(n²) where n = max(length(s1),length(s2)) (which can be determined in less than quadratic time - see below). Let's take a look at a textbook definition: f(n) ∈ O(g(n)) if a positive real number c and positive integer N exist such that f(n) <= c g(n) for all n >= N By this definition we see that n represents a ...
6,372,650
6,372,686
Trailing commas and C++
I have read somewhere that the C++ standard does not allow something like enum an_enum { a, b, c, };, while later versions of C (I think from mid-90s) do allow such declarations with trailing commas. If C++ is supposed to have backwards compatibility with C, how come this feature is forbidden? Any special reason? I als...
C++03 (which is a fairly minor update of C++98) bases its C compatibility on C89 (also known as C90, depending on whether you're ANSI or ISO). C89 doesn't allow the trailing comma. C99 does allow it. C++11 does allow it (7.2/1 has the grammar for an enum declaration). In fact C++ isn't entirely backward-compatible even...
6,372,732
6,372,943
nested class as a parameter for the member function in C++
I am integrating someone's code, which has everything in one cpp file. The main code is like this: class Outer { public: struct Inner { struct In_inner { ... } } int func(Inner& inn, Inner::In_inner& in_inn) { ... } } To make separation, should I add the "Outer::" fo...
int Outer::func(Outer::Inner& inn, Outer::Inner::In_inner& in_inn) Yes. You've correctly written this. You've to add Outer:: if you define it outside the class. It sounds a bit weird to me that the parameter list is a bit different from the declaration That is okay. The function is defined outside the class. You'r...
6,372,980
6,373,469
CUDA invalid redeclaration of int2
I have several .cpp files and a couple of .h files. If I compile them using nvcc instead of g++, everything is fine. Now, when I start (in main.cpp) to allocate memory on the device, i.e cudaMalloc( (void**)&_a, _DSIZE * sizeof(float) ) then the problems start. I have tried to change the extension of to .cu, but it i...
Obviously, int2, int3, float3 etc are my own re-declarations which are located in a mylib.h file and are global. Looks like CUDA uses those names, and now you have a name collision. Pick names that aren't taken by the libraries you use, or better yet, use a namespace for your code. (Best: do both)
6,373,121
6,373,168
Visual Studio 2010, Maximum Concurrent C++ Compilations for Hyper-Threaded Processors
I am trying to optimise the compilation time of a large VC++ project. My processor is a Core i7 950 (4 Cores, 8 Threads since it supports Intel Hyper-Threading Technology). In Microsoft Visual Studio 2010, if you go to Tools>Options>Projects and Solutions>VC++ Project Settings>Maximum Concurrent C++ complilations you c...
This is will save me a huge amount of time. No, it wouldn't. Hyperthreading is useful when you have different sorts of tasks to run which use complementary resources inside the CPU. For example, one thread uses a lot of floating-point and the other doesn't. While the first is doing floating-point math, the rest of...
6,373,436
6,374,280
Displaying not moving text not in 3D (eg. displaying HUD or frame rate)
I want to make something to display text on the screen. But I want something like FPS displayer - wherever you are text is in the same place (eg. in corner) and have the same height. Something like drawing HUD. I'd like to see code.
That kind of thing is usually done in the a way like this: void render_frame() { glViewport(0, 0, win_width, win_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); set_perspective_projection(); // glFrustum, gluPerspective, etc. glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClear(G...
6,373,513
6,373,572
Currency formatting with c++
Is there an obvious way to perform currency formatting in C++ ? For example: 1978879 would become 1'978'879 Thanks
Short answer: int value = 1978879; std::cout.imbue(std::locale("")); std::cout << value << std::endl; Locales are responsible for formatting. Any stream can be imbued with a locale; by default they use the global locale, which by default is the "C" locale which doesn't use any thousands separators. By creating a local...
6,373,710
6,373,936
How to set a default option for an application?
Here is a small application i coded. Now i wanna make /h as default option, so that when a user runs it he can get a help message. Can anyone help me with this please? #include "Poco/Util/Application.h" #include "Poco/Util/Option.h" #include "Poco/Util/OptionSet.h" #include "Poco/Util/HelpFormatter.h" #include "Poco/Ut...
OT: <rant>I love PoCo, have used it before. These days I gravitate to Boost instead, since compiler support is becoming ubiquitous. This problem is my definition of a intrusive/restrictive framework: simple things become hard to do. Defies the value of a good programmer sometimes.</rant> I suggest keeping a flag, like ...
6,373,743
6,374,052
Inaccessible QPushButton mystery
I have a QT application. It has functioning QPushButtons that are connected to slots in my program. I am now trying to add a new button myNewButton, but somewhere, somehow it is not being registered. For an existing, working button myExistingButton I have the line: connect(ui->myExistingButton, SIGNAL(clicked()), this,...
I fixed this by deleting the generated file ui_viewer.h and then rebuilding.
6,373,809
6,374,616
CUDA/Thrust Image Processing
I was unable to find any information about if the Thrust library could support matrix operations. Therefore, I was wondering if it were possible to use the Thrust library in Image processing? I would also like to see any examples. Thanks for any responses.
Thrust supports regualar algebra operations on matrices but if you are using mostly sparse matrices and need solver type operations take a look at cusp
6,373,829
6,374,945
Move DirectX window from one monitor to another in extended mode
I have a simple directX-9 test app that I want to move from one monitor to another in extended mode. The window and the device are created on the primary monitor and scene is drawn correctly but when I move my window to the second monitor it will freeze. There is no error and even the present calls do not fail but ther...
Make sure to enumerate over your adapter modes. The mode you are using might have a problem with the graphics card. Also, for each format that an adapter supports there is a list of display modes based on the number of modes available. Here's a quick example of looping through these modes: D3DDISPLAYMODE mode; UINT ada...
6,373,944
6,391,658
how to handle bad pointers
all, as the title asked how to handle bad pointers. I am using MSHTML::IHTMLStyle to handle style features that when I read in a snippet of html code, I collect some specific style features among all the html elements within the code. hash_map<wstring, wstring> CMyAppDlg::GetNodeStyles(VARIANT varSrc) { long lLeng...
the problem is caused by using smart pointers on IHTMLDocument2, IHTMLElement and IHTMLElementCollection, and IHTMLStyle. I solved the bad pointers problem by declaring normal pointers on them, and dont know why smart pointers failed me this time, and seems to be failed in some other places too.
6,374,054
6,422,747
How to have a "custom split()" in a list with strtk?
I have read http://www.codeproject.com/KB/recipes/Tokenizer.aspx and I want to have the last example ( at the end, just before all the graphs) "Extending Delimiter Predicates" in my main, but I don't get the same output tokens as the author of the article does when I assign the token_list to a vector, why? How to put t...
I could same results in codeproject. What version of gcc do you use? My gcc's version is following. g++ (GCC) 4.5.2 Copyright (C) 2010 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. UP...
6,374,264
6,374,525
Is cout synchronized/thread-safe?
In general I assume that streams are not synchronized, it is up to the user to do appropriate locking. However, do things like cout get special treatment in the standard library? That is, if multiple threads are writing to cout can they corrupt the cout object? I understand that even if synchronized you'd still get ran...
The C++03 standard does not say anything about it. When you have no guarantees about the thread-safety of something, you should treat it as not thread-safe. Of particular interest here is the fact that cout is buffered. Even if the calls to write (or whatever it is that accomplishes that effect in that particular imple...
6,374,577
6,374,605
Compare different length char arrays in c++ without string library
I have 2 char arrays, one with length 50, other whose length varies from 1...50. I need to compare these. The problem is, that the array containing 50 chars, usually contains less chars, but when comparing, it also takes them into account. So if I have 2 array, whose value is U2, length of first will be 50, the second ...
If you aren’t allowed to use the standard library functionality then your first task is to re-program the required functionality. In your example, this would be strcmp. Programming this function isn’t difficult – searching online should find you several possible implementations. Roughly: Start walking through both str...
6,374,609
6,374,903
Error in a simple cuda compilation
FSPB_main.cpp int main(int args, char* argv[]){ ....... float *d_a; cudaMalloc( (void**)&d_a, 5*sizeof(float) ); } $ nvcc -L/usr/local/cuda/lib -lcutil -lcudpp -lcuda -lcudart -c -o FSPB_main.o FSPB_main.cpp FSPB_main.cpp: In function ‘int main(int, char**)’: FSPB_main.cpp:167:45: error: ‘cu...
You need to include the header files where the CUDA functions are declared: #include <cuda_runtime_api.h> #include <cuda.h> and then on the cmd line you also need to add the PATH (option -I) where those includes are located. On my system, version 2.1 of CUDA installed the header files on /usr/local/cuda. To compile, I...
6,374,629
6,388,455
Keeping symbols from different builds of static libraries separate
I have an static Objective-C++ library basic.a, with a function BasicFunction(). Static Objective-C++ libraries foo.a and bar.a depend on basic.a and have functions Foo() and Bar() that call BasicFunction(). Here's the tricky part: When I make a project that links in foo.a and bar.a, each built at a different time, I ...
Well, it's unlikely anyone else will have this particular problem, but the solution was to have an Objective-C sentinel class called from a plain C function, both with unique names per build, called by each library. The sentinel class ensures there is only one instance with its name at runtime.
6,374,637
6,374,849
Error while trying to use OpenGL
I have a very simple C code in which I am trying to use OpenGl. When I include the following files #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <stdlib.h> I get the following error(and many more but they are similar): C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\GL/gl.h(115...
GLUT isn't part of OpenGL. You need to install it, which is what that error says.
6,374,799
6,374,830
Function 'not declared in this scope', but it is! Isn't it?
'initPhysics' was not declared in this scope. I have simplified my program as much as I could; here it is: helloworld.hpp #ifndef HELLOWORLD_HPP #define HELLOWORLD_HPP class testWorld { public: testWorld() {} ~testWorld() {} void initPhysics(); }; #endif hello.cpp #include "helloworld.hp...
It should be world->initPhysics(), not world<-initPhysics() Your version is being read as the expression "world is less than -1 multiplied by the result of the global function initPhysics()" and it's that global function that it can't find. And although this is obviously test code, I'd just like to point out that if yo...
6,375,010
6,375,109
c++ error codes propagation
I work on a legacy code in c++ which uses error codes instead of exceptions. In this case, fn A() calls B() which calls C() etc. Now if C() returns the error, i would like to exit at B() itself without having to pass it back to A() and have A() handle the error. However few other team members have the top most functi...
I think that errors should be handled as locally as possible. That is, if a class' method has enough knowledge to handle an error, it should do so. However, if the way to handle an error si to exit the program, I think this criterion doesn't apply. In that case, you should return back in a phased manner, like @Als says...
6,375,121
6,375,211
When using boost::thread::interrupt(), do you *need* to catch the thread_interrupted exception?
I've got several long running boost threads that I want to be able to shut down by interrupting them. All of the documentation I can find says that you can catch the thread_interrupted exception, but it doesn't really say what happens if you don't. I would assume it kills the thread (and hopefully the thread gets prop...
The exception is just like any other C++ exception. If you choose not to catch it, it will cause the same effect as any other unhandled exception. If left uncaught, it will not propagate to the main thread, but could cause other undesirable behaviour. On Visual C++, by default this will terminate your process, for e...
6,375,213
6,375,292
How to redirect file operations calls?
We write a programm. From some point we want to make all operations related to files like opening file, writting to file, reading from file (normal FS calls via standart c++ API) instead of calling some OS default FS api's call our own functions. How to make such thing? How to protect it from assembler hacks? and how t...
You might be interested in writing your own file system filter that would handle that. Such a filter could then decide if it should intercept the function call basing on your criteria or it should just forward the call down to the actual file system.
6,375,383
6,375,872
What's the best language for real-time graphics programming on Android?
Some googling has led me to believe that C++ is the best language for real-time 2D graphics programming, but since the Android is Java-based, is that still the best option? Or us the fact that I have to use NDK going to slow it down or something? My program also has a lot of scientific computing and I know C++ is best/...
Android applications are written Java, yes - however the Android NDK allows you to write performance-critical sections of your program in C or C++. From the Android NDK website, The Android NDK is a companion tool to the Android SDK that lets you build performance-critical portions of your apps in native code. I...
6,375,411
6,375,830
Linking POCO C++ Library gives numerous memory leaks
I've just started trying to integrate the Poco C++ Library with our game engine, however every time I link /usr/lib/libPocoFoundation.so my program suddenly has 51 memory leaks. Removing the link option gets rid of all the leaks (none of them are from my code). This happens even if I remove all Poco #includes from my c...
You don't say what tool is telling you that you have memory leaks, but I'm going to presume that it is valgrind since you are on Ubuntu. If the leaks occur even if you aren't calling any POCO methods, then it is likely that these are one-off allocations occurring during the static initialization of the POCO library tha...
6,375,423
6,376,119
Why My Flatten Shader (from Lighthouse3d Tutorial) Is Not Working?
The tutorial has an example called the Flatten Shader, which displays the GLUT teapot as a flatten teapot. Here is the link to the Flatten Shader. I have done everything exactly like the steps mentioned in the tutorial, but my teapot is not flat like how the teapot in the tutorial looks like. It just looks like a norma...
A few things: You are not binding your shaders correctly. Your createProgram function needs to bind both the fragment shader and the vertex shader together. You should replace it with code that looks like this: GLuint createProgram ( const GLuint fshader, const GLuint vshader ) { GLuint program = glCreateProgra...
6,375,472
6,375,506
Overloading post-increment operator
MyClass MyClass::operator++(int) { return ++(*this); } That's the code I have written. I works correctly, but all tutorials say that I have to create a temporary object and return it: MyClass MyClass::operator++(int) { MyClass tmp = *this; ++(*this); return tmp; } Please tell me which way is the best?...
Second One! Post Increment means that the variable is incremented after the expression is evaluated. Simple example: int i = 10; int j = i++; cout<<j; //j = 10 cout<<i; // i = 11 Your First example would make j = 11, which is incorrect.
6,375,530
6,375,597
declaring a 2d array of pointers that point to different strings (in a 2d array)
I actually need to sort a lot of words according to their lengths. So the words get stored in a 2d array. Now rather than having words itself in the sorted form I want to have a pointer to each word which can be stored in a 2d array where rows represent length of word -1 and columns no. of words -1. so words are in ...
Why not make a std::multimap<std::string, LenghtComparator>, where LengthComparator is a predicate that returns s1.length() < s2.length()? Then you can retrieve an equal_range of all words of a given length.
6,375,631
6,375,666
printf string output "Dz↕" getch() C++
I want the output to say what arrow key the user pressed. The output I get is: "You pressed the Dz↕ button." What I wrote was: unsigned int key; string K; do { key = getch(); if (key==72) K=" up"; else if(key==80) K="down"; else if (key==77) K="right"; else if (key==75) ...
should do std::cout << "You have pressed " << K << " button." << std::endl; You have mixed string object type with printf. printf only accepts a char * or char [] with the %s format string. Or you might want to access the c string associated with the string object with K.c_str () printf ("\ntest %s", K.c_str ());
6,375,634
6,375,679
Restrict parameter type in template instantiation
I'm trying to trigger a compile time error if the user of my library tries to instantiate a template with a type that is not appropriate. I've implemented: template <typename T> struct good_type { enum { value = false }; }; template <> struct good_type<string> { enum { value = true }; }; template <> struct good_type<...
You can use boost::enable_if, along with typelist. Define a typelist which contains all the types which you want to support, and write some metafunction(s), to check if a given type exists in the list or not, and then pass the value which metafunction returns to enable_if, so as to enable/disable the class. Alright, ...
6,375,697
6,375,794
Do I have to return a reference to the object when overloading a pre-increment operator?
Can I use: MyClass& MyClass::operator++ () { a++; // private var of MyClass return (*this); } Or it can be: MyClass MyClass::operator++ (); What's the difference? Thanks for answers. I have another issue. Many people do something like that: MyClass& MyClass::operator++(); MyClass MyClass::operator++(int); ...
No, you don't have to return the reference to your object when you overload the pre-increment operator. In fact you may return anything you'd like, MyClass, int, void, whatever. This is a design issue -- you must ask yourself what is the most useful thing to the users of your class that you are able to return. As a gen...
6,375,829
6,376,286
Visual Studio plugin to find out which files are being included implicitly
A particular header file may only be including "Foo.h" but Foo.h is including other headers which implicitly include many other headers. I would like to know all the headers that a particular file is including. In case anybody is wondering why a plugin for Visual Studio; simply because of the way the include directori...
I don't know of any plugins that do this, but you could whip up a homebrew solution by turning on the showIncludes flag in your projects settings, then doing a full build and parsing the output. The indentation changes based on the nesting of the includes.
6,376,000
6,376,060
How does this Array Size Template Work?
I came across this snippet template <typename T, size_t N> char (&ArraySizeHelper(T (&array)[N]))[N]; #define arraysize(array) (sizeof(ArraySizeHelper(array))) in this article http://software.intel.com/en-us/articles/pvs-studio-vs-chromium/ I've seen other templates to do the same thing, like this one Use templat...
The function template is named ArraySizeHelper, for a function that takes one argument, a reference to a T [N], and returns a reference to a char [N]. The macro passes your object (let's say it's X obj[M]) as the argument. The compiler infers that T == X and N == M. So it declares a function with a return type of cha...
6,376,177
6,436,556
boost::spirit - parsing AST style from randomly placed entries
I have this data in my file: #TITLE:Destiny; #SUBTITLE:; #ARTIST:Smiley; #BACKGROUND:bg.png; #SAMPLESTART:43.960; #SAMPLELENGTH:12.000; I want to parse it using AST into a structure like this: struct data { std::string title, subtitle, artist, background; double samplestart, samplelength; }; Note: the entries i...
I'd suggest to utilize the permutation parser (see here), which allows to match a bunch of alternatives in any sequence.
6,376,580
6,376,743
What standard clause mandates this lvalue-to-rvalue conversion?
Given: int main() { int x = 0; int y = x; // <--- } Could someone please tell me which clause of the standard (2003 preferred) mandates the conversion of the expression x from lvalue to rvalue in the initialisation of the object y? (Or, if I'm mistaken and no such conversion takes place, then I'd like to learn t...
I find it easier (if maybe not 100% precise) to think of lvalue-s as real objects and rvalue-s as the value stored in the object. The expression x is an lvalue expression that refers to the object x defined in the first line, but when used as the right hand side of an assignment to a type that is not a user defined typ...
6,376,840
6,376,867
fread-ing uint16 in C++?
I'm trying to read use fread to read in values from an external file in C++. The values are stored as uint16's, which does not seem to exist in C++. I did some googling and found people using typedef to make their own uint16, but I'm also wondering if I could just use fread(ptr, uint8, 2, file) to read two uint8's to b...
You probably want: fread(ptr, sizeof(uint8), 2, file) Seems OK to me, fread(ptr, 1, 2, file) is even better. Or fread(ptr, sizeof(uint16_t), 1, file). I assume that ptr is a pointer pointing to the location where you want to store your data, not the variable itself (if so - use &ptr). Reading two bytes at a time thoug...
6,377,160
6,377,634
Link library based on build configuration [cmake]
Possible Duplicate: Debug and Release Library Linking with CMAKE (VISUAL STUDIO) cmake newb here, I would like to tell target_link_libraries to link a debug lib when using the debug configuration and link to a release lib when compiling under the release configuration. How do I tell cmake to link a different lib fil...
The solution is: SET(LINK_LIBRARY optimized Foo debug Foo_d) target_link_libraries(MyEXE ${LINK_LIBRARY})
6,377,204
6,377,275
Compiling C++ code with allegro 5 and g++
What flags do I need to add to g++ in order to compile code using allegro 5? I tried g++ allegro5test.cpp -o allegro5test `allegro-config --libs` but that is not working. I'm using ubuntu 11.04. I installed allegro 5 using the instructions at http://wiki.allegro.cc/index.php?title=Install_Allegro5_From_SVN/Linux/Debia...
So you successfully installed allegro5 on your system from the SVN. One thing you should know is that this build doesn't come with allegro-config. If you have it on your system it means you have previously installed allegro4. allegro5 brings many changes, including different initialization procedures, library and funct...
6,377,544
6,377,579
Stack push causes critical error
I am new to C++ and working with STL container at the moment. I got a serious problem executing a nodeStack.push(startnode) - the compiler shows up a Critical error detected c0000374 Followign code shows the function where the mentioned error occurs: vector<int> Graph::iterativeDepthSearch(map<int, vector<int>> adj...
try int* val = new int[adjlist.size()]; you are currently allocating a single int and initializing its value, not allocating an array of ints. The stack structure is corrupting because it is next to your pointer in the memory stack.
6,377,767
6,377,826
Deletion of stack variable in C++
In C++, if we declare a stack variable inside of a function, is it automatically deleted at the end of the function or is it deleted at the end of the program execution? Also, is the answer to this question the same for the C language?
For stack-declared variables, the destructor is called and the memory reclaimed as it falls out of scope. Note that this doesn't mean at the end of the function if the variable is declared in an inner block, like an if-statement or loop. int main(int argc, char **argv) { int a = 3; if (argc > 1) { ...
6,377,786
6,377,869
C++ Operator Overloading in expression
I'm sure this has already been answered somewhere, but I don't know what to search for. I have the following situation. I made a Vector class and overloaded the "*" (multiply by escalar) and the "+" operators (add two vectors). Now, the following line of code: Vector sum = (e_x*u_c) + (e_y*u_r); This gives me the foll...
Replace Vector& right with const Vector& right. The expression (e_x*u_c) is an rvalue, and references to non-const won't bind to rvalues. Also, the member functions themselves should be marked const as well: Vector Vector::operator+(const Vector& right) const { return Vector(x + right.x, y + right.y, z + right.z); ...
6,378,098
6,378,403
How to prevent an app from being pinned in Windows 7?
I am trying to prevent the user from pinning my .NET app to the taskbar. I've found some code on the Old New Thing that does just that. However, it is in C++. #include <shellapi.h> #include <propsys.h> #include <propkey.h> HRESULT MarkWindowAsUnpinnable(HWND hwnd) { IPropertyStore *pps; HRESULT hr = SHGetPropertyS...
You can download the Windows API Code Pack which has the necessary p/invoke calls you need to translate the code in your post to C#. Either use the library in whole or find the specific calls and definitions you require (search it for SHGetPropertyStoreForWindow and then its other dependencies).
6,378,409
6,378,546
What's going on here? Am I losing const-ness?
I have a Singleton class here designed to be inherited by classes wanting to use it. But I have a question about something the compiler is allowing and I don't understand why: template<class DerivedT> class Singleton { static DerivedT*& internalPointer() { static DerivedT* object(nullptr); return object; } ...
I think the question is: Why does the compiler allow me to declare a const Singleton? I'm assuming you are wondering how the compiler can let you create a const Singleton when you only want to have pointers to a non-const Singleton. If you declare a const instance of a class that has a constructor, it still needs to be...
6,378,550
6,378,736
Assertion fails/Exceptions for STL
Suppose I've an empty list L. Currently if I run L.front(), it will merrily execute returning a garbage value. Is there some option I can turn on such that executing this would throw an exception or result in an assertion failure? Thanks
GCC STL checked iterators MSVC checked iterators ( on by default ) STLPort debug mode, with checked iterators Previous question on the same subject
6,378,584
6,378,627
multithreading object-oriented socket code with timeout
We have a nice class that establishes a socket connection and then hits it repeatedly. If it ever gets a timeout, we want to throw an exception. What I'd like is an independent timeout for each object. However, as noted in other posts there is no portable socket timeout code. Socket Timeout in C++ Linux I am currently...
You can do that by using async I/O. For example, using libevent or asio. Just fire up a read operation and a timer on the same dispatching thread (I/O service).
6,378,738
6,378,770
portable unsigned long in C/C++
Is there portable unsigned long in C++? Is there a way to make a portable structures? On my home machine unsigned long is 8 bytes. On work machine its 4 bytes. When you start at home applications that are written on work there is a problem of correctness of data transmitted over the network. Thanks.
#include <stdint.h> for the following typedefs: (u)int8_t (u)int16_t (u)int32_t (u)int64_t While the last may or may not be available, depending on the platform.
6,378,849
6,421,278
Adobe Adam and Eve, C++: How to create a clickable button, trackbar, text input field and an image?
So I found out that I need a gui for my app. I have a crossplatform video broadcaster. (Linux, Windows, Mac OS X). I use a lot of boost and thought give ASL a shot. But I found out there are no tutorials on how to do what I need. So I ask you to help me with one - how to create a new window with clickable button (on cl...
ASL delivers some examples by itslef (in LIB_ROOT/test directory).There are open source application "mission photo" which uses asl too, but I don't know how good its sourcecode is. Anyway, here is the link http://www.missioncode.org/#Welcome. Good look !
6,379,166
6,404,847
How to extract Virtual Table informations from a shared library?
I'm implementing a performance analysis tool. One thing that I'm doing is to estimate the cost of a function call. In order to do that, I need to know if a given function is virtual in a shared library. For that, I have access to the shared library assembly. I have also a call graph of the execution. I cannot make any...
Finally we found a way to do that. It was not so complicated. In our case, the virtual tables addresses are in the .dynsym section of the ELF shared library file. And then the content of the virtual table is available on the .rela.dyn section. So we have to find the address and the size of every virtual table and then ...
6,379,193
6,384,688
What API is available to create a Drive on the Windows File System?
I'm basically looking for an example of the API used by, for example, an external USB hard drive driver that adds a new Drive to the file system on Windows. Thanks!
The file system is really implemented by a stack of drivers. For instance, the USB drive is first handled by the USB Mass Storage driver. Since an USB drive may contain multiple partitions, with different file systems, you can have multiple file system drivers in parallel, and you'd have multiple drives show up in Expl...
6,379,237
6,380,612
C++ class for application/program settings?
Using Visual Studio C++ with MFC. I'm trying to figure out what would be a good way to store application/program settings. I'm not referring to their persistent storage but to the data structure used in code to hold the settings. I created a static class called Settings that has several static methods and also neste...
You can do this if it works for you. You can ditch the enum and go to const strings or even free-form strings. The enum doesn't really have to be defined in the class either. There are lots of ways to do it. Another class could do something similar with multiple instances using a template to define the enum type if ...
6,379,336
6,379,604
Fast file writing in C++
I'm working in a system that use PHYSFS to search files. The problem is that now I need to deploy files (that is, to copy a phisical copy of the file into a directory). My first solution is open file, load into memory and then write to another file, but I think that it would exists a faster method to deploy files. Any ...
In general, yes, going through each file, reading it and then writing it is what you want. Note that you probably shouldn't load the entire file into memory at once, though - instead use PHYSFS_read to read a fixed buffer (64kb or so should be good) from the source file, write it to the destination file, and repeat.
6,379,422
6,379,437
C++ Multiple classes with same name
Say I have two different cpp files. Both declare classes with the same name, but perhaps a totally different structure (or perhaps the same structure, different implementation). The classes do not appear in the header files. (As an example, suppose they are Node classes for different list classes.) I've seen these clas...
The standard way around this problem is to wrap the classes in different namespaces.
6,379,443
6,379,647
using a mutex as a condition variable
Given the canonical example for condition variables pthread_mutex_lock(&count_mutex); pthread_cond_wait(&count_threshold_cv, &count_mutex); Then I can send a signal from another thread, and this thread will continue. But I fail to see whats wrong with just trying to lock a mutex, and if the lock is taken then the thre...
Let's make this concrete. Your suggested alternative to condition variables is for the "waiter" to do this: loop: lock mutex check predicate if (predicate is false) unlock mutex sleep a bit // (is this what you had in mind?) goto loop And for the "signaler" to do this: lock mut...
6,379,508
6,380,460
how to call a function when auto_ptr is a parameter of it!
#include <iostream> #include <memory> class test { private: int x , y; public: test(int a , int b):x(a),y(b){} void fun() { std::cout<< x<<" "<<y<<" "<<std::endl; } }; void show(std::auto_ptr<test> t1) { t1->fun(); } int main() { show(new te...
James explained how to resolve the problem. But the reason auto_ptr was designed so that you can not do this: show(new test(3,4)); Is because this is a bad idea. Even this (if it were allowed): show(std::auto_ptr<test>(new test(3,4))); Would be a bad idea. So you ask why. Well in the normal situation not a big deal. ...
6,379,866
6,379,946
C/C++ equivalent for Matlab's imtransform?
Is there something equivalent to matlab's imtransform in C++? I'm having a hard time wrapping my head around the code for imtransform in matlab, and I'm trying to use or rewrite it in C++. edit: Not built into C++, but any libraries that you may know of which would do the same thing would be great
Check out OpenCV. I don't remember whether it has that exact transform, but it has a lot of related code to take a look at (it's open source).
6,379,921
6,568,142
Compiling native C++ module for Node.js, linking to openSSL/libcrypto fails
I'm using Cygwin/Windows and I'm trying to build a native module for node.js. I intend to make use of the OpenSSL Library. I have installed openssl from the Cygwin package manager. I have the following lines in my .cc file: #include <openssl/dh.h> and DH* public_dh_key = DH_new(); But when I try to link/compile i...
Adding -lcrypto should do the trick. According to the nm output on my system _DH_new and _HMAC seem to be in the libcrypto (part of OpenSSL) dynamic library : jhacktheripper@macbook-prolocal:~$ nm /usr/lib/libcrypto.dylib | grep _DH_new 0000000000036360 T _DH_new 0000000000036120 T _DH_new_method jhacktheripper@macbo...
6,379,992
6,380,157
How can I instantiate a C++ template with a class with specific methods
Let's say we have a class class X { public: void my_method() { std::cout << "I'm X"; } } and we have a template class: template<typename T> class Y { public: void put(typename T item) { item.my_method(); } }; I want to execute item.my_method(); if the class Y is instantiated with a X class (if not there wou...
Not sure I fully understand the question because what you have works. class X { public: void my_method() { std::cout << "I'm X"; } }; class Z { }; template <typename T> class Y { public: void put(T item) { item.my_method(); } }; int main(int argc, char* argv[]) { // This compiles fine X theX; Y<X...
6,380,191
6,380,201
C++: variable declaration with 3 asterisks
double ***x; what does it mean to declare declare a variable with three asterisks? Is this a pointer to a pointer to a pointer to a double?
It is a pointer to a pointer to a pointer to a double.
6,380,274
6,380,298
how to copy data in buffer?
I am working on network programming using epoll and I have this code. int str_len = read(m_events[i].data.fd, buf, BUF_SIZE); printf("read %d \n", str_len); if(str_len == 0){ if(!removeClient(m_events[i].data.fd)) break; close(m_ev...
Yes, you can copy the data: char* pdata = new char[str_len]; memcpy(pdata, buf, str_len); pushWork(pdata); At the pushWork end, it has to take care of freeing the data when it's done: delete[] pdata; You will also want to consider encapsulating this all into a std::vector so you don't have to worry about exception s...
6,380,326
6,380,358
C++ symbol export for class extending template class
I'm working on a C++ project built with Visual Studio 2008. I'm defining (in a project producing a dll) a template class and a derived, not-template, one: template <class T> struct DLL_EXPORT Base { int base() { return 1; } }; struct DLL_EXPORT Deriv: public Base<Deriv> { int deriv() { return 1; } }; the DLL_EXPO...
I don't know much about this, but I think you might be able to fix it by writing template struct Base<Derive>; somewhere in your source file. (or perhaps template DLL_EXPORT struct Base<Derive>;)
6,380,417
6,380,507
Duplicating C/C++ functions at compile time
If I have a function A(), I am interested in finding a convenient method to create a function B() that has the exact same functionality as A(), differing only in name. The new function would be for a one-time use. The intent is to differentiate between calls to the same function in a somewhat primitive sampling profi...
Using templates template<int x> void A() { // .. } int main() { A<0>(); A<1>(); return 0; } Update The compiler can be too smart and create only one body for A<0> and A<1>. At least Visual C++ 2010 does it in Release mode. To prevent it, just use the template parameter inside the function template bod...