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
1,442,162
1,442,194
StretchDIBits failed, sometimes it draw nothing,
I am using gdi c++, StretchDIBits function sometimes failed if I draw large Images such as 7000*5000. It draw nothing. GetLastError() says no enough system resource. Can anyone explain why StretchDIBits need resource even The DC is prepared successfully.
It may be that StretchDIBits expands the source image into a temporary bitmap of the same dimensions as the destination bitmap, and then copies the temporary into the destination as the final step. So even if you have enough memory to create the destination bitmap (140 MB) before the StretchDIBits call, your system do...
1,442,213
1,442,238
CreateDIBSection failed
BITMAPINFO bmi; memset(&bmi,0,sizeof(BITMAPINFO)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth =m_pImg->GetWidth(); bmi.bmiHeader.biHeight =m_pImg->GetHeight(); bmi.bmiHeader.biPlanes = 1; //if( m_pImg->GetInfo()->biBitCount!=16) //{ // bmi.bmiHeade...
I think the answer to this is the same as the answer to your earlier question: your bitmaps are way too big. Also, since your dimensions are now half the dimensions of the bitmap in your earlier question, I'm guessing you're trying to break the destination up into quadrants, but now you don't have enough resources to ...
1,442,258
1,442,301
How do applications like Google Sidebar reduce the desktop size?
I'm trying to write an application which will sit at the top of the desktop on top of every window. I need this window however to not just sit on top of other windows, but to actually reduce the size of the desktop so when these windows maximise they don't get covered up by my application's bar. So, basically, I want m...
Yes, it is. These windows are known as Application Desktop Toolbars. MSDN has a reference page on them here.
1,442,436
1,442,754
Script to insert logging into every function in a project?
I have inherited a fairly large codebase, 90% C++, and I need to get up to speed on it quickly. There are hundreds of .cc files in a wide directory tree structure. It's fairly complex, and has no logging. In order to figure out how some major subsystems work, I want to insert a function call into every function. E....
Had something similar for adding profiling code using Macros in VS, here's the code (this also groups everything under a single "undo" command and lists all of the changes in its own output window) Imports System Imports EnvDTE Imports EnvDTE80 Imports System.Diagnostics Public Module Module1 Function GetOutputWi...
1,442,750
1,442,767
The power of .NET without the garbage collection?
I love C# because the powerful features of the .NET framework make it so easy to develop for Windows. However I also love standard C++ primarily because it gives me fine-tuned control over memory management. Is there a way to have the best of both worlds? Are there C++ libraries that can compete with the rich set of li...
Have you looked at Boost? Alternatively, you can use "C++/CLI" (a.k.a. managed C++, a.k.a. C++.NET); code written in this language can call into .NET APIs and can also manually manage memory via traditional Win32 APIs like HeapAlloc/HeapFree. In my experience, though, this language is most frequently used for writing ...
1,442,762
1,442,835
Challenge working with Visual Studio and VC++?
I have started working with C++ recently and am not comfortable with Visual Studio Development Environment and also I do not have proper understanding of MFC, Win32, ATL, COM Terminologies. From example point of view, I had taken a simple C++ program to see how it works with Visual Studio Environment and I was having s...
The classic book about Win32 is presumably Petzold's. Petzold's book is I think (I've never read it) mostly about GUI programming; whereas the other classic/recommended Win32 book, which is Richter's, is about 'system' (non-GUI) programming. For learning COM, perhaps Essential COM? Some reviewers praise it, but some ot...
1,443,206
52,044,247
How to determine if 2 paths reference the same file in portable C++
I was wondering if there is a portable way to determine if 2 different paths actually reference the same file. I have read this thread but is Windows-specific. AFAIK, fstream isn't suitable for the job.
Filesystem library Since C++17 you can use the standard <filesystem> library. The function you are looking for is equivalent, under namespace std::filesystem: bool std::filesystem::equivalent(const std::filesystem::path& p1, const filesystem::path& p2 ); To summarize from the documentation: this function takes two pat...
1,443,659
1,443,688
Should I return bool or const bool?
Which is better: bool MyClass::someQuery() const; const bool MyClass::someQuery() const; I've been using 'const bool' since I'm sure I remember hearing it's "what the ints do" (for e.g. comparison operators) but I can't find evidence of that anywhere, mostly due to it being difficult to Google and Intellisense not he...
So you know it's right, you're just after the Voice of Authority? Preventing accidental modification of temporaries is very valuable. In general, you should declare as many things as you possibly can const, it protects you from a variety of accidents and gives the optimiser useful hints. D'you have a copy of Scott Meye...
1,443,793
1,443,818
Iterate keys in a C++ map
Is there a way to iterate over the keys, not the pairs of a C++ map?
If you really need to hide the value that the "real" iterator returns (for example because you want to use your key-iterator with standard algorithms, so that they operate on the keys instead of the pairs), then take a look at Boost's transform_iterator. [Tip: when looking at Boost documentation for a new class, read t...
1,443,865
1,443,926
C++ api for understanding tone signals on a phone line
Is there any good c++ source codes or api for handling phone lines like understanding tone signals. For example i like to find out if the person enters 3 (it's likely that this is done using it's tone sound). Do i need a special modem for this purpose or it can be done using only standard modems.
DTMF is the term you are looking for: http://en.wikipedia.org/wiki/Dual-tone_multi-frequency Whether you can process incoming DTMF tones with a particular modem depends on whether the modem supports it. If it does there will be an AT command to manage it, both for issuing outgoing DTMF tones and being notified of incom...
1,443,870
1,444,303
C++ difference between automatic type conversion to std::string and char*
As a learning exercise, I have been looking at how automatic type conversion works in C++. I know that automatic type conversion should generally be avoided, but I'd like to increase my knowledge of C++ by understanding how it works anyway. I have created a StdStringConverter class that can be automatically converted ...
The problem is due to the fact std::string is actually an instance of the class template std::basic_string. An operator== that is available in namespace std takes two std::basic_string templates: template<class charT, class traits, class Allocator> bool operator==(const basic_string& lhs, const basic_s...
1,443,982
1,443,997
When do compilers inline C++ code?
In C++, do methods only get inlined if they are explicitly declared inline (or defined in a header file), or are compilers allowed to inline methods as they see fit?
Yes, the compiler can inline code even if it's not explicitly declared as inline. Basically, as long as the semantics are not changed, the compiler can virtually do anything it wants to the generated code. The standard does not force anything special on the generated code.
1,444,025
1,444,066
C++ Overridden method not getting called
Shape.h namespace Graphics { class Shape { public: virtual void Render(Point point) {}; }; } Rect.h namespace Graphics { class Rect : public Shape { public: Rect(float x, float y); Rect(); void setSize(float x, float y); virtual void Render(Point point); ...
Here's your problem: struct ShapePointPair { Shape shape; Point location; }; You are storing a Shape. You should be storing a Shape *, or a shared_ptr<Shape> or something. But not a Shape; C++ is not Java. When you assign a Rect to the Shape, only the Shape part is being copied (this is object slicin...
1,444,112
1,444,186
Why does this work? This is a small example, but it even worked on a much more complex project
#include <cstdio> class baseclass { }; class derclass : public baseclass { public: derclass(char* str) { mystr = str; } char* mystr; }; baseclass* basec; static void dostuff() { basec = (baseclass*)&derclass("wtf"); } int main() { dostuff(); __asm // Added this after the answer found,...
Ugh. This is one of those "don't ever do this" examples. In dostuff, you create a temporary of type derclass, take its address, and manage to pass it outside of dostuff (by assigning it to basec). Once the line creating the temporary is finished, accessing it via that pointer yields undefined behavior. That it work...
1,444,388
1,444,603
What's the point of _MERGE_PROXYSTUB?
I have generated an ATL COM object using VS2008 and the code contains references to a definition called _MERGE_PROXYSTUB (because I chose the 'Merge proxy/stub' option when I initially ran the wizard.) What is the point of a proxy/stub? If I don't select the the merge option then I get a separate MyControlPS.DLL inste...
You need a proxy/stub if you want your COM object to be called from an application using a different threading model than your COM object. For example, we have a plug in that gets loaded by an application that uses a particular threading model (can't remember which), but our COM object is multithreaded apartment (MTA) ...
1,444,528
1,444,568
Why is this code so slow?
So I have this function used to calculate statistics (min/max/std/mean). Now the thing is this runs generally on a 10,000 by 15,000 matrix. The matrix is stored as a vector<vector<int> > inside the class. Now creating and populating said matrix goes very fast, but when it comes down to the statistics part it becomes so...
Have you tried to profile your code? You don't even need a fancy profiler. Just stick some debug timing statements in there. Anything I tell you would just be an educated guess (and probably wrong) You could be getting lots of cache misses due to the way you're accessing the contents of the vector. You might want to ...
1,444,837
1,444,911
Automatic creation of constructor, based on parent class' constructor (C++)
Here is a code I would like to get to work: template <class A> class B : public A { public: // for a given constructor in A, create constructor with identical parameters, // call constructor of parent class and do some more stuff B(...) : A(...) { // do some more stuff } }; Is it possible to achieve behavi...
No this is currently not possible in C++. It's called "perfect forwarding", and is allowed in C++0x. You can simulate it by producing overloads of your constructor up to a fixed maximum (like, say, 8 parameters), both for const and non-const references. This is still not perfect (temporaries won't be forwarded as tempo...
1,444,843
1,444,892
Can creating a C++ control and using it in C# gain performance?
In reality, I am trying to create a control showing price depths of a stock which needs to accept a large number of messages and summarizing them for display purposes. Will I get a better result if I create it in MFC and use that control in my .Net Winform application than writing the whole thing in .NET?
I would write the whole thing in .NET, profile if it's too slow, then if it is, port only the processing code to C++ and use P/Invoke to get the summarized results for a .NET control. Trying to interface an MFC control with .NET can take a long time and be prone to error, whereas if you write the display logic in .NET...
1,444,961
1,445,024
Is there a good Python library that can parse C++?
Google didn't turn up anything that seemed relevant. I have a bunch of existing, working C++ code, and I'd like to use python to crawl through it and figure out relationships between classes, etc. EDIT: Just wanted to point out: I don't think I need or want to parse every bit of C++; I just need something smart enough ...
C++ is notoriously hard to parse. Most people who try to do this properly end up taking apart a compiler. In fact this is (in part) why LLVM started: Apple needed a way they could parse C++ for use in XCode that matched the way the compiler parsed it. That's why there are projects like GCC_XML which you could combine ...
1,444,991
1,445,027
how to differentiate if client is using TCP or UDP from server side
I am writing simple client-server program. Client send some messages to server using UDP or TCP. Server must be able to support both UDP and TCP. If client, sends message using UDP, sequence of method calls in client is socket(),bind(),sendto(),recvfrom(),close() and that in server is socket(),bind(),sendto(),recvfrom(...
Before the packet reaches you, you don't know whether it's UDP or TCP. So you want to bind to both UDP and TCP sockets if you expect requests both ways. Once you did, you just know which way it came by the socket you received the packet through.
1,445,084
1,445,178
Pattern for synching object lists among computers (in C++)?
I've got an app that has about 10 types of objects. There will be potentially a few thousand object instances of each type. These lists of objects need to stay synchronized between apps running on different machines. If an object is added, changed or deleted, that needs to propagate to the other machines. This will be ...
How you implement synchronization very much depends on your needs. Do the changes need to be sent to the clients, or is it sufficient that the clients checks if an object is up to date whenever it uses the objects? How bout using the Proxy pattern? This pattern allows you to create a proxy-implementation of your objec...
1,445,237
1,445,310
Why does int count jump from 1 to 4 on entering a loop? C++
My "counter" is jumping from 1 to 4 when I enter my loop. Any ideas? Code and output below: static bool harvestLog() { ifstream myFile("LOGS/ex090716.log"); if (myFile.fail()) {cout << "Error opening file";return 1;} else { cout << "File opened... \n"; string line; string fie...
I would bet that it's going throught the while (!foundField.eof()) { foundField >> field; //if (count == cs_uri_stemLocation) cout << field << endl; count++; ...
1,445,274
1,445,327
Ternary operator evaluation order
class Foo { public: explicit Foo(double item) : x(item) {} operator double() {return x*2.0;} private: double x; } double TernaryTest(Foo& item) { return some_condition ? item : 0; } Foo abc(3.05); double test = TernaryTest(abc); In the above example, why is test equal to 6 (instead of 6.1) if some_cond...
The conditional operator checks conversions in both directions. In this case, since your constructor is explicit (so the ?: is not ambiguous), the conversion from Foo to int is used, using your conversion function that converts to double: That works, because after applying the conversion function, a standard conversion...
1,445,308
1,445,622
Saving 'global' data as a standard user?
in my application I need to store settings that are 'global' (i.e. not user specific) in a known and predictable location. I want the application to be able to be run from anywhere (as a standard user, NOT administrator), including multiple copies from different locations and be able to read and write the saved config ...
If you decide that CSIDL_COMMON_APPDATA isn't appropriate (maybe CSIDL_COMMON_APPDATA is a good default, but you want the administrator to be able to change the location) you can have the installer write something to an HKLM\SOFTWARE\<your app subkey> that indicates the desired path for the common directory that will h...
1,445,608
1,445,985
Reading license file from RLM with C# (C++ to C# translation)
I'm using the Reprise RLM license manager researching internet activation. I can't figure out how to get the license file from the webserver into a text file with C# (I'm also very new to C#). RLM comes with an example in C++ but I can't translate it. My code (for the demo) looks like so: int stat = RLM.rlm_act_request...
Well, that was surprisingly easy. It turns out that the 'new byte[]' that gets passes to rml_act_request() holds the contents of the license file. All I had to do was make it a local variable, convert it to string and write it to file using TextWriter.WriteLine(); I wish this had been documented somewhere...
1,445,679
1,446,086
Easiest way to locate a static variable in code?
I have a bug on my plate to locate and rewrite a static variable in one of our libraries that is taking up launch time in our application. I am not familiar with the library code base and am asking for good heuristics/techniques/grep commands/etc. that would ease my task in identifying the location of said static varia...
You could try to do a nm -aC <libname> first and grep by the static and global vars (IIRC they should be prefixed with a B/b or a T/t), then look for those vars in the source code. It may narrow down the haystack a little.
1,445,736
1,445,749
How do I iterate through a std::list<MyClass *> and get to the methods in that class from the iterator?
If I have the list, typedef std::list<MyClass *> listMyClass; How do I iterate through them and get to the methods in that class? This is what I’ve tried, but that is not it: (MyClass::PrintMeOut() is a public method) for( listMyClass::iterator listMyClassIter = listMyClass.begin(); listMyClassIter != listMyCl...
Use this method: (*listMyClassIter)->PrintMeOut();
1,446,461
4,523,360
Getting started with OpenGL ES 2.0 on Windows
This is a very specific questions about the steps necessary to Build a simple OpenGL ES 2.0 program on the Windows platform. The environment is Visual Studio with unmanaged C++. I go to the Khronos.org site and, frankly, find it a bit opaque because it reads like something written by a standards body. I don't want to...
After alot of digging around for the same thing. I found an emulator for openGL es 2 from PowerVR: http://www.imgtec.com/powervr/insider/sdkdownloads/index.asp The AMD one linked above is no longer available or supported.
1,446,987
1,448,786
Lightweight Delaunay trianguation library (for c++)
I'd like to play around with some (2D) Delaunay triangulations, and am looking for a reasonably small library to work with. I'm aware of CGAL, but I was wondering if there was something fairly simple and straightforward out there. Things I would like to do: create a triangulation of an arbitrary set of points find tr...
You should probably detail your goals a bit, so that more relevant answers can be provided, but let me first mention Triangle, a 2D Delaunay generation tool, which is written in C, and can be used both as a standalone program, or called from your own code. Then, about CGAL, here is a typical small example, in case you ...
1,446,999
1,447,023
C++ std::system 'system' not a Member of std
I receive an error compiling a C++ program in which of the lines makes a call from "std::system(SomeString)". This program compiled 3 years ago, but when compiling it today, I receive an error that states ‘system’ is not a member of ‘std’. Is there something that I must import to use std::system, has it been abandoned,...
std::system is (and always has been) in <cstdlib>. It is not defined by the C++ standard whether standard headers include each other, and if so which ones. So it's possible that 3 years ago, on a different compiler or a different version of the same compiler, your code worked by accident, because one of the headers you...
1,447,053
1,447,088
Why do I get different outputs when encrypting using DPAPI?
I'm using DPAPI in C++ to encrypt some data that I need to store in a file. The thing is that I need to read that file from C#, so I need to be able to: C++ encrypt, C++ decrypt (is working good) C# encrypt, C# decrypt (is working good) C++ encrypt, C# decrypt and vice-versa (not working) In C# I'm using DllImport to p...
It would help if you could post your C++ and your C# code. Perhaps there are some subtle parameter differences or something like this. For example, you should make sure that the pOptionalEntropy parameter is the same (or set it to NULL to test if this is the error source). Also, make sure to try to encrypt and decrypt ...
1,447,094
1,447,110
Where does Visual Studio search for txt files when conducting file management operations?
I know this is a noob question, but I've worked with Python before and when you wanted to simply access a .txt file for example, all you had to do was make sure the txt file was in the same directory. I have the following C++ code below but it's not finding the Numbers.txt file that I have saved on my desktop. All I ha...
Visual Studio sets the working directory to YourProjectDirectory\Debug\Bin when running in debug mode. If your text file is in YourProjectDirectory, you need to account for that difference. The easiest way to do that is to include your text files in the project and set their build action (in the Properties window) to ...
1,447,141
1,447,360
How to use a template parameter in another template parameter declared before
a template parameter can be used in another template parameter that follows it this way : template<typename T, T N> struct s { }; But is it possible to reference "T" if it is declared after "N" ? This does not work : template<T N, typename T> struct s { }; Can we help the compiler by pre-declaring "T" or doing anythi...
Like others say - No this isn't possible, the compiler can't infer the type of T from the non-type template arguments (in the case of functions, it infers types from the function arguments): 14.8.2.4/12: A template type argument cannot be deduced from the type of a non-type template-argument. In any case, no deducti...
1,447,143
1,447,161
Integration testing C++ code from NUnit in managed code
I have a library written in c++ that I want to end-to-end test from C# via interop. Basically this library takes in some parameters and spits out a file at the other end. I want to pass requests to a com interop and then assert that all the data was written correctly to the file. Is it possible to do this? Is there an ...
I'd use C++/CLI for gluing together .net tests and native C++ code. It works well enough in practise : I had a similar issue some months ago -- wanting to verify that a C++ protocol library I'd written would be interoperable with an existing Java implementation. For that I used a thin C++/CLI shim to the C++ code, b...
1,447,199
1,447,312
C++ closures and templates
We all know you can simulate closures in C++98 by defining local structs/classes inside a function. But is there some reason that locally defined structs can't be used to instantiate templates outside of the local scope? For example, it would be really useful to be able to do things like this: void work(std::vector<Fo...
There's no better reason than "it's not allowed by the standard". I believe C++0x is going to lift this restriction, and allow you to use local classes as template parameters freely. But for now, it's not allowed.
1,447,268
1,447,275
Does an arbitrary instruction pointer reside in a specific function?
I have a very difficult problem I'm trying to solve: Let's say I have an arbitrary instruction pointer. I need to find out if that instruction pointer resides in a specific function (let's call it "Foo"). One approach to this would be to try to find the start and ending bounds of the function and see if the IP reside...
Look at the *.map file which can optionally be generated by the linker when it links the program, or at the program's debug (*.pdb) file.
1,447,423
1,451,586
How to include directories in cmake generated visual studio projects?
I have (roughly) the following CMakeLists.txt project(Test) set(SOURCE 123.cpp 456.cpp ) find_package(Boost COMPONENTS unit_test_framework REQUIRED) include_directories(${Boost_INCLUDE_DIRS}) link_directories(${Boost_LIBRARY_DIRS}) message("${Boost_INCLUDE_DIRS}") add_executable(Tests ${SOURCE}) The message gener...
ok... the include_directories and link_directories need to be after the add_executable...
1,447,552
1,447,555
Performance penalty for using C++ vector instead of C array
Is there a performance penalty for working with a vector from the standard library in C++ instead of arrays in C?
No, there's not (provided you compile with optimization so inlining can happen), provided you mean dynamically sized C "arrays" obtained with malloc. Fixed-sized arrays in C will have the slight advantage that their address is fixed after linking (if global), or that they live directly on the stack rather than indirect...
1,447,554
1,447,560
Class constructor with non-argument template type
For a normal C++ function, it's possible to have template parameters not appearing in the argument list: template<typename T> T default_construct() { return T(); } and call this with some_type x = default_construct<some_type>(); Even though the type I'm using is not in the argument list, I can still pass it to th...
No, there is no way to do that. The note at 14.8.1/5 in the Standard explains why [Note: because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way t...
1,447,701
1,447,711
C++ Template abuse question - Augmenting floats with additional type information
I had an idea motivated by some of the documentation I read in the tutorial of the boost MTL library. The basic premise is that I would like to use templates to give me compile time type checking errors for things that are otherwise the same. Namely, lets say I have two units of measurement, Radians and Degrees. The mo...
I believe you are looking for something like Boost.Units. I think that's a place to get started.
1,447,783
1,447,804
Using a struct member in STL algorithms
#include <iostream> #include <vector> #include <iterator> using namespace std; struct Point { int x; int y; Point(int x, int y) : x(x), y(y) {} }; int main() { vector<Point> points; points.push_back(Point(1, 2)); points.push_back(Point(4, 6)); vector<int> xs; for...
You wouldn't use std::for_each, but rather std::transform (you're transforming a point into a single number.) For example: #include <algorithm> // transform resides here #include <iostream> #include <iterator> #include <vector> struct Point { int x; int y; Point(int x, int y) : x(x), y(y) { ...
1,447,939
1,447,978
Parameter choice for copy constructor
I was recently asked in an interview about the parameter for a copy constructor. [Edited] As a designer of C++ language implementing copy constructor feature, why would you choose constant reference parameter over a const pointer to a const object. I had a few ideas like since a pointer can be assigned to NULL which ...
Because Stroustrup wanted classes to be like primitive-types. When you initialize an int variable: int x = 5; int y = x; // Why would you write int y = &x; ? Passing constant pointer to constant object, is inconsistent with what C++ brought to C. classes in C++ are just User-Defined Types, if they don't work like prim...
1,447,989
2,275,189
"Unable to resolve..." in NetBeans 6.7.1, Linux, C++
I am working with a small group on a C++ project in NetBeans. For some reason, NetBeans is reporting things like "string", "endl", "cout" as "Unable to Resolve" even though the correct libraries have been included. The project compiles and runs as expected, so at the end of the day, it is no big deal, it is just that h...
For anyone interested, a few days later I had 6 updates available for NetBeans. After installing this updates, the problem was rectified, despite the code not changing. So, apparently it was a NetBeans bug.
1,448,119
1,448,169
How to write a function that takes an iterator or collection in a generic way?
I've been a Java programmer almost exclusively for the past 8 years or so, and recently I've been playing with C++ again. Here's an issue that I've come up against with regards to iterators in C++ STL and Java. In Java, you can write a method that takes an iterator like this: void someMethod(Iterator<String> data) { ...
Its best to indicate through a naming convention the kind of iterator and subsequently the kind of properties the iterator is required to posses. Below are some common naming conventions for iterators: template<typename Iterator> void foo_iterator(Iterator begin, Iterator end) { typedef typename std::iterator_trait...
1,448,396
1,448,478
How to use enums as flags in C++?
Treating enums as flags works nicely in C# via the [Flags] attribute, but what's the best way to do this in C++? For example, I'd like to write: enum AnimalFlags { HasClaws = 1, CanFly =2, EatsFish = 4, Endangered = 8 }; seahawk.flags = CanFly | EatsFish | Endangered; However, I get compiler errors re...
The "correct" way is to define bit operators for the enum, as: enum AnimalFlags { HasClaws = 1, CanFly = 2, EatsFish = 4, Endangered = 8 }; inline AnimalFlags operator|(AnimalFlags a, AnimalFlags b) { return static_cast<AnimalFlags>(static_cast<int>(a) | static_cast<int>(b)); } Etc. rest o...
1,448,426
1,486,485
How to avoid entering library's source files while debugging in Qt Creator with gdb?
How can I configure Qt Creator and/or gdb so that while debugging my program using Qt libraries the debugger would avoid stepping into Qt's source files?
You need to turn off auto-solib-add. From a normal gdb prompt you would type: (gdb) set auto-solib-add off In Qt Creator, under Options->Debugger->Gdb you can specify a Gdb startup script. Create a file with the "set auto-solib-add off" command in it and then set your Gdb startup script to that file.
1,448,467
1,448,480
initializing a C++ std::istringstream from an in memory buffer?
I have a memory block (opaque), that I want to store in a Blob in mySQL through their C++ adapter. The adapter expects a istream: virtual void setBlob(unsigned int parameterIndex, std::istream * blob) = 0; So my question is: how can I create a std::istream from this memory block (typed as char*). It's not a string as ...
Look at std::istrstream it has a constructor istrstream( char* pch, int nLength ); This class is sort of depreciated or at least you are normally told to use other classes. The issue with strstream is that it is more complex to manage the memory of the char* buffer so in general you would prefer stringstream as it do...
1,448,596
1,448,673
operator overloading in C++
Besides 'new', 'delete', '<<' & '>>' operators, what other operators can be overloaded in C++ outside of a class context?
The following operators (delimitted by space) can be overloaded as non-member functions: new delete new[] delete[] + - * / % ˆ & | ˜ ! < > += -= *= /= %= ˆ= &= |= << >> >>= <<= == != <= >= && || ++ -- , ->* The following have to be non-static member functions: -> () [] = The following can not be overloaded: . .*...
1,448,601
1,448,867
Convenient strategies for assertion checks
Some asserts are costly, some are better turned off at production code. At least it is not clear that assertions should be always enabled. In my application I would like to be able to turn on/off part of assertions on per-file or per-class basis. How to do it in C++?
For deactivating asserts module-wide i'd use: #if defined(assert) # undef assert # define assert(x) ((void)0) #endif ... of course this can be simplified if you are okay with using a custom macro. #if defined(_NO_ASSERTS) # define myAssert(x) ((void)0) #else # define myAssert(x) assert(x) #endif For class-wide de...
1,448,699
1,448,729
Opinions about list item and its class design
I'm currently designing a list widget to add to my widget engine. Since every elements visual aspects are defined outside the code I can reuse most of the code base. For instance tab buttons are actually checkboxes. New templates take time to implement since they should have at least a viewer in design application. I a...
OK, I come up with an idea IWidgetObject | ICheckbox CheckboxBase IRadioButton | \ / | \ / | | `-------------´ | `---------´ | | | | | | | Checkbox | RadioButton | |...
1,448,817
1,448,846
Why there is no std::copy_if algorithm?
Is there any specific reason for not having std::copy_if algorithm in C++ ? I know I can use std::remove_copy_if to achieve the required behavior. I think it is coming in C++0x, but a simple copy_if which takes a range, a output iterator and a functor would have been nice. Was it just simply missed out or is there some...
According to Stroustrup's "The C++ Programming Language" it was just an over-sight. (as a citation, the same question answered in boost mail-lists: copy_if)
1,448,925
1,449,012
Advice on Abstract Factory, DLL Exporting and Smart Pointers
This is a follow up to one of my previous questions and I have come up with a possible solution to my project and I need some advice or guidance if I have this right. Basically my project is a library to be used and compiled on both Linux and Windows, the Linux part isn't much of an issue, its Windows. My library consi...
Exporting the factory function and including the headers for the classes in user code is sufficient. If you don't depend on it let the user choose his best tool for the job. __stdcall extern "C" gives you a c-style declaration scope - therefore you can't have overloading there. see here. as win32 dll is c-style too yo...
1,449,055
1,449,067
Disk Space? (used/free/total) how do I get this? in C++
Disk Space? (used/free/total) how do I get this? in C++... thanks just for reading.
GetDiskFreeSpaceEx win32 API
1,449,125
1,449,302
Writing a C# Variable Length Structure to Binary and Reading it in in C++?
Okay, so i am continuing to work on my little game engine to teach me C#/C++ more. Now i am attempting to write a way of storing data in a binary format, that i created. (This is learning, i want to do this my self from scratch). What i am wondering what is the best way of dealing with variable length arrays inside a s...
You can read it from binary format mapping a copy of these structures. Each array should be treated as a pointer and you should have a integer with size of this array. For example in C# [StructLayout(LayoutKind.Sequential)] public struct A { public Int32 m_CheckSumLength; public byte[] m_C...
1,449,215
1,449,234
Is Vim editor very smart?
I am programming in C++ or Java. So I want to use Vim editor, because it is very flexible. I have heard that I can configure the Vim editor to be able to go from object to the definition from function to the definition from class name to the definition Do we have any professional Vim-er that could tell me exactly how...
What you're looking for is ctags and tags/TAGS files. Ctags (I recommend Exuberant Ctags) is a program which scans source files for identifiers and creates a file indexing them. You can then use ^] to jump to the definition for the tag under the cursor. There may be some additional details needed to tell vim how to f...
1,449,299
1,449,353
Qsort based on a column in a c-string?
A class project involves sorting an array of strings, with each string containing an equal number of columns like this: Cartwright Wendy 93 Williamson Mark 81 Thompson Mark 100 Anderson John 76 Turner Dennis 56 The program accepts a command-line argument for which column to sort on, ...
You can pass the structs like this: struct line { char * line; char column_to_sort_on[MAX_COLUMN]; } ... line* Lines[max_lines]; // here you store the structs int cmp_lines( const void *elem1, const void *elem2 ) { line* line1 = *(line**)elem1; line* line2 = *(line**)elem2; // do the comparison...
1,449,304
1,449,350
Ideas to debug and solve a very sporadic crash - appears to be an AV
I have a bug somewhere that is causing my app to just vanish without an error message or something like that. The app just dissapears from the screen and it's no longer listed on the Task Manager. The app is a C++Builder app (CBuilder2007), and I have tried everything I have think of to try to catch this error. It happ...
terminate/unexpected gets called only by C++ runtime, and only for C++ exceptions. Access violation is a SEH exception - to catch that, you need SetUnhandledExceptionFilter, or AddVectoredExceptionHandler (if it's >=XP). You could then create a minidump, using MiniDumpWriteDump and related.
1,449,432
1,449,579
Message loop gets blocked when application menu has the focus
I'm developing an application that looks mainly like this: while (true) { while (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&Msg); DispatchMessage(&Msg); } DoSomething(); Sleep(1); } What I noticed is that DoSomething() doesn't get called when I click on the menu bar...
The reason why is because Windows takes over the processing of messages when something like an application menu or message box is displayed, and that message loop which Windows uses won't call your DoSomething() method. This may be hard to visualize, so I'll try to step through what is happening: When someone opens yo...
1,449,525
1,449,589
c++ operator overloading memory question
In c++ you can create new instances of a class on both the heap and stack. When overloading an operator are you able to instantiate on the stack in a way that makes sense? As I understood it an instance that sits on the stack is removed as soon as the function is done executing. This makes it seems as though returning ...
If you're talking about for example operator+, where the object returned is not either of those input, then the answer is you instantiate on the stack and return by value: struct SomeClass { int value; }; SomeClass operator+(const SomeClass &lhs, const SomeClass &rhs) { SomeClass retval; retval.value = lhs...
1,449,703
1,449,735
how to append a list<T> object to another
in C++, I have two list<T> objects A and B and I want to add all the members of B to the end of A. I've searched a few different sources and haven't found a simple solution (e.i. A.append(B);) and this surprises me a bit. What is the best way to do this? As it happens, I don't care about B after this (it gets deleted i...
If you want to append copies of items in B, you can do: a.insert(a.end(), b.begin(), b.end()); If you want to move items of B to the end of A (emptying B at the same time), you can do: a.splice(a.end(), b); In your situation splicing would be better, since it just involves adjusting a couple of pointers in the linked...
1,449,818
1,449,864
Formatting C++ console output
I've been trying to format the output to the console for the longest time and nothing is really happening. I've been trying to use as much of iomanip as I can and the ofstream& out functions. void list::displayByName(ostream& out) const { node *current_node = headByName; // I have these outside the loop so I ...
You can write a procedure that always print the same number of characters to standard output. Something like: string StringPadding(string original, size_t charCount) { original.resize(charCount, ' '); return original; } And then use like this in your program: void list::displayByName(ostream& out) const { ...
1,449,908
1,449,960
Multiple Inheritance and Duck Typing
In working on Kira3, I was playing around with the C++ compiler and looking for a good way of implement Kira's duck typing. I was hoping (as it has been a few years of direct C++ programming) that I could use multiple inheritance for member access under multiple types. Alas, I have failed so far... The ideal code would...
I tried ... with the hope of the compiler combining them, but this gives ambiguous access to member variables. To solve that problem, try virtual inheritance.
1,450,133
1,457,665
Code that compiles for the iPhone Device but not for the Simulator
I am using C++ to develop the algorithmic part of an iPhone application, and I am encountering a strange bug. The code that I have, compiles fine with gcc-4.2 both on Linux, on the Mac, and on the iPhone device, just not on the Simulator, which makes debugging and testing very difficult. The error messages from the at...
Not sure if this is exactly the right answer, but this would probably explain why you're seeing the 4.0 behaviour while using 4.2: > pwd /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk/usr/include/c++ > ls -l total 4 drwxr-xr-x 10 root wheel 2278 10 Sep 09:32 4.0.0/ lrwxr-xr-x 1...
1,450,423
1,450,433
What's wrong with this c++ code?
My C++ is a bit rusty so... #include<list> typedef list<int> foo; that gives me the oh so nice error message: test.cpp:2: syntax error before `;' token What the heck can I even Google for in that...
You are expecting the list to be in global namespace. But is defined inside std namespace. Hence either you should use using namespace std; or expliictly specify the namespace as std::list; I personally prefer the second option.
1,450,439
1,450,444
Cannot pass string to CreateThread receiver
I have a thread function that looks something like this: DWORD WINAPI Thread_ProcessFile( LPVOID lpParam ) { char *filename = (char*)lpParam; printf( "%s\n", filename ); } I also have a class that calls CreateThread and uses the above function for the routine address: void CMyClass::ProcessFile( void ) { HANDLE tH...
You are creating the szBuffer on the stack. Hence by the time your thread starts, the ProcessFile() function would have returned and the stack variable would have been deallocated. Hence you are getting the garbage value. In the second case, you are passing a const-string which post probably resides in the read-only pa...
1,450,452
1,450,757
MySQL Connector/C++ Library Linking ERROR Problem
PROBLEM: Ok, I've been TRYING to follow the sample code on the MySQL Forge Wiki and some other websites that offer a tutorial on how to get a simple database connection, but for some reason, my project always fails at a linking error and I can't figure out why or how to fix it myself (I'm still learning). PLEASE HELP M...
You must first change your code: driver = sql::mysql::get_mysql_driver_instance(); And next, you have to link your code with mysqlclient.lib Add the right path of your lib mysqlclient.lib on your project: Properties->Linker->General-> Additionnal Libraries Here add the path of your lib.
1,450,654
1,518,397
Eclipse CDT with Cygwin GCC: automatic discovery of symbols and paths
I am using Eclipse CDT with Cygwin GCC 3 as compiler. My project is using a custom Makefile. The problem is that when debugging the code, it couldn't locate the source files, even though I added a custom path mapping for: /cygdrive/c <-> c:\ That in addition to the fact that I am getting "unresolved inclusion" for all ...
Yours is a frequest source of complaints regarding mixing eclipse & cygwin. The crux of the problem is that eclipse understands only the windows environment & cygwin, well not so much. Define your paths in in eclipse windows style. Also is /usr is under C:\cygwin, you have to give it the full path. Otherwise eclipse...
1,450,896
1,450,976
Defragmenting C++ Heap Allocator & STL
I'm looking to write a self defragmenting memory manager whereby a simple incrementing heap allocator is used in combination with a simple compacting defragmenter. The rough scheme would be to allocate blocks starting at the lowest memory address going upwards and keeping book-keeping information starting at the high...
If you're going to be moving objects around in memory then you can't do this fully generically. You will only be able to do this with objects that know that they might be moved. You also will need a locking mechanism. When a function is being called on an object, then it can't be moved. The reason is that the whole C++...
1,451,103
1,451,123
Imposing constrains of template function types, without c++0x concepts
Now that we know that Concepts is not part of C++0x, I am looking for methods to impose restrictions on types in template functions. Here are two examples: If we want to make sure that a given type is an integer, we can use: template <class N> inline int f(const N n) { if ((N)0.1 != 0) // if type of N...
Your checks can be handled much better at compile-time by using type-traits. The first: STATIC_ASSERT(std::numeric_limits<N>::is_integer) The second: STATIC_ASSERT(not std::numeric_limits<M>::is_signed) Have a look at the Boost Concept Check Library and at Boost.StaticAssert.
1,451,160
1,451,316
C++ Member Function Pointers and STL Algorithm
I have an abstract functor class that overloads operator() and derived objects that implement it. I have a function (part of another class) that tries to take an Array of these functor classes and tries to pass a pointer to a member function to the std algorithm for_each(), here is a overview of what I'm doing: EDIT: I...
If I understand what you want to do, there are quite a few errors in your code snippet: sizeof aArr is wrong, you need to pass the size explicitly (noticed by ChrisW) Missing virtual specifier on the original declaration of operator()() Not sure where your for loop ends as there's no matching } (I suspect it shouldn't...
1,451,269
1,453,397
C++ libraries for Image Segmentation
I am going to do a project in Data Mining related to image clustering (in C++) .I am looking for a powerful library which is helpful in image processing, linear algebra and 3d graphics. Any thoughts? Thanks.
OpenCV is your best option in the C/C++ world in my opinion.
1,451,304
1,451,334
Python generators in various languages
How do you emulate Python style generators in your favorite language? I found this one in Scheme. It must be interesting to see other implementations, especially in those languages that don't have first-class continuations.
Here is an example in C++ that simulates generators using fibers: Yield Return Iterator for Native C++ Using Fibers The "yield return" iterator is a language feature that was created for one reason: simplicity. It is generally much easier to iterate across whole collectionl, storing all context needed in loc...
1,451,433
1,451,443
C++ Templates and Inheritance
Let's say I have a simple Server with a template which accepts a Client as it's template argument: template<class T> class Server<T>{ Server(int port); } and a Client is defined something like this: class Client{ Client(Server<Client> *server, // <-- int socket); }; But I also want say, have the cl...
What about this? template<class T> class Server<T>{ Server(int port); }; template<class Derived> class Client { Client(Server<Derived> *server, int socket); virtual ~Client() {} // Base classes should have this }; class User : public Client<User> { };
1,451,569
1,451,585
Member variables and STL algorithms
#include <vector> #include <functional> #include <algorithm> using namespace std; struct Foo { int i; double d; Foo(int i, double d) : i(i), d(d) {} int getI() const { return i; } }; int main() { vector<Foo> v; v.push_back(Foo(1, 2.0)); v.push_back(Foo(5, 3.0)); ve...
It's absolutely unclean to need an accessor function in order to do that. But that's the current C++. You could try using boost::bind, which does the trick quite easily, or iterate the vector explicitly, using a for( vector<int>::const_iterator it = v.begin(); .....) loop. I find the latter often resulting in clearer...
1,451,606
1,451,799
Programably make and play a sound through speakers C++
I'm making a game in native vc++ (not .Net) I'm looking for a way to play a noise (maybe 8 bit or something) through the real speakers (not internal). I know about PlaySound, but I don't want to make my EXE big. I want to program the sound. Is there an api way (kinda like Beep() ) but that plays through the real speake...
You mention that you know about PlaySound. One of the it's flags (SND_MEMORY) will allow you to play a WAVE that is already loaded into memory, i.e. a buffer that you have created yourself. As long as the buffer has the appropriate WAVE header, whatever you you put in there should play through the speakers. The header ...
1,451,694
1,472,965
Is there a way to diff files from C++?
I'm looking for a C or C++ diff library. I know I can use the Unix diff tool in combination with system or exec, but I really want a library. It would be handy if the library could perform patches as well, like the Unix patch tool.
I think I've found a good solution, finally: The DTL - Diff Template Library --- Tutorial It supports patch. I had to type "diff.cpp" into Google to find it. Hopefully it works!
1,451,740
1,451,753
calculate array index from pointers
Me and some peers are working on a game (Rigs ofRods) and are trying to integrate OpenCL for physics calculation. At the same time we are trying to do some much needed cleanup of our data structures. I guess I should say we are trying to cleanup our data structures and be mindful of OpenCL requirements. One of the prob...
This should give you the index of pointer relative to base: pointer - base Yes, it's that easy. =] Use ptrdiff_t to store the result portably.
1,451,780
1,451,806
Fast exponentiation: real^real (C++ MinGW, Code::Blocks)
I am writing an application where in a certain block I need to exponentiate reals around 3*500*500 times. When I use the exp(y*log(x)) algorithm, the program noticeably lags. It is significantly faster if I use another algorithm based on playing with data types, but that algorithm isn't very precise, although provides ...
If you need good accuracy, and you don't know anything about the distribution of bases (x values) a priori, then pow(x, y) is the best portable answer (on many -- not all -- platforms, this will be faster than exp(y*log(x)), and is also better behaved numerically). If you do know something about what ranges x and y ca...
1,451,861
1,451,951
Creating an array of zero width and zero height?
I have an assignment from my programming class, which is very poorly worded... The following line really stumps me. We're creating a class called FloatArray, which contains an array (arr, which is just a pointer to a bunch of floats). The default constructor FloatArray(); should create array of zero width and zero h...
Doing *arr = 0 in the constructor would be very unwise. Since arr is uninitialized it might point to anything. Therefor *arr = 0 means "set some random memoryblock to 0 which probably will fail. On the other hand, doing arr = new float[0] is indeed a valid operation. I would recommend using a "new float[0]" for 0-size ...
1,451,925
1,476,691
DirectShow DVD playback
I have created a custom allocator/presenter that works fine for playback of normal media files. However, when I use the following code to try to playback a DVD, it fails with a stack overflow exception. vmr9_ap = new vmr9ap(); HMONITOR monitor = MonitorFromWindow(hwnd, NULL); IGraphBuilder *graph; IBaseFilter *f...
Your graph should look something like this. Make sure there aren't any buggy filters in your graph. Because you are using a custom allocator, I would look there for the issue and set some breakpoints there. You code you pasted might be incomplete as I do not see you configure the VMR9 with the custom allocator, nor d...
1,451,973
1,451,985
Good books or tutorials for beginning Direct X with c++
I'm pretty familiarity with c++. I'v made a few games like tetris and solitaire with it. But what I would really like is some nice textured graphics for those games :-p GDI just isn't doing it for me anymore. Really, all I would need to know is: DX scene initialization making something simple like a round rectangle an...
This is a good tutorial. I've started with it and it was helpful. That is not a book, but good enough tutorial with step-by-step explanations.
1,452,040
1,452,435
How to read an intermittent hard drive consistently?
I have a faulty hard drive that works intermittently. After cold booting, I can access it for about 30-60 seconds, then the hard drive fails. I'm willing to write a software to backup this drive to a new and bigger disk. I can develop it under GNU/Linux or Windows, I don't care. The problem is: I can only access the di...
I think the simplest way for you is to copy the entire disk image. Under Linux your disk will appear as a block device, /dev/sdb1 for example. Start copying the disk image until the read error appear. Then wait for the user to "repair" the disk and start reading from the last position. You can easily mount file disk im...
1,452,140
1,452,206
Count up and down elegantly
I'm trying to make a flashing object, i.e., increment it's alpha value from 0 to 255 (gradually) and then back down to 0, and repeat. Is there a way I can do this without using some boolean? Getting it to increment is easy: alpha = time.elapsed()%256; But what's a nice way to get it to count back down again after that...
How about using a sin function, that way the fading is more pleasant and you'll get what you want.
1,452,235
5,570,354
Does an R compiler to C/C++ exist?
I'm wondering about the best way to deploy R. Matlab has the "matlab compiler" (MCR). There has been discussion about something similar in the past for R that would compile R into C or C++. Does anyone have any experience with the R to C Compiler (RCC) that was developed by John Garvin at Rice? I've looked into it, ...
A byte code compiler will be part of the R 2.13 release. By default it is not used in this release but it is available; I expect the 2.14 release will by default byte compile all base and recommended packages. The compiler::compile help page and the R Installation and Administration Manual give some more details.
1,452,501
1,452,520
String Replace in C++
I've spent the last hour and a half trying to figure out how to run a simple search and replace on a string object in C++. I have three string objects. string original, search_val, replace_val; I want to run a search command on original for the search_val and replace all occurrences with replace_val. NB: Answers in pu...
A loop should work with find and replace void searchAndReplace(std::string& value, std::string const& search,std::string const& replace) { std::string::size_type next; for(next = value.find(search); // Try and find the first match next != std::string::npos; // next is npos if nothing was...
1,452,668
1,452,758
Advantages of knowing for a client, how big the package sended by the server is
I'm really new at network-programming, so I hope this isn't a complete Newbie-question. I read a tutorial at the Qt-Homepage how to build a little server, and I found this: QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out << (quint16)0; out << "..."; // just some text out.device()->seek(0); out <<...
It is standard stuff. To the receiving program everything coming over the network is just a stream of bytes. The stream has no meaning beyond what the application imposes upon it, exactly the same way a file has no meaning beyond how its records, lines, etc., are defined by the application(s). The only way the client ...
1,452,710
1,453,259
RTSP library in Python or C/C++?
I am trying to find any RTSP streaming library for Python or C/C++. If not is there any other solutions for real time streaming? How much easy or difficult it is to implement RTSP in Python or C/C++ and where to get started?
try live555. They have a lots of libraries and modules for implementing rtp and rtsp (as well as sip) into your c and c++ programs
1,452,721
1,452,738
Why is "using namespace std;" considered bad practice?
I have heard using namespace std; is bad practice, and that I should use std::cout and std::cin directly instead. Why is this? Does it risk declaring variables that share the same name as something in the std namespace?
Consider two libraries called Foo and Bar: using namespace foo; using namespace bar; Everything works fine, and you can call Blah() from Foo and Quux() from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function called Quux(). Now you've got a conflict: Both Foo 2.0 and ...
1,452,883
1,452,905
Is there an C++ equivalent to Python's "import bigname as b"?
I've always liked Python's import big_honkin_name as bhn so you can then just use bhn.thing rather than the considerably more verbose big_honkin_name.thing in your source. I've seen two type of namespace use in C++ code, either: using namespace big_honkin_name; // includes fn(). int a = fn (27); (which I'm assured is...
namespace bhn = big_honkin_name; There's another way to use namespaces too: using big_honkin_name::fn; int a = fn(27);
1,453,131
1,453,141
How can I get polymorphic behavior in a C++ constructor?
I have a base class that I want to look like this: class B { // should look like: int I() { return someConst; } virtual int I() = 0; public B() { something(I()); } } The point being to force deriving classes to override I and force it to be called when each object is constructed. This gets used to do some ...
You can't call virtual methods from the constructor (or to be more precise, you can call them, but you'll end up calling the member function from the class currently being constructed)., the problem is that the derived object does not yet exist at that moment. There is very little you can do about it, calling virtual m...
1,453,243
1,453,266
How can I avoid using exceptions in C++?
What techniques can I use to avoid exceptions in C++, as mentioned in Google's style guide?
Don't throw exceptions. Don't use STL (which relies heavily on exceptions). Use only new(std::nothrow) or override ::operator new to return 0 on failure. Note that by avoiding exceptions, you're effectively throwing out lots of useful libraries, including Boost. Basically, you'll have to program everything from scrat...
1,453,392
1,453,898
UpdateLayeredWindow, SIZE_RESTORED and GetClientRect problem
I have a layered window set up in my MFC application. I have set up my own derivation of CDialog to allow me to customise various parts of how the window is rendered. Everything works fine right up until I start worrying about minimise and maximise. If you click minimise or maximise then the window reacts exactly a...
I have come up with a sort of hack to solve this problem. In OnSize and OnMove I ignore the (c)x and (c)y that I receive and work everything out from a GetWindowRect. The application now reacts as expected. I have marked the code with a [HACK] comment. This does seem very odd though, I'd love to hear WHY this is hap...
1,453,393
1,453,412
Legit Uses of the offsetof Macro in C / C++
There is this macro offsetof in C/C++ which allows you to get the address offset of a member in a POD structure. For an example from the C FAQ: struct foo { int a; int b; }; struct foo; /* Set the b member of foo indirectly */ *(int *)((char *)foo + offsetof(b)) = 0xDEADBEEF; Now this just seems evil to me and I ca...
Well ... In C, it's very useful for any place where you need code to describe a data structure. I've used it e.g. to do run-time-generated GUI:s for setting options. This worked like this: a command that needs options defines a local structure holding its options, and then describes that structure to the code that gene...
1,453,497
1,453,573
Discover if user has Admin rights
How can I determine if the current user (the user running my application) has admin rights (i.e. is a member of the Administrator group)? I need to register some COM components differently for users with limited access. I am using C++ (WTL and Win32).
IsUserAnAdmin() is the fast and easy way, but MSDN warns that it might go away in the future, so you might want to call CheckTokenMembership() on your thread/process token instead (Comparing with a well known sid for the admin group)
1,453,568
1,453,620
Portable way to detect heap fragmentation in c++ at runtime?
I'm writing a qt-based c++ application and i need to be able to detect memory fragmentation in order to check if the current system can actually sustain the memory load: the program load a big image (15/21 megapixels are the norm) in memory and then perform some filtering on it (w/ sparse matrices). For instance, i'm h...
Short answer: There is no portable way. Longer answer: How the heap is implemented and how it works is an implementation detail of your implementation that widely differs between platforms, std libraries, and operating systems. You'll have to create a different version for each implementation - provided, the implement...
1,453,725
1,453,758
Sorting names with numbers correctly
For sorting item names, I want to support numbers correctly. i.e. this: 1 Hamlet 2 Ophelia ... 10 Laertes instead of 1 Hamlet 10 Laertes 2 Ophelia ... Does anyone know of a comparison functor that already supports that? (i.e. a predicate that can be passed to std::sort) I basically have two patterns to support: Lead...
That's called alphanumeric sorting. Check out this link: The Alphanum Algorithm
1,453,878
1,453,893
Distributed shared memory library for C++?
I am writing a distributed application framework in C++. One of the requirements is the provision of distributed shared memory. Rather than write my own from scratch (and potentially re-invent the wheel), I thought I would see if there were any pre-existing Open source libraries - a quick google search did not yield an...
Have you considered memcached ? It is network distributed and it can be really fast. It has bindings for lots of languages, you can access it from different OS and supports multiple writers multiple readers.
1,454,050
1,454,069
Borland C++ localization
I am currently using Codegear RAD Studio 2007. One of my company clients' decided that he would be interested in localized version of our software (to Russian - I don't know if it matters, that we won't be able to use standard windows code page). As a part of our software we are using RAVE to generate some reports. Is ...
I'm not sure about your particulars, but generally the gettext library is the right way to go about internationalization and googling for gettext borland c++ does yield some results.
1,454,058
1,462,211
Windows messages serviced whilst assert dialog is being displayed?
I have an MFC application that spawns a number of different worker threads and is compiled with VS2003. When calling CTreeCtrl::GetItemState() I'm occasionally getting a debug assertion dialog popup. I'm assuming that this is because I've passed in a handle to an invalid item but this isn't my immediate concern. My con...
The message box that shows the assertion failure has a message pump for its own purposes. But it'll dispatch all messages that come in, not just those for the message box (otherwise things could get blocked). With a normal modal dialog, this isn't a problem because the parent window is typically disabled for the durat...
1,454,208
1,454,288
Passing ant command line options to an exec'd ant process?
I'm using ant to build a mixture of Java and C++ (JNI) code that makes up a client project here. I've recently switched the C++ part of the build to using ant with cpptasks to build the C++ code instead of having ant invoke the various versions of Visual Studio that are necessary to build the code. In order to get this...
<target name="blah"> <property environment="env"/> <exec executable="cmd" failonerror="true"> <arg value="/C"/> <arg value="${cpp.compiler.path}/vsvars32.bat"/> <arg value="&amp;&amp;"/> <arg value="${env.ANT_HOME}/bin/ant.bat"/> <arg value="-f" /> <arg value="cpp-build.xml" ...