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 memset(), can be useful, so I tried adding my own implementation. It works fine in Debug builds (even for those places where the compiler generates an implicit call to memset()). But in Release builds, I get an error saying that I cannot define an intrinsic function. You see, in Release builds, intrinsic functions are enabled, and memset() is an intrinsic. I would love to use the intrinsic for memset() in my release builds, since it's probably inlined and smaller and faster than my implementation. But I seem to be a in catch-22. If I don't define memset(), the linker complains that it's undefined. If I do define it, the compiler complains that I cannot define an intrinsic function. Does anyone know the right combination of definition, declaration, #pragma, and compiler and linker flags to get an intrinsic function without pulling in RTL overhead? Visual Studio 2008, x86, Windows XP+. To make the problem a little more concrete: extern "C" void * __cdecl memset(void *, int, size_t); #ifdef IMPLEMENT_MEMSET void * __cdecl memset(void *pTarget, int value, size_t cbTarget) { char *p = reinterpret_cast<char *>(pTarget); while (cbTarget > 0) { *p++ = static_cast<char>(value); --cbTarget; } return pTarget; } #endif struct MyStruct { int foo[10]; int bar; }; int main() { MyStruct blah; memset(&blah, 0, sizeof(blah)); return blah.bar; } And I build like this: cl /c /W4 /WX /GL /Ob2 /Oi /Oy /Gs- /GF /Gy intrinsic.cpp link /SUBSYSTEM:CONSOLE /LTCG /DEBUG /NODEFAULTLIB /ENTRY:main intrinsic.obj If I compile with my implementation of memset(), I get a compiler error: error C2169: 'memset' : intrinsic function, cannot be defined If I compile this without my implementation of memset(), I get a linker error: error LNK2001: unresolved external symbol _memset
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 implementation file, provide an implementation. The trick to preventing the compiler from complaining about re-defining an intrinsic function is to use another pragma first. Like this: #pragma function(memset) void * __cdecl memset(void *pTarget, int value, size_t cbTarget) { unsigned char *p = static_cast<unsigned char *>(pTarget); while (cbTarget-- > 0) { *p++ = static_cast<unsigned char>(value); } return pTarget; } This provides an implementation for those cases where the optimizer decides not to use the intrinsic version. The outstanding drawback is that you have to disable whole-program optimization (/GL and /LTCG). I'm not sure why. If someone finds a way to do this without disabling global optimization, please chime in.
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 would probably look like this: int main() { ContainerFile cntf("myContainer.cnt", ContainerFile::CREATE); cntf.addFile("data/some-interesting-stuff.txt"); cntf.addDirectory("data/foo/"); cntf.addDirectory("data/bar/", ContainerFile::RECURSIVE); cntf.close(); } ... I hope you get the Idea. Important Requirements are: The Library must be crossplatform anything *GPL is not acceptable in this case (MIT and BSD License are) I already played with the thought of creating an Implentation based on SQLite (and its ability to store binary blobs). Unfortunately, it seems impossible to store Directory structures in a SQLite Database, which makes it pretty much useless in this case. Is it useless to hope for such a class library?
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 std::string. And of course this wrapper is available under the MIT/X11 License (just as libmars), which means you can do whatever you want with it. ;-)
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 approach would be better. The obvious one means making my method act like std::string GetValue(const std::string& name) const and return a copy of the object and rely on RVO in performance meanings. The other one would mean making two methods std::string& GetValue(...) const std::string& GetValue(...) const which generally means duplicating code or using some evil constant casts to use one of these routines twice. #Q What would be your choice in this kind of situation and why?
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 const-reference, it's been explained in a article by Dave Abrahams, "Want Speed? Pass by Value." Using a Setter is usually better, because you can check the value being set whereas with a plain reference you have no guarantee that the caller won't do anything stupid with the data. For the getter: Returning by copy seems a waste since most times you won't modify the object returned (for a settings map), however pointer or reference do mean that the object aliased will live long enough, if you can't guarantee it then the point is moot: return by value. Also copy allow to avoid exposing an internal detail, for example if you were suddenly to switch to std::wstring because you need some settings in UTF-8... If you need performance, then you are ready to do some concessions in this department. However a reference does not allow you to signal the absence of the property (unless you have some magic value) while the pointer makes it easy (NULL is already cut out for you).
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 function is never called, does the static variable get allocated? Thanks
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 to, an inability to determine what depends on the symbol, etc). It's worth checking your linker map file (sometimes just a text file!), or using objdump, nm, or dumpbin utilities on the final executable to see if the symbol or related symbols (such as static initializer code) survived.
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; [...] } Is there a possible race condition in the above code? Specifically, is the compiler likely to generate code equivalent to the following, "behind the scenes"? void MyFunction() { static bool _myClassObjectInitialized = false; if (_myClassObjectInitialized == false) { _myClassObjectInitialized = true; _myClassObject.MyClass(); // call constructor to set up object } [...] } ... in which case, if two threads were to call MyFunction() nearly-simultaneously, then _myArray might get allocated twice, causing a memory leak? Or is this handled correctly somehow?
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 convenient namespace, and get allocated at the start of the application.
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 to be virtual. I'd like to know if there's any way around this problem. template <typename T> class BaseVisitor { public: BaseVisitor(); T visit(BaseVisited *visited); virtual ~BaseVisitor(); } class BaseVisited { BaseVisited(); template <typename T> virtual void accept(BaseVisitor<T> *visitor) { visitor->visit(this); }; // problem virtual ~BaseVisited(); }
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<typename T> class BaseVisitor : public BaseVisitorInternal { void visit(BaseVisited* visited); }; If you need BaseVisited's derived classes to be templated too AND pass their correct types/overloads to visit, you're officially dead.
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 pressed. I was thinking about registering a hook every timer timeout and on any key press to unregister it. So if there is no key press for a long time then my program will know if the user is idle. Anyway, I couldn't find any global hooks for any key, including modifiers. Is there an easy way to do this? Or would someone have a better way to detect keyboard idleness? Thanks
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 { // equal current keymap XQueryKeymap(display, prevKeymap); // ask for new keymap return true; // exit with true } } return false; // no change == no activity } When I call it every 100-300ms it detects any pressed key anywhere in X.
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, reliable UDP library would be greatly appreciated.
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 "inToOut.insert" it works just fine : class MapFile { public: /* ... */ }; bool MapFile::LoadMapFile( const wxString& fileName ) { /* ... */ std::map <unsigned int, unsigned int> inToOut; inToOut.insert( std::make_pair(input,output) ); } ? OK. Thanks guys, it seems that I have fixed this issue thanks to your help. The problem was in the part of the code where I've been calling the LoadMapFile : void WizardProductPage::OnTestButtonMapFile( wxCommandEvent& event ) { wxString filename; filename = locMapFile->GetValue(); MapFile::LoadMapFile( filename ); } Should be : void WizardProductPage::OnTestButtonMapFile( wxCommandEvent& event ) { wxString filename; filename = locMapFile->GetValue(); MapFile mapFile; mapFile.LoadMapFile( filename ); }
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-by-step debugging or post your whole code here, because this has no problems in it. Also, yes. If you're trying to do that operation from different threads simultaneosly without locking, it could cause segfault.
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 static 0.02V).. I also tried the following with C++: int main () { int val = 0; printf("Enter a value\n"); scanf("%d", &val); _outp(0x378, val); getchar(); _outp(0x378, 0); return 0; } But it throws an exception: Unhandled exception at 0x01281428 in ppac.exe: 0xC0000096: Privileged instruction. I remember once I made something like this work on xp (C# not the C++ code), I hope it's possible on win7 too.. Please help me with this. Thanks.
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 version of windows that's modern enough to have good kernel/userspace separation (namely anything based on Windows NT). I'm almost 100% certain you never got _outp to work on XP. To access the parallel port in high-level code, just open it like a normal file, using the filename LPT1:.
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 file and get the metadata. any input is appreciated. ( alternatively, if you know of an app that already does this I'd like to know :)
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 exiftool -r -d images/%Y-%m-%d/%Y%m%d_%%.4c.%%e "-filename<filemodifydate" pics -move files to folders (images/YYYY-MM-DD/) and rename files to YYYYMMDD_####.ext that are in pics folder(and subfolders) hope this helps others
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 (boundingRect()); } However, this event handler code is never executed. I've explicitly enabled mouse tracking: MyGraphicsView::MyGraphicsView(MainView *parent) : QGraphicsView(parent) { setMouseTracking(true); viewport()->setMouseTracking(true); ... } Still, no luck. What am I doing wrong?
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, typename D> struct foo; template<typename X> struct bar : foo<X,bar<X> > { X evaluate() { return static_cast<X>( 5.3 ); } }; template<typename X> struct baz : foo<X,baz<X> > { X evaluate() { return static_cast<X>( "elk" ); } }; template<typename X, typename D> struct foo : D { X operator() () { return static_cast<D*>(this)->evaluate(); } }; template<typename X, typename D> void print_foo( foo<X,D> xyzzx ) { cout << "Foo is " << xyzzx() << "\n"; } int main() { bar<double> br; baz<const char*> bz; print_foo( br ); print_foo( bz ); return 0; } Compiler errors foo.C: In instantiation of ‘foo<double, bar<double> >’: foo.C:8: instantiated from ‘bar<double>’ foo.C:30: instantiated from here foo.C:18: error: invalid use of incomplete type ‘struct bar<double>’ foo.C:8: error: declaration of ‘struct bar<double>’ foo.C: In instantiation of ‘foo<const char*, baz<const char*> >’: foo.C:13: instantiated from ‘baz<const char*>’ foo.C:31: instantiated from here foo.C:18: error: invalid use of incomplete type ‘struct baz<const char*>’ foo.C:13: error: declaration of ‘struct baz<const char*>’
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: template<typename X, typename D> struct foo // : D // ... ^ remove that
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 regards!
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); The copy assignment operator is a special case of an assignment operator. It is any assignment operator that takes the same type as the class, either by value or by reference (the reference may be const- or volatile-qualified). If you do not explicitly implement some form of the copy assignment operator, then one is implicitly declared and implemented by the compiler.
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 returns null to the following request: CvVideoWriter *writer = cvCreateVideoWriter("video.avi", CV_FOURCC('M','J','P','G'), fps, size, 0); I've walked through the OpenCv folders - it even seems to have ffmpeg inside. I've also installed it on the system to make sure. I've changed CV_FOURCC('M','J','P','G') to -1 - all worthless. I would appreciate your help soo much!
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 components are in C++ and exposed via SWIG to Python for experimentation and rapid prototyping of new components. Qt seems like it has some classes I could use to avoid re-inventing the wheel too much here, but I'm concerned about how some of the bits will fit together. Specifically, if I create some C++ classes, I'll need to expose them via SWIG. Some of these classes likely subclass Qt classes or otherwise have Qt stuff exposed in their public interfaces. This seems like it could raise some complications. There are already two interfaces for Qt in Python, PyQt and PySide. Will probably use PySide for licensing reasons. About how painful should I expect it to be to get a SWIG-wrapped custom subclass of a Qt class to play nice with either of these? What complications should I know about upfront?
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 other. You couldn't conveniently use SWIG to wrap any code using the C++ extensions that Qt requires (to support signals and slots) and I have no idea what perils may await you in trying to interoperate SIP-wrapped (or Shiboken-wrapped) and SWIG-wrapped code. Why, may I ask, have you chosen to use two separate and equivalent ways to wrap different parts of your C++ codebase (Qt via SIP or Shiboken, everything else via SWIG)? If you can still reconsider this weird design decision I would earnestly recommend that you do so. If your choice of SWIG is carved in stone, I predict big trouble any time you're wrapping C++ code using Qt extensions (i.e., slots or signals) and a generally thoroughly miserable time for all involved. If you pick one way to wrap, and stick with it, the problems should be enormously reduced. I have no real-world experience with Shiboken (it's a bit too new, and I hardly ever do GUI apps these days any more... my world's all web app!-), but have used SIP in this role in the past (way back before it was decently documented -- these days it seems to me that it's splendidly documented, and superficial perusal of Shiboken gives me the same impression) and I can recommend it highly (indeed if I could choose it would be an option probably preferable to SWIG even if no Qt code was involved in a project).
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. The class monotonic_clock is conditionally supported. Can I use SFINAE or another technique to define a traits class to determine if monotonic_clock is defined? If not, shouldn't there be a standard macro that indicates whether monotonic_clock is available?
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; } However, if you have compiled against the "older" SDK, GetWinData has no chance to figure out you don't know about extraData. If it would fill it in regardless, it would overwrite data on the stack. BOOOM! That's why, the "size known to the caller" is added to the structure, and new members are appended at the end. The GetWinDataimplementation can inspect the size and decide "this poor guy doesn't know about all the new features yet".
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 example, what should I do to deal with the return type, and parameter? FAACAPI is defined as: #define FAACAPI __stdcall faacEncConfigurationPtr is defined: typedef struct faacEncConfiguration { int version; char *name; char *copyright; unsigned int mpegVersion; unsigned long bitRate; unsigned int inputFormat; int shortctl; psymodellist_t *psymodellist; int channel_map[64]; } faacEncConfiguration, *faacEncConfigurationPtr; AFAIK this means that the return type of the function is a reference to this struct? And faacEncHandle is: typedef struct { unsigned int numChannels; unsigned long sampleRate; ... SR_INFO *srInfo; double *sampleBuff[MAX_CHANNELS]; ... double *freqBuff[MAX_CHANNELS]; double *overlapBuff[MAX_CHANNELS]; double *msSpectrum[MAX_CHANNELS]; CoderInfo coderInfo[MAX_CHANNELS]; ChannelInfo channelInfo[MAX_CHANNELS]; PsyInfo psyInfo[MAX_CHANNELS]; GlobalPsyInfo gpsyInfo; faacEncConfiguration config; psymodel_t *psymodel; /* quantizer specific config */ AACQuantCfg aacquantCfg; /* FFT Tables */ FFT_Tables fft_tables; int bitDiff; } faacEncStruct, *faacEncHandle; So within that struct we see a lot of other types... hmm. Essentially, I'm trying to figure out how to deal with these types in my managed wrapper? Do I need to create versions of these types/structs, in C#? Something like this: [StructLayout(LayoutKind.Sequential)] struct faacEncConfiguration { uint useTns; ulong bitRate; ... } If so then can the runtime automatically "map" these objects onto eachother? And, would I have to create these "mapped" types for all the types in these return types/parameter type hierarchies, all the way down until I get to all primitives? I know this is a broad topic, any advice on getting up-to-speed quickly on what I need to learn to make this happen would be very much appreciated! Thanks!
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, pass it to a function and get some other structure in return. It is OK to use P/Invoke for an odd function call that is not otherwise exposed as .NET API, but for a full blown API wrapper I would highly recommend using managed C++(C++/CLI). It is absolutely unparalleled in creating unmanaged interop layers for .NET. The biggest challenge would be to convert this essentially C interface into an object orientated interface where you call methods off objects, as opposed to calling global functions with structures of all-public members. As you start writing elaborate structure graphs for P/Invoke you would yourself having to deal with quite a bit of "magic" that governs how managed primitive types convert to unmanaged types. Often, using incorrect types will cause a run-time error. With managed C++ (IJW - It Just Works) you define managed structures, classes, interfaces in C++, which allows more natural use of the underlying library and a more native interface to your C# application. This is a great overview of C++/CLI. Also MSDN has extensive documentation for all managed C++ features.
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 hue[4] = {'R','e','d','\0'}; color = hue; info = "Balloons"; text += (term + color + info); cout << endl << text << endl; return 0; }
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 text: text += (term + color + " " + info);
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. What does it mean? I am a newb so the less jargon, the better, thanks!
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->DoSomething(); } The cast converts the pointer to an ISomeInterface pointer into a pointer to a void pointer so that CoCreateInstance() can set ifaceptr to a valid value. Since it is a pointer to a void pointer, the function can output pointers of any type, depending on the interface ID (such as IID_ISomeInterface).
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 do i keep my application running at all times UPDATE bada agent applications alt text http://www.freeimagehosting.net/uploads/1c8b9c134c.jpg
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. Bada platform is not limited to single tasking, bada allows multitasking between base applications such as music player, calendar and so on. So continuously monitoring GPS coordinates is difficult
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; temp = new node; if (listpointer == NULL){ temp->name = newname; temp->next = listpointer; listpointer = temp; }else{ node *add; add = new node; while (true){ if(listpointer->name > newname){ add->name = newname; add->next = listpointer->next; break; } listpointer = listpointer->next; } } } int main(){ A = NULL; string name1 = "bob"; string name2 = "tod"; string name3 = "thomas"; string name4 = "kate"; string name5 = "alex"; string name6 = "jimmy"; addnode(A,name1); addnode(A,name2); addnode(A,name3); addnode(A,name4); addnode(A,name5); addnode(A,name6); while(true){ if(A == NULL){break;} cout<< "name is: " << A->name << endl; A = A->next; } return 0; }
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 = new node; if (listpointer == NULL){ temp->name = newname; temp->next = listpointer; listpointer = temp; }else{ node *add; add = new node; while (true){ if( (listpointer) == NULL){ std:cout << "oops (listpointer) == NULL)"; } if(listpointer->name > newname){ add->name = newname; add->next = listpointer->next; break; } listpointer = listpointer->next; } } } Will print out "oops" then segfault as lispointer is NULL and using -> on a NULL will cause a segfault. This is because in the while (true) loop listpointer eventually reaches the end and gets set to NULL. You then get the segfault. I think a better idea would be to do something like: bool has_inserted; while ( listpointer != NULL){ if(listpointer->name > newname){ add->name = newname; add->next = listpointer->next; has_inserted = true; break; } listpointer = listpointer->next; } if(has_inserted == false){ //insert at end of list } Also this code leaks memory as you don't delete the things you created with new. You may want to run this (and other code) with valgrind to see what I mean.
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 IplImage (img) with sub-image dimensions ( window.height,window.width) Create a new Cvmat (mat) with sub-image dimensions ( window.height,window.width) CvGetSubRect(originalImage,mat,window) seizes the sub-image transform Mat (cvMat) to img (IplImage) using cvGetImage my problem is that for each frame i create new IplImage and cvMat which take a lot of memory and when i try to free the allocated memory I get a segmentation fault or in the case of the CvMat the allocated space does not get free (valgrind keeps telling me its definetly lost space). the following code does it: int main(void){ CvCapture* capture; CvRect window; CvMat * tmp; //window size window.x=0;window.y=0;window.height=100;window.width=100; IplImage * src=NULL,*bk=NULL,* sub=NULL; capture=cvCreateFileCapture( "somevideo.wmv"); while((src=cvQueryFrame(capture))!=NULL){ cvShowImage("common",src); //get sub-image sub=cvCreateImage(cvSize(window.height,window.width),8,3); tmp =cvCreateMat(window.height, window.width,CV_8UC1); cvGetSubRect(src, tmp , window); sub=cvGetImage(tmp, sub); cvShowImage("Window",sub); //free space if(bk!=NULL) cvReleaseImage(&bk); bk=sub; cvReleaseMat(&tmp); cvWaitKey(20); //window dimensions changes window.width++; window.height++; } } cvReleaseMat(&tmp); does not seem to have any effect on the total amount of lost memory, valgrind reports the same amount of "definetly lost" memory if i comment or uncomment this line. cvReleaseImage(&bk); produces a segmentation fault. notice i'm trying to free the previous sub-frame which i'm backing up in the bk variable. If i comment this line the program runs smoothly but with lots of memory leaks i'm using ubuntu 9.10 with opencv 2.0 . I really need to get rid of memory leaks, can anyone explain me how to correct this or even better how to correctly perform image windowing? Thank you
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++) { parser.get(); //Skip period parser >> result[idx]; } } bool LessThanVersion(const std::string& a,const std::string& b) { int parsedA[4], parsedB[4]; Parse(parsedA, a); Parse(parsedB, b); return std::lexicographical_compare(parsedA, parsedA + 4, parsedB, parsedB + 4); } Anything more complicated is going to be harder to maintain and isn't worth your time.
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 draw window" as parent window, not dialog itself. I know I can use ::CreateWindow(...) API to dynamic create a window in code, and specify the custom draw window as parent HWND. But we already has child controls layout in *.rc file, I just want to reuse them, without create HWND again. Thanks, William L.
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, Part 4, Part 5, Part 6, Part 7, Part 8, Part 9) - but it might be overkill for this situation. What is your custom draw window doing anyway?
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 am getting to like using it quite a lot. I am thinking of using SWIG to generate my future PHP extensions. I am using PHP v5.2 (and above) on my production servers. My questions are: Is SWIG PHP interface stable yet (i.e. ready for production)? If you answered yes to question 1 -are YOU using it in YOUR production site? Are there any 'gotchas' I need to be aware of when creating PHP extension ,modules using SWIG?
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 precompiled header** // the precompiled header stdafx.h is included in this line .\MapTest.cpp(186) : fatal error C1020: unexpected #endif but when I add the precompiled header before the include guard, no warning or error is emitted. What is the reason for this?
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 underscore and a capital letter (or double leading underscores) are reserved, which might be causing a name conflict. see this answer for more details.
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 signature in my C# file is not the same as the one from C++ but I really can't see it. First of all this is my unamanged function below: TEngine GCreateEngine(int width,int height,int depth,int deviceType); And here is my function in C#: [DllImport("Engine.dll", EntryPoint = "GCreateEngine", CallingConvention = CallingConvention.StdCall)] public static extern IntPtr CreateEngine(int width,int height,int depth,int device); When I debug into C++ I see all arguments just fine so thus I can only think it's got something to do with transforming from TEngine (which is a pointer to a class named CEngine) to IntPtr. I've used this before in VS2008 with no problem.
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(); // do somthing with the ptr ... // what to do here ? to delete the poinetr or not? delete ptr; // ?? }
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. On the otherhand, getItemPtr might be documented as returning a pointer to a new object which must be deleted, in this case you would need to delete it but a better way to ensure this happens would be to use a smart pointer to ensure that this happens. In your example initializing a std::auto_ptr would be the simplest and most portable way to do this. std::auto_ptr<ptrTmp> ptr( getItemPtr() );
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 { int H; // list height Node *Header; List() { Header = new Node(0, maxH); H = 1; } }; The problem, I think, is in the function that searches for a node with a given value and then deletes it. The function is implemented like this: 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 ) break; else if ( current->link_[i]->info == v ) { // Node *del = current->link_[i]; current->link_[i] = current->link_[i]->link_[i]; // delete del; break; } } } The function works fine as it is, however the list seems to break if I uncomment the two commented lines. By break I mean that the following test code never finishes: int main() { srand((unsigned)time(0)); List *SKL = new List(); for ( int i = 0; i < 1000000; ++i ) Insert(rand() * rand(), SKL); for ( int i = 0; i < 1000000; ++i ) Search(rand() * rand(), SKL); for ( int i = 0; i < 1000000; ++i ) Remove(rand() * rand(), SKL); for ( int i = 0; i < 1000000; ++i ) Insert(rand() * rand(), SKL); return 0; } The problem lies in the last for loop that inserts more values in the list. If those two lines are commented out, the program finishes in about 10 seconds. If I uncomment them, it seems to enter an infinite loop as it doesn't even finish in minutes. I'm not sure if that's the right way of deleting a node from a skip list or not, so I'm posting my insertion function as well: void Insert(int v, List *L) { // this section just determines the levels the new node will be part of int newH = 0; int tmp; unsigned int rnd = rand() * rand(); do { tmp = lookup[rnd & 255]; rnd >>= 8; newH += tmp; } while ( tmp == 8 ); if ( newH >= L->H ) ++L->H; // this does the actual insertion Node *newNode = new Node(v, L->H); 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 ) break; if ( i <= newH ) { newNode->link_[i] = current->link_[i]; current->link_[i] = newNode; } } } So, my questions are: Why does the program break, and how can I make it work while actually deleting the nodes I want to delete from memory? Is this a correct way of implementing skip lists, or am I using a wrong approach?
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 ) { break; } else if ( current->link_[i]->info == v ) { // Node *del = current->link_[i]; current->link_[i] = current->link_[i]->link_[i]; // if (0 == i) delete del; break; } } } } For the sake of example, let's assume that the node we wish to delete appears in 2 levels: 0 and 1. The for loop on levels L->H to 2 does not do anything. On level 1 it will find the node requested, and delete it. On level 0, it will attempt to follow a pointer to the already deleted node, leading to undefined behavior. Solution: Only delete the node when at level 0. As long as your in a upper layer, the node is still referenced and you need to keep it alive.
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 installed the Qt libraries/binaries. In a console, when I type qmake && make, make fails, complaining that 'g++' is not recognized as an internal command. If I type g++ in the same console, I however have the following output: g++: no input files So g++ is definitely recognized. For those who may ask, both the Qt binaries directory and MinGW binaries directory are in the system PATH environment variable. What could be wrong here ?
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 to post the part of the makefile tat causes the problem. Oh, and check that you are actually using GNU make.
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) doesn't do it. So, how can I specify which f() I want?
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 (*)(int)>(&f)); Or, you can also do this: // The compiler will figure out which f to use according to // the function pointer declaration. void (*fpc)(char) = &f; std::for_each(s.begin(), s.end(), fpc); // Uses the void f(char c); overload void (*fpi)(int) = &f; std::for_each(s.begin(), s.end(), fpi); // Uses the void f(int i); overload If f is a member function, then you need to use mem_fun, or for your case, use the solution presented in this Dr. Dobb's article.
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 straight away without fiddling with anything extra. The problem then becomes the fact that my program is compiled with VS 2008 which requires versions of the CRT which I can't guarantee is installed. I'm linking statically to the CRT, which I incorrectly thought would circumvent this problem. I've been thinking of tracking down some older VS version, but I have a feeling this is the incorrect path. I want the program to run on a fresh install of windows xp and above. Grateful for any help.
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 walker (depends.exe) to figure out exactly which dlls use which and who still depends on the dynamic CRT or in any other DLL. Another approach is to run your exe from the debugger and see which DLLs are being loaded in the output window. Which depends.exe gives you only the dlls loaded on the startup, this can give you some additional dependencies that are loaded only on runtime.
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 assigning your process realtime priority. You may also have a look at this: http://msdn.microsoft.com/en-us/library/ms838340(WinEmbedded.5).aspx Several frameworks were developed to do hard realtime on windows. Otherwise, your question probably implies that you might be doing something wrong. There're numerous mechanisms to trick around ever needing precise delays, such as using proper bus drivers (in case of hardware/IO, or respective DMAs if you are designing a driver), and more. Please tell us what exactly are you building.
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 the question)
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 then create the instance with CoCreateInstance. However I have no idea how to get these clsid's! Thanks!
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.Configure, i need to check how many of the derived1Obj, derived2Obj,derived3Obj is active. Should i add this in the "Base" class like a function say, GetNumberOfActive()? And If the implementation is like this: class Imp { public: void Configure() { //Code instantiating a particular Derived1/2/3 Object int GetNumberOfActiveDerivedObj(); baseRef.Configure(int numberOfActiveDerivedClasses); } prive: Derived1 dObj1(true); Derived2 dObj2(false); Derived3 dObj3(true); }; should i calculate the numberOfActive Derived Objects in Imp Class? THanks
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( 0 ); class Base { public: void Configure(); //more stuff }; class Derived1 : public Base, counter<Derived1> { public: void Configure() { std::cout << "num Derived1 objects: "<< counter<Derived1>::objects_alive << std::endl; } }; class Derived2 : public Base, counter<Derived2> { public: void Configure() { std::cout << "num Derived2 objects: " << counter<Derived2>::objects_alive << std::endl; } }; int main (int argc, char* argv[]) { Derived1 d10; d10.Configure(); { Derived1 d11; d11.Configure(); Derived2 d20; d20.Configure(); } Derived1 d12; d12.Configure(); Derived2 d21; d21.Configure(); return 0; } Output: $ g++-4 -pedantic crtp1.cpp -o crtp1 && ./crtp1 num Derived1 objects: 1 num Derived1 objects: 2 num Derived2 objects: 1 num Derived1 objects: 2 num Derived2 objects: 1
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->LineTo(po); PS: First question on SO.
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, for example) - so you would have to maintain a regex database for every possible multimedia player caption. There is a more complicated approach that is harder to code, but which is more efficient. The number of players that are widely used isn't very big, therefore you can enumerate processes in your system using Winapi call and take only players (like mpc.exe or winamp.exe). Then you can easily retrieve the active application window (from it's process handle) and only then invoke your regex search. This is actually much better, because you would only have to store process name - caption regex values in your database. After that (when you've parsed out the name of currently opened file), it's all up to you - I mean storing it at the server, etc, etc.
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 increases over time). Each project has a copy of a few files or of an entire library, not a link into one central place. Sometimes project uses one file, two files, some use everything. Normally, utility functions are included as a copy of every file and SConscript/SConstruct or Visual Studio Project (depending on the situation). Each project has a separate git repository. Sometimes one project is derived from other, sometimes it isn't. You work on every one of them, in random order. There are no other people (to make things simpler) The problem arises when while working on one project you modify those utility function files. Because each project has a copy of file, this introduces new version, which leads to the mess when you try later (week later, for example) to guess which version has a most complete functionality (i.e. you added a function to a.cpp in one project, and added another function to a.cpp in another project, which created a version fork) How would you handle this situation to avoid "version hell"? One way I can think of is using symbolic links/hard links, but it isn't perfect - if you delete one central storage, it will all go to hell. And hard links won't work on dual-boot system (although symbolic links will). It looks like what I need is something like advanced git repository, where code for the project is stored in one local repository, but is synchronized with multiple external repositories. But I'm not sure how to do it or if it is possible to do this with git. So, what do you think?
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, create_britney_spears() returns NULL. This is, as far as I know, a very common pattern. Now I want to wrap this inside a C++ class. //britney_spears.hpp class BritneySpears { public: BritneySpears(); private: boost::shared_ptr<britney_spears> m_britney_spears; }; And here is the implementation: // britney_spears.cpp BritneySpears::BritneySpears() : m_britney_spears(create_britney_spears(), free_britney_spears) { if (!m_britney_spears) { // Here I should throw something to abort the construction, but what ??! } } So the question is in the code sample: What should I throw to abort the constructor ? I know I can throw almost anything, but I want to know what is usually done. I have no other information about why the allocation failed. Should I create my own exception class ? Is there a std exception for such cases ? Many thanks.
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 what() function. You then throw it in your constructor: throw MyError( "failed to create spears object" ); The following is the declaration for the exception class I use in my own utility library: class Exception : public std::exception { public: Exception( const std::string & msg = "" ); Exception( const std::string & msg, int line, const std::string & file ); ~Exception() throw(); const char *what() const throw(); const std::string & Msg() const; int Line() const; const std::string & File() const; private: std::string mMsg, mFile; int mLine; }; #define ATHROW( msg )\ { \ std::ostringstream os; \ os << msg \ throw ALib::Exception( os.str(), __LINE__, __FILE__ ); \ } \ The macro is for conveniently adding the file name and line number, and providing stream formatting for the message. This lets you say things like: ATHROW( "britney construction failed - bad booty value of " << booty );
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 functionality in my own programs? For example, how could I pass a string to a particular instance of a program? Thanks
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 different procedures your app exports (for example play/stop actions), and then in the same application implement a client. This way, if arguments like --play are passed, you don't run the usual code, but just check for an instance of the running app and send a command to your already running program. On the other hand, when no arguments are passed, your program just starts and registers the proper triggers, so that a later called instance can control it. Here is a tutorial on dbus, and the DBus homepage
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: testApp.h: vector<videoObject> videoObjects; vector<videoObject>::iterator itVid; testApp.cpp: // Get the videoObject which relates to the user event for(itVid = videoObjects.begin(); itVid != videoObjects.end(); ++itVid) { if(videoObjects.at(itVid - videoObjects.begin()).isInside(ofPoint(tcur.getX(), tcur.getY()))) { videoObjects.erase(itVid); } } This should be so simple but I just don't see where I'm taking the wrong turn.
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 is the vector end if the operation erased the last element in the sequence. Update: the way you access the current element inside your condition looks rather strange. Also one must avoid incrementing the iterator after erase, as this would skip an element and may cause out-of-bounds errors. Try this: for(itVid = videoObjects.begin(); itVid != videoObjects.end(); ){ if(itVid->isInside(ofPoint(tcur.getX(), tcur.getY()))){ itVid = videoObjects.erase(itVid); } else { ++itVid; } }
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 programatically, in C++ (no Javascript hacks)? Update: I tried to call HRESULT IWebFrame::setAllowsScrolling(BOOL flag). To get an IWebFrame interface, I called HRESULT IWebView::mainFrame(IWebFrame **frame). This doesn't seem to work. Scrollbars still appear. What am I doing wrong? Is it not the main frame my main interest here? Update: I tried enabling flat frame mode like this: IWebPreferences *Preferences; hr = pWebView->preferences(&Preferences); if (FAILED(hr)) goto exit; IWebPreferencesPrivate *PrivatePreferences = 0; hr = Preferences->QueryInterface(IID_IWebPreferencesPrivate, (void **)&PrivatePreferences); if (FAILED(hr)) goto exit; hr = PrivatePreferences->setFrameSetFlatteningEnabled(TRUE); if (FAILED(hr)) goto exit; The code runs fine but nothing seems to happen. What am I doing wrong here? Update: I've received the suggestion that I might include WS_VSCROLL when creating the main window. This is not the case: MainWindow = CreateWindow( WindowClass, WindowTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, iPhoneXRes + 16 + 20, iPhoneYres + 110, NULL, NULL, hInstance, NULL ); Thanks,
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 time, and the errors stopped. so, i figure its a timing issue of some kind. I trace through until i find what i suspect is the culprit. A call to ShellExecute(...), that terminates an image editor i use. (http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx) Now, if I step past this call, and then continue to run the program, everything works fine, but if I just run past this line, the error occurs. how can this be? I have a call to SetFocus() at the very end of this method. shouldnt the program hit this no matter what? This is all so very frustrating...
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 concurrently with yours. Note that ShellExecute is an asynchronous function. It returns immediately after creating the process, and from now on your application and the process you've created run concurrently. Now, since only one window in the system may have a focus at a time - it's very likely that the process you've created just steals the focus from you. In order to avoid this - you should first wait for that process to finish working, and only then restore the focus to your window and continue working. For this you have to obtain the handle of the created process, and call a Win32 waiting function on it. ShellExecute doesn't return you the handle of the created process. However ShellExecuteEx - does. BTW it also allows you to launch a process with instruction for it not to show the UI, if this is what you want. You should write it like this: SHELLEXECUTEINFO sei; memset(&sei, 0, sizeof(sei)); sei.cbSize = sizeof(sei); sei.fMask = SEE_MASK_NOCLOSEPROCESS; sei.lpFile = L"notepad.exe"; sei.nShow = SW_SHOWNORMAL; // or SW_HIDE if you don't want to show it if (ShellExecuteEx(&sei)) { // wait for completion WaitForSingleObject(sei.hProcess, INFINITE); CloseHandle(sei.hProcess); } This should be helpful P.S. Of course you should close the handle of the created process. That is, CloseHandle must be called after WaitForSingleObject.
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 look at it as well.
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: // got virtual and non-virtual functions, working with these memebers virtual void func1(); void func2(); // no inline functions or friends }; Does changing the order of private data members breaks ABI in this case? class A { string str; static const int static_const_number; int number; // <-- integer member moved here bool b; ... }; Edit The types are not changed, only the order of the members. No bit flags are used as well. The code is used as shared library, there's no static linking to this code. I'm on Linux and the compilers are gcc-3.4.3 and gcc-4.1
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 was thinking, would it be fastest to make a VBO with vertices for the sides of the texture with no offset included so I can then use glTranslate, glScale and glRotate to move the drawing position for my texture. Then I can use the same VBO with no changes to draw the texture each time. I could only change the VBO when I need to add coordinates for the rounded corners. Is that the best way to do this? What things should I look out for while doing it? Is it really fastest to use GL_TRIANGLES instead of GL_QUADS in modern graphics cards? Thank you for any answer.
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. The most important bottleneck here is to transfer per-vertex data (such as color, position AND texture coordinate(s)) to GPU, and that's what vertex buffer objects on the GPU can greatly help. If the mesh that you want to draw to screen is static, that is, you set it once and do not need to modify (parts of) it later, you can generate the texture coordinates for the entire mesh, including all corners) only once. You can later modify texture coordinates for the entire mesh using texture matrix multiplier. However, if you want to modify different parts of the mesh using different transformations, you will have to divide the mesh into parts. From what you have described, I understand that you want to draw a rounded-corner rectangle which holds a picture inside, which can be accomplished using a single static mesh (a list of per-vertex data). Lastly, GL_QUADS are also deprecated in modern OpenGL specifications. They do not offer much functionality anyway, so you should switch QUADS to triangles or triangle strips/fans.
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): x ? true : false It got me thinking. Can we replace anything else incase it's more readable. So those are the ones I can think of off the top of my head for the if statement and doing comparisons. So I'm wondering what about how to replace looping constructs like for, while, etc. How would you replace a while loop for example (without using a for loop). It's probable that it can't be done in these languages? while (a < b) { }
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 but I cannot assign it to input? Thanks
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 once you've declared it. After the declaration the reference behaves as if it is the object referenced to itself. So using operator= on it tries to copy into it.
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 macro ARRAY_COUNTOF uses the fact that the size of a function is the size of it's returned type. It works just fine. However, when I tried to check if it's portable, I didn't find any evidence for that. I couldn't find any reference to sizeof(function reference) in the standard (14882/1998) and, in fact, I am not entirely sure I am allowed to even create a function reference any more (although the standard does mention it several times). So, does someone know where in the standard I should look? (Or, if I misinterpreted the declaration some how, what is the correct interpretation?) Thanks Oren P.S. (for those of you who think I didn't find the appropriate solution for my problem) I know I can always use #define ARRAY_COUNTOF sizeof(arr)/sizeof(arr[0]) or even template <typename T, unsigned N> size_t arrayCountof(T(&)[N]) {return N;} but the first will not check if arr is a array (or pointer) and the second is not usable inside static_assert. (and I would have used std::tr1::array or std::vector, but this is a legacy code I am maintaining)
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 either an expression, which is not evaluated, or a parenthesized type-id. In other words, it yields the size of a type in bytes or finds the type of an expression and yields the size of that. We don't have a type, we have the expression arrayCountofHelper(arr). You can dissect this expression by looking at the definitions of primary-expression and postfix-expression as defined in §5.1 and §5.2 respectively. You will find it is a postfix-expression and fits the requirements of a function call (§5.2.2). Now back to sizeof. We only care about the type of this function call expression (so we can yield the size of it), and §5.2.2/3 says: The type of the function call expression is the return type of the statically chosen function [...]. This type shall be a complete object type, a reference type or the type void. So we need to find the return type of the function that would be called (remember, this is all unevaluated) with arrayCountofHelper(arr). arrayCountofHelper is a function template which we would be instantiating (§14.7), so we need to do that before we have an instantiated function to get the return type of. All the template parameters need to have values (§14.8.2), and by using the rules defined in §14.8.2.1 we will find T and N by matching the array passed to the function with the functions parameter (which is a reference to an array). (For example, if arr was int[10], T would be int and N would be 10.) Once we have those, the function can be instantiated. Once instantiated, the return type of the function would be char(&)[N]*, a reference to an array of N char's. (If you need help parsing, see §8.3.5. There are also questions on SO on how to parse "complex" types.) So now we've found the type of the expression, we must take the size of it. §5.3.3/2 defines how sizeof works with references and arrays (emphasis mine): When applied to a reference or a reference type, the result is the size of the referenced type. When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array. The size of a most derived class shall be greater than zero (1.8). The result of applying sizeof to a base class subobject is the size of the base class type.70) When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element. The size of a reference type is the size of its referenced type, so we need to size of char[N]. The size of this is N * sizeof(char). char is fundamental as it is the smallest type there is; that is, sizeof(char) is always one. (§5.3.3/1) So the size yielded by this expression is 1 * N, or what we wanted the whole time: N. And that's how it works. The reason this one is preferred over your last example of arrayCountof is because the result of sizeof is a constant expression, so can be used in places where a constant expression is required. It should be noted that in C++0x, we can get our clean no-macro syntax with: template <typename T, unsigned N> constexpr size_t arrayCountof(T(&)[N]) {return N;} * The reason the function return type is a reference to an array and not an array is simply because you cannot return arrays. If you could, either choice would suffice.
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 namespaces because: vector<int>::iterator Would appear to be an iterator from the namespace vector, but namespaces are another topic which I'm not familiar with. Mainly I'm asking what would it involve to implement an iterator such that it could be referenced in a similar way to the stl iterators. I'm also aware that I could use boost.iterators or something similar to save myself a lot of work, but I'm more interested in learning all of the details that go into something like this.
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++(); operator==(const TYPE &other); If you want an iterator that can fully participate with the rest of the STL, there are other things you need to do such as give it a category.
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 external function will carry the same name as the builtin, with an additional suffix `_n' where n is the size of the data type. Basically this says that it's safe to use these builtins. They will generate either direct instruction sequence if supported, or a call to an emulation function by the given name. The compiler will warn you if particular builtin is not supported, so it's easy to experiment. And since these originally come from Intel specs, it's safe to assume they are there on x86 and x86_64.
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 almost all simulation software, deals with a lot of floats. My question is: Is there some issue of endianness when dealing with binary formats of floating point numbers? I know that all the machines where my code will run use IEEE implementation of floating points, but is there some endianness issue when dealing with floats? Since I only have access to machines with the same endian, I cannot test this by myself. So, I'll be glad if someone can help me with this.
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, but, how/why does it affect badly, or in other words - why telling the compiler that it can assume no aliasing would get me a "tighter code"
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 reload the memory pointed to by b into a register as long as the compiler knows nothing has used b to modify it. If aliasing is allowed it's possible there's another pointer char* c = b; that was used elsewhere to mess with that memory
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 of pointers to their objects. The problem is when I try to access the result vector form outside the objects. In one case I can get the elements (which are simply pointers), in the other I cannot, the vector is empty. Code: class E; class A{ protected: vector<E*> _result; public: virtual void execute()=0; vector<E*> get_result(); }; vector<E*> A::get_result() { return _result; } class B : public A { public: virtual void execute(); }; B::execute() { //... _result = tempVec; return; } class C : public A { public: virtual void execute(); }; C::execute() { //different stuff to B _result = tempvec; return; } main() { B* b = new B(); C* c = new C(); b->execute(); c->execute(); b->get_result();//returns full vector c->get_result(); //returns empty vector!! } I have no idea what is going on here... I have tried filling _result by hand from a temp vector in the offending class, doing the same with vector::assign(), nothing works. And the other object works perfectly. I must be missing something.... Any help would be greatly appreciated.
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 find liblo for OSC, exiting!' Exit(1) if not guiconf.CheckLibWithHeader('fltk', 'FL/Fl.H','c++'): print 'Did not find FLTK for the gui, exiting!' Exit(1) Unfortunately, on my (Gentoo Linux) system, and many others (Linux distributions) this can be quite troublesome if the package manager allows the simultaneous install of FLTK-1 and FLTK-2. I have attempted to modify the SConstruct file to use fltk-config --cflags and fltk-config --ldflags (or fltk-config --libs might be better than ldflags) by adding them like so: guienv.Append(CPPPATH = os.popen('fltk-config --cflags').read()) guienv.Append(LIBPATH = os.popen('fltk-config --ldflags').read()) But this causes the test for liblo to fail! Looking in config.log shows how it failed: scons: Configure: Checking for C library lo... gcc -o .sconf_temp/conftest_4.o -c "-I/usr/include/fltk-1.1 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_THREAD_SAFE -D_REENTRANT" gcc: no input files scons: Configure: no How should this really be done? And to complete my answer, how do I remove the quotes from the result of os.popen( 'command').read()? EDIT The real question here is why does appending the output of fltk-config cause gcc to not receive the filename argument it is supposed to compile?
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 is installed !?' sys.exit(1)
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::InitWindow() { } main.cpp #include "stdafx.h" #include "GameProject1.h" #define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { code..... #endif dont know what's going on. The error I get is 1>c:\users\numerical25\desktop\intro todirectx\gameproject\gameproject1\gameproject1\enginuity.cpp(1) : warning C4627: '#include "Enginuity.h"': skipped when looking for precompiled header use 1> Add directive to 'stdafx.h' or rebuild precompiled header 1>c:\users\numerical25\desktop\intro todirectx\gameproject\gameproject1\gameproject1\enginuity.cpp(8) : fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?
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 source (.cpp) file.
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 have the C++ algorithms chime back into the script with callbacks in python. Something like: myObject = MyObject() myObject.setCallback(myCallback) myObject.run() def myCallback(val): """Do something with the value passed back to the python script.""" pass Will this be possible? How can I run a callback in python from a loop that is running in a C++ module? Anyone have a link or a tutorial to help me do this correctly?
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://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock): Beginning with version 2.3, threads can now take advantage of the PyGILState_*() functions to do all of the above automatically. The typical idiom for calling into Python from a C thread is now: PyGILState_STATE gstate; gstate = PyGILState_Ensure(); /* Perform Python actions here. */ result = CallSomeFunction(); /* evaluate result */ /* Release the thread. No Python API allowed beyond this point. */ PyGILState_Release(gstate) I recommend making the callbacks short & sweet - to limit the need to perform exception handling in C++ code. If you're using wxPython, you could use it's robust async event system. Or the callbacks could put events on a Queue and you could have a thread devoted to asynchronously executing callback/event code. Even with Boost.Python magic, you'll have to get familiar with this portion of the Python C API when dealing with threads. (Don't forget to wrap the C++ functions with Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS to release the GIL!)
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) * (180.0 / PI); After to know the angle I calculate the following: double angle = abs(theta2 - theta1); The problem or doubt that I have is: sometimes I get the correct angle but sometimes I get the complementary angle (for me outer). How can I know when subtract 180º to know the inner angle? There is any algorithm better to do that? Because I tried some methods: dot product, following formula: result = (m1 - m2) / (1.0 + (m1 * m2)); But always I have the same problem; I never known when I have the outer angle or the inner angle!
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*dy31 ); float theta = acos( (dx21*dx31 + dy21*dy31) / (m12 * m13) ); Answer is in radians. EDIT: Here's a complete implementation. Substitute the problematic values in p1, p2, and p3 and let me know what you get. The point p1 is the vertex where the two lines intersect, in accordance with your definition of the two lines. #include <math.h> #include <iostream> template <typename T> class Vector2D { private: T x; T y; public: explicit Vector2D(const T& x=0, const T& y=0) : x(x), y(y) {} Vector2D(const Vector2D&ltT>& src) : x(src.x), y(src.y) {} virtual ~Vector2D() {} // Accessors inline T X() const { return x; } inline T Y() const { return y; } inline T X(const T& x) { this->x = x; } inline T Y(const T& y) { this->y = y; } // Vector arithmetic inline Vector2D<T> operator-() const { return Vector2D<T>(-x, -y); } inline Vector2D<T> operator+() const { return Vector2D<T>(+x, +y); } inline Vector2D<T> operator+(const Vector2D<T>& v) const { return Vector2D<T>(x+v.x, y+v.y); } inline Vector2D<T> operator-(const Vector2D<T>& v) const { return Vector2D<T>(x-v.x, y-v.y); } inline Vector2D<T> operator*(const T& s) const { return Vector2D<T>(x*s, y*s); } // Dot product inline T operator*(const Vector2D<T>& v) const { return x*v.x + y*v.y; } // l-2 norm inline T norm() const { return sqrt(x*x + y*y); } // inner angle (radians) static T angle(const Vector2D<T>& v1, const Vector2D<T>& v2) { return acos( (v1 * v2) / (v1.norm() * v2.norm()) ); } }; int main() { Vector2D<double> p1(215, 294); Vector2D<double> p2(174, 228); Vector2D<double> p3(303, 294); double rad = Vector2D<double>::angle(p2-p1, p3-p1); double deg = rad * 180.0 / M_PI; std::cout << "rad = " << rad << "\tdeg = " << deg << std::endl; p1 = Vector2D<double>(153, 457); p2 = Vector2D<double>(19, 457); p3 = Vector2D<double>(15, 470); rad = Vector2D<double>::angle(p2-p1, p3-p1); deg = rad * 180.0 / M_PI; std::cout << "rad = " << rad << "\tdeg = " << deg << std::endl; return 0; } The code above yields: rad = 2.12667 deg = 121.849 rad = 0.0939257 deg = 5.38155
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 local area network far removed. Ask more questions about it at superuser.com
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=fRand(.5);color[i][0].b=fRand(); ...etc
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 to me but are not exactly what they seem. The interface I know of are like contracts. They are objects that have only method declarations, with no body. All classes that implement an interface must include the methods of the interface. The interface I hear about in COM seems to be just pointers. They can not retrieve objects directly but only can retrieve objects through the means of a method. Is this what a COM Interface is ?? If so, then why did they give them the same names if they are completely different. Also I just wanted to add that headers in C++ kind of remind me of the C# Interfaces. Not sure if their are any relations. But anyways, I am just trying to clear that up.
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 methods of IUnknown. A COM interface has the AddRef and Release methods to take care of memory managed, using reference counting. A non-issue in C# because the garbage collector take care of it. And COM doesn't support inheritance. Not an issue in C#, if you want to obtain an interface pointer then you simply cast the object reference. It has to be done explicitly in COM with the IUnknown::QueryInterface() method. There is some support in COM for object re-use, implemented by aggregation. It is so obtuse that few ever implement it.
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 any possible path, i.e execution paths 1, 2 & 3 in the code above. I thought about having a global function, vector and a macro. This macro would simply call that function, passing as parameters the source file name and the line of code, and that function would mark that as "checked", by inserting to the vector the info that the macro passed. The problem is that I will not see anything about paths that did not "check". Any idea how do I do this? How to "register" a line of code at compile-time, so in run-time I can see that it didn't "check" yet? I hope I'm clear.
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 once. C2 - every path is executed at least once So even if your tests shows 100% C0 coverage you may not catch every path in code - and probably you don't have time to do it (number of paths grows exponentially with respect to branches). However it is good to know if you have 10% C2 or 70% C2 (or 0.1% C2).
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 alternative for dynamically allocated arrays? Thanks in advance.
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 auto_ptr then you don't need the reference counting and ownership model of shared_array. So just use a std::vector as they are tailored to replace dynamically allocated arrays which is really what you are trying to manage with the use of auto_ptr.
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). Ideally I'd use Xcode but I'm not even sure if you can manually upgrade the compiler for Xcode. Is this possible? Otherwise, what is the best way to install a different version of GCC that doesn't interfere with the rest of the system?
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_size = _tcslen(xxx) * sizeof(TCHAR) This will not work. All it will guarantee is that the string copied is not longer than whatever is already in the buffer. If the buffer has not been initialized, it will fail; if the buffer begins with a '\0', nothing will be copied; and so forth.
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 the installation path. Therefore, I was wondering if there is a way to get the application path [where the application is located] and set it so that when another program executes from another path everything might work properly...? [Using C++ without .NET Framework] Thanks.
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->setDynamicSortFilter(true); setSourceModel(createMailModel(parent)); ui.treeView->setModel(proxyModel); ui.treeView->setSortingEnabled(true); ui.treeView->sortByColumn(4, Qt::DescendingOrder); // and my signal/slot looks like this but its not working //and im not getting eny clicked event fired connect(ui.treeView,SIGNAL(Clicked(const QModelIndex& ) ), this,SLOT( treeViewSelectedRow(const QModelIndex& ) ) ); also how can i debug QT signal/slots so i can see some debug massages printing when something is wrong ?
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 bindB(int number, int number2) { std::cout << "1 " << number << "2 " << number2 << std::endl; } }; template < class Han > struct Wrap_ { Wrap_(Han h) : h_(h) {} template<typename Arg1, typename Arg2> void operator()(Arg1 arg1, Arg2 arg2) { h_(arg1, arg2); } Han h_; }; template< class Handler > inline Wrap_<Handler> make(Handler h) { return Wrap_<Handler> (h); } int main() { A a; B b; ((boost::bind)(&B::bindB, b, _1, _2))(1, 2); ((boost::bind)(&A::bindA, a, make(boost::bind(&B::bindB, b, _1, _2))))(); /*i want compiled success and execute success this code*/ }
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. Incidentally in the example I use boost::function (the sister library to bind) to specify what type of function pointers are being used. I think this makes it far more readable and would highly recommend that you become familiar with it if you are going to continue using bind. #include "boost/bind.hpp" #include "boost/function.hpp" int main(int c, char** argv) { A a; B b; typedef boost::function<void(int, int)> BFunc; typedef boost::function<void(BFunc)> AFunc; BFunc bFunc( boost::bind(&B::bindB, b, _1, _2) ); AFunc aFunc( boost::bind(&A::bindA<BFunc>, a, make(bFunc)) ); bFunc(1,2); }
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 fine if the string is all one word, but the second I add a space (IE: aeio aatest) it will only count the first block and count the space as a consonant, and quit reading the sentence (exiting the for loop or something). Does a space count as no character == null? Or some oddity with std::string?, It would be helpful to know why that is happening! EDIT: I'm simply accepting the string through std::cin, such as: std::string analyse = ""; std::cin >> analyse;
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. You might also want to look at an answer I posted to a previous question (provides some alternatives to 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, which has 2 fields: (uchar) keyCode and (bool) isDown. Here's the interesting part: I generate an EventKey event using the following syntax: Event evt = EventKey(15, true); and I ship it to the handlers: EventDispatch::sendEvent(evt); // void EventDispatch::sendEvent(const Event &event); (EventDispatch contains a linked list of IHandlers and calls their onEvent(const Event &event) method with the parameter containing the sent event. Now the actual question: Say I want my handlers to poll the events in a queue of type Event, how do I do that? Dynamic pointers with reference counting sound like too big of a solution. Making copies is more difficult than it sounds, since I'm only receiving a reference to a base type, therefore each time I would need to check the type of event, upcast to EventKey and then make a copy to store in a queue. Sounds like the only solution - but is unpleasant since I would need to know every single type of event and would have to check that for every event received - sounds like a bad plan. I could allocate the events dynamically and then send around pointers to those events, enqueue them in the array if wanted - but other than having reference counting - how would I be able to keep track of that memory? Do you know any way to implement a very light reference counter that wouldn't interfere with the user? What do you think would be a good solution to this design?
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 aOtherKey) : BarBC(aKey), mOtherKey(aOtherKey) // Compile error here }; }; I am getting a compilation error at the point indicated: error: class `Foo::Bar' does not have any field named `mOtherKey'. Can anyone explain this? I suspect it's a syntactical problem due to my Bar class being defined within the Foo class, but can't seem to find a way around it. This is simple public inheritance, so mOtherKey should be accessible from the Bar constructor. Right? Or is it something to do with the fact that mOtherKey is const and I have already initialised it to 0 in the BarBC constructor?
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), mOtherKey(otherKey) {} // ... }; struct Bar : public BarBC { Bar(uint32_t aKey, uint32_t aOtherKey) : BarBC(aKey, aOtherKey) {} };
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; ++loop ) { picker1 = rand() % 8 + 1; picker2 = rand() % 8 + 1; ssPIN << picker1; ssBN << picker2; } /* Convert them */ ssPIN >> pin; ssBN >> bankNum; CCard card( pin, bankNum ); return card; } that creates a new CCard variable and returns it to the caller CCard card = newCard(); My teacher advised me that doing this is a violation of OOP principles and has to be put in the class. He told me to use this method as a constructor. Which I did: CCard::CCard() { m_Sperre = false; m_Guthaben = rand() % 1000; /* Work */ /* Convert them */ ssPIN >> m_Geheimzahl; ssBN >> m_Nummer; } All variables with m_ are member variables. However, the constructor works when I initialize the card normally CCard card(); at the start of the program. However, I also have a function, that is supposed to create a new card and return it to the user, this function is now broken. The original command: card = newCard(); isn't available anymore, and card = new CCard(); doesn't work. What other options do I have? I have a feeling using the constructor won't work, and that I probably should just create a class method newCard, but I want to see if it is somehow at all possible to do it the way the teacher wanted. This is creating a lot of headaches for me. I told the teacher that this is a stupid idea and not everything has to be classed in OOP. He has since told me that Java or C# don't allow code outside of classes, which sounds a little incredible. Not sure that you can do this in C++, especially when templated functions exist, or generic algorithms. Is it true that this would be bad code for OOP in C++ if I didn't force it into a class? EDIT: I would like to thank everyone for their helpful answers! However, I believe that my phrasing of the question is a little screwed up, and I think people don't understand what I am looking for. I do not want to initialize another member of type CCard. I want to intitialize CCard card once and then give card new values through the constructor, because this is what the teacher told me to do. I do not want to create a new CCard object, just use the same variable with new values over again. This is why I said it probably won't work with the constructor. So I have a function that is supposed to take the initialized variable card and then call the constructor again( "What?" is what I told the teacher ) and then give it new values. Example code: void foo() { /* Initialize card with constructor */ CCard card; /* Give it new values through the constructor AGAIN... */ card; } This is the actual question. I'm sorry if I confused everybody xD
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 be initialized correctly. The expression new CCard() dynamically creates a CCard object and "returns" a pointer to a CCard object which you would then need to delete. I don't recommend using this until you've successfully created and understood using local objects first. EDIT in response to question edit A constructor can only be called once in an object's lifetime so you can't ever 're-construct' an object. If your class is assignable, though, you can typically assign it the value of a default constructed temporary: card = CCard();
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]; memcpy(arr, (BYTE*)wav, me); Didnt work. Thanks Roey
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. But (1) what you have to do to read from a serial connection, and (2) what you need to do between consecutive reads, and (3) how to do it are all platform dependent. Looking at some Microsoft Documentation, you don't have to "clear the port" at all. But when a flag is set to signal something -- for instance that an error occurred -- then you need to reset the flag before continuing. Of course you reset the flag after handling whatever the flag was meant to signal.
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 assuming it's some sort of cache in the application that gets populated when the document loads but not freed when the document is closed. Which methods or tools could I use to find out where these allocations are being made? UPDATE: Following Hans's post I added a loop to the app to repeatedly open and close documents. I found that there was an initial jump in memory usage ('Private Bytes' as reported by Process Explorer) after loading the first couple of documents, but then it no longer increased every time. So this suggests that there are no new allocations, and the apparent increase is likely to be mostly due to an artefact of paging. I've also taken a closer look at Instruments on the mac, which was useful for seeing where allocations were happening: create an Instrument composed of the Allocations and Leaks tools then add a heap snapshot at the start and end of a cycle and in the Heapshots list it'll show all the allocation deltas relative to the last snapshot. This suggests that on the Mac the memory allocations were increasing but it was due to internal caches such as CoreGraphics drawing, over which we have little control.
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 working set pre-emptively, on Windows for example when the app's windows are minimized. If it is actually virtual memory pages you've measured: that's normal too. After you release the memory, the heap blocks are added to the list of free blocks, ready to be used by the next memory allocation. If releasing the memory happens to free an entire range of pages then the memory manager has an opportunity to unmap that range. It doesn't happen often and its an implementation detail of your memory manager how aggressively it does so.
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("%d,"), nPlayerId); assert(nWritten >= 0 ); pTmp += nWritten; } *pTaskPlayers = '\0'; If during testing the assert never hits, can I be sure that it will never hit in live code? That is, do I need to check if nWritten < 0 and handle that, or can I safely assume that there won't be a problem? Under which circumstances can it return -1? The documentation more or less just states "If the function fails". In one place I've read that it will fail if it can't match the arguments (i.e. the formatting string to the varargs) but that doesn't worry me. I'm also not worried about buffer overrun in this case - I know the buffer is big enough.
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 that the operator way edit the flight plan while the simulation is running. The aircraft model most of the time only needs to read-acess the flight plan object which at first thought calls for simply passing a const reference. But ocassionally the aircraft will need to call AdvanceActiveWayPoint() to indicate a way point has been reached. This will affect the Iterator returned by function ActiveWayPoint(). This implies that the aircraft model indeed needs a non-const reference which in turn would also expose functions like AppendWayPoint() to the aircraft model. I would like to avoid this because I would like to enforce the useage rule described above at compile time. Note that class WayPointIter is equivalent to a STL const iterator, that is the way point can not be mutated by the iterator. class FlightPlan { public: void AppendWayPoint(const WayPointIter& at, WayPoint new_wp); void ReplaceWayPoint(const WayPointIter& ar, WayPoint new_wp); void RemoveWayPoint(WayPointIter at); (...) WayPointIter First() const; WayPointIter Last() const; WayPointIter Active() const; void AdvanceActiveWayPoint() const; (...) }; My idea to overcome the issue is this: define an abstract interface class for each usage role and inherit FlightPlan from both. Each user then only gets passed a reference of the appropriate useage role. class IFlightPlanActiveWayPoint { public: WayPointIter Active() const =0; void AdvanceActiveWayPoint() const =0; }; class IFlightPlanEditable { public: void AppendWayPoint(const WayPointIter& at, WayPoint new_wp); void ReplaceWayPoint(const WayPointIter& ar, WayPoint new_wp); void RemoveWayPoint(WayPointIter at); (...) }; Thus the declaration of FlightPlan would only need to be changed to: class FlightPlan : public IFlightPlanActiveWayPoint, IFlightPlanEditable { (...) }; What do you think? Are there any cavecats I might be missing? Is this design clear or should I come up with somethink different for the sake of clarity? Alternatively I could also define a special ActiveWayPoint class which would contain the function AdvanceActiveWayPoint() but feel that this might be unnecessary. Thanks in advance!
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 add IFlightPlanFoo interface ? There is a risk that you will soon face an imbroglio in the inheritance. The traditional approach is to create another object, a Proxy, and use this object to adapt/restrict/control the usage. It's a design pattern: Proxy Here you would create: class FlightPlanActiveWayPoint { public: FlightPlanActiveWayPoint(FlightPlan& fp); // forwarding void foo() { fp.foo(); } private: FlightPlan& mFp; }; Give it the interface you planned for IFlightPlanActiveWayPoint, build it with a reference to an actual FlightPlan object, and forward the calls. There are several advantages to this approach: Dependency: it's unnecessary to edit flightPlan.h each time you have a new requirement, thus unnecessary to rebuild the whole application It's faster because there is no virtual call any longer, and the functions can be inlined (thus amounting to almost nothing). Though I would recommend not to inline them to begin with (so you can modify them without recompiling everything). It's easy to add checks / logging etc without modifying the base class (in case you have a problem in a particular scenario) My 2 cents.
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, &iBytesRead, NULL); printf("Data Recieved Through Serial port and no. of Bytes Recieved is %d",iBytesRead); }
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? Something along the lines of the defined operator in Python, I suppose. (But correct me if I'm wrong.) I thought of modifying the class and the c-tors the following way: class A { public: A () : defined(false) {} A (double val) : m_val(val), defined(true) {} ~A () {} private: double m_val; bool defined; }; How do you rate this solution? Any suggestion? TIA, Chris
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 () {} private: double m_val; };
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 myclass { static shared_ptr<int> ptr; myclass() { ptr = shared_ptr<int>(NEW int); } } myclass_instance; shared_ptr<int> myclass::ptr; int main() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)); return 0; }
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() { cerr << "dtor" << endl; } }; struct A { static shared_ptr<R> ptr; A() { ptr = shared_ptr<R>(new R); } }; shared_ptr<R> A::ptr; static A a; int main() { } It prints: ctor dtor
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/O Transactions Keeping the Hard Drive Spinning Parsing Memory Is Faster I improved the performance of one application from 65 minutes down to 2 minutes, by appling these techniques. Reduction of I/O Transactions Reducing the I/O transactions results in few calls to the operating system, reducing time there. Reducing the number of branches in your code; improving the performance of the instruction pipeline in your processor. And also reduces traffic to the hard drive. The hard drive has less commands to process so it has less overhead. Keeping the Hard Drive Spinning To access a file, the hard drive has to ramp up the motors to a decent speed (which takes time), position the head to the desired track and sector, and read the data. Positioning the head and ramping up the motor is overhead time required by all transactions. The overhead in reading the data is very little. The objective is to read as much data as possible in one transaction because this is where the hard drive is most efficient. Reducing the number of transactions will reduce the wait times for ramping up the motors and positioning the heads. Although modern computers have caches for both data and commands, reducing the quantity will speed things up. Larger "payloads" will allow more efficient use of the their caches and not require overhead of sorting the requests. Parsing Memory Is Faster Always, reading from memory is faster than reading from an external source. Reading a second line of text from a buffer requires incrementing a pointer. Reading a second line from a file requires an I/O transaction to get the data into memory. If your program has memory to spare, haul the data into memory then search the memory. Too Much Data Negates The Performance Savings There is a finite amount of RAM on the computer for applications to share. Accessing more memory than this memory may cause the computer to "page" or forward the request to the hard drive (as known as virtual memory). In this case, there may be little savings because the hard drive is accessed anyway (by the Operating System without knowledge by your program). Profiling will give you a good indication as to the optimum size of the data buffer. The application I optimized was reading one byte at a time from a 2 GB file. The performance greatly improved when I changed the program to read 1 MB chunks of data. This also allowed for addition performance with loop unrolling. Hope this helps.
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 to a register, and problem solved in a nice efficient fashion. These registers will also never need backing, since there's nothing function-dependent about them, and they'll grow in perfect accordance with my stack. It had just never occurred to me that I could push values into them without pushing an equivalent value into the stack. The absolutely hideous template mess this is turning into for simple design concepts though is making me extremely unhappy. Want to buy: static if and variadic templates.
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 someone help me.
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 loaded, breakpoints get loaded. The reason why "additional dlls" setting is needed here is because you in-proc server doesn't get loaded until an instance of his is CoCreated. So the debugger doesn't load its PDB file and the source files are treated as unknown text files, so the breakpoints in them get inactive (white).
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 the way VS2010 invokes 2005's compiler and noticed some differences to the way VS2005 invokes it. So I started deleting those differences one by one while trying to compile after every try, and once I removed the /Gd flag, the file compiled successfully. Looking at the compiler docs, this flag controls the calling convention and sets it to __cdecl, which is the default. Only difference is in VS2005 it's omitted but VS2010 decides to add it to the command line, resulting in the crash. Has anyone encountered this, or knows of a way around this issue? I can't seem to figure out a way to make VS2010 drop /Gd from the command line, even though it's the default. Only thing I could find is how to add parameters, not remove. Thanks.
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 the IDE invokes the compiler without any /Gx switch - at least that's what the "Command Line" branch shows. It might be a good idea to boil your problem down to a repro case and contact MS support supplying that. They might already have a hotfix for that problem, and if they haven't, they might be able to produce one in relatively short time. Contacting support due to a bug in their software used to be free of charge (and when a compiler crashes instead of issuing a meaningful message that's always a compiler bug).