question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
4,501,867
4,502,169
Accessing to mm1 register parts
Is it possible to access to a single byte in a mmx register, like a array? I've this code: movq mm1,vector1 movq mm2,vector2 psubw mm1,mm2 I want to put mm1[1],mm1[2],mm1[3]....into c++ vars, like: int a,b=0; mov a,mm1[1] mov b,mm1[2] Thanks.
Yes, it is possible. I can show the code for SSE2 for c++, but is similar for MMX : __m128i a; unsigned char *p = (unsigned char*) &a; // access bytes pointed by pointer p
4,502,564
4,502,589
how to find width of font?
I'm using directx to draw my string, directx uses GDI to draw the string.. I'm using DrawText to draw my string. I need a way to find the width of the string. Any idea ?
DrawText can calculate it for you. See the DT_CALCRECT flag: http://msdn.microsoft.com/en-us/library/dd162498%28v=vs.85%29.aspx
4,502,618
4,502,704
How to include a self-created class in another self-created class's header file?
Say I have created two classes: Tires, and Car. So I have four files: Tires.cpp, Tires.h, Car.cpp, Car.h. The Car constructor takes Tires as its parameter. But I am not sure how to modify Car.h to include Tires.h. Here's what I've done so far (note: they are in separate files) Tires.h #include <iostream> using namesp...
Your approach seems fine here. One thing to keep in mind when headers include other headers is that you may find you need to include an include guard: // At the start of Tires.h: // // Only delcare this stuff if this is the first time including Tires.h: // #ifndef __myproject_Tires_h__ #define __myproject_Tires_h__ c...
4,502,670
4,504,731
Continuous build infrastructure recommendations for primarily C++; GreenHills Integrity
I need your recommendations for continuous build products for a large (1-2MLOC) software development project. Characteristics: ClearCase revision control Approx 80% C++; 15% Java; 5% script or low-level Compiles for Green Hills Integrity OS, but also some windows and JVM chunks Mostly an embedded system; also includ...
From my experience with similar systems, there are approximately two parts to this problem: A repeatable method for checking out sources, building the software, and testing it (if you want to do continual testing as well as building), using a small number of command-line invocations. A means of calling these command l...
4,502,685
4,503,140
Program crashing on exit
Whenever I exit my program it gives me this exception "0xC0000022: A process has requested access to an object, but has not been granted those access rights." It breaks right at the end of a function called _lock_file in _file.c. After trying to narrow down what the cause of the problem is I found out that it does not...
Are you using the same runtime library (Debug DLL, Debug, Release DLL, Release, etc.) for your main program as was used to build the SDL library? That can often (but not always) cause odd problems, and would be my first port of call when getting this sort of odd behaviour at runtime. (If you get an LNK4098 warning when...
4,502,691
4,502,878
What is the purpose of allocator_traits<T> in C++0x?
Why isn't standard C++03 interface for querying member types for allocators used in C++0x? What are the use cases where member types are not sufficient?
I'm not familiar with this kind of things (at all), but this document seems like a good starting point to get a grasp on the rationale behind allocator_traits : The keystone of this proposal is the definition of an allocator_traits template containing types and static member functions for using allocators, ef...
4,502,719
4,502,771
Stop XML parsing after a specific number of entries
I am currently using Poco::XML to parse through a number of very large XML files using SAX. For some of those files I only need the first n number of entries. I was wondering if anyone can show me how to tell Poco::XML to cease parsing once I go over my threshold of entries.
What you are looking for is a pull parser and If I am looking at the correct library (I am a java developer) poco does support pull parsing. Look here http://pocoproject.org/blog/?p=322 If this is not the right library for you then you need to throw an exception that stops the parsing operation (may be SAXException whe...
4,502,728
4,502,807
Accessing an object in operator new
My professor in C++ has shown us this as an example in overloading the operator new (which i believe is wrong): class test { // code int *a; int n; public: void* operator new(size_t); }; void* test::operator new(size_t size) { test *p; p=(test*)malloc(size); cout << "Input the size of array...
It's definitely "not right", in the sense that it's giving me the creeps. Since test has no user-declared constructors, I think it could work provided that the instance of test isn't value-initialized (which would clear the pointer). And provided that you write the corresponding operator delete. It's clearly a silly ex...
4,502,741
4,505,728
Add a menu resource to a dialog box
I was wondering if it is possible to add a menu resource to a dialog box. It would be easier to "design" my applications layout in multiple dialog boxes rather than the standard window, however, I will need to be able to add a menu. I would preferably be able to do this through a resource defined menu, however, I have ...
Call SetMenu(hDlg, hMenu) during WM_INITDIALOG.
4,503,069
4,503,079
Which boolean expression gets evaluated first in an IF statement containing an OR operation?
In the following statement, in VC++, which boolean expression gets evaluated first? Also, do they both get evaluated? if( (X==Y) || (Z==T)) { //code here }
They're evaluated left-to-right and if the first one is true the expression short-circuits and the second one is not evaluated.
4,503,260
4,512,052
Problem with wxWidgets on Snow Leopard
I have a problem with getting compiled an wxWidget-application. I have installed the latest version of the library as follows: set arch_flags="-arch x86_64 " ./configure -with-osx_cocoa --disable-shared --disable-compat24 --enable-unicode --enable-universal-binary CFLAGS="$arch_flags" CXXFLAGS="$arch_flags" CPPFLAGS="$...
I'm surprised that you have libwx_xxx in /usr/lib when the default installation prefix is /usr/local. Are you sure you don't have multiple incompatible libraries versions on your system? Also, when using static linking the libraries containing the dependencies of your code must come after the object file referencing th...
4,503,403
4,503,438
Sinusoid and derivative function
I have some object whish moves by sinusoid. I have to animate it each time it reaches the top (or the bottom) of the "wave". I want to do this with derivative function: as we know it changes the value (from positive to negative or contrary) at that points. So the code is: // Start value int functionValue = +1; // Fun...
You have y = a * sin(b * x) + c derivative of that is y' = a * b * cos(b * x) not y' = -cos(y)
4,503,506
4,503,528
Cursor style doesn't stay updated
I have a normal Windows GUI application (made using the API, not MFC) and as I move my mouse on and off the application and the mouse changes styles (like when you move it over the border, it changes to a resize arrow, etc.) but sometimes it "sticks" in that style, so that I can move the mouse around and it will stay i...
Set a valid cursor handle when you register your window class. See WNDCLASSEX::hCursor. Use LoadCursor to load a valid cursor. Like, WNDCLASSEX wc = {0}; ... wc.hCursor = LoadCursor(NULL, IDC_ARROW); ... RegisterClassEx(&wc);
4,503,574
4,543,527
boost multi_index partial indexes
I want to implement inside boost multi-index two sets of keys with same search criteria but different eviction criteria. Say i have two sets of data with same search condition, but one set needs a MRU(Most Recently Used) list of 100 and the other set requires a MRU of 200. Say the entry is like this class Student { ...
It is possible to do the same with sequenced in place of the second index and holding the iterator which splits the male and female as a cached one. This helps is with the same behavior.
4,503,623
4,503,721
How to store structs in a file to easily reload?
I've got these two structs that I need to store in files. I can't find a good way to get them into a file without parsing the struct and writing it as a text file, which is far less efficient than I'd like. What is the simplest way to get a struct of mostly primitives into a file? The structs are below struct object { ...
You can't write a struct containing a vector using raw byte I/O. The vector class is a small data structure that stores its data somewhere on the heap, not in the struct. This is because it is impossible for a struct to "know," ahead of time, how many objects it will hold. You can write the contents of the vector thus:...
4,503,628
4,504,078
How can I atomically swap two pointers on Windows?
Okay, I'm asking the same thing as this deleted question, but I'm asking it more directly. I've got two pointer variables in two instances of the same class. I'd like to swap the contents of those variables (not what they POINT to, just the variables themselves) atomically. I'd like to avoid locks if at all possible. H...
I'm going to go out on a limb and say that you need a lock and that there is no general-case lock-free solution to this problem. You would need to read from two addresses and write back to both addresses all atomically. To the best of my knowledge, X86 can only atomically exchange data from a single memory address a...
4,503,673
4,575,714
Determining Cross Domain Active Directory Group Membership
I am currently working on a project where I need to query Active Directory to determine group membership of a user. I initially was locating the user and retrieving the memberOf attribute. The problem with this is that there is a domain and a child domain. The groups are universal groups so they can be used in both dom...
If you are using managed C++, you can use UserPrincipal.GetAuthorizationGroups. If you are not using managed C++, to solve this particular problem, you should bind to Global Catalog and do a LDAP search on the member attribute of the group object to find out which Universal Group containing the user. You should limit ...
4,504,109
4,504,121
LPBYTE Macro Generates Error at Compile - C++
I have the following code that is generating an error when I try to build the application: #define LPAFDU LPBYTE; typedef struct appAfDataIndIeee_tag { integrPktHead_t head; BYTE flags; WORD dstShort; BYTE dstEndpoint; BYTE srcShort; BYTE srcIeee[8]; WORD clusterId; BYTE afduLength; ...
Get rid of the semicolon at the end of your #define (it's part of the macro): #define LPAFDU LPBYTE A far better way to do this, however, is to use typedef rather than #define: typedef LPBYTE LPAFDU; The most important advantage of typedefs is that they obey scope rules.
4,504,132
4,512,198
What is causing boost::lower to fail an is_singular assertion?
I am occasionally getting odd behavior from boost::lower, when called on a std::wstring. In particular, I have seen the following assertion fail in a release build (but not in a debug build): Assertion failed: !is_singular(), file C:\boost_1_40_0\boost/range/iterator_range.hpp, line 281 I have also seen what appear ...
After further debugging, I figured out what was going on. The cause of my trouble was that one project in the solution was not defining NDEBUG (despite being in release mode), while all the other modules were. Boost allocates some extra fields in its data structures, which it uses to store debug information (such as w...
4,504,380
4,504,394
What types are types of in c?
I'm wondering what type types have in c. For example, how would I do something like this. type type_a = int; type type_b = float; In context of my project, I'm trying to make a function that can be used as follows. // createSelector(const char *name, ...) Selector *mySelector = createSelector("myMethod", int, char); ...
You can't do that in either C or C++. The ability to perform such type-based introspection is called "Reflection", and it's simply not a feature in C or C++. Honestly though, if you find yourself needing something like this you need to take an extremely long, hard look at your design -- needing things like this, even i...
4,504,612
4,504,637
Reading strings to a structure member in C++
I am from C#, Java background trying to learn C++. The following is a snippet I found for reading values for a structure variable. Could not quite figure out what is being done or whether this is the standard way of reading a string structure member. Isn't there a more cleaner way to do this. string mystr; struc...
That code uses a temporary stringstream fed with a line read from stdin to read the data into the struct member. Although there are some reasons for which you may be doing that (e.g. to check that the >> operator consumes the whole line), generally you could more simply do cin >> mystruct[n].member; As for the explana...
4,504,623
4,509,670
TCP IOCP won't receive after acceptex
I'm trying to write an IOCP server. Basically, I have it accepting new connections. For the purpose of my testing, I'm running and connecting to 127.0.0.1. I create the pseudo socket prior to calling AcceptEx(). Once a connection is accepted, the new pseudo socket is used for communication. This new socket is associat...
I figured it out. I'm an idiot. I was sending zero bytes.
4,504,687
4,505,127
Cycle through pixels with opencv
How would I be able to cycle through an image using opencv as if it were a 2d array to get the rgb values of each pixel? Also, would a mat be preferable over an iplimage for this operation?
If you use C++, use the C++ interface of opencv and then you can access the members via http://docs.opencv.org/2.4/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#the-efficient-way or using cv::Mat::at(), for example.
4,504,722
4,504,750
C++ Instantiate an object from a class two different ways
I'm pretty sure this has been asked before, but I can't for the life of me find it via search. So here it goes: What's the difference between: MyObj myObj; and MyObj myObj = MyObj(); I believe both achieve the same result, but is one better to use than the other? Assume all I want is the default constructor. *edit -...
Yes, there can be a difference. In the first instance, myObj is not initialized if it is a POD type otherwise it is default-initialized. In the second instance myObj is copy-initialized from a value-initialized temporary. The temporary may (and almost certainly should) be eliminated to make the effect value-initializat...
4,504,883
4,504,995
Vector iterator not dereferencable?
I'm getting that error with this code: for(std::vector<AguiTimedEvent*>::iterator it = timedEvents.begin(); it != timedEvents.end();) { if((*it)->expired()) { (*it)->timedEventCallback(); delete (*it); it = timedEvents.erase(it); } else it++; } What could be the pro...
If you are looping through a vector and the callback function causes the vector to be added to, then all iterators into the vector may be invalidated including the loop variable it. In this case (where the callback modifies the vector) you are probably better off using an index as your loop variable. You probably need ...
4,505,080
4,505,102
Does a C++ or C# library exist for converting CSS/HTML/jQuery code to C++ or C# code?
I am working on designing a GUI for a software that will be written in C++ or C#. My partner and I would like to test out the GUI in the browser first and then import to C++ or C#. Does a C++ or C# library exist for converting CSS/HTML/jQuery code to C++ or C# code?
No, the paradigms for developing for web applications and desktop applications are completely incompatible. If you don't have experience developing UI for a desktop application, the prototyping phase is a great time to get that experience. I always find it easiest to create prototypes in Visual Studio, and I also rely ...
4,505,090
4,505,117
Linking templates with g++
I'm implementing a hash table and linked list in C++ (no STL - don't ask) using templates, and I'm running into problems linking them with g++. If I #include all my .cpp files together, everything works, so my code definitely works, it's just the linking that's tripping me up. I read the bit in the GCC manual about tem...
If you are making template classes, it is not a good idea to put them in .cpp files and compile separately. The right way is to put them in .h files (both declaration and definition) and include them where you need them. The reason is that templates won't actually be compiled unless their template arguments are defined...
4,505,342
4,981,508
Strobe signal output on Pointgrey Firefly MV using libdc1394
I am using a Pointgrey Firefly MV (FFMV-03M2M/C to be precise) and want to trigger some external device with every shutter start. According to the datasheet, the camera supports IIDC 1.31 and also provides four GPIOs usable as a trigger and/or strobe signal outputs. As described in section 4.11.3 of the IIDC standard i...
Browsing through the (accessible, can't get to the technical reference) camera documentation it seems like you need to set a direction for the GPIOs, that is whether they are inputs or outputs. The documentation describes a PIO_DIRECTION register at 0x11F8 where low signifcant bits control whether the IO is input (0) ...
4,505,362
4,505,376
cl.exe not finding any standard include file
I found this sample code on the msdn library #include <iostream> int main() { std::cout << "This is a native C++ program." << std::endl; return 0; } from How to Compile a Native C++ Program From the Command Line I store this code in file.cpp I then go to the command prompt and type this The output is as follo...
The Visual C++ compiler depends on a whole bunch of environment variables. The easiest way to get these set right is using the "Visual Studio Command Prompt" item created on the Start menu during the install, or running vcvars32.bat from the program directory. Otherwise, you'll have to set INCLUDE= and LIB= variables ...
4,505,487
4,505,709
Linker error: already defined in my project when I don't define it at all
I am trying to build a C project in Visual C++ 2010 Express as C++ so I can create a C++/CLI .net wrapper for it. It compiles fine, but the linker tells me that swprintf(...), vswprintf(...), _swprintf_l(...), and _vswprintf(...) are already defined. The strange thing is that it says they are already defined in an .o...
you can use the preprocess-to-file option. This will tell you quickly where the function come from ! May be you're using the _tcs-versions of them ?
4,505,688
4,505,703
Compiling linux library for mingw
I have been using a socket library for C++. Some other info: 32 bit Linux, Codelite and GCC toolset. I want to be able to compile my program for Windows using the windows edition of Codelite. The socket library I have been using doesn’t have a mingw32 build of the library, but it’s open source. So how can I make a ming...
You port it to the new platform. :) You're fortunate that it is opensource, because then it would be practically impossible to port it (You'd have to pay $$$'s to get a copy of the code for a particular license, or rewrite the entire product). Enjoy. Alternatively, they may well already have a port... Check the docume...
4,505,806
9,969,887
Compiling WIN32 code with GCC
I have tried to compile some C++ WIN32 code with GCC through DevC++ (MinGW GCC). It seams that it failed to link the objects and it didn't give me a clear error message: "[PathToSource] > Error 1". Tried the same thing with Eclipse (MinGW GCC) and it compiled. However, not all of the resources show as I have an icon se...
Resource files in Eclipse: In the Build Steps of the project, there needs to be entered the command and the full path to the resource and its output file. windres ../Resources/resource_file.rc -o ../Debug/resource_file.o In the Tool Settings of the project in the linker options, the path to the resource output file ne...
4,505,861
4,505,888
Windows Messages Bizarreness
Probably just a gross oversight of some sort, but I'm not receiving any WM_SIZE messages in the message loop. However, I do receive them in the WndProc. I thought the windows loop gave messages out to WndProc? LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { switch(message) { ...
If a message is sent by the system to your window while it's in DefWindowProc or elsewhere in that netherworld that's the Windows message queue, then that message is not going to be seen by your message loop at all. Note that this is only true for sent messages. Posted messages will show up in the message loop. If you ...
4,505,917
4,511,527
Accessing array elements
I have a small problem, which I think it will be easy for you to figure out. But still I'm not a good programmer. Anyway, the problem is that I need to access the matrix element (20*2), this matrix is representing x,y locations for 20 features in image. I need to have a parameter that can give me the value of all them ...
Do you want something like this: void GetMatrixElem( float t [][2] ,int x ,int y ,float** val ) { if (val) // && (x >= 0) && (x < 20) && (y>=0) && (y<2) *val = &t[x][y]; } // ... float t [20][2]; float* pElem = NULL; GetMatrixElem( t ,10 ,1 ,&pElem ); for Columns and Rows you can use something like this:...
4,505,938
4,505,951
When/why to make function private in class?
When should i make a function private and why is it good idea?
You should make a function private when you don't need other objects or classes to access the function, when you'll be invoking it from within the class. Stick to the principle of least privilege, only allow access to variables/functions that are absolutely necessary. Anything that doesn't fit this criteria should be p...
4,506,367
4,506,436
C/C++ Is there any cross plataform way of using relative paths?
I'm programming a little game in SDL and the files are structured like this: "src/game/" have both .h and .cpp source files. "data/" have the game files like maps, tilesets, sprites and so on... to load a sprite for example I would use the following code. spriteLib.loadSprite("data/sprites/sprite-ghost.bmp"); to conve...
Few points: char converted[128]; realpath(file.c_str(),converted); First of all realpath on some operating systems (Solaris) may still return the relative path. Your code contains buffer overflow, it is better to use canonicalize_file_name or char *m=realpath(file.c_str(),0); ... free(m); - however this is Linux spec...
4,506,369
4,506,872
When and how should I use exception handling?
I am reading about exception handling. I got some information about what exception handling is, but I have a few questions: When to throw an exception? Instead of throwing an exception, can we use a return value to indicate the error? If I protect all my functions by try-catch blocks, won't it reduce the performance? ...
Here's quite comprehensive guide on exceptions that I think is a Must Read: Exceptions and error handling - C++ FAQ or C++ FAQ lite As a general rule of thumb, throw an exception when your program can identify an external problem that prevents execution. If you receive data from the server and that data is invalid, thr...
4,506,533
4,506,613
How can static functions be useful?
I don't get all these keywords. Specially this one static. An example of how important it is and how it used would be wonderful.
static member functions are just like regular functions. class Sample { public: static void DoWork() { cout << "Static Member Function"<< endl; } }; //access Sample::DoWork(); Output: Static Member Function You can treat them just like regular functions, that means, you can p...
4,506,657
4,506,771
Create a paint like work area and ability to move them
I like to design a workplace or form(not decided) in VC++ (MFC) or (C++) where I can select and place different objects like car , bike etc and move them programmatically.Each object has its own properties(which is already designed) I have no problem in moving them by changing x,y position. But my question is how do I...
Qt is an excellent framework for this kind of thing.
4,506,732
4,506,765
fopen/fclose performance
Normally, Most of the product has log file mechanism implemented. What is the best practice to write debug log file in terms of fopen / fclose performance. Does keeping file pointer open (if logger is enable) is good option or frequent open and close file pointers every time when some statement need to write into log f...
Ideally, you shouldn't close the log file until the end. Usually many products also have some "crash handling" mechanism, that would be called in any case before application terminates. This will be the best place to close the logfile. For windows, you can check SetUnhandledExceptionFilter
4,506,750
4,506,768
How do I use the Enum value from a class in another part of code?
Coming from a C# background from a night course at a local college, I've sort of started my way in C++. Having a lot pain getting used to the syntax. I'm also still very green when it comes to coding techniques. From my WinMain function, I want to be able to access a variable which is using an enum I declared in anothe...
Use core.gameMode = Core::INIT; The individual values of an enumeration are scoped not within that enumeration but at the same level as the enumeration itself. This is something that most other languages (including C#) do differently, and C++0x will allow both variants so that there, core.gameMode = Core::GAME_MODE::I...
4,506,817
4,506,912
Can I add columns in a QListView in Qt?
Can I add columns in a QListView object?? here's something I found here: model->setHeaderData( 0, Qt::Horizontal, "numéro" ); model->setHeaderData( 1, Qt::Horizontal, "prénom" ); model->setHeaderData( 2, Qt::Horizontal, "nom" ); //... model->setData( model->index( line, 0 ), contact->num(), Qt::DisplayRole ); mod...
I don't believe QListView supports multiple columns. You can use a QTreeWidget instead, it supports multiple columns.
4,506,870
4,510,392
Using macro in Objective-C to log function name and line number
I have the following simplified code example: // in .h file // define a macro for partial method #define debugWithMsg context:(CFStringRef)__FUNCTION__ lineNumber:__LINE__ debug: @interface MyLogger : NSObject { ... } - (void) context:(CFStringRef)function lineNumber:(int)line debug:(NSString*)me...
This is what I use. #define SFLog(message, ...) NSLog((@"SFLOG: %s [Line %d] " message), __PRETTY_FUNCTION__, __LINE__, ## __VA_ARGS__) You use it exactly like SFLog(@"Some var %f", myFloat); except it prepends the 'SFLog' (I also use 'SFError') and the __PRETTY_FUNCTION__ macros. [EDIT] I found the SO post where I go...
4,507,222
4,507,511
Inconsistency in Unicode with wchar_t vs. ICU in C++
While wchar_t is inconsistent in case of support on different compilers, but is it safe to assume wchar_t implementation and size are similar in GNU/GCC at least on Linux ? Despite to the fact that wchar_t size has system architecture dependency in terms of bit-size (32bit/64bit) is Wide Character Type on Linux (GNU/...
If you want to present strings to the user, you might have to take wchar_t (or some other library defined type) into consideration. Different compilers and platforms define wchar_t differently, because they use different Unicode encoding techniques. On Windows/Visual C++ for instance, wchar_t is a 16 bit type, suitable...
4,507,224
4,507,346
Need assistance with Regular Expressions in Qt (QRegExp) [bad repetition syntax?]
void MainWindow::whatever(){ QRegExp rx ("<span(.*?)>"); //QString line = ui->txtNet1->toHtml(); QString line = "<span>Bar</span><span style='baz'>foo</span>"; while(line.contains(rx)){ qDebug()<<"Found rx!"; line.remove (rx); } } I've tested the regular expression online using this...
The problem is that QRegExp only supports greedy quantifiers. More precisely, it supports either greedy or reluctant quantifiers, but not both. Thus, <span(.*?)> is invalid, since there is no *? operator. Instead, you can use QRegExp rx("<span(.*)>"); rx.setMinimal(true); This will give every *, +, and ? in the QRe...
4,507,363
4,507,841
Exception thrown by unexpected assembler code after a call to new (heap)
I am chasing an exception which is thrown from a part of code which is added by the compiler after each call to new. It's the standard C++ new, which should get some memory from the heap and call the constructor of the class. We are running VxWorks 5.5.1 with GCC 2.95 (or 2.96 not sure about that) on a SH4 processor. C...
A guess would be that this pattern is applied because it is a requirement of c++ that if the constructor throws, the memory for the object should be freed. So if an exception is thrown from within the constructor, the newly allocated object gets deleted. You could always try to explicitly throw something from the const...
4,507,401
4,507,563
Is it possible to perform arithmetic operation on void pointer with sizeof?
Is it possible to perform arithmetic operation on void pointer without the use of casting? If I have a generic function that takes a pointer of unknown type and an integer specifying the size of the type. Is it possible to perform some pointer arithmetic with just two arguments? void* Function( void* ptr, int size);
Warning - the below is probably misleading. As indicated by others in comments (special thanks to Steve Jessop) the union-based type pun below has no special guarantees in standard C++ compared with cast-based puns, and using casts to char* to do the pointer arithmetic will probably be more portable that using unions ...
4,507,565
4,507,593
Problem with copy constructor with class with polymorphic pointers
I have class with two fields witch are pointers to abstract class. How i can write copy constructor witch will copy the data pointed with the two pointers. Here is the class class OSGFMenu; class OSGFMenuItem; typedef void(OSGFMenu::*OSGFMenuCommand)(OSGFMenuItem*); typedef int (OSGFMenuItem::*FNMETHOD) ( int, char* )...
If you need to copy the exact type of the IDrawable hierarchy, I think your only chance is to add a Clone() abstract method to IDrawable interface. Its signature will be IDrawable* clone() const; you may omit const if it needs to modify the object pointed by this.
4,507,583
4,507,674
Why virtual tables are used to resolve function calls?
In the follwing as i understand the compiler validates the pointer assignment A *p_a = &b; knowing it points to derived class object. but why does it require virtual table to resolve the function call? class A { public: A():x(1){} virtual void getX() {cout << x << endl;} private: int x; }; class B : public...
In this case, the compiler could theoretically resolve that call at compile time. But what about? A* o; if (userClicksWidgetA()) o = new A(); else o = new B(); o->method(); That call can't be resolved at compile time. Or what about a separately compiled module which has a method taking an A*, but it knows nothin...
4,507,822
4,507,869
How to access variables in different class from other class?
Let just say that we have two classes, A and B. Here is code for both of them class A { public: int x; }; class B { public: int y; void FindY() { y = x + 12; } }; void something() { A fs; B fd; fs.x = 10; fd.FindY(); } the problem is that i want to access x but i don't wanna pass anythi...
Three different approaches: Make B::FindY take an A object as a parameter class B { public: void FindY(const A &a) { y = a.x + 12; } }; Make A::x static class A { public: static int x; }; class B { public: void FindY() { y = A::x + 12; } }; Make B inherit from A. class B : public A { public: void FindY() { y...
4,507,864
4,508,212
How to customize the title bar of a Qt app through Qt stylesheet?
I'm able to customize the controls of a Qt app in a Qt stylesheet. However, I couldn't find a way to customize the title bar. I found some solutions but that requires modifying the code of the app itself. Is there anyway you could customize it using just the Qt stylesheet?
Title bar isn't a part of your application or Qt and it cannot be configured with stylesheet. Title bar is provided by Window manager. In some WMs there is no title bar at all. Most WMs support customisable themes for window decoration. Usualy you can configure you WM to display specific window with specific theme. In ...
4,507,885
4,510,498
how to create drop shadows in Qt stylesheet?
My impression on drop shadows before was that, it's done with images having drop shadows already. Until I found out that you could create drop shadows using plain CSS. How do you create drop shadows though in Qt stylesheet?
For QFrame you can set the frameShadow property, but not via CSS. QGraphicsView has the QGraphicsDropShadowEffect class. In a QWebView you can use all CSS effects, but only be using CSS stylesheet in the content.
4,508,053
4,508,298
Access to derived class variable in C++?
I am trying to access a variable inside derived class. printf("%c", God.m_Please.me); Inside God class declaration I have declared m_Please as private: Please *m_Please and helpme is a variable declared in a class derived from Please class Help : public Please and me is defined as unsigned...
Please* Please is private. You cannot access a private member from a derived class. It must be protected. class Please{ protected: Please* m_Please; int pplHelped; }; class Help : public Please { void whatever(){ //assume m_Please was initialized elsewhere Please::m_Please->pplHelped; //do somethi...
4,508,095
4,508,149
How to set configuration parameters using an array table?
Following situation: I have an array with some constant values, which represent ranges. A range is always between two values in the array, e.g.: 10 - 20 = range1 20-30 = range2 and so on... const int arr[] = {10, 20, 30, 40, 50, 60}; With a Search function, I search for the number(val) between those ranges in arr[] an...
You could hold the parameters for each range in a struct: struct range_parameters { int x; int y; // etc } And keep all these structs in a std::vector: std::vector<range_parameters> params; Adding the data would be done like this: range_parameters params_for_range_1; params_for_range_1.x = 1; params_for_r...
4,508,114
4,508,293
clock() vs getsystemtime()
I developed a class for calculations on multithreads and only one instance of this class is used by a thread. Also I want to measure the duration of calculations by iterating over a container of this class from another thread. The application is win32. The thing is I have read QueryPerformanceCounter is useful when com...
QueryPerformanceCounter is fine for multithreaded applications. The processor instruction that may be used (rdtsc) can potentially provide invalid results when called on different processors. I recommend reading "Game Timing and Multicore Processors". For your specific application, the problem it appears you are trying...
4,508,181
4,508,275
thread destructors in C++0x vs boost
These days I am reading the pdf Designing MT programs . It explains that the user MUST explicitly call detach() on an object of class std::thread in C++0x before that object gets out of scope. If you don't call it std::terminate() will be called and the application will die. I usually use boost::thread for threading in...
This is indeed true, and this choice is explained in N3225 on a note regarding std::thread destructor : If joinable() then terminate(), otherwise no effects. [ Note: Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or per...
4,508,368
4,508,412
Which destructor is called when in C++?
I am hunting memory leaks in a program. I narrowed it down to some destructors not being called. However, I can't figure out why: class CMain : public CList { public: CMain(); virtual ~CMain(); ... } class CList : public CProc { public: CList(); virtual ~CList(); ... } /* some code and a main ...
Can you set a breakpoint in ~CMain to see where it goes?
4,508,371
4,508,413
problem in reading output of dd command using pipe
I am developing an application, in which I want to redirect the output (progress information) of dd command to my C++ program, but it is not actually getting the output, here is the code FILE * progressInfo = popen("gzip -dc backup/backup.img.gz | pv -ptrbe -i 2 -s 2339876653 | dd of=/dev/sdb","r"); if(!progressInfo) {...
The output is probably being written to standard error rather than standard output. Just add " 2>&1" to the very end of your command string and you should see the output (note the leading space).
4,508,423
4,508,541
What are these so-called 'disasters' that improper use of pointers can cause?
I've been using pointers more and more in my programs, and while reading up about pointers, every single guide or tutorial I found said that incorrect use of pointers could yield 'disastrous' results. Now, I've had a few cases of some big memory leaks, and pointers dereferencing a wrong pointer variable, returning an i...
Incorrect pointer arithmetic can lead to disasters too, because getting the bounds wrong leads to buffer overflows, and buffer overflows lead to corrupted data, for example stack smashing: void test_fun(int i) int x[5]; for (int *p = x; p < x+10; ++p) { // obvious error, some are more subtle *p = i; ...
4,508,533
4,508,687
What happens to base class destructor if a derived class destructor throws an exception
It just happened to me I wondered how resources are freed in the following case. class Base { Resource *r; public: Base() { /* ... */ } ~Base() { delete r; } }; class Derived : public Base { public: Derived() { /* ... */ } ~Derived() { /* Suddenly something here throws! */ } }; int main() { ...
According to §15.2/2: An object that is partially constructed or partially destroyed will have destructors executed for all of its fully constructed subobjects, that is, for subobjects for which the constructor has completed execution and the destructor has not yet begun execution. So the base class destructor should...
4,508,600
4,508,645
Detecting if computer is idle based on mouse and keyboard interactions
I'm am writing a piece of software in C++ that controls the keyboard backlight on my MacBook Pro which runs Arch Linux as main OS and Debian for funzies. The program runs as a daemon and is as of now able to turn the keyboard backlight on. Next step is to make it keep an eye on when the computer is idle (based on mouse...
The XScreensaver extension in the X server tracks keyboard and mouse idle time. If you download the source code to Psi, their source tree has a file idle_x11.cpp that contains logic to query the idle time. Use that as an example. The basic idea is to use XScreenSaverQueryInfo to read the screen saver status info.
4,508,635
4,508,660
How can I use namespaces across files in C++?
I have 2 .cpp files a1.cpp #include <iostream> #include <conio.h> using namespace std; using namespace te; int main(int argc, char ** argv) { A a1(5); cout<<a1.display(); return 0; } a2.cpp #include <iostream> namespace te { class A{ int i; public: A(int a) {i = a;} ...
Yes, you require a2.h. Add namespace te{ class A { public: A(int a); int display();};} in the header file and include the header file from a1.cpp
4,508,911
4,509,001
Convert uint8_t* to std::string in C++?
Possible Duplicate: How to Convert Byte* to std::string in C++? I'm on an embedded device and try to receive a message. This message is given by a const uint8_t* data and its length size_t len. Now I need a std::string to output my data.
If you don't want to convert the encoding, this will work: std::string s( data, data+len ); If you want to convert UTF-8 into whatever system encoding is used by your platform, you need to use some platform-specific means.
4,509,062
4,509,279
boost::program_options - how to handle multiple sections with the same name in INI file
In a config like below; is there a way to handle individual sections. I am looking for a way to validate individual "server" sections below, in a reliable manner. [basic] number_of_servers=3 [server] ip=10.20.30.40 password=sdfslkhf [server] ip=10.20.30.41 password=sdfslkhf [server] ip=10.20.30.42 password=sdfsl...
When using boost::program_options to parse a INI file, the option names must be prefixed by their enclosing section names. In other words, sections are part of the option 'identifier', but I don't think you have a way to identify to which section a given server.ip variable belongs (and thus, which is the associated ser...
4,509,570
4,509,605
recv receiving not whole data sometime
I have following issue: here is the chunk of code: void get_all_buf(int sock, std::string & inStr) { int n = 1; char c; char temp[1024*1024]; bzero(temp, sizeof(temp)); n = recv(sock, temp, sizeof(temp), 0); inStr = temp; }; but sometimes recv returning not whole data (data length always le...
The TCP standard allows for fragmentation of data packets. In practice this doesn't happen with small data packets of a few hundred bytes or so, but a megabyte of data is almost certain to get fragmented. Secondly, when you say the sniffer says all the data gets sent, in one packet or in many? Good network programming ...
4,509,730
4,509,792
Class Assignment Operators
I made the following operator overloading test: #include <iostream> #include <string> using namespace std; class TestClass { string ClassName; public: TestClass(string Name) { ClassName = Name; cout << ClassName << " constructed." << endl; } ~TestClass() { cout <...
The code you've shown would do it. No one would consider it to be a particularly good implementation, though. This conforms to what is expected of an assignment operator: TestClass& operator=(TestClass other) { using std::swap; swap(ClassName, other.ClassName); // repeat for other member variables; ret...
4,509,798
4,509,848
Finding nearest point in an efficient way
I've got a point in 2d plane for example (x0,y0) and a set of n points (x1,y1)...(xn,yn) and I want to find nearest point to (x0,y0) in a way better than trying all points. Any solutions? I should also say that my points are sorted in this way: bool less(point a,point b){ if(a.x!=b.x) return a.x<b.x; else ...
Use a quad-tree for 2D http://en.wikipedia.org/wiki/Quadtree
4,509,811
4,509,857
How to build an accurate translation engine?
I found a formula few months ago, myself to translate any source language (computer characters) to destination (computer characters). Using Lua (desk top users) and C++ class (for native access) so that i can embed it in Web Browser etc etc. I am wondering if we have already better something for this in C++ or Lua. Min...
Did you take a look at Google Translator Toolkit API? By analyzing its aspects you can have a glimpse of what it implements and what you may need to develop your own translation framework (a lot of work by the way). Creating/Uploading translation documents Full list of supported source and target languages http://www....
4,509,850
4,509,871
static member function and thread-safety
In C++, when you have local variables in a static member function, does it mean those local variables are also implicitly static or are they really local? example: static void myClass::somefunc(int someint) { int myint = someint; // is myint really a local variable or does it change due to the static qualifier at fun...
They are local unless you declare them static - each invokation of the function will have its own copy of the variable and you don't need to to protect them.
4,509,908
4,509,929
What exactly does the syntax ::~ mean in newly added class in C++ Visual Studio 2010
I have s simple question: Situation: When I rightclick Source Files folder and select Add->Class - C++ class , a class is added in a separate file *.cpp and *.h (great! This is exactly what I wanted). Now: what does the function name classname::~classname(void) exactly does ? Is it a destructor of that class called "...
There are two different things at work here: The namespace delimiter operator, :: The destructor, which is a special function that’s always called ~classname. In your case, the syntax classname::~classname(void) simply defines the class’ destructor. The :: means that what follows belongs to the class called classname...
4,510,109
4,510,214
Macro-based selection of C++ headers
I am currently writing a C++ library which will be required to compile with both GCC for linux and Sun CC for Solaris. In the interest of performance I am creating some classes which select different headers based on compiler; GCC with c++0x or TR1 or with niether and Sun CC RogueWave or STLPort. I'm sturggling to work...
This won't work for two reasons: Headers must be included outside of the scope of namespace project { ... }. (If the header contains nothing but templates and inline functions, it might work anyway, but I wouldn't count on it.) typedef doesn't work on templates. There's a workaround where you define an empty derived c...
4,510,190
5,017,515
IO Completion Ports vs. Thread Pool API
I had a problem described here, and I was suggested to use IO completion ports or thread pool. I have implemented IO completion, calling PostQueuedCompletionStatus to enqueue the task and GetQueuedCompletionStatus to get the next task to execute it. I am using IO completion port as a multi-producer/multi-consumer thre...
Completion Ports are designed to avoid unnecessary context switching. When your thread that is calling GetQueuedCompletionStatus is done processing a work item, it can call right back to GetQueuedCompletionStatus to continue to get more work within its current CPU timeslice. @Jonathan - If you have blocking calls, then...
4,510,288
4,510,326
Working with huge quantity of float matrices
Ok I'm actually working with in-memory storage of huge quantities of float matrices. These matrices stores statistics data and most of the time, just a few cells contain non-null value. Lets consider this simple problem. An item collects statistics over time. These statistics are stored in single-line format matrix of ...
Maybe SparseLib++ could be something you're interested in. Take a look and see if it suits your needs: http://math.nist.gov/sparselib++/ SparseLib++ is a C++ class library for efficient sparse matrix computations across various computational platforms.
4,510,312
4,510,545
Introducing smart pointers into a legacy project
I'm changing some legacy code so that is uses smart pointers. Our projects pre-date boost and so we have an existing intrusive smart pointer class (see below for API). I want to remove explicit calls to delete for these types, so what is the best way to find them? For example: class A : public RefCount // RefCount adde...
Get rid of operator void const * () const; in your smart pointer class and that should do it. Implicit conversions from smart pointer to raw pointer generally hide so many problems it's not worth implementing. Even with the conversion operator I still got a warning in g++ with the code as posted.
4,510,495
4,512,609
Can't display modal QProgressDialog in MFC application
I'm having problems displaying a modal Qt dialog while starting up a Qt application from an MFC application. Specifically, a QProgressDialog instance won't display within the MFC application when I set its parent to a QWinWidget instance. Here's my problem in more detail... My MFC application needs to transfer a lot o...
Gotcha! The problem was caused by the call to SetParent(). I needed to instead create the QWinWidget before the QProgressDialog and pass the QWinWidget instance in to the QProgressDialog's constructor as its parent. As the help says, QWidget::setParent resets the window flags, so the dialog was no longer being recognis...
4,510,534
4,511,048
how to find if the process is suspended or not?
i am using this code for suspend process.i found it here http://www.codeproject.com/KB/threads/pausep.aspx BOOL SuspendResumeThreadList(DWORD dwOwnerPID, bool bResumeThread) { HANDLE hThreadSnap = NULL; BOOL bRet = FALSE; THREADENTRY32 te32 = {0}; hThreadSnap = Create...
If I remember correct you can use NtQuerySystemInformation for this purpose. With NtQuerySystemInformation you can get SYSTEM_PROCESS_INFORMATION structure by iterating over array of SYSTEM_PROCESS_INFORMATION and looking for the PID of the target process. You can find detailed description of SYSTEM_PROCESS_INFORMATION...
4,510,672
4,510,746
Why is the this-pointer needed to access inherited attributes?
assume the following class is given: class Base{ public: Base() {} Base( const Base& b) : base_attr(b.base_attr) {} void someBaseFunction() { .... } protected: SomeType base_attr; }; When I want a class to inherit from this one and include a new attribute for the derived class, I would write: class Derived: public...
You are only seeing this if Base in some way depends on template arguments. In that case, it's deemed too dangerous that a name like base_attr is lookup up in such a dependent base class: For some template instantiation, the name could be found in the base class, and for another instantiation, the member could be abse...
4,510,683
4,510,841
Sharing files across applications
We have a common functionality we need to share among several applications. We already have a few internal libraries, into which we put common code with a well-defined interface. Sometimes, though, there are problems with some code (typically a single or a few .cpp files) as it doesn't fit into an existing library and ...
Why don't you just create a folder in SVN called "Shared" and put your shared files into that? You can include the shared files into your projects from there. Update: Seems like you are looking for a 3rd party tool that tracks dependencies. Subversion and dependencies
4,510,791
4,510,868
"Using" directive fails within template
I understand that the member names of a base-class template are hidden within the scope of a derived class, and therefore must be accessed using this->foo or Base<T>::foo. However, I recall that C++ also allows you to use the using keyword, which can come in handy in a derived-class function which frequently accesses ...
It doesn't work because C++ language has no such feature and never had. A using-declaration for a class member must be a member declaration. This means that you can only use in class scope, but never in local scope. This all has absolutely nothing to do with templates. In other words, you can place your using-declarati...
4,511,005
4,511,026
Overloading operator []
Let's say I have a container class called MyContainerClass that holds integers. The [] operator, as you know, can be overloaded so the user can more intuitively access values as if the container were a regular array. For example: MyContainerClass MyInstance; // ... int ValueAtIndex = MyInstance[3]; // Gets the value a...
The obvious return type is int& :) For increased elaboration: int &operator[](ptrdiff_t i) { return myarray[i]; } int const& operator[](ptrdiff_t i) const { return myarray[i]; } // ^ could be "int" too. Doesn't matter for a simple type as "int".
4,511,107
4,518,649
Why do I get a numeric::ublas::bad_index error when iterating on the elements of a sparse matrix?
I am using the Boost library, version 1.44.0 and c++ with gcc 4.0. I have created a ublas::compressed_matrix<double> and I have filled it using the method insert_element(index1, index2, value). Thereafter I am iterating through the elements of the matrix and printing out the non-zero elements. I use the following code ...
I have found what the problem was, and of course it was my mistake on the code. In fact the inner loop (i.e. the second for loop) iterates through the wrong thing. Originally I wrote: for (i2_t i2 = matrix->begin2(); i2 != matrix->end2(); i2++) However, i2 should not iterate from matrx->begin2() to matrix->end2(). Ins...
4,511,250
4,514,305
Comparing two arrays
I've two arrays, say A = {1,2,3,4,5} and B = {5,6,3,4,5}. I want to compare the two arrays and tell how many elements in A are lesser than B and vice versa and also possibly the elements position which are lesser. I can do this using nested loop but is there a efficient way in C++ to do this ? In this example, A = {1,2...
Do you want to compare corresponding elements of A and B and count how many A' are less than the matching B's? This can be done with std::inner_product like this: int A[] = { 1,2,3,4,5 }; int B[] = { 5,6,3,4,5 }; int count = std::inner_product(A, A+5, B, 0, std::plus<int>(), std::less<int>()); std::cout << count << "...
4,511,350
4,511,424
C++ <map> vs <unordered_map> vs <tr1/unordered_map> vs <ext/unordered_map>
I'm currently looking for a better alternative to std::map and have come across classes mentioned in the post title. Could someone clarify the differences between them, not in terms of performance/API, but in terms of where they beleong in relation to the current and forthcomnig standard.
std::map : the current C++ standard associative container (key/value), that works as a tree behind; std::unordered_map : the next standard(C++0x -- or in the Technical Report 1) hash-map container, that works as an... hash map. std::tr1::unordered_map : the same as the previous one but in the tr1 namespace, often foun...
4,511,555
4,511,640
typedef variable inside same class. Is it a good practice?
Initially I was trying to typedef a template class and I got to the "gotw 79" article. And I didn't want to create another class so I ended up doing the following. Basically typedef'ing inside the same class. It works obviously. but is it a good practice? template <typename T,typename L> class MyClass{ typedef std...
Well, I'm not a big fan of it unless you are designing MyClass to be specifically used only within shared_ptr objects, at which point I would insist that requirement be enforced. It's a little ridiculous to put typedefs for every unrelated template instantiation that you might use with a given object. Just because you...
4,511,683
4,511,825
Copy Constructor question
I'm trying to understand this copy constructor problem. The question I have pertains to the destructor after the program exits. It seems the variable char* title is not destructed and I think this maybe wrong, thanks Another question is why the assignment operator isn't called when the object x is equal to x2. I'm usin...
You have a variety of problems that I was able to see, both in your actual code and in your general approach. First of all, the char* title isn't deleted because you don't delete it. This is probably a logical error: if (p) { cout<<"deleting p"<<endl; delete p; } else if(title) { ...
4,511,733
4,511,839
Cannot access vector when constructing with istream_iterator range
I tried to compile this code snippet but I got compiler error :( ! Compile with Visual Studio 2010 #include <vector> #include <string> #include <sstream> #include <iterator> #include <iostream> using namespace std; int main() { string s( "Well well on" ); istringstream in( s ); vector<string> v( istream_...
I think this vector<string> v( istream_iterator<string>( in ), istream_iterator<string>() ); is parsed as a function declaration: vector<string> v( istream_iterator<string> in, istream_iterator<string> ); This is usually called "C++' most-vexing parse". I think a few extra parentheses will cure this: vector<strin...
4,511,767
4,519,817
Qt "Creating SSL context" error in few computers
I have this "Error creating SSL context" in a C++ application based on Qt. I've put these DLL in the application directory and in "C:\Windows\system32": - libeay32.dll - libssl32.dll - ssleay32.dll But still have the problem. It's weird because the application still works on allmost all the systems. Idee...
All computers need to install the Microsoft Visual C++ 2008 SP1 Redistributable Package (Download here). After installation, all works!
4,511,772
4,511,806
What software options are available for prototyping and creating C++ or C# desktop app GUIs?
I am looking for a program that will allow me to easily create GUIs for desktop applications written in C++ or C#. This software will allow me to : import image files or Photoshop files add animated effects that will be triggered by mouse events like: fade in/out slide scale hue change test my prototype GUI via a t...
if your looking for something to create really graphical interfaces, check out WPF and using Microsoft Expression Blend. http://www.microsoft.com/expression/products/Blend_Overview.aspx http://msdn.microsoft.com/en-us/library/ms754130.aspx
4,511,812
4,512,170
segmentation fault produced by tests running under CppUnit
Today I found that one of my tests is using some code/library that segfaults. I work in Linux environment in C++ and CppUnit. Is there any feature of function in CppUnit to test against segfault and report it as failure for the specific test case? In CppUnit I can even test against exceptions, but I think that what I...
A seg fault will result in a non-zero exit status from your test (On Solaris I believe it's 139). Are you able to test this from whatever method is being used to call your unit test?
4,511,925
4,512,154
Specializing a template class
I just created a template class template< typename T > class LinkedList { private: struct LinkedListElement { T *m_data; LinkedListElement *m_next; }; LinkedListElement *head; public: void insert(T *elem); void remove(T *elem); T *find(const char *name); }; and I want to custom...
For this case, you can specialize the member function only template<> inline MyType *LinkedList<MyType>::find(const char *name) { /* ... */ }
4,512,109
4,512,599
how to develop plug-in based application?
How to design(architecture) & write an application,in which plug-in can be released later. Can any one give some suggestion on the concepts that i have to concentrate to make the product more reliable & can be upgradable very easily? using QT & c++....
If you're using Qt, you may find its support for plugins useful. http://qt-project.org/doc/qt-5.0/qtcore/plugins-howto.html http://qt-project.org/doc/qt-5.0/qtcore/qpluginloader.html That said, this is nowhere near what you get with the Eclipse RCP framework. If your plug-ins are released on a different schedule than...
4,512,269
4,512,494
How to tokenize strings using std::regex library in Visual Studio 2010?
I could not find the reference of std::regex library. I did some google searches and found some tutorials, but they're all brief and short. I couldn't figure out how to tokenize a string using regex. Could anyone give me a hint how to start?
I think an example from boost::regex site could solve my problem ;) /* * * Copyright (c) 12003 * John Maddock * * Use, modification and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * */ /* ...
4,512,613
4,512,646
Can I use windows event log to debug an application?
My application crashes and generates a windows event log that says: Faulting application someapp.exe, version 1.0.0.0, faulting module TAOd.dll, version 1.6.9.0, fault address 0x0000f8286. Is there a way to map this address to a method call? I don't have debug information. The app is running on a production mac...
Yes there is a way. Generate a map file and look up the function. Edit: Try http://www.codeproject.com/KB/debug/mapfile.aspx
4,512,631
4,512,653
Difference between "endl" and "\n"
Possible Duplicate: C++: “std::endl” vs “\n” I'm wondering if there is any significant difference between these two ways to print newline : cout << endl; //approach1 cout << "\n"; //approach2 Is there any practical difference?
Yes, they're different. "\n" is just a string of length 1 that gets appended to stdout. std::endl, instead, is an object that will cause to append the newline character ("\n") AND to flush stdout buffer. For this reason it will take more processing.
4,512,669
4,512,864
Vertex Shader Input Order
Does input order for a SM 4.0 vertex shader matter? e.g. is struct App2VS { float3 position : POSITION; float4 color : COLOR0; float3 normal : NORMAL; ... }; equivalent to struct App2VS { float4 color : COLOR0; float3 position : POSITION; float3 normal : NORMAL; ... };
No it shouldn't matter. The mapping information is performed by the Input Layout. Essentially the input layout maps a given struct element to a specific input "register". These input registers are then used to load the struct used by HLSL. The HLSL struct is not a real memory mapping as those input register (ie POSI...
4,512,757
4,512,891
type mapping by templates
I'm looking for a way to map types, f.i. having a class Double: class Double { public: typedef double basic_type; ... }; I'd like to be able to have a type caster so that typeid(TypeToObjectType<double>::type) == typeid(Double) Any ideas how to accomplish this (through partial specializations etc.) ?
You can achieve this through specialization : template<class T> struct TypeToObjectType; template<> struct TypeToObjectType<double> { typedef Double type; }; Note that you have to provide a specialization for each of the types on which you want TypeToObjectType to work. Macros can be helpful here : #define SPECIA...
4,512,802
5,087,962
Permutations of a List of Types Using boost::mpl
I am trying to create a list containing the permutations of a given type list. The below code seems to function, though without the intended result, when I use a specified list instead of generating a new list by removing from the actual input. This is demonstrated by the difference between permutation_helper and brok...
mpl::remove works correctly. The problem is with your template for permutations of singleton lists: it catches only types that are mpl::lists, while the result of remove has another sequence type. With other words, the result of mpl::remove is mpl::equal to the singleton list, but not std::is_same: #include <boost/mpl/...
4,512,834
4,513,190
Object Factory with Properties Questions?
This is just a general question. As I understand it an object factory is just a place where your program can make and destroy predefined objects. I also understand it that this makes scripting and networking easier. What is the pattern where I can say give me an object with this feature and that feature? Is that such a...
So you know that you need a spaceship. This spaceship will have different gadgets attached to it, so you may want something like that: class Spaceship { public: void add(Gadget*); }; maybe there will be different ship, so Spaceship will be the base class for the hierarchy. For example, you'll have scout ships, war...
4,513,350
4,513,422
How static local POD constants are initialized? Lazily or not?
POD means primitive data type without constructor and destructor. I am curious, how compilers handle lazy initialization of POD static local variables. What is the implication of lazy initialization if the function are meant to be run inside tight loops in multithreaded applications? These are the possible choices. Whi...
When a static variable is initialized with constant data, all compilers that I'm familiar with will initialize the values at compile time so that there is no run time overhead whatsoever. If the variable isn't static it must be allocated on each function invocation, and the values must be copied into it. I suppose it's...
4,513,696
4,513,721
inheriting vectors and initialization
Am trying to inherit a class from a C++ vector and initialize it at the constructor. How do I do it? For example: class Dataset:public std::vector<float>{ public: Dataset(vector<float> val):*baseclass*(val){} // bruteforce way. // Dataset(vector<float> val){//for every val[i] call push_back(...
Don't derive from std::vector<>. This class was never meant to be derived from. Use an instance of the class as a member instead: struct Owns { Owns() : the_vector_(42, 128) { } private: std::vector<float> the_vector_; };