question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,050,805
3,050,819
pointer to const member function typedef
I know it's possible to separate to create a pointer to member function like this struct K { void func() {} }; typedef void FuncType(); typedef FuncType K::* MemFuncType; MemFuncType pF = &K::func; Is there similar way to construct a pointer to a const function? I've tried adding const in various places with no success. I've played around with gcc some and if you do template deduction on something like template <typename Sig, typename Klass> void deduce(Sig Klass::*); It will show Sig with as a function signature with const just tacked on the end. If to do this in code it will complain that you can't have qualifiers on a function type. Seems like it should be possible somehow because the deduction works.
You want this: typedef void (K::*MemFuncType)() const; If you want to still base MemFuncType on FuncType, you need to change FuncType: typedef void FuncType() const; typedef FuncType K::* MemFuncType;
3,050,811
3,050,911
Why should virtual functions not be used excessively?
I just read that we should not use virtual function excessively. People felt that less virtual functions tends to have fewer bugs and reduces maintenance. What kind of bugs and disadvantages can appear due to virtual functions? I'm interested in context of C++ or Java. One reason I can think of is virtual function may be slower than normal functions due to v-table lookup.
You've posted some blanket statements that I would think most pragmatic programmers would shrug off as being misinformed or misinterpreted. But, there do exist anti-virtual zealots, and their code can be just as bad for performance and maintenance. In Java, everything is virtual by default. Saying you shouldn't use virtual functions excessively is pretty strong. In C++, you must declare a function virtual, but it's perfectly acceptable to use them when appropriate. I just read that we should not use virtual function excessively. It's hard to define "excessively"... certainly "use virtual functions when appropriate" is good advice. People felt that less virtual functions tends to have fewer bugs and reduces maintenance. I'm not able to get what kind of bugs and disadvantages can appear due to virtual functions. Poorly designed code is hard to maintain. Period. If you're a library maintainer, debugging code buried in a tall class hierarchy, it can be difficult to trace where code is actually being executed, without the benefit of a powerful IDE, it's often hard to tell just which class overrides the behavior. It can lead to a lot of jumping around between files tracing inheritance trees. So, there are some rules of thumb, all with exceptions: Keep your hierarchies shallow. Tall trees make for confusing classes. In c++, if your class has virtual functions, use a virtual destructor (if not, it's probably a bug) As with any hierarchy, keep to a 'is-a' relationship between derived and base classes. You have to be aware, that a virtual function may not be called at all... so don't add implicit expectations. There's a hard-to-argue case to be made that virtual functions are slower. It's dynamically bound, so it's often the case. Whether it matters in most of the cases that its cited is certainly debatable. Profile and optimize instead :) In C++, don't use virtual when it's not needed. There's semantic meaning involved in marking a function virtual - don't abuse it. Let the reader know that "yes, this may be overridden!". Prefer pure virtual interfaces to a hierarchy that mixes implementation. It's cleaner and much easier to understand. The reality of the situation is that virtual functions are incredibly useful, and these shades of doubt are unlikely coming from balanced sources - virtual functions have been widely used for a very long time. More newer languages are adopting them as the default than otherwise.
3,050,835
3,050,991
Rewriting a simple Pygame 2D drawing function in C++
I have a 2D list of vectors (say 20x20 / 400 points) and I am drawing these points on a screen like so: for row in grid: for point in row: pygame.draw.circle(window, white, (particle.x, particle.y), 2, 0) pygame.display.flip() #redraw the screen This works perfectly, however it's much slower then I expected. I want to rewrite this in C++ and hopefully learn some stuff (I am doing a unit on C++ atm, so it'll help) on the way. What's the easiest way to approach this? I have looked at Direct X, and have so far followed a bunch of tutorials and have drawn some rudimentary triangles. However I can't find a simple (draw point).
DirectX doesn't have functions for drawing just one point. It operates on vertex and index buffers only. If you want simpler way to make just one point, you'll need to write a wrapper. For drawing lists of points you'll need to use DrawPrimitive(D3DPT_POINTLIST, ...). however, there will be no easy way to just plot a point. You'll have to prepare buffer, lock it, fill with data, then draw the buffer. Or you could use dynamic vertex buffers - to optimize performance. There is a DrawPrimitiveUP call that is supposed to be able to render primitives stored in system memory (instead of using buffers), but as far as I know, it doesn't work (may silently discard primitives) with pure devices, so you'll have to use software vertex processing. In OpenGL you have glVertex2f and glVertex3f. Your call would look like this (there might be a typo or syntax error - I didn't compiler/run it) : glBegin(GL_POINTS); glColor3f(1.0, 1.0, 1.0);//white for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) glVertex2f(points[y][x].x, points[y][x].y);//plot point glEnd(); OpenGL is MUCH easier for playing around and experimenting than DirectX. I'd recommend to take a look at SDL, and use it in conjuction with OpenGL. Or you could use GLUT instead of SDL. Or you could try using Qt 4. It has a very good 2D rendering routines.
3,051,042
3,051,200
How might one implement FileTimeToSystemTime?
I'm writing a simple wrapper around the Win32 FILETIME structure. boost::datetime has most of what I want, except I need whatever date type I end up using to interpolate with Windows APIs without issues. To that end, I've decided to write my own things for doing this -- most of the operations aren't all that complicated. I'm implementing the TimeSpan - like type at this point, but I'm unsure how I'd implement FileTimeToSystemTime. I could just use the system's built-in FileTimeToSystemTime function, except FileTimeToSystemTime cannot handle negative dates -- I need to be able to represent something like "-12 seconds". How should something like this be implemented? Billy3
Windows SYSTEMTIME and FILETIME data types are intended to represent a particular date and time. They are not really suitable to represent time differences. Time differences are better of as a simple integer representing the number of between two SYSTEMTIMEs or FILETIMEs. might be seconds, or something smaller if you need more precision. If you need to display a difference to users, simple division and modulus can be used to compute the components. std::string PrintTimeDiff(int nSecDiff) { std::ostringstream os; if (nSecDiff<0) { os << "-"; nSecDiff= -nSecDiff; } int nSeconds = nSecDiff % (24*60*60); nSecDiff /= 60; int nMinutes = nSecDiff % (24*60) nSecDiff /= 60; int nHours = nSecDiff % 24; int nDays = nSecDiff / 24; os << nDays << " Days " << nHours << ":" << nMinutes << ":" << nSeconds; return os .str(); }
3,051,204
3,051,265
strerror_r returns trash when I manually set errno during testing
During testing I have a mock object which sets errno = ETIMEDOUT; The object I'm testing sees the error and calls strerror_r to get back an error string: if (ret) { if (ret == EAI_SYSTEM) { char err[128]; strerror_r(errno, err, 128); err_string.assign(err); } else { err_string.assign(gai_strerror(ret)); } return ret; } I don't understand why strerror_r is returning trash. I even tried calling strerror_r(ETIMEDOUT, err, 128) directly and still got trash. I must be missing something. It seems I'm getting the gnu version of the function not the posix one, but that shouldn't make any difference in this case. Edit I'm on Ubuntu 8.04. glibc version looks like 2.7 in features.h.
According to this page, http://linux.die.net/man/3/strerror_r, if you're using the GNU version of strerror_r(), the function might decide to not store anything at all into the buffer you provide; you'd need to use the string returned from the function (seems like a rather bizarre interface): The GNU-specific strerror_r() returns a pointer to a string containing the error message. This may be either a pointer to a string that the function stores in buf, or a pointer to some (immutable) static string (in which case buf is unused). If the function stores a string in buf, then at most buflen bytes are stored (the string may be truncated if buflen is too small) and the string always includes a terminating null byte. So if you happen to be using the GNU version you can't rely on your err buffer to have anything useful put into it, unless strerror_r() returns the address of err.
3,051,479
3,052,252
How do I cast Qt's QVariant to boost::any?
How do I cast Qt's QVariant to boost::any?
i dont think there is an easy way, i would do following: boost::any qvariant_to_any(const QVariant& v) { switch(v.userType()) { case QVariant::Bool: return boost::any(v.value<bool>()); //or: return boost::any(v.toBool()); case QVariant::Int: return boost::any(v.value<int>()); //or: return boost::any(v.toInt()); case QVariant::UInt: return boost::any(v.value<unsigned>()); // ... // all your types which store in a QVariant in your use case case QVariant::Invalid: default: throw std::bad_cast(); //or return default constructed boost::any } } if Boost.Variant would do the job aswell instead of Boost.Any, in a german magazin there was a nice article about converting QVariant to Boost.Variant and vice versa, take a look at the source code if this interrests you: german article: http://www.heise.de/developer/artikel/Konvertierungen-992950.html source: ftp://ftp.heise.de/pub/ix/developer/elfenbein.zip
3,051,483
3,051,763
Is this a MinGW bug?
I have been trying to execute this program on my MinGW, through Code::Blocks: #include <string.h> #include <math.h> #include <stdio.h> #define N 100 int p[N]; int pr[N]; int cnt; void sieve() { int i,j; for(i=0;i<N;i++) pr[i]=1; pr[0]=pr[1]=0; for(i=2;i<N;i++) if(pr[i]) { p[cnt]=i; cnt++; for(j=i+i;j<=N;j+=i) pr[j]=0; } } int main(){ sieve(); int i; for(i=0;i<cnt;i++) printf("%d ",p[i]); puts(""); printf("Total number of prime numbers : %d",cnt); return 0; } On my system the output is: 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 Total number of prime numbers : 22 Which is completely insane, since I am completely sure about the implementation of my algorithm. So I decided to try it in Ideone where it gives correct output. Can anybody point out the reason ? I changed it to N, but the output doesn't change.
There are two important bugs in your code. One is that your p array is too small, so you are writing off the end of it. This is undefined behaviour, though on the platforms you are using it overwrites the start of the pr array. This has no effect on the output, since the location you are overwriting is before the location you are testing in the sieve. The other is that you are also writing off the end of your pr array: for(j=i+i;j<=N;j+=i) pr[j]=0; This loops sets pr[N] to zero, which is off the end of pr. In MinGW this is where cnt is stored, so each time i divides N, cnt is set to zero. As N is 100, this happens for i==2 and i==5, so you lose the primes before five from your result. IdeOne seems to put cnt somewhere else in relation to pr, so it does not get overwritten. This is why you get different output with the different compilers. Change the size of the array p to N, or use only one array for both sieve and output, and change <= in line 18 to < so you don't write off the end of it. int p[N]; int *pr = p; // reuse the array
3,051,776
3,052,022
While within a switch block
I've seen the following code, taken from the libb64 project. I'm trying to understand what is the purpose of the while loop within the switch block - switch (state_in->step) { while (1) { case step_a: do { if (codechar == code_in+length_in) { state_in->step = step_a; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar = (fragment & 0x03f) << 2; case step_b: do { if (codechar == code_in+length_in) { state_in->step = step_b; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar++ |= (fragment & 0x030) >> 4; *plainchar = (fragment & 0x00f) << 4; case step_c: do { if (codechar == code_in+length_in) { state_in->step = step_c; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar++ |= (fragment & 0x03c) >> 2; *plainchar = (fragment & 0x003) << 6; case step_d: do { if (codechar == code_in+length_in) { state_in->step = step_d; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar++ |= (fragment & 0x03f); } } What can give the while? It seems that anyway, always the switch will perform only one of the cases. Did I miss something? Thanks.
Although this is Duff's Device, this version is not about implementing a loop-unrolling optimisation but rather to implement an iterator over a Base64 encoded stream. So you can do something like this: Base64Stream stream; // the base64 data char c; while ((c == stream->NextChar ()) != 0) { // do something with c } In the given code, the first switch us used to jump back to where the previous return exited, and then the while (1) allows the iteration loop to continue indefinately. However, there's no protection against a buffer overrun in this function. In C#, there is a neater solution to this, the yield statement.
3,052,028
3,052,990
Detect pointer arithmetics because of LARGEADDRESSAWARE
I would like to switch my application to LARGEADDRESSAWARE. One of issues to watch for is pointer arithmetic, as pointer difference can no longer be represented as signed 32b. Is there some way how to find automatically all instances of pointer subtraction in a large C++ project? If not, is there some "least effort" manual or semi-automatic method how to achieve this?
As our code already compiles with GCC, I think perhaps the fastest way might be: build a GCC create a custom modification of GCC so that it prints warning (or error) whenever pointer subtraction is detected build the project and gather all warnings about pointer subtraction Here is the outline of changes which need to be done to GCC for this: Add your warnings into: c-typeck.c (pointer_diff function) cp/typeck.c (pointer_diff function). Besides of directly detecting pointer subtraction, another thing to do can be to detect cases where you first convert pointers to integral types and then subtract them. This may be more difficult depending on how is your code structured, in out case regexp search for (.intptr_t).-.*-(.*intptr_t) has worked quite well.
3,052,138
3,052,287
Pause the log4c++ logger
is it possible to pause the logger in log4c++, and by pause I mean to stop writing messages in the log file but not finalize the logger object or delete it. thanks in advance
I think you can change the level with setLevel() to OFF
3,052,158
3,052,246
Socket send recv functions
I have created a socket using the following lines of code. Now i change the value of the socket i get like this m_Socket++; Even now the send recv socket functions succeeds without throwing SOCKET_ERROR. I expect that it must throw error. Am i doing something wrong. struct sockaddr_in ServerSock; // Socket address structure to bind the Port Number to listen to char *localIP ; SOCKET SocServer; //To Set up the sockaddr structure ServerSock.sin_family = AF_INET; ServerSock.sin_addr.s_addr = INADDR_ANY; ServerSock.sin_port = htons(pLantronics->m_wRIPortNo); // To Create a socket for listening on wPortNumber if(( SocServer = socket( AF_INET, SOCK_STREAM, 0 )) == INVALID_SOCKET ) { return FALSE; } //To bind the socket with wPortNumber if(bind(SocServer,(sockaddr*)&ServerSock,sizeof(ServerSock))!=0) { return FALSE; } // To Listen for the connection on wPortNumber if(listen(SocServer,SOMAXCONN)!=0) { return FALSE; } // Structure to get the IP Address of the connecting Entity sockaddr_in insock; int insocklen=sizeof(insock); //To accept the Incoming connection on the wPortNumber pLantronics->m_Socket=accept(SocServer,(struct sockaddr*)&insock,&insocklen); if(pLantronics->m_Socket == INVALID_SOCKET) { shutdown(SocServer, 2 ); closesocket(SocServer ); return FALSE; } // To make socket non-blocking DWORD dwNonBlocking = 1; if(ioctlsocket( pLantronics->m_Socket, FIONBIO, &dwNonBlocking )) { shutdown(pLantronics->m_Socket, 2); closesocket(pLantronics->m_Socket); return FALSE; } pLantronics->m_sModemName = inet_ntoa(insock.sin_addr); Now i do m_Socket++;//change to some other number ideally expecting send recv to fail. Even now the send recv socket functions succeeds without throwing SOCKET_ERROR. I expect that it must throw error. Am i doing something wrong.
It's because of the peculiar nature of Windows handles -- when created they are divisible by four and when used their two lowest bits are ignored. Incrementing a handle by one will make m_Socket refer to the same socket as before (only when you increment by four will the function return an error -- unless there is another handle with that value open). You should not probe for open handles in this manner. While there are other ways to enumerate open handles, you shouldn't use them. Do not depend on the system to keep track of your handles -- track them yourself.
3,052,298
3,052,321
Strange iterator behaviour
#include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { string s = "Haven't got an idea why."; auto beg = s.begin(); auto end = s.end(); while (beg < end) { cout << *beg << '\n'; if (*beg == 'a') {//whithout if construct it works perfectly beg = s.erase(beg); } ++beg; } return 0; } Why if I erase one or more chars from this string this code breaks? I suppose it has something to do with returned iterator after erase operation being created at higher address than end iterator but I'm not sure and it surely isn't right behaviour. Or is it?
There are several problems with this code. Don't cache the value of s.end(); it changes as you delete elements. Don't use beg < end. The idiomatic approach is to write beg != end. If you try to iterate past end, the result is undefined, and a debug version of the string library may deliberately crash your process, so it is meaningless to use <. The iterator returned from s.erase(beg) might be s.end(), in which case ++beg takes you past the end. Here's a (I think) correct version: int _tmain(int argc, _TCHAR* argv[]) { string s = "Haven't got an idea why."; for (auto beg = s.begin(); beg != s.end();) { cout << *beg << '\n'; if (*beg == 'a') {//whithout if construct it works perfectly beg = s.erase(beg); } else { ++beg; } } } EDIT: I suggest accepting FredOverflow's answer. It is simpler and faster than the above.
3,052,415
3,052,618
Template class that refers to itself as a template template parameter?
This code: template <template <typename> class T> class A { }; template <typename T> class B { A<B> x; }; doesn't compile, I suppose since A<B> is interpreted as A<B<T> > within B's scope. So, how do you pass B as a template template parameter within it's scope?
Try this: template <typename T> class B { A< ::B > x; // fully qualified name for B }; According to C++ Standard 14.6.1/2 you should use the normal name of the template (i.e., the name from the enclosing scope, not the injected-class-name).
3,052,467
3,059,767
How to iterate over a STL set and selectively remove elements?
The following code does not work correctly. How should it be done correctly? for (std::set<Color>::iterator i = myColorContainer.begin(); i!=myColorContainer.end(); ++i) { if ( *i == Yellow) { DoSomeProccessing( *i ); myColorContainer.erase(i); } }
You don't need a loop as youre dealing with a set. std::set<Color>::iterator it = myColorContainer.find(Yellow); if (it != it.myColorContainer.end()){ DoSomeProcessing(*it); myColorContainer.erase(it); }
3,052,486
3,052,596
sending sms from windows application
I am creating a windows application which needs to send some sms to mobile phone.This is just for testing purpose. Now can I use my cell phone to get this done. I have android phone which can be connected to pc using USB. Application is created in C++, windows api. Any pointers will help
You can write a simple android application that runs in the background that checks for text files. When you want to send an SMS just push a new text file with the phone number and the message onto the sd card. You can use the android SDK 'adb push' command for that. It's a hacky way tho, wouldn't recommend it unless it's just for basic testing Another option is using an online gateway such as Twilio. It's super easy to set up and allows you to easily send messages through an easy to use HTTP api. You can use CURL to connect to a HTTP site through C++.
3,052,579
3,052,604
Explicit specialization in non-namespace scope
template<typename T> class CConstraint { public: CConstraint() { } virtual ~CConstraint() { } template <typename TL> void Verify(int position, int constraints[]) { } template <> void Verify<int>(int, int[]) { } }; Compiling this under g++ gives the following error: Explicit specialization in non-namespace scope 'class CConstraint' In VC, it compiles fine. Can anyone please let me know the workaround?
VC++ is non-compliant in this case - explicit specializations have to be at namespace scope. C++03, §14.7.3/2: An explicit specialization shall be declared in the namespace of which the template is a member, or, for member templates, in the namespace of which the enclosing class or enclosing class template is a member. An explicit specialization of a member function, member class or static data member of a class template shall be declared in the namespace of which the class template is a member. Additionally you have the problem that you can't specialize member functions without explicitly specializing the containing class due to C++03, §14.7.3/3, so one solution would be to let Verify() forward to a, possibly specialized, free function: namespace detail { template <typename TL> void Verify (int, int[]) {} template <> void Verify<int>(int, int[]) {} } template<typename T> class CConstraint { // ... template <typename TL> void Verify(int position, int constraints[]) { detail::Verify<TL>(position, constraints); } };
3,052,625
3,052,648
typedef boost::shared_ptr<MyJob> Ptr; or #define Ptr boost::shared_ptr
I've just started working on a new codebase where each class contains a shared_ptr typedef (similar to this) like: typedef boost::shared_ptr<MyClass> Ptr; Is the only purpose to save typing boost::shared_ptr? If that is the case, is the only reason not to do #define Ptr boost::shared_ptr in one common header the general problems with #define? Then you can do: Ptr<MyClass> myClass(new MyClass); which is no more typing than MyClass::Ptr myClass(new MyClass); and saves the Ptr definition in each class.
A macro (#define) is always defined globally. This means that every use of the 'string' Ptr (even a variable) will be replaced by the macro. The typedef can be placed in a class, in a namespace, ... so you have much better control over it. EDIT: another advantage is that you can haver different Ptr types in different classes, e.g. ClassX::Ptr is a boost shared_ptr ClassY::Ptr can be another shared_ptr ClassZ::Ptr can be a simple "Class Z *" pointer If these classes are then used in templated code, you can use T::Ptr as a type of pointer to the class, and the template will use the most-appropriate pointer for the class.
3,052,788
3,052,796
How to select a random element in std::set?
How can I select a random element in an std::set? I naively tried this: int GetSample(const std::set<int>& s) { double r = rand() % s.size(); return *(s.begin() + r); // compile error } But the operator+ is not allowed in this way.
You could use the std::advance method. #include <set> #include <algorithm> int main() { using namespace std; // generate a set... set<int> s; for( int i = 0; i != 10; ++i ) s.insert(i); auto r = rand() % s.size(); // not _really_ random auto n = *select_random(s, r); } Where template<typename S> auto select_random(const S &s, size_t n) { auto it = std::begin(s); // 'advance' the iterator n times std::advance(it,n); return it; }
3,052,949
3,052,957
How do I sort a file that has a very long list of items?
I have a text file that has a very long list of items. So I want to sort them alphabetically but I do not want to load all the file into the memory (RAM). I tried loading all the contents of the file to an array and sort them just like I do normally. But the system complains that there are no much memory!! Thanks, Mohammad
You'll need to read up on external sorting. The basic approach is to use some sort of divide-and-conquer routine like merge sort, where you read and sort a portion of the file, then read and sort another portion of the file, etc. and when you get to the end you merge the sorted portions together.
3,053,081
3,053,353
C++ and virtual methods overriding
Sorry for this stupid question, but I can't find an answer by myself, I'm too new in C++ :( class DBObject : public QObject { ... protected: virtual QString tableName() = 0; }; class DBUserObject : public DBObject { ... protected: virtual QString tableName() { return "profiles"; }; }; And I have this code in parent: DBObject::DBObject(quint32 id) : QObject(0) { ... if (id != 0) load(id); } bool DBObject::load(quint32 id) { QString query = QString("select %1 from %2 where id = :id") .arg(fieldList().join(",")) .arg(tableName()); <--- here is trouble ... } So I'm trying to execute: DBUserObject user(3); But in result I have a runtime error. Why not "profiles"?
Based on the OP's followup comment: DBUserObject user(3). It is loading item in its constructor. If you mean the DBObject constructor (and not the DBUserObject constructor), then there's your problem. Virtual functions do not work inside constructors. Constructors run from the least-derived (most base) class to the most-derived (actual type) class. When a class' constructor runs, the object is only of that class' type, and nothing more derived. In other words, when you create a DBUserObject, first the QObject constructor runs, and inside that constructor the object is only a QObect and nothing more. Then, the DBObject constructor runs, and inside that constructor the object is only a DBObject and nothing more. Finally, the DBUserObject constructor runs and the object is finally a DBUserObject. So if you call load() inside of the DBObject constructor, the object is only a DBObject at that point and so has only the DBObject version of load. This applies similarly for any virtual function. If you want to get the effect of calling the DBUserObject version of load(), you will need to call it from the DBUserObject constructor, or from outside the class after the object has been constructed. More information: http://www2.research.att.com/~bs/bs_faq2.html#vcall http://www.artima.com/cppsource/nevercall.html
3,053,219
3,053,238
Retrieve Heap memory size and its usage statistics etc...?
Lets say I open some application or process. Did some work with that. Now I closed it. Need to know whether this application caused any memory leak. i.e used up some heap memory and not cleared it properly. Can I get this statistics some how? I'm using Visual Studio (for development) under Windows OS. Even I would be interested in knowing this information for any 3rd party application.
When an application closes all resources are automatically released by Windows. A quick & dirty tool to get an indication for memory/resource-leaks inside an application is Perfmon. The actions executed by an application, can cause other processes to use more memory. SQL Server can make its cache size bigger, maybe you have opened Word or Explorer, the Windows Search engine might kick in because you saved some file. The virus scanner can be more active, etc.....
3,053,359
3,923,696
Creating Binary Block from struct
I hope the title is describing the problem, i'll change it if anyone has a better idea. I'm storing information in a struct like this: struct AnyStruct { AnyStruct() : testInt(20), testDouble(100.01), testBool1(true), testBool2(false), testBool3(true), testChar('x') {} int testInt; double testDouble; bool testBool1; bool testBool2; bool testBool3; char testChar; std::vector<char> getBinaryBlock() { //how to build that? } } The struct should be sent via network in a binary byte-buffer with the following structure: Bit 00- 31: testInt Bit 32- 61: testDouble most significant portion Bit 62- 93: testDouble least significant portion Bit 94: testBool1 Bit 95: testBool2 Bit 96: testBool3 Bit 97-104: testChar According to this definition the resulting std::vector should have a size of 13 bytes (char == byte) My question now is how I can form such a packet out of the different datatypes I've got. I've already read through a lot of pages and found datatypes like std::bitset or boost::dynamic_bitset, but neither seems to solve my problem. I think it is easy to see, that the above code is just an example, the original standard is far more complex and contains more different datatypes. Solving the above example should solve my problems with the complex structures too i think. One last point: The problem should be solved just by using standard, portable language-features of C++ like STL or Boost (
I've now used the std::bitset for generating bit-sequences for the datatypes and then concatenated these bitsets to one big bitset. This then holds the data I need. I just have to check for little/big endian.
3,053,513
3,053,626
Converting a macro to an inline function
I am using some Qt code that adds a VERIFY macro that looks something like this: #define VERIFY(cond) \ { \ bool ok = cond; \ Q_ASSERT(ok); \ } The code can then use it whilst being certain the condition is actually evaluated, e.g.: Q_ASSERT(callSomeFunction()); // callSomeFunction not evaluated in release builds! VERIFY(callSomeFunction()); // callSomeFunction is always evaluated Disliking macros, I would instead like to turn this into an inline function: inline VERIFY(bool condition) { Q_ASSERT(condition); } However, in release builds I am worried that the compiler would optimise out all calls to this function (as Q_ASSERT wouldn't actually do anything.) I am I worrying unnecessarily or is this likely depending on the optimisation flags/compiler/etc.? I guess I could change it to: inline VERIFY(bool condition) { condition; Q_ASSERT(condition); } But, again, the compiler may be clever enough to ignore the call. Is this inline alternative safe for both debug and release builds?
In case of inline functions there's no guarantee the function arguments are not evaluated. Since their evaluation might have or not have side effects you will at very best have hard times maintaining the code - in cases where there is a side effect evaluation will surely take place, in other cases it will take or not take place at the discretion of the compiler. This leaves you with a program that behaves in loosely controlled manner. So even with your dislike towards macros you should make an informed decision. Either you use a macro and then the whole construct is eliminated by the preprocessor and the parameters are not evaluated, or you use an inline function and then the compiler decides for you.
3,053,561
18,919,937
How do I assign an alias to a function name in C++?
It's easy to create a new name for a type, a variable or a namespace. But how do I assign a new name to a function? For example, I want to use the name holler for printf. #define is obvious... any other way? Solutions: #define holler printf void (*p)() = fn; //function pointer void (&r)() = fn; //function reference inline void g(){ f(); }
There are different approaches: With C++11 with non-template non-overloaded functions you can simply use: const auto& new_fn_name = old_fn_name; If this function has multiple overloads you should use static_cast: const auto& new_fn_name = static_cast<OVERLOADED_FN_TYPE>(old_fn_name); Example: there are two overloads of function std::stoi int stoi (const string&, size_t*, int); int stoi (const wstring&, size_t*, int); If you want to make an alias to the first version you should use the following: const auto& new_fn_name = static_cast<int(*)(const string&, size_t*, int)>(std::stoi); Note: there is no way to make an alias to overloaded function such that all its overloaded versions work, so you should always specify which exact function overload you want. With C++14 you can go even further with constexpr template variables. That allows you to alias templated functions: template<typename T> constexpr void old_function(/* args */); template<typename T> constexpr auto alias_to_old = old_function<T>; Moreover, starting with C++11 you have a function called std::mem_fn that allows to alias member functions. See the following example: struct A { void f(int i) { std::cout << "Argument: " << i << '\n'; } }; A a; auto greet = std::mem_fn(&A::f); // alias to member function // prints "Argument: 5" greet(a, 5); // you should provide an object each time you use this alias // if you want to bind an object permanently use `std::bind` greet_a = std::bind(greet, a, std::placeholders::_1); greet_a(3); // equivalent to greet(a, 3) => a.f(3);
3,053,578
3,053,600
How to declare ULARGE_INTEGER in c#?
Based upon this question How to declarate LARGE_INTEGER in C# with answer of: [StructLayout(LayoutKind.Absolute, Size=8)] struct LARGE_INTEGER { [FieldOffset(0)]public Int64 QuadPart; [FieldOffset(0)]public UInt32 LowPart; [FieldOffset(4)]public Int32 HighPart; } Is my assumption below for declaring ULARGE_INTEGER correct? [StructLayout(LayoutKind.Explicit, Size = 8)] public struct ULARGE_INTEGER { [FieldOffset(0)] public UInt64 QuadPart; [FieldOffset(0)] public UInt32 LowPart; [FieldOffset(4)] public UInt32 HighPart; }
It is simply an ulong in C#, no need to jump through the LayoutKind.Explicit hoop. The union was necessary because C and C++ compilers didn't have a native 64-bit type in the olden days.
3,053,667
3,054,207
Qt - How to place a QTextEdit with left and right margins in a QVBoxLayout?
How to place a QTextEdit with left and right margins in a QVBoxLayout? I could use, of course, a QHBoxLayout, place the QTextEdit into that horizontal layout in between to spacings (addSpacing(40)) and only then the horizontal layout could add into the vertical layout, but want to know if there is a direct way of doing that.
If you want the margins only for your QTextEdit and not any other element in the QVerticalLayout you can use QT stylesheets for that. You just need to give a name to the QTextEdit object (like "myMarginsTextEdit") and style it, eg: QTextEdit#myMarginsTextEdit { margin-left: 40px; margin-right: 40px; } If you are not using QT stylesheets to style your application you can still use it only to style that item. You can do it like this (imagine your QTextEdit variable is call "textEditItem"): textEditItem.setStyleSheet("QTextEdit {margin-left:40px; margin-right:40px}"); The other option is use content margins in the vertical layout but then it is applied to all elements.
3,053,681
3,053,885
Declaration of struct variables in other class when obtained by getters
I am using Qt 4.5 so do C++. I have a class like this class CClass1 { private: struct stModelDetails { QString name; QString code; ..... // only variables and no functions over here }; QList<stModelDetails> m_ModelDetailsList; public: QList<stModelDetails> getModelDetailsList(); ... }; In this I have functions that will populate the m_ModelDetailsList; I have another class say CClassStructureUsage, where I will call the getModelDetailsList() function. Now my need is that I have to traverse the QList and obtain the name, code from each of the stModelDetails. Now the problem is even the CClass1's header file is included it is not able to identify the type of stModelDetails in CClassStructureUsage. When I get the structure list by QList<stModelDetails> ModelList = obj->getModelInformationList(); it says stModelDetails : undeclared identifier. How I can able to fetch the values from the structure? Am I doing anything wrong over here?
You've already gotten a couple of suggestions for how to attack your problem directly. I, however, would recommend stepping back for a moment to consider what you're trying to accomplish here. First of all, you've said you only really want the name member of each stModelDetails item. Based on that, I'd start by changing the function to return only that: QList<QString> GetModelDetailNames(); or, quite possibly: QVector<QString> GetModelDetailNames(); The former has a couple of good points. First, it reduces the amount of data you need to copy. Second, it keeps client code from having to know more implementation details of CClass1. The latter retains those advantages, and adds a few of its own, primarily avoiding the overhead of a linked list in a situation where you haven't pointed to any reason you'd want to use a linked list (and such reasons are really fairly unusual). The alternative to that is to figure out why outside code needs access to that much of CClass1's internal data, and whether it doesn't make sense for CClass1 to provide that service directly instead of outside code needing to access its data.
3,053,739
3,053,759
error C2504: 'BASECLASS' : base class undefined
I checked out a post similar to this but the linkage was different the issue was never resolved. The problem with mine is that for some reason the linker is expecting there to be a definition for the base class, but the base class is just a interface. Below is the error in it's entirety c:\users\numerical25\desktop\intro todirectx\godfiles\gxrendermanager\gxrendermanager\gxrendermanager\gxdx.h(2) : error C2504: 'GXRenderer' : base class undefined Below is the code that shows how the headers link with one another GXRenderManager.h #ifndef GXRM #define GXRM #include <windows.h> #include "GXRenderer.h" #include "GXDX.h" #include "GXGL.h" enum GXDEVICE { DIRECTX, OPENGL }; class GXRenderManager { public: static int Ignite(GXDEVICE); private: static GXRenderer *renderDevice; }; #endif at the top of GxRenderManager, there is GXRenderer , windows, GXDX, GXGL headers. I am assuming by including them all in this document. they all link to one another as if they were all in the same document. correct me if I am wrong cause that's how a view headers. Moving on... GXRenderer.h class GXRenderer { public: virtual void Render() = 0; virtual void StartUp() = 0; }; GXGL.h class GXGL: public GXRenderer { public: void Render(); void StartUp(); }; GXDX.h class GXDX: public GXRenderer { public: void Render(); void StartUp(); }; GXGL.cpp and GXDX.cpp respectively #include "GXGL.h" void GXGL::Render() { } void GXGL::StartUp() { } //...Next document #include "GXDX.h" void GXDX::Render() { } void GXDX::StartUp() { } Not sure whats going on. I think its how I am linking the documents, I am not sure.
The problem is You need to have #include "GXRenderer.h" at the top of both: GXGL.h and also GXDX.h. The base type must be defined not just declared before defining a derived type. By the way, the error is a compiling error not linking error. Edit: About your class type redefinition: at the top of every header file you should have #pragma once. The #pragma once directive specifies that the file will be included at most once by the compiler in a build.
3,053,851
3,053,866
Difference between Object var and Object* var = new Object()
If I have a class named Object, what's the difference between creating an instance just like that: Object var; and: Object* var = new Object(); ?
Here you are creating var on the stack: Object var; So in the above, var is the actual object. Here you are creating var on the heap (also called dynamic allocation): Object* var = new Object() When creating an object on the heap you must call delete on it when you're done using it. Also var is actually a pointer which holds the memory address of an object of type Object. At the memory address exists the actual object. For more information: See my answer here on what and where are the stack and heap.
3,053,904
3,054,003
Is a C++ compiler allowed to emit different machine code compiling the same program?
Consider a situation. We have some specific C++ compiler, a specific set of compiler settings and a specific C++ program. We compile that specific programs with that compiler and those settings two times, doing a "clean compile" each time. Should the machine code emitted be the same (I don't mean timestamps and other bells and whistles, I mean only real code that will be executed) or is it allowed to vary from one compilation to another?
The C++ standard certainly doesn't say anything to prevent this from happening. In reality, however, a compiler is normally deterministic, so given identical inputs it will produce identical output. The real question is mostly what parts of the environment it considers as its inputs -- there are a few that seem to assume characteristics of the build machine reflect characteristics of the target, and vary their output based on "inputs" that are implicit in the build environment instead of explicitly stated, such as via compiler flags. That said, even that is relatively unusual. The norm is for the output to depend on explicit inputs (input files, command line flags, etc.) Offhand, I can only think of one fairly obvious thing that changes "spontaneously": some compilers and/or linkers embed a timestamp into their output file, so a few bytes of the output file will change from one build to the next--but this will only be in the metadata embedded in the file, not a change to the actual code that's generated.
3,053,956
3,054,024
How do I implement a dictionary "with a Python tuple" as key in C++?
I currently have some python code I'd like to port to C++ as it's currently slower than I'd like it to be. Problem is that I'm using a dictionary in it where the key is a tuple consisting of an object and a string (e.g. (obj, "word")). How on earth do I write something similar in C++? Maybe my algorithm is horrendous and there is some way I can make it faster without resorting to C++? The whole algorithm below for clarity's sake. The dictionary "post_score" is the issue. def get_best_match_best(search_text, posts): """ Find the best matches between a search query "search_text" and any of the strings in "posts". @param search_text: Query to find an appropriate match with in posts. @type search_text: string @param posts: List of candidates to match with target text. @type posts: [cl_post.Post] @return: Best matches of the candidates found in posts. The posts are ordered according to their rank. First post in list has best match and so on. @returntype: [cl_post.Post] """ from math import log search_words = separate_words(search_text) total_number_of_hits = {} post_score = {} post_size = {} for search_word in search_words: total_number_of_hits[search_word] = 0.0 for post in posts: post_score[(post, search_word)] = 0.0 post_words = separate_words(post.text) post_size[post] = len(post_words) for post_word in post_words: possible_match = abs(len(post_word) - len(search_word)) <= 2 if possible_match: score = calculate_score(search_word, post_word) post_score[(post, search_word)] += score if score >= 1.0: total_number_of_hits[search_word] += 1.0 log_of_number_of_posts = log(len(posts)) matches = [] for post in posts: rank = 0.0 for search_word in search_words: rank += post_score[(post, search_word)] * \ (log_of_number_of_posts - log(1.0 + total_number_of_hits[search_word])) matches.append((rank / post_size[post], post)) matches.sort(reverse=True) return [post[1] for post in matches]
map<pair<..., string>, ...> if you're hellbent on using C++ for this.
3,054,048
3,054,360
Why doesn't C++ allow you to request a pointer to the most derived class?
(This question should probably be answered with a reference to Stroustrup.) It seems extremely useful to be able to request a pointer to the most derived class, as in the following: class Base { ... }; class DerivedA { ... }; class DerivedB { ... }; class Processor { public: void Do(Base* b) {...} void Do(DerivedA* d) {...} void Do(DerivedB* d) {...} }; list<Base*> things; Processor p; for(list<Base*>::iterator i=things.begin(), e=things.end(); i!=e; ++i) { p.Do(CAST_TO_MOST_DERIVED_CLASS(*i)); } But this mechanism isn't provided in c++. Why? Update, Motivating Example: Suppose instead of having Base and Derived and Processor, you have: class Fruit class Apple : public Fruit class Orange: public Fruit class Eater { void Eat(Fruit* f) { ... } void Eat(Apple* f) { Wash(f); ... } void Eat(Orange* f) { Peel(f); ... } }; Eater me; for each Fruit* f in Fruits me.Eat(f); But this is tricky to do in C++, requiring creative solutions like the visitor pattern. The question, then, is: Why is this tricky to do in C++, when something like "CAST_TO_MOST_DERIVED" would make it much simpler? Update: Wikipedia Knows All I think Pontus Gagge has a good answer. Add to it this bit from the Wikipedia entry on Multiple Dispatch: "Stroustrup mentions that he liked the concept of Multi-methods in The Design and Evolution of C++ and considered implementing it in C++ but claims to have been unable to find an efficient sample implementation (comparable to virtual functions) and resolve some possible type ambiguity problems. He goes on to state that although the feature would still be nice to have, that it can be approximately implemented using double dispatch or a type based lookup table as outlined in the C/C++ example above so is a low priority feature for future language revisions." For background, you can read a little summary about Multi-Methods, which would be better than a call like the one I mention, because they'd just work.
What you are suggesting would be equivalent to a switch on the runtime type, calling one of the overloaded functions. As others have indicated, you should work with your inheritance hierarchy, and not against it: use virtuals in your class hierarchy instead of dispatching outside it. That said, something like this could be useful for double dispatch, especially if you also have a hierarchy of Processors. But how would the compiler implement it? First, you'd have to extract what you call 'the most overloaded type' at runtime. It can be done, but how would you deal with e.g. multiple inheritance and templates? Every feature in a language must interact well with other features -- and C++ has a great number of features! Second, for your code example to work, you'd have to get the correct static overload based on the runtime type (which C++ does not allow as it is designed). Would you like this to follow the compile time lookup rules, especially with multiple parameters? Would you like this runtime dispatch to consider also the runtime type of your Processor hierarchy, and what overloads they have added? How much logic would you like the compiler to add automatically into your runtime dispatcher? How would you deal with invalid runtime types? Would users of the feature be aware of the cost and complexity of what looks like a simple cast and function call? In all, I´d say the feature would be complex to implement, prone to errors both in implementation and usage, and useful only in rare cases.
3,054,068
3,056,015
How to create named pipe acsessible Only on your machin? (VS08 C++)
I have created a program that write video stream to a named pipe on windows, using Visual Studio C++ 2008 . how to be sequre that no one exept programms on this computer can acsess this pipe? npipe = CreateNamedPipe("\\\\.\\pipe\\TestChannel", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES , 1024, 1024,5000,NULL);
As of Windows Vista, you can include the PIPE_REJECT_REMOTE_CLIENTS flag in the dwPipeMode parameter. For earlier Windows versions, the documentation suggests using the lpSecurityAttributes parameter to deny access to the network.
3,054,078
3,054,177
ASCII definition of symbol
I've spent hours with no luck on this. In terms of cmd prompt, what does the white filled in square with a 1 followed afterwards mean? e.g. http://i1012.photobucket.com/albums/af249/dororoj/square1.jpg I've tried using string.find() (using C++) with various hex symbols listed on the ascii table at: http://web.cs.mun.ca/~michael/c/ascii-table.html to no avail. Such a simple question yet I can't for the life of me figure it out! As for what I want to do, I simply want to be able to locate that square with the 1 afterwards in any string. Many thanks.
I ran the following C# code bit and found the symbol you mentioned when the loop hit 166. So i doubt that it could mean anything useful.Although it doesnt mean anything it could've been used for primitive ASCII based display/drawing :) namespace block { class Program { static void Main(string[] args) { int j; for ( j = 0; j < 1000; j++) { Console.Write((char)j+" "+j +"\t"); } Console.Read(); } } }
3,054,161
3,054,199
Does any compiler support constexpr yet?
I want to play with constexpr, does any compiler support it yet?
The Apache Stdcxx project has a nice table detailing which C++0x features are supported by which compilers. It's been updated on a regular basis and covers most of the modern C++ compilers. According to that, only GCC 4.5 supports constexpr (note that that support may be experimental). Between that list and what has been said in the comments, it appears the answer is "no."
3,054,235
3,054,242
TCHAR* envp[]: What is it?
I created a VC++ console project with Visual Studio and it auto-generated this function: int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { ... } I was just wondering what envp stands for and how/when I can/should use it? Thank you!
The envp argument above will store the environment variables. The envp array, which is a common extension in many UNIX® systems, is used in Microsoft C++. It is an array of strings representing the variables set in the user's environment. This array is terminated by a NULL entry. It can be declared as an array of pointers to char(char *envp[ ]) or as a pointer to pointers to char(char **envp). If your program uses wmain instead of main, use the wchar_t data type instead of char. The environment block passed to main and wmain is a "frozen" copy of the current environment. Source
3,054,257
3,054,274
Is there STDCALL in Linux?
I'm trying to port a Windows app to Linux. This appplication marks some functions with the __stdcall attribute. However, I was told by a friend that stdcall is used only on Windows and has no meaning in Linux (but DOES exist in Windows GCC). Searching Google - some results state that there IS stdcall in Linux. Is there a stdcall in Linux? Additionally, GCC indicates that: __attribute__((__stdcall__)) and __attribute__((stdcall)) (without the underscores near stdcall). Which one is preferred (if applied to Linux at all)?
The simplest solution is to just define __stdcall to nothing conditionally on Linux.
3,054,400
3,055,545
Application disappears after starting - C++ linking managed code dll
we have a problem with our applications. We have recently upgraded our toolchain to Visual Studio 2010 and friends, it all works fine on Windows Vista + Windows 7 developer machines and Windows 7 customer machines. (all x86) Today we did a first installation to a client PC running Windows XP SP2 x86, and all applications linking managed code dll do not work. After starting the .exe seemingly nothing happens, no window pops up, no memory gets eaten, no task shows in task manager, nothing, nada. Event log is empty, everything is just as if the application returned to the OS right after the start. I am at loss about this, I really don't know how should I start even debugging this problem. I don't want to install VS2010 and everything onto a Windows XP box, I'd like to try something less time intensive first. This all is happening just to native C++ apps that link managed c++ DLL. Pure managed C# apps do work. Pure native C++ apps do work.
See if drwtsn32 is configured as the application debugger on the client pc. Check for "C:\Documents and Settings\All Users\Application Data\Microsoft\Dr Watson". If you have a log in that location, search for "fault ->" and you will find the address within the process that caused the access violation. From there, you can trace it back to a line in code.
3,054,442
3,055,497
Is it possible to use threads to speed up file reading?
I want to read a file as fast as possible (40k lines) [Edit : the rest is obsolete]. Edit: Andres Jaan Tack suggested a solution based on one thread per file, and I want to be sure I got this (thus this is the fastest way) : One thread per entry file reads it whole and stocks its content in a container associated (-> as many containers as there are entry files) One thread calculates the linear combination of every cell read by the input threads, and stocks the results in the exit container (associated to the output file). One thread writes by block (every 4kB of data, so about 10 lines) the content of the output container. Should I deduce that I must not use m-mapped files (because the program's on standby waiting for the data) ? Thanks aforehand. Sincerely, Mister mystère.
Your question got a little bit deeper, when you asked further. I'll try to cover all your options... Reading One File: How many threads? Use one thread. If you read straight through a file front-to-back from a single thread, the operating system will not fetch the file in small chunks like you're thinking. Rather, it will prefetch the file ahead of you in huge (exponentially growing) chunks, so you almost never pay a penalty for going to disk. You might wait for the disk a handful of times, but in general it will be like the file was already in memory, and this is even irrespective of mmap. The OS is very good at this kind of sequential file reading, because it's predictable. When you read a file from multiple threads, you're essentially reading randomly, which is (obviously) less predictable. Prefetchers tend to be much less effective with random reads, in this case probably making the whole application slower instead of faster. Notice: This is even before you add the cost of setting up the threads and all the rest of it. That costs something, too, but it's basically nothing compared with the cost of more blocking disk accesses. Reading Multiple Files: How many threads? Use as many threads as you have files (or some reasonable number). File prefetching done separately for each open file. Once you start reading multiple files, you should read from several of them in parallel. This works because the disk I/O Scheduler will try to figure out the fastest order in which to read all of them in. Often, there's a disk scheduler both in the OS and on the hard drive itself. Meanwhile, the prefetcher can still do its job. Reading several files in parallel is always better than reading the files one-by-one. If you did read them one at a time, your disk would idle between prefetches; that's valuable time to read more data into memory! The only way you can go wrong is if you have too little RAM to support many open files; that's not common, anymore. A word of caution: If you're too overzealous with your multiple file reads, reading one file will start kicking bits of other files out of memory, and you're back to a random-read situation. Combining n Files into One. Processing and producing output from multiple threads might work, but it depends how you need to combine them. You'll have to be careful about how you synchronize the threads, in any case, though there are surely some relatively easy lock-less ways to do that. One thing to look for, though: Don't bother writing the file in small (< 4K) blocks. Collect at least 4K of data at a time before you call write(). Also, since the kernel will lock the file when you write it, don't call write() from all of your threads together; they'll all wait for each other instead of processing more data.
3,054,460
3,054,484
Possible to call a managed DLL from unmanaged C++?
Is it possible to call CLR DLL (one for example which is made with C#) from unmanaged C++ code? I need a DLL that is not managed to call into it somehow, maybe even via some proxy C++ process that is built with C++ / CLI?
The CLR DLL would have to be built as a COM visible assembly. If you have control of the C#, it's a simple rebuild, otherwise, is pretty much impossible to use it directly.
3,054,567
3,054,584
"Right" way to deallocate an std::vector object
The first solution is: std::vector<int> *vec = new std::vector<int>; assert(vec != NULL); // ... delete vec; An alternative is: std::vector<int> v; //... vec.clear(); vec.swap(std::vector<int>(vec)); The second solution's a bit of a trick --- what's the "right" way to do it? Update: I'm aware that the destructor will be called once it's off the stack, I was curious about other methods.
The simplest and most reliable way to deallocate a vector is to declare it on the stack and simply do nothing. void Foo() { std::vector<int> v; ... } C++ guarantees that the destructor of v will be called when the method executes. The destructor of std::vector will ensure any memory it allocated is freed. As long as the T type of the vector<T> has proper C++ deallocation semantics all will be well.
3,054,892
3,055,093
What's the best way to write to more files than the kernel allows open at a time?
I have a very large binary file and I need to create separate files based on the id within the input file. There are 146 output files and I am using cstdlib and fopen and fwrite. FOPEN_MAX is 20, so I can't keep all 146 output files open at the same time. I also want to minimize the number of times I open and close an output file. How can I write to the output files effectively? I also must use the cstdlib library due to legacy code. The executable must also be UNIX and windows cross-platform compatible.
A couple possible approaches you might take: keep a cache of opened output file handles that's less than FOPEN_MAX - if a write needs to occur on a files that already open, then just do the write. Otherwise, close one of the handles in the cache and open the output file. If your data is generally clumped together in terms of the data for a particular set of files is grouped together in the input file, this should work nicely with an LRU policy for the file handle cache. Handle the output buffering yourself instead of letting the library do it for you: keep your own set of 146 (or however many you might need) output buffers and buffer the output to those, and perform an open/flush/close when a particular output buffer gets filled. You could even combine this with the above approach to really minimize the open/close operations. Just be sure you test well for the edge conditions that can happen on filling or nearly filling an output buffer.
3,055,028
3,055,438
How to send stream data via Bluetooth from an iPhone/iPod Touch to a Windows C++ application?
I need to develop an iPhone/iPod Touch application that creates a server to send some data stream (characters or bytes) to a Windows C++ application via Bluetooth. I'm thinking of creating a TCP connection, but don't know where to start. What iPhone API should I use do to something like this? Does anyone knows some code examples that i can use to do this? And in Windows, what should I use to support this kind of communication? Thanks
Yes. From what it looks like you can use the PAN bluetooth profile (the same profile used for tethering) with everything except the original iPhone. Here's an article doing bluetooth over iPhone/iPad using GameKit. The article notes that you would need at least 2 iPhone/iPad devices running iPhone OS 3.0, but I wouldn't take that as an impossibility to talk to any other bluetooth capable device. Update This forum indicates that the iPhone is only capable of headset pairing. It could be that the iPhone is "picky" about what you can pair it with. "The iPhone only recognizes the "headset" profile. Another well thought out idea from Apple. No A2DP profiles, no OBEX." -sapporobaby Update 2 As jamone as indicated iPhone 3.0 supports A2DP. How nice is that? Here's a table listing of iPhone/iPad bluetooth supported profiles
3,055,141
3,055,155
Interview question about virtual functions in C++
I was asked this crazy question. I was out of my wits. Can a method in base class which is declared as virtual be called using the base class pointer which is pointing to a derived class object? Is this possible?
If you're trying to invoke a virtual method from the base class pointer, yes. That's polymorphism. If you're asking, with a base class pointer to a derived class, can you invoke a base class method that is overriden by the derived class? Yes that's also possible by explicitly scoping the base class name: basePtr->BaseClass::myMethod();
3,055,240
3,055,306
Create a modifiable string literal in C++
Is it possible to create a modifiable string literal in C++? For example: char* foo[] = { "foo", "foo" }; char* afoo = foo[0]; afoo[2] = 'g'; // access violation This produces an access violation because the "foo"s are allocated in read only memory (.rdata section I believe). Is there any way to force the "foo"s into writable memory (.data section)? Even via a pragma would be acceptable! (Visual Studio compiler) I know I can do strdup and a number of other things to get around the problem, but I want to know specifically if I can do as I have asked. :)
You could create a multidimensional array of chars: #include <iostream> int main(int argc, char** argv) { char foo[][4] = { "foo", "bar" }; char* afoo = foo[0]; afoo[2] = 'g'; std::cout << afoo << std::endl; } More verbose way to define the array: char foo[][4] = { {'f', 'o', 'o', '\0'}, {'b', 'a', 'r', '\0'} };
3,055,267
3,056,082
Combine Video and Audio Streams (Qt, OpenCV, PortAudio,libsnd?)
I was wondering, how would I combine recorded audio and video into one if I have them in separate files? Preferably using OpenCV and PortAudio/libsnd. Thanks in advance.
FFmpeg is used to decode and encode almost all popular formats. It can be used as an alternative to all of these. PortAudio will probably only be useful for audio playback, so unless you need to play the stuff back it won't be needed. In case you do need A/V playback, FFmpeg is also good (VLC uses it.)
3,055,421
3,056,049
Find missing number in sequence in set or list
If a std::set or std::list contains a sequence of natural numbers (1, 2, 3..). would there be a function in standard library to find the missing number?
You can find all missing numbers using set_difference and a custom iterator: class seqIter : public std::iterator<std::input_iterator_tag, int> { public: seqIter(int n) : num(n) {} seqIter(const seqIter & n) : num(n.num) {} int & operator *() {return num;} seqIter & operator ++() { ++num; return *this; } bool operator !=(const seqIter & n) { return n.num != num; } private: int num; }; int main(int argc, char *argv[]) { int n[] = { 1, 3, 4, 7, 10 }; std::set<int> numbers(n, n + sizeof(n)/sizeof(n[0])); std::set<int> missing; std::set_difference( seqIter(*numbers.begin()+1), seqIter(*numbers.rbegin()), numbers.begin(), numbers.end(), std::insert_iterator<std::set<int> >(missing, missing.begin()) ); } It's probably not any faster than going thru the numbers with a for loop though.
3,055,733
3,055,764
Strange GCC 'expected primary expression...' error
Possible Duplicate: Templates: template function not playing well with class’s template member function template <typename T> struct A { template <int I> void f(); }; template <typename T> void F(A<T> &a) { a.f<0>(); // expected primary-expression before ‘)’ token } int main() { A<int> a; a.f<0>(); // This one is ok. } What it's all about?
When a dependent name is used to refer to a nested template, the nested name has to be prepended with the keyword template to help the compiler understand that you are referring to a nested template and parse the code correctly template <typename T> void F(A<T> &a) { a.template f<0>(); } Inside main the name a is not dependent, which is why you don't need the extra template keyword. Inside F name a is dependent, which is why the keyword is needed. This is similar to the extra typename keyword when referring to nested type names through a dependent name. Just the syntax is slightly different.
3,055,924
3,057,051
Problems with system() calls in Linux
I'm working on a init for an initramfs in C++ for Linux. This script is used to unlock the DM-Crypt w/ LUKS encrypted drive, and set the LVM drives to be available. Since I don't want to have to reimplement the functionality of cryptsetup and gpg I am using system calls to call the executables. Using a system call to call gpg works fine if I have the system fully brought up already (I already have a bash script based initramfs that works fine in bringing it up, and I use grub to edit the command line to bring it up using the old initramfs). However, in the initramfs it never even acts like it gets called. Even commands like system("echo BLAH"); fail. So, does anyone have any input? Edit: So I figured out what was causing my errors. I have no clue as to why it would cause errors, but I found it. In order to allow hotplugging, I needed to write /sbin/mdev to /proc/sys/kernel/hotplug...however I ended up switching around the parameters (on a function I wrote myself no less) so I was writing /proc/sys/kernel/hotplug to /sbin/mdev. I have no clue as to why that would cause the problem, however it did.
Amardeep is right, system() on POSIX type systems runs the command through /bin/sh. I doubt you actually have a legitimate need to invoke these programs you speak of through a Bourne shell. A good reason would be if you needed them to have the default set of environment variables, but since /etc/profile is probably also unavailable so early in the boot process, I don't see how that can be the case here. Instead, use the standard fork()/exec() pattern: int system_alternative(const char* pgm, char *const argv[]) { pid_t pid = fork(); if (pid > 0) { // We're the parent, so wait for child to finish int status; waitpid(pid, &status, 0); return status; } else if (pid == 0) { // We're the child, so run the specified program. Our exit status will // be that of the child program unless the execv() syscall fails. return execv(pgm, argv); } else { // Something horrible happened, like system out of memory return -1; } } If you need to read stdout from the called process or send data to its stdin, you'll need to do some standard handle redirection via pipe() or dup2() in there. You can learn all about this sort of thing in any good Unix programming book. I recommend Advanced Programming in the UNIX Environment by W. Richard Stevens. The second edition coauthored by Rago adds material to cover platforms that appeared since Stevens wrote the first edition, like Linux and OS X, but basics like this haven't changed since the original edition.
3,056,113
3,123,255
Recording Audio with OpenAL
I've been comparing various audio libraries available in C++. I was wondering, I'm kind of stuck starting with OpenAL. Can someone point out an example program how to record from a mic using OpenAL in C++. Thanks in advance!
Last time I checked OpenAL it was quite simple. You create the recording device and start the recording going. You then just call the get buffer function. It will wait until there is enough data to fill the buffer and then return when there is enough data. Why not just look at the "capture" example that comes with the OpenAL SDK ...?
3,056,174
3,056,288
Deleting a element from a vector of pointers in C++
I remember hearing that the following code is not C++ compliant and was hoping someone with much more C++ legalese than me would be able to confirm or deny it. std::vector<int*> intList; intList.push_back(new int(2)); intList.push_back(new int(10)); intList.push_back(new int(17)); for(std::vector<int*>::iterator i = intList.begin(); i != intList.end(); ++i) { delete *i; } intList.clear() The rationale was that it is illegal for a vector to contain pointers to invalid memory. Now obviously my example will compile and it will even work on all compilers I know of, but is it standard compliant C++ or am I supposed to do the following, which I was told is in fact the standard compliant approach: while(!intList.empty()) { int* element = intList.back(); intList.pop_back(); delete element; }
Your code is fine. If you're worried for some reason about the elements being invalid momentarily, then change the body of the loop to int* tmp = 0; swap (tmp, *i); delete tmp;
3,056,309
3,056,326
Meaning of int(0) in int *pi = new int(0);?
int *pi = new int(0); What's the significance of 0 here? Does it mean integer array of length 0?
It is an initializer (constructor parameter). The newly created int will have value of 0.
3,056,597
3,056,619
Are vectors more rigorous at checking out of bounds than heap arrays?
How rigorous is the bounds checking on vectors compared to heap arrays? How exactly is it checking bounds and how does that compare with how a heap array is checked?
A vector will do bounds checking if you use the at() function, for example: std::vector<int> v(5); v.at(3) = 10; v.at(5) = 20; // throws an exception, std::out_of_range However, if you use operator[], there is no bounds checking. (And accessing non-existent elements leads to undefined behavior.) It should be noted, though, that most implementations will have the possibility to include bounds-checking on all iterators, which is discussed in the answers here. By default, VS2008 and below have it on in Debug and Release, VS2010 does only in Debug. gcc requires you define _GLIBCXX_DEBUG to get checked iterators.
3,056,655
3,056,753
Can overloading is possible with two version of function, constant member function and function without const
I just came across various overloading methods like type of parameter passed, varying number of parameters, return type etc. I just want to know that can I overload a function with following two version //function which can modify member String& MyClass::doSomething(); //constant member function String& MyClass::doSomething() const; Please let me know the reason behind it.
Yes you can. If you have MyClass m; m.doSomething(); The non-const version will be called. When you have const MyClass m; m.doSomething(); The const version will be called.
3,056,696
3,056,728
is there any faster way to parse than by walk each byte?
is there any faster way to parse a text than by walk each byte of the text? I wonder if there is any special CPU (x86/x64) instruction for string operation that is used by string library, that somehow used to optimize the parsing routine. for example instruction like finding a token in a string that could be run by hardware instead of looping each byte until a token is found. *edited->note: I'am asking more to algorithm instead of CPU architecture, so my really question is, is there any special algorithm or specific technique that could optimize the string manipulation routine given the current cpu architecture.
The x86 had a few string instructions, but they fell out of favor on modern processors, because they became slower than more primitive instructions which do the same thing. The processor world is moving more and more towards RISC, ie, simplistic instruction sets. Quote from Wikipedia (emphasis mine): The first highly (or tightly) pipelined x86 implementations, the 486 designs from Intel, AMD, Cyrix, and IBM, supported every instruction that their predecessors did, but achieved maximum efficiency only on a fairly simple x86 subset that resembled only a little more than a typical RISC instruction set (i.e. without typical RISC load-store limitations). This is still true on today's x86 processors. You could get marginally better performance processing four bytes at a time, assuming each "token" in the text was four-byte-aligned. Obviously this isn't true for most text... so better to stick with byte-by-byte scanning.
3,056,698
3,057,121
Item in multiple lists
So I have some legacy code which I would love to use more modern techniques. But I fear that given the way that things are designed, it is a non-option. The core issue is that often a node is in more than one list at a time. Something like this: struct T { T *next_1; T *prev_1; T *next_2; T *prev_2; int value; }; this allows the core have a single object of type T be allocated and inserted into 2 doubly linked lists, nice and efficient. Obviously I could just have 2 std::list<T*>'s and just insert the object into both...but there is one thing which would be way less efficient...removal. Often the code needs to "destroy" an object of type T and this includes removing the element from all lists. This is nice because given a T* the code can remove that object from all lists it exists in. With something like a std::list I would need to search for the object to get an iterator, then remove that (I can't just pass around an iterator because it is in several lists). Is there a nice c++-ish solution to this, or is the manually rolled way the best way? I have a feeling the manually rolled way is the answer, but I figured I'd ask.
As another possible solution, look at Boost Intrusive, which has an alternate list class a lot of properties that may make it useful for your problem. In this case, I think it'd look something like this: using namespace boost::intrusive; struct tag1; struct tag2; typedef list_base_hook< tag<tag1> > base1; typedef list_base_hook< tag<tag2> > base2; class T: public base1, public base2 { int value; } list<T, base_hook<base1> > list1; list<T, base_hook<base2> > list2; // constant time to get iterator of a T item: where_in_list1 = list1.iterator_to(item); where_in_list2 = list2.iterator_to(item); // once you have iterators, you can remove in contant time, etc, etc.
3,056,839
3,056,857
Checking for open ports in C/C++
There have been other questions regarding the subject of verifying the accessibility and accessibility of socket ports. How would one go about looking for a port to listen on dynamically in C/C++? The basic process I'm trying to accomplish is this: Client starts Client finds open port XYZ and listens on it. Client transmits a basic 'I Am Here' message via UDP Datagrams to a server with the port information Client and Server can communicate. I know you can accomplish something like this if you pick an arbitrary port number and try binding to it. If it fails, increment the number and try again until you get a successful 'bind'. Is there a more elegant way to do this? It seems kind of hacky.
If you bind to port 0, a random port will be allocated. Then getsockname() may be used to find out the actual port used.
3,056,853
3,056,932
any stl/boost functors to call operator()
template <typename T> struct Foo { void operator()(T& t) { t(); } }; Is there any standart or boost functor with the similar implementation? I need it to iterate over container of functors: std::for_each(beginIter, endIter, Foo<Bar>()); Or maybe there are other way to do it?
Binders like Boosts or C++0x bind() make it trivial to generate such a functor: std::for_each(begin, end, boost::bind(&Bar::operator(), _1)); Or using mem_fun_ref: std::for_each(v.begin(), v.end(), std::mem_fun_ref(&Bar::operator()));
3,056,925
3,057,057
CURL C API: callback was not called
The code below is a test for the CURL C API . The problem is that the callback function write_callback is never called. Why ? /** compilation: g++ source.cpp -lcurl */ #include <assert.h> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <curl/curl.h> using namespace std; static size_t write_callback(void *ptr, size_t size, size_t nmemb, void *userp) { std::cerr << "CALLBACK WAS CALLED" << endl; exit(-1); return size*nmemb; } static void test_curl() { int any_data=1; CURLM* multi_handle=NULL; CURL* handle_curl = ::curl_easy_init(); assert(handle_curl!=NULL); ::curl_easy_setopt(handle_curl, CURLOPT_URL, "http://en.wikipedia.org/wiki/Main_Page"); ::curl_easy_setopt(handle_curl, CURLOPT_WRITEDATA, &any_data); ::curl_easy_setopt(handle_curl, CURLOPT_VERBOSE, 1); ::curl_easy_setopt(handle_curl, CURLOPT_WRITEFUNCTION, write_callback); ::curl_easy_setopt(handle_curl, CURLOPT_USERAGENT, "libcurl-agent/1.0"); multi_handle = ::curl_multi_init(); assert(multi_handle!=NULL); ::curl_multi_add_handle(multi_handle, handle_curl); int still_running=0; /* lets start the fetch */ while(::curl_multi_perform(multi_handle, &still_running) == CURLM_CALL_MULTI_PERFORM ); std::cerr << "End of curl_multi_perform."<< endl; //cleanup should go here ::exit(EXIT_SUCCESS); } int main(int argc,char** argv) { test_curl(); return 0; } Many thanks Pierre
You need to check the value of still_running and call curl_multi_perform() again if there are still pending operations. Simple example: int still_running=0; /* lets start the fetch */ do { while(::curl_multi_perform(multi_handle, &still_running) == CURLM_CALL_MULTI_PERFORM); } while (still_running);
3,056,996
3,057,023
Stringified template argument
Is it possible to get a stringified version of a template argument name? Something like this, if only we were running the preprocessor: template <typename T> struct Named{ const char* name(){ return "Named<" #T ">"; } }; Edit Duplicate. See here Stringifying template arguments
No. The closest thing you can have is typeid(T).name(). However, the result of this is unspecified, even an implementation which returned empty strings for all types would be conforming. For debugging purposes it often is sufficient, though.
3,057,009
3,057,219
Storing objects in the array
I want to save boost signals objects in the map (association: signal name → signal object). The signals signature is different, so the second type of map should be boost::any. map<string, any> mSignalAssociation; The question is how to store objects without defining type of new signal signature? typedef boost::signals2::signal<void (int KeyCode)> sigKeyPressed; mSignalAssociation.insert(make_pair("KeyPressed", sigKeyPressed())); // This is what I need: passing object without type definition mSignalAssociation["KeyPressed"] = (typename boost::signals2::signal<void (int KeyCode)>()); // One more trying which won't work. And I don't want use this sigKeyPressed mKeyPressed; mSignalAssociation["KeyPressed"] = mKeyPressed; All this tryings throw the error: /usr/include/boost/noncopyable.hpp: In copy constructor ‘boost::signals2::signal_base::signal_base(const boost::signals2::signal_base&)’: In file included from /usr/include/boost/signals2/detail/signals_common.hpp:17:0, /usr/include/boost/noncopyable.hpp:27:7: error: ‘boost::noncopyable_::noncopyable::noncopyable(const boost::noncopyable_::noncopyable&)’ is private /usr/include/boost/signals2/signal_base.hpp:22:5: error: within this context ---------- /usr/include/boost/signals2/detail/signal_template.hpp: In copy constructor ‘boost::signals2::signal1<void, int&, boost::signals2::optional_last_value<void>, int, std::less<int>, boost::function<void(int)>, boost::function<void(const boost::signals2::connection&, int)>, boost::signals2::mutex>::signal1(const boost::signals2::signal1<void, int, boost::signals2::optional_last_value<void>, int, std::less<int>, boost::function<void(int)>, boost::function<void(const boost::signals2::connection&, int)>, boost::signals2::mutex>&)’: In file included from /usr/include/boost/preprocessor/iteration/detail/iter/forward1.hpp:52:0, /usr/include/boost/signals2/detail/signal_template.hpp:578:5: note: synthesized method ‘boost::signals2::signal_base::signal_base(const boost::signals2::signal_base&)’ first required here from /usr/include/boost/signals2.hpp:16, --------- /usr/include/boost/signals2/preprocessed_signal.hpp: In copy constructor ‘boost::signals2::signal<void(int)>::signal(const boost::signals2::signal<void(int)>&)’: In file included from /usr/include/boost/signals2/signal.hpp:36:0, /usr/include/boost/signals2/preprocessed_signal.hpp:42:5: note: synthesized method ‘boost::signals2::signal1<void, int, boost::signals2::optional_last_value<void>, int, std::less<int>, boost::function<void(int)>, boost::function<void(const boost::signals2::connection&, int)>, boost::signals2::mutex>::signal1(const boost::signals2::signal1<void, int, boost::signals2::optional_last_value<void>, int, std::less<int>, boost::function<void(int)>, boost::function<void(const boost::signals2::connection&, int)>, boost::signals2::mutex>&)’ first required here from /home/ockonal/Workspace/Projects/Pseudoform-2/include/Core/Systems.hpp:6,
This has nothing to do with any or map. Boost signals are simply non-copyable. You can wrap them in a smart pointer such as shared_ptr if you want something that's copyable and cleans up after itself.
3,057,029
3,057,797
Do I have to bind a UDP socket in my client program to receive data? (I always get WSAEINVAL)
I am creating a UDP socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP) via Winsock and trying to recvfrom on this socket, but it always returns -1 and I get WSAEINVAL (10022). Why? When I bind() the port, that does not happen, but I have read that it is very lame to bind the client's socket. I am sending data to my server, which answers, or at least, tries to. Inc::STATS CConnection::_RecvData(sockaddr* addr, std::string &strData) { int ret; // return code int len; // length of the data int fromlen; // sizeof(sockaddr) char *buffer; // will hold the data char c; //recv length of the message fromlen = sizeof(sockaddr); ret = recvfrom(m_InSock, &c, 1, 0, addr, &fromlen); if(ret != 1) { #ifdef __MYDEBUG__ std::stringstream ss; ss << WSAGetLastError(); MessageBox(NULL, ss.str().c_str(), "", MB_ICONERROR | MB_OK); #endif return Inc::ERECV; } ... This is a working example I wrote a few moments ago, and it works without the call to bind() in the client: #pragma comment(lib, "Ws2_32.lib") #define WIN32_LEAN_AND_MEAN #include <WS2tcpip.h> #include <Windows.h> #include <iostream> using namespace std; int main() { SOCKET sock; addrinfo* pAddr; addrinfo hints; sockaddr sAddr; int fromlen; const char czPort[] = "12345"; const char czAddy[] = "some ip"; WSADATA wsa; unsigned short usWSAVersion = MAKEWORD(2,2); char Buffer[22] = "TESTTESTTESTTESTTEST5"; int ret; //Start WSA WSAStartup(usWSAVersion, &wsa); //Create Socket sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //Resolve host address memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_protocol = IPPROTO_UDP; hints.ai_socktype = SOCK_DGRAM; if(getaddrinfo(czAddy, czPort, &hints, &pAddr)) { std::cerr << "Could not resolve address...\n"; std::cin.get(); return 1; } //Start Transmission while(1) { ret = sendto(sock, Buffer, sizeof(Buffer), 0, pAddr->ai_addr, pAddr->ai_addrlen); if(ret != sizeof(Buffer)) { std::cerr << "Could not send data\n"; std::cin.get(); return 1; } fromlen = sizeof(SOCKADDR); ret = recvfrom(sock, Buffer, sizeof(Buffer), 0, &sAddr, &fromlen); if(ret != sizeof(Buffer)) { std::cout << "Could not receive data - error: " << WSAGetLastError() << std::endl; std::cin.get(); return 1; } Buffer[ret-1] = '\0'; std::cout << "Received: " << Buffer << std::endl; } return 0; }
With UDP, you have to bind() the socket in the client because UDP is connectionless, so there is no other way for the stack to know which program to deliver datagrams to for a particular port. If you could recvfrom() without bind(), you'd essentially be asking the stack to give your program all UDP datagrams sent to that computer. Since the stack delivers datagrams to only one program, this would break DNS, Windows' Network Neighborhood, network time sync.... You may have read somewhere on the net that binding in a client is lame, but that advice only applies to TCP connections.
3,057,101
3,057,248
C++ function-pointer and inheritance
I have an generic math-method, that operates under a set of functions (with a lot of variables and states, so it can't be static). I've implemented method in parent class and I want to declare a different set of functions in every child-class. I've try to do something like this: class A { public: typedef int (A::*func)(); func * fs; void f() { /*call functions from this->fs*/ } }; class B : public A { public: int smth; B(int smth) { this->smth = smth; //user-provided variables //there may be a lot of functions with same interface this->fs = new func[1]; fs[0] = &B::f; } int f() { return smth + 1; } }; It fails with this error: error C2440: '=' : cannot convert from 'int (__thiscall B::* )(void)' to 'A::func' Or "IntelliSense: a pointer to a bound function may only be used to call the function" if I try to use &this->f;
Curiously recurring template pattern would help. template<typename Derived> class A { public: typedef int (Derived::*func)(); func * fs; void f() { Derived* const This = static_cast<Derived*>(this); /* call functions like (This->*(fs[0]))() */ } }; class B : public A<B> { public: int smth; B(int smth) { this->smth = smth; //user-provided variables //there may be a lot of functions with same interface this->fs = new func[1]; fs[0] = &B::f; } int f() { return smth + 1; } };
3,057,105
3,059,028
Thread raising event gets blocked by handlers?
I am raising an event from managed C++ which is handled by a C# app. Is the C# event handler executed on the same thread it was raised from C++ ?? In other words, Is raising event blocking for C++ until it is completely handled by C#?
Event handler invocation is synchronous by default in .NET, and since your code is both Managed C++ and C#, it is all ".NET". If you wish your event handlers to function asynchronously, you could simply attach a handler on the C# side that either starts another Thread to do the work, drops a worker into ThreadPool, or invokes another method to handle the work asynchronously via a Delegate using asynchronous programming. The handler would then return quickly, allowing the C# work to execute in the background while the MC++ code can continue invoking other listeners of the event. Make sure that if you do execute the code that actually handles the event asynchronously, that the C++ code does not expect data in the event arguments to be modified by the handlers. This would be the case if something like CancelEventArgs were used.
3,057,136
3,057,502
Is Private Bytes >> Working Set normal?
OK, this may sound weird, but here goes. There are 2 computers, A (Pentium D) and B (Quad Core) with almost the same amount of RAM running Windows XP. If I run the same code on both computers, the allocated private bytes in A never goes down resulting in a crash later on. In B it looks like the private bytes is constantly deallocated and everything looks fine. In both computers, the working set is deallocated and allocated similarly. Could this be an issue with manifests or DLLs (system)? I'm clueless. Also, I compiled the executable on A and ran it on B and it worked. Note: I observed the utilized memory with Process Explorer. Question: During execution (where we have several allocations and deallocations) is it normal for the number of private bytes to be much bigger (1.5 GB vs 70 MB) than the working set?
The fact that a memory leak (increasing private bytes) doesn't have an effect on working set is no surprise. The working set size is determined by the number of memory pages the application has touched recently. Private bytes is the amount of memory that a process has allocated (and not shared with other processes). If an application is forgetting to free objects that it is no longer using (a memory leak), then it's private bytes will not go down, but the working set will because it's not actively using that memory. See http://technet.microsoft.com/en-us/library/cc780836.aspx for details on the types of statistics for resources that Windows can track for a process. You might want to look at the versions of the DLLs loaded by the application on each machine - it could be that a patch or service pack needs to be installed on the machine with the memory leak to fix the problem. Process Explorer can also show details of the DLLs loaded in a process.
3,057,153
3,061,727
Tips for submitting a library to Boost?
Summer is coming, and a group of friends and I are getting ready for it :) We decided to build a compile-time Arbitrary precision Unsigned Integers. We would like to provide a set of integers algorithms(functions) with the library. We have seen a number of requests for such a library(SoC2010, C++0x Standard Library wishlist). Also, a regular run-time bigint is requested usually with that, but we don't want to go into the hassle of memory management. The idea came to me from a library called TTMath, unfortunately this library works only on specific platforms because Assembly was used extensively in the library. We would like to write a standard library, depending on the C++ standard library and Boost. Also, we would like to use the available C++0x facilities in current compilers like user-defined literals and others. This would technically make the library non-standard for a while, but we think that it is a matter of time the new standards will be official. Your hints on the whole process including design, implementation, documentation, maintainable of the library are more than welcom. We are a group of students and fresh graduates who are looking for something interesting in the summer, but we see that Boost is full of gurus and we don't want to forget something too obvious. We are communicating on-line, so there is no shared white-boards :( Here is an example of using such a library: typedef our_namespace::uint<512> uint512_t; // declaring an unsigned int with 512 bits width. // After that the user is supposed to deal with it just like the native types. Thanks,
Two additional hints: a) Planning for a pure C++0x library seems not to be a good idea in the context of Boost. One of Boost's goals is to provide cross-platform/cross-compiler libraries. Usually Boost authors interested in using C++0x features do that as an alternative enabled when using a C++0x compiler. For that purpose Boost predefines a whole set of preprocessor macros, one for each of the C++0x features. b) Please consider writing to the Boost devel list with your ideas, outlining the feature set of your planned library. You may ask the same questions there, btw. I'm sure you'd get a lot of useful answers and suggestions if you did.
3,057,213
3,057,228
accessing a vector from the back
Is there a way to access an element on a vector starting from the back? I want to access the second last element.currently I'm using the following to achieve that: myVector[myVector.size() - 2] but this seems slow and clunky, is there a better way?
Not likely to be any faster, but this might look nicer: myVector.end()[-2]
3,057,346
3,057,540
Vertical Rebar (WinAPI)
I was wondering if it was possible to make a Rebar that goes vertically instead of controls horizontally? Thanks
The answer is Yes :) Google for CCS_VERT style as keyword (this one makes toolbars vertical).
3,057,448
3,057,465
Angle between 3 vertices
For example, GetAngle((0,0),(100,0),(100,100)) = 90. How could I find the angle between 3 2D Points.
Given points A, B, and C, you want the angle between AB and AC? First compute the vectors AB and AC -- it's just the coordinates of B minus coordinates of A and likewise for AC. Take the dot product of the two vectors. This is just the product of the x coordinates plus the product of the y coordinates of the vectors. Divide this number by the length of AB, and again by the length of AC. This result is the cosine of the angle between the two vectors, so take the arccos() and you have it.
3,057,826
3,058,959
ServicedComponent not being disposed in finaliser
Questions needing answers : Does the finalizer of the client side ServicedComponent call ServicedComponent.DisposeObject or Dispose? How should destruction (release of memory) occur in the com server in relation to its usage in the client? Basically - we are reaching a 2 gig limit on process size (memory) of the COM server as memory is not being released - is the solution to call explicitly call Dispose or use the using statement in the client?
You should definitely be calling either Dispose or ServicedComponent.DisposeObject on the client side. Microsoft says "It is preferable to use the Dispose design pattern rather than DisposeObject." Exactly what is happening in COM+ will depend on a few things: Is the application a Library or Server application Is object pooling being used Is JIT being used If the calls are out of process then it is possible that lease times may come into play. Understanding Enterprise Services (COM+) in .NET is one of the best COM+ articles I've read but, since it was written in 2002, I wonder if it is still 100% accurate.
3,057,845
3,057,861
C++ initializing constants and inheritance
I want to initialize constant in child-class, instead of base class. And use it to get rid of dynamic memory allocation (I know array sizes already, and there will be a few child-classes with different constants). So I try: class A { public: const int x; A() : x(0) {} A(int x) : x(x) {} void f() { double y[this->x]; } }; class B : A { B() : A(2) {} }; Pretty simple, but compiler says: error C2057: expected constant expression How can I say to compiler, that it is really a constant?
It isn't a constant though. It can still be modified by the constructor. Only a compile time constant is allowed for the size of an array. When the compiler says "constant expression", it is not meaning an expression which returns a constant value, but an constant, such as "52" or "45" or something along those lines. Use std::vector instead. EDIT: In response to "I know array sizes already, and there will be a few child-classes with different constants" The only way to do that is to use a template. template<size_t x> class A { public: void f() { double y[x]; } }; typedef A<2> B;
3,057,859
3,057,880
What's the difference between explicit and implicit assignment in C++
int value = 5; // this type of assignment is called an explicit assignment int value(5); // this type of assignment is called an implicit assignment What is the difference between those, if any, and in what cases do explicit and implicit assignment differ and how? http://weblogs.asp.net/kennykerr/archive/2004/08/31/Explicit-Constructors.aspx EDIT: I actually just found this article, which makes the whole thing a lot clearer... and it brings up another question, should you (in general) mark constructors taking a single parameter of a primitive type - numeric/bool/string - as explicit and leave the rest as they are (of course keeping watch for gotchas such as constructors like (int, SomeType = SomeType())?
They differ if a class has a constructor marked 'explicit'. Then, one of these does not work. Otherwise, no difference.
3,057,975
3,058,077
How to iterate a list of vector
If I have a vector of object vector, how can I check if A* myA is inside that vector?
Try this... #include <algorithm> bool in_vector(const std::vector<A*>& vec, const A* myA) { std::vector<A*>::const_iterator end = vec.end(); return std::find(vec.begin(), end, myA) != end; }
3,057,977
3,057,994
Rewinding std::cout to go back to the beginning of a line
I'm writing a command-line tool for Mac OS X that processes a bunch of files. I would like to show the user the current file being processed, but do not want a bazillion files polluting the terminal window. Instead I would like to use a single line to output the file path, then reuse that line for the next file. Is there a character (or some other code) to output to std::cout to accomplish this? Also, if I wanted to re-target this tool for Windows, would the solution be the same for both platforms?
"\r" should work for both windows and Mac OS X. Something like: std::cout << "will not see this\rwill see this" << std::flush; std::cout << std::endl; // all done
3,058,006
3,058,048
C++: Trouble with Pointers, loop variables, and structs
Consider the following example: #include <iostream> #include <sstream> #include <vector> #include <wchar.h> #include <stdlib.h> using namespace std; struct odp { int f; wchar_t* pstr; }; int main() { vector<odp> vec; ostringstream ss; wchar_t base[5]; wcscpy_s(base, L"1234"); for (int i = 0; i < 4; i++) { odp foo; foo.f = i; wchar_t loopStr[1]; foo.pstr = loopStr; // wchar_t* = wchar_t ? Why does this work? foo.pstr[0] = base[i]; vec.push_back(foo); } for (vector<odp>::iterator iter = vec.begin(); iter != vec.end(); iter++) { cout << "Vec contains: " << iter->f << ", " << *(iter->pstr) << endl; } } This produces: Vec contains: 0, 52 Vec contains: 1, 52 Vec contains: 2, 52 Vec contains: 3, 52 I would hope that each time, iter->f and iter->pstr would yield a different result. Unfortunately, iter->pstr is always the same. My suspicion is that each time through the loop, a new loopStr is created. Instead of copying it into the struct, I'm only copying a pointer. The location that the pointer writes to is getting overwritten. How can I avoid this? Is it possible to solve this problem without allocating memory on the heap?
... odp foo; foo.f = i; wchar_t loopStr[1]; //A foo.pstr = loopStr; //B foo.pstr[0] = base[i]; //C vec.push_back(foo); ... A - You allocate an array (of size 1) to the stack B - You assign foo.pstr to point to the array on the stack C - You assign base[i] to the first element of the array (which is on the stack) After the for loop exits its current cycle the variable loopStr is no longer in scope and its content is undefined. The next loop iteration will most likley re-use the same memory address (hence why you get the same value when you print at the end). If you have optimisations turned on your C compiler may be able to warn you about taking addresses of local variables (although I doubt it). Without using any heap allocation I would think your only option is to fix the size of foo.pstr in odp, i.e. struct odp { int f; wchar_t pstr[1]; }; or allocate the array on the heap as part of the odp initialisation ... odp foo; foo.f = i; foo.pstr = new wchar_t [1]; foo.pstr[0] = base[i]; vec.push_back(foo); ... better still use std::wstring since you are using c++, and let it do the memory allocation and management for you.
3,058,101
3,058,144
Setting the default stack size on Linux globally for the program
So I've noticed that the default stack size for threads on linux is 8MB (if I'm wrong, PLEASE correct me), and, incidentally, 1MB on Windows. This is quite bad for my application, as on a 4-core processor that means 64 MB is space is used JUST for threads! The worst part is, I'm never using more than 100kb of stack per thread (I abuse the heap a LOT ;)). My solution right now is to limit the stack size of threads. However, I have no idea how to do this portably. Just for context, I'm using Boost.Thread for my threading needs. I'm okay with a little bit of #ifdef hell, but I'd like to know how to do it easily first. Basically, I want something like this (where windows_* is linked on windows builds, and posix_* is linked under linux builds) // windows_stack_limiter.c int limit_stack_size() { // Windows impl. return 0; } // posix_stack_limiter.c int limit_stack_size() { // Linux impl. return 0; } // stack_limiter.cpp int limit_stack_size(); static volatile int placeholder = limit_stack_size(); How do I flesh out those functions? Or, alternatively, am I just doing this entirely wrong? Remember I have no control over the actual thread creation (no new params to CreateThread on Windows), as I'm using Boost.Thread.
You do not need to do this. The machine's physical memory is employed only where it is needed by a demand page fault system. Even if the thread stacks are significantly larger than the amount you are using the extra size is in virtual address space and does not tie up physical RAM. Had physical RAM been tied up at that rate, a typical machine would run out of memory with only a few dozen processes running. You can see from a ps -Al that quite a few more than that execute concurrently.
3,058,109
3,066,411
Named captured substring in pcre++
I want to capture named substring with the pcre++ library. I know the pcre library has the functionality for this, but pcre++ has not implemented this. This is was I have now (just a simple example): pcrepp::Pcre regex("test (?P<groupName>bla)"); if (regex.search("test bla")) { // Get matched group by name int pos = pcre_get_stringnumber( regex.get_pcre(), "groupName" ); if (pos == PCRE_ERROR_NOSUBSTRING) return; // Get match std::string temp = regex[pos - 1]; std::cout << "temp: " << temp << "\n"; } If I debug, pos return 1, and that is right, (?Pbla) is the 1th submatch (0 is the whole match). It should be ok. But... regex.matches() return 0. Why is that :S ? Btw. I do regex[pos - 1] because pcre++ reindexes the result with 0 pointing to the first submatch, so 1. So 1 becomes 0, 2 becomes 1, 3 becomes 2, etc. Does anybody know how to fix this?
My mistake unfortunately, I tested the regex in my real program and there the regex was different. I used something like this: (?:/(?P<controller>[^/]+)(?:/(?P<action>[^/]+))?)? So the group name to number conversion goes well, but when i try to access the group i get index of range because of the (?: ... )? groups. I just added a check if the group index i in the correct range, it is i could use the group. Sorry for asking it here too early.
3,058,267
3,058,343
Nested Class member function can't access function of enclosing class. Why?
Please see the example code below: class A { private: class B { public: foobar(); }; public: foo(); bar(); }; Within class A & B implementation: A::foo() { //do something } A::bar() { //some code foo(); //more code } A::B::foobar() { //some code foo(); //<<compiler doesn't like this } The compiler flags the call to foo() within the method foobar(). Earlier, I had foo() as private member function of class A but changed to public assuming that B's function can't see it. Of course, it didn't help. I am trying to re-use the functionality provided by A's method. Why doesn't the compiler allow this function call? As I see it, they are part of same enclosing class (A). I thought the accessibility issue for nested class meebers for enclosing class in C++ standards was resolved. How can I achieve what I am trying to do without re-writing the same method (foo()) for B, which keeping B nested within A? I am using VC++ compiler ver-9 (Visual Studio 2008). Thank you for your help.
foo() is a non-static member function of A and you are trying to call it without an instance. The nested class B is a seperate class that only has some access privileges and doesn't have any special knowledge about existing instances of A. If B needs access to an A you have to give it a reference to it, e.g.: class A { class B { A& parent_; public: B(A& parent) : parent_(parent) {} void foobar() { parent_.foo(); } }; B b_; public: A() : b_(*this) {} };
3,058,481
3,058,506
c++ callback syntax in a class
I am trying to figure out the syntax to register a callback with this 3rd party software. I think it is probably a basic question, I just am not too familiar with c++. They have a method for registering a callback function so their code can call a function in my code when an event happens. They provided a working example that registers the callback from the main file, but I want to know how to do it when working inside a class Their method signature: smHTRegisterHeadPoseCallback(smEngineHandle engine_handle, void *user_data, smHTHeadPoseCallback callback_fun); Working example from the main file: void STDCALL receiveHeadPose(void *,smEngineHeadPoseData head_pose, smCameraVideoFrame video_frame) { ... } void main() { ... smHTRegisterHeadPoseCallback(engine_handle,0,receiveHeadPose) ... } But I want to use this from my class MyClass.h class FaceEngine { public: void STDCALL receiveFaceData(void *, smEngineFaceData face_data, smCameraVideoFrame video_frame); ... MyClass.cpp void FaceEngine::Start(void) { rc = smHTRegisterFaceDataCallback(hFaceAPIEngine,0,&FaceEngine::receiveFaceData); ... Results in this compiler error: Error 1 error C2664: 'smHTRegisterFaceDataCallback' : cannot convert parameter 3 from 'void (__stdcall FaceEngine::* )(void *,smEngineFaceData,smCameraVideoFrame)' to 'smHTFaceDataCallback' d:\stuff\programming\visual studio 2008\projects\tut02_vertices\faceengine.cpp 43 Beard If my question isn't clear please let me know how I can clarify.
You need to use a trampoline function as member functions can't be called without an instance: void STDCALL trampoline(void* data, smEngineHeadPoseData hp, smCameraVideoFrame vf) { static_cast<FaceEngine*>(data)->receiveFaceData(hp, vf); } // ... register: smHTRegisterFaceDataCallback(hFaceAPIEngine, static_cast<void*>(this), &trampoline); Note that this uses the user-data parameter to pass the this pointer, so the trampoline function knows what instance to call the member function on.
3,058,552
3,058,595
Raw OpenGL equivillant of GLUPerspective?
how could I do the same as GluPerspective without Glu? Thanks ex: gluPerspective(45.0, (float)w / (float)h, 1.0, 200.0);
void gluPerspective( GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar ) { GLdouble xmin, xmax, ymin, ymax; ymax = zNear * tan( fovy * M_PI / 360.0 ); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; glFrustum( xmin, xmax, ymin, ymax, zNear, zFar ); }
3,058,561
3,058,733
How do I make a class whose interface matches double, but upon which templates can be specialized?
How do I make a class whose interface matches double, but whose templated types do not dynamic cast to double? The reason is that I have a run-time type system, and I want to be able to have a type that works just like double: template<int min_value, int max_value> class BoundedDouble: public double {}; And then use template specialization to get run-time information about that type: template<typename T> class Type { etc. } template<int min_value, int max_value> class Type<BoundedDouble<min_value, max_value>> { int min() const { return min_value; } etc. } But, you can't inherit from double...
You can't derive from native types. Use composition instead: #include <cstdlib> #include <string> #include <stdexcept> #include <iostream> using namespace std; template<typename Type = double, const Type& Min = -10.0, const Type& Max = 10.0> class Bounded { public: Bounded() {}; Bounded(const Type& rhs) : val_(rhs) { if(rhs > Max || rhs < Min) throw logic_error("Out Of Bounds"); } operator Type () const { return val_; } Type val_; }; int main() { typedef Bounded<double, -10.0, 10.0> double_10; double_10 d(-4.2); cout << "d = " << d << "\n"; double d_prime = d; cout << "d_prime = " << d_prime << "\n"; double_10 d2(-42.0); cout << "d2 = " << d << "\n"; return 0; } The output is: d = -4.2 d_prime = -4.2
3,058,820
3,067,365
How do you return a pointer to a base class with a virtual function?
I have a base class called Element, a derived class called Vector, and I'm trying to redefine two virtual functions from Element in Vector. //element.h template <class T> class Element { public: Element(); virtual Element& plus(const Element&); virtual Element& minus(const Element&); }; and in another file //Vector.h #include "Element.h" template <class T> class Vector: public Element<T> { T x, y, z; public: //constructors Vector(); Vector(const T& x, const T& y = 0, const T& z =0); Vector(const Vector& u); ... //operations Element<T>& plus(const Element<T>& v) const; Element<T>& minus(const Element<T>& v) const; ... }; //sum template <class T> Element<T>& Vector<T>::plus(const Element<T>& v) const { Element<T>* ret = new Vector((x + v.x), (y + v.y), (z + v.z)); return *ret; } //difference template <class T> Element<T>& Vector<T>::minus(const Element<T>& v) const { Vector<T>* ret = new Vector((x - v.x), (y - v.y), (z - v.z)); return *ret; } but I always get error: 'const class Element' has no member named 'x' So, can I define my virtual functions to take Vector& as an argument instead, or is there a way for me to access the data members of Vector through a pointer to Element? I'm still fairly new to inheritance polymorphism, fyi. EDIT: Trying a static_cast (as suggested below) hasn't solved my problem – or I have the wrong syntax for it. I've tried a static cast in the two ways I could imagine, and now my error is > error: 'const class Element' has no member named 'x' My updated code is: //sum template Element& Vector::plus(const Element& v) const { Element* ret = static_cast*>(operator new((x + v.x), (y + v.y), (z + v.z))); return *ret; } //difference template <class T> Element<T>& Vector<T>::minus(const Element<T>& v) const { Element<T>* ret = new Vector<T>(static_cast<Vector*>((x - v.x), (y - v.y), (z - v.z))); return *ret; } I thought the whole point of inheritance polymorphism is that a reference to a derived class is practically the same as a reference to a base class. Why do I have to jump through these hoops?
compiler says what is obvious: the base class Element doesn't have member variable 'x' because x is declared and in Vector and not in Element. Try this: Element<T>& plus(const Element<T>& v) const { const Vector<T> & vect = dynamic_cast<const Vector<T> &>(v); Vector<T>* ret = new Vector((x + vect.x), (y + vect.y), (z + vect.z)); return *ret; } Note that If you return a pointer in that manner, you could have any memory leak problem.
3,058,833
3,058,845
Strange exception phenomenon in Windows 7
I spot some interesting articles about exception handle in CodeProject http://www.codeproject.com/KB/cpp/seexception.aspx After reading, I decided to do some experiment. The first time I try to execute the following code char *p; p[0] = 0; The program died without question. But After several times when I executed the same problem binary code, it magically did fine. Even the following code is doing well. Any clue or explanation? char *p; p[1000] = 'd'; cout<<p[1000]<<endl; My O/S is Windows 7 64bit and compiler is VS2008 rc1.
Dereferencing a pointer that doesn't point to an object (for example, an uninitialized pointer) results in undefined behavior. This means that anything can happen. Typically, writing via an uninitialized pointer will cause your program to crash--either immediately or at some point in the future. It is conceivable that your program could appear to continue running correctly, but you can never rely on that.
3,058,878
3,059,339
OpenGL polygons stuck at top left?
I'm using theallegro library and through it OpenGL. I enable depth testing, then upon resize I do: glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(0,event.display.width,event.display.height,0,1,300); Then my drawing looks like: float BOX_SIZE = 200.0f; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glRotatef(0.5, 0, 0.0f, 1.0f); glBegin(GL_QUADS); //Top face glColor3f(1.0f, 1.0f, 0.0f); glNormal3f(0.0, 1.0f, 0.0f); glVertex3f(500 + -BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2); glVertex3f(500 + -BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2); glVertex3f(500 + BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2); glVertex3f(500 + BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2); //Bottom face glColor3f(1.0f, 0.0f, 1.0f); glNormal3f(0.0, -1.0f, 0.0f); glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2); glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2); glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2); glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2); //Left face glNormal3f(-1.0, 0.0f, 0.0f); glColor3f(0.0f, 1.0f, 1.0f); glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2); glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2); glColor3f(0.0f, 0.0f, 1.0f); glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2); glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2); //Right face glNormal3f(1.0, 0.0f, 0.0f); glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2); glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2); glColor3f(0.0f, 1.0f, 0.0f); glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2); glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2); glEnd(); glEnable(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glColor3f(1.0f, 1.0f, 1.0f); glBegin(GL_QUADS); //Front face glNormal3f(0.0, 0.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2); glTexCoord2f(1.0f, 0.0f); glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2); glTexCoord2f(1.0f, 1.0f); glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2); glTexCoord2f(0.0f, 1.0f); glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2); //Back face glNormal3f(0.0, 0.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2); glTexCoord2f(1.0f, 0.0f); glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2); glTexCoord2f(1.0f, 1.0f); glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2); glTexCoord2f(0.0f, 1.0f); glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2); glEnd(); glDisable(GL_TEXTURE_2D); //code goes here al_flip_display(); for some reason the cube no matter how I translate it seems to extend from 0,0 and theres always a vertex at 0,0. What have I done wrong? Thanks
I don't know any specifics of the allegro library, but two things come to mind when reading your code snippet. Why don't you call glViewport(event.display.width,event.display.height) upon resize? The glFrustum call usually shouldn't depend on the display size. Do you ever call glMatrixMode(GL_MODELVIEW)? Otherwise all matrix operations will be applied to the projection matrix. I hope that helps.
3,058,992
3,059,528
All possible paths in a cyclic undirected graph
I'm trying to develop an algorithm that identifies all possible paths between two nodes in a graph, as in this example: . in fact, i just need to know which nodes appear in all existing paths. in the web only got references about DFS, A* or dijkstra, but i think they doesn't work in this case. Does anyone know how to solve it?
You can find all paths using DFS like |Vlad described. To find which nodes appear in every path, you could just maintain an array of booleans that says whether each node has appeared in every path so far. When your DFS finds a path, go through each vertex not in the path and set the corresponding array value to false. When you are done, only the vertices with values of true will be the ones that appear in every path. Pseudocode: int source; int sink; int nVerts; bool inAllPaths[nVerts]; // init to all true bool visited[nVerts]; // init to all false stack<int> path; // init empty bool dfs(int u) if (visited[u]) return; if (u == sink) for i = 0 to nVerts-1 if !stack.contains(i) inAllPaths[i] = false; return true; else visited[u] = true; stack.push(u); foreach edge (u, v) dfs(v); stack.pop(); visited[u] = false; return false; main() dfs(source); // inAllPaths contains true at vertices that exist in all paths // from source to sink. However, this algorithm isn't very efficient. For example, in a complete graph of n vertices (all vertices have edges to all others) the number of paths will be n! (n factorial). A better algorithm would be to check for the existence in every path of each vertex separately. For each vertex, try to find a path from the source to the sink without going to that vertex. If you can't find one, that's because the vertex appears in every path. Pseudocode: // Using the same initialisation as above, but with a slight modification // to dfs: change the foreach loop to foreach edge (u, v) if (dfs(v)) return true; // exit as soon as we find a path main() for i = 0 to nVerts-1 set all visited to false; if (inAllPaths[i]) visited[i] = true; if (dfs(source)) inAllPaths[i] = false; visited[i] = false; Unfortunately, this still has exponential worst case when searching for a path. You can fix this by changing the search to a breadth-first search. If I'm not mistaken, this should give you O(VE) performance.
3,059,032
3,059,120
Documentation for Qt documentation comments? Qt + Doxygen?
Where can I find documentation for Qt documentation comments? I'm referring to how Qt uses a specific style for documentation comments, like so: /*! \class MyClassName \brief The MyClassName class is used as an example on Stack Overflow. This class serves a few functions, the most important being: \list \i So people can understand my question. \i So people can have a few laughs at the comedy in my example. \endlist */ ...you get the picture. So where can I find information about all the switches, like \class, \list, \brief, etc. Also, what tool(s) do I use to generate documentation files from these comments in my source files? Does Doxygen support this syntax?
Don't use qdoc. It is deprecated. Use Doxygen, which is based on qdoc anyway. That said, the documentation (in qdoc format :-D ) is here.
3,059,143
3,059,228
what the snippet of code does
I would like to know what the snippet of code does.. Drive[0] = 'A'; Drive[1] = ':'; Drive[2] = '\\'; Drive[3] = 0; DriveMask = GetLogicalDrives(); for( anIndex = 0; anIndex < 26; anIndex++ ) { if( DriveMask & 1 ) { Drive[0] = 'A' + anIndex; DriveMask >>= 1; } } Please let me know your answer. Thank you for your time to read my post.
It's enumerating all the possible attached drives between A:\ and Z:\ and checking to see whether they're removable (eg CD, floppy). It loops 26 times, and each time DriveMask >>= 1; causes the bitmask to be shifted right by 1 bit, so that each logical drive can be tested for via the if( DriveMask & 1 ) in succession. GetDriveType() requires a drive path, so the label is constructed by adding the loop count to the letter A (so A, B, C, D, ..., Z) and leaving the previously-initialized :\ part in-place.
3,059,343
3,063,343
How to give 'Everybody' full rights to a file (programmatically)
I'm modifying an old C++ program to run on Vista. It does not require Admin privileges. I've changed the code to put logfiles in \ProgramData\MyApp\. These logfiles are written with the stdio functions (fopen, fprintf, fclose). Here's the problem: UserA runs the program first, it creates \ProgramData\MyApp\MyLogFile.txt using CreateFile() UserB runs the program next, it tries to append to MyLogFile.txt and gets access denied. I tried creating a null SECURITY_DESCRIPTOR and passing that to CreateFile(). That does create a file with "no permissions assigned", but it seems as if the first user to write to the file takes ownership and afterwards all the other non-admin users are out of luck. It's important that all users share the same logfiles, but it's also important that I change as little code as possible. Edited to add: \ProgramData\MyApp is created by a standard Visual Studio installer. (I don't see any place to set directory security.) When it creates \MyApp it grants Users these permissions: Read & execute List folder contents Read Special permissions Under Advanced I see that Special permissions includes: Create files / write data Create folders / append data Write attributes Write extended attributes
+1 to everyone for trying, but eventually I found the answer here: how to change the ACLs from c++? I did have to change one line of that solution, from this: ea[0].grfAccessMode = DENY_ACCESS; to this: ea[0].grfAccessMode = GRANT_ACCESS;
3,059,358
3,059,378
how to get the type of a deferred template parameter
Is there a way to get the defered type of a class template parameter ? template <class TPtr> struct foo { typedef TPtr ptr_type; typedef ??? element_type; /* shall be the type of a deferred TPtr*/ }; so foo<const char*>::element_type results in const char, and foo<std::vector<int>::iterator_type>::element_type results in int. i am aware of that i can use the value_type typedef for c++ iterators (like std::vector<int>::iterator_type::value_type), but raw pointers havent got a value_type typedef, so i am out of luck there.
If TPtr can only be a pointer, you're looking for Boost's remove_pointer. If you're wondering how in the world that works, it uses partial specialization in this manner: template<typename T> struct RemovePointer; template<typename T> struct RemovePointer<T*> { typedef T Type; }; int main() { RemovePointer<int*>::Type foobar; // foobar has the type int return 0; } If TPtr can be either an iterator or a pointer, you need the iterator_traits class, which is part of the standard library. In your case, it's used like this: template <class TPtr> struct foo { typedef TPtr ptr_type; // The compiler won't know for sure if value_type is actually // a type until TPtr is known. The typename keyword is a hint // to the compiler so it doesn't cause an error. typedef typename iterator_traits<TPtr>::value_type element_type; }; Believe it or not, it works by partial specialization as well. It's basically defined like this: // Primary template for iterators template<class Iterator> struct iterator_traits { typedef typename Iterator::difference_type difference_type; typedef typename Iterator::value_type value_type; typedef typename Iterator::pointer pointer; typedef typename Iterator::reference reference; typedef typename Iterator::iterator_category iterator_category; }; // Partial specializations for pointers template<class T> struct iterator_traits<T*> { typedef ptrdiff_t difference_type; typedef T value_type; typedef T* pointer; typedef T& reference; typedef random_access_iterator_tag iterator_category; }; template<class T> struct iterator_traits<const T*> { typedef ptrdiff_t difference_type; typedef T value_type; typedef const T* pointer; typedef const T& reference; typedef random_access_iterator_tag iterator_category; }; That's why the iterator_traits class works on both iterators and pointers.
3,059,649
3,059,673
STL in C++ how does it work
I have very technical question, I was working with C, and now I'm studying C++, if I have for example this class class Team { private: list<Player> listOfPlayers; public: void addPlayer(string firstName, string lastName, int id) { Player newPlayer(string firstName, string lastName, int id); listOfPlayers.push_back(Player(string firstName, string lastName, int id)); } }; this is a declaration of the Player: class Player{ private: string strLastName; string strFirstName; int nID; public: Player(string firstName, string lastName, int id); }; and this is my constructor of Player: Player::Player(string firstName, string lastName, int id){ nId = id; string strFirstName = firstName; string strLastName = lastName; } so my question is when I call function addPlayer what exactly is going on with program, in my constructor of Account do I need to allocate new memory for new Player(cause in C I always use malloc) for strFirstName and strLastName, or constructor of string of Account and STL do it without me, thanks in advance (if you don't want to answer my question please at least give me some link with information) thanks in advance
Here's a "correct" implementation of what you have now: #include <list> #include <string> class Player { private: std::string strLastName; std::string strFirstName; int nID; public: // You should pass std::strings to functions by const reference. // (see Kirill V. Lyadvinsky's comment to OP's question) Player(const std::string& firstName, const std::string& lastName, int id); }; // What follows after the colon is called the initializer list. Player::Player(const std::string& firstName, const std::string& lastName, int id) : strFirstName(firstName), strLastName(lastName), nID(id) {} class Team { private: std::list<Player> listOfPlayers; public: void addPlayer(const std::string& firstName, const std::string& lastName, int id) { // Constructs a Player instance and adds it to the list. listOfPlayers.push_back(Player(firstName, lastName, id)); } }; The push_back() function of list allocates a new node that holds the Player instance and pointers to other nodes, so you have sort of a "chain" of Player instances. For your question about Account, if you have this: class Account { private: std::string strFirstName; std::string strLastName; }; Then you don't need to worry about allocating/freeing memory for the character arrays, for std::string will handle that for you.
3,059,756
3,059,944
C++: how to truncate the double in efficient way?
I would like to truncate the float to 4 digits. Are there some efficient way to do that? My current solution is: double roundDBL(double d,unsigned int p=4) { unsigned int fac=pow(10,p); double facinv=1.0/static_cast<double>(fac); double x=static_cast<unsigned int>(d*fac)*facinv; return x; } but using pow and delete seems to me not so efficient. kind regards Arman.
round(d*10000.0)/10000.0; or if p must be variable; double f = pow(10,p); round(d*f)/f; round will usually be compiled as a single instruction that is faster than converting to an integer and back. Profile to verify. Note that a double may not have an accurate representation to 4 decimal places. You will not truly be able to truncate an arbitrary double, just find the nearest approximation.
3,059,768
3,059,848
Qt - QTimeEdit as a timer viewer
I have a QTimeEdit which I want to set to some value and the each second I want to decrease by 1 the value that shows the QTimeEdit. So when it will be 0, the I want to have a QMeesageBox that says "Your time is off.". Can I some how do this with QTimeEdit interface, or I should use QTimer?
You can use QTimeEdit for displaying the time but you will have to use QTimer to decrease the time every second. You can do something like this: timeEdit->setTime(...); //set initial time QTimer timer; timer.start(1000); //timer will emit timeout() every second connect(&timer, SIGNAL(timeout()), this, SLOT(slotTimeout())); void slotTimeout() { QTime time = timeEdit->time().addSecs(-1); timeEdit->setTime(time); if (time == QTime(0, 0)) //time is zero, show message box }
3,059,917
3,059,964
Are unspecified and undefined behavior required to be consistent between compiles of the same program with the same compiler in the same environment?
Let's pretend my program contains a specific construct the C++ Standard states to be unspecified behavior. This basically means the implementation has to do something reasonable but is allowed not to document it. But is the implementation required to produce the same behavior every time it compiles a specific construct with unspecified behavior or is it allowed to produce different behavior in different compiles? What about undefined behavior? Let's pretend my program contains a construct that is UB according to the Standard. The implementation is allowed to exhibit any behavior. But can this behavior differ between compiles of the same program on the same compiler with same settings in the same environment? In other words, if I dereference a null pointer on line 78 in file X.cpp and the implementation formats the drive in such case does it mean that it will do the same after the program is recompiled? The question is... I compile the same program with the same compier in the same environment with the same compiler settings. Will construct stated to be unspecified behavior and undefined behavior produce each the same behavior on each compile or are they allowed to differ between compiles?
Undefined behavior can vary between runs of the same program, and even between execution of the same code in the same run of the program. As an example, the value of an uninitialized (automatic) variable is undefined, and then its actual value is just whatever value that happened to be at that place in memory. Obviously, this can vary. EDIT: This goes for unspecified behavior too. For example, the order of evaluation of function arguments is unspecified, so if they have side effects, those side effects can occur in any order. This may print "Hi!Ho!" or "Ho!Hi!": f( printf("Hi!"), printf("Ho!") ); This can vary between executions, too. As the standard says: "An instance of the abstract machine can thus have more than one possible execution sequence for a given program and a given input." The difference is that with undefined behavior, anything can happen: the computer can explode, reformat the disk, or whatever. If the behavior is unspecified, the computer is not allowed to explode. There is also implementation-defined behavior, such as the value of sizeof(int). This must be the same at all times, for the same compiler.
3,059,932
3,059,970
Why would I use a struct in a program?
I see lot of struct code like below struct codDrives { WCHAR letter; WCHAR volume[100]; } Drives[26]; We can use variables or array something like that to store the data. But I am not sure why would I use a struct in the programs?
Structs are inherited from C, and in C++ they are almost identical to classes. The difference is that the members of a struct are by default public, while class members are by default private. So the typical use of structs in C++ is dummy data structures which contain no logic (only - possibly - constructors and/or necessary operators). On a more general level, classes / structs are used to group together conceptionally related data pieces. E.g. for representing a person, you may need his/her first name, surname, gender, date of birth etc. It is convenient to define a struct containing all these pieces of data as members. Then you can store and pass around instances of this struct instead of a whole bunch of distinct variables. This makes the code cleaner, less error prone, more readable and easier to maintain.
3,059,946
3,060,248
localtime_r supposed to be thread safe, but causing errors in Valgrind DRD
I searched google as much as I could but I couldn't find any good answers to this. localtime_r is supposed to be a thread-safe function for getting the system time. However, when checking my application with Valgrind --tool=drd, it consistantly tells me that there is a data race condition on this function. Are the common search results lying to me, or am I just missing something? It doesn't seem efficient to surround each localtime_r call with a mutex, especially if it is supposed to by thread safe in the first place. here is how i'm using it: timeval handlerTime; gettimeofday(&handlerTime,NULL); tm handlerTm; localtime_r(&handlerTime.tv_sec,&handlerTm); Any ideas?
If the documentation says it is reentrant (and thus thread-safe), then it is. If ever there was a bug in the code (not your code) and the function wasn't really thread-safe, there is nothing much you can do about it (unless using another function), and it's not up to you to fix this in your code: the function must behave the way it is documented. However, I would be careful with the results given by valgrind. It is a great tool, and I use it often. But sometimes, it is just wrong. And for something as hard as detecting race conditions, I would be even more careful about what it says. Especially about a standard function that is beeing used for decades. My advice here would be: just ignore it. If you ever experience issues and believe localtime_r() is responsible for it, write to the appropriate mailing-list to report the issue, and/or use another function. In the meanwhile, you should be just fine.
3,060,006
3,060,024
Is it worth setting pointers to NULL in a destructor?
Imagine I have a class that allocates memory (forget about smart pointers for now): class Foo { public: Foo() : bar(new Bar) { } ~Foo() { delete bar; } void doSomething() { bar->doSomething(); } private: Bar* bar; }; As well as deleting the objects in the destructor is it also worth setting them to NULL? I'm assuming that setting the pointer to NULL in the destructor of the example above is a waste of time.
Since the destructor is the last thing that is called on an object before it "dies," I would say there is no need to set it to NULL afterwards. In any other case, I always set a pointer to NULL after calling delete on it.
3,060,015
3,060,047
organizing external libraries and include files
Over the years my projects use more and more external libraries, and the way I did it starts feeling more and more awkward (although, that has to be said, it does work flawlessly). I use VS on Windows, CMake on others, and CodeComposer for targetting Digital Signal Processors (DSPs) on Windows. Except for the DSPs, both 32bit and 64bit platforms are used. Here's a sample of what I am doing now; note that as shown, the different external libraries themselves are not always organized in the same way. Some have different lib/include/src folders, others have a single src folder. Some came ready-to-use with static and/or shared libraries, others were built /path/to/projects /projectA /projectB /path/to/apis /apiA /src /include /lib /apiB /include /i386/lib /amd64/lib /path/to/otherapis /apiC /src /path/to/sharedlibs /apiA_x86.lib -->some libs were built in all possible configurations /apiA_x86d.lib /apiA_x64.lib /apiA_x64d.lib /apiA_static_x86.lib /apiB.lib -->other libs have just one import library /path/to/dlls -->most of this directory also gets distributed to clients /apiA_x86.dll and it's in the PATH /apiB.dll Each time I add an external libary, I roughly use this process: build it, if needed, for different configurations (release/debug/platform) copy it's static and/or import libraries to 'sharedlibs' copy it's shared libraries to 'dlls' add an environment variable, eg 'API_A_DIR' that points to the root for ApiA, like '/path/to/apis/apiA' create a VS property sheet and a CMake file to state include path and eventually the library name, like include = '$(API_A_DIR)/Include' and lib = apiA.lib add the propertysheet/cmake file to the project needing the library It's especially step 4 and 5 that are bothering me. I am pretty sure I am not the only one facing this problem, and would like see how others deal with this. I was thinking to get rid of the environment variables per library, and use just one 'API_INCLUDE_DIR' and populating it with the include files in an organized way: /path/to/api/include /apiA /apiB /apiC This way I do not need the include path in the propertysheets nor the environment variables. For libs that are only used on windows I even don't need a propertysheet at all as I can use #pragmas to instruct the linker what library to link to. Also in the code it will be more clear what gets included, and no need for wrappers to include files having the same name but are from different libraries: #include <apiA/header.h> #include <apiB/header.h> #include <apiC_version1/header.h> The withdrawal is off course that I have to copy include files, and possibly** introduce duplicates on the filesystem, but that looks like a minor price to pay, doesn't it? ** actually once libraries are built, the only thing I need from them is the include files and thie libs. Since each of those would have a dedicated directory, the original source tree is not needed anymore so can be deleted..
Why not use file system links? ln -s /path/to/apis/apiA/include /path/to/api/include/apiA Voilá. Similar can be done on Windows, but I don't have the command line handy right now.
3,060,157
3,060,164
What determines when a destructor is called for a temporary object in C++?
Guys I've asked few days ago a question and didn't have really time to check it and think about it, but now I've tried one of the solutions and I can't understand why does it work? I mean why destructor is called at the end of line like this: #include "stdafx.h" #include "coutn.h" #define coutn coutn() int _tmain(int argc, _TCHAR* argv[]) { coutn << "Line one " << 1;//WHY DTOR IS CALLED HERE coutn << "Line two " << " and some text."; return 0; } I assume that it has something to do with lifetime of an object but I'm not sure what and how. As I think of it there are two unnamed objects created but they do not go out of scope so I can't understand for what reason is dtor called. Thank you.
coutn() create a temporary object, which will be destroyed at the next sequence point (the end of the line in this case).
3,060,187
3,060,196
an error "has no member named"
I have this snippet of the code account.cpp #include "account.h" #include <iostream> #include <string> using namespace std; Account::Account(string firstName, string lastName, int id) : strFirstName(firstName), strLastName(lastName), nID(id) {} void Account::printAccount(){ cout << strFirstName; } account.h #include <string> using std::string; class Account{ private: string strLastName; //Client's last name string strFirstName; //Client's first name int nID; //Client's ID number int nLines; //Number of lines related to account double lastBill; public: Account(string firstName, string lastName, int id); void printAccount(); }; company.h #ifndef CELLULAR_COMPANY_H #define CELLULAR_COMPANY_H #include <string> #include <list> #include <iostream> #include "account.h" using namespace std; class Company { private: list<Account> listOfAccounts; public: void addAccount(string firstName, string lastName, int id) { Account newAccount(firstName, lastName, id); listOfAccounts.push_back(newAccount); } void printAccounts(){ for(list<Account>::iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){ i.printAccount; //here bug } } }; #endif // CELLULAR_COMPANY_H main.cpp #include "cellularcompany.h" int main(){ Company newCompany; newCompany.addAccount("Pavel", "Nedved", 11111); newCompany.printAccounts(); return 0; } can somebody please explain what does my error mean? thanks in advance (I have it in company.h see comment there) I have bug 'struct std::_List_iterator<Account>' has no member named 'printAccount'
You forgot the parentheses after printAccount(). Otherwise, it's not a method call. Also, you need to use the -> operator, since it's an iterator. for(list<Account>::iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i) { i->printAccount(); // Note the ()! // This is equivalent to (*i).printAccount(); }
3,060,201
3,060,934
Compile OpenCL kernels with debug information?
How can I compile opencl kernels with debug information? If i do it like hear debugging [const char* options = "-g"; clBuildProgram( *hProgram, 0, 0, options,NULL,NULL);]: i get following error: clang: Unknown command line argument '-g'. Try: 'clang --help'
"-g" is not a supported build option in OpenCL, see section 5.4.3/5.6.3 (version 1.0/1.1 respectively) of the specification for a list of the supported options. If you're targetting a CPU then "-g" may work but is unsupported. For debugging on GPUs you could check out gDEBugger CL perhaps, I've not tried it though. NVIDIA's Parallel Nsight (formerly codenamed Nexus) has OpenCL profiling features in the beta and will support OpenCL debugging.