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,938,966
2,945,619
How to use VC++ intrinsic functions w/o run-time library
I'm involved in one of those challenges where you try to produce the smallest possible binary, so I'm building my program without the C or C++ run-time libraries (RTL). I don't link to the DLL version or the static version. I don't even #include the header files. I have this working fine. Some RTL functions, like me...
I think I finally found a solution: First, in a header file, declare memset() with a pragma, like so: extern "C" void * __cdecl memset(void *, int, size_t); #pragma intrinsic(memset) That allows your code to call memset(). In most cases, the compiler will inline the intrinsic version. Second, in a separate implementa...
2,939,106
3,921,654
Is there something like a Filestorage class to store files in?
Is there something like a class that might be used to store Files and directories in, just like the way Zip files might be used? Since I haven't found any "real" class to write Zip files (real class as in real class), It would be nice to be able to store Files and Directories in a container-like file. A perfect API wou...
I took the time to write a tiny, yet working wrapper around libarchive. I'm not exactly familiar with all features of Libarchive, but the result fits what I needed: archive_wrapper.cpp @ gist.github.com It uses libmars for strings, etc. But I guess it wouldn't be too hard to replace the mars::mstring occurances with st...
2,939,165
2,939,692
C++ get method - returning by value or by reference
I've go a very simple question, but unfortunately I can't figure the answer myself. Suppose I've got some data structure that holds settings and acts like a settings map. I have a GetValue(const std::string& name) method, that returns the corresponding value. Now I'm trying to figure out - what kind of return-value app...
Actually I would probably use: std::string GetValue(const std::string& name) const; // or const std::string* GetValue(const std::string& name) const; void SetValue(std::string name, std::string value); Setter first: Passing by value in SetValue allows the compiler some optimizations that cannot be made with pass by ...
2,939,286
2,939,292
error C2440: '=' : cannot convert from 'bool' to 'bool *'
I'm getting said error on this line "b = true". Now Why am I getting this error? Aren't I pointing to TurnMeOn and thus saying TurnMeOn = true? class B{ void turnOn(bool *b){b = true} }; int main(){ B *b = new B(); bool turnMeOn = false; b->turnOn(&turnMeOn); cout << "b = " << turnMeOn << endl; }
b->turnOn(&turnMeOn); and *b = true;
2,939,367
2,939,432
Static variables within functions in C++ - allocated even if function doesn't run?
I've been reading up on C++ on the Internet, and here's one thing that I haven't been quite able to find an answer to. I know that static variables used within functions are akin to globals, and that subsequent invocations of that function will have the static variable retain its value between calls. However, if the fu...
If the function is never called, it is likely that your linker will deadstrip both the function and the static variable, preventing it from entering .rodata, .data, or .bss segments (or your executable file format's equivalents). However, there are various reasons why a linker might not deadstrip (flags telling it not ...
2,939,550
2,939,564
Does a static object within a function introduce a potential race condition?
I'm curious about the following code: class MyClass { public: MyClass() : _myArray(new int[1024]) {} ~MyClass() {delete [] _myArray;} private: int * _myArray; }; // This function may be called by different threads in an unsynchronized manner void MyFunction() { static const MyClass _myClassObject; [......
There's absolutely a possible race condition there. Whether or not there actually is one is pretty damn undefined. You shouldn't use such code in single-threaded scenarios because it's bad design, but it could be the death of your app in multithreaded. Anything that is static const like that should probably go in a con...
2,939,860
2,939,905
need a virtual template member workaround
I need to write a program implementing the visitor design pattern. The problem is that the base visitor class is a template class. This means that BaseVisited::accept() takes a template class as a parameter and since it uses 'this' and i need 'this' to point to the correct runtime instance of the object, it also needs ...
What you should do is separate the BaseVisitor. class BaseVisited; class BaseVisitorInternal { public: virtual void visit(BaseVisited*) = 0; virtual ~BaseVisitorInternal() {} }; class BaseVisited { BaseVisited(); virtual void accept(BaseVisitorInternal* visitor) { visitor->visit(this); } }; template<typ...
2,939,870
3,006,459
How to capture any key in X?
I am building an application for which I need to periodically get information about users keyboard. It is going to be user idle detection application. I have a fairly simple solution to periodically check if the mouse has been moved. But I can't figure any reasonable non root way to detect if the keyboard has been pres...
After a lot of searching I found this: bool kbdActivity(Display* display) // checks for key presses { XQueryKeymap(display, keymap); // asks x server for current keymap for (int i=0; i<32; i++) // for 0 to 32 (keymap size) { if (prevKeymap[i] != keymap[i]) // if previous keymap does not ...
2,940,106
2,940,129
Simple Reliable UDP C++ Libraries
I am in need of a reliable UDP library. The one I wrote does not work too well and I would like to see what a 3rd party can do in the same circumstances. Enet will not work because of some "interesting" compile issues in xcode (I have another question on stack overflow about that). Any suggestions for a portable, reli...
Try boost::asio or ACE. I would recommend the former over the latter.
2,940,285
2,940,315
std::map insert segmentation fault
Why does this code stop with segmentation fault : class MapFile { public: /* ... */ std::map <unsigned int, unsigned int> inToOut; }; bool MapFile::LoadMapFile( const wxString& fileName ) { /* ... */ inToOut.insert( std::make_pair(input,output) ); } but when I put the "std::map inToOut;" just before "i...
I guess your problem is somewhere else. The following code works ok: class MapFile { public: std::map <unsigned int, unsigned int> inToOut; void LoadMapFile(); }; void MapFile::LoadMapFile() { inToOut.insert( std::make_pair(1, 1) ); } int main() { MapFile a; a.LoadMapFile(); return 0; } Try step-b...
2,940,371
2,940,533
Parallel port with C#
I am trying to send data to LPT1 port with a C# program, unfortunately with no success.. I am using windows 7 x64. I tried both x86 and x64 (inpoutx64.dll) dll's.. With the x64 dll when I send: Output(888, 255); It just continues the program as everything went ok, but i can't see anything on my multimeter (only the st...
An IO port in the sense used by _outp isn't the same as what you're trying to do with a parallel port. An IO port is a processor-level way to get raw access to different devices. The use of IO ports with _outp is supposed to be the kind of thing device drivers do. It is therefore privileged (i.e. kernel only) in any ve...
2,940,379
2,940,881
get metadata from jpg, dng and arw raw files
I was wondering if anyone new how to get access the metadata (the date in particular) from jpg, arw and dng files. I've recently lost the folder structure after a merge operation gone-bad and would like to rename the recovered files according to the metadata. I'm planning on creating a little C++ app to dig into each f...
ok, so I did a google search (probably should have started with that) for "batch rename based on exif data arw dng jpg" and the first page that popped up was the ExifTool by Phil Harvey it supports recent arw and dng files, and with some command line magic I should be able to get it to do what pretty much what I want e...
2,940,392
2,940,441
QGraphicsItem doesn't receive mouse hover events
I have a class derived from QGraphicsView, which contains QGraphicsItem-derived elements. I want these elements to change color whenever the mouse cursor hovers over them, so I implemented hoverEnterEvent (and hoverLeaveEvent): void MyGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent* event) { update (boundin...
Fixed it. I need to use setAcceptHoverEvents(true) in the constructor of my QGraphicsItem-derived class.
2,940,402
2,940,446
Templated derived class in CRTP (Curiously Recurring Template Pattern)
I have a use of the CRTP that doesn't compile with g++ 4.2.1, perhaps because the derived class is itself a template? Does anyone know why this doesn't work or, better yet, how to make it work? Sample code and the compiler error are below. Source: foo.C #include <iostream> using namespace std; template<typename X, ty...
The idea of CRTP is to have a base class that knows of what type its derivative is - not to let the base class derive from its derivative. Otherwise you'd have the following situation: Derived derives from Base<Derived>, which derives from Derived, which derives from Base<Derived>, which ... Use the following instead...
2,940,447
2,940,455
what functions are called when passing value to function
In C++, if an object of a class is passed as a parameter into a function, the copy constructor of the class will be called. I was wondering if the object is of nonclass type, what function will be called? Similarly in C, what function is called when passing values or address of variables into a function? Thanks and reg...
No function will be called; the bytes composing the object will simply be copied to the correct place for the callee (be that a location in memory or a register).
2,940,596
2,940,600
Must parameter of assignment operator be reference?
When overloading assignment operator of a class in C++, must its parameter be reference? For example, class MyClass { public: ... MyClass & operator=(const MyClass &rhs); ... } Can it be class MyClass { public: ... MyClass & operator=(const MyClass rhs); ... } ? Thanks!
The parameter of an overloaded assignment operator can be any type and it can be passed by reference or by value (well, if the type is not copy constructible, then it can't be passed by value, obviously). So, for example, you could have an assignment operator that takes an int as a parameter: MyClass& operator=(int); ...
2,940,660
2,940,666
How to treat RAM data as if it was a real file?
So I have some temp data in my program (in RAM). I want to somehow make it seem as it is a file (for example for sending it into another program which takes a file link as argument)? Is it possible? How to do such thing?
You can do it in C using the popen() function: FILE *f = popen("program args", "w"); // write your output to f here using stdio pclose(f); This is possible if your external program reads its input from stdin.
2,940,682
3,033,352
Problem with cvCreateVideoWriter in OpenCv. Again )
I know, that the issue had been widely discussed before, but after 5 hours of inefficient googling I guess I deserve to ask :) By the way, all such problems concerned earlier versions of OpenCV, so.. I've compiled fresh OpenCV 2.1. from source under Ubuntu 9.10. It works fine except of cvCreateVideoWriter, which retu...
I recompiled OpenCV and ffmpeg from source again and it seems to work fine right now.
2,940,686
2,940,781
Using custom Qt subclasses in Python
First off: I'm new to both Qt and SWIG. Currently reading documentation for both of these, but this is a time consuming task, so I'm looking for some spoilers. It's good to know up-front whether something just won't work. I'm attempting to formulate a modular architecture for some in-house software. The core component...
PyQt exposes C++ code to Python via SIP; PySide does so via Shiboken. Both have roughly the same capabilities as SWIG (except that they only support "extended C++ to Python", while SWIG has back-ends for Ruby, Perl, Java, and so forth as well). Neither SWIG nor SIP and Shiboken are designed to interoperate with each ...
2,940,748
3,784,821
How to determine if std::chrono::monotonic_clock is available?
C++0x N3092 states that monotonic_clock is optional: 20.10.5.2 Class monotonic_clock [time.clock.monotonic] Objects of class monotonic_clock represent clocks for which values of time_point never decrease as physical time advances. monotonic_clock may be a synonym for system_clock if system_clock::is_monotonic is true...
There is no fully-standards-conforming way to detect the presence of std::chrono::monotonic_clock. As was apparent from the discussions on comp.std.c++, there are some non-standard-conforming techniques involving declaring new code in namespace std.
2,940,924
2,940,952
Why do structures need to be told how big they are?
I've noticed that in c/c++ a lot of Win32 API structs need to be told how big they are. i.e someStruct.pbFormat = sizeof(SomeStruct) Why is this the case? Is it just for legacy reasons? Also any idea what "pb" stands for too? EDIT: oops, yeah I meant "cbFormat"
This is for backward compatibility when Windows API is extended. Imagine the following declarations struct WinData { long flags; } BOOL GetWinData(WinData * wd); which you are calling like this: WinData wd; GetWinData(&wd); A future OS version may extend this to struct WinData { long flags; long extraData; ...
2,941,100
2,941,139
Writing a managed wrapper for unmanaged (C++) code - custom types/structs
faacEncConfigurationPtr FAACAPI faacEncGetCurrentConfiguration( faacEncHandle hEncoder); I'm trying to come up with a simple wrapper for this C++ library; I've never done more than very simple p/invoke interop before - like one function call with primitive arguments. So, given the above C++ function, for exampl...
Your are on the right track with how you would need to create managed structures that represent unamanged structures for use with P/Invoke. It is however not the best strategy for interop with unmanaged libraries, because using this API from C# would still feel like using a C API - create and initialise a structure, pa...
2,941,131
2,941,140
Why is this c++ string concatenation missing a space?
I am working with c++ strings, and am a beginner at programming. I am expecting: 99 Red Balloons But I am receiving: 99 RedBalloons Why is that? #include <string> #include <iostream> using namespace std; int main() { string text = "9"; string term( "9 "); string info = "Toys"; string color; char h...
Your definition of hue does not include any spaces. (The \0 is how C++ knows where the end of the string is, this is not a space.) Note that term in your code does have a trailing space. To fix it, change hue to: char hue[5] = {'R','e','d',' ','\0'}; Or, include a space in your addition, when you construct the final...
2,941,260
2,941,263
What does (void**) mean in C?
I would look this up, but honestly I wouldn't know where to start because I don't know what it is called. I've seen variables passed to functions like this: myFunction((void**)&variable); Which confuses the heck out of me cause all of those look familiar to me; I've just never seen them put together like that before. ...
It's a cast to a pointer to a void pointer. You see this quite often with functions like CoCreateInstance() on Windows systems. ISomeInterface* ifaceptr = 0; HRESULT hr = ::CoCreateInstance(CLSID_SomeImplementation, NULL, CLSCTX_ALL, IID_ISomeInterface, (void**)&ifaceptr); if(SUCCEEDED(hr)) { ifaceptr->DoSometh...
2,941,363
2,955,734
Monitoring GPS Coordinates
I need to monitor GPS Coordinates changes at every 15 min and take action based on that. as per bada developer guide report "only one application allowed to run at a time if another application try to run first one is closed" .so that how do i monitor GPS coordinates without interruption from other applications. how ...
I came to understand that Agent application functionality still not implemented for 3rd party applications, it is reserved for internal use only. And there is no daemon like application functionalities. We can use multitasking inside user application but not multiple user applications due to single application policy...
2,941,368
2,941,414
sorting names in a linked list
I'm trying to sort names into alphabetical order inside a linked list but am getting a run time error. what have I done wrong here? #include <iostream> #include <string> using namespace std; struct node{ string name; node *next; }; node *A; void addnode(node *&listpointer,string newname){ node *temp; ...
I believe the mistake is that you think: if (listpointer == NULL){ temp->name = newname; temp->next = listpointer; listpointer = temp; } guarantees that listpointer won't ever be NULL later. However this isn't the case, for example: void addnode(node *&listpointer,string newname){ node *temp; temp =...
2,941,488
3,259,968
Memory leaks getting sub-images from video (cvGetSubRect)
i'm trying to do video windowing that is: show all frames from a video and also some sub-image from each frame. This sub-image can change size and be taken from a different position of the original frame. So , the code i've written does basically this: cvQueryFrame to get a new image from the video Create a new IplIm...
Someone report the same problem as a bug in the library. http://sourceforge.net/tracker/index.php?func=detail&aid=3025393&group_id=22870&atid=376677 I solved it by using ROI in the image instead of cvGetSubRect, that way you avoid to alloc another mat.
2,941,491
2,941,508
Compare versions as strings
Comparing version numbers as strings is not so easy... "1.0.0.9" > "1.0.0.10", but it's not correct. The obvious way to do it properly is to parse these strings, convert to numbers and compare as numbers. Is there another way to do it more "elegantly"? For example, boost::string_algo...
I don't see what could be more elegant than just parsing -- but please make use of standard library facilities already in place. Assuming you don't need error checking: void Parse(int result[4], const std::string& input) { std::istringstream parser(input); parser >> result[0]; for(int idx = 1; idx < 4; idx+...
2,941,496
2,941,592
specify parent window in Windows Resource Script file(*.rc)
I'm looking for a method to specify parent window in *.rc file. In *.rc file, it contains the layout and controls of a dialog. Any new control added into it, will automatically become a child window of Dialog itself. But I want to add a custom draw window into dialog, and some other controls which has that "custom dra...
It is not possible to specify a parent window for the controls defined in the resource file. All controls in the resource file have the dialog set as the parent when the dialog is created. You can try rolling out your own dialog manager - Raymond Chen has a 9-part series of blog posts on it (Part 1, Part 2, Part 3, Par...
2,941,662
3,032,282
creating PHP C/C++ extension modules using SWIG
I have written some C/C++ extension modules for PHP, using the 'old fashioned way' - i.e. by using the manual way (as described by Sarah Golemon in her book). This is too fiddly for me, and since I am lazy, and would like to automate as much as possible. Also, I have used SWIG now to generate extensions to Python, and ...
I have extensively used SWIG in production environment for generating PHP wrappers. Its pretty stable and can be used without issues.
2,941,736
2,941,782
Problem with include guard
When I add an include guard to my header file for a Visual C++ project, it gives me the following warning and error: warning C4603: '_MAPTEST_H' : macro is not defined or definition is different after precompiled header use Add macro to precompiled header instead of defining here .\MapTest.cpp(6) : use of prec...
Two problems I can think of: According to this, Visual C++ won't compile anything before the line where you include stdafx.h - so that line needs to be the very first one in the file. If you put it after the macro definition, it gets skipped, hence the errors you're seeing. Identifiers starting with a leading undersc...
2,941,960
2,941,979
A call to PInvoke function '[...]' has unbalanced the stack
I'm getting this weird error on some stuff I've been using for quite a while. It may be a new thing in Visual Studio 2010 but I'm not sure. I'm trying to call a unamanged function written in C++ from C#. From what I've read on the internet and the error message itself it's got something to do with the fact that the sig...
Maybe the problem lies in the calling convention. Are you sure the unmanaged function was compiled as stdcall and not something else ( i would guess fastcall ) ?
2,942,095
2,942,205
listen for events in c++
I got a CWnd like thie CWnd * pWnd = pDC->GetWindow(); Is there away I can be notified when the windows is closing?
Yes, you can use Windows Hooks. http://msdn.microsoft.com/en-us/library/ms632589(VS.85).aspx
2,942,128
2,942,161
What is better: to delete pointer or set it with a new value?
simple question in c++ , say i have a loop and i have function that returns pointer to item so i have to define inner loop pointer so my question is what to do with the pointer inside the loop , delete it ? or to set it with new value is good for example: for(int i =0;i<count();i++) { ptrTmp* ptr = getItemPtr();...
It totally depends on what the interface getItemPtr specifies. Usually a "get pointer" interface that returns a raw pointer isn't trasnfering ownership of the pointed-to object so it would be a mistake to delete it. In this case you can safely let the pointer variable go out of scope. There is no need to set it to NULL...
2,942,235
2,943,870
Deleting a node from a skip list
I'm having some problems deleting a node from a skip list. I have the following structures: struct Node { int info; Node **link_; Node(int v, int levels) { info = v; link_ = new Node*[levels]; for ( int i = 0; i < levels; ++i ) link_[i] = NULL; } }; struct List...
There is an issue with the Remove method, as you guessed: void Remove(int v, List *L) { Node *current = L->Header; for ( int i = L->H - 1; i >= 0; --i ) { for ( ; current->link_[i] != NULL; current = current->link_[i] ) { if ( current->link_[i]->info > v ) { ...
2,942,387
2,942,428
Using Qt with custom MinGW
I don't know if this question would fit better on superuser.com, but since it's rather compiler related, I give it a try here. I have to use Qt with a specific version of gcc (4.5). I downloaded the last official Qt release for Windows (Vista, 32 bits version) and didn't install the shipped MinGW version; I just instal...
The "not an internal command" message is not one you would get if the g++ executable simply could not be found. For example, this makefile: foo: zz foo.cpp gives the error: make: zz: Command not found when the zz executabe does not exist. I don't know what is meant by an "internal command", but I think you need t...
2,942,426
2,942,442
How do I specify a pointer to an overloaded function?
I want to pass an overloaded function to the std::for_each() algorithm. For example, class A { void f(char c); void f(int i); void scan(const std::string& s) { std::for_each(s.begin(), s.end(), f); } }; I'd expect the compiler to resolve f() by the iterator type. Apparently, it (GCC 4.1.2) doe...
You can use static_cast<>() to specify which f to use according to the function signature implied by the function pointer type: // Uses the void f(char c); overload std::for_each(s.begin(), s.end(), static_cast<void (*)(char)>(&f)); // Uses the void f(int i); overload std::for_each(s.begin(), s.end(), static_cast<void ...
2,942,599
2,942,627
Deploying without installer
I'm doing a very small windows application consisting of just a single executable. As the program will reside on a SD card I want the application to be as self contained as possible, and I'd rather not have an installer. I'd want the user to be able to simply copy the executable to the SD card and be able to run it str...
Linking statically to the CRT using /MT or /MTd (for debug) should do exactly what you need. The fact that it isn't suggest that there is still something that depends on the dynamic library. That would be the case if you has some additional DLLs which are not compiled with the static CRT. you can use the dependency wa...
2,942,680
2,942,715
Sleep thread 100.8564 millisecond in c++ under window plateform
I there any method to sleep the thread upto 100.8564 millisecond under window OS. I am using multimedia timer but its resolution is minimum 1 second. Kindly guide me so that I can handle the fractional part of the millisecond.
Yes you can do it. See QueryPerformanceCounter() to read accurate time, and make a busy loop. This will enable you to make waits with up to 10 nanosecond resolution, however, if thread scheduler decides to steal control from you at the moment of the cycle end, it will, and there's nothing you can do about it except as...
2,942,784
2,942,807
Calling a C function in a pro*C file
I have these line in my pro*C program. The function initAverage(int i) is defined in a C language and I am trying to call this function in a .pcc (Pro C++) file. I am getting an error Error: initAverage(int i);was declared before with a different language extern "C" { int initAverage(int i); }
You probably have an include before that already declares initAverage without extern "C". Look at all declarations of initAverage and fix the missing extern declaration then it should be fine. PS: Adding the calling convention explicitly is a good idea in general. I would add that too (while not being actually part of ...
2,942,860
2,942,896
About long long and long double
Since when have they been part of standard C++? I think long long is a C++0x feature, is that right? What about long double? Was that already in C++98 or C++03?
Both long double and long long have been around for quite a while, and were standardised in C89 and C99, respectively. C++ standardised long double from its first version, C++98, and will add long long in the upcoming revision to the standard.
2,942,910
2,943,269
Enumerating and using wmp visualizers
I want to use the systems available windows media player visualizers in my app. Apperently visualizers expose an IWMPEffects interface to the world. My question is how do I enumerate and create instances to the available visualizers on my system? Probably it's just a process of getting the cslid of the visualizers and ...
The CLSIDs of the objects that implement IWMPEffects are stored as subkeys of HKLM\SOFTWARE\Microsoft\MediaPlayer\Objects\Effects.
2,943,050
2,943,153
c++ design question: Can i query the base classes to find the number of derived classes satisfying a condition
I have a piece of code like this class Base { public: Base(bool _active) { active = _active; } void Configure(); void Set Active(bool _active); private: bool active; }; class Derived1 : public Base { public: Derived1(bool active):Base(active){} }; similarly Derived 2 and Derived 3 Now if i call derived1Object.C...
You could use CRTP in conjunction with a static counter variable: Wikipedia Link edit: some code #include <iostream> template <typename T> struct counter { counter() { ++objects_alive; } virtual ~counter() { --objects_alive; } static int objects_alive; }; template <typename T> int counter<T>::objects_alive...
2,943,142
2,943,179
What are marker interfaces?
Possible Duplicate: What is the use of marker interfaces in Java? What are marker interfaces and why are they used?
Example usage in Java: if (obj instanceof MarkerInterface) { // do marker interface related stuff }
2,943,169
2,943,185
How does the LPtoDP function work?
I have a book about programming under Windows, and the author uses a function called LPtoDP (MSDN). But I can't see the difference between code that uses this function and code that doesn't. I use this function in this way, which seems to me to be a proper way. POINT po; po.x = -50; po.y = 100; pDC->LPtoDP(&po); pDC-...
The difference becomes apparent when there is mapping mode set. For example, as a result of viewport (scroll). Read about mapping modes here: http://wvware.sourceforge.net/caolan/mapmode.html
2,943,299
2,943,359
Auto-scrobble video titles
I want to automate the service myshows.ru. Riht now, people must manually input information about movies they watched. I want to write a program in c++, that gets the titles of movies in video players and scrobbles them to their account on the service. What libraries I can use for this work?
Use plain Winapi functions paired with some regex library. What you have to do is to enumerate windows in your system (get their HWND - handles), then take their captions and store them in std::strings. The next step would be checking if your caption matches some regex (this could be boost::regex or boost::xpressive, f...
2,943,632
2,943,656
how to search "n bits" in a byte array?
i have a byte array. Now i need to know the count of appearances of a bit pattern which length is N. For example, my byte array is "00100100 10010010" and the pattern is "001". here N=3, and the count is 5. Dealing with bits is always my weak side.
You could always XOR the first N bits and if you get 0 as a result you have a match. Then shift the searched bit "stream" one bit to the left and repeat. That is assuming you want to get matches if those sub-patterns overlap. Otherwise you should shift by pattern length on match.
2,943,666
2,943,690
Generate Random Number from fix Set of numbers in iphone
Suppose I have One set of numbers i.e {1, 6, 3, 5, 7, 9} I want to Generate Random number from this set of number only i.e. a Generated number should be random and should be from these number({1, 6, 3, 5, 7, 9}) only. standard C/C++ function will also do...
arc4random%(set count) = a random index.
2,943,667
2,944,012
Version Control: multiple version hell, file synchronization
I would like to know how you normally deal with this situation: I have a set of utility functions. Say..5..10 files. And technically they are static library, cross-platform - SConscript/SConstruct plus Visual Studio project (not solution). Those utility functions are used in multiple small projects (15+, number increas...
It is not completely clear to me what you want but maybe git submodules might help : http://git-scm.com/docs/git-submodule
2,943,809
2,943,838
What to throw in a C++ class wrapping a C library?
I have to create a set of wrapping C++ classes around an existing C library. For many objects of the C library, the construction is done by calling something like britney_spears* create_britney_spears() and the opposite function void free_britney_spears(britney_spears* brit). If the allocation of a britney_spears fails...
You would not want to derive a BritneyFailedToConstruct exception. My experience is that you should keep exception hierarchies as flat as possible (I use one single type per library). The exception should derive from std::exception, and should somehow contain a message that is accessible via std:;exceptions virtual wha...
2,943,860
2,943,930
MFC component defocus event handler
Is there a standard way to handle MFC Edit box defocus event? I mean if I click on the box enter something and then move on on the other component handling event gets fired? Thank you for any help!
Yes, Windows send the WM_KILLFOCUS. MFC uses the EN_KILLFOCUS for edit boxes, IIRC.
2,943,899
2,944,011
C++ passing arguments to a program already running
I'm reading through a tutorial on using voice commands to control applications and, in an example of controlling rhythmbox, it suggests commands such as the following can be executed: rhythmbox-client --play rhythmbox-client --pause Why does this not simply open a new instance of the program, and how can I emulate the...
Rhythmbox uses inter-process communictation to achieve this type of functionality, and this can be implemented in a number of different ways. One of them is to use D-Bus, like Rhythmbox does. Using D-Bus is not very easy, but the basic idea is that you register your application in D-Bus, so other applications can call ...
2,943,912
2,943,932
Vector.erase(Iterator) causes bad memory access
I am trying to do a Z-Index reordering of videoObjects stored in a vector. The plan is to identify the videoObject which is going to be put on the first position of the vector, erase it and then insert it at the first position. Unfortunately the erase() function always causes bad memory access. Here is my code: testAp...
You should do itVid = videoObjects.erase(itVid); Quote from cplusplus.com: [vector::erase] invalidates all iterator and references to elements after position or first. Return value: A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which i...
2,944,092
3,866,692
Disabling Scrollbars in WebKit (flat frame mode)
I'm embedding WebKit in a Windows C++ Application. I'm using the Cairo port. It works fine. I'd like to disable the scrollbars that appear when there's more data that the client area can display. Like the iPhone, the iPhone does not have scrollbars, scrolling is implemented differently. How can I disable the scrollbars...
Are you rebuilding the Cairo-port of webkit ? If so, you can modify WebCore/css/html4.css and WebCore/css/quirks.css to include the "overflow: hidden" in the body tag. If not, I am afraid that the only way to disable scrollbar is to pass through javascript.
2,944,141
2,944,868
How can I fix my window focus problem?
I have a very frustrating bug in an application I am working on. The routine is supposed to do something in one window, and then return focus to the other at the end of the method, but when I started to use a large data set the other day, the focus stopped returning at the end. I stepped through the code one line at a ...
First thing that should be clear is that Win32 API calls that are related to windows/messages/focus and etc. do not depend on timing. Every thread has its own window/messaging subsystem, there's no race conditions here. What you describe is something else. You actually launch another process (application), which runs c...
2,944,155
2,944,254
Emacs: Auto Complete for C++
i found this autocompletion for Emacs: http://www.emacswiki.org/emacs/AutoComplete, but I can't find what languages it supports. I want to use it particular for C++-autocompletion. Has anybody experience with this?
As you can see from the User's Guide it has built-in support for C/C++ by means of Semantic. There is also one more tool from the auto-complete mode developer called GCC Sense, which he claims to be most intelligent tool for C/C++ programming and of course it integrates nicely with auto-complete so you might have a loo...
2,944,321
2,944,372
Does changing the order of class private data members breaks ABI
I have a class with number of private data members (some of them static), accessed by virtual and non-virtual member functions. There's no inline functions and no friend classes. class A { int number; string str; static const int static_const_number; bool b; public: A(); virtual ~A(); public: ...
It might, yes, if for no other reason than that the size of A could be different due to differences in the location and number of padding bytes between the data members.
2,944,607
2,948,198
OpenGL fast texture drawing with vertex buffer objects. Is this the way to do it?
I am making a 2D game with OpenGL. I would like to speed up my texture drawing by using VBOs. Currently I am using the immediate mode. I am generating my own coordinates when I rotate and scale a texture. I also have the functionality of rounding the corners of a texture, using the polygon primitive to draw those. I wa...
For better performance, you should not use immediate mode rendering, but instead use vertex buffer (on CPU or GPU) and draw using glDrawArrays etc like methods. Scaling/rotating the texture coordinates by modifying texture matrix multiplier is not a performance issue, you just set some small values for the entire mesh....
2,944,738
2,945,121
Alternative Control Structures
I've been wondering about alternative ways to write control structures like you can write your own language constructs in Forth. One that you learn early on for if statements is a replacement for this: if ( x ) { // true } else { // false } with this (sometimes this is more readable compared to lots of brackets)...
How would you replace a while loop Loops can be replaced by recursion. void doWhile(a, b) { /* do something with a and b, hopefully changing them */ if (a > b) doWhile(a, b); }
2,944,789
2,944,847
Beginner question about getting reference to cin
I'm having problems wrapping my head around this. I have a function void foo(istream& input) { input = cin; } This fails (I'm assuming because cin isn't supposed to be "copyable". however, this works void foo(istream& input) { istream& baz = cin; } Is there a reason that I can get a reference to cin in baz b...
This syntax: void foo(istream& input) { input = cin; } Doesn't create a reference. it invokes the operator= which is meant to copy things around. This syntax however: void foo(istream& input) { istream& baz = cin; } defines a new reference variable. The key point is that in C++ you can't change a reference...
2,944,794
2,945,818
Is a function reference sizeof portable?
Looking for a way to do a portable, safe, elements count for c-style arrays, I found this solution: template <typename T, unsigned N> char (&arrayCountofHelper(T(&)[N]))[N]; #define ARRAY_COUNTOF(arr) (sizeof(arrayCountofHelper(arr))) It seems like arrayCountofHelper is actually a reference to a function, and the mac...
We will pick this apart loosely, I'm using INCITS+ISO+IEC+14882-2003. I'll quote the small stuff, but some of the more complex stuff is too large to quote. sizeof is defined in §5.3.3, and it says (abridged): The sizeof operator yields the number of bytes in the object representation of its operand. The operand is eit...
2,944,862
2,944,881
How is the syntax for stl iterators implemented?
I've been working on writing a library in my spare time to familiarize myself more with c++ and singular value decomposition. I've been working on writing an Iterator class and I'm entirely capable of writing the functionality and I have already for my own currently MatrixIterator class. I'm guessing that it involves n...
No, this has nothing to do with namespaces. It's simply a typedef within a class: template <typename T> class container { public: typedef ... iterator; }; Once you have a your iterator class, there are a couple of operators you need to implement. For a forward iterator, that would be: operator*(); operator++(); ...
2,945,091
2,945,299
GCCs atomic builtins - Which processors are supported
This document says: Not all operations are supported by all target processors. Does anybody know, for which processor which operation is supported?
Not a direct answer, but the following snippet from the linked page gives a clue (emphasis is mine): Not all operations are supported by all target processors. If a particular operation cannot be implemented on the target processor, a warning will be generated and a call an external function will be generated. The ext...
2,945,174
2,945,186
Floating point Endianness?
I'm writing a client and a server for a realtime offshore simulator, and, as I have to send a lot of data through a socket, I'm using binary data to maximize the amount of data I can send. I already know about integers endianness, and how to use htonl and ntohl to circumvent endianness issues, but my application, as al...
Yes, floating point can be endianess dependent. See Converting float values from big endian to little endian for info, be sure to read the comments.
2,945,312
2,945,444
Does an optimistic lock-free FIFO queue implementation exist?
Is there any C++ implementation (source codes) of "optmistic approach to lock-free FIFO queues" algorithm?
Herb Sutter covered just such a queue as part of his Effective Concurency column in Dr. Dobbs Journal. Writing Lock-Free Code: A Corrected Queue
2,945,343
2,945,369
C++ variable alias - what's that exactly, and why is it better to turn if off?
I've read the essay Surviving the Release Version. Under the "Aliasing bugs" clause it says: You can get tighter code if you tell the compiler that it can assume no aliasing.... I've also read Aliasing (computing). What exactly is a variable alias? I understand it means using a pointer to a variable is an alias, ...
Disallowing aliasing means if you have a pointer char* b, you can assume that b is the only pointer in the program that points to that particular memory location, which means the only time that memory location is going to change is when the programmer uses b to change it. The generated assembly thus doesn't need to rel...
2,945,379
2,945,720
Is there a program that reorganizes .cc method definitions to be ordered according to .h declarations?
Is there a program that reorganizes .cc method definitions to be ordered according to .h declarations?
The closest thing that I'm aware of is Lazy C++. It'll generate .h and .cc files from a single .lzz file.
2,945,827
2,945,854
Attribute vector emptying itself
I have two classes, derived from a common class. The common class has a pure virtual function called execute(), which is implemented in both derived classes. In the inherited class I have an attribute which is a vector. In both execute() methods I overwrite this vector with a result. I access both classes from a vector...
Since everything else is the same between classes B and C I would have to say that the line //different stuff to B is probably important! Also your get_result() method should really be const vector<E*>& get_result() const; to save you making a copy of the vector each time.
2,945,877
2,976,666
Why does output of fltk-config truncate arguments to gcc?
I'm trying to build an application I've downloaded which uses the SCONS "make replacement" and the Fast Light Tool Kit Gui. The SConstruct code to detect the presence of fltk is: guienv = Environment(CPPFLAGS = '') guiconf = Configure(guienv) if not guiconf.CheckLibWithHeader('lo', 'lo/lo.h','c'): print 'Did not f...
There are 2 similar ways to do this: 1) conf = Configure(env) status, _ = conf.TryAction("fltk-config --cflags") if status: env.ParseConfig("fltk-config --cflags") else: print "Failed fltk" 2) try: env.ParseConfig("fltk-config --cflags") except (OSError): print 'failed to run fltk-config you sure fltk...
2,945,980
2,945,990
skipped when looking for precompiled header
So some reason, my .cpp file is missing it's header file. But I am not including the header file anywhere else. I just started so I checked all the files I made enginuity.h #ifndef _ENGINE_ #define _ENGINE_ class Enginuity { public: void InitWindow(); }; enginuity.cpp #include "Enginuity.h" void Enginuity::In...
Did you read the error message? fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source? I don't see an #include "stdafx.h" in enginuity.cpp. ;) If you're using precompiled headers, you need to include the precompiled header in every s...
2,946,226
2,950,666
Realtime processing and callbacks with Python and C++
I need to write code to do some realtime processing that is fairly computationally complex. I would like to create some Python classes to manage all my scripting, and leave the intensive parts of the algorithm coded in C++ so that they can run as fast as possible. I would like to instantiate the objects in Python, and...
I suggest using Boost.Python as suggested by ChristopheD. A gotcha would be if the C++ extension is running in it's own thread context (not created by Python). If that's the case, make sure to use the PyGILState_Ensure() and PyGILState_Release() functions when calling into Python code from C++. From the docs (http://...
2,946,327
2,946,536
Inner angle between two lines
I have two lines: Line1 and Line2. Each line is defined by two points (P1L1(x1, y1), P2L1(x2, y2) and P1L1(x1, y1), P2L3(x2, y3)). I want to know the inner angle defined by these two lines. For do it I calculate the angle of each line with the abscissa: double theta1 = atan(m1) * (180.0 / PI); double theta2 = atan(m2)...
I think what you're looking for is the inner product (you may also want to look over the dot product entry) of the two angles. In your case, that's given by: float dx21 = x2-x1; float dx31 = x3-x1; float dy21 = y2-y1; float dy31 = y3-y1; float m12 = sqrt( dx21*dx21 + dy21*dy21 ); float m13 = sqrt( dx31*dx31 + dy31*dy3...
2,946,413
2,946,441
what is a virtual adapter
I hear the term virtual adapter from time to time. But not exactly sure what it is. I can't exactly find a good definition online. Is there an exact definition for a virtual adapter. If so, what is it. Or what does it usually mean ?
In most scenarios, it involves a device driver at the operating system kernel level that pretends to implement a hardware device. A very common implementation is a driver that supports VPN. It looks like a regular network adapter to user code. But it actually transparently transmits packets across the Internet to a ...
2,946,442
2,946,462
missing subscript c++
right now c++ is giving me this error: error C2087 'color' missing subscript first time i get this and i dont know what to do >.< hope any1 can help me struct Color{ float r; float g; float b; }; Color color[][]; and im using it here for(int i=0;i<cubes;i++) { color[i][0].r = fRand();color[i][0].g=fRa...
You should specify the size of your array: Color color[HEIGHT][WIDTH];
2,946,457
2,946,563
What is an interface in C (COM) is it the same as a interface in C#
Ok, I know what a interface is, but since I got into C and working with COM objects (Component Object Model), it seems an interface in COM is a little different from the interface I know of. So what I am trying to do is bridge the gaps here cause since I been learning C, alot of things have been sounding very familiar ...
There are definitely low-level details they have in common. An interface is a list of function pointers in both languages. More commonly implemented in C++ because most compilers already implement virtual functions as a "v-table". A one-to-one match with a COM dispatch table. Where they start to diverge is the metho...
2,946,540
2,946,543
Using #define one time for multiple source files
Is there a way in Visual C++ to #define something in a cpp file and have it defined in other cpp files as well?
There are at least two options: Put the definition into a header file and include that header file in all the source files in which you need the definition Use the /D compiler option to define the macro (this can also be set in the project properties under C/C++ -> Preprocessor -> Preprocessor Definitions)
2,946,651
2,946,730
Code coverage (c++ code execution path)
Let's say I have this code: int function(bool b) { // execution path 1 int ret = 0; if(b) { // execution path 2 ret = 55; } else { // execution path 3 ret = 120; } return ret; } I need some sort of a mechanism to make sure that the code has gone in an...
Usually coverage utilities (such as gcov) are supplied with compiler. However please note that they will usually give you only C0 coverage. I.e. C0 - every line is executed at least once. Please note that a ? b : c is marked as executed even if only one branch have been used. C1 - every branch is executed at least onc...
2,946,671
2,946,684
What is the correct way of using an auto_ptr on dynamically allocated arrays?
If i use auto_ptr to hold a pointer to a dynamically allocated array, when the auto_ptr gets killed it will use a plain delete operation and not delete[] thus not deleting my allocated array. How can i (properly) use auto_ptr on dynamically allocated arrays? If this is not possible, is there another smart pointer alter...
boost::shared_array is what your looking for. EDIT: If you want to avoid the use of boost I would recommend just using std::vector they are array's underneath and there is no need to worry about memory allocation. Actually this is a better solution than shared_array anyway. Since you indicate that you wanted to use au...
2,946,887
3,003,829
Can I upgrade Xcode to support a newer version of GCC to learn C++0x?
I would like to jump in learn C++0x, which has matured to a level I'm happy with. Xcode on Snow Leopard 10.6 is currently at GCC 4.2.1, and the new features I'd like to try, like std::shared_ptr, lambdas, auto, null pointer constant, unicode string literals, and other bits and pieces, require at least 4.3 (I believe). ...
I ended up downloading the latest Intel Compiler for Mac trial, and it does what I need. It's a good way to test the waters without messing with your system. http://software.intel.com/en-us/intel-compilers/
2,946,916
2,947,265
using strcpy_s for TCHAR pointer (Microsoft Specific)
I was wondering which is the correct way? _tcscpy(tchar_pointer, _tcslen(tchar_pointer), _T("Hello World")); or _tcscpy(tchar_pointer, _tcsclen(tchar_pointer), _T("Hello World")); or _tcscpy(tchar_pointer, ???, _T("Hello World"));
the tchar pointer are coming from external, and my side has no idea how large the buffer referred by the pointer is If this is so, then none of these do what you want. The way all the "safe" functions work is that you tell them how big the target buffer is. You don't know? You can't use those functions. int buffer_...
2,947,034
2,947,083
How to set the application path to the running program?
I have a program that is executed by another program. The program that is being executed needs files located at its own location [same folder]. If I call myfile.open("xpo.dll") I might get an error because I am not passing the [fullpath + name + extension]. The program that is being executed can vary paths depending on...
Use GetModuleFileName and pass NULL for hModule. DWORD GetModuleFileName( HMODULE hModule, // handle to module LPTSTR lpFilename, // path buffer DWORD nSize // size of buffer );
2,947,114
2,947,117
QT clicked signal dosnt work on QStandardItemModel with tree view
i have this code in QT and all i want to to catch the clicked event when some one clicking in one of the treeview rows without success here is my code: (parant is the qMmainwindow) m_model = new QStandardItemModel(0, 5, parent); // then later in the code i have proxyModel = new QSortFilterProxyModel; proxyModel->se...
lowercase c for the clicked signal. connect(ui.treeView,SIGNAL(clicked(const QModelIndex& ) ), this,SLOT( treeViewSelectedRow(const QModelIndex& ) ) );
2,947,151
2,947,243
C++ question: boost::bind receive other boost::bind
I want to make this code work properly, what should I do? giving this error on the last line. what am I doing wrong? i know boost::bind need a type but i'm not getting. help class A { public: template <class Handle> void bindA(Handle h) { h(1, 2); } }; class B { public: void bind...
The problem that you are having is that you are trying to bind to a templated function. In this case you need to specify the template type of the method you are calling to bind. This is happening for the method A::bindA. See below for a code fragment for main that compiles correctly with the supplied classes. Incident...
2,947,194
2,947,207
C++: Why does space always terminate a string when read?
Using type std::string to accept a sentence, for practice (I haven't worked with strings in C++ much) I'm checking if a character is a vowel or not. I got this: for(i = 0; i <= analyse.length(); i++) { if(analyse[i] == 'a' || analyse[i] == 'e' [..etc..]) { ...vowels++; } else { ... ...consonants++; } This works ...
I'd guess you're reading your string with something like your_stream >> your_string;. Operator >> for strings is defined to work (about) the same as scanf's %s conversion, which reads up until it encounters whitespace -- therefore, operator>> does the same. You can read an entire line of input instead with std::getline...
2,947,443
2,947,474
C++ Storing variables and inheritance
Here is my situation: I have an event driven system, where all my handlers are derived from IHandler class, and implement an onEvent(const Event &event) method. Now, Event is a base class for all events and contains only the enumerated event type. All actual events are derived from it, including the EventKey event, whi...
Opinion: choose the reference counting option. Use boost::shareed_ptr, and boost::dynamic_pointer_cast to determine actual type.
2,947,544
2,947,570
How to copy files in VC++ ?
I want to copy the files present in a flash drive into hard drives and then run them using a VC++ application. I have VS 2008..?
You could use FindFile() to figure out what files are in the folder.. CopyFile(_T("c:\\test"), _T("c:\\test1"), true); Then ShellExecute(...)
2,947,583
2,947,592
Problem accessing base member in derived constructor
Given the following classes: class Foo { struct BarBC { protected: BarBC(uint32_t aKey) : mKey(aKey) mOtherKey(0) public: const uint32_t mKey; const uint32_t mOtherKey; }; struct Bar : public BarBC { Bar(uint32_t aKey, uint32_t aOt...
You can't initialize members of a base class through a member initializer list, only direct and virtual base classes and non-static data members of the class itself. Pass additional parameters to the base class' constructor instead: struct BarBC { BarBC(uint32_t aKey, uint32_t otherKey = 0) : mKey(aKey), mOth...
2,947,766
2,947,800
Initialize a Variable Again
That may sound a little confusing. Basically, I have a function CCard newCard() { /* Used to store the string variables intermittantly */ std::stringstream ssPIN, ssBN; int picker1, picker2; int pin, bankNum; /* Choose 5 random variables, store them in stream */ for( int loop = 0; loop < 5; +...
Just some basic pointers, because you have some misunderstandings. This doesn't intialize a CCard, object. It declares card to be a function returning a CCard and taking no parameters. CCard card(); If you want to construct a CCard object then just do this. CCard card; Your constructor will be called and card should ...
2,948,024
2,948,153
WAVEFORMATEX - how to read codecdata at the end?
I've a WAVEFORMATEX struct with some codecdata at the end of it (10 bytes). I'm using C++. How do I access the data at the end? (this is a purely technical question). I tried : WAVEFORMATEX* wav = (WAVEFORMATEX*)pmt->pbFormat; WORD me = wav->cbSize; wav = wav + sizeof(WAVEFORMATEX); BYTE* arr = new BYTE[me...
You've done a little mistake in pointer arithmetic. After wav = wav + sizeof(WAVEFORMATEX); wav points far beyond the end of the buffer (because wav is not CHAR* but WAVEFORMATEX*). You need to write: wav = wav + 1;
2,948,193
2,948,244
Can i clear the serial port every time after reading the data from it?
i need to clear the data on serial port when i have read the data from it before i read the data again? i m using c/c++ on windows xp how can i do so ? thanx in advance.
The C++ standard has interfaces for writing to files, to the screen and to a log. It also has interfaces for reading from files and reading from "standard input." There is no standard way to interact with serial ports, network connections, etc. Luckily your operating system or platform will have an interface for this...
2,948,307
2,948,543
How to find out where my memory is going
I've got the situation where the cycle of loading and then closing a document eats up a few Mb of RAM. This memory isn't being leaked as something owns it and cleans it up when the app exits (Visual Leak Detector and the Mac Leaks tool show agreement on this). However, I'd like to find out where it's going. I'm assu...
Working from the assumption that it is actually RAM you've measured: sure this is entirely normal. Your program is actively addressing virtual memory pages when loading a document, they'll get mapped to RAM. They'll stay there until another process needs to have pages mapped to RAM. Some operating systems trim the w...
2,948,361
2,948,466
When and why can sprintf fail?
I'm using swprintf to build a string into a buffer (using a loop among other things). const int MaxStringLengthPerCharacter = 10 + 1; wchar_t* pTmp = pBuffer; for ( size_t i = 0; i < nNumPlayers ; ++i) { const int nPlayerId = GetPlayer(i); const int nWritten = swprintf(pTmp, MaxStringLengthPerCharacter, TEXT("...
From the c99 standard: The sprintf function returns the number of characters written in the array, not counting the terminating null character, or a negative value if an encoding error occurred. This generally happens only with the multi-byte and wide character character set functions.
2,948,438
2,948,537
Use multiple inheritance to discriminate useage roles?
it's my flight simulation application again. I am leaving the mere prototyping phase now and start fleshing out the software design now. At least I try.. Each of the aircraft in the simulation have got a flight plan associated to them, the exact nature of which is of no interest for this question. Sufficient to say tha...
From a strict design point of view, your idea is quite good indeed. It is equivalent to having a single objects and several different 'views' over this object. However there is a scaling issue here (relevant to the implementation). What if you then have another object Foo that needs access to the flight plan, you would...
2,948,590
2,948,732
how to do event based serial port reading in c?
i want to read serial port when there is some data present i mean on the event when data arrives only then i will read serial port instead of continuously reading the port i have this code for continuous reading the port how can i make it event based. thanx in advance. while(1) { bReadRC = ReadFile(m_hCom, &byte, 6,...
According to MSDN you can use the WaitCommEvent() operation on your serial port handle. Also, this article gives a nice introduction into the topic.
2,948,605
2,948,623
Undefined / Uninitialized default values in a class
Let's suppose you have this class: class A { public: A () {} A (double val) : m_val(val) {} ~A () {} private: double m_val; }; Once I create an instance of A, how can I check if m_val has been initialized/defined? Put it in other words, is there a way to know if m_val has been initialized/defined or not? Somet...
You'll need to set a sensible default value in the default constructor, otherwise its value is undefined. Which basically means it will be a random value -- could be 0, NaN, or 2835.23098 -- no way to tell unless you set it explicitly. class A { public: A () : m_val(0.0) {} A (double val) : m_val(val) {} ~A () {}...
2,948,648
2,948,729
C++ static classes & shared_ptr memory leaks
I can't understand why does the following code produce memory leaks (I am using boost::shared_ptr with static class instance). Could someone help me? #include <crtdbg.h> #include <boost/shared_ptr.hpp> using boost::shared_ptr; #define _CRTDBG_MAP_ALLOC #define NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) static struct ...
At a guess the CRT is reporting a false positive - the following code illustrates that the shared pointer is working correctly, at least with g++ #include <iostream> #include "boost/shared_ptr.hpp" using namespace std; using namespace boost; struct R { R() { cerr << "ctor" << endl; } ~R() { ...
2,948,700
2,951,889
Reading a file in C++
I am writing application to monitor a file and then match some pattern in that file. I want to know what is the fastest way to read a file in C++ Is reading line by line is faster of reading chunk of the file is faster.
In general, reading large amounts of a file into a buffer, then parsing the buffer is a lot faster than reading individual lines. The actual proof is to profile code that reads line by line, then profile code reading in large buffers. Compare the profiles. The foundation for this justification is: Reduction of I...
2,948,756
2,952,938
How many registers in custom VM?
I'm designing a custom VM and am curious about how many registers I should use. Initially, I had 255, but I'm a little concerned about backing 255 pointers (a whole KB) on to the stack or heap every time I call a function, when most of them won't even be used. How many registers should I use?
Sorry guys. I made a stupid on this one. Turns out that I already had a vector of registers to optimize access to the stack, which I totally forgot about. Instead of duping them, I just set the registers in the state to be a reference to the stack's registers. Now all I need to do is specialize pushing to push straight...
2,949,012
2,967,960
Debugging InProc COM Dll
I have a project in VC++ 6.0 where there is an exe and a InProc COM Dll. I want to be able to place a breakpoint somewhere in the InProc COM DLL, but VC++ won't allow me to set a breakpoint. I have the source code for this DLL, however I cannot figure out how I can place a breakpoint in the code and the debug it? Can ...
Attach to the process Open Project->Settings (Alt+F7) Open Debug tab, category Additional DLLs Add you in-proc server DLL Save .opt file on closing the debugger This way next time you attach to process or manually open the .opt file, your in-proc server DLL gets loaded, its PDB gets parsed, last open source files get...
2,949,435
2,949,914
VS2005 C++ compiler crashes with the /Gd flag
I was trying to compile our project in Visual Studio 2010 using the 2005 compiler and I stumbled upon this strange bug. There's this particular file that crashes the compiler whenever I try to compile it from VS2010 with a "Microsoft (R) C/C++ Optimizing Compiler" error dialog with "don't send" buttons. I looked at th...
Supposing you have a good reason for wanting to use the new IDE with its compiler's grandparent (I'm curious!), you can change the calling convention in the "Advanced" branch of the "C/C++" configuration properties of a project. That listbox only gives me three value to pick from, but when I manually delete the text th...