question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,436,115
2,437,760
Drag and Drop text - What am I missing?
I am trying to add drag-and-drop text to my Doc-View App. I added the COleDropTarget variable to the view class, registered it in OnCreate(). I added OnDragEnter(), OnDragOver(), OnDragLeave() and OnDrop() to that class as virtual overrides, but none of them are ever called. I previously had added m_pMainWnd->DragAcceptFiles(TRUE); to my App class. I tried commenting out that statement, but no affect. I tried using Spy++ to see where the messages go while I do a drag, but it logs nothing at all while I am dragging the text around in the App. What do I need? Or what else can I try, to narrow down the problem? TIA, Harvey
Solved: In using F1 to get the syntax for OnDrop and the others, MSDN gave me: virtual BOOL OnDrop( CWnd* pWnd, COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point ); But the correct virtual function does not have the first parameter and should be: virtual BOOL OnDrop( COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point ); Same with the others. So I was never actually overriding the default functions.
2,436,125
2,436,147
C++ Access derived class member from base class pointer
If I allocate an object of a class Derived (with a base class of Base), and store a pointer to that object in a variable that points to the base class, how can I access the members of the Derived class? Here's an example: class Base { public: int base_int; }; class Derived : public Base { public: int derived_int; }; Base* basepointer = new Derived(); basepointer-> //Access derived_int here, is it possible? If so, then how?
No, you cannot access derived_int because derived_int is part of Derived, while basepointer is a pointer to Base. You can do it the other way round though: Derived* derivedpointer = new Derived; derivedpointer->base_int; // You can access this just fine Derived classes inherit the members of the base class, not the other way around. However, if your basepointer was pointing to an instance of Derived then you could access it through a cast: Base* basepointer = new Derived; static_cast<Derived*>(basepointer)->derived_int; // Can now access, because we have a derived pointer Note that you'll need to change your inheritance to public first: class Derived : public Base
2,436,165
2,436,351
Emulating Dynamic Dispatch in C++ based on Template Parameters
This is heavily simplified for the sake of the question. Say I have a hierarchy: struct Base { virtual int precision() const = 0; }; template<int Precision> struct Derived : public Base { typedef Traits<Precision>::Type Type; Derived(Type data) : value(data) {} virtual int precision() const { return Precision; } Type value; }; I want a non-template function with the signature: Base* function(const Base& a, const Base& b); Where the specific type of the result of the function is the same type as whichever of a and b has the greater Precision; something like the following pseudocode: Base* function(const Base& a, const Base& b) { if (a.precision() > b.precision()) return new A( ((A&)a).value + A(b.value).value ); else if (a.precision() < b.precision()) return new B( B(((A&)a).value).value + ((B&)b).value ); else return new A( ((A&)a).value + ((A&)b).value ); } Where A and B are the specific types of a and b, respectively. I want function to operate independently of how many instantiations of Derived there are. I'd like to avoid a massive table of typeid() comparisons, though RTTI is fine in answers. Any ideas?
You can't have function() delegate to templated code directly without selecting between a massive list of all possible types, because templates are expanded at compile-time, and at compile-time function() does not know what derived types it will actually be called with. You need to have compiled instantiations of the templated code for every version of your templated operation function that will be required, which is potentially an infinite set. Following that logic, the only place that knows all of the templates that might be required is the Derived class itself. Thus, your Derived class should include a member: Derived<Precision> *operation(Base& arg2) { Derived<Precision> *ptr = new Derived<Precision>; // ... return ptr; } Then, you can define function like so, and do the dispatching indirectly: Base* function(const Base& a, const Base& b) { if (a.precision() > b.precision()) return a.operation(b); else return b.operation(a); } Note that this is the simplified version; if your operation is not symmetric in its arguments, you'll need to define two versions of the member function -- one with this in place of the first argument, and one with it in place of the second. Also, this has ignored the fact that you need some way for a.operation to get an appropriate form of b.value without knowing the derived type of b. You'll have to solve that one yourself -- note that it's (by the same logic as earlier) impossible to solve this by templating on the type of b, because you're dispatching at runtime. The solution depends on exactly what types you've got, and whether there is some way for a type of higher precision to pull a value out of an equal-or-lower precision Derived object without knowing the exact type of that object. This may not be possible, in which case you've got the long list of matching on type IDs. You don't have to do that in a switch statement, though. You can give each Derived type a set of member functions for up-casting to a function of greater precision. For example: template<int i> upCast<Derived<i> >() { return /* upcasted value of this */ } Then, your operator member function can operate on b.upcast<typeof(this)>, and will not have to explicitly do the casting to get a value of the type it needs. You may well have to explicitly instantiate some of these functions to get them to be compiled; I haven't done enough work with RTTI to say for sure. Fundamentally, though, the issue is that if you've got N possible precisions, you've got NN possible combinations, and each of these will in fact need to have separately-compiled code. If you can't use templates in your definition of function, then you have to have compiled versions of all NN of these possibilities, and somehow you have to tell the compiler to generate them all, and somehow you have to pick the right one to dispatch to at runtime. The trick of using a member function takes out one of those factors of N, but the other one remains, and there's no way to make it entirely generic.
2,436,217
2,467,014
Convert image buffer to pdf with ImageMagick in C++
I've downloaded the dll's for ImageMagick and am wondering if anybody knows of some example code to accomplish a simple task: I have generated an image in C++ and have the buffer in RGB format. I need to convert it to PDF format (without writing to a file) before sending it over a TCP socket. Is this doable with ImageMagick (or any other library)?
Assuming you're using Magick++ Magick::Image has a constructor that can create an image from an in-memory blob and a write() method that can write a PDF (and a bunch of other formats) to an in-memoy blob as well. Note that on my Linux machine ImageMagick appears to be creating a few temporary files during operation. I'm not sure that meets your requirement but it might be configurable. You can probably get a good idea from this code snippet: #include <iostream> #include <Magick++.h> using namespace std; using namespace Magick; static char imageData[] = { /* ... */ }; int main(int argc, char** argv) { /* Initialize the library */ InitializeMagick(*argv); /* Instantiate an image from RGB data */ Image image(4, // Width 14, // Height "RGB", // Color components ordering CharPixel, // Components storage type imageData);// Image data /* Write pdf in memory */ Blob b; image.write(&b, string("pdf")); /* write pdf data to cout */ /* it should be easy to send it over a socket instead */ cout.write(static_cast<const char*>(b.data()), b.length()); return 0; } Edit: I should probably add that writing binary data to cout on Windows will cause troubles unless you switch the output stream to binary mode. The code above is just a short sample so I've ignored that.
2,436,283
2,436,344
Displaying text in correct column
After getting a helpful answer here, I have run into yet another problem: displaying two or more strings in the column I want it to be displayed in. For an example of the problem I have, I want this output: Come here! where? not here! but instead get Come here! where? not here! when I use the code cout << left << setw(30) << "Come here!" << " where? " << setw(20) << "not here!" << endl; I made sure (I think) that the width of both columns could contain the two strings, but no matter how large I set the width of the columns to be, the error is still there.
As stated, setw() only applies to the next input, and you are trying to apply it to two inputs. An alternative to the other suggestions which gives you a chance to use variables in place of literal constants: #include <iostream> #include <sstream> #include <iomanip> using namespace std; int main() { stringstream ss; ss << "Come here!" << " where?"; cout << left << setw(30) << ss.str() << setw(20) << "not here!" << endl; return 0; }
2,436,499
2,436,528
Instantiating class with custom allocator in shared memory
I'm pulling my hair due to the following problem: I am following the example given in boost.interprocess documentation to instantiate a fixed-size ring buffer buffer class that I wrote in shared memory. The skeleton constructor for my class is: template<typename ItemType, class Allocator > SharedMemoryBuffer<ItemType, Allocator>::SharedMemoryBuffer( unsigned long capacity ){ m_capacity = capacity; // Create the buffer nodes. m_start_ptr = this->allocator->allocate(); // allocate first buffer node BufferNode* ptr = m_start_ptr; for( int i = 0 ; i < this->capacity()-1; i++ ) { BufferNode* p = this->allocator->allocate(); // allocate a buffer node } } My first question: Does this sort of allocation guarantee that the buffer nodes are allocated in contiguous memory locations, i.e. when I try to access the n'th node from address m_start_ptr + n*sizeof(BufferNode) in my Read() method would it work? If not, what's a better way to keep the nodes, creating a linked list? My test harness is the following: // Define an STL compatible allocator of ints that allocates from the managed_shared_memory. // This allocator will allow placing containers in the segment typedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator; //Alias a vector that uses the previous STL-like allocator so that allocates //its values from the segment typedef SharedMemoryBuffer<int, ShmemAllocator> MyBuf; int main(int argc, char *argv[]) { shared_memory_object::remove("MySharedMemory"); //Create a new segment with given name and size managed_shared_memory segment(create_only, "MySharedMemory", 65536); //Initialize shared memory STL-compatible allocator const ShmemAllocator alloc_inst (segment.get_segment_manager()); //Construct a buffer named "MyBuffer" in shared memory with argument alloc_inst MyBuf *pBuf = segment.construct<MyBuf>("MyBuffer")(100, alloc_inst); } This gives me all kinds of compilation errors related to templates for the last statement. What am I doing wrong? Is segment.construct<MyBuf>("MyBuffer")(100, alloc_inst) the right way to provide the two template parameters?
My first question: Does this sort of allocation guarantee that the buffer nodes are allocated in contiguous memory locations, i.e. when I try to access the n'th node from address m_start_ptr + n*sizeof(BufferNode) in my Read() method would it work? No. The reason being that you have the first node only. All BufferNode objects that you create are not being saved (say, in a linked-list fashion) and contribute to memory leaks. Further, this style of allocation does not gurantee contiguous memory locations. Random access (as you state later in your question) will most likely fail. To get contiguous memory, you need to create an array (perhaps dynamic) of BufferNode objects. This gives me all kinds of compilation errors related to templates for the last statement. What am I doing wrong? Difficult to say without knowing about the actual errors. Further, do you understand your code (and how Boost::Interprocess fits in or how the allocator works)? Note that the example you cite creates a vector which is guaranteed to have contiguous memory for its contained objects. The only difference here is that the objects are created on a shared memory segment rather than the free store which is what typically happens when you don't specify an allocator as the second parameter and the default one is used.
2,436,564
2,436,617
A rocket following the tracks height. Not Homing Missile
What I am trying to create is a rocket that will hug the track in a straight direction. ie) The rocket travels in a straight direction and can orientate based on its local x axis. This is so it can go up/down ramps and never hit the ground. Currently I am using PhysX opengl and C++. This is the method I'm trying right now: 1. Ray cast from ahead of the missile (ray casting downwards) 2. If the ray cast is less then the expected ray cast length, then I have to orientate up. 3. If the ray cast is more then the expected ray cast length, then I have to orientate down. Now the problem, I am having is that my missile is orientating at an arbitary angle (I'm giving it 1 degrees.) Though I think this is a bad approach because the amount of frames in the game is not as much as I would think there would be. So the rocket would run into a ramp. My main question is: is there a better way of approaching this and how? NxVec3 frontRayLoc = m_rocketConfig->getValueForKey<NxVec3>("r_frontRayCastLocation"); float threshhold = m_rocketConfig->getValueForKey<float>("r_angleThreshhold"); float predRayCastHeight = m_rocketConfig->getValueForKey<float>("r_predRayCastHeight"); NxVec3 rayGlobalPos_1 = m_actor->getGlobalPosition() + m_actor->getGlobalOrientation() * frontRayLoc; NxVec3 dir = m_actor->getGlobalOrientation() * NxVec3(0,-1.0,0); NxReal dist1 = castRay(rayGlobalPos_1, dir); // Get the percentage difference float actualFrontHeight = abs(1 - (dist1/predRayCastHeight)); // See if the percentage difference is greater then threshold // Also check if we are being shot off track if ((actualFrontHeight > threshhold) && (dist1 != m_rayMaxDist)){ // Dip Down if (dist1 > predRayCastHeight){ printf("DOWN - Distance 1: %f\n", dist1); // Get axis of rotation NxVec3 newAxis = m_actor->getGlobalOrientation() * NxVec3(1.0,0,0.0); // Rotate based on that axis m_orientateAngle = -1.0 * m_orientateAngle; // For rotating clockwise NxQuat newOrientation(m_orientateAngle, newAxis); NxMat33 orientation(newOrientation); m_orientation = m_orientation * orientation; // Orientate the linear velocity to keep speed of rocket and direct away from road NxVec3 linVel = m_actor->getLinearVelocity(); m_actor->setLinearVelocity(m_orientation * linVel); } // Go Up else if (dist1 < predRayCastHeight){ printf("UP - Distance 1: %f\n", dist1); // Get axis of rotation NxVec3 newAxis = m_actor->getGlobalOrientation() * NxVec3(1.0,0,0.0); // Rotate around axis NxQuat newOrientation(m_orientateAngle, newAxis); m_actor->setGlobalOrientationQuat(newOrientation); NxMat33 orientation(newOrientation); m_orientation = m_orientation * orientation; // Orientate the linear velocity to keep speed of rocket and direct away from road NxVec3 linVel = m_actor->getLinearVelocity(); m_actor->setLinearVelocity(m_orientation*linVel); } m_actor->setGlobalOrientation(m_orientation); } Thanks for the support :)
If your ray trace can determine the height of the terrain at some point out ahead, why couldn't you just determine the height of the terrain at the current horizontal coordinates of the rocket, and render the rocket at a fixed height above that? I.e., you seem to be trying to invent a guidance system for the rocket, when it sounds like all you really need is to figure out where to draw it. Actually, you probably could get the orientation for the rocket by making it match the slope of the terrain underneath it, so that it doesn't appear dead level all the time. It would look sort of strange if it were level while tracking over noticeable slopes.
2,436,705
2,436,728
Defining < for STL sort algorithm - operator overload, functor or standalone function?
I have a stl::list containing Widget class objects. They need to be sorted according to two members in the Widget class. For the sorting to work, a less-than comparator comparing two Widget objects must be defined. There seems to be a myriad of ways to do it. From what I can gather, one can either: a. Define a comparison operator overload in the class: bool Widget::operator< (const Widget &rhs) const b. Define a standalone function taking two Widgets: bool operator<(const Widget& lhs, const Widget& rhs); And then make the Widget class a friend of it: class Widget { // Various class definitions ... friend bool operator<(const Widget& lhs, const Widget& rhs); }; c. Define a functor and then include it as a parameter when calling the sort function: class Widget_Less : public binary_function<Widget, Widget, bool> { bool operator()(const Widget &lhs, const Widget& rhs) const; }; Does anybody know which method is better? In particular I am interested to know if I should do 1 or 2. I searched the book Effective STL by Scott Meyer but unfortunately it does not have anything to say about this. Thank you for your reply.
If you are only comparing two Widgets to each other, use a member operator <. If you are comparing Widget to something else, define a global operator < (the two parameter version, optionally a friend of the Widget class but that is a separate issue. Functor you really only want if you are doing something a little less orthodox. Choose a functor if a "less than" comparison doesn't make sense in the context of widgets. In that case, having operator < could be confusing. Of course, functors still have to provide an ordering, but just because it is an ordering doesn't really mean it is a "less than" operation. (Example, sorting states by population is probably better for a functor than an operator <.
2,436,755
2,437,076
Compiling a C program with a specific architecture
I was recently fighting some problems trying to compile an open source library on my Mac that depended on another library and got some errors about incompatible library architectures. Can somebody explain the concept behind compiling a C program for a specific architecture? I have seen the -arch compiler flag before and have seen values passed to it such as ppc, i386 and x86_64 which I assume maps to the CPU "language", but my understanding stops there. If one program uses a particular architecture, do all libraries that it loads need to be on the same architecture as well? How can I tell what architecture a given program/process is running under?
Can somebody explain the concept behind compiling a C program for a specific architecture? Yes. The idea is to translate C to a sequence of native machine instructions, which have the program coded into binary form. The meaning of "architecture" here is "instruction-set architecture", which is how the instructions are coded in binary. For example, every architecture has its own way of coding for an instruction that adds two integers. The reason to compile to machine instructions is that they run very, very fast. If one program uses a particular architecture, do all libraries that it loads need to be on the same architecture as well? Yes. (Exceptions exist but they are rare.) How can I tell what architecture a given program/process is running under? If a process is running on your hardware, it is running on the native architecture which on Unix you can discover by running the command uname -m, although for the human reader the output from uname -a may be more informative. If you have an executable binary or a shared library (.so file), you can discover its architecture using the file command: % file /lib/libm-2.10.2.so /lib/libm-2.10.2.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, stripped % file /bin/ls /bin/ls: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.8, stripped You can see that these binaries have been compiled for the very old 80386 architecture, even though my hardware is a more modern i686. The i686 (Pentium Pro) is backward compatible with 80386 and runs 80386 binaries as well as native binaries. To make this backward compatibility possible, Intel went to a great deal of trouble and expense—but they practically cornered the market on desktop CPUs, so it was worth it!
2,436,762
2,443,188
Why are string and vector distinct types?
They're both resizable arrays, and std::basic_string doesn't have any specifically character-related functions like upper(). What's special about string to make it better for character data?
Most of the reason has to do with localization and internationalization (L10I18),performance and for historical reasons. For the L10I18 issues, char_traits was added, and you will note that streams has these as well. The intent was to make "smarter characters" in a way, but the outcome was useless. About the only thing char_traits is good for is to specialize some of the std::string/wstring compares, copies, etc as compiler intrinsics. The failure is mostly due to UNIX streams themselves, which see the character as the main "atom" where in GUIs, web etc that are internationalized the string is the main "atom." In other words, in C/C++ land, we have "dumb arrays of smart characters" for strings, whereas every other language uses "smart arrays of dumb characters." Unicode takes the latter approach. Another big difference between basic_string and vector -- basic_string can only contain POD types. This can make a difference in some cases somoetime the compiler has an easier time optimizing basic_string compared to vector. basic_string sometimes has many other optimization, such as Copy on Write and Small String Optimization. These vary from one implementation to the next. However probably the most reason there are two things nearly the same is historical: strings predates the STL quite a bit, and most of the work seemed to center on making them interoperate with IOStream library. One C++ Urban Myth is that STL is a "container library" that was added to C++. It is not, and to get it adopted into C++, containers were added. An "STL Interface" was also bolted onto the existing string class. std::vector was largely taken from a vector implemenation that existed in the AdaSTL.
2,436,774
2,436,862
Locate modules by stack address
I have a Winodws Mobile 6.1 application running on an ARMV4I processor. Given a stack address (from unwinding an exception), I like to determine what module owns that address. Using the ToolHelpAPI, I'm able to determine most modules using the following method: HANDLE snapshot = ::CreateToolhelp32Snapshot( TH32CS_SNAPMODULE | TH32CS_GETALLMODS, 0 ); if( INVALID_HANDLE_VALUE != snapshot ) { MODULEENTRY32 mod = { 0 }; mod.dwSize = sizeof( mod ); if( ::Module32First( snapshot, &mod ) ) { do { if( stack_address > (DWORD)mod.modBaseAddr && stack_address < (DWORD)( mod.modBaseAddr + mod.modBaseSize ) ) { // Found the module! // offset = stack_address - mod.modBaseAddr break; } } while( ::Module32Next( snapshot, &mod ) ); } ::CloseToolhelp32Snapshot( snapshot ); } // if it's still not found snapshot = ::CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS | TH32CS_SNAPNOHEAPS, 0 ); if( INVALID_HANDLE_VALUE != snapshot ) { PROCESSENTRY32 proc = { 0 }; proc.dwSize = sizeof( proc ); if( ::Process32First( snapshot, &proc ) ) { do { if( stack_address > proc.th32MemoryBase && stack_address < ( proc.th32MemoryBase + 0x2000000 ) ) { // Found the executable // offset = stack_address - proc.th32MemoryBase break; } } while( ::Process32Next( snapshot, &proc ) ); } ::CloseToolhelp32Snapshot( snapshot ); } But, I don't always seem to be able to find a module that matches an address. For example: stack address module offset 0x03f65bd8 coredll.dll + 0x0001bbd8 0x785cab1c mylib.dll + 0x0002ab1c 0x785ca9e8 mylib.dll + 0x0002a9e8 0x785ca0a0 mylib.dll + 0x0002a0a0 0x785c8144 mylib.dll + 0x00028144 0x3001d95c my.exe + 0x0001d95c 0x3001dd44 my.exe + 0x0001dd44 0x3001db90 my.exe + 0x0001db90 0x03f88030 coredll.dll + 0x0003e030 0x03f8e46c coredll.dll + 0x0004446c 0x801087c4 ??? 0x801367b4 ??? 0x8010ce78 ??? 0x801086dc ??? 0x03f8e588 coredll.dll + 0x00044588 0x785a56a4 mylib.dll + 0x000056a4 0x785bdd60 mylib.dll + 0x0001dd60 0x785bbd0c mylib.dll + 0x0001bd0c 0x785bdb38 mylib.dll + 0x0001db38 0x3001db20 my.exe + 0x0001db20 0x3001dc40 my.exe + 0x0001dc40 0x3001a8a4 my.exe + 0x0001a8a4 0x3001a79c my.exe + 0x0001a79c 0x03f67348 coredll.dll + 0x0001d348 Where do I find those stack addresses that are missing? Any suggestions? Thanks, PaulH Edit: By taking @SoapBox's suggestion, I've filled in some of the gaps with "my.exe"
The CPU stack contains more than just addresses of code. Function arguments get passed on the stack as well. Only a debugger would know exactly what's in the stack frame, it gets it from the .pdb file. That won't really help you, a program cannot debug itself. On regular Windows, you'd use a minidump to do postmortem analysis, no idea if that's available on Mobile. It should be.
2,436,908
2,436,917
Do I specify exception types in just the function header or declarations as well? (C++)
SVector.H: void pop_back() throw (underflow_error); In my SVector.cpp file, should I also include the throw (underflow_error) part as well? void pop_back() throw (underflow_error) { // implementation } OR void pop_back() { // implementation } Thanks.
15.4/2: If any declaration of a function has an exception-specification, all declarations, including the definition and an explicit specialization, of that function shall have an exception-specification with the same set of type-ids.
2,437,126
2,437,140
How to you find out what group the current user belongs to via c++?
Using my c++ program how can I find out what group the current user running my program belongs to? So my program need to figure out a couple of things : The current username of the user The group the user belongs to How can do the above 2 using c++ on a RedHat / Linux machine?
With getuid(2) and getgid(2). See credentials(7) for more information. Use getpwuid(3) and getgrgid(3) for the names.
2,437,189
2,437,194
Is cin a proper file object?
As in, can I pass cin to any function that accepts an ifstream object?
std::cin is not a file stream, but an input stream, or istream. You can pass it to any function that accepts an istream.
2,437,265
2,438,891
How to pass parameters to manage_shared_memory.construct() in Boost.Interprocess
I've stared at the Boost.Interprocess documentation for hours but still haven't been able to figure this out. In the doc, they have an example of creating a vector in shared memory like so: //Define an STL compatible allocator of ints that allocates from the managed_shared_memory. //This allocator will allow placing containers in the segment typedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator; //Alias a vector that uses the previous STL-like allocator so that allocates //its values from the segment typedef vector<int, ShmemAllocator> MyVector; int main(int argc, char *argv[]) { //Create a new segment with given name and size managed_shared_memory segment(create_only, "MySharedMemory", 65536); //Initialize shared memory STL-compatible allocator const ShmemAllocator alloc_inst (segment.get_segment_manager()); //Construct a vector named "MyVector" in shared memory with argument alloc_inst MyVector *myvector = segment.construct<MyVector>("MyVector")(alloc_inst); Now, I understand this. What I'm stuck is how to pass a second parameter to segment.construct() to specify the number of elements. The interprocess document gives the prototype for construct() as MyType *ptr = managed_memory_segment.construct<MyType>("Name") (par1, par2...); but when I try MyVector *myvector = segment.construct<MyVector>("MyVector")(100, alloc_inst); I get compilation errors. My questions are: Who actually gets passed the parameters par1, par2 from segment.construct, the constructor of the object, e.g. vector? My understanding is that the template allocator parameter is being passed. Is that correct? How can I add another parameter, in addition to alloc_inst that is required by the constructor of the object being created in shared memory? There's very little information other than the terse Boost docs on this.
I asked the same question on the boost users mailing list and Steven Watanabe replied that the problem was simple: std::vector does not have a constructor of the type (size, allocator). Looking at its documentation I see that the constructor is vector ( size_type n, const T& value= T(), const Allocator& = Allocator() ); so the correct call should be MyVector *myvector = segment.construct<MyVector>("MyVector")(100, 0, alloc_inst); Elementary, my dear, Watson, elementary!
2,437,270
2,438,003
assign member based on string value
I need start off with code because I am not sure what terminology to use. Lets say I have the following code: class Node { public: void Parse(rapidxml::xml_node<> *node) { for (rapidxml::xml_attribute<> *attr = node->first_attribute(); attr; attr = attr->next_attribute()) { std::stringstream converter; converter << attr->value(); if( !strcmp(attr->name(), "x") ) converter >> x; else if( !strcmp(attr->name(),"y") ) converter >> y; else if( !strcmp(attr->name(), "z") ) converter >> z; } } private: float x; float y; float z; }; What I can't stand is the repetition of if( !strcmp(attr->name(), "x") ) converter >> x; I feel that this is error prone and monotonous, but I cannot think of another way to map a string value to a member assignment. What are some other approaches one can take to avoid code such as this? The only other possible alternative I could think of was to use a hashmap, but that runs into problems with callbacks This is the best I could up with but it's not as flexible as I'd like: class Node { Node() : x(0.0f), y(0.0f), z(0.0f) { assignmentMap["x"] = &x; assignmentMap["y"] = &y; assignmentMap["z"] = &z; } public: void Parse(rapidxml::xml_node<> *node) { for (rapidxml::xml_attribute<> *attr = node->first_attribute(); attr; attr = attr->next_attribute()) { map<std::string, float*>::iterator member = assignmentMap.find(attr->name()); //check for a pre-existing entry if( member == assignmentMap.end()) continue; std::stringstream converter; converter << attr->value(); converter >> *(member->second); } } private: float x; float y; float z; std::map<std::string, float*> assignmentMap; };
For the implementation with a map, you could use pointers-to-members. Then you won't need a deep copy of the map (when you copy it, the pointers in the map still point into the original Node), and it will also allow you to make the whole thing static (this map is unnecessary at per-instance basis). For example: class Node { //... static std::map<std::string, float Node::*> initVarMap(); static float Node::* varFromName(const std::string& name); }; std::map<std::string, float Node::*> Node::initVarMap() { std::map<std::string, float Node::*> varMap; varMap["x"] = &Node::x; varMap["y"] = &Node::y; varMap["z"] = &Node::z; return varMap; } float Node::* Node::varFromName(const std::string& name) { static std::map<std::string, float Node::*> varMap = initVarMap(); std::map<std::string, float Node::*>::const_iterator it = varMap.find(name); return it != varMap.end() ? it->second : NULL; } Usage: float Node::* member(varFromName(s)); if (member) this->*member = xyz; This isn't any more flexible, though. To support different types of members, you might modify the above to use a map of string to "variant of all supported member types". For example so. The member setter visitor should be reusable, and the only change to the code, to add or change member types, should be done to the typedef. #include <map> #include <string> #include <iostream> #include <boost/variant.hpp> template <class Obj, class T> struct MemberSetter: boost::static_visitor<void> { Obj* obj; const T* value; public: MemberSetter(Obj* obj, const T* value): obj(obj), value(value) {} void operator()(T Obj::*member) const { obj->*member = *value; } template <class U> void operator()(U Obj::*) const { //type mismatch: handle error (or attempt conversion?) } }; class Node { public: Node() : i(0), f(0.0f), d(0.0f) { } template <class T> void set(const std::string& s, T value) { std::map<std::string, MemberTypes>::const_iterator it = varMap.find(s); if (it != varMap.end()) { boost::apply_visitor(MemberSetter<Node, T>(this, &value), it->second); } //else handle error } void report() const { std::cout << i << ' ' << f << ' ' << d << '\n'; } private: int i; float f; double d; typedef boost::variant<int Node::*, float Node::*, double Node::*> MemberTypes; static std::map<std::string, MemberTypes> initVarMap(); static std::map<std::string, MemberTypes> varMap; }; int main() { Node a; a.set("i", 3); a.set("d", 4.5); a.set("f", 1.5f); a.report(); } std::map<std::string, Node::MemberTypes> Node::initVarMap() { std::map<std::string, Node::MemberTypes> varMap; varMap["i"] = &Node::i; varMap["f"] = &Node::f; varMap["d"] = &Node::d; return varMap; } std::map<std::string, Node::MemberTypes> Node::varMap = Node::initVarMap(); This is naturally just an example of what you can do. You can write a static_visitor to do what you want. E.g storing a stream and attempting to extract a value of the right type for the given member.
2,437,283
2,437,336
C/C++ packing signed char into int
I have need to pack four signed bytes into 32-bit integral type. this is what I came up to: int32_t byte(int8_t c) { return (unsigned char)c; } int pack(char c0, char c1, ...) { return byte(c0) | byte(c1) << 8 | ...; } is this a good solution? Is it portable (not in communication sense)? is there a ready-made solution, perhaps boost? issue I am mostly concerned about is bit order when converting of negative bits from char to int. I do not know what the correct behavior should be. Thanks
I liked Joey Adam's answer except for the fact that it is written with macros (which cause a real pain in many situations) and the compiler will not give you a warning if 'char' isn't 1 byte wide. This is my solution (based off Joey's). inline uint32_t PACK(uint8_t c0, uint8_t c1, uint8_t c2, uint8_t c3) { return (c0 << 24) | (c1 << 16) | (c2 << 8) | c3; } inline uint32_t PACK(sint8_t c0, sint8_t c1, sint8_t c2, sint8_t c3) { return PACK((uint8_t)c0, (uint8_t)c1, (uint8_t)c2, (uint8_t)c3); } I've omitted casting c0->c3 to a uint32_t as the compiler should handle this for you when shifting and I used c-style casts as they will work for either c or c++ (the OP tagged as both).
2,437,583
2,440,172
A specific string format with a number and character together represeting a certain item
I have a string which looks like this "a 3e,6s,1d,3g,22r,7c 3g,5r,9c 19.3", how do I go through it and extract the integers and assign them to its corresponding letter variable?. (i have integer variables d,r,e,g,s and c). The first letter in the string represents a function, "3e,6s,1d,3g,22r,7c" and "3g,5r,9c" are two separate containers . And the last decimal value represents a number which needs to be broken down into those variable numbers. my problem is extracting those integers with the letters after it and assigning them into there corresponding letter. and any number with a negative sign or a space in between the number and the letter is invalid. How on earth do i do this?
The description of the string format is not really clear but I think I can answer your question anyway (extracting the integers with the letters and adding(?) them to the proper int variable). So beginning with this string: char* was = "3e,6s,1d,3g,22r,7c"; // was == weird ass string it is probably easiest to tokenize it using strtok. char* token = strtok (was,","); while (token != NULL) { assign(token); // first token is 3e, second 6s etc... token = strtok (NULL, ","); } Now you can use sscanf to find the number and letter. void assign(char* token) { char letter; int number; if (0 != sscanf(token, "%d%c", number, letter)) { // the first token produces letter 'e' and number '3' // now you can switch on letter and add number // to the proper variable in each case } else { //matching failure!! } } With regards to the other quirks with your string format (the separate containers and the float at the end (others??)), you can handle those in similar ways. Just think of it like pealing an onion, work your way through the format layer by layer until you get to the letter number combination. Additionally any format faults will be caught at the very least when sscanf is invoked.
2,437,586
2,437,680
Accessing base class's method with derived class's object which has a method of same name
when accessing foo() of "base" using derived class's object. #include <iostream> class base { public: void foo() { std::cout<<"\nHello from foo\n"; } }; class derived : public base { public: void foo(int k) { std::cout<<"\nHello from foo with value = "<<k<<"\n"; } }; int main() { derived d; d.foo();//error:no matching for derived::foo() d.foo(10); } how to access base class method having a method of same name in derived class. the error generated has been shown. i apologize if i am not clear but i feel i have made myself clear as water. thanks in advance.
You could add using base::foo to your derived class: class derived : public base { public: using base::foo; void foo(int k) { std::cout<<"\nHello from foo with value = "<<k<<"\n"; } }; Edit: The answer for this question explains why your base::foo() isn't directly usable from derived without the using declaration.
2,437,763
2,825,320
Testing approach for multi-threaded software
I have a piece of mature geospatial software that has recently had areas rewritten to take better advantage of the multiple processors available in modern PCs. Specifically, display, GUI, spatial searching, and main processing have all been hived off to seperate threads. The software has a pretty sizeable GUI automation suite for functional regression, and another smaller one for performance regression. While all automated tests are passing, I'm not convinced that they provide nearly enough coverage in terms of finding bugs relating race conditions, deadlocks, and other nasties associated with multi-threading. What techniques would you use to see if such bugs exist? What techniques would you advocate for rooting them out, assuming there are some in there to root out? What I'm doing so far is running the GUI functional automation on the app running under a debugger, such that I can break out of deadlocks and catch crashes, and plan to make a bounds checker build and repeat the tests against that version. I've also carried out a static analysis of the source via PC-Lint with the hope of locating potential dead locks, but not had any worthwhile results. The application is C++, MFC, mulitple document/view, with a number of threads per doc. The locking mechanism I'm using is based on an object that includes a pointer to a CMutex, which is locked in the ctor and freed in the dtor. I use local variables of this object to lock various bits of code as required, and my mutex has a time out that fires my a warning if the timeout is reached. I avoid locking where possible, using resource copies where possible instead. What other tests would you carry out? Edit: I have cross posted this question on a number of different testing and programming forums, as I'm keen to see how the different mind-sets and schools of thought would approach this issue. So apologies if you see it cross-posted elsewhere. I'll provide a summary links to responses after a week or so
Firstly, many thanks for the responses. For the responses posted across different forumes see; http://www.sqaforums.com/showflat.php?Cat=0&Number=617621&an=0&page=0#Post617621 Testing approach for multi-threaded software http://www.softwaretestingclub.com/forum/topics/testing-approach-for?xg_source=activity and the following mailing list; software-testing@yahoogroups.com The testing took significantly longer than expected, hence this late reply, leading me to the conclusion that adding multi-threading to existing apps is liable to be very expensive in terms of testing, even if the coding is quite straightforward. This could prove interesting for the SQA community, as there is increasingly more multi-threaded development going on out there. As per Joe Strazzere's advice, I found the most effective way of hitting bugs was via automation with varied input. I ended up doing this on three PCs, which have ran a bank of tests repeatedly with varied input over about six weeks. Initially, I was seeing crashes one or two times per PC per day. As I tracked these down, it ended up with one or two per week between the three PCs, and we haven't had any further problems for the last two weeks. For the last two weeks we have also had a version with users beta testing, and are using the software in-house. In addition to varying the input under automation, I also got good results from the following; Adding a test option that allowed mutex time-outs to be read from a configuration file, which in turn could be controlled by my automation. Extending mutex time-outs beyond the typical time expected to execute a section of thread code, and firing a debug exception on time-out. Running the automation in conjunction with a debugger (VS2008) such that when a problem occurred there was a better chance of tracking it down. Running without a debugger to ensure that the debugger was not hiding other timing related bugs. Running the automation against normal release, debug, and fully optimised build. FWIW, the optimised build threw up errors not reproducible in the other builds. The type of bugs uncovered tended to be serious in nature, e.g. dereferencing invalid pointers, and even under the debugger took quite a bit of tracking down. As has been discussed elsewhere, the SuspendThread and ResumeThread functions ended up being major culprits, and all use of these functions were replaced by mutexes. Similarly all critical sections were removed due to lack of time-outs. Closing documents and exiting the program were also a bug source, where in one instance a document was destroyed with a worker thread still active. To overcome this a single mutex was added per thread to control the life of the thread, and aquired by the document destructor to ensure the thread had terminated as expected. Once again, many thanks for the all the detailed and varied responses. Next time I take on this type of activity, I'll be better prepared.
2,437,783
2,438,127
Turning one file with lots of classes to many files with one class per file
How do I turn one file with lots of classes to many files with one class per file? (C\C++) So I have that file with such structure: Some includes and then lots of classes that sometimes call each other: #include <wchar.h> #include <stdlib.h> //... class PG_1 { //... } class PG_2 { //... } //...... class PG_N { //... }
Two basic coding style patterns are possible: Class declarations in headers, member function/static data instantiation in .cpp files. Class definitions with in-line implementation in headers Option 2 may lead to code bloat since if you use the class in multiple compilation units you may get multiple copies of the implementation in the final link; it is down to the linker to eradicate this and it may or may not do so - YMMV. It also allows users of the class access to the implementation, which may be undesirable in some cases. A combination of the two with simple getter/setter functions in-lined and larger code bodies in separate compilation units is an option. Often if I have a constructor that is entirely implemented by the initialiser list, I will include its empty body in-line. Example for class cExampleClass: cExampleClass.h class cExampleClass { public: cExampleClass() ; ~cExampleClass() ; void memberfn() ; } ; cExampleClass.cpp cExampleClass::cExampleClass() { // body } cExampleClass::~cExampleClass() { // body } void cExampleClass::memberfn() { // body } or in-lined: cExampleClass.h class cExampleClass { public: cExampleClass() { // body } ~cExampleClass() { // body } void memberfn() { // body } } ; In both cases any source file that then uses cExampleClass simply includes the cExampleClass.h, and cExampleClass.cpp (if it exists) is separately compiled and linked. Note that if the class includes static data member variables, these must be instantiated in a separate compilation unit in order for there to be just one common instance. Example: cExampleClass.h class cExampleClass { public : static int staticmember ; } ; cExampleClass.cpp int cExampleClass::staticmember = 0xffff ;
2,437,858
3,350,263
How to convert AS3 ByteArray into wchar_t const* filename? (Adobe Alchemy)
How to convert AS3 ByteArray into wchar_t const* filename? So in my C code I have a function waiting for a file with void fun (wchar_t const* filename) how to send to that function my ByteArray? (Or, how should I re-write my function?)
A four month old question. Better late than never? To convert a ByteArray to a String in AS3, there are two ways depending on how the String was stored. Firstly, if you use writeUTF it will write an unsigned short representing the String's length first, then write out the string data. The string is easiest to recover this way. Here's how it's done in AS3: byteArray.position = 0; var str:String = byteArray.readUTF(); Alternatively, toString also works in this case. The second way to store is with writeUTFBytes. This won't write the length to the beginning, so you'll need to track it independantly somehow. It sounds like you want the entire ByteArray to be a single String, so you can use the ByteArray's length. byteArray.position = 0; var str:String = byteArray.readUTFBytes(byteArray.length); Since you want to do this with Alchemy, you just need to convert the above code. Here's a conversion of the second example: std::string batostr(AS3_Val byteArray) { AS3_SetS(byteArray, "position", AS3_Int(0)); return AS3_StringValue(AS3_CallS("readUTFBytes", byteArray, AS3_Array("AS3ValType", AS3_GetS(byteArray, "length")) )); } This has a ridiculous amount of memory leaks, of course, since I'm not calling AS3_Release anywhere. I use a RAII wrapper for AS3_Val in my own code... for the sake of my sanity. As should you. Anyway, the std::string my function returns will be UTF-8 multibyte. Any standard C++ technique for converting to wide characters should work from here. (search the site for endless reposts) I suggest leaving it is as it, though. I can't think of any advantage to using wide characters on this platform.
2,437,914
2,451,818
LLVM JIT segfaults. What am I doing wrong?
It is probably something basic because I am just starting to learn LLVM.. The following creates a factorial function and tries to git and execute it (I know the generated func is correct because I was able to static compile and execute it). But I get segmentation fault upon execution of the function (in EE->runFunction(TheF, Args)) #include "llvm/Module.h" #include "llvm/Function.h" #include "llvm/PassManager.h" #include "llvm/CallingConv.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Support/IRBuilder.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/GenericValue.h" using namespace llvm; Module* makeLLVMModule() { // Module Construction LLVMContext& ctx = getGlobalContext(); Module* mod = new Module("test", ctx); Constant* c = mod->getOrInsertFunction("fact64", /*ret type*/ IntegerType::get(ctx,64), IntegerType::get(ctx,64), /*varargs terminated with null*/ NULL); Function* fact64 = cast<Function>(c); fact64->setCallingConv(CallingConv::C); /* Arg names */ Function::arg_iterator args = fact64->arg_begin(); Value* x = args++; x->setName("x"); /* Body */ BasicBlock* block = BasicBlock::Create(ctx, "entry", fact64); BasicBlock* xLessThan2Block= BasicBlock::Create(ctx, "xlst2_block", fact64); BasicBlock* elseBlock = BasicBlock::Create(ctx, "else_block", fact64); IRBuilder<> builder(block); Value *One = ConstantInt::get(Type::getInt64Ty(ctx), 1); Value *Two = ConstantInt::get(Type::getInt64Ty(ctx), 2); Value* xLessThan2 = builder.CreateICmpULT(x, Two, "tmp"); //builder.CreateCondBr(xLessThan2, xLessThan2Block, cond_false_2); builder.CreateCondBr(xLessThan2, xLessThan2Block, elseBlock); /* Recursion */ builder.SetInsertPoint(elseBlock); Value* xMinus1 = builder.CreateSub(x, One, "tmp"); std::vector<Value*> args1; args1.push_back(xMinus1); Value* recur_1 = builder.CreateCall(fact64, args1.begin(), args1.end(), "tmp"); Value* retVal = builder.CreateBinOp(Instruction::Mul, x, recur_1, "tmp"); builder.CreateRet(retVal); /* x<2 */ builder.SetInsertPoint(xLessThan2Block); builder.CreateRet(One); return mod; } int main(int argc, char**argv) { long long x; if(argc > 1) x = atol(argv[1]); else x = 4; Module* Mod = makeLLVMModule(); verifyModule(*Mod, PrintMessageAction); PassManager PM; PM.add(createPrintModulePass(&outs())); PM.run(*Mod); // Now we going to create JIT ExecutionEngine *EE = EngineBuilder(Mod).create(); // Call the function with argument x: std::vector<GenericValue> Args(1); Args[0].IntVal = APInt(64, x); Function* TheF = cast<Function>(Mod->getFunction("fact64")) ; /* The following CRASHES.. */ GenericValue GV = EE->runFunction(TheF, Args); outs() << "Result: " << GV.IntVal << "\n"; delete Mod; return 0; } Edit: The correct way to enable JIT (see the accepted answer below): 1.#include "llvm/ExecutionEngine/Jit.h"` 2.InitializeNativeTarget();
I would bet that the ExecutionEngine pointer is null.... You are missing a call to InitializeNativeTarget, the documentation says: InitializeNativeTarget - The main program should call this function to initialize the native target corresponding to the host. This is useful for JIT applications to ensure that the target gets linked in correctly. Since there is no JIT compiler available without calling InitializeNativeTarget, ModuleBuilder selects the interpreter (if available). Probably not what you wanted. You may want to look at my previous post on this subject.
2,437,918
2,437,994
Windows API - Beginner help
I try to create a very simple app using windows API. I've done some small apps in console. This is the first time I do with Win32 apps. I've searched and found a document from forgers which is recommended in this site. But I try to write very first line: #include <stdafx.h> #include <windows.h> int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MessageBoxW(NULL, "Good bye Cruel World", "Note", MB_OK); return 0; } But it doesn't work (erased lines from default project created by VS 2008 and write these lines).
There are two versions of most windows API calls, one which takes single byte string and one which takes 2 byte unicode strings. The single byte one has an A on the end of the name and the 2 byte one has a W. There are macros defined in windows.h so that if you leave the letter out it picks one or the other depending on compiler macros. In your code you write - MessageBoxW (NULL, "Good bye Cruel World", "Note", MB_OK ); You are calling the wide character version of the API with single byte strings which won't work. Either change to MessageBoxA or change your strings to wide strings - MessageBoxW (NULL, L"Good bye Cruel World", L"Note", MB_OK );
2,437,937
2,437,945
Mixing c++ standard strings and windows API
Many windows APIs take a pointer to a buffer and a size element but the result needs to go into a c++ string. (I'm using windows unicode here so they are wstrings) Here is an example :- #include <iostream> #include <string> #include <vector> #include <windows.h> using namespace std; // This is the method I'm interested in improving ... wstring getComputerName() { vector<wchar_t> buffer; buffer.resize(MAX_COMPUTERNAME_LENGTH+1); DWORD size = MAX_COMPUTERNAME_LENGTH; GetComputerNameW(&buffer[0], &size); return wstring(&buffer[0], size); } int main() { wcout << getComputerName() << "\n"; } My question really is, is this the best way to write the getComputerName function so that it fits into C++ better, or is there a better way? I don't see any way to use a string directly without going via a vector unless I missed something? It works fine, but somehow seems a little ugly. The question isn't about that particular API, it's just a convenient example.
In this case, I don't see what std::vector brings to the party. MAX_COMPUTERNAME_LENGTH is not likely to be very large, so I would simply use a C-style array as the temporary buffer.
2,438,049
2,438,063
What is the difference between wmain and main?
So I have some class starting with #include <wchar.h> #include <stdlib.h> and there is a wmain function . How is it different from main function i usually use in my C/C++ programs?
"If your code adheres to the Unicode programming model, you can use the wide-character version of main, which is wmain." http://msdn.microsoft.com/en-us/library/aa299386%28VS.60%29.aspx main( int argc, char *argv[ ], char *envp[ ] ) { program-statements } wmain( int argc, wchar_t *argv[ ], wchar_t *envp[ ] ) { program-statements }
2,438,185
2,438,260
Macro to improve callback registration readability
I'm trying to write a macro to make a specific usage of callbacks in C++ easier. All my callbacks are member functions and will take this as first argument and a second one whose type inherits from a common base class. The usual way to go is: register_callback(boost::bind(&my_class::member_function, this, _1)); I'd love to write: register_callback(HANDLER(member_function)); Note that it will always be used within the same class. Even if typeof is considered as a bad practice, it sounds like a pretty solution to the lack of __class__ macro to get the current class name. The following code works: typedef typeof(*this) CLASS; boost::bind(& CLASS :: member_function, this, _1)(my_argument); but I can't use this code in a macro which will be given as argument to register_callback. I've tried: #define HANDLER(FUN) \ boost::bind(& typeof(*this) :: member_function, this, _1); which doesn't work for reasons I don't understand. Quoting GCC documentation: A typeof-construct can be used anywhere a typedef name could be used. My compiler is GCC 4.4, and even if I'd prefer something standard, GCC-specific solutions are accepted.
Your problem might be that typeof yields my_class&. It appears to work with boost::remove_reference: #include <boost/bind.hpp> #include <boost/type_traits.hpp> #include <iostream> struct X { void foo(int i) { std::cout << i << '\n'; } void bar() {boost::bind(&boost::remove_reference<typeof(*this)>::type::foo, this, _1)(10); } }; int main() { X x; x.bar(); } It might be more portable to use BOOST_TYPEOF, and in C++0x decltype
2,438,247
2,438,254
Why am I getting "too many include files : depth = 1024"?
I'm using Visual Studio 2008 Express edition, and keep getting the following error: "Cascadedisplay.h(4) : fatal error C1014: too many include files : depth = 1024. Obviously I'm doing something very wrong with include files, but I just can't see what. Basically, I have an interface class, StackDisplay, from which I want to derive CascadeDisplay in another file: #if !defined __BASE_STACK_DISPLAY_H__ #define __BASE_STACK_DISPAY_H__ #include <boost\shared_ptr.hpp> #include "CascadeDisplay.h" namespace Sol { class StackDisplay { public: virtual ~StackDisplay(); static boost::shared_ptr<StackDisplay> make_cascade_display(boost::shared_ptr<int> csptr) { return boost::shared_ptr<StackDisplay>(new CascadeDisplay(csptr)); } }; } #endif and then in CascadeDisplay.h: #if !defined __CASCADE_DISPLAY_H__ #define __CASCADE_DISPAY_H__ #include "StackDisplay.h" #include <boost\shared_ptr.hpp> namespace Sol { class CascadeDisplay: public StackDisplay { public: CascadeDisplay(boost::shared_ptr<int> csptr){}; }; } #endif So what's up with that?
Is #if !defined... legit? I always used #ifndef. Either way, why does your "base" class require the reference to CascadeDisplay? That doesn't seem right. Consider replacing your call to create a new CascadeDisplay with a call to a pure virtual function in StackDisplay that your subclass must implement appropriately. IE, something like (and forgive, I don't have a c++ compiler handy to check this): namespace Sol { class StackDisplay { public: virtual ~StackDisplay(); boost::shared_ptr<StackDisplay> make_cascade_display(boost::shared_ptr<int> csptr) { return make_display(csptr); } protected: virtual boost::shared_ptr<StackDisplay> make_display(boost::shared_ptr<int> csptr) = 0; }; class CascadeDisplay: public StackDisplay { public: CascadeDisplay(boost::shared_ptr<int> csptr){}; protected: virtual boost::shared_ptr<StackDisplay> make_display(boost::shared_ptr<int> csptr) { return new CascadeDisplay(csptr); } }; } I believe this solution is superior, in general, to the forward declaration because you're eliminating some tight coupling between your superclass and your subclass, and making a more generic interface besides. This lets you eliminate the #include of CascadeDisplay.h in StackDisplay.h.
2,438,291
2,440,290
Programmatically allow write access for a Registry key
I need to programmatically modify the Access Descriptors on a known Registry key during product installation. The way I want it to work is: The installer is run in Administrative mode. A Registry key is created. A function (the one I need) queries the ACL from the key. If this function finds that the group 'Users' already has write access, nothing should be done. If not, it should add a new permission allowing write access to the 'Users' group. The permissions are saved for the Registry key. This question is similar to Setting Registry key write permissions using .NET, however, I need a C++/Win32 implementation. Thanks in advance
For getting and setting the ACL of the key you need to use RegGetKeySecurity and RegSetKeySecurity. Then you need to iterate through the ACEs, examining any that apply to the "Users" group SID. Then you'll either modify/remove the existing one and/or add a new one. Be advised that working with ACLs in plain old Win32 C is a pain.
2,438,297
2,438,306
Can we use wmain() with Unix compilers or it'll work only on Windows?
Can we use the wmain() function with Unix compilers or it'll work only on/for Windows?
The only standard signatures for main are: int main(void); int main(int argc, char *argv[]); However, a freestanding implementation can provide extensions/allow other signatures. But those are not guranteed to be portable. wmain looks like a Windows/VS thing. There's not much chance this will work on a *nix/GNU GCC.
2,438,334
2,438,384
Are destructors of automatic objects invoked when terminate is called?
What happens when we throw from a destructor? I know that it causes terminate() to be called, and memory is indeed freed and the destructor is called, but, is this before or after throw is called from foo? Perhaps the issue here is that throw is used while the stack is unwinding that is the problem.
Is this before or after throw is called from foo? This is what is happening: foo() is called An object a of type A is created on the stack The next statement throws Now, the dtor for a is called, which throws another exception std::terminate is called -- which is nothing but abandoning the exception handling mechanism: From C++0x draft: 15.5.1 The std::terminate() function 1 In the following situations exception handling must be abandoned for less subtle error handling techniques: [...] — when the destruction of an object during stack unwinding (15.2) exits using an exception, or 2 In such cases, std::terminate() is called (18.7.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before std::terminate() is called. In all other situations, the stack shall not be unwound before std::terminate() is called. An implementation is not permitted to finish stack unwinding prematurely based on a determination that the unwind process will eventually cause a call to std::terminate(). Note: Emphasis mine
2,438,801
2,438,823
Handler invocation speed: Objective-C vs virtual functions
I heard that calling a handler (delegate, etc.) in Objective-C can be even faster than calling a virtual function in C++. Is it really correct? If so, how can that be? AFAIK, virtual functions are not that slow to call. At least, this is my understanding of what happens when a virtual function is called: Obtain the pointer to vtbl. De-reference the pointer and obtain the beginning of the array of function pointers. Offset (in pointer scale) the beginning of the array with the index of the method. Considering that the index is known at compile time, it's as easy as adding a multiple of uintptr_t. Issue a call instruction. Unfortunately, I don't know Objective-C so it's hard for me to compare performance. But at least, the mechanism of a virtual function call doesn't look that slow, right? How can something other than static function call be faster?
This is all, of course, implementation-dependent. I don't know if an Obj-C method call can be "faster" than a virtual function call, but it can certainly be in the ballpark-- there's discussion on the mechanism on SO here: Objective C message dispatch mechanism and Mike Ash has more here: http://www.mikeash.com/pyblog/friday-qa-2009-03-20-objective-c-messaging.html Bottom line is, selectors can be cached, and if the selector you're calling is cached at runtime, the dispatch is on the order of operations of a virtual function call. Also: Standard disclaimer: The performance of this is essentially irrelevant for almost all code. It only matters in an incredible minority of cases. Can't tell from your question, but basically this should not be a decision criterion in figuring out whether to implement a bunch of code in pure Obj-C or C++. You can always watch the behavior (and count the ops :) ) explicitly by stepping through the asm in Xcode-- if you do, report back!
2,438,928
2,438,983
Which constructor of std::vector is used in this case
This looks simple but I am confused: The way I create a vector of hundred, say, ints is std::vector<int> *pVect = new std::vector<int>(100); However, looking at std::vector's documentation I see that its constructor is of the form explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() ); So, how does the previous one work? Does new call the constructor with an initialization value obtained from the default constructor? If that is the case, would std::vector<int, my_allocator> *pVect = new std::vector<int>(100, my_allocator); where I pass my own allocator, also work?
You are doing it all wrong. Just create it as an automatic object if all you need is a vector in the current scope and time std::vector<int> pVect(100); The constructor has default arguments for the second and third parameters. So it is callable with just an int. If you want to pass an own allocator, you have to pass a second argument since you can't just skip it std::vector<int, myalloc> pVect(100, 0, myalloc(some_params)); A dedicated example might clarify the matter void f(int age, int height = 180, int weight = 85); int main() { f(25); // age = 25, height and weight taken from defaults. f(25, 90); // age=25, height = 90 (oops!). Won't pass a weight! f(25, 180, 90); // the desired call. }
2,439,254
2,439,442
How to get the call graph of a program with a bit of profiling information
I want to understand how a C++ program that was given to me works, and where it spends the most time. For that I tried to use first gprof and then gprof2dot to get the pictures, but the results are sometimes kind of ugly. How do you usually do this? Can you recommend any better alternatives? P.D. Which are the open source solutions (preferably for Linux or Mac OS )X?
You can try KCachegrind. This is a program that visualizes samples acquired by Valgrind tool called Callgrind. KCachegrind may seem to be not actively maintained, but the graphs he produces are very useful.
2,439,283
2,439,294
How can I create Min stl priority_queue?
The default stl priority queue is a Max one (Top function returns the largest element). Say, for simplicity, that it is a priority queue of int values.
Use std::greater as the comparison function: std::priority_queue<int, std::vector<int>, std::greater<int> > my_min_heap;
2,439,402
2,439,436
Why friend overloaded operator is preferred to conversion operator in this case
Hi I have a code like this, I think both the friend overloaded operator and conversion operator have the similar function. However, why does the friend overloaded operator is called in this case? What's the rules? Thanks so much! class A{ double i; public: A(int i):i(i) {} operator double () const { cout<<"conversion operator"<<endl;return i;} // a conversion operator friend bool operator>(int i, A a); // a friend funcion of operator > }; bool operator>(int i, A a ){ cout<<"Friend"<<endl; return i>a.i; } int main() { A aa(1); if (0 > aa){ return 1; } }
No conversion is necessary for the overloaded operator> to be called. In order for the built-in operator> to be called, one conversion is necessary (the user-defined conversion operator. Overload resolution prefers options with fewer required conversions, so the overloaded operator> is used. Note that if you were to change the definition of your overloaded operator> to be, for example: friend bool operator>(double i, A a); you would get a compilation error because both the overloaded operator> and the built-in operator> would require one conversion, and the compiler would not be able to resolve the ambiguity.
2,439,461
2,439,980
How to provide stl like container with public const iterator and private non-const iterator?
I have a class that includes a std::list and wish to provide public begin() and end() for const_iterator and private begin() and end() for just plain iterator. However, the compiler is seeing the private version and complaining that it is private instead of using the public const version. I understand that C++ will not overload on return type (in this case const_iterator and iterator) and thus it is choosing the non-const version since my object is not const. Short of casting my object to const before calling begin() or not overloading the name begin is there a way to accomplish this? I would think this is a known pattern that folks have solved before and would like to follow suit as to how this is typically solved. class myObject { public: void doSomethingConst() const; }; class myContainer { public: typedef std::list<myObject>::const_iterator const_iterator; private: typedef std::list<myObject>::iterator iterator; public: const_iterator begin() const { return _data.begin(); } const_iterator end() const { return _data.end(); } void reorder(); private: iterator begin() { return _data.begin(); } iterator end() { return _data.end(); } private: std::list<myObject> _data; }; void myFunction(myContainer &container) { myContainer::const_iterator itr = container.begin(); myContainer::const_iterator endItr = container.end(); for (; itr != endItr; ++itr) { const myObject &item = *itr; item.doSomethingConst(); } container.reorder(); // Do something non-const on container itself. } The error from the compiler is something like this: ../../src/example.h:447: error: `std::_List_iterator<myObject> myContainer::begin()' is private caller.cpp:2393: error: within this context ../../src/example.h:450: error: `std::_List_iterator<myObject> myContainer::end()' is private caller.cpp:2394: error: within this context Thanks. -William
I think your only option is to rename the private methods (if you need them in the first place). In addition I believe you should rename the typedefs: class MyContainer { public: typedef std::list<Object>::const_iterator iterator; typedef iterator const_iterator; const_iterator begin() const; const_iterator end() const; private: typedef std::list<Object>::iterator _iterator; _iterator _begin(); _iterator _end(); ... }; Containers are supposed to typedef both iterator and const_iterator. A generic function accepting a non-const instance of your container might expect to make use of the iterator typedef - even if it is not going to modify the elements. (For example BOOST_FOREACH.) It will be fine as far as const correctness goes, because should the generic function actually try to modify the objects, the real iterator type (being a const_iterator) wouldn't let it. As a test, the following should compile with your container: int main() { myContainer m; BOOST_FOREACH(const myObject& o, m) {} } Note that m is not const, but we are only trying to obtain const references to the contained types, so this should be allowed.
2,439,494
2,439,712
Forcing value to boolean: (bool) makes warning, !! doesnt
I like (bool) way more, but it generates warnings. How do i get rid off the warnings? I have code like: bool something_else = 0; void switcher(int val = -1){ if(val != -1){ something_else = (bool)val; }else{ something_else ^= 1; } } Should i just do it like everyone else and use '!!' or make it somehow hide the warning messages when using (bool) ? Or is '!!' actually faster than (bool) ? I would like to use (bool) and so i have to hide the warning, but how? Edit: Visual Studio 2008 i am using, sorry i forgot to tell. Edit 2: The warning message is warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning) And it comes on the line something_else = (bool)val; And on the line something_else = val; But not on the line something_else = !!val; The problem is, i want it to respect that i want to convert it to boolean. I dont want to hide all boolean warnings, because sometimes they saved my ass.
another way: switch (val) { case -1: something_else = !something_else; break; case 0: something_else = false; break; default: something_else = true; break; }
2,439,536
2,439,635
strategy to allocate/free lots of small objects
I am toying with certain caching algorithm, which is challenging somewhat. Basically, it needs to allocate lots of small objects (double arrays, 1 to 256 elements), with objects accessible through mapped value, map[key] = array. time to initialized array may be quite large, generally more than 10 thousand cpu cycles. By lots I mean around gigabyte in total. objects may need to be popped/pushed as needed, generally in random places, one object at a time. lifetime of an object is generally long, minutes or more, however, object may be subject to allocation/deallocation several times during duration of program. What would be good strategy to avoid memory fragmentation, while still maintaining reasonable allocate deallocate speed? I am using C++, so I can use new and malloc. Thanks. I know there a similar questions on website, Efficiently allocating many short-lived small objects, are somewhat different, thread safety is not immediate issue for me. my development platform is Intel Xeon, linux operating system. Ideally I would like to work on PPC linux as well, but it is not the most important for me.
Create a slotted allocator: Allocator is created with many pages of memory, each of equal size (512k, 256k, the size should be tuned for your use). The first time an object asks this allocator for memory it allocates a page. Allocating a page consists of removing it from the free list (no search, all pages are the same size) and setting the size of objects that will be allocated on this page. Typically this size calculated by taking the requested size and rounding it up to the nearest power of 2. Subsequent allocations of the same size just require a little bit of pointer math and incrementing the number of objects on the page. Fragmentation is prevented because slots are all the same size and can be refilled on subsequent allocations. Efficiency is maintained (in some cases improved) because there is no memheader per allocation (which makes a big difference when the allocations are small, once allocations become large this allocator starts to waste almost 50% of available memory). Both allocations and deallocations can be performed in constant time (no searches of the free list for correct slots). The only tricky part about a deallocation is that you don't typically want a memheader preceding the allocation, so you have to figure out the page and index in the page yourself... It's saturday and I haven't had my coffee so I don't have any good advice about doing that, it's easy enough to figure out from the deallocated address, though. Edit: This answer is a bit long winded. As usual boost has your back.
2,439,556
2,439,600
Check if window is losing focus
Which notification message do you receive if any window is losing focus?
WM_KILLFOCUS. In case you care, wParam will be the handle of the window that's receiving the focus.
2,439,643
2,439,662
Linked List exercise, what am I doing wrong?
Hey all. I'm doing a linked list exercise that involves dynamic memory allocation, pointers, classes, and exceptions. Would someone be willing to critique it and tell me what I did wrong and what I should have done better both with regards to style and to those subjects I listed above? /* Linked List exercise */ #include <iostream> #include <exception> #include <string> using namespace std; class node{ public: node * next; int * data; node(const int i){ data = new int; *data = i; } node& operator=(node n){ *data = *(n.data); } ~node(){ delete data; } }; class linkedList{ public: node * head; node * tail; int nodeCount; linkedList(){ head = NULL; tail = NULL; } ~linkedList(){ while (head){ node* t = head->next; delete head; if (t) head = t; } } void add(node * n){ if (!head) { head = n; head->next = NULL; tail = head; nodeCount = 0; }else { node * t = head; while (t->next) t = t->next; t->next = n; n->next = NULL; nodeCount++; } } node * operator[](const int &i){ if ((i >= 0) && (i < nodeCount)) throw new exception("ERROR: Invalid index on linked list.", -1); node *t = head; for (int x = i; x < nodeCount; x++) t = t->next; return t; } void print(){ if (!head) return; node * t = head; string collection; cout << "["; int c = 0; if (!t->next) cout << *(t->data); else while (t->next){ cout << *(t->data); c++; if (t->next) t = t->next; if (c < nodeCount) cout << ", "; } cout << "]" << endl; } }; int main (const int & argc, const char * argv[]){ try{ linkedList * myList = new linkedList; for (int x = 0; x < 10; x++) myList->add(new node(x)); myList->print(); }catch(exception &ex){ cout << ex.what() << endl; return -1; } return 0; }
There's no need for data to be a pointer. Use the ctor-initializer list, it's better for const-correctness and exception safety. None of your constructors need to have any code inside the body. Your linkedList constructor didn't initialize nodeCount. You aren't using your list's tail pointer for anything. It would save you scanning through the entire list in the non-empty case of add -- if you kept it up to date. Indexing (operator[]) is an unusual thing to support on a linked list. OTOH you haven't made a remove function. operator[] shouldn't take its parameter by reference. Only large structures need to be passed by const reference, small type like int should just be passed by value. Right now, if add fails, the pointer to new node() leaks. (But I don't actually see a way for add to fail unless the list links got corrupted.) You should define a private copy-constructor on node to prevent double-free of the data. Any time you define operator= and destructor you should also be defining or deleting the copy constructor (rule of three). You should also define private copy constructor and assignment operator on linkedList to prevent double-free. The variable string collection in your print function isn't used. The variable t in print() should be a pointer to const. print itself should be a const member function.
2,439,647
2,439,681
computing hash values, integral types versus struct/class
I would like to know if there is a difference in speed between computing hash value (for example std::map key) of primitive integral type, such as int64_t and pod type, for example struct { int16_t v[4]; };. what about int128_t versus struct {int32_t v[4];}? I know this is going to implementation specific, so my question ultimately pertains to gnu standard library. Thanks the link I found very useful How can I use a custom type for keys in a boost::unordered_map?
std::map is not a hash table. It is usually implemented as a balanced binary tree. What you want is std::unordered_map* . And for std::unordered_map, C++ only defines the hash value for the internal types and the common ones** such as std::string. You need to implement the hash function for struct { int16_t v[4]; }; yourself. You can cast this struct into int64_t in the computation, then there won't be any difference in hashing speed. (*: == std::tr1::unordered_map == boost::unordered_map ≈ __gnu_cxx::hash_map == stdext::hash_map etc) (**: 20.8.16 Class template hash: ... integer types (3.9.1), floating-point types (3.9.1), pointer types (8.3.1), and std::string, std::u16string, std::u32string, std::wstring, std::error_code, std::thread::id, std::bitset, and std::vector<bool>.)
2,439,722
2,439,760
Webservice and ORM Framework?
Does anybody know a good web framework that includes an ORM mapper and allows straight forward implementation of web services? I'm looking for a framework written in PHP or C++. I'm looking for the following features (not all of them required, some will do nicely) data definition in one place used by database and web service WSDL generation XML output/JSON output boilerplate code generation So what I would like is a framework that let's me specify the objects, the web service functions on those objects and then generate everything that is required leaving me to fill the business logic (connecting the database to the web service). Anything like that out there? Background information for why I need this: I'm looking into creating a web project: the client is a rich web application that fetches all its data using AJAX. It will be completely custom made using only a low level javascript library. The server back end is supposed to serve static content and javascript (basically the rich web application) and to provide a RESTful web service API (which I would like to implement using aforementioned framework).
I would recommend using Zend_Framework and replacing Zend_Db with Doctrine as your ORM. You can use Zend_Service to consume webservices and Zend_Rest_Controller to serve a REST API. There are some good screencasts on integrating Doctrine and Zend here. If you have alot of PHP experience, it shouldn't take very long to integrate. I believe there are even some sample integrations on Github.
2,439,791
2,439,871
Nested class or not nested class?
I have class A and list of A objects. A has a function f that should be executed every X seconds (for the first instance every 1 second, for the seconds instance every 5 seconds, etc.). I have a scheduler class that is responsible to execute the functions at the correct time. What i thought to do is to create a new class, ATime, that will hold ptr to A instance and the time A::f should be executed. The scheduler will hold a min priority queue of Atime. Do you think it is the correct implementation? Should ATime be a nested class of the scheduler?
From what you describe, sounds like it could work :-) IMHO class ATime belongs to the scheduler more than to A. It is necessary for the scheduler to do its job, and it is not needed for A. In fact, A (and the rest of the world) need not even know about its existence - so putting it a private nested class of the scheduler would be appropriate for me.
2,440,033
2,440,086
LALR(1) or GLR on Windows - Alternatives to Bison++ / Flex++ that are current?
UPDATE: This question is out of date, but left for informational purposes. Original Question I have been using the same version of bison++ (1.21-8) and flex++ (2.3.8-7) since 2002. I'm not looking for an alternative to LALR(1) or GLR at this time, just looking for the most current options. Is anyone aware of any later ports of these than the original that aren't Cygwin dependent? What are other folks using in Windows environments for C++ compiler development (besides ANTLR or Boost.spirit)? Commercial options are ok, if you have firsthand experience. I do need to compile on Linux as well. UPDATE: This old question was asked when I wasn't aware of the policies about tool recommendations (not sure if policy existed in 2010 but regardless... I since updated to Bison 3.0 which has GLR capabilities and have begun experimenting with that. I eventually decided that any rewrite of my parser would be a recursive descent, to improve error reporting and allow easier use in tools besides the compiler, so for now I will complete the reference version in Bison. I see little point in converting to a different PG tool at this time.
You can try Elsa (now it is a part of Oink project). But it is almost dead now. The only attractive feature of it is that there is a complete and robust C and C++ parser is written on top of it. LLVM contains a reasonably modern parsing framework. And there is a C++ parser as well (see clang project). Some Packrat implementations for C++ are available, sort of the most trendy thing in parsing.
2,440,411
2,444,325
Setting Connection Parameters via ADO for SQL Server
Is it possible to set a connection parameter on a connection to SQL Server and have that variable persist throughout the life of the connection? The parameter must be usable by subsequent queries. We have some old Access reports that use a handful of VBScript functions in the SQL queries (let's call them GetStartDate and GetEndDate) that return global variables. Our application would set these before invoking the query and then the queries can return information between date ranges specified in our application. We are looking at changing to a ReportViewer control running in local mode, but I don't see any convenient way to use these custom functions in straight T-SQL. I have two concept solutions (not tested yet), but I would like to know if there is a better way. Below is some pseudo code. Set all variables before running Recordset.OpenForward Connection->Execute("SET @GetStartDate = ..."); Connection->Execute("SET @GetEndDate = ..."); // Repeat for all parameters Will these variables persist to later calls of Recordset->OpenForward? Can anything reset the variables aside from another SET/SELECT @variable statement? Create an ADOCommand "factory" that automatically adds parameters to each ADOCommand object I will use to execute SQL // Command has been previously been created ADOParameter *Parameter1 = Command->CreateParameter("GetStartDate"); ADOParameter *Parameter2 = Command->CreateParameter("GetEndDate"); // Set values and attach etc... What I would like to know if there is something like: Connection->SetParameter("GetStartDate", "20090101"); Connection->SetParameter("GetEndDate", 20100101"); And these will persist for the lifetime of the connection, and the SQL can do something like @GetStartDate to access them. This may be exactly solution #1, if the variables persist throughout the lifetime of the connection.
Since no one has ventured an answer I'm guessing there isn't an elegant solution, that said: Global cursors persist for the duration of the connection and can be accessed from any SQL or stored proc so you could execute this once on the connection: DECLARE KludgeKursor CURSOR GLOBAL STATIC FOR SELECT StartDate = '2010-01-01', EndDate = '2010-04-30' OPEN KludgeKursor and in your stored procedures: --get the values DECLARE @StartDate datetime, @EndDate datetime FETCH FIRST FROM GLOBAL KludgeKursor INTO @StartDate, @EndDate --go crazy SELECT @StartDate, @EndDate Each connection would only see their own values, so the same stored procs can be used for different connection/values. The global cursor is automatically deallocated when the connection ends
2,440,420
2,440,430
Compare equality of char[] in C
I have two variables: char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE"; I want to check if these two are equal... using charTime == buf doesn't work. What should I use, and can someone explain why using == doesn't work? Would this action be different in C and C++?
char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE"; C++ and C (remove std:: for C): bool equal = (std::strcmp(charTime, buf) == 0); But the true C++ way: std::string charTime = "TIME", buf = "SOMETHINGELSE"; bool equal = (charTime == buf); Using == does not work because it tries to compare the addresses of the first character of each array (obviously, they do not equal). It won't compare the content of both arrays.
2,440,491
2,440,535
use printf("text %d", number) type format to assign value to variable
I would like to use the syntax that printf uses, using the %d, %s and adding values after to assign a value to a char[]. Is this possible? e.g. Given an output of: printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); I'd like to assign that to char[] output; How can this be done? I tried: sprintf(output, "now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); but that didn't seem to work. Is sprintf used differently... or is that not what I should be using? Thanks! EDIT: It turned out I simply needed to increase the initialized length of output...
That should work fine provided you have enough space in the output buffer (at least 26 bytes) to take the largest string you'll create: char output[26]; sprintf(output, "now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); You need: 5 for "now: ". 4 for the year (for at least the next 79 centuries). 2 each for the other five numerics. 5 for the separators ("-- ::"). 1 for the newline. 1 for the terminating null character. You may also want to consider changing the format string to "now: %04d-%02d-%02d %02d:%02d:%02d" so that the datetimes will line up if you're outputting them, to avoid something like: 2009-12-31 23:59:58 blah blah blah 2010-1-1 0:0:7 yada yada yada when 2009-12-31 23:59:58 blah blah blah 2010-01-01 00:00:07 yada yada yada looks so much better. You'll notice I've left the "\n" off the end - since this is the sort of code you see a lot in logging, you'd want the datetime to be in a format you could easily append to, something like: fprintf (logFile, "%s Cannot write to '%s', error = %d\n", output, fileSpec, errno); If I've misunderstood what you're using this for, feel free to ignore the last few paragraphs.
2,440,979
2,441,028
How to (legitimately) access files after putting self into chrooted sandbox?
Changing a Linux C++ program which gives the user limited file access. Thus the program chroots itself to a sandbox with the files the user can get at. All worked well. Now, however, the program needs to access some files for its own needs (not the user's) but they are outside the sandbox. I know chroot allows access to files opened before the chroot but in this case the needed files could a few among many hundreds so it is obviously impractical to open them all just for the couple that might be required. Is there any way to get at the files?
If the files you need to access are within a few directories you could open those directories before you chroot and save the file descriptors. You can then use the so-called *at functions (e.g. openat(), renameat(), etc.) to get at the individual files. Basically you are opening the files relative to the already open directory file descriptors rather than the chrooted directory. Whether this is a safe thing to do is open to question but it should work in Linux. EDIT: This is on the ugly side but it seems to work. You should poke around a lot more for vulnerabilities than I have. I haven't tested how dropping privileges and so forth will effect things. #include <iostream> #include <string> using namespace std; #include <cstdio> #include <cstdlib> #include <cerrno> #include <cstring> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> int main(int argc, char *argv[]) { if (argc < 4) { cerr << "USAGE: " << argv[0] << " <jail directory> <freeworld directory> <filename>\n"; exit(EXIT_FAILURE); } const string JAILDIR(argv[1]); const string FREEDIR(argv[2]); string freefilename(argv[3]); while (freefilename[0] == '/') freefilename.erase(0, 1); DIR *pDir; if ((pDir = opendir(FREEDIR.c_str())) == NULL) { perror("Could not open outside dir"); exit(EXIT_FAILURE); } int freeFD = dirfd(pDir); //cd to jail dir if (chdir(JAILDIR.c_str()) == -1) { perror("cd before chroot"); exit(EXIT_FAILURE); } //lock in jail if (chroot(JAILDIR.c_str()) < 0) { cerr << "Failed to chroot to " << JAILDIR << " - " << strerror(errno) << endl; exit(EXIT_FAILURE); } // //in jail, won't work // string JailFile(FREEDIR); JailFile += "/"; JailFile += freefilename; int jailFD; if ((jailFD = open(JailFile.c_str(), O_RDONLY)) == -1) { cout << "as expected, could not open " << JailFile << endl; perror("exected open fail"); } else { cout << "defying all logic, opened " << JailFile << endl; exit(EXIT_FAILURE); } // //using this works // if ((jailFD = openat(freeFD, freefilename.c_str(), O_RDONLY)) == -1) { cout << "example did not work. Could not open " << freefilename << " Sorry!" << endl; exit(EXIT_FAILURE); } else cout << "opened " << freefilename << " from inside jail" << endl; char buff[255]; ssize_t numread; while (1) { if ((numread = read(jailFD, buff, sizeof(buff) - 1)) == -1) { perror("read"); exit(EXIT_FAILURE); } if (numread == 0) break; buff[numread] = '\0'; cout << buff << endl; } return 0; } To test: echo "Hello World" >/tmp/mystuff.dat mkdir /tmp/jail sudo ./myprog /tmp/jail /tmp mystuff.dat
2,441,009
2,441,024
How to catch the exception in initialization list?
I have a question about how to catch the exception in the initialization list. For example, we have a class Foo derived from Bar class Foo { public: Foo(int i) {throw 0; } } class Bar : public Foo{ public: Bar() : Foo(1) {} }
I think the syntax is like this (even though it's better to catch such things in the caller. And what are you going to do once you caught it?) Bar::Bar() try : Foo(1) { } catch( const SomeException &e ) { }
2,441,045
2,441,066
Bewildering SegFault involving STL sort algorithm
I am trying to recreate the program in Column 15 of programming pearls using the STL. I am trying to create a suffix array using a string and a vector of indices. I record the list of words that I read in a string called input that acts as a list of words separated by ' ' that I read from stdin at the beginning of the program. Everything works as expected until I get to the sorting portion of the code. I'd like to use the STL's sort algorithm, but I am completely perplexed at a seg fault that I seem to be creating. I have: vector<unsigned int> words; and global variable string input; I define my custom compare function: bool wordncompare(unsigned int f, unsigned int s) { int n = 2; while (((f < input.size()) && (s < input.size())) && (input[f] == input[s])) { if ((input[f] == ' ') && (--n == 0)) { return false; } f++; s++; } return true; } When I run the code: sort(words.begin(), words.end()); The program exits smoothly. However, when I run the code: sort(words.begin(), words.end(), wordncompare); I generate a SegFault deep within the STL. The GDB back-trace code looks like this: #0 0x00007ffff7b79893 in std::string::size() const () from /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/libstdc++.so.6 #1 0x0000000000400f3f in wordncompare (f=90, s=0) at text_gen2.cpp:40 #2 0x000000000040188d in std::__unguarded_linear_insert<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, unsigned int, bool (*)(unsigned int, unsigned int)> (__last=..., __val=90, __comp=0x400edc <wordncompare(unsigned int, unsigned int)>) at /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_algo.h:1735 #3 0x00000000004018df in std::__unguarded_insertion_sort<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, bool (*)(unsigned int, unsigned int)> (__first=..., __last=..., __comp=0x400edc <wordncompare(unsigned int, unsigned int)>) at /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_algo.h:1812 #4 0x0000000000402562 in std::__final_insertion_sort<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, bool (*)(unsigned int, unsigned int)> (__first=..., __last=..., __comp=0x400edc <wordncompare(unsigned int, unsigned int)>) at /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_algo.h:1845 #5 0x0000000000402c20 in std::sort<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, bool (*)(unsigned int, unsigned int)> (__first=..., __last=..., __comp=0x400edc <wordncompare(unsigned int, unsigned int)>) at /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_algo.h:4822 #6 0x00000000004012d2 in main (argc=1, args=0x7fffffffe0b8) at text_gen2.cpp:70 I have similar code in another program, but in that program I am using a vector instead of vector. For the life of me I can't figure out what I'm doing wrong. Thanks!
Most likely your comparator doesn't satisfy strict weak ordering; e.g., it violates transitivity because some ring of values exists such that A < B, B < C, and C < A. Here are the requirements. I don't see it off the top of my head, but I am going to keep staring at it for a few minutes.
2,441,047
2,441,243
How do I set scons system include path
Using scons I can easily set my include paths: env.Append( CPPPATH=['foo'] ) This passes the flag -Ifoo to gcc However I'm trying to compile with a lot of warnings enabled. In particular with env.Append( CPPFLAGS=['-Werror', '-Wall', '-Wextra'] ) which dies horribly on certain boost includes ... I can fix this by adding the boost includes to the system include path rather than the include path as gcc treats system includes differently. So what I need to get passed to gcc instead of -Ifoo is -isystem foo I guess I could do this with the CPPFLAGS variable, but was wondering if there was a better solution built into scons.
There is no built-in way to pass -isystem include paths in SCons, mainly because it is very compiler/platform specific. Putting it in the CXXFLAGS will work, but note that this will hide the headers from SCons' dependency scanner, which only looks at CPPPATH. This is probably OK if you don't expect those headers to ever change, but could cause weird issues if you use the build results cache and/or implicit dependency cache.
2,441,220
2,441,647
Writing my own iostream utility class: Is this a good idea?
I have an application that wants to read word by word, delimited by whitespace, from a file. I am using code along these lines: std::istream in; string word; while (in.good()) { in>>word; // Processing, etc. ... } My issue is that the processing on the words themselves is actually rather light. The major time consumer is a set of mySQL queries I run. What I was thinking is writing a buffered class that reads something like a kilobyte from the file, initializes a stringstream as a buffer, and performs extraction from that transparently to avoid a great many IO operations. Thoughts and advice?
An istream works with a buffer class, so it'll normally read in fairly large chunks (though the exact size isn't guaranteed). As such, you're probably already getting the effect you're looking for. If you handle the buffering on your own, it's somewhat non-trivial -- when you reach the end of a buffer, chances are that you'll be in the middle of a word, so you'll have to copy the current word to the beginning of your buffer and read more to fill the rest of the buffer before you can process that word. Chances are you should just use a corrected loop like: while (in>>word) { // process word } ...but you might improve speed a bit by reading the file directly into a stringstream, and processing the words from there: std::istream in; std::istringstream buffer; buffer << in.rdbuf(); while (buffer >> word) { // process word } This can be detrimental with a really large input file though.
2,441,269
2,441,284
pthread_create from non-static member function
This is somewhat similiar to this : pthread function from a class But the function that's getting called in the end is referencing the this pointer, so it cannot be made static. void * Server::processRequest() { std::string tmp_request, outRequest; tmp_request = this->readData(); outRequest = this->parse(tmp_request); this->writeReply(outRequest); } void * LaunchMemberFunction(void * obj) { return ((Server *)obj)->processRequest(); } and then the pthread_create Server SServer(soc); pthread_create(&handler[tcount], &attr, (void*)LaunchMemberFunction,(void*)&SServer); errors: SS_Twitter.cpp:819: error: invalid conversion from void* to void* ()(void) SS_Twitter.cpp:819: error: initializing argument 3 of int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)
You are casting the third argument to a void* ((void*), and then getting an error, as void* cannot be cast to a function pointer. I believe it should compile if you just use &LaunchMemberFunction instead.
2,441,320
2,443,131
VC9 C1083 Cannot open include file: 'boost...' after trying to abstract an include dependency
So I've been working on a project for the past number of weeks and it uses a number of Boost libraries. In particular I'm using the boost::dynamic_bitset library quite extensively. I've had zero issues up until now; but tonight I discovered a dependency between some includes which I had to resolve; and I tried to do so by providing an abstract callback class. Effectively I now have the following: First include... class OtherClassCallback { public: virtual int someOtherMethod() const = 0; }; class SomeClass { public: void someMethod(OtherClassCallback *oc) { ... oc->someOtherMethod(); ... } }; Second include... #include "SomeClass.h" class SomeOtherClass : public OtherClassCallback { public: int someOtherMethod() const { return this->someInt; } }; Here is the issue; ever since I implemented this class I'm now getting the following error: fatal error C1083: Cannot open include file: 'boost/dynamic_bitset/dynamic_bitset.hpp': No such file or directory Now I'm getting no other compiler errors; and it's a pretty substantial project. My include paths and so on are perfect; my files are fully accessible and removing the changes fixes the issue. EDIT: I should highlight the fact the error is occurring in a file which neither directly includes and which hasn't been altered in any other way. Does anyone have any idea what might be going on? I'm compiling to native Windows executables in VS9. I should confess that I'm very inexperienced with C++ in general so go easy on me if it's something horribly straightforward; I can't figure it out.
So it turns out one of my executables which was using SomeOtherClass did not have the Boost libraries in its include list. I would have realised this earlier if I paid more attention to the output logs. 3>c:.. ClassUsingDynamicBitset.h(2) : fatal error C1083: Cannot open include file: 'boost/dynamic_bitset/dynamic_bitset.hpp': No such file or directory 3>SomeClassInExecutableProjectWhichDidntPreviouslyRequireBoostHeaders.cpp 2>Build log was saved at "file://c:...\BuildLog.htm" 2>some_library_already_including_boost_libraries - 0 error(s), 1 warning(s) Effectively I failed to realise that VS was concurrently building my libraries/executables as I played with the headers; and it was in fact an executable which previously knew nothing about the class which included the Boost library where the problem lay. As soon as I extended the aforementioned class to implement the Callback interface I introduced a dependency back down to the Boost library; and I failed to ensure each of my projects using said class were including all required headers.
2,441,457
2,444,363
Keyboard Input & the Win32 message loop
How do I handle key presses and key up events in the windows message loop? I need to be able to call two functions OnKeyUp(char c); and OnKeyDown(char c);. Current literature I've found from googling has lead me to confusion over WM_CHAR or WM_KEYUP and WM_KEYDOWN, and is normally targeted at PDA or Managed code, whereas I'm using C++.
Use char c = MapVirtualKey(param,MAPVK_VK_TO_CHAR); to convert virtual key codes to char, and process WM_KEYUP and WM_KEYDOWN and their wParams. if (PeekMessage (&mssg, hwnd, 0, 0, PM_REMOVE)) { switch (mssg.message) { case WM_QUIT: PostQuitMessage (0); notdone = false; quit = true; break; case WM_KEYDOWN: WPARAM param = mssg.wParam; char c = MapVirtualKey (param, MAPVK_VK_TO_CHAR); this->p->Input ()->Keyboard ()->Listeners ()->OnKeyDown (c); break; case WM_KEYUP: WPARAM param = mssg.wParam; char c = MapVirtualKey (param, MAPVK_VK_TO_CHAR); this->p->Input ()->Keyboard ()->Listeners ()->OnKeyUp (c); break; } // dispatch the message TranslateMessage (&mssg); DispatchMessage (&mssg); }
2,441,585
2,442,283
dynamic array pointer to binary file
Know this might be rather basic, but I been trying to figure out how to one after create a dynamic array such as double* data = new double[size]; be used as a source of data to be kept in to a binary file such as ofstream fs("data.bin",ios:binary"); fs.write(reinterpret_cast<const char *> (data),size*sizeof(double)); When I finish writing, I attempt to read the file through double* data = new double[size]; ifstream fs("data.bin",ios:binary"); fs.read(reinterpret_cast<char*> (data),size*sizeof(double)); However I seem to encounter a run time error when reading the data. Do you guys have any advice how i should attempt to write a dynamic array using pointers passed from other methods to be stored in binary files?
Hy:) If you use Unix you have some functions: int read(int fd, void *buf, int count);. int write (int fd, void *buf, int nbytes);. The functions are verry fast because are kernel-functions. i run your code and everything was ok : 1 #include <iostream> 2 #include <fstream> 3 #include <cstring> 4 using namespace std; 5 6 int main() 7 { 8 double * s; 9 int ns = 10; //information 10 s = new double[ns]; 11 12 for (int i = 0 ; i < ns ; ++i) 13 s[i] = 17*i + 23; // i put my information here 14 15 ofstream os("data.txt", ios::binary); 16 os.write(reinterpret_cast<const char*> (s), sizeof(double) * ns); 17 os.close(); 18 19 double * final; 20 final = new double[ns]; 21 22 ifstream is("data.txt", ios::binary); 23 is.read(reinterpret_cast<char *>(final), sizeof(double) * ns); 24 is.close(); 25 26 for (int i=0; i < ns; ++i) 27 cout<<s[i]<<" "<<final[i]<<"\n"; 28 29 return 0; 30 } ~ none@Brusture:~/Desktop$ g++ -o test test.cpp none@Brusture:~/Desktop$ ./test 23 23 40 40 57 57 74 74 91 91 108 108 125 125 142 142 159 159 176 176
2,441,659
2,441,706
Dilemma of Sending a Byte Array from JavaScript to COM
I'm having a bit of a problem because neither Javascript nor ActiveX (written in C++) are behaving like good little children. All I'm asking them to do is for Javascript to send a byte array and for the ActiveX to receive the byte array correctly in order to do more computation. This is how I declared my byte array in JS, and I verified it inside JS: var arr = new Array(0x00, 0xA4, 0x04, 0x00, 0x10,0xA0, 0x00, 00, 00, 0x18, 0x30, 0x03, 0x01, 00, 00, 00, 00, 00, 00, 00, 00); Javascript sends this array as an argument to an ActiveX method. Here is the tricky part; I want the ActiveX method to receive the byte array as a SAFEARRAY or VARIANT, but I can't get it to work for the life of me. I tried debugging and seeing the contents received inside the ActiveX as both SAFEARRAY or VARIANT, but to no avail. Here is the IDL segment: [id(7), helpstring("blah blah blah")] HRESULT Blah( [in] VARIANT blah1, [out, retval]VARIANT* blah2); Any help is greatly appreciated. Thanks in advance!
Arrays in JScript are no distinct types, they are just objects that have a property length and allow access to their contents via properties. In your Invoke()/InvokeEx() method, the VARIANT argument you receive should contain an IDispatch, which represents the scriptable object. On that retrieve the property length and get the contents via the property names 0 to length-1. As an implementation example, see e.g. FireBreaths IDispatchAPI::GetProperty() (IDispatchAPI wraps the scriptable browser object there). dispApi->GetProperty("length") would get the size of the array, while dispApi->GetProperty("0") to length-1 would get the actual content of the array.
2,441,705
2,441,710
I overloaded operator > but it still says no operator matches operands
I need B class to have a min priority queue of AToTime objects. AToTime have operator>, and yet I receive error telling me than there is no operator> matching the operands... #include <queue> #include <functional> using namespace std; class B { public: B(); virtual ~B(); private: log4cxx::LoggerPtr m_logger; class AToTime { public: AToTime(const ACE_Time_Value& time, const APtr a) : m_time(time), m_a(a){} bool operator >(const AToTime& other) { return m_time > other.m_time; } public: ACE_Time_Value m_time; APtr m_a; }; priority_queue<AToTime, vector<AToTime>, greater<AToTime> > m_myMinHeap; };
bool operator >(const AToTime& other) It should be a const function. bool operator >(const AToTime& other) const
2,442,081
2,442,572
Convert GUI C++ app to a console one
I have a GUI C++ application (Visual Studio 2008) that needs to be converted to a console one. I don't have any experience in C programming. Mostly I use .NET. Where do I start?
Down-converting a GUI app is major surgery. The programming model is entirely different, a GUI app is event driven. Relying on a message loop to deliver events, processed in message handlers. And typically a bunch of controls that take care of the grunge work of taking input. Given that you have to completely redesign the app to make it work as a console mode app and that you don't have experience with the language, writing this in a .NET language you have experience with is the best way to get it completed quickly.
2,442,358
2,442,406
Do c++ templates make programs slow?
I have heard from many people that usage of templates make the code slow. Is it really true. I'm currently building a library. There are places where if templates are not created, it would result in code management problem. As of now I can think two solutions to this problem: use #defines Use templates and define all possible types in the header file/library itself but do not allow end user to make template instances. e.g. typedef Graph<int> GraphI32; etc. Is there anyway, to restrict user from creating various template instances on their own. Help on above queries would be highly regarded.
The short answer is no. For the longer answer please read on. As others have already noted, templates don't have a direct run-time penalty -- i.e. all their tricks happen at compile time. Indirectly, however, they can slow things down under a few circumstances. In particular, each instantiation of a template (normally) produces code that's separate and unique from other instantiations. Under a few circumstances, this can lead to slow execution, by simply producing enough object code that it no longer fits in the cache well. With respect to code size: yes, most compilers can and will fold together the code for identical instantiations -- but that's normally the case only when the instantiations are truly identical. The compiler will not insert code to do even the most trivial conversions to get two minutely different instantiations to match each other. For example, a normal function call can and will convert T * to T const * so calls that use either const or non-const arguments will use the same code (unless you've chosen to overload the function on constness, in which case you've probably done so specifically to provide different behavior for the two cases). With a template, that won't happen -- instantiations over T * and T const * will result in two entirely separate pieces of code being generated. It's possible the compiler (or linker) may be able to merge the two after the fact, but not entirely certain (e.g., I've certainly used compilers that didn't). But in the end, templates have positive effects on speed far more often than negative.
2,442,386
2,476,184
Looking for a better way to integrate a static list into a set of classes
I'm trying to expand my sons interest from Warcraft 3 programming into C++ to broaden his horizons to a degree. We are planning on porting a little game that he wrote. The context goes something like this. There are Ships and Missiles, for which Ships will use Missiles and interact with them A Container exists which will hold 'a list' of ships. A Container exists which will hold 'a list' of planets. One can apply a function over all elements in the Container (for_each) Ships and Missles can be created/destroyed at any time New objects automatically insert themselves into the proper container. I cobbled a small example together to do that job, so we can talk about topics (list, templates etc) but I am not pleased with the results. #include <iostream> #include <list> using namespace std; /* Base class to hold static list in common with various object groups */ template<class T> class ObjectManager { public : ObjectManager(void) { cout << "Construct ObjectManager at " << this << endl; objectList.push_back(this); } virtual ~ObjectManager(void) { cout << "Destroy ObjectManager at " << this << endl; } void for_each(void (*function)(T *)) { for (objectListIter = objectList.begin(); objectListIter != objectList.end(); ++objectListIter) { (*function)((T *) *objectListIter); } } list<ObjectManager<T> *>::iterator objectListIter; static list<ObjectManager<T> *> objectList; }; /* initializer for static list */ template<class T> list<ObjectManager<T> *> ObjectManager<T>::objectList; /* A simple ship for testing */ class Ship : public ObjectManager<Ship> { public : Ship(void) : ObjectManager<Ship>() { cout << "Construct Ship at " << this << endl; } ~Ship(void) { cout << "Destroy Ship at " << this << endl; } friend ostream &operator<<(ostream &out,const Ship &that) { out << "I am a ship"; return out; } }; /* A simple missile for testing */ class Missile : public ObjectManager<Missile> { public : Missile(void) : ObjectManager<Missile>() { cout << "Construct Missile at " << this << endl; } ~Missile(void) { cout << "Destroy Missile at " << this << endl; } friend ostream &operator<<(ostream &out,const Missile &that) { out << "I am a missile"; return out; } }; /* A function suitable for the for_each function */ template <class T> void show(T *it) { cout << "Show: " << *it << " at " << it << endl; } int main(void) { /* Create dummy planets for testing */ Missile p1; Missile p2; /* Demonstrate Iterator */ p1.for_each(show); /* Create dummy ships for testing */ Ship s1; Ship s2; Ship s3; /* Demonstrate Iterator */ s1.for_each(show); return 0; } Specifically, The list is effectively embedded in each ship though the inheritance mechanism. One must have a ship, in order to access the list of ships. One must have a missile in order to be able to access the list of missiles. That feels awkward. My question boils down to "Is there a better way to do this?" Automatic object container creation Automatic object insertion Container access without requiring an object in the list to access it. I am looking for better ideas. All helpful entries get an upvote. Thanks Evil.
I think the problem here is that you are stretching the notion of inheritance. What you have is valid code and works but as you point out it doesn't feel right to have a container class hidden behind the scenes of the constructor of your child class. This is (in my opinion) because a Missile doesn't really have anything in common with it's parent class (a container), you are using inheritance to provide this container when this is a design pattern that has (rightly) been abstracted out in the standard template library. As John Zwinck suggests a Factory pattern will provide a much more expressive way of achieving what you want. /* Container class to create and store various object groups */ template<class T> class ObjectManager { public : ObjectManager() : nextAvailableIndex(0) {} virtual ~ObjectManager(void) { for (objectListIter = objectList.begin(); objectListIter != objectList.end(); ++objectListIter) delete *objectListIter; } T* ObjectManager::Create() { T* object = new Object(nextAvailableIndex++); cout << "Constructed object " << object << endl; objectList.push_back(object); } void for_each(void (*function)(T *)) { for (objectListIter = objectList.begin(); objectListIter != objectList.end(); ++objectListIter) { (*function)((T *) *objectListIter); } } int nextAvailableIndex; list<T*>::iterator objectListIter; list<T*> objectList; }; int main(void) { /* Create dummy planets for testing */ ObjectManager<Missile> missileManager; Missile* p1 = missileManager.Create(); /* Demonstrate Iterator */ missileManager.for_each(show); /* Create dummy ships for testing */ ObjectManager<Ship> shipManager; shipManager.Create(); shipManager.Create(); shipManager.Create(); /* Demonstrate Iterator */ shipManager.for_each(show); // will show three ships return 0; } I've left out the class definitions for Missile and Ship as the only change I put there is a single integer to the constructors to functions as a unique identifier.
2,442,473
2,442,541
Split text by whitespaces
I have text file with some text information and i need to split this text at spaces and all word push into List. I make so: QStringList list = line.split(" "); for (int i = 0; i < list.count(); i++){ table.push_back(list[i]); this->ui->textEdit->setText(list[i]); } In line i have my text. But when i test this code i get all text, but not by the word. Thank you.
Try it with: line.split(QRegExp("\\s"));
2,442,518
2,442,667
How to retrieve SID's byte array
How can I convert a PSID type into a byte array that contains the byte value of the SID? Something like: PSID pSid; byte sidBytes[68];//Max. length of SID in bytes is 68 if(GetAccountSid( NULL, // default lookup logic AccountName,// account to obtain SID &pSid // buffer to allocate to contain resultant SID ) { ConvertPSIDToByteArray(pSid, sidBytes); } --how should I write the function ConvertPSIDToByteArray?
I think the function you might be looking for is ConvertSidToStringSid. The general idea is to convert the PSID struct to a LPTSTR which is in fact of type wchar_t. You can then convert this using standard functions to a multi-byte char array using wcstombs which will then give you the SID in bytes. Alternatively, you can operate on the wchar_t type directly and just write that out - there are functions for handling that. In either case, the result will be UTF-16 LE encoded and if you need to change from that you'll have to do a conversion.
2,442,863
2,442,869
Catching a nested-in-template exception [C++]
I have a problem with writing a catch clause for an exception that is a class nested in a template. To be more specific, I have a following definition of the template and exception: /** Generic stack implementation. Accepts std::list, std::deque and std::vector as inner container. */ template < typename T, template < typename Element, typename = std::allocator<Element> > class Container = std::deque > class stack { public: class StackEmptyException { }; ... /** Returns value from the top of the stack. Throws StackEmptyException when the stack is empty. */ T top() const; ... } I have a following template method that I want exception to catch: template <typename Stack> void testTopThrowsStackEmptyExceptionOnEmptyStack() { Stack stack; std::cout << "Testing top throws StackEmptyException on empty stack..."; try { stack.top(); } catch (Stack::StackEmptyException) { // as expected. } std::cout << "success." << std::endl; } When I compile it (-Wall, -pedantic) I get the following error: In function ‘void testTopThrowsStackEmptyExceptionOnEmptyStack()’: error: expected type-specifier error: expected unqualified-id before ‘)’ token === Build finished: 2 errors, 0 warnings === Thanks in advance for any help! What is interesting, if the stack implementation was not a template, then the compiler would accept the code as it is. PS. I also tried redefining the template method type, but I couldn't make this work.
Use typename: template <typename Stack> void testTopThrowsStackEmptyExceptionOnEmptyStack() { Stack stack; std::cout << "Testing top throws StackEmptyException on empty stack..."; try { stack.top(); } catch (typename Stack::StackEmptyException) { // as expected. } std::cout << "success." << std::endl; } The compiler's parser otherwise assumes that Stack::StackEmptyException is not a type and misparses the code (it can't know that it is a type, because at that point it doesn't know what type Stack is, so potentially StackEmptyException could be a static data-member likewise). You should also generally catch by reference instead of by value.
2,443,064
2,443,501
Interaction between C++ and Rails applications
I have two applications: c++ service and a RoR web server (they are both running at same VPS) I need to "send" some variables (and then do something with them) from each other. For exaple, i'm looking for something like this: // my C++ sample void SendMessage(string message) { SendTo("127.0.0.1", message); } void GetMessage(string message) { if (message == "stop") SendMessage("success"); } # Ruby sample # application_controller.rb def stop @m = Messager.new @m.send("stop") end I have never used it before, and i even don't know which technology should i search and learn.
Ok, i have found the solution. Its TCP sockets: Ruby TCP server, to send messages: require 'socket' server = TCPServer.open(2000) loop { Thread.start(server.accept) do |client| client.puts(Time.now.ctime) client.puts "Closing the connection. Bye!" client.close end } Ruby client, to accept messages: require 'socket' host = 'localhost' port = 2001 # it should be running server, or it will be connection error s = TCPSocket.open(host, port) while line = s.gets puts line.chop end s.close Now you should write TCP-server+client in another application. But you have got the idea.
2,443,079
2,443,101
c/c++ how to convert short to char
I am using ms c++. I am using struct like struct header { unsigned port : 16; unsigned destport : 16; unsigned not_used : 7; unsigned packet_length : 9; }; struct header HR; here this value of header i need to put in separate char array. i did memcpy(&REQUEST[0], &HR, sizeof(HR)); but value of packet_length is not appearing properly. like if i am assigning HR.packet_length = 31; i am getting -128(at fifth byte) and 15(at sixth byte). if you can help me with this or if their is more elegant way to do this. thanks
Sounds like the expected behaviour with your struct as you defined packet_length to be 9 bits long. So the lowest bit of its value is already within the fifth byte of the memory. Thus the value -128 you see there (as the highest bit of 1 in a signed char is interpreted as a negative value), and the value 15 is what is left in the 6th byte. The memory bits look like this (in reverse order, i.e. higher to lower bits): byte 6 | byte 5 | ... 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 packet_length | not_used | ... Note also that this approach may not be portable, as the byte order inside multibyte variables is platform dependent (see endianness). Update: I am not an expert in cross-platform development, neither did you tell much details about the layout of your request etc. Anyway, in this situation I would try to set the fields of the request individually instead of memcopying the struct into it. That way I could at least control the exact values of each individual field.
2,443,165
2,443,379
Has the small object allocator found in "Modern C++ Design"/Loki been deprecated in favor of newer implementations?
It seems the code and the book have been relegated to the foundation of the movement of modern C++, and isn't updated any more. Is there some kind of replacement for this in Boost or TR1?
Check out the Boost.Pool library.
2,443,166
2,443,191
C language program is detected as a virus
#include<stdio.h> #include<conio.h> union abc { int a; int x; float g; }; struct pqr { int a; int x; float g; } ; void main() { union abc b; struct pqr c; clrscr(); b.a=10; textbackground(2); textcolor(6); cprintf(" A = %d",b.a); printf("\nUnion = %d",sizeof(b)); printf("\nStructure = %d",sizeof(c)); getch(); } I have saved this program as virus.cpp. I am using Turbo C compiler to compile this program and run from Turbo C (Ctrl + F9). I am using Windows 7 and I have installed Avira AntiVir virus system. When I tried to run above program, it creates a worm (DOS/Candy). I believe there is nothing wrong in program. alt text Now here is something special. Execute the same program with following difference. Here the only difference is space between \n: #include<stdio.h> #include<conio.h> union abc { int a; int x; float g; }; struct pqr { int a; int x; float g; } ; void main() { union abc b; struct pqr c; clrscr(); b.a=10; textbackground(2); textcolor(6); cprintf(" A = %d",b.a); printf("\n Union = %d",sizeof(b)); printf("\n Structure = %d",sizeof(c)); getch(); } The difference is only \n and space. My question is, why is my simple program is detected as virus? Here is another code sample, this time for C++: #include<iostream.h> #include<conio.h> class A { int a,b; public: A() { a=0;b=0; } A(int x) {a=x; b=0; } A(int x,int y) { a=x; b=y; } ~A() { cout<<"All things are deleted."; } void get() { cout<<"\nA = "<<a; cout<<"\nB = "<<b; } }; void main() { A a1(5,10); clrscr(); a1.get(); getch(); } When I run this program it gives "Virus Warning" - Even it is not an virus. Now, the tragedy is when you remove destructors, it won't detect it as virus. Here is the screen shot and similar question: C Language - \n - creating virus alt text The question is how, and why?
Looks like a false-positive. Because modern viruses use polymorphism to hide from anti-virus programs, the anti-virus program has to report even partial matches, and apparently your compiler with the given source code produces a partial match to that malware.
2,443,288
2,443,376
Objective-C @class / import best practice
I've noticed that a lot of Objective-C examples will forward declare classes with @class, then actually import the class in the .m file with an import. I understand that this is considered a best practice, as explained in answers to question: @class vs. #import Coming from C++ this feels backwards. I would normally include all needed .h files in the new classes header file. This seems useful since it would make the compiler generate a warning when two classes include each other, at which point I can decide whether this is a bad thing or not then use the same Objective-C style and forward declare the class in the header and include it in the .cpp file. What is the benefit of forward declaring @class and importing in the implementation file? Should it be a best practice in C++ to forward declare classes rather than including the header file? Or is it wrong to think of Objective-C and C++ in these similar terms to begin with?
To be honest, your C++ is actually backwards. Generally in C++ you want to avoid headers being included inside other headers preferring forward declarations to includes. This is generally considered the best practice because it decreases compile time, and shrinks the size of the preprocessed code files fed into the compiler to as small as needed. Scott Meyers has a great section about that in Effective C++. To more directly answer your question, the advantage of forward declaring classes, and importing them in the implementation file (in both C++ and objective c), is basically that forward declarations make it so that any other class using your class doesn't necessarily need to include all of the things your class uses. Which reduces the size of preprocessed code files (which makes preprocessing faster), makes compilation faster, and linking faster. All of which are usually good things. In more obscure cases having reduced include statements can make it easier to find certain types of errors (like missing semicolons in headers) that produce compiler warnings that aren't always obvious but are repeated and spammed everywhere headers are included.
2,443,316
2,443,334
C++ random number from a set
Is it possible to print a random number in C++ from a set of numbers with ONE SINGLE statement? Let's say the set is {2, 5, 22, 55, 332} I looked up rand() but I doubt it's possible to do in a single statement.
Say these numbers are in a set of size 5, all you gotta do is find a random value multiplied by 5 (to make it equi probable). Assume the rand() method returns you a random value between range 0 to 1. Multiply the same by 5 and cast it to integer you will get equiprobable values between 0 and 4. Use that to fetch from the index. I dont know the syntax in C++. But this is how it should look my_rand_val = my_set[(int)(rand()*arr_size)] Here I assume rand() is a method that returns a value between 0 and 1.
2,443,353
2,443,357
How to override virtual function in good style? [C++]
guys I know this question is very basic but I've met in few publications (websites, books) different style of override virtual function. What I mean is: if I have base class: class Base { public: virtual void f() = 0; }; in some publications I saw that to override this some authors would just say: void f(); and some would still repeat the virtual keyword before void. Which form of overwriting is in good style? Thank you for your answers.
This is purely a matter of taste. Some weak arguments can be made back and forth as to the self-documentation value of some styles versus the non-redundancy of others.
2,443,358
2,448,473
How to add lines numbers to QTextEdit?
I am writing a Visual Basic IDE, and I need to add lines numbers to QTextEdit and highlight current line. I have found this tutorial, but it is written in Java and I write my project in C++.
Here's the equivalent tutorial in C++: Qt4: http://doc.qt.io/qt-4.8/qt-widgets-codeeditor-example.html Qt5: http://doc.qt.io/qt-5/qtwidgets-widgets-codeeditor-example.html
2,443,372
2,443,410
inline and member initializers
When should I inline a member function and when should I use member initializers? My code is below.. I would like to modify it so I could make use some inline when appropriate and member initializers: #include "Books.h" Book::Book(){ nm = (char*)""; thck = 0; wght = 0; } Book::Book(const char *name, int thickness, int weight){ nm = strdup(name); thck = thickness; wght = weight; } Book::~Book(){ } const char* Book::name(){ return nm; } int Book::thickness(){ return thck; } int Book::weight(){ return wght; } // // Prints information about the book using this format: // "%s (%d mm, %d dg)\n" // void Book::print(){ printf("%s (%d mm, %d dg)\n", nm, thck, wght); } Bookcase::Bookcase(int id){ my_id = id; no_shelf = 0; } int Bookcase::id(){ return my_id; } Bookcase::~Bookcase(){ for (int i = 0; i < no_shelf; i++) delete my_shelf[i]; } bool Bookcase::addShelf(int width, int capacity){ if(no_shelf == 10) return false; else{ my_shelf[no_shelf] = new Shelf(width, capacity); no_shelf++; return true; } } bool Bookcase::add(Book *bp){ int index = -1; int temp_space = -1; for (int i = 0; i < no_shelf; i++){ if (bp->weight() + my_shelf[i]->curCapacity() <= my_shelf[i]->capacity()){ if (bp->thickness() + my_shelf[i]->curWidth() <= my_shelf[i]->width() && temp_space < (my_shelf[i]->width() - my_shelf[i]->curWidth())){ temp_space = (my_shelf[i]->width()- my_shelf[i]->curWidth()); index = i; } } } if (index != -1){ my_shelf[index]->add(bp); return true; }else return false; } void Bookcase::print(){ printf("Bookcase #%d\n", my_id); for (int i = 0; i < no_shelf; i++){ printf("--- Shelf (%d mm, %d dg) ---\n", my_shelf[i]->width(), my_shelf[i]->capacity()); my_shelf[i]->print(); } }
Short member functions that are called frequently are good candidates for inlining. In order to make the member function "inlinable," you need to define it in the header file (either in the class definition itself, or below the class definition using the inline keyword). You should always use constructor initializer lists to initialize member data. For user-defined types, this can make a substantial performance difference in some cases. Your constructor should look like this: Book::Book() : nm(""), thck(0), wght(0) { } Here is a pretty good explanation of why to use initializer lists.
2,443,431
2,443,458
Project-wide additional library paths -- MSVS2008
I'm setting up a VC++ project in MS Visual Studio 2008 that'll be used by several people. I wanted to keep things as simple as possible so I've set up Additional Include Directories via the Project properties. I've also set up additional library files via Tools -> Options -> Projects and Solutions -> VC++ Directories. However, my issue is that I really need to set up Additional library PATHs, because I am using an SDK which does inline linking of libraries. I could just tell each one of the participants to manually add the library path to their MSVS2008 environment, but it would be handy if I could integrate the RELATIVE library path in the project itself.
You can set additional library paths in your project properties: Project Properties | Configuration Properties | Linker | General | Additional Library Directories
2,443,479
2,443,516
C++, how implicit conversion/constructor are determined?
How does C++ determine implicit conversion/construction of objects few levels deep? for example: struct A {}; struct B: A {}; struct C { operator B() { return B(); } }; void f(A a) {} int main(void) { f(C()); } Does it create tree of all possible conversions and chooses appropriate terminal? Something else? Thanks
The call to f() would need two conversions, one user-defined conversion (C to B) and one built-in conversion (derived-to-base: B to A). Calls with non-matching arguments succeed when they would need zero or one user-defined conversions. If different conversions (built-in or user-defined) would succeed, then, if all possible ways are equal in the number/kind of conversions they need, the call is ambiguous and the compiler needs to emit a diagnostic. How compilers implement this isn't specified by the standard.
2,443,701
2,443,748
Piping EOF problems with stdio and C++/Python
I got some problems with EOF and stdio in a communication pipeline between a python process and a C++ program. I have no idea what I am doing wrong. When I see an EOF in my program I clear the stdin and next round I try to read in a new line. The problem is: for some reason the getline function immediatly (from the second run always, the first works just as intended) returns an EOF instead of waiting for a new input from the python process... Any idea? alright Here is the code: #include <string> #include <iostream> #include <iomanip> #include <limits> using namespace std; int main(int argc, char **argv) { for (;;) { string buf; if (getline(cin,buf)) { if (buf=="q") break; /*****///do some stuff with input //my actual filter program cout<<buf; /*****/ } else { if ((cin.rdstate() & istream::eofbit)!=0)cout<<"eofbit"<<endl; if ((cin.rdstate() & istream::failbit)!=0)cout<<"failbit"<<endl; if ((cin.rdstate() & istream::badbit)!=0)cout<<"badbit"<<endl; if ((cin.rdstate() & istream::goodbit)!=0)cout<<"goodbit"<<endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max()); //break;//I am not using break, because I //want more input when the parent //process puts data into stdin; } } return 0; } and in python: from subprocess import Popen, PIPE import os from time import sleep proc=Popen(os.getcwd()+"/Pipingtest",stdout=PIPE,stdin=PIPE,stderr=PIPE); while(1): sleep(0.5) print proc.communicate("1 1 1") print "running"
communicate in python is a one shot function. It sends the given input to a process, closes the input stream, and reads the output streams, waiting for the process to terminate. There is no way you can 'restart' the pipe with the same process after "communicating". Conversely, on the other side of the pipe, when you read EOF there is no more data to read. Any attempt to read will immediately return EOF; python has closed the pipe. If you want to carry on communicating with the same pipe you need to use the subprocess' stdin and stdout members and not communicate (but be careful of the potential of deadlocks) and use something other than the end of stream to signal that the C++ side should do another "batch" of processing.
2,443,738
2,445,047
C++ TerminateProcess function
I've been searching examples for the Win32 API C++ function TerminateProcess() but couldn't find any. I'm not that familiar with the Win32 API in general and so I wanted to ask if someone here who is better in it than me could show me an example for, Retrieving a process handle by its PID required to terminate it and then call TerminateProcess with it. If you aren't familiar with C++ a C# equivalent would help too.
To answer the original question, in order to retrieve a process handle by its PID and call TerminateProcess, you need code like the following: BOOL TerminateProcessEx(DWORD dwProcessId, UINT uExitCode) { DWORD dwDesiredAccess = PROCESS_TERMINATE; BOOL bInheritHandle = FALSE; HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); if (hProcess == NULL) return FALSE; BOOL result = TerminateProcess(hProcess, uExitCode); CloseHandle(hProcess); return result; } Keep in mind that TerminateProcess does not allow its target to clean up and exit in a valid state. Think twice before using it.
2,443,911
2,444,213
std::string constructor corrupts pointer
I have an Entity class, which contains 3 pointers: m_rigidBody, m_entity, and m_parent. Somewhere in Entity::setModel(std::string model), it's crashing. Apparently, this is caused by bad data in m_entity. The weird thing is that I nulled it in the constructor and haven't touched it since then. I debugged it and put a watchpoint on it, and it comes up that the m_entity member is being changed in the constructor for std::string that's being called while converting a const char* into an std::string for the setModel call. I'm running on a Mac, if that helps (I think I remember some problem with std::string on the Mac). Any ideas about what's going on? EDIT: Here's the code for GEntity: GEntity::GEntity(GWorld* world, unsigned long int idNum) { GEntity(world, idNum, btTransform::getIdentity()); } GEntity::GEntity(GWorld* world, unsigned long int idNum, btTransform trans) : m_id(idNum), m_trans(trans), m_world(world) { // Init unused properties m_rigidBody = NULL; m_entity = NULL; // I'm setting it here m_parent = NULL; // Find internal object name std::ostringstream ss; ss << "Entity" << idNum << "InWorld" << world; m_name = ss.str(); // Create a scene node m_sceneNode = m_world->m_sceneMgr->getRootSceneNode()->createChildSceneNode(m_name+"Node"); // Initialize the SceneNode's transformation m_sceneNode->setPosition(bv3toOv3(m_trans.getOrigin())); m_sceneNode->setOrientation(bqToOq(m_trans.getRotation())); } void GEntity::setModel(std::string model) { m_model = model; // Delete entity on model change if(m_entity != NULL) { // And by the time this line comes around, it's corrupt m_world->m_sceneMgr->destroyEntity(m_entity); m_entity = NULL; } // Create new entity with given model m_entity = m_world->m_sceneMgr->createEntity(m_name+"Ent", model); // Apply a new rigid body if needed if(m_rigidBody != NULL) { initPhysics(); } } void GEntity::initPhysics() { deinitPhysics(); } void GEntity::deinitPhysics() { if(m_rigidBody != NULL) { m_world->m_dynWorld->removeRigidBody(m_rigidBody); delete m_rigidBody; m_rigidBody = NULL; } } And here's the definition of GEntity: class GEntity : public btMotionState { public: GEntity(GWorld* world, unsigned long int idNum); GEntity(GWorld* world, unsigned long int idNum, btTransform trans); void setModel(std::string modelName); void initPhysics(); void deinitPhysics(); void getWorldTransform(btTransform& worldTrans) const; void setWorldTransform(const btTransform &trans); void parent(GEntity* parent); protected: unsigned long int m_id; // Physics representation btTransform m_trans; btRigidBody* m_rigidBody; // Graphics representation Ogre::SceneNode* m_sceneNode; Ogre::Entity* m_entity; // Engine representation GWorld* m_world; GEntity* m_parent; std::string m_name; std::string m_model; // Used to find physics collision mesh }; And here's the code calling setModel: // Setup game world GWorld* world = new GWorld(win); GEntity* ent = world->createEntity(); ent->setModel(std::string("Cube.mesh"));
Your problem is that this line is constructing a nameless temporary GEntity inside the constructor body for a different GEntity. The temporary is then thrown away once the statement completes and no further initialization of the non-temporary GEntity is performed. GEntity(world, idNum, btTransform::getIdentity()); If you want to share some initialization code between your two constructors you should create a member function that performs the required actions and call this function from both constructors. C++ doesn't (currently) allow you to delegate initialization from one constructor to a different constructor or call two constructors on the same object.
2,444,085
2,444,099
alternative to strdup
I'm writing a C++ class for a book that contains a name: class Book { private: char* nm; .......... ............ .......... ........... }; I am not allowed to use std::string in this assignment. So here I am using strdup to copy the value of the parameter name into nm in the constructor: Book::Book(const char *name, int thickness, int weight) : nm(NULL) , thck(thickness) , wght(weight) { if (name) nm = strdup(name); } Is there an alternative of achieving the same result without using strdup, but using the keyword new instead?
Strictly speaking: The string class is part of the Strings library. This is much easier to use, dynamic in nature and you have less worry when copying/assigning than C-style strings. The other approach is to manually copy out: class Book { public: Book(const char *name, ...) : nm(0), ... { if (!name) throw "invalid parameter"; nm = new char [ strlen(name) + 1 ]; strcpy(nm, name); } ~Book() { delete [] nm; // ... } Book(Book const& o) : nm(0), ... { if (!name) throw "invalid parameter"; char *p = new char [ strlen(name) + 1 ]; if (p) { strcpy(p, name); delete [] nm; nm = p; } } Book& operator=(Book const& o) { if (this != &o) { char *p = new char [ strlen(name) + 1 ]; if (p) { strcpy(p, name); delete [] nm; nm = p; } } return *this; } }; The problem with this approach is that you will have to manage the memory yourself and implement all the Big-three special member functions yourself (and ensure exception-safety as much as you can).
2,444,148
2,449,152
GDI+ Load a jpg and save as 24bit png problem
Problem Hello all! I have this code which takes my jpg image loops through altering pixels and finally saving it as a png type. The problem is that the resulting image has a bit depth of 32 bits. I need it to be 24 bit, can any one shiny some light on the correct method of setting it? Am I along the right tracks looking at setting the pixel format to PixelFormat24bppRGB? Code static inline void Brighten(Gdiplus::Bitmap* img) { int width = img->GetWidth()/8,height = img->GetHeight(), max = (width*height),r,g,b; Gdiplus::Color pixel; for(int a = 0,x = 0, y = -1; a < max; ++a) { x = a%width; if(x == 0) ++y; img->GetPixel(x,y,&pixel); r = pixel.GetR(); g = pixel.GetG(); b = pixel.GetB(); if (r > 245) r = 245; if (g > 245) g = 245; if (b > 245) b = 245; r += 10; g += 10; b += 10; pixel = Gdiplus::Color(r,g,b); img->SetPixel(x,y,pixel);; } } ULONG_PTR m_dwToken = 0; Gdiplus::GdiplusStartupInput input; Gdiplus::GdiplusStartupOutput output; Gdiplus::GdiplusStartup( &m_dwToken, &input, &output ); USES_CONVERSION_EX; Gdiplus::ImageCodecInfo* pEncoders = static_cast< Gdiplus::ImageCodecInfo* >( _ATL_SAFE_ALLOCA(1040, _ATL_SAFE_ALLOCA_DEF_THRESHOLD)); Gdiplus::DllExports::GdipGetImageEncoders(5, 1040, pEncoders ); CLSID clsidEncoder = pEncoders[4].Clsid; Gdiplus::Bitmap img1((CT2W)L"IMG_1.JPG"); Brighten(&img1); img1.Save((CT2W)L"IMG_1_R3.PNG",&clsidEncoder,NULL); Thanks in advance!
Ok I actually fixed it, I've used the LockBits() to access the bits directly and modify them, this gives me a much needed performance boost and keeps it as a 24bit image. static inline void Brighten(Gdiplus::Bitmap* img) { int width = img->GetWidth(),height = img->GetHeight(),r,g,b; Gdiplus::Rect rect(0,0,width,height); Gdiplus::BitmapData data; img->LockBits(&rect,Gdiplus::ImageLockModeWrite,PixelFormat24bppRGB,&data); int stride = data.Stride,offset = stride - width*3; byte * p1 = (byte *)(void *)data.Scan0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { r = p1[0]; g = p1[1]; b = p1[2]; if (r > 245) r = 245; if (g > 245) g = 245; if (b > 245) b = 245; r += 10; g += 10; b += 10; p1[0] = r; p1[1] = g; p1[2] = b; p1 += 3; } p1 += offset; } img->UnlockBits(&data); } Thanks for all of your help!
2,444,351
2,444,355
A 16-digit hashing function
Is there a hash function that returns a 16-digit hex value (as MD5 returns 32-digit), or is there a library (for C++) in which I can use MD5 or SHA-1 which returns a 16-digit value
Since you're willing to live with the much-higher collision rate, you can just truncate the MD5 hash of the data.
2,444,428
2,454,874
Need help modifying C++ application to accept continuous piped input in Linux
The goal is to mine packet headers for URLs visited using tcpdump. So far, I can save a packet header to a file using: tcpdump "dst port 80 and tcp[13] & 0x08 = 8" -A -s 300 | tee -a ./Desktop/packets.txt And I've written a program to parse through the header and extract the URL when given the following command: cat ~/Desktop/packets.txt | ./packet-parser.exe But what I want to be able to do is pipe tcpdump directly into my program, which will then log the data: tcpdump "dst port 80 and tcp[13] & 0x08 = 8" -A -s 300 | ./packet-parser.exe Here is the script as it is. The question is: how do I need to change it to support continuous input from tcpdump? #include <boost/regex.hpp> #include <fstream> #include <cstdio> // Needed to define ios::app #include <string> #include <iostream> int main() { // Make sure to open the file in append mode std::ofstream file_out("/var/local/GreeenLogger/url.log", std::ios::app); if (not file_out) std::perror("/var/local/GreeenLogger/url.log"); else { std::string text; // Get multiple lines of input -- raw std::getline(std::cin, text, '\0'); const boost::regex pattern("GET (\\S+) HTTP.*?[\\r\\n]+Host: (\\S+)"); boost::smatch match_object; bool match = boost::regex_search(text, match_object, pattern); if(match) { std::string output; output = match_object[2] + match_object[1]; file_out << output << '\n'; std::cout << output << std::endl; } file_out.close(); } } Thank you ahead of time for the help!
You're going to have to make some bigger changes to get it to work. Your getline delimited by '\0' won't terminate until it either sees a '\0' (which isn't going to happen) or the input reaches EOF. That's why it works when you use a file (which eventually reaches EOF) but not with streaming straight from tcpdump. I'm having trouble compiling with Boost, so I'm still not totally sure this will work. But you should get the idea. [Edit: It works :-)] std::string text, line1, line2; std::getline(std::cin, line1); while(std::getline(std::cin, line2)) { text = line1 + '\n' + line2; // ... line1 = line2; } file_out.close();
2,444,514
2,444,521
Why do programmers sometimes refer to "C++/STL" like it's a separate language?
This may seem a trivial question, but it's one that's bothered me a lot lately. Why do some programmers refer to "C++/STL" like it's a different language? The STL is part of the C++ standard library -- and therefore is part of the language, "C++". It's not a separate component, and it does not live alone in the scope of things C++. Yet some continually act like it's a different language altogether. Why?
An understanding of the STL isn't necessary to understand C++. It's useful to have when you need ADTs, but you can go (could have gone?) through your whole C++ career without needing it.
2,444,650
2,444,682
Colour instead of color?
I'm working on a game engine in C++ and I have methods like setColour and things that use British grammar. While I was thinking how C++ compilers mostly use the English language (correct me if I'm wrong) and how most APIs use American grammar, should I go with the flow and continue the unofficial standard in the grammar programmer high council or be a rebel? I'm not sure which.
You should use the American spelling of color. 99% of code out there uses this, even including much of the code written by British or Australian English speakers. If you use something different, you (or someone else that uses your code) are just going to end up forgetting which to use at some point and making a needless mistake.
2,444,695
2,444,706
volatile vs. mutable in C++
I have a question about the difference between volatile and mutable. I noticed that both of the two means that it could be changed. What else? Are they the same thing? What's the difference? Where are they applicable? Why the two ideas are proposed? How to use them in different way? Thanks a lot.
A mutable field can be changed even in an object accessed through a const pointer or reference, or in a const object, so the compiler knows not to stash it in R/O memory. A volatile location is one that can be changed by code the compiler doesn't know about (e.g. some kernel-level driver), so the compiler knows not to optimize e.g. register assignment of that value under the invalid assumption that the value "cannot possibly have changed" since it was last loaded in that register. Very different kind of info being given to the compiler to stop very different kinds of invalid optimizations.
2,444,843
2,444,876
why nResult != nConvertedLen,when use CComBSTR;
CComBSTR wsData = (char*)pvData; when constuct CComBSTR,call A2WBSTR,but sometimes nResult != nConvertedLen,just 1/20. why? inline BSTR A2WBSTR(_In_opt_ LPCSTR lp, int nLen = -1) { if (lp == NULL || nLen == 0) return NULL; USES_CONVERSION_EX; BSTR str = NULL; #pragma warning(push) #pragma warning(disable: 6385) int nConvertedLen = MultiByteToWideChar(_acp_ex, 0, lp, nLen, NULL, NULL); #pragma warning(pop) int nAllocLen = nConvertedLen; if (nLen == -1) nAllocLen -= 1; // Don't allocate terminating '\0' str = ::SysAllocStringLen(NULL, nAllocLen); if (str != NULL) { int nResult; nResult = MultiByteToWideChar(_acp_ex, 0, lp, nLen, str, nConvertedLen); ATLASSERT(nResult == nConvertedLen); if(nResult != nConvertedLen) { SysFreeString(str); return NULL; } } return str; }
My best guess is that there are multi-threading issues involved. As you can see both nResult and nConvertedLen are results to calls to MultiByteToWideChar with the same source string. The first call is used to simply determine the length of the buffer that needs to be allocated to return the result of the conversion. MultiByteToWideChar Documentation describes the behaviour of the function when the buffer length parameter is 0: cchWideChar [in] Size, in wide characters, of the buffer pointed to by the lpWideCharStr parameter. If this value is zero, the function returns the required buffer size, in wide characters, and makes no use of the lpWideCharStr buffer. So, the only time that the two values would be different is when string pointed to by lp changes between to calls, most likely due to threading issues.
2,444,933
2,444,940
One question with array declaration in C++
What's the difference between the two code below. int a[] = {0,0}; int a[2] = {0,0}; It seems I can assign value to a[3] in both cases. I can access a[3] in any case. So what's the difference?
There is no difference. In the first one, the compiler does the counting for you, which is nice if you decide to change the number of elements later on. The fact that your compiler forgives you for assigning to or using a[3] doesn't mean that doing so is correct. In fact, you can't even access a[2] since it only has two elements, indexed by subscripts 0 and 1.
2,445,050
2,445,071
How different is Objective-C from C++?
What are the main differences between Objective-C and C++ in terms of the syntax, features, paradigms, frameworks and libraries? *Important: My goal is not to start a performance war between the two languages. I only want real hard facts. In fact, my question is not related to performance! Please give sources for anything that may seem subjective.
Short list of some of the major differences: C++ allows multiple inheritance, Objective-C doesn't. Unlike C++, Objective-C allows method parameters to be named and the method signature includes only the names and types of the parameters and return type (see bbum's and Chuck's comments below). In comparison, a C++ member function signature contains the function name as well as just the types of the parameters/return (without their names). C++ uses bool, true and false, Objective-C uses BOOL, YES and NO. C++ uses void* and nullptr, Objective-C prefers id and nil. Objective-C uses "selectors" (which have type SEL) as an approximate equivalent to function pointers. Objective-C uses a messaging paradigm (a la Smalltalk) where you can send "messages" to objects through methods/selectors. Objective-C will happily let you send a message to nil, unlike C++ which will crash if you try to call a member function of nullptr Objective-C allows for dynamic dispatch, allowing the class responding to a message to be determined at runtime, unlike C++ where the object a method is invoked upon must be known at compile time (see wilhelmtell's comment below). This is related to the previous point. Objective-C allows autogeneration of accessors for member variables using "properties". Objective-C allows assigning to self, and allows class initialisers (similar to constructors) to return a completely different class if desired. Contrast to C++, where if you create a new instance of a class (either implicitly on the stack, or explicitly through new) it is guaranteed to be of the type you originally specified. Similarly, in Objective-C other classes may also dynamically alter a target class at runtime to intercept method calls. Objective-C lacks the namespace feature of C++. Objective-C lacks an equivalent to C++ references. Objective-C lacks templates, preferring (for example) to instead allow weak typing in containers. Objective-C doesn't allow implicit method overloading, but C++ does. That is, in C++ int foo (void) and int foo (int) define an implicit overload of the method foo, but to achieve the same in Objective-C requires the explicit overloads - (int) foo and - (int) foo:(int) intParam. This is due to Objective-C's named parameters being functionally equivalent to C++'s name mangling. Objective-C will happily allow a method and a variable to share the same name, unlike C++ which will typically have fits. I imagine this is something to do with Objective-C using selectors instead of function pointers, and thus method names not actually having a "value". Objective-C doesn't allow objects to be created on the stack - all objects must be allocated from the heap (either explicitly with an alloc message, or implicitly in an appropriate factory method). Like C++, Objective-C has both structs and classes. However, where in C++ they are treated as almost exactly the same, in Objective-C they are treated wildly differently - you can create structs on the stack, for instance. In my opinion, probably the biggest difference is the syntax. You can achieve essentially the same things in either language, but in my opinion the C++ syntax is simpler while some of Objective-C's features make certain tasks (such as GUI design) easier thanks to dynamic dispatch. Probably plenty of other things too that I've missed, I'll update with any other things I think of. Other than that, can highly recommend the guide LiraNuna pointed you to. Incidentally, another site of interest might be this. I should also point out that I'm just starting learning Objective-C myself, and as such a lot of the above may not quite be correct or complete - I apologise if that's the case, and welcome suggestions for improvement. EDIT: updated to address the points raised in the following comments, added a few more items to the list.
2,445,143
2,445,182
How does void QTableWidget::setItemPrototype ( const QTableWidgetItem * item ) clones objects?
QTableWidget::setItemPrototype says following. "The table widget will use the item prototype clone function when it needs to create a new table item. For example when the user is editing in an empty cell. This is useful when you have a QTableWidgetItem subclass and want to make sure that QTableWidget creates instances of your subclass." How does this actually work as you can pass any of the QTableWidgetItem subclass pointer to setItemPrototype and at run time there is no way you can get the size of an object having just pointer to it?
QTableWidgetItem::clone() is a virtual member function and has to be reimplemented by subclasses of QTableWidget. Thus, when clone() is called, the implementation of clone() in the subclass is getting invoked, and in the subclass, the correct type is of course known.
2,445,469
2,445,486
Why cant we initialize Const and reference varibales inside the constructor braces({ }) and is always done via initialization list
Why cant we initialize Const and reference varibales inside the constructor braces({ }) and is always done via initialization list Thanks, Sandeep
The lifetime for a reference begins after it's initialized (like all variables), and once it's initialized it represents an alias to another variable. Consider: int& x; /// ... SomeClassConstructor(void) { // initialization list is done, reference lifetime has begun, and // therefore is an alias. It already must alias a variable, then. x = 5; // setting whatever x is an alias for to 5 } You see, once we enter the constructor, all member variables are initialized. For a reference, this means it must be referring to a variable. Ergo, we must initialize it to refer to something in the initialization list. Likewise, assigning to a const variable is illegal: const int x = 5; x = 2; // doesn't compile. It must be initialized to a value, and it will remain the value for its lifetime. Therefore, it too must be initialized in the initialization list.
2,445,476
2,445,851
Ruby on Rails, PHP or C++ for web social network
I have chosen diploma work in university. It's a mini social network. But now I am really stuck with which technology I should stick. I am average at C++ ISAPI web services development, below average PHP(had few projects with it) and new to Ruby and its framework RAILS. I have a deadline 1.5 month to develop it(about 5 hours every day after my full time job). Also I heard that its very easy to learn and develop with Ruby on Rails. Considering C++ I know that I have to do lots of coding and work by myself and PHP looks almost the same to me. So I am looking for you skilled developers advise what would you do in my position? Learn RoR, stick with C++ or PHP or maybe use something else?
Definitely not C++. I work with C++, Ruby, PHP, Ruby on Rails, CakePHP, CodeIgniter and Kohana. Since C++ is more similar to PHP than Ruby and you have little time to learn, I would go with a PHP framework. Every now and then I like to make little social networks in my local machine , I would recommend that you got with codeigniter simply because it can provide everything I can think of that a social network would need and it's the easiest of all to learn and master. Am sure these codeigniter screencasts will help you.
2,445,514
2,445,552
Returning recursive ternary freaks out
assume this following function: int binaryTree::findHeight(node *n) { if (n == NULL) { return 0; } else { return 1 + max(findHeight(n->left), findHeight(n->right)); } } Pretty standard recursive treeHeight function for a given binary search tree binaryTree. Now, I was helping a friend (he's taking an algorithms course), and I ran into some weird issue with this function that I couldn't 100% explain to him. With max being defined as max(a,b) ((a)>(b)?(a):(b)) (which happens to be the max definition in windef.h), the recursive function freaks out (it runs something like n^n times where n is the tree height). This obviously makes checking the height of a tree with 3000 elements take very, very long. However, if max is defined via templating, like std does it, everything is okay. So using std::max fixed his problem. I just want to know why. Also, why does the countLeaves function work fine, using the same programmatic recursion? int binaryTree::countLeaves(node *n) { if (n == NULL) { return 0; } else if (n->left == NULL && n->right == NULL) { return 1; } else { return countLeaves(n->left) + countLeaves(n->right); } } Is it because in returning the ternary function, the values a => countLeaves(n->left) and b => countLeaves(n->right) were recursively double called simply because they were the resultants? Thank you! The question was answered below I just wanted to link some literature on the subject for future reference: http://www.boostpro.com/tmpbook/preprocessor.html http://msdn.microsoft.com/en-us/library/z3f89ch8.aspx The main difference between the two implementations being: #define max(i, j) (((i) > (j)) ? (i) : (j)) vs template<class T> T max (T i, T j) { return ((i > j) ? i : j) } Thank you all!
Macros are expanded by the preprocessor, before the compiler gets to see the code. This means that, for example, macro parameters might be evaluated more than once. With your macro, you're going to end up with something akin to: int binaryTree::findHeight(node *n) { if (n == NULL) { return 0; } else { return 1 + (findHeight(n->left) > findHeight(n->right)) ? // call once... findHeight(n->left) : findHeight(n->right); // and ouch } } As you can see, it's going to evaluate both functions, then one more an additional time. This is why macros can be evil. You can disable the macro by defining NOMINMAX prior to including the Windows headers. Then use the function in <algorithm> instead. If he must use the macro, he'll have to store the calculations in a variable: int binaryTree::findHeight(node *n) { if (n == NULL) { return 0; } else { const int leftHeight = findHeight(n->left); const int rightHeight = findHeight(n->right); return 1 + max(leftHeight, rightHeight); } } With a function, each call will be evaluated prior to calling the function. That is, it's somewhat like the previous code block. It evaluates the function's arguments, gets the results, then passes those into the std::max function. There are no repeated evaluations.
2,445,543
2,445,811
C++ for Ruby scripters
I am a fairly capable Ruby scripter/programmer, but have been feeling pressure to branch out into C++. I haven't been able to find any sites along the lines of "C++ for Ruby Programmers". This site exists for Python (which is quite similar, I know). Does anyone know of a guide that can help me translate my Ruby 'thoughts' into C++?
I don't think that language introductions written specifically for migrants from a certain language have considerable advantage over traditional "independent" introductory books. Reading as a cognitive process has a great feature: reading speed varies greatly. That means that you should take any good C++ book (I'm sure you'll find excellent recommendations here on SO) and your reading speed will be greatly affected by your previous programming knowledge - reading about things you already know will become almost skimming-fast, others will take some time. In the end, you will spend practically the same amount of time as you would if you read a specific migrant course, with the difference of having read a book that you will be able to use as a language reference at any given time in the future, unlike the "transitional guide", which is always kind of "one-time read". On the other hand, from a perspective of a writer, it's pretty ungrateful to assume (and rely on) such thing as reader's knowledge on a topic. When one says he knows Ruby is it really a guarantee that he knows OOP thoroughly, for example? Or just have been using it not understanding the internals (which is really easy for a Rails programmer, for example). So a general book is a safe bet both for a writer and a reader. :)
2,445,760
2,454,607
Vim plugin for updating C++ function definition
I'm looking for a Vim plugin that can do these kind of thing. Let's say I have a function in a .cpp file void myFunction(int arg1, int arg2, int arg3){ //code } The function definition is defined in the .h file. So every time I change the function name or add a new argument to the function, I have to go back the the .h file to do the same. Is there a Vim plugin that can automate this task?
It sounds to me like you are looking for a C++ refactoring tool. A quick search for 'refactor' on vim.org brought up one script specifically meant for C/C++ but it doesn't have a very high rating.
2,445,771
2,445,783
Function return type style
I'm learning c++0x, at least the parts supported by the Visual C++ Express 2010 Beta. This is a question about style rather than how it works. Perhaps it's too early for style and good practice to have evolved yet for a standard that isn't even released yet... In c++0x you can define the return type of a method using -> type at the end of the function instead of putting the type at the start. I believe this change in syntax is required due to lambdas and some use cases of the new decltype keyword, but you can use it anywhere as far as I know. // Old style int add1(int a, int b) { return a + b; } // New style return type auto add2(int a, int b) -> int { return a + b; } My question really then, is given that some functions will need to be defined in the new way is it considered good style to define all functions in this way for consistency? Or should I stick to only using it when necessary?
Do not be style-consistent just for being consistent. Code should be readable, i.e. understandable, that's the only real measure. Adding clutter to 95% of the methods to be consistent with the other 5%, well, that just does not sound right to me.
2,445,820
2,445,867
DST change handling in a daemon process (*NIX)
In a *NIX environment, if I have a 24x7 running application, how do I handle DST changes? I am looking for a solution for my app written in C/C++.
Why would a deamon use anything else that UTC time?
2,445,868
2,445,876
Is select() Ok to implement single socket read/write timeout?
I have an application processing network communication with blocking calls. Each thread manages a single connection. I've added a timeout on the read and write operation by using select prior to read or write on the socket. Select is known to be inefficient when dealing with large number of sockets. But is it ok, in term of performance to use it with a single socket or are there more efficient methods to add timeout support on single sockets calls ? The benefit of select is to be portable.
Yes that's no problem, and you do want some timeout mechanisms to not leak resources from bad behaving clients etc. Note that having a large number of threads is even more inefficient than having select dealing with a large number of sockets.
2,445,899
2,446,020
Does operator new allocate on THREAD heap?
My problem seems to be this: heap data allocated by one thread (that later dies) seems to die as well. As so: Thread X: starts Thread Y: starts Thread X: ptr = new some bytes Thread X: dies Thread Y: tries to use ptr - and crashes! So far, I've only seen this problem on Darwin (Mac OS 10.5 and 10.6), but haven't tried more other platforms than Windows and Linux (Ubuntu) where it works as expected. I've had this problem for some time, so any know-how or more information about this is highly appreciated! Edit: the problem was caused by an unrelated crash bug.
Do threads have a distinct heap? This thread has some good information regarding this subject
2,446,142
2,446,159
How to differentiate two constructors with the same parameters?
Suppose we want two constructors for a class representing complex numbers: Complex (double re, double img) // construct from cartesian coordinates Complex (double A, double w) // construct from polar coordinates but the parameters (number and type) are the same: what is the more elegant way to identify what is intended? Adding a third parameter to one of the constructors?
It is better to add static methods with appropriate names and let them to create the objects. static Complex createFromCartesian(double re, double img); static Complex createFromPolar(double A, double w);