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 |
|---|---|---|---|---|
479,816 | 479,888 | networking lib + helper (c++) | Are there any c++ networking libs that are very useful and robust? and libs to help them be run better? something like automatically endian conversion when using <<, blocking reads until the struct or w/e your reading completely transfers, something to help debug your protocol, etc
| Have you had a look at Boost.Asio? It's a networking library supporting both asynchronous and synchronous operation. I've made some experiments with it in the past, and found it quite useful.
|
479,919 | 480,146 | Searching fast through a sorted list of strings in C++ | I have a list of about a hundreds unique strings in C++, I need to check if a value exists in this list, but preferrably lightning fast.
I am currenly using a hash_set with std::strings (since I could not get it to work with const char*) like so:
stdext::hash_set<const std::string> _items;
_items.insert("LONG_NAME_A_WI... | If your list of strings are fixed at compile time, use gperf
http://www.gnu.org/software/gperf/
QUOTE:
gperf is a perfect hash function generator. For a given list of strings, it produces a hash function and hash table, in form of C or C++ code, for looking up a value depending on the input string. The hash function i... |
480,211 | 480,232 | When I need to specialize the typename I declared in my template class, what arguments I must use? | I have a template class for thread-safe vector:
template <class T>
class SharedVector {
std::vector<T> vect;
CRITICAL_SECTION cs;
SharedVector(const SharedVector<T>& rhs) {}
public:
typedef typename std::vector<T>::size_type SizeType;
SharedVector();
void PushBack(const T& value);
void PopBa... | You have to provide a type argument for the SharedVector template:
SharedVector<Connection*>::SizeType size();
....
SharedVector<Connection*>::SizeType TCPClientManager::size() {
return connections.size();
}
Because that Connection* type is not a template parameter in TCPClientManager, but an explicit chosen type... |
480,233 | 481,598 | Are there any web frameworks for compiled languages like C++? | On our embedded device, we currently use PHP for its web interface, and unfortunately it's quite slow. We've been experimenting with Python, but is seems (at least on FPU-less ARM architecture) to be as slow as PHP.
Therefore we're thinking about implementing web interface in some compiled language like C++, but so far... | If I were you, I would give Wt a try. I don't think you will find another solution as complete and easy to use as Wt with similar performance. The mailinglist are active, and has regular posts of people who use it on embedded devices. The Wiki (here) of the project mentions some numbers for embedded deployment and perf... |
480,482 | 480,499 | Linux/c++ log rotation scheme | I have a logger system which basically is a fancy way of writing my data to std::clog in a thread safe way.
I also, redirect std::clog to a file like this:
int main() {
std::ofstream logfile(config::logname, std::ios::app);
std::streambuf *const old_buffer = std::clog.rdbuf(logfile.rdbuf());
// .. the gut... | You can use the built-in log rotation method configured in /etc/logrotate.conf and/or /etc/logrotate.d/ - it's common to have logrotate send your app a SIGUSR1 as a signal to close and re-open all your log files.
|
480,525 | 483,942 | Blocking read from FIFO via ifstream object | I open a FIFO file as ifstream. As soon as the object is created the thread is blocked until I send something into the FIFO (which is OK for me). Then I call getline() to get the data from the stream.
How do I read-block the thread again until more data is written into FIFO file?
Thanks
| I haven't tested this code but I'm wondering if the FIFO is simply setting the EOF bit when you read all available data. In that case, you might be able to do this:
std::ifstream fifo;
std::string line;
bool done = false;
/* code to open your FIFO */
while (!done)
{
while (std::getline(fifo, line))
... |
481,119 | 481,291 | Why does STL map core dump on find? | So, I have this situation where I need to see if an object is in my stl map. If it isn't, I am going to add it.
char symbolName[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
map<string,TheObject> theMap;
if (theMap.find(symbolName)==theMap.end()) {
TheObject theObject(symbolName);
theMap.insert(pair<s... | It can crash because of many reasons. Without knowing the definition of at least TheObject's constructors, i think we are largely left to guess at the problem. So far, your code looks fine, but it can be simplified:
char symbolName[] = "Hello";
map<string,TheObject> theMap;
theMap.insert(make_pair(symbolName, TheObject... |
481,196 | 481,382 | How to detect if a base 10 decimal can be represented exactly in base 2 | As part of a numerical library test I need to choose base 10 decimal numbers that can be represented exactly in base 2. How do you detect in C++ if a base 10 decimal number can be represented exactly in base 2?
My first guess is as follows:
bool canBeRepresentedInBase2(const double &pNumberInBase10)
{
//check if a ... | I think what you are looking for is a number which has a fractional portion which is the sum of a sequence of negative powers of 2 (aka: 1 over a power of 2). I believe this should always be able to be represented exactly in IEEE floats/doubles.
For example:
0.375 = (1/4 + 1/8) which should have an exact representation... |
482,073 | 482,091 | Make a copy of an unknown concrete type in c++ | Suppose we have the following class hierarchy:
class Base {
...
};
class Derived1 : public Base {
...
};
class Derived2 : public Base {
...
};
Given a Base* which could point to either a Derived1 or Derived2 object how can I make a copy of the actual object given that it's concrete type is unknown. I tho... | Unfortunately a virtual clone/copy pattern is your only real choice.
There are variations of this, but essentially they all come down to writing functions for each type that can return a new copy.
|
482,315 | 482,323 | How do you check for an invalid pointer? | My current code to the effect of:
if( objectPointer != NULL){
delete objectPointer;
}
doesn't work because the pointers are getting set to invalid hex numbers by the compiler such as:
0xbaadf00d
0xdeadbeef
etc....
So what's the best way to check for an invalid pointer before trying to delete the object?
| Always initialize your pointers to NULL (that is, 0). From http://www.lysator.liu.se/c/c-faq/c-1.html:
A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere.
|
482,726 | 482,737 | signal when user kills process? | I overloaded the 6 signals listed on this site http://www.cplusplus.com/reference/clibrary/csignal/signal.html
Then i ran my app (double click not ran through IDE) and tried 1) end task 2) X on topright and 3) kill process. I expected the first two to cause some kind of signal (i am on XP) but alas i got nothing. Am i ... | Win32 does not provide an option to intercept your program being killed with TerminateProcess (which is what will happen when you "End Task" from Task Manager or click on the [X]).
You can catch the SIGSEGV signal because the C runtime library provides an emulation of this signal when running on Windows. When your prog... |
482,745 | 484,304 | namespaces for enum types - best practices | Often, one needs several enumerated types together. Sometimes, one has a name clash. Two solutions to this come to mind: use a namespace, or use 'larger' enum element names. Still, the namespace solution has two possible implementations: a dummy class with nested enum, or a full blown namespace.
I'm looking for pros... | Original C++03 answer:
The benefit from a namespace (over a class) is that you can use using declarations when you want.
The problem with using a namespace is that namespaces can be expanded elsewhere in the code. In a large project, you would not be guaranteed that two distinct enums don't both think they are called ... |
482,798 | 482,825 | Accessing a subset (not subtree) of an object hierarchy | I have a base class "Node" which contains a list of child nodes. Node defines a "forEachNode" function which takes a callback as a parameter and calls it on each node in the hierarchy.
I have a class derived from Node - "SpecialNode" (not really a name I'd choose - just an example!). Node knows nothing about SpecialNo... | You can try something like:
if (dynamic_cast<SpecialNode*>(n) != NULL) {
do_something();
}
Or you put a virtual function in Node in order to be called from the callback which you can implement differently in the subclasses.
|
482,955 | 482,977 | Why was constness removed from Java and C#? | I know this has been discussed many times, but I am not sure I really understand why Java and C# designers chose to omit this feature from these languages. I am not interested in how I can make workarounds (using interfaces, cloning, or any other alternative), but rather in the rationale behind the decision.
From a lan... | In this interview, Anders said:
Anders Hejlsberg: Yes. With respect to
const, it's interesting, because we
hear that complaint all the time too:
"Why don't you have const?" Implicit
in the question is, "Why don't you
have const that is enforced by the
runtime?" That's really what people
are asking, altho... |
483,031 | 483,052 | Best way to get a query result | I'm developing an application that gets large images from an Internet server which is the best way to download this images, without freeze the entire application? I mean background download. I have thought about download it in another thread.
| Yes, you need to spawn another thread to do the network communication, and then when it is finished doing it's reading, you can use a volatile boolean flag to indicate that the work is complete and the main/application thread can take the data and incorporate it. The data may be "part" of an image if you want to show ... |
483,136 | 566,463 | Split a varbinary in a SELECT | I have a large varbinary field in one of my tables, and I would like to download in parts for show a download progress indicator in my application.
How can I split the data sent in a SELECT query?
Thanks
| You can do this with just the SQLGetData ODBC call. If the buffer size you provide is smaller than the total varbinary size, it will fill the buffer and return SQL_SUCCESS_WITH_INFO and and SQLSTATE 01004. If you call it again, it will return the next segment of data. You just repeat until all the data is retrieved. To... |
483,164 | 483,286 | Looking for benchmarking code snippet (c++) | Some loading routines in my program takes to long to complete. I want a quick small snippet for checking how long a function took to execute. By small I mean "preferably without 3rd party libraries".
Maybe something as simple as taking the system time?
start = current_system_time()
load_something()
delta = current_syst... | Your answer: Yes
Caveat: That WON'T work in multihtreaded code or multiple core machines, you need a robust wall-clock timer.
So I recommend you use omp's wallclock. OMP is included with VC and GCC, and most compilers and its a standard you don't need to worry about disappearing
#include <omp.h>
// Starting the time m... |
483,276 | 483,314 | How to prevent crashing if com dll isnt registered | From some old c++ code im trying to use a com dll, it works fine when the dll is registered, but it crahses if the dll isnt registered.
// Initialize COM.
HRESULT hr = CoInitialize(NULL);
IGetTestPtr ptest(__uuidof(tester));
"Use method from the dll"
// Uninitialize COM.
CoUninitialize();
Is it anyway to check if the d... | Calling CreateInstance on your object will return an HRESULT that can be tested for success:
IGetTestPtr p = null;
HRESULT hRes = p.CreateInstance( __uuidof(tester) );
bool bSuccess = SUCCEEDED(hRes);
This assumes you've created an interface wrapper around your type library using Visual Studio, where COM Smart Pointe... |
483,609 | 483,653 | How can I convert hexadecimal numbers to binary in C++? | I am taking a beginning C++ class, and would like to convert letters between hex representations and binary. I can manage to print out the hex numbers using:
for(char c = 'a'; c <= 'z'; c++){
cout << hex << (int)c;
}
But I can't do the same for binary. There is no std::bin that I can use to convert the decimal num... | Like so:
for(char c = 'a'; c <= 'z'; c++){
std::bitset<sizeof(char) * CHAR_BIT> binary(c); //sizeof() returns bytes, not bits!
std::cout << "Letter: " << c << "\t";
std::cout << "Hex: " << std::hex << (int)c << "\t";
std::cout << "Binary: " << binary << std::endl;
}
|
483,652 | 483,765 | XA distributed transactions in C++ | Is there a good C++ framework to implement XA distributed transactions?
With the term "good" I mean usable, simple (doesn't imply "easy"), well-structured.
Due to study reasons, at the moment I'm proceeding with a personal implementation, following X/Open XA specification.
Thank you in advance.
| I am not aware of an open-source or free transaction monitor that has any degree of maturity, although This link does have some fan-out. The incumbent commercial ones are BEA's Tuxedo, Tibco's Enterprise Message Service (really a transactional message queue manager like IBM's MQ) and Transarc's Encina (now owned by IB... |
483,797 | 483,887 | Dynamic Shared Library compilation with g++ | I'm trying to compile the following simple DL library example code from Program-Library-HOWTO with g++. This is just an example so I can learn how to use and write shared libraries. The real code for the library I'm developing will be written in C++.
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
int main... | C allows implicit casts from void * to any pointer type (including function pointers); C++ requires explicit casting. As leiflundgren says, you need to cast the return value of dlsym() to the function pointer type you need.
Many people find C's function pointer syntax awkward. One common pattern is to typedef the funct... |
483,919 | 483,965 | CTreeCtrl - getting an item position | Is there a way of getting the position (index) of an item in a CTreeCtrl?
I am interested in the index of a node at its particular level.
I was thinking to maintain the item positions within the item "data" field, but the problem is that my tree is sorted and I cannot predict the position an item will receive (well, ... | I don't think you can. I assumed that maybe the control could be treated as an array (maybe it still can but I can't find a reference).
Anyways, there are no member functions (according to the MFC API) that give you access to that information
|
483,971 | 484,149 | Why is my ReadDirectoryChangesW not picking up changed files? | I'm sure I am just doing something really dumb and not seeing it but can anyone tell me why the following code would not be picking up changes in the passed in directory?
When calling this code, creating and modifying files or directories in the passed in m_directory is ignored. But if I call
PostQueuedCompletionSt... | Did you check the return values? And is this over a network?
Edit: You probably want to initialize OVERLAPPED to zero.
|
484,142 | 495,448 | How can you make an MFC application with an HTML view consistently accept drag-dropped files? | I'm trying to decipher CHtmlView's behaviour when files are dragged into the client area, so I've created a new MFC app and commented out the CHtmlView line that navigates to MSDN on startup. In my main frame, I've overridden CWnd::OnDropFiles() with a function that shows a message box, to see when WM_DROPFILES is sen... | This is part of the underlying WebBrowser control behaviour. CHtmlView sets RegisterAsDropTarget to true by default, which means the control intercepts the drop operation and performs its own processing.
If you want to inhibit it, call SetRegisterAsDropTarget(FALSE) in your OnInitialUpdate implementation. All drop oper... |
484,172 | 484,551 | Do we need a Java++? | It seems to me that, in some ways, Java is where C was a while back. Both are fairly minimalist languages for their time, with relatively clean, simple cores to build on. (I'm referring to the core language here, not the libraries.) Both are/were extremely popular. Both are/were lingua francas, with tons of legacy ... | Going to get downvoted by the Java fanboys for this but as someone who writes both Java and C# I'd say that C# is as close to Java ++ as you are going to get.
C to C++ was a paradigm shift, from procedural to Object oriented, the only reason they retain the name is to woo C programmers into thinking that it was the sam... |
484,213 | 484,386 | Replace line breaks in a STL string | How can I replace \r\n in an std::string?
| Use this :
while ( str.find ("\r\n") != string::npos )
{
str.erase ( str.find ("\r\n"), 2 );
}
more efficient form is :
string::size_type pos = 0; // Must initialize
while ( ( pos = str.find ("\r\n",pos) ) != string::npos )
{
str.erase ( pos, 2 );
}
|
484,466 | 484,686 | Best way to create a timer on screen | I had this idea of creating a count down timer, like 01:02, on the screen (fullsize).
One thing is that I really don't have a clue on how to start.
I do know basic c/c++, win32 api and a bit of gdi.
Anyone have any pointers on how to start this? My program would be like making the computer into a big stopwatch (but wi... | If you have some experience with windows message processing and the Win32 API, this should get you started.
LRESULT WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT r;
char szBuffer[200];
static int count = 120;
int seconds = 0;
int minutes = 0;
int ... |
484,592 | 484,736 | Overriding public virtual functions with private functions in C++ | Is there is any reason to make the permissions on an overridden C++ virtual function different from the base class? Is there any danger in doing so?
For example:
class base {
public:
virtual int foo(double) = 0;
}
class child : public base {
private:
virtual int foo(double);
}
The C++ faq say... | The problem is that the Base class methods are its way of declaring its interface. It is, in essence saying, "These are the things you can do to objects of this class."
When in a Derived class you make something the Base had declared as public private, you are taking something away. Now, even though a Derived object "... |
484,707 | 489,073 | Viewing a dynamically-allocated array with the Xcode debugger? | Let's say I have an array in C++:
double* velocity = new double[100];
Using the GDB command line, I can view this array with the command:
> print *velocity @ 100
and it will print a nicely-formatted list of all the double values inside the array.
However, when using the Xcode debugger, the most it will do is treat th... | You can use gdb syntax as expressions:
Use Run/Show/Expressions... menu to show the expressions window
Enter '*velocity @ 100' at the bottom of the window (Expression:)
|
484,758 | 484,779 | unable to pass a pointer to a function between classes | I'm attempting to pass a pointer to a function that is defined in one class into another class. After much research, I believe my syntax is correct, but I am still getting compiler errors. Here is some code which demonstrates my issue:
class Base
{
public:
BaseClass();
virtual ~BaseClass();
};
class Derived ... | your syntax is correct for a C style function pointer. Change it to this:
Derived(string (MainClass::*funPtr)(int)) : strFunction(funPtr) {}
and
string (MainClass::*strFunction)(int value);
remember to call strFunction, you will need an instance of a MainClass object. Often I find it useful to use typedefs.
typedef s... |
484,853 | 484,867 | Levenshtein algorithm: How do I meet this text editing requirements? | I'm using levenshtein algorithm to meet these requirements:
When finding a word of N characters, the words to suggest as correction in my dictionary database are:
Every dictionary word of N characters that has 1 character of difference with the found word.
Example:
found word:bearn, dictionary word: bears
Every dict... | You may also want to add Norvig's excellent article on spelling correction to your reading.
It's been a while since I've read it but I remember it being very similar to what your writing about.
|
484,882 | 484,915 | What OOP design decision will suit the situation of protocol in client/server app? | I am writing a client/server app in C++ and need to realize simple protocol to sent and receive data correctly. I have a class for server protocol which can convert the message to my format and then convert it again from this format.
That what is server-side protocol looks like:
class BaseProtocol {
protected:
int... | I would create a protocol class independent of both the client and the server. They can each call the functions of that class rather than inheriting from the class.
This follows the principle of favoring composition over inheritance. Also, neither the client nor the server "is a" protocol interpreter. Rather, they eac... |
485,155 | 485,271 | C/C++ Performance Globals vs Get/Set Methods | I saw this question asking about whether globals are bad.
As I thought about the ramifications of it, the only argument I could come up with that they're necessary in some cases might be for performance reasons.
But, I'm not really sure about that. So my question is, would using a global be faster than using a get/set... | A more appropriate comparison would be between accessing a global (a static) and a local.
Indeed a global is faster because accessing a local requires the variable offset to be added to the value of the stack pointer.
However, you will never, ever need to worry about this. Try concentrating on things that matter, such ... |
485,230 | 485,251 | C++ Tokenizing using iterators in an eof() cycle | I'm trying to adapt this answer
How do I tokenize a string in C++?
to my current string problem which involves reading from a file till eof.
from this source file:
Fix grammatical or spelling errors
Clarify meaning without changing it
Correct minor mistakes
I want to create a vector with all the tokenized words. ... | Using a while (!….eof()) loop in C++ is broken because the loop will never be exited when the stream goes into an error state!
Rather, you should test the stream's state directly. Adapted to your code, this could look like this:
while (getline(streamOfText, readTextLine)) {
cout << readTextLine << endl;
}
However,... |
485,358 | 485,434 | Why did I get a Segmentation Fault with a map insert | I want to insert a pair< string, vector<float> > into a map, first it works, but after several loops, it cannot insert any more and throw me a segmentation fault. Can anybody give a possible reason?
Btw: I first read a file and generate the map (about 200,000 elements) and I read another file and update the old map. ... | The type in question is pair<string, vector<float> >. You will be copying that pair on every insert. If either the string or the vector are big then you could be running out of memory.
Edit: to fix running out of memory, you can change how you insert key-value pairs to:
pair<map::iterator, bool> insert_result= map.inse... |
485,371 | 485,445 | How do I alter this tokenization process to work on a text file with multiple lines? | I'm working this source code:
#include <string>
#include <vector>
#include <iostream>
#include <istream>
#include <ostream>
#include <iterator>
#include <sstream>
#include <algorithm>
int main()
{
std::string str = "The quick brown fox";
// construct a stream from the string
std::stringstream strstr(str);
//... | Yes, then you have one whole line in readTextLine. Is it that what you wanted in that loop? Then instead of constructing the vector from the istream iterators, copy into the vector, and define the vector outside the loop:
std::vector<std::string> results;
while (getline(streamOfText, readTextLine)){
std::istringstr... |
485,448 | 2,962,150 | Programmatically access CPU fan on a laptop? (Windows) | Is there a Windows standard way to do things such as "start fan", "decrease speed" or the like, from C/C++?
I have a suspicion it might be ACPI, but I am a frail mortal and cannot read that kind of documentation.
Edit: e.g. Windows 7 lets you select in your power plan options such as "passive cooling" (only when things... | I am at the moment working on a project that, among other things, controls the computer fans. Basically, the fans are controlled by the superIO chip of your computer. We access the chip directly using port-mapped IO, and from there we can get to the logical fan device. Using port-mapped IO requires the code to run in k... |
485,525 | 11,101,890 | round() for float in C++ | I need a simple floating point rounding function, thus:
double round(double);
round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1
I can find ceil() and floor() in the math.h - but not round().
Is it present in the standard C++ library under another name, or is it missing??
| It's available since C++11 in cmath (according to http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf)
#include <cmath>
#include <iostream>
int main(int argc, char** argv) {
std::cout << "round(0.5):\t" << round(0.5) << std::endl;
std::cout << "round(-0.5):\t" << round(-0.5) << std::endl;
std::cout... |
485,649 | 501,573 | Confusing gprof output | I ran gprof on a C++ program that took 16.637s, according to time(), and I got this for the first line of output:
% cumulative self self total
time seconds seconds calls s/call s/call name
31.07 0.32 0.32 5498021 0.00 0.00 [whatever]
Why does it list 3... | The bottleneck turned out to be in file I/O (see Is std::ifstream significantly slower than FILE?). I switched to reading the entire file in a buffer and it sped up enormously.
The problem here was that gprof doesn't appear to generate accurate profiling when waiting for file I/O (see http://www.regatta.cs.msu.su/doc/u... |
485,730 | 485,744 | Keys / Values Functionality to Iterators in C++ | I know this questions has come up in various guises before, but this is slightly different.
I have a class which contains a std::map. Although I wish to use the map for other purposes inside the class, externally I want to expose an iterator adapter to just the values inside the map (ie the second item in the std::pair... | Have a look at Boost's transform_iterator which provides exactly this kind of functionality:
template <typename K, typename V>
struct get_value {
const V& operator ()(std::pair<K, V> const& p) { return p.second; }
};
class your_class {
typedef map<int, float> TMap;
TMap mymap;
public:
typedef get_valu... |
486,087 | 486,409 | How to call an external program with parameters? | I would like to call a windows program within my code with parameters determined within the code itself.
I'm not looking to call an outside function or method, but an actual .exe or batch/script file within the WinXP environment.
C or C++ would be the preferred language but if this is more easily done in any other lang... | When you call CreateProcess(), System(), etc., make sure you double quote your file name strings (including the command program filename) in case your file name(s) and/or the fully qualified path have spaces otherwise the parts of the file name path will be parsed by the command interpreter as separate arguments.
syste... |
486,252 | 486,259 | Class design suggestions - C++ | Background
I am working on a phonetic converter program which converts english text into equivalant regional language text. Regional languages will have more characters than english letters and regional language fonts uses almost all positions (1-255) in a font.
My program supports different fonts and I have created a... | I suggest you use a standard encoding of non-ASCII (regional) characters.
A standard encoding is called "unicode", for example http://www.joelonsoftware.com/articles/Unicode.html
Anyway: to answer your questions ...
Will 255 virtual functions in a single class make any performance issues?
In a word: no, it won't.
Bu... |
486,313 | 531,185 | How to check if a Server and Client are in the same concurrency model? | The concurrency model can be either apartment-threaded or multi-threaded
Question:
How to ensure that both the Client and Server are operating from within the same concurrency model?
| Sometimes you need to know. Two quick examples:
Performance hit of proxy/stub pairs is a problem
You need to pass around "unmarshallable" data or objects
So, the answer -- if you do need to know:
The server and the client must be designed and implemented to support the same or compatible models. Either one of these s... |
486,435 | 486,498 | Where can I find MSCVR80.DLL v8.0.50727.3053? | I've got a bug from one of our customers and believe that the problem lies with MSVCR80.DLL v8.0.50727.3053 - a version which I cannot find for download anywhere, however a google search turns up plenty of other crash reports.
Latest version on my system (and others here) is 8.0.50727.1433 and the Microsoft Visual C++ ... | A thread on the MSDN forums pointed out the answer: msvcr80.dll version 8.0.50727.3053 is included in .NET Framework 3.5 SP1
|
486,454 | 486,465 | Basic C++ question regarding scope of functions | I'm just starting to learn C++ so you'll have to bear with my ignorance. Is there a way to to declare functions such that they can be referenced without being written before the function that uses them. I'm working with one cpp file (not my decision) and my functions call themselves so there is not really a proper orde... | You can write function prototypes before you implement them. A function prototype names a function, its return type, and the type of its arguments. The only thing that needs to be above the call to your function is the prototype. Here's an example:
// prototype
int your_function(int an_argument);
// ...
// here you ca... |
486,508 | 486,597 | How does template argument shadowing work in VS2005? | In GCC this code won't compile, because T gets shadowed, however in VS2005 it compiles with no warnings, so what are the assumptions VS compiler is making?
template<typename T>
class Foo
{
template<typename T>
void Bar(const T& bar)
{
...
}
};
| Found the right answer after 3 months of searching :) It's in 14.6.1/4 of the Standard:
A template-parameter shall not be redeclared within its scope (including nested scopes). A template-parameter shall not have the same name as the template name.
Example:
template<class T, int i> class Y {
int T;
// error: ... |
486,555 | 488,832 | Is there a correct way to avoid warnings when comparing two different enums? | When comparing enums that come from different sources such as those of the following code GCC emits warnings. Is there a way to avoid these warnings without c-style casts?
struct Enumerator
{
enum { VALUE = 5 };
};
template<int V>
struct TemplatedEnumerator
{
enum { VALUE = V };
};
if(Enumerator::VALUE == Tem... | Simple answer in your case: don't use an enum, use an inline-defined static const int:
struct Enumerator
{
static int const VALUE = 5;
};
template<int V>
struct TemplatedEnumerator
{
static int const VALUE = V;
};
In this special case, that's equivalent and all compilers of the last few years should treat it ... |
486,562 | 486,767 | Variable height items in Win32 ListView | Is it possible to have variable size (owner draw) items in the Win32 ListView, if yes, how?
| Check out WM_MEASUREITEM
|
486,797 | 486,820 | What is an analog for win32 file locking in boost::interprocess? | What sync mechanism should I use to give exclusive access to the text file in boost?
The file will likely be accessed by threads from only one process.
| If you are sure it will only be accessed from one process, a read-write lock with file handles in thread local storage could be a solution. That would simulate the above with only one writer but several readers.
|
487,035 | 487,039 | How to Convert 64bit Long Data Type to 16bit Data Type | I would like to know how to convert 64 bit long Data Type to any of the 16 bit Data Types. This feature is required in the Ethernet Application to include the Time Stamp. Only 2 Bytes ( 16 bits ) are available to include the Time Stamp. But we are getting 64 bit long as the Time Stamp value from Win API. So a conversio... | Well, you can't fit 64 bits of information into 16 bits of storage without losing some of the information.
So it's up to you how to quantize or truncate the timestamp. E.g. suppose you get the timestamp in nanosecond precision, but you only need to store it at seconds precision. In that case you divide the 64 bit numbe... |
487,048 | 487,058 | Difference between const declarations in C++ | What is the difference between
void func(const Class *myClass)
and
void func(Class *const myClass)
See also:
C++ const question
How many and which are the uses of "const" in C++?
and probably others...
| The difference is that for
void func(const Class *myClass)
You point to a class that you cannot change because it is const.
But you can modify the myClass pointer (let it point to another class; this don't have any side effects to the caller because it's pointer is copied, it only changes your local the pointer copy)
... |
487,108 | 487,520 | How to suppress specific warnings in g++ | I want to suppress specific warnings from g++. I'm aware of the -Wno-XXX flag, but I'm looking for something more specific. I want some of the warnings in -Weffc++, but not all of them. Something like what you can do with lint - disable specific messages.
Is there a built in way in gcc to do this? Do I have to write a ... | Unfortunately, this feature isn't provided by g++. In VC++, you could use #pragma warning to disable some specific warnings. In gcc, the closest you can have is diagnostic pragmas, which let you enable/disable certain types of diagnostics for certain files or projects.
Edit: GCC supports pushing/popping warnings since ... |
487,114 | 487,155 | C/C++ Header file documentation | What do you think is best practice when creating public header files in C++?
Should header files contain no, brief or massive documentation? I've seen everything from almost no documentation (relying on some external documentation) to large specifications of invariants, valid parameters, return values etc. I'm not sur... | Usually I put documentation for the interface (parameters, return value, what the function does) in the interface file (.h), and the documentation for the implementation (how the function does) in the implementation file (.c, .cpp, .m).
I write an overview of the class just before its declaration, so the reader has imm... |
487,243 | 487,362 | Implementation in global functions, or in a class wrapped by global functions | I have to implement a set of 60 functions, according to the predefined signatures. They must be global functions, and not some class's member functions. When I implement them, I use a set of nicely done classes provided by 3rd party.
My implementation of most functions is quite short, about 5-10 lines, and deals mostly... |
All the state information is stored in the static members of my and 3rd party's classes, so I don't have to create global variables.
That is the keypoint. No, they should definitely not be put into classes. Classes are made to be used for creating objects. In your situation, you would use them just as a scope, for th... |
487,283 | 488,076 | Storing and Retrieving Dynamically Changing Structures | I am creating a game using Allegro/C++. The game is almost done and now, I want to create a map editor. The game contains numerous classes and their number will vary depending on the number of objects the map requires. I was thinking of creating a separate structure to hold level data and store it as a map. The problem... | So, what you want to do is serialization.
I suggest simply using an already existing library for that. Have a look at this thread: How to serialize in c++ ?
|
487,342 | 490,895 | Error in QSqlTableModel inherited table | I have this class that inherits from QSqlTableModel and it brokes after calling the submitAll() slot, after calling insertPoint some times. Here is the code.
Thanks for the help.
Regards.
#ifndef VWLANDMARKTABLEMODEL_H
#define VWLANDMARKTABLEMODEL_H
#include <QSqlTableModel>
class GraphicsPointLandmarkItem;
class VW... | The problem was in my custom select. Calling setFilter() causes a infinite calling loop
|
487,416 | 487,567 | Making a C++ app scriptable | I have several functions in my program that look like this:
void foo(int x, int y)
Now I want my program to take a string that looks like:
foo(3, 5)
And execute the corresponding function. What's the most straightforward way to implement this?
When I say straightforward, I mean reasonably extensible and elegant, but ... | I'd also go for the scripting language answer.
Using pure C++, I would probably use a parser generator, which will will get the token and grammar rules, and will give me C code that exactly can parse the given function call language, and provides me with an syntax tree of that call. flex can be used to tokenize an inp... |
487,566 | 487,599 | Why Does This Pointer-Pointer Initialization Seg Fault? | I create a pointer-to-pointer of a class object and when I try to create a new object using the pointers it seg-faults. Why does this happen?
struct Level
{
int SoldierCount;
Soldier **soldier;
int taskCount;
int *taskPercentage;
int *taskBitmapX;
int *taskBitmapY;
}le... | With empty Soldier constructor your code works fine (except for corrected typos, like lowercase level.soldier[])
Please post the constructor body.
|
487,866 | 492,525 | HOT(Heap On Top) Queues | Could anyone point me to an example implementation of a HOT Queue or give some pointers on how to approach implementing one?
| Here is a page I found that provides at least a clue toward what data structures you might use to implement this. Scroll down to the section called "Making A* Scalable." It's unfortunate that the academic papers on the subject mention having written C++ code but don't provide any.
|
488,456 | 488,474 | Why can't I get a decent function browser in Visual Studio 2008? | There is no way to list the functions in a C++ solution for me... I have a class browser but that isn't helpful since this project has no classes. I need a simple list of all the functions in a c++ file and then just double click one to jump to its source (as a side pane, NOT as a dropdown)... I have to be missing some... | I've never found a built-in way to do this, in 10 years of working with Visual Studio. However, Visual Assist X will do this for you in its Outline View. The down side is that it's not free, but I've found it to be an essential tool for working with C++ in Visual Studio. Well worth the money IMHO.
|
488,687 | 488,697 | Refactoring a class in C++ | I have a class A which implements many functions. Class A is very stable.
Now I have a new feature requirement, some of whose functionality matches that implemented by A. I cannot directly inherit my new class from class A, as that would bring lot of redundancy into my new class.
So, should i duplicate the common ... | Unless there is a very good reason not to modify class A, refactor and make a common base (or even better, a common class that both can use, but not necessarily derive from).
You can always use private inheritance to gain access to the shared functionality without modifying class As external interface - this change wou... |
488,729 | 488,762 | Are these appropriate practices when working with std::map? | I have some questions on using std::map:
Is using an enum as the key in std::map a good practice? Consider the following code:
enum Shape{
Circle,
Rectangle
};
int main(int argc, char* argv[])
{
std::map<Shape,std::string> strMap;
// strMap.insert(Shape::Circle,"Circle"); // This will not compile
... |
Having an enum as key_type is not bad by itself. (edit) But if you only use sequential enum-values, a std::vector with O(1) access is even better.
insert must be used like this: mapVar.insert(make_pair(key, value));
See also cppreference.com.
Yes, std::map has O(log(n)) lookup, as guaranteed by the standard, and this... |
488,837 | 488,880 | How do I create a GUI for a windows application using C++? | I am deciding on how to develop a GUI for a small c++/win32 api project (working Visual Studio C++ 2008). The project will only need a few components to start off the main process so it will be very light weight (just 1 button and a text box pretty much...). My question is this:
I don't have experience developing GUIs ... | If you're doing a very simple GUI and you're already using Visual Studio then it may make sense to just go with MFC. You can just use the Visual Studio MFC wizard to create a dialog based application, drop two controls on it and away you go.
MFC is dated and has its fair share of annoyances, but it will certainly do t... |
488,874 | 488,977 | How to reset a class using placment delete/new from a template? | I have a pool manager template class. When a class object gets added back to the pool manager I would like to reset it back to it's initial state. I would like to call the placment destructor and placment constructor on it so it gets fully reset for the next time it is given out by the pool manager. I've tried many way... | How about:
template <class T>
void PoolClass<T>::ReleaseToPool(T *obj)
{
obj->~T(); //call destructor
obj = new ((void *)obj)T(); //call constructor
// add a pointer to the object to the list...
}
|
488,959 | 488,989 | How do you create a static template member function that performs actions on a template class? | I'm trying to create a generic function that removes duplicates from an std::vector. Since I don't want to create a function for each vector type, I want to make this a template function that can accept vectors of any type. Here is what I have:
//foo.h
Class Foo {
template<typename T>
static void RemoveVectorDuplic... | Short Answer
Define the function in the header, preferably inside the class definition.
Long answer
Defining the template function inside the .cpp means it won't get #included into any translation units: it will only be available to the translation unit it's defined in.
Hence RemoveVectorDuplicates must be defined in t... |
489,364 | 491,069 | transform_iterator compile problem | HI,
I don't like posting compile problems, but I really can't figure this one out. Using this code:
#include <map>
#include <boost/iterator/transform_iterator.hpp>
using namespace std;
template <typename K, typename V>
struct get_value
{
const V& operator ()(std::pair<K, V> const& p) { return p.second; }
};
clas... | Since you also asked for an explanation
The transform_iterator needs to know the return type of the function called in order to instantiate itself. This is determined via result_of (found in <boost/utility/result_of.hpp>
If you use a function object, you need to define a member result_type to specify the result type of... |
489,880 | 489,900 | Code Dependency documentation software | I am looking for a tool to document legacy source code for an embedded C project I work with. I had it in my mind that there was a tool that would create charts of the various C and .h files, but I can't recall what it is called. Does anyone know of such a tool?
| There's a big list at this url too.
|
490,005 | 490,099 | Best c++ container to strip items away from? | I have a list of files (stored as c style strings) that I will be performing a search on and I will remove those files that do not match my parameters. What is the best container to use for this purpose? I'm thinking Set as of now. Note the list of files will never be larger than when it is initialized. I'll only be de... | I would definitely not use a set - you don't need to sort it so no point in using a set. Set is implemented as a self-balancing tree usually, and the self-balancing algorithm is unnecessary in your case.
If you're going to be doing this operation once, I would use a std::vector with remove_if (from <algorithm>), follow... |
490,235 | 490,351 | hostname not translated into an IP address using Winsock | getaddrinfo() does not translate a hostname into an IP address and consequently does not connect() to the server. Is something wrong with my implementation - compiles with no warning messages?
Is this function call to connect correct?
connect(client, result->ai_addr, result->ai_addrlen)
Full implementation listed belo... | getaddrinfo may be giving you an IPv6 address, or perhaps the machine has more than one IP address and you're trying to connect to the wrong one.
Also, if your server is listening on 127.0.0.1 and you try to connect to the real IP address, the connection will fail. Similarly, if the server is listening on the real IP a... |
490,403 | 490,409 | There are Strings in C++? | I have been learning C++ with some books from school that are from the 80's and I'm not really sure if they are strings in C++ or just really long arrays of type char. Can anyone help?
| There is a string class in C++.
|
490,430 | 490,518 | LoaderLock error on program termination | I have recently integrated the .NET NLog logging component into one of our applications which developed purely in unmanaged code (C++ and VB6 components compiled in Visual Studio 6). We have a bunch of C++ application talking to NLog via a COM interface.
Everything is working fine at the moment but I do notice that the... | It is most definitely not safe to ignore this message. If you hit this message, you've almost certainly created a real loader lock policy violation. This is a very serious error and can cause unpredictable behavior in a program (including deadlock).
The best way to avoid this is to not access any other .Net Object... |
490,487 | 490,496 | Returning a reference from a constant function | #include "iostream"
#include "vector"
class ABC {
};
class VecTest {
std::vector<ABC> vec;
public:
std::vector<ABC> & getVec() const { //Here it errors out
return vec;
}
};
Removing the const fixes it , is it not the case that getVec is a constant method. So why is this not allowed?
| What you should probably be doing is returning a const reference.
const std::vector& getVec() const { return vec; }
It's not allowed because you've said getVec is a const method, meaning the method should not change the this object in any way. Returning a non-const reference would possibly allow its object to be change... |
490,720 | 490,809 | Including boost::filesystem produces linking errors | Ok first off, I am linking to boost_system and boost_filesystem.
My compiler is a custom build of MinGW with GCC 4.3.2
So when I include:
#include "boost/filesystem.hpp"
I get linking errors such as:
..\..\libraries\boost\libs\libboost_system.a(error_code.o):error_code.cpp:
(.text+0xe35)||undefined reference to `_... | Ok, I found the problem. It's a bit convoluted.
GCC is gradually becoming more IS 14882 compliant in the 4.x branch. As they go on, they are removing deprecated non-standards complaint features.
While 4.1.x seem to only have them deprecated and not removed, 4.3.x seems to actually have them removed. What this means is ... |
490,737 | 491,006 | Making GCC and other C++ compilers very strict | I'm working on a large collaborative C++ project that is both developed and run on various flavors of Linux, OS X and Windows. We compile across these platforms with GCC, Visual Studio C++ and the Intel C++ compiler. As more and more people start developing code for the project, we're starting to see weird errors in co... | Beside the pedantic-error that everyone else suggested, IMO, it's always good to run lint as part of your compile process.
There are some tools out there:
cpplint (free)
gimple lint
coverity
They will save a lot of your time.
|
490,773 | 491,120 | How is the C++ exception handling runtime implemented? | I am intrigued by how the C++ exception handling mechanism works. Specifically, where is the exception object stored and how does it propagate through several scopes until it is caught? Is it stored in some global area?
Since this could be compiler specific could somebody explain this in the context of the g++ compile... | Implementations may differ, but there are some basic ideas that follow from requirements.
The exception object itself is an object created in one function, destroyed in a caller thereof. Hence, it's typically not feasible to create the object on the stack. On the other hand, many exception objects are not very big. Erg... |
490,803 | 490,817 | Describing header file locations in makefile | In a new project I am working on I have the following dir structure:
Project_base
|---- src
|---- bin
|---- h
| Makefile
And in my source files I have includes that look like so:
#include "../h/SomeHeaderFile.h"
instead of the more correct form:
#include "SomeHeaderFile.h"
What do I need to add to my makefile so tha... | You need to add -I../h in the list of parameters you pass to gcc.
|
491,000 | 491,511 | friend class : inherited classes are not friend as well? | In C++, I have a class A which is friend with a class B.
I looks like inherited classes of B are not friend of class A.
I this a limitation of C++ or my mistake ?
Here is an example. When compiling, I get an error on line "return new Memento":
Memento::Memento : impossible to access private member declared in Memento.
... | See: Friend scope in C++
Voted exact duplicate.
I looks like inherited classes of B are not friend of class A.
Correct
I this a limitation of C++ or my mistake ?
It is the way C++ works. I don't see it as a limitation.
|
491,060 | 491,095 | How to convert standard IP address format string to hex and long? | Does anyone know how to get the IP address in decimal or hex from standard IP address format string ("xxx.xxx.xxx.xxx")?
I've tried to use the inet_addr() function but didn't get the right result.
I tested it on "84.52.184.224"
the function returned 3770168404 which is not correct (the correct result is 1412741344).
Th... | The htonl, htons, ntohl, ntohs functions can be used to convert between network and local byte orders.
|
491,199 | 491,341 | Why don't Java, C# and C++ have ranges? | Ada, Pascal and many other languages support ranges, a way to subtype integers.
A range is a signed integer value which ranges from a value (first) to another (last).
It's easy to implement a class that does the same in OOP but I think that supporting the feature natively could let the compiler to do additional static ... | Subrange types are not actually very useful in practice. We do not often allocate fixed length arrays, and there is also no reason for fixed sized integers. Usually where we do see fixed sized arrays they are acting as an enumeration, and we have a better (although "heavier") solution to that.
Subrange types also compl... |
491,304 | 494,714 | Pimpl idiom with inheritance | I want to use pimpl idiom with inheritance.
Here is the base public class and its implementation class:
class A
{
public:
A(){pAImpl = new AImpl;};
void foo(){pAImpl->foo();};
private:
AImpl* pAImpl;
};
class AImpl
{
public:
void foo(){/*do something*/};
};
And I want to be able t... | class A
{
public:
A(bool DoNew = true){
if(DoNew)
pAImpl = new AImpl;
};
void foo(){pAImpl->foo();};
protected:
void SetpAImpl(AImpl* pImpl) {pAImpl = pImpl;};
private:
AImpl* pAImpl;
};
class AImpl
{
public:
void foo(){/*do something*/};
};
class... |
491,487 | 2,187,462 | DirectX Font tutorial that doesn't use GDI | Does anyone have any tutorials/info for creating and rendering fonts in native directx 9 that doesn't use GDI? (eg doesn't use ID3DXFont).
I'm reading that this isn't the best solution (due to accessing GDI) but what is the 'right' way to render fonts in dx?
| ID3DXFont is a great thing for easy to use, early, debug output. However, it does use the GDI for font rasterization (not hardware accelerated) and there is a significant performance hit (try it, its actually very noticable). As of DirectX 11, though, fonts will be rendered with Direct2D and be hardware accelerated.
Th... |
491,883 | 495,326 | Howto format a boost::date_time-object as per RFC 3339 | I want to use the date_time library in boost to represent time in my application. This application will generate Atom feeds, which in turn mandates time-stamps in the format specified in RFC 3339, for example "1990-12-31T23:59:60Z" or "1990-12-31T15:59:60-08:00".
So, how do I format time according to this RFC?
I have b... |
ABNF from RFC says that there must be at least one digit after dot, there is no defined maximum.
There is no real need for the Z, you can use 00:00 instead, and this is possible with facets
In some rare circumstances date_time will generate a "Z". See code snapshot from boost (local_date_time.hpp) that suggests this i... |
491,972 | 492,007 | Giving to child access to parent's member by reference - is it OK? | C++ newbie question. Please, verify I'm doing it right.
I have a global application class spawning it's little kids and I need to give the kids access to some of the application facilities. So I decided to pass them to children by reference.
I tested the idea as show below. It seems to work fine. I just wanted to make ... | Looks good to me (if keys is all they need). They might need some other services from Dad which are requested later - like:
Wallet += MyDad.GasMoney(REQUEST_MAX_AND_PROMISE_TO_BE_HOME_BY_10PM) ;
But they don't have a reference to Dad, so they won't be able to do that. So I would have the CChild constructor take a th... |
491,994 | 492,086 | Is it possible to treat a template instance as a namespace? | Suppose I have
template< unsigned int num >
class SomeFunctionality
{
static unsigned int DoSomething()
{
//...
}
static void DoSomethingElse()
{
}
};
typedef SomeFunctionality<6> SomeFunctionalityFor6;
Semantically, "SomeFunctionalityFor6" is essentially a namespace spec... | You can't do that. Neither templatized namespace, nor using class_name.
The only places in the code that can use static functions from a class without qualification are derived classes.
In your case, I would use a typedef for some short name, like
int main()
{
typedef SomeFunctionalityFor6 SF6;
SF6::DoSom... |
492,014 | 492,392 | How to start writing a PHP5 extension in C++ | I'm writing a PHP5 extension, and while I could write it in C, it would be easier to use C++ and take advantage of the STL and Boost.
Trouble is, the tutorials I've seen only deal with C, and I'm looking for a basic example which uses C++
Here's what I've tried so far:
config.m4
[ --enable-hello Enable Hello World su... | After posting I came across CodeGen_PECL which creates a skeleton extension from an XML based description of the extension. This includes a tag make it output C++
As well as making sure the header file used extern "C", the generated cpp file also ensured the ZEND_GET_MODULE(hello) was inside an extern "C" block also.
A... |
492,061 | 492,112 | Why doesn't std::string provide implicit conversion to char*? | std::string provides const char* c_str ( ) const which:
Get C string equivalent
Generates a null-terminated sequence
of characters (c-string) with the same
content as the string object and
returns it as a pointer to an array of
characters.
A terminating null character is
automatically appended.
The returned ... | From the C++ Programming Language 20.3.7 (emphasis mine):
Conversion to a C-style string could have been provided by an operator const char*() rather than c_str(). This would have provided the convenience of an implicit conversion at the cost of surprises in cases in which such a conversion was unexpected.
|
492,091 | 492,143 | C++ scanner (string-fu!) | I'm writing a scanner as part of a compiler.
I'm having a major headache trying to write this one portion:
I need to be able to parse a stream of tokens and push them one by one into a vector, ignoring whitespace and tokenizing special symbols (simple case, lets just consider parentheses and braces)
Example:
int ... | Stroustrup's book, The C++ Programming Language, has a great example in it about building a lexer/parser for a simple calculator program. It should serve as a good starting point to learn how to do what you want.
|
492,286 | 492,378 | Free static code scanner for C/C++/C# | Does anyone know an open-source and/or free code-scanner for automated code analysis in C#, C or C++?
I know for Java there's some brilliant stuff like FindBugs (Eclipse integrated), PMD, or Hammurapi.
Is there anything similar for the C-languages?
wishi
| For .NET languages, you can look at Reflector CodeMetrics which provides some code analysis and design metrics. Also take a look at all of the Reflector addins.
I also second the recommendation for FxCop and StyleCop.
|
492,307 | 1,499,819 | Uploading big files over HTTP | I need to upload potentially big (as in, 10's to 100's of megabytes) files from a desktop application to a server. The server code is written in PHP, the desktop application in C++/MFC. I want to be able to resume file uploads when the upload fails halfway through because this software will be used over unreliable conn... | I'm eight months late, but I just stumbled upon this question and was surprised that webDAV wasn't mentioned. You could use the HTTP PUT method to upload, and include a Content-Range header to handle resuming and such. A HEAD request would tell you if the file already exists and how big it is. So perhaps something li... |
492,475 | 493,224 | Inline ostringstream macro reloaded | Referring to C++ format macro / inline ostringstream
The question there was for a macro that allows inline concatenation of objects to create a string, iostream-style.
The answer was:
#define SSTR( x ) dynamic_cast< std::ostringstream & >( \
( std::ostringstream().seekp( 0, std::ios_base::cur ) << x ) \
).s... | Unfortunately I don't have access to a MSVC compiler to test against.
In my past experiences with microsoft's tools, it seems like microsoft treats language definitions and standards as little more than a rough guide. (I've lost lots of time on projects only to discover microsoft broke tradition with something as basi... |
492,741 | 492,767 | Java: No interface implementation? | Today I got my book "Head First Design Patterns" in the mail. Pretty interesting stuff so far, however I do have a question about it's contents.
I have no Java/C# background nor do I wish to jump into those languages right now (I'm trying to focus on C++ first). In the book is said that java does not have an implementa... | What the author of the book meant, if you change the signatures of the members of the interface or add new ones, you will need to make those changes in the implementing classes as well so that they keep implementing the interface.
You can change the implementing classes whatever way you want as long you have the member... |
492,916 | 492,925 | Best way to monitor disk mounts in Linux using C++? | I am currently constructing a Carputer front end and one function that it needs is to be able to recognize when external media is inserted, such as USB/SD memory sticks or iPods. Upon their insertion, I will then scan the device for music/video/images and add them to the media library. Alternately, I need to know when ... | You can read kernel uevents from a NetLink socket. It provides events about device adding/removal, mount/umount.
-- Netlink
A daemon listening to the netlink
socket receives a packet of data for
each hotplug event, containing the
same information a usermode helper
would receive in environment
variables.
The ... |
492,953 | 493,192 | Calling PowerShell scripts from unmanaged C++ | Microsoft appears to be moving a lot of configuration and query capabilities to PowerShell (accessible from C# or managed C++), while deprecating and even removing older APIs (accessible for C or unmanaged C++). Those of us who have extensive unmanaged C++ programs that can't switch to managed C++ may have a need to ca... | The MS suggestion would probably be to compile specific classes/modules in your generally unmanaged C++ app as managed code (compiling individual files with /clr), and letting the IJW transition code manage the calls to/from it (and calling PowerShell API's from the managed bits). I've been told (from MS VC++ people) t... |
493,194 | 493,294 | What do I need to compile the kernel on Ubuntu Eee? | I'm trying follow a tutorial to create a custom USB driver in Linux and I hope to develop this thing on my Eee PC with Ubuntu Eee using g++. Unfortunately to follow the tutorial I need the linux/module.h header file. From what I understand I will need to compile the kernel to get this to work. I never compiled a ker... | Most (All?) of the major Linux distros not only distribute the linux kernel, but also apply numerous patches to it. Thereby improving stability and adding lots of features. So you'll want to use Ubuntu's package system to grab down Ubuntu's patched kernel source!
You probably do NOT need to rebuild the kernel! Most... |
493,200 | 493,217 | Creating XML in C++ Code | In my project there are situations where we have to send xml messages (as char *) among modules. They are not really large ones, just 10-15 lines. Right now everybody just creates the string themselves. I dont think this is the right approach. We are already using xerces DOM library. So why not create a Dom tree, seria... | If you are really just creating small XML messages, Xerces is an overkill, IMHO. It is a parser library and you are not parsing anything.
|
493,401 | 493,547 | How the C++0x standard defines C++ Auto multiple declarations? | mmm, I have just a little confusion about multiple auto declarations in the upcoming C++0x standard.
auto a = 10, b = 3.f , * c = new Class();
somewhere I read it is not allowed.
The reason was(?) because it was not clear if the consecutive declarations should have the same type of the first one , (int in the example... | It's probably not the latest, but my C++0x draft standard from June 2008 says you can do the following:
auto x = 5; // OK: x has type int
const auto *v = &x, u = 6; // OK: v has type const int*, u has type const int
So unless something has changed from June this is (or will be) permitted in a limited form with a prett... |
493,447 | 493,496 | Should I use GetProcAddress or just include various win32 libraries? | Wonder what the difference between:
static PROCESSWALK pProcess32First=(PROCESSWALK)GetProcAddress(hKernel,"Process32First");
...
pProcess32First(...);
what is hKernel? Look in here. You can replace with GetModuleHandle()
and
#include <Tlhelp32.h>
...
Process32First(...);
What are the differences, I wonder which I sh... | NOTE: my answer assumes that the function is available either way, there are other things to consider if you are after non-exported functions.
If you use LoadLibrary and GetProcAddress, then you have the option running with reduced functionality if the required library isn't there. if you use the include and link direc... |
493,613 | 493,639 | C++ Project dependencies issue Visual studio 2005 | I am working on a dataManagement project that periodically deletes files in a specific folder. The solution has three projects of which, one is the application and the other two are static libraries. Now I want to add one more project which is a static library used for logging. The logging static library project has a ... | It needs an additional include file path to reference the header file directory...
Project->Properties->Config Properties->C/C++->Additional Include Directories
it doesn't auto pick up the header file paths, it just knows how to link to the project.... Its completely undefined where the header file should be. or even ... |
493,774 | 493,868 | Why don't the standard C++ container adaptors provide a clear function? | Does anyone know why std::queue, std::stack, and std::priority_queue don't provide a clear() member function? I have to fake one like this:
std::queue<int> q;
// time passes...
q = std::queue<int>(); // equivalent to clear()
IIRC, clear() is provided by everything that could serve as the underlying container. Is th... | Well, I think this is because clear was not considered a valid operation on a queue, a priority_queue or a stack (by the way, deque is not and adaptor but a container).
The only reason to use the container
adaptor queue instead of the container
deque is to make it clear that you are
performing only queue operat... |
493,985 | 495,510 | C++ compiler unable to find function (namespace related) | I'm working in Visual Studio 2008 on a C++ programming assignment. We were supplied with files that define the following namespace hierarchy (the names are just for the sake of this post, I know "namespace XYZ-NAMESPACE" is redundant):
(MAIN-NAMESPACE){
a bunch of functions/classes I need to implement...
... | OK I figured this out.
jpalecek's intuition about there existing another operator<< in the namespace was correct (apparently I forgot to comment it out).
The lookup rules for namespaces first start the search in the function call's namespace and search up the enclosing namespaces, right up to the global namespace (th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.