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,399,644
2,400,673
What does DetourAttach(&(PVOID &)BindKeyT, BindKeyD); mean? Attaching a detour to a memory address
This is just a simple question. I've been reading the source of something which attaches to a memory address of a subroutine using DetourAttach(&(PVOID &)BindKeyT, BindKeyD); where BindKeyT is the address to a subroutine in memory. I'm curious, what exactly does (&(PVOID &) mean in english? I understand that PVOID is a...
Terry Mahaffey is right, what you are passing is a pointer to a pointer to the function. This is commonly used whenever the function you are passing the pointer to (in this case, DetourAttach) wants to return more than one value, and one of those returned values is a pointer. Since functions in C/C++ can only return a ...
2,399,744
2,399,755
Root base class in C++
Every object in .NET inherits (directly or indirectly) from the common root base "Object". Is there such a common object root in C++? How do I pass any object to a function? public void DoSomeStuff(object o) { ... } EDIT: To clarify, the purpose: In that function I want to invoke a pointer to member function. For that...
There is no common root class. Use either void* to pass any object into a function, or better define some base class.
2,400,083
2,400,124
Open source libraries for sound effects in games
does aybody know about an open source sound library in C++ or some other popular language that can be used in open source games for recreating sounds and especifically in car racing games to recreate engine sound? Thanks
A long time ago, there was OpenAL and was moderately successful on Linux. It's fairly easy, modelled around the OpenGL library principles.
2,400,157
2,400,205
The intersection of two sorted arrays
Given two sorted arrays: A and B. The size of array A is La and the size of array B is Lb. How to find the intersection of A and B? If La is much bigger than Lb, then will there be any difference for the intersection finding algorithm?
Use set_intersection as here. The usual implementation would work similar to the merge part of merge-sort algorithm.
2,400,458
2,401,137
Is there a boost::weak_intrusive_pointer?
For legacy reasons I need to use intrusive pointers, as I need the ability to convert raw pointers to smart pointers. However I noticed there is no weak intrusive pointer for boost. I did find a talk about it on the boost thread list, however nothing concrete. Does anyone know of a thread safe implementation of weak in...
It does not make any sense. To elaborate: weak_ptr points to the same instance of a counter object that shared_ptr do. When the shared_ptr goes out of scope, the instance of the counter stays (with a count effectively at 0), which allows the weak_ptr instances to check that they effectively point to a freed object. Wit...
2,400,690
2,400,717
Why callback functions needs to be static when declared in class
I was trying to declare a callback function in class and then somewhere i read the function needs to be static but It didn't explain why? #include <iostream> using std::cout; using std::endl; class Test { public: Test() {} void my_func(void (*f)()) { cout << "In My Function" << endl; f(); ...
A member function is a function that need a class instance to be called on. Members function cannot be called without providing the instance to call on to. That makes it harder to use sometimes. A static function is almost like a global function : it don't need a class instance to be called on. So you only need to get...
2,400,766
2,400,793
Linking C and CXX files in CMake
I'm building C++ app with CMake. But it uses some source files in C. Here is simplified structure: trunk/CMakeLists.txt: project(myapp) set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -g -Wall") add_subdirectory (src myapp) trunk/src/main.cpp: #include "smth/f.h" int main() { f(); } trunk/src/CMakeLists.txt: add_subdirectory (...
Change f.h to: #ifndef F_H #define F_H #ifdef __cplusplus extern "C" { #endif void f(); #ifdef __cplusplus } #endif #endif
2,401,046
2,401,108
Avoid stuck calling callback
This is a question about generic c++ event driven applications design. Lets assume that we have two threads, a "Dispatcher" (or "Engine"...) and a "Listener" (or "Client"...). Let's assume that I write the Dispatcher code, and release it as a library. I also write the Listener interface, of course. When the Dispatcher...
Well if the event gets invoked in the same thread (as I seem to understand can be a requirement), then there isn't much you can do about it. If this is under a Win32 app with a message pump, you could register a windows message and call PostMessage with data representing this event and you can patch the message loop to...
2,401,225
2,401,253
Template classes and include guards in C++
Is it wise to have include guards around template classes? Aren't template classes supposed to be reparsed each time you reference them with a different implementation? N.B In Visual C++ 2008 I get no errors combining the two...
Templates definitions are supposed to be parsed once (and things like two phases name lookup are here so that as much errors as possible can be given immediately without having an instantiation). Instantiations are done using the internal data structure built at that time. Templates definitions are usually (i.e. if yo...
2,401,241
2,403,005
Is it worth using std::tr1 in production?
I'm using MS VC 2008 and for some projects Intel C++ compiler 11.0. Is it worth using tr1 features in production? Will they stay in new standard? For example, now I use stdext::hash_map. TR1 defines std::tr1::unordered_map. But in MS implementation unordered_map is just theirs stdext::hash_map, templatized in another w...
My advice would be to use an alias for the namespace containing the TR1 items you use. This way, you'll be able to "move" from using the TR1 version to the standard version when your compiler supports it. namespace cpp0x = std::tr1; cpp0x::unordered_map<std::string, int> mymap; for a C++0x compiler, the first line be...
2,401,710
2,407,538
Not receiving clear list notifications from Call log
I have been using CLogViewRecent and MLogViewChangeObserver to monitor call log on S60 5th edition phones. MLogViewChangeObserver has three functions: virtual void HandleLogViewChangeEventAddedL(TLogId aId, TInt aViewIndex, TInt aChangeIndex, TInt aTotalChangeCount); virtual void HandleLogViewChangeEventChangedL(TLog...
Reading the Symbian^3 logcli source, "list cleared" is an event different from "event deleted". It's not reflected in the MLogViewChangeObserver callback mixin, only in MLogViewChangeObserverInternal as HandleLogViewChangeEventLogClearedL(). That's why it's happening. Sorry, cannot offer you a workaround, short of impl...
2,401,800
2,403,082
MinGW/G++/g95 link error - libf95 undefined reference to `MAIN_'
Summing up, my problem consists on compiling g95 objects inside a C++ application. Actually, I'm constructing an interface for an old fortran program. For this task, I'm using the wxWidgets GUI library, and calling fortran subroutines when necessary. At the beginning, I was developing the entire project compiling my fo...
I'm answering my own question because I got the solution. The problem wasn't with my g95 intergration. I just overwrite the wxWidgets main macro for an int main function initialization as presented bellow: // Give wxWidgets the means to create a MyApp object //IMPLEMENT_APP(MyApp); int main(int argc, char *argv[]) { ...
2,401,976
2,402,103
Very simple application fails with "multiple target patterns" from Eclipse
Since I'm more comfortable using Eclipse, I thought I'd try converting my project from Visual Studio. Yesterday I tried a very simple little test. No matter what I try, make fails with "multiple target patterns". (This is similar to this unanswered question.) I have three files: Application.cpp: using namespace std; #...
Are you working from a Cygwin installation? I've seen this problem before using Cygwin--basically, make sees the : in the path and thinks it is another target definition, hence the error. If you are working from a Cygwin installation, you might try replacing the c:/ with /cygdrive/c/. If not, you might try using rel...
2,402,374
2,402,588
Qt - reloading widget contents
I'm trying to modify the fridge magnets example by adding a button that will reload the widget where the draggable labels are drawn, reflecting any changes made to the text file it reads. I defined another class that would contain the button and the DragWidget object, so there would be an instance of this class instead...
My quick guess is, you haven't added Q_OBJECT macro to dragwidget.h header, the moc file for DragWidget class wasn't generated and the connect failed with "no such slot as draw()" error. It might be also a good idea to add "CONFIG += console" to .pro file - you'll see all warning messages (like the one about connect er...
2,402,579
2,402,607
Function pointer to member function
I'd like to set up a function pointer as a member of a class that is a pointer to another function in the same class. The reasons why I'm doing this are complicated. In this example, I would like the output to be "1" class A { public: int f(); int (*x)(); } int A::f() { return 1; } int main() { A a; a.x = a.f; ...
The syntax is wrong. A member pointer is a different type category from a ordinary pointer. The member pointer will have to be used together with an object of its class: class A { public: int f(); int (A::*x)(); // <- declare by saying what class it is a pointer to }; int A::f() { return 1; } int main() { A a; ...
2,402,636
2,402,670
Object not declared in scope
I'm using Xcode for C++ on my computer while using Visual Studio at school. The following code worked just fine in Visual Studio, but I'm having this problem when using Xcode. clock c1(2, 3, 30); Everything works just fine, but it keeps giving me this error that says "Expected ';' before 'c1'" Fine, I put the ';' .....
There is a function clock that will hide your clock class of the same name. You can work this around by saying class clock c1(2, 3, 30); It's very bad practice to do using namespace std; in a header. Instead put that line into the cpp file only. It may solve your problem if you remove that line (if the name comes from...
2,402,803
2,402,827
Creating a window application that will perform certain action after every 10 minutes
I was wondering would I still need to use a basic game loop for this particular operation?
You could create a timer and perform that action on WM_TIMER message handling or on timer proc function you specify when creating the timer. See SetTimer and WM_TIMER.
2,403,020
2,403,026
Why doesn't the C++ default destructor destroy my objects?
The C++ specification says the default destructor deletes all non-static members. Nevertheless, I can't manage to achieve that. I have this: class N { public: ~N() { std::cout << "Destroying object of type N"; } }; class M { public: M() { n = new N; } // ~M() { //this should happen by ...
What makes you think the object n points to should be deleted by default? The default destructor destroys the pointer, not what it's pointing to. Edit: I'll see if I can make this a little more clear. If you had a local pointer, and it went out of scope, would you expect the object it points to to be destroyed? { ...
2,403,330
2,403,628
Does COM automatically unload DLLs when there are no more object references?
For example, in language X: let x = CreateOject( "MyProgID" ) x.LateBoundCall() x.Release() // (or setting x to Nothing in VB-like language, etc) What happens to the DLL MyProgID lives in? Does COM unload DLLs automatically? EDIT This is assuming that the code above is in an executable that does not expose any COM.
Yes, but not in a deterministic way. Windows periodically asks every loaded DLL "is it safe to unload you now?" Any DLL that responds "Yes" is unloaded. Note a remark from MSDN : If a DLL loaded through a call to CoGetClassObject fails to export DllCanUnloadNow, the DLL will not be unloaded until the applicat...
2,403,354
2,403,503
How do I guarantee cleanup code runs in Windows C++ (SIGINT, bad alloc, and closed window)
I have a Windows C++ console program, and if I don't call ReleaseDriver() at the end of my program, some pieces of hardware enter a bad state and can't be used again without rebooting. I'd like to make sure ReleaseDriver() gets runs even if the program exits abnormally, for example if I hit Ctrl+C or close the console ...
Under Windows, you can create an unhandled exception filter by calling SetUnhandledExceptionFilter(). Once done, any time an exception is generated that is not handled somewhere in your application, your handler will be called. Your handler can be used to release resources, generate dump files (see MiniDumpWriteDump),...
2,403,355
2,403,395
Memory allocation in case of static variables
I am always confused about static variables, and the way memory allocation happens for them. For example: int a = 1; const int b = 2; static const int c = 3; int foo(int &arg){ arg++; return arg; } How is the memory allocated for a,b and c? What is the difference (in terms of memory) if I call foo(a), foo(b) and ...
I am always confused about static variables In global scope, static only means it will not be visible to other files when linking. How is the memory allocated for a,b and c? All of them will live in the executable file (e.g. the __DATA segment) which will be mapped into the RAM on execution. If the compiler is good...
2,403,371
2,407,005
Why do I get LNK2005 errors when compiling a PHP extension DLL
I'm trying to compile a PHP extension in VS2008. It is dependent on 3 other projects which I link statically. It used to work fine when I had all my code in one .cpp file. I separated the code into several files to make it more manageable and now it won't compile. I'm getting several (~100 per file) linker errors, LNK2...
change the order of the link libraries that might help... can you post the some errors... it will make picture more clearer... click Settings. click to select the project configuration that is getting the link errors. On the Link tab, click to select Input in the Category combo box. In the Ignore libraries box, insert...
2,403,391
2,403,409
How does an extern "C" declaration work?
I'm taking a programming languages course and we're talking about the extern "C" declaration. How does this declaration work at a deeper level other than "it interfaces C and C++"? How does this affect the bindings that take place in the program as well?
extern "C" is used to ensure that the symbols following are not mangled (decorated). Example: Let's say we have the following code in a file called test.cpp: extern "C" { int foo() { return 1; } } int bar() { return 1; } If you run gcc -c test.cpp -o test.o Take a look at the symbols names: 00000010 T _...
2,403,421
2,406,953
Get Pixel with Magic++
Can anybody show me an example how i get the pixel values of an Image ? I want to read an Image and iterate over it .. and print out the actual "red" value. Can anyone help ? i'm a beginner :(
There is a direct function in magic++ called read in the image class: image::read i.e image.read( 640, 480, "RGB", CharPixel, pixels ); in which pixels will give you arrays of pixel values... that you can use later. Or you can access direct low level pixels.. Here is how... http://www.imagemagick.org/Magick++/Image++...
2,403,536
2,404,259
Pthreads in Visual C++
I'm experimenting with multithreading in Windows and was wondering whether I should use Win32 API use POSIX Threads for Windows Learning Pthreads would be useful if I tried to develop such applications on different platforms - but am I losing anything by not learning Win32 API? Or are both similar enough so that lear...
Use Boost Threads. When C++0x comes along, we will have std::threads. Boost threads has the closest implementation to std threads. else use pthreads. Pthreads is second closest to std::threads, and formed the main basis of std threads and boost threads. else do windows threading directly. You can still learn how t...
2,403,567
2,403,623
VC++ project: MSXML vs any other XML libraries
We are aware of MSXML, based on COM technologies. We want to use it for a VC++ project starting soon. Are there any other XML libraries do good compared to MSXML?
TinyXML - A C++ open source library
2,403,660
2,405,517
Determine processor support for SSE2?
I need to do determine processor support for SSE2 prior installing a software. From what I understand, I came up with this: bool TestSSE2(char * szErrorMsg) { __try { __asm { xorpd xmm0, xmm0 // executing SSE2 instruction } } #pragma warning (suppress: ...
Call CPUID with eax = 1 to load the feature flags in to edx. Bit 26 is set if SSE2 is available. Some code for demonstration purposes, using MSVC++ inline assembly (only for x86 and not portable!): inline unsigned int get_cpu_feature_flags() { unsigned int features; __asm { // Save registers ...
2,403,741
2,403,777
Get last/newly added element in std::set
can you get the last or newly added element in std::set? for example say if the loop runs to collect the elements to fill in the std::set. if on the first run the set was, [0] "A" [1] "B" [2] "D" and, on second run, the set becomes [0] "A" [1] "B" [2] "C" [3] "D" How would you check if 'C' is the new element that was...
set::insert returns an iterator to the newly inserted item. Hold on to that iterator if you're interested in that item.
2,403,924
2,403,946
Call by reference in C++
What is actually passed in call by reference to a function? void foo(int &a,int &b) when I write foo(p,q) what is actually passed to the function. Is it the address of p and q?
What's actually passed to the function is a reference. The named parameter b becomes a synonym for the argument object q. How the compiler probably implements this that the caller places the address of q on the stack or in a register before calling, and the callee uses that value to effect all accesses to b. But it cou...
2,403,928
2,405,478
Partial template specialization of free functions - best practices
As most C++ programmers should know, partial template specialization of free functions is disallowed. For example, the following is illegal C++: template <class T, int N> T mul(const T& x) { return x * N; } template <class T> T mul<T, 0>(const T& x) { return T(0); } // error: function template partial specialization ...
As litb says, ADL is superior where it can work, which is basically whenever the template parameters can be deduced from the call parameters: #include <iostream> namespace arithmetic { template <class T, class S> T mul(const T& x, const S& y) { return x * y; } } namespace ns { class Identity {}; // t...
2,404,094
2,404,126
How do I get characters common to two vectors in C++?
I am trying to compare two vector objects, and return a single vector containing all the chars which appear in both vectors. How would I go about this without writing some horribly complex manual method which compares every char in the first vector to every char in the second vector and using an if to add it to a third...
I think you're looking for std::set_intersection. The source vectors have to be sorted though. If you don't care about the order of your output vector, you could always run it on sorted copies of your source vectors. And BTW, the manual naive way isn't horribly complex. Given two source vectors s1 and s2, and a dest...
2,404,103
2,404,566
ExpandEnvironmentStrings Not Expanding My Variables
I have a process under the Run key in the registry. It is trying to access an environment variable that I have defined in a previous session. I'm using ExpandEnvironmentStrings to expand the variable within a path. The environment variable is a user profile variable. When I run my process on the command line it does no...
One problem is that you are providing the wrong parameters to ExpandEnvironmentStrings and then using a cast to hide that fact (although you do need a cast to get the correct type out of a CString). You are also using the wrong value for the last parameter. That should be the size of the output buffer, not the size of...
2,404,115
2,404,148
Is auto_ptr deprecated?
Will auto_ptr be deprecated in incoming C++ standard? Should unique_ptr be used for ownership transfer instead of shared_ptr? If unique_ptr is not in the standard, then do I need to use shared_ptr instead?
UPDATE: This answer was written in 2010 and as anticipated std::auto_ptr has been deprecated. The advice is entirely valid. In C++0x std::auto_ptr will be deprecated in favor of std::unique_ptr. The choice of smart pointer will depend on your use case and your requirements, with std::unique_ptr with move semantics for ...
2,404,150
2,404,229
Save all file names in a directory to a vector
I need to save all ".xml" file names in a directory to a vector. To make a long story short, I cannot use the dirent API. It seems as if C++ does not have any concept of "directories". Once I have the filenames in a vector, I can iterate through and "fopen" these files. Is there an easy way to get these filenames at ...
Something like this (Note, Format is a sprintf:ish funciton you can replace) bool MakeFileList(const wchar_t* pDirectory,vector<wstring> *pFileList) { wstring sTemp = Format(L"%s\\*.%s",pDirectory,L"xml"); _wfinddata_t first_file; long hFile = _wfindfirst(sTemp.c_str(),&first_file); if(hFile != -1) ...
2,404,221
2,404,302
The question regarding cerr cout and clog
Can anybody explain the difference between cerr cout and clog and why does different objects are proposed? I know the differences are as below: 1) cout can redirected but cerr can't 2) clog can use buffer. I am confused about the point 2, I am grateful if anybody can elaborate it more.
Buffered output is typically much faster than unbuffered. So if you wanted to write a vast amount of data quickly to a log (but didn't care if it actually ended up there), you would use clog rather than cerr. And all streams can normally be redirected, assuming a vaguely competent operating system, but this is outwith ...
2,404,288
2,404,329
How are exceptions allocated on the stack caught beyond their scope?
In the following code, the stack-based variable 'ex' is thrown and caught in a function beyond the scope in which ex was declared. This seems a bit strange to me, since (AFAIK) stack-based variables cannot be used outside the scope in which they were declared (the stack is unwound). void f() { SomeKindOfException e...
The exception object is copied to a special location to survive the stack unwinding. The reason you see two destructions is because when you exit f() the original exception is destroyed and when you exit g() the copy is destroyed.
2,404,439
2,404,474
How do I bit shift a long by more than 32 bits?
It seems like I should be able to perform bit shift in C/C++ by more than 32 bits provided the left operand of the shift is a long. But this doesn't seem to work, at least with the g++ compiler. Example: unsigned long A = (1L << 37) gives A = 0 which isn't what I want. Am I missing something or is this just not pos...
Re-try this using a variable of type uint64_t (from stdint.h) instead of long. uint64_t is guaranteed to be 64 bits long and should behave as you expect.
2,404,567
2,404,600
How to reliably get size of C-style array?
How do I reliably get the size of a C-style array? The method often recommended seems to be to use sizeof, but it doesn't work in the foo function, where x is passed in: #include <iostream> void foo(int x[]) { std::cerr << (sizeof(x) / sizeof(int)); // 2 } int main(){ int x[] = {1,2,3,4,5}; std::cerr << (...
In C array parameters in C are really just pointers so sizeof() won't work. You either need to pass in the size as another parameter or use a sentinel - whichever is most appropriate for your design. Some other options: Some other info: for C++, instead of passing a raw array pointer, you might want to have the param...
2,404,781
2,404,933
Insert an element to std::set using constructor
is it possible to insert a new element to std::set like in case of std::list for example: //insert one element named "string" to sublist of mylist std::list< std::list<string> > mylist; mylist.push_back(std::list<string>(1, "string")); Now, mylist has one element of type std::string in its sub-list of type std::list. ...
I think this should do the trick: int main() { string s = "test"; set<string> mySet(&s, &s+1); cout << mySet.size() << " " << *mySet.begin(); return 0; } For clarification on the legality and validity of treating &s as an array, see this discussion: string s; &s+1; Legal? UB?
2,404,880
2,480,467
Graph algorithms (lib) with input graph in read-only shared memory on C/++
I would like to have a manager process sharing graphs via shared memory, read-only for other processes which will run various graph algorithms on these graphs. I would like to ask some questions emerged while researching the issue: Are there any graph libraries which are able to operate on (possibly their own) graph s...
In Boost Graph Library the various graph types are just concepts ( http://www.boost.org/doc/libs/1_42_0/libs/graph/doc/graph_concepts.html ). You should be able to implement your own graph structure, adhere to the concept you need and apply any BGL algorithm on your own data (or perhaps just wrap your shared data in a...
2,405,045
2,405,074
C++ class with char pointers returning garbage
I created a class "Entry" to handle Dictionary entries, but in my main(), I create the Entry() and try to cout the char typed public members, but I get garbage. When I look at the Watch list in debugger, I see the values being set, but as soon as I access the values, there is garbage. Can anyone elaborate on what I m...
Word and Definition both point into tmp, which has gone out of scope and so contains garbage.
2,405,115
2,405,139
Questions regarding ordering of catch statements in catch block - compiler specific or language standard?
I am currently using Visual Studio Express C++ 2008, and have some questions about catch block ordering. Unfortunately, I could not find the answer on the internet so I am posing these questions to the experts. I notice that unless catch (...) is placed at the end of a catch block, the compilation will fail with error ...
According to the standard, the order is significant. Basically the first catch that matches the exception will be caught. a) Because catch(...) will make any following catches irrelevant, the standard only allows it to be the last catch. b) C# and Java have similar rules. c) catch (by reference or pointer) of a base b...
2,405,214
2,406,475
Optimize CUDA with Thrust in a loop
Given the following piece of code, generating a kind of code dictionary with CUDA using thrust (C++ template library for CUDA): thrust::device_vector<float> dCodes(codes->begin(), codes->end()); thrust::device_vector<int> dCounts(counts->begin(), counts->end()); thrust::device_vector<int> newCounts(counts->size()); fo...
for every reiteration of i, size, index, code, etc. have to be copied from host to device.. the way you have your program, there is not much you can do. For best results, consider moving entire i loop on the device, this way you will not have host to device copies. Trust is great for some things, however where performa...
2,405,242
2,405,285
Cartesian product of several vectors
similar questions have been asked before but I cant find an exact match to my question. I have 4 vectors each of which hold between 200-500 4 digit integers. The exact number of elements in each vector varies but I could fix it to a specific value. I need to find all possible combinations of the elements in these 4 v...
Not much of an algorithm... for(vector<int>::const_iterator i1 = v1.begin(); i1 != v1.end(); ++i1) for(vector<int>::const_iterator i2 = v2.begin(); i2 != v2.end(); ++i2) for(vector<int>::const_iterator i3 = v3.begin(); i3 != v3.end(); ++i3) for(vector<int>::const_iterator i4 = v4.begin(); i4 != ...
2,405,555
2,405,582
string s; &s+1; Legal? UB?
Consider the following code: #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { string myAry[] = { "Mary", "had", "a", "Little", "Lamb" }; const size_t numStrs = sizeof(myStr)/sizeof...
It is legal and not UB to have a pointer to "one past the end" of an array, and any single object can be treated as if it were in an array of length 1; however, you need to use ptr + 1 instead due to the technicality of &ptr[1] dereferencing and then taking the address. This also applies to &array[size] becoming array...
2,405,722
2,405,781
Why is it not possible to access the size of a new[]'d array?
When you allocate an array using new [], why can't you find out the size of that array from the pointer? It must be known at run time, otherwise delete [] wouldn't know how much memory to free. Unless I'm missing something?
In a typical implementation the size of dynamic memory block is somehow stored in the block itself - this is true. But there's no standard way to access this information. (Implementations may provide implementation-specific ways to access it). This is how it is with malloc/free, this is how it is with new[]/delete[]. ...
2,405,731
2,410,608
Using ACE_Service_Object
I'm trying to use the ACE_Service_Object or the ACE_Shared_Object. I'm not sure which one is applicable. I'm trying to encapsulate some functionality in a DLL so a consumer of the DLL would open the library, create an instance of the exported class, call some functions on the class, and then destroy the class. A bas...
If all you need is to load, unload, and call some functions in a shared library, you could use the ACE_DLL class instead. That's what ACE_Shared_Object ends up using under the covers.
2,405,776
2,405,800
Programmatically monitor files on Windows
I'm looking for a way to monitor which processes are using (or attempting to access) a file over a duration of time. What are some good Windows APIs or tools to achieve this?
FileSystemWatcher is not suitable for determining the process. There already was a different question. look here, this solution fits your needs.
2,405,849
2,405,882
How does one modify the thread scheduling behavior when using Threading Building Blocks (TBB)?
Does anyone know how to modify the thread scheduling (specifically affinity) when using TBB? Doing a high level analysis on a simple parallel-for application, it seems like TBB is specifying the underlying threads' affinity in a way that reduces performance. Specifically, the cores I'm running on have hyper-threading...
TBB 2.1 added an affinity partitioner which assigns tasks to threads based on cache affinity. Using this partitioner instead of the default one might help out. You can also dive into individual tasks and use tbb::task::set_affinity (documentation here). The scheduler can notify you if the task happens to run on a th...
2,405,871
2,405,891
Temporary non-const istream reference in constructor (C++)
It seems that a constructor that takes a non-const reference to an istream cannot be constructed with a temporary value in C++. #include <iostream> #include <sstream> using namespace std; class Bar { public: explicit Bar(std::istream& is) {} }; int main() { istringstream stream1("bar1"); Bar bar1(stream1); ...
This is just how C++ works currently: you cannot bind non-const references to temporary objects. MSVC is non-standard in allowing this. C++0x will have r-value references and change things around a bit here. There are various philosophical interpretations people have tried to apply—for both sides of the issue—but I h...
2,406,060
2,406,088
Virtual Function Implementation
I have kept hearing this statement. Switch..Case is Evil for code maintenance, but it provides better performance(since compiler can inline stuffs etc..). Virtual functions are very good for code maintenance, but they incur a performance penalty of two pointer indirections. Say i have a base class with 2 subclasses(X ...
The compiler can't do that because of the separate compilation model. At the time the virtual function call is being compiled, there is no way for the compiler to know for sure how many different subclasses there are. Consider this code: // base.h class base { public: virtual void doit(); }; and this: // usebase.c...
2,406,095
2,406,138
Does boost::asio::deadline_timer use a thread for each timer?
I have a list of items that I need to update on different intervals. The list can grow to be thousands of items long. Each item could potentially have a different interval. If I create one timer per item, am I going to saturate the system with threads? I was thinking it might be better to create one timer equal to the ...
Boost does not use a thread per timer, it keeps a timer queue. Every timer is created with boost::asio::io_service object that does the actual work. This object can dispatch its work in one or more threads, when you run boost::asio::io_service::run() explicitly from multiple threads, but there is no one-to-one correspo...
2,406,144
2,406,153
C++ overide global operator comma gives error
the second function gives error C2803 http://msdn.microsoft.com/en-us/library/zy7kx46x%28VS.80%29.aspx : 'operator ,' must have at least one formal parameter of class type. any clue? template<class T,class A = std::allocator<T>> class Sequence : public std::vector<T,A> { public: Sequence<T,A>& operator,(const T& ...
Change that to: Sequence<double> operator,(const Sequence<double>& a, const double& b) { Sequence<double> seq(a); seq.push_back(b); return seq; } or (based on this article): Sequence<double> operator,(Sequence<double> seq, const double& b) { seq.push_back(b); return seq; }
2,406,168
2,413,673
Constraining window position to desktop working area
I want to allow a user to drag my Win32 window around only inside the working area of the desktop. In other words, they shouldn't be able to have any part of the window extend outside the monitor(s) nor should the window overlap the taskbar. I'd like to do it in a way that does cause any stuttering. Handling WM_MOVE me...
Keep in mind that users with multi-monitor setups may have a desktop that extends into negative x- and y-coordinates, or that is not rectangular. Also, some users use alternative window managers such as LiteStep, which implement virtual desktops by moving them off-screen; if you try to fight this, your application will...
2,406,211
2,443,727
What libraries should I use to manipulate archives from C++?
I want to manipulate .zip and .rar files from C++. What libraries should I use?
zlib and minizip, yes. minizip was last updated in 2005. Some facts about version 1.01e: This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g, WinZip, InfoZip tools and compatible. Multi volume ZipFile (span) are not supported. Encryption compatible with pkzip 2.04g only supported Old comp...
2,406,224
2,433,527
Cross Platform C++ webserver Library
I am looking for a cross platform Library in C++ that can run a web server. Does any one know if tntnet can work on windows computers. or libmicrohttpd
POCO has a HTTP server, among lots of other useful stuff. Runs on Windows, Linux, etc.
2,406,247
2,406,514
How to skip integers in C++ taken from a fstream txt file?
I need to create a function that uses a loop. This function will open a text file and then must be able to skip a variable number of leading random integers. The program must be able to handle any number of leading random integers. Example if the opened file reads this on its first line: 100 120 92 82 38 49 102 and th...
If I were you, I would approach this problem like this: 1. create ifstream object m_strm 2. open the file 3. whie (m_strm.good()) (a.) use ifstream's getline() to read a line from the file (b.) use strtok() function to tokenize the string (for whitespaces) (c.) maintain a counter when you keep getting token...
2,406,372
2,406,544
Test Driven Development with C++: How to test a class which depends on other classes?
Suppose I have a class A which depends on 3 other classes X, Y and Z, either A uses these through a reference or a pointer or say A is templated to be instantiated with X, Y and Z doesn't matter, the key is that in order to test A, I need to have X, Y and Z. So I need to have fakes for A, B and C. Suppose I write them...
First make sure that the objects you depend on (X, Y & Z) are passed in at the constructor, this way you can easily pass in 'fakes' when you are testing. (I really hope you are using a unit test framework, like CUnit) Now when you are writing the test, all you need to do is make up 'fakes' for the objects the class und...
2,406,410
2,412,265
SWIG_NewPointerObj and values always being nil
I'm using SWIG to wrap C++ objects for use in lua, and Im trying to pass data to a method in my lua script, but it always comes out as 'nil' void CTestAI::UnitCreated(IUnit* unit){ lua_getglobal(L, "ai"); lua_getfield(L, -1, "UnitCreated"); swig_module_info *module = SWIG_GetModule( L ); swig_type_info ...
When you use the colon in function AI:UnitCreated(unit), it creates a hidden self parameter that receives the AI instance. It actually behaves like this: function AI.UnitCreated(self, unit) So when calling that function from C, you need to pass both parameters: the ai instance and the unit parameter. Since you passed ...
2,406,485
2,406,515
What is an overloaded operator in C++?
I realize this is a basic question but I have searched online, been to cplusplus.com, read through my book, and I can't seem to grasp the concept of overloaded operators. A specific example from cplusplus.com is: // vectors: overloading operators example #include <iostream> using namespace std; class CVector { publ...
Operator overloading is the technique that C++ provides to let you define how the operators in the language can be applied to non-built in objects. In you example for the Time class operator overload for the + operator: Time operator+(const Time& lhs, const Time& rhs); With that overload, you can now perform addition...
2,406,642
2,409,303
Monitoring processes of the Windows OS using the C language
I want to make an application in C or C++ which have to monitor some specific processes. How can I make it possible in C?
You said that you have tomaonitor "some specific processes". If your application started the processes, you can extract the process handles from the PROCESS_INFORMATION structure (field hProcess) you passed to the CreateProcess function. If the process you want to track has been launched in some different way, you need...
2,406,764
2,406,807
What happens when we combine RAII and GOTO?
I'm wondering, for no other purpose than pure curiosity (because no one SHOULD EVER write code like this!) about how the behavior of RAII meshes with the use of goto (lovely idea isn't it). class Two { public: ~Two() { printf("2,"); } }; class Ghost { public: ~Ghost() { printf(" BOO...
The standard talks about this explicitly - with an example; 6.7/3 "Declaration statement" (emphasis added by me): Variables with automatic storage duration are initialized each time their declaration-statement is executed. Variables with automatic storage duration declared in the block are destroyed on exit f...
2,406,972
2,407,873
Problem in passing arrays from C# to C++
I have an application in which I need to pass an array from C# to a C++ DLL. What is the best method to do it? I did some search on Internet and figured out that I need to pass the arrays from C# using ref. The code for the same: status = IterateCL(ref input, ref output); The input and output arrays are of length 20. ...
You need to use: [DllImport("your_dll")] public extern void IterateCL([In, MarshalAs(UnmanagedType.LPArray)] int[] arr1, [Out, MarshalAs(UnmanagedType.LPArray)] int[] arr2);
2,407,077
2,407,145
Read from cin or a file
When I try to compile the code istream in; if (argc==1) in=cin; else { ifstream ifn(argv[1]); in=ifn; } gcc fails, complaining that operator= is private. Is there any way to set an istream to different values based on a condition?
You can replace cin's streambuf with another, and in some programs this is simpler than the general strategy of passing around istreams without referring to cin directly. int main(int argc, char* argv[]) { ifstream input; streambuf* orig_cin = 0; if (argc >= 2) { input.open(argv[1]); if (!input) return 1;...
2,407,257
2,407,417
Disable keyboard keys when the console of c Run using c or c++
I want to disable keyboard when my program Run, means that no one can use alt+F4 etc. How I can make it possible using c in window OS.
Handle WM_SYSKEYUP , WM_SYSKEYDOWN and return 0 Here's the WndProc to handle these messages LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); ...
2,407,451
2,409,438
Find unique vertices from a 'triangle-soup'
I am building a CAD-file converter on top of two libraries (Opencascade and DWF Toolkit). However, my question is plattform agnostic: Given: I have generated a mesh as a list of triangular faces form a model constructed through my application. Each Triangle is defined through three vertexes, which consist of three flo...
Dump all the vertices in an array, then do unique(sort(array)). This should be O(k n log(n)), where k is the average number of triangles that share a vertex, usually k<7. The only caveat I can think of is that your unique function should be able to take a pointer to a comparison function, since you probably want to con...
2,407,558
2,407,677
pthreads: reader/writer locks, upgrading read lock to write lock
I'm using read/write locks on Linux and I've found that trying to upgrade a read locked object to a write lock deadlocks. i.e. // acquire the read lock in thread 1. pthread_rwlock_rdlock( &lock ); // make a decision to upgrade the lock in threads 1. pthread_rwlock_wrlock( &lock ); // this deadlocks as already hold rea...
What else than a dead lock do you want in the following scenario? thread 1 acquire read lock thread 2 acquire read lock thread 1 ask to upgrade lock to write thread 2 ask to upgrade lock to write So I'd just release the read lock, acquire the write lock and check again if I've to make the update or not.
2,407,690
2,410,363
Lookin' for a container and memory pool solution
In an embedded program I have a screen object that needs to manage a list of items to display. The initial list of items will be pulled from a simple DB on screen load and the list will be updated via "Add" and "Remove" events. This list needs to be sorted according to certain criteria. I am looking of a container clas...
If you use a standard container (such as std::map or std::set) you need to worry about different dynamic allocations: the allocation of the internal container data structures and the allocation of your own data you want to store in the container. The allocation of the internal data structures can be customized by suppl...
2,407,711
2,408,105
Avoiding improper std::string initialization with NULL const char* using g++
A there any g++ options which can detect improper initialization of std::string with NULL const char*? I was in the process of turning some int fields into std::string ones, i.e: struct Foo { int id; Foo() : id(0) {} }; ...turned into: struct Foo { std::string id; Foo() : id(0) {} //oooops! }; I complet...
I think it is actually undefined behavior and not checked by the compiler. You are lucky that this implementation throws an exception. However, you can avoid such problems by specifying that you want default or zero-initialization in a type-agnostic way: struct Foo { X id; Foo() : id() {} //note empty parenthesis...
2,407,724
2,407,809
Is delete p where p is a pointer to array always a memory leak?
following a discussion in a software meeting I've set out to find out if deleting a dynamically allocated, primitives array with plain delete will cause a memory leak. I have written this tiny program and compiled it with visual studio 2008 running on windows XP: #include "stdafx.h" #include "Windows.h" const unsig...
delete p, where p is an array is called undefined behaviour. Specifically, when you allocate an array of raw data types (ints), the compiler doesnt have a lot of work to do, so it turns it into a simple malloc(), so delete p will probably work. delete p is going to fail, typically, when: p was a complex data type - d...
2,407,939
2,416,716
IShockwaveFlashEvents: how to handle getURL("javascript:?
I wrote a simple WinAPI application in C++ which embeds the Abode Flash ActiveX control. It works fine. Next task that i have to do it is handle getURL("javascript:somefoo(someparam)", "")in C++ I don't understand the right way to do this. I create connection point to listen to _IShockwaveFlashEvents and my STDMETHODIM...
I solved this question. you cannot handle getURL flash must use fscommand to pass data to host application
2,407,972
2,408,009
Cannot convert const char * to char *
Visual Studio c++ 2005 I am getting an error on the last line of this code. int Utils::GetLengthDiff ( const char * input, int & num_subst ) { int num_wide = 0, diff = 0 ; const char * start_ptr = input ; num_subst = 0 ; while ( ( start_ptr = strstr ( start_ptr, enc_start ) ) != NULL ) { ...
C++ has two overloaded versions of this function. http://www.cplusplus.com/reference/clibrary/cstring/strstr/ const char * strstr ( const char * str1, const char * str2 ); char * strstr ( char * str1, const char * str2 ); Since your start_ptr is const char * the C++ compiler resolves to call the version th...
2,407,976
2,409,782
Doxygen, too heavy to maintain?
I am currently starting using doxygen to document my source code. I have notice that the syntax is very heavy, every time I modify the source code, I also need to change the comment and I really have the impression to pass too much time modifying the comment for every change I make in the source code. Do you have some ...
Is it the Doxygen syntax you find difficult? Or is it the fact that you have to comment all of the functions now. If it's the former, there may be a different tool that fits your coding style better. Keep in mind that Doxygen supports multiple commenting styles, so experiment until you find one you like. If it's the ...
2,408,038
2,408,059
What does "-Wall" in "g++ -Wall test.cpp -o test" do?
-o changes the output filename (I found that using --help) But I can't find out what -Wall does?
It's short for "warn all" -- it turns on (almost) all the warnings that g++ can tell you about. Typically a good idea, especially if you're a beginner, because understanding and fixing those warnings can help you fix lots of different kinds of problems in your code.
2,408,179
2,409,069
Memory allocation while insertion into a map
#include <stdio.h> #include <stdlib.h> #include <memory.h> #include <vector> #include <string> #include <iostream> #include <map> #include <utility> #include <algorithm> void * GetMemory(size_t n) { void *ptr = malloc(n); printf("getMem n %d ptr 0x%x\n", n, reinterpret_cast<unsigned int> (ptr)); return ptr; } ...
Stick some tracing in FreeMemory and change main to this: int main(int argc, char *argv[]) { printf("map\n"); std::map<int, vec> z; printf("vec\n"); vec x; printf("pair\n"); std::pair<int,vec> y(1,x); printf("insert\n"); z.insert(y); printf("inserted 1\n"); y.first = 2; printf("insert\n"); z.ins...
2,408,181
2,408,225
dual map structure implementation?
I'm looking for a standard dual-map structure - is there one implemented in std/boost/another standard C++ library? When I say "dual-map" I mean a map which can be indexed efficiently both by the key and the "value" (it actually has two key types instead of one key type and one value type). for example: dualmap<int,str...
There's boost bimap if you don't want all the horsepower of boost multi index.
2,408,414
2,408,434
Changing contents of ItemData
I store objects of a custom data type in QStandardListItems. I recover these objects by calling: i.data(Qt::UserRole + 1).value<LiteReach>(); This only creates a new object in the stack. Any changes I do to them would be temporary. Is there a way to get the base object stored in itemData so that it could be manipulate...
You could use pointers that allow access to the concrete data objects instead of copying the whole data into a QVariant like above. The problem is that value() returns a copy of your data. So if you make any modifications, they will be gone as soon as the copy is removed from stack. If you don't want to use pointers, I...
2,408,523
2,410,137
Detect modification of variable at runtime in C/C++
I am developing a library in C++ where users/programmer will extend a class BaseClass that has a method initArray. This method should be implemented by the user/programmer and it should normally initialize all elements of the array m_arr. Here is a snipplet, modified to this example: class BaseClass { public: ...
I don't see a straightforward way of doing this in C++. What you are intending to implement is filters in Ruby on Rails where before accessing any method, the filters are invoked. Alternatively you can wrap your array inside a structure and inside this structure overload the [] operator for both assignment and access. ...
2,409,138
2,409,171
DllRegisterServer error 0xc0000005, (C++ COM Dll). how do I debug my DllRegisterServer function in Visual Studio 2008?
I have written a COM dll, and wish to register it using regsvr32 myComdll.dll I get an error : DllRegisterServer failed, Return code was: 0xc0000005 I want to debug my DllRegsiterServer function, but I do not know how to set up Visual Studio 2008 to run regsvr32 in debug mode... Thanks Roey
Project + Properties, Debugging, set Command = Regsvr32.exe $(TargetPath). Set a breakpoint on your DllRegisterServer function or use Debug + Exceptions, check Win32 Exceptions. Press F5 to get it going.
2,409,456
2,409,677
Can a QT window be completely styled, including the menu bar when running on Windows 7 or Vista?
I noticed that the sample apps from QT show their menu bar as opaque, and with a color that doesn't match any of the styling on the window. It seems as if the windows being created by QT when running on Vista or Windows 7 don't pick up the translucency that are no the mainstay of the new Windows look and feel. Is there...
On Windows 7 there is a special flag that activates the "Glass" Look&Feel: Here is some more detailed information: http://labs.trolltech.com/blogs/2009/09/15/using-blur-behind-on-windows/ Screenshot http://labs.trolltech.com/blogs/wp-content/uploads/2009/09/blurbehind2.png From what I see, only the Qt::WA_TranslucentBa...
2,409,504
13,394,183
Using C++ filestreams (fstream), how can you determine the size of a file?
I'm sure I've just missed this in the manual, but how do you determine the size of a file (in bytes) using C++'s istream class from the fstream header?
You can open the file using the ios::ate flag (and ios::binary flag), so the tellg() function will directly give you directly the file size: ifstream file( "example.txt", ios::binary | ios::ate); return file.tellg();
2,409,539
2,437,741
Getting Parent Layout in Qt
quick question. Is there any way to (easily) retrieve the parent layout of a widget in Qt? PS: QObject::parent() won't work, for logical reasons. EDIT: I'm positive the widget has a parent layout, because I added it to a layout earlier in the code. Now, I have many other layouts in the window and while it is possible f...
After some exploration, I found a "partial" solution to the problem. If you are creating the layout and managing a widget with it, it is possible to retrieve this layout later in the code by using Qt's dynamic properties. Now, to use QWidget::setProperty(), the object you are going to store needs to be a registered me...
2,409,775
2,444,346
Mapping Java Native Methods to C++ Member Functions
The examples for JNI i've seen map Java native methods to implementation by C++ global functions. Is there a way to set the native methods implementation to be the member functions of a C++ object instead?
JNI doesn't know anything about your C++ classes. It just allows you to implement the methods of your Java classes using native code. The C++ functions you write are the methods of a Java class so it doesn't make sense to simultaneously make them methods of a different C++ class. If you are worried about namespace po...
2,409,819
2,409,853
C++: constructor initializer for arrays
I'm having a brain cramp... how do I initialize an array of objects properly in C++? non-array example: struct Foo { Foo(int x) { /* ... */ } }; struct Bar { Foo foo; Bar() : foo(4) {} }; array example: struct Foo { Foo(int x) { /* ... */ } }; struct Baz { Foo foo[3]; // ??? I know the foll...
Edit: see Barry's answer for something more recent, there was no way when I answered but nowadays you are rarely limited to C++98. There is no way. You need a default constructor for array members and it will be called, afterwards, you can do any initialization you want in the constructor.
2,409,840
2,409,868
Determining files in a directory
I come from a C# background and I am working on a C++ project. I need to open files in a directory, then process that data in the files. The problem is on my target environment (Greenhills Integrity), I cannot access a "directory". It seems C++ does not have a concept of a directory. Why not? This problem is simpl...
No, it's not possible. C++ has no "built-in" directory functionality - you need to use a library of some sort.
2,409,956
2,410,084
Convert HTML to Plain Text using c++
I am doing mail parsing application which required to convert the HTML file to Plain Text. regarding this i have found some scripts which does conversion. I want to do same thing in C++. So please suggest me any Cross platform and open source C++ libraries for converting HTML to Plain Text. Thanks in advance Regard...
Try using regular expression extracting html tags and save result as file text. But it not simple. Use this help class DEELX - Regular Expression Engine.
2,410,191
2,410,203
getting around const in an init method
So I can't use initializers in my class constructor because of using arrays, so I decided to use an init() method instead. Now I have a different problem. I have a class like this: class EPWM { private: volatile EPWM_REGS* const regs; public: void init(volatile EPWM_REGS* _regs); }; where I need to implement ini...
You could consider const_cast and pointers, but it's something best used very rarely. Something like... EPWM_REGS** regsPP = const_cast<EPWM_REGS**>(&regs); *regsPP = _regs;
2,410,300
2,410,728
How to use wxTheApp macro outside the module it is declared?
I'm using wxWidgets 2.8.9, built with the default settings under Windows XP, VC9. And I have absolutely standard EXE with IMPLEMENT_APP like this: #include <wx/wx.h> #include <wx/image.h> #include "MainFrame.h" class MyMainApp: public wxApp { public: bool OnInit(); }; IMPLEMENT_APP(MyMainApp) bool MyMainApp::OnI...
I don't use wxWidgets myself (go Qt!) But did you by any chance statically link your DLL to wxWidgets, such that the EXE and the DLL each have their own copy of the lib...? http://wiki.wxwidgets.org/Creating_A_DLL_Of_An_Application That would explain why your DLL's global variables for tracking the instance would be n...
2,410,532
2,410,696
C++: How can I avoid "invalid covariant return type" in inherited classes without casting?
I have a quite complex class hierarchy in which the classes are cross-like depending on each other: There are two abstract classes A and C containing a method that returns an instance of C and A, respectively. In their inherited classes I want to use a co-variant type, which is in this case a problem since I don't know...
I know of no way of having directly coupled covariant members in C++. You'll have either to add a layer, or implement covariant return yourself. For the first option class C; class A { public: virtual C* outC() = 0; }; class C { public: virtual A* outA() = 0; }; class BI : public A { public: }; cl...
2,410,609
2,410,847
c++ exception parameter
I have a question regarding the following code snippet I came across in one of our older libraries. try { throw "this is an error message"; } catch( char* error ) { cout << "an exception occured: " << error << endl; } My understanding of the behavior in this case is, that the error message is thrown by value, whic...
In throw context arrays decay to pointers. And string literal is an array of characters. This means that: (1) What is "thrown by value" in this case is a const char * pointer to the existing string literal. No copy of string literal is made. No additional memory is allocated by this throw. There's no need to deallocate...
2,410,631
2,731,574
Movement towards continuous integration in progress, any suggestions?
We have a bunch of C/C++ modules and projects for QNX4, QNX6 and Linux. All of these are written in Eclipse/QNX Momentics and we use Project Sets (psf files) to combine different modules into projects as required. The projects are built using make. The psf files specify which modules are required for a certain project....
I ended up using Hudson along with Ant and ant4eclipse plugin. Ant4Eclipse works with ProjectSet files, so it is perfect. Ant can also do Telnet and so I use it for QNX4
2,410,683
2,410,713
What's the connection between the heap used in dynamic memory allocation and the data structure?
Possible Duplicate: Why are two different concepts both called “heap”? I've googled around, but cannot find the answer for this question; what's the connection between the heap used in dynamic memory allocation and the data structure? Is memory organized on the heap in a way which is similar the the heap data struct...
Heap is a synonym for what the standard calls the free-store. In contrast to stacks, which is used for function calls, and function-local object storage, heaps grow in the opposite direction (top to bottom) on many implementations (as opposed to stacks -- which grow from bottom to top). Of course, none of these are req...
2,411,017
2,411,508
Using custom and built-in properties in Boost::Graph
I am building a graph class based on the following suggestion: Modifying vertex properties in a Boost::Graph Unfortunately, I realized an unexpected behavior. When using my own vertex-properties (for simplicity please ignore the edge properties), the built-in properties seem not to be used. So for example, when I have:...
Been a long time since I've used Boost.Graph, but Googling "vertex_index_t", in hit #5 Andrew Sutton says : Just declaring a vertex index as a property (either bundled or interior, as here) won't buy you any new functionality. It just provides a place where you can assign an index for each vertex or edge. The...
2,411,043
2,411,114
Design question regarding threads
I have class A and classes B and C. class B runs one thread and class C runs n threads. class A should start the threads and than wait for a signal from the user (say Ctrl-c in Linux) - class A will stop all threads (of classes B and C), do some final work and the application will exit. The question is: how should clas...
Sounds like a job for a condition variable. There's a tutorial on how to use pthreads condition variables here and another one on wikipedia here The basic approcah is that all the threads that you want to kill periodically call pthread_cond_timedwait to check if a signal has been sent from class A. In pseudocode each ...
2,411,098
2,411,132
Help with char input and printing in C++
i want to read characters from the console and print them one after another only if they have a certain value. Well i tried using something like this: char c; while (c != '\n') { c = getch(); if (printable(c)) cout << c; // where printable is a function which checks /...
You may want to change your cout statement to cout << "You just typed: " << c; That way you can actually see if you've hit the if condition successfully. Also post printable(). Here is a sample of just grabbing a char, not sure why you are using getch() you should use cin.get, but anyhow for your example: bool isPrint...
2,411,315
2,411,425
How to convert for loop to STL for_each statement
I would like to convert my for loop to STL std::for_each loop. bool CMyclass::SomeMember() { int ii; for(int i=0;i<iR20;i++) { ii=indexR[i]; ishell=static_cast<int>(R[ii]/xStep); theta=atan2(data->pPOS[ii*3+1], data->pPOS[ii*3]); al2[ishe...
You need to seperate out the loop body into a seperate function or functor; I've assumed all the undeclared variables are member variables. void CMyclass::LoopFunc(int ii) { ishell=static_cast<int>(R[ii]/xStep); theta=atan2(data->pPOS[ii*3+1], data->pPOS[ii*3]); al2[ishell] += massp*cos(fm*theta); } b...
2,411,556
2,411,761
Cleaning up threads referencing an object when deleting the object (in C++)
I have an object (Client * client) which starts multiple threads to handle various tasks (such as processing incoming data). The threads are started like this: // Start the thread that will process incoming messages and stuff them into the appropriate queues. mReceiveMessageThread = CreateThread(NULL, 0, (LPTHREAD_STA...
You don't have much leeway because of the running threads. No combination of shared_ptr + weak_ptr may save you... you may call a method on the object when it's valid and then order its destruction (using only shared_ptr would). The only thing I can imagine is to first terminate the various processes and then destroy t...
2,411,704
2,411,720
C++, vector of objects
In c++, is using a vector of objects a good idea? If not, what's wrong with this c++ code? #include <vector> using namespace std; class A {}; int main() { vector<A*> v ( new A); return 0; } from g++: 13: error: invalid conversion from A*' tounsigned int'
The constructor for std::vector takes an initial length, not an element. This means you'd normally do: vector<A*> v(1); // Initialize to length 1 v.push_back( new A() ); // Add your element... You're getting the compiler error you are because, on your system, size_type is defined as an unsigned int. It's trying to us...
2,412,238
2,412,266
When do c++ stream objects use mutexes?
In the answer to this question ovanes states: Please be aware that boost::lexical_cast is much slower as atoi. I also use it very often in a performance non-critical code. The problem with lexical_cast is that it uses stringstream for conversion. If you are working in a multi-threaded environement any st...
The current C++ standard (C++03) does not contain anything about multi-threading. Because of this, how a library uses mutexes would depend on the specific implementation.
2,412,240
2,412,511
Free numerical libraries, C++, Windows
I am totally new to math/numerical analysis programming and I was looking all over the internet to find appropriate libraries. What I stumbled upon are CLAPACK, Boost::uBLAS, ATLAS. I need to solve SLEs (system of linear equations) so I guess BLAS itself would not be sufficient without some implementation of LAPACK. No...
Mkl libraries are available free of charge under noncommercial license, search Google and you will find it. http://software.intel.com/en-us/articles/non-commercial-software-development/ I do not know what SEL are, system linear equations? boost ublas has LU decompose which you can use to solve a few problems. Ublas ...