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 |
|---|---|---|---|---|
862,068 | 868,461 | How do I dynamically change the text of a CMFCRibbonLabel | My CMDIFrameWndEx derived main frame window uses a CMFCRibbonStatusBar to which I add a CMFCRibbonLabel.
I'd like to change the text of this label at runtime:
m_pLabel->SetText(description);
m_pLabel->Redraw();
It only updates the text but not the rectangle in which to draw it. So if the original text was too short, t... | Answering my own question again...
I worked around the issue by adding and removing the label instead of trying to change the text.
Code for adding the label:
CMFCRibbonLabel* pLabel = new CMFCRibbonLabel(description);
pLabel->SetID(ID_MYLABEL); // ID is 0 by default
m_wndStatusBar.AddDynamicElement(pLabel);
m_wndStat... |
862,093 | 862,246 | Object delete itself from container | So I have a container(any kind, probably std::map or std::vector) which contains objects of a class with some network thing running in a thread that checks if it is still connected (the thread is defined inside that class and launches when constructed).
Is there any way I can make the object delete itself from the cont... | I would have am unload queue.
When a thread notices that the connection is down it registers the object (and continer) with the unload queue tides everything up as much as possible then the thred terminates.
A separate thread is then inside the unload queue. Its sole purpose is to monitor the queue. When it sees a ne... |
862,256 | 862,647 | How can I end a Lua thread cleanly? | My situation is that I'm using the Lua (C) API to execute a script held in a string.
I would like the user to be able to terminate the execution of the script (this is essential if the script contains an infinite loop), how can I do this?
lua_State *Lua = lua_open();
char * code;
// Initialisation code
luaL_dostring(L,... | You can use a hook to callback to C every time lua executes a line of the script.
In this hook function you can check if the user wanted to quit, and call lua_error if they did.
static bool ms_quit = false;
void IWantToQuit()
{
ms_quit = true;
}
void LineHookFunc(lua_State *L, lua_Debug *ar)
{
if(ar.event == ... |
862,699 | 862,758 | C++ SpellChecker Library | Can anybody recommend a good (ideally open source) C++ spell checker library. We are currenly using Talo, which isn't very good, so we are looking to change.
One which includes a grammar checker would also be good.
Thanks
| I have heard good things about hunspell. I have used and integrated aspell, which has some nice features and some which I did not like.
|
862,846 | 862,903 | Why in this example using floats makes me go 2x slower than with doubles? | I've been doing some profiling lately and I've encountered one case which is driving me nuts. The following is a piece of unsafe C# code which basically copies a source sample buffer to a target buffer with a different sample rate. As it is now, it takes up ~0.17% of the total processing time per frame. What I don't ge... | Are you running this on a 64 or 32 bit processor? My experience has been that in some edge cases there are optimisations the CPU can do with low level functionality like this if the size of your object matches the size of the registers (even though you may assume that two floats would fit neatly in a 64 bit register yo... |
862,858 | 863,761 | What other useful casts can be used in C++ | C++ comes with four built-in casts.
static_cast
dynamic_cast
const_cast
reinterpret_cast
Not to meantion the frowned upon C (style*)cast.
Additionally boost supplies a lexical_cast, are there any other useful casts that you use or would like to exist?
| My favorite and most loved cast is implicit_cast. It only succeeds if the types can be implicitly converted.
Useful for conversion from some type into void* or from some derived class into a base (if you want to select a specific instance of an overloaded function or constructor) or to safely add const-qualifications ... |
862,934 | 863,061 | Count the network interfaces with WSAIoctl function (WIN32 API) | I'm trying to list available interfaces using the WSAIoctl function. I have to pass in a buffer to hold the complete list. I want to get a count of the interfaces before I allocate memory to hold the interface details but if I pass in a NULL pointer the call just fails (I dont get a valid count returned). Any way to ge... | From the msdn documentation for WSAIoctl:
Note: If the output buffer is not
large enough to contain the address
list, SOCKET_ERROR is returned as the
result of this IOCTL and
WSAGetLastError returns WSAEFAULT. The
required size, in bytes, for the
output buffer is returned in the
lpcbBytesReturned parame... |
863,240 | 863,281 | Cross-Platform Objective-C / C++ Development | I work in a team of developers, one of us works specifically under Windows, and I work primarily in Mac OS X. We're wanting to develop C-based applications either in C++ or Objective-C however I'm not really knowledgeable in how to go about a cross-platform development project.
Is it viable to work in C++ using Mac OS... | You could look at Qt. I've used it successfully on Windows, Linux and Mac OSX projects.
|
863,523 | 863,700 | Does the OS (POSIX) flush a memory-mapped file if the process is SIGKILLed? | If a process is killed with SIGKILL, will the changes it has made to a memory-mapped file be flushed to disk? I assume that if the OS ensures a memory-mapped file is flushed to disk when the process is killed via SIGKILL, then it will also do so with other terminating signals (SIGABRT, SIGSEGV, etc...).
| It will depend on whether the memory-mapped file is opened with modifications private (MAP_PRIVATE) or not (MAP_SHARED). If private, then no; the modifications will not be written back to disk. If shared, the kernel buffer pool contains the modified buffers, and these will be written to disk in due course - regardles... |
863,575 | 863,616 | Using nibbles (4 bits variables) in windows C/C++ | I'm programming network headers and a lot of protocols use 4 bits fields. Is there a convenient type I can use to represent this information?
The smallest type I've found is a BYTE. I must then use a lot of binary operations to reference only a few bits inside that variable.
| Since the memory is byte-addressed, you can't address any unit smaller than a single byte. However, you can build the struct you want to send over the network and use bit fields like this:
struct A {
unsigned int nibble1 : 4;
unsigned int nibble2 : 4;
};
|
863,991 | 864,073 | Using C++ to edit the registry | I have a limited c++ background and I would like to edit the registry. For example, I want to grab the value of HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\NoDriveTypeAutoRun and check to see if 0x20 is in it, and then if it is, subtract 0x20 from it's value and write it back (and kill... |
Open the registry : RegOpenKeyEx
Query the value : RegQueryValueEx
/* do something with value*/
Set the value back : RegSetValueEx
close the registry : RegCloseKey
|
864,124 | 864,145 | How do I create const arrays and calculated const values in C++ class? | I'm running into some compiler errors I don't understand. I'm pretty sure I'm doing something very wrong here but I don't know what. I would like all the world constants to be defined as belonging to the class.
Notes:
I'm only using classes as structs with attached members. I'm not following strict Object-Orriented D... | Defining the static consts outside of the body of the class compiles and executes with gcc.
#include <iostream>
using namespace std;
struct Pair { int a; int b; Pair(int x, int y) : a(x),b(y) {}};
struct F {
static const float blah = 200.0;
static const Pair corners[4];
};
// square boards are so ordinary
const P... |
864,204 | 864,223 | What happens to memory that is not freed after end of program? |
Duplicate: What REALLY happens when you don’t free after malloc?
Let's say, for example:
int main()
{
char* test = new char[50000];
return 0;
}
What happens to the allocated memory after the program had finished? Does it get freed for other applications immediately? Or perhaps after some time? Or maybe it's lost... | See: What REALLY happens when you don't free after malloc?
|
864,250 | 864,263 | Converting Double to String in C++ | I am having some issues trying to convert a double to C++ string. Here is my code
std::string doubleToString(double val)
{
std::ostringstream out;
out << val;
return out.str();
}
The problem I have is if a double is being passed in as '10000000'. Then the string value being returned is 1e+007
How can i get... | #include <iomanip>
using namespace std;
// ...
out << fixed << val;
// ...
You might also consider using setprecision to set the number of decimal digits:
out << fixed << setprecision(2) << val;
|
864,394 | 864,401 | Why isn't my change to the registry persisting in C++? | I'm attempting to edit the registry with C++ and this is my first time trying to do so, and I'm failing. I'm not getting any error code, everything says it completed successfully, but it doesn't actually change the registry key.
Here is the code I am using:
HKEY hkey;
DWORD dwDisposition, dwType, dwSize;
int autorun = ... | You appear to be setting the registry key to the same value that you read it.
int newAutorun = (autorun - CD_AUTORUN_DISABLED);
cout << "New value: " << newAutorun << endl;
errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) **&autorun**, dwSize);
Should be
... |
864,858 | 899,710 | Managed C++ - Importing different DLLs based on configuration file | I am currently writing an application that will serve a similar purpose for multiple clients, but requires adaptations to how it will handle the data it is feed. In essence it will serve the same purpose, but hand out data totally differently.
So I decided to prodeed like this:
-Make common engine library that will hol... | The solution I came to is the following:
Engine_Base^ engine_for_app;
Assembly^ SampleAssembly;
Type^ engineType;
if (this->M_ENGINE == "A")
{
SampleAssembly = Assembly::LoadFrom("path\\Engine_A.dll");
engineType = SampleAssembly->GetType("Engine_A");
engine_for_app = static_cast<Engine_Base^>(Activator... |
865,000 | 865,287 | Collision-Detection methods in C++ | I am new to c++ and I have been practicing collision in a small game program that does nothing and I just can't get the collision right
So I use images loaded into variables
background = oslLoadImageFile("background.png", OSL_IN_RAM, OSL_PF_5551);
sprite = oslLoadImageFile("sprite.png", OSL_IN_RAM, OSL_PF_5551);
bush =... | I think you have the basic idea. Just check your work. Here is a simple version which compiles:
#import <stdlib.h>
typedef struct {
// I'm going to say x, y, is in the center
int x;
int y;
int width;
int height;
} Rect;
Rect newRect(int x, int y, int w, int h) {
Rect r = {x, y, w, h};
re... |
865,035 | 1,237,432 | "error C2248: 'CObject::CObject' : cannot access private member declared in class 'CObject' |
Possible Duplicate:
error using CArray
Duplicate : error using CArray
so, i am trying to use CArray like this :
CArray<CPerson,CPerson&> allPersons;
int i=0;
for(int i=0;i<10;i++)
{
allPersons.SetAtGrow(i,CPerson(i));
i++;
}
but when compiling my program, i get this error :
"error C2248:... | Write a constructor for your class (CPerson) and make it public. it should solve the problem.
|
865,152 | 865,201 | How can I get a process handle by its name in C++? | I'm trying to get the process handle of, say example.exe, so I can call TerminateProcess on it. How can I do this? Notice, it doesn't have a window so FindWindow won't work.
| #include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
int main( int, char *[] )
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE)
{
while (Process32Next(... |
865,209 | 865,256 | Should I learn C++ based on new or old standard (specification)? | OK, I am considering of getting into c++ development in coming months (there is no set date). I am vaguely familiar with the language (primarily C), as well as some basics of OO, MI, templates, exceptions, patterns, used STL. And now I am at the point in time where I would like to master the language in depth. And the... | My recommendation is to start out in the middle. Start with C++03, but check the features and C++0x libs that some compilers are already offering each so often. As of now, C++03 is THE standard (not only formally, but most code you will find will be strictly C++03).
Now, if you intend on learning go for the best: start... |
865,395 | 865,411 | How can I start explorer.exe via C++? | I'm trying to programmatically start explorer.exe but I'm not having any luck.
This is my code:
cout << pName << "died, lets restart it." << endl;
STARTUPINFO startupInfo = {0};
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInformation;
if(CreateProcess(pName, NULL, NULL, NULL, false, NORMAL_PRIORI... | The first parameter is the application name; the second is the command line. Try specifying "explorer.exe" as the second parameter.
See this MSDN article:
lpApplicationName [in, optional]
The name of the module to be executed.
This module can be a Windows-based
application. It can be some other type
of module ... |
865,546 | 871,315 | Generating Symbols in release binaries with Visual Studio | Update: I posted a comment on John Robbins blog about the. He wrote a response here:
http://www.wintellect.com/CS/blogs/jrobbins/archive/2009/06/19/do-pdb-files-affect-performance.aspx
The project I am working on does not build symbols for its release binaries, and I would like to change this.
Some info:
Mostly C++ co... | Update: I posted a comment on John Robbins blog about the. He wrote a response here:
http://www.wintellect.com/CS/blogs/jrobbins/archive/2009/06/19/do-pdb-files-affect-performance.aspx
I found the following link on microsofts website:
Generating and Deploying Debug Symbols with Microsoft Visual C++ 6.0
This link pertai... |
865,666 | 865,682 | How come random deletion from a std::vector is faster than a std::list? | How come that random deletion from a std::vector is faster than a std::list? What I'm doing to speed it up is swapping the random element with the last and then deleting the last.
I would have thought that the list would be faster since random deletion is what it was built for.
for(int i = 500; i < 600; i++){
swap(... | What you're doing is not random deletion though. You're deleting from the end, which is what vectors are built for (among other things).
And when swapping, you're doing a single random indexing operation, which is also what vectors are good at.
|
865,668 | 865,687 | Parsing Command Line Arguments in C++? | What is the best way of parsing command-line arguments in C++ if the program is specified to be run like this:
prog [-abc] [input [output]]
Is there some way of doing this built into the standard library, or do I need to write my own code?
Related:
Parsing command line arguments in a unicode C++ application
| Boost.Program_options should do the trick
|
865,689 | 865,750 | "Echo" device for Unit Testing | I'm currently writing up some CPPunit tests for a program that tests a hardware communication port (yes, I'm writing unit tests for a tester app ;-) ). One of the classes I'm testing is basically a wrapper around the device's file descriptor; I make read() and write() calls on the file descriptor. Is there a device f... | Why don't you use a UNIX pipe in the filesystem?
mkfifo /dev/test
echo test > /dev/test
on a second terminal:
cat /dev/test
Then the first will unblock and the second will show the text!
|
865,756 | 2,923,148 | Can't call base class method even though I have a pointer to it (Decorator)? | I have a template class that I've subclassed with a pointer to it (Decorator pattern). I added a getBase() call to return the pointer to the base class for any further subclasses. However, when I use that getBase() and call the base classes only method, I get a linker error that it can't find the symbol for that meth... | You have forgotten to specify the template parameter in the template definition. Furthermore you had some more errors. Here is the working code:
template <typename T> class B {
public:
typedef std::auto_ptr<T> MYFUN(
std::istream&, const std::string&, const std::string& );
public:
B<T>( MYFUN* p );
... |
865,785 | 865,810 | Why does the order of my #includes matter? (C++) | I've created a header file called "list_dec.h", put it in a folder "C:\Headers", and set my compiler to include files from "C:\Headers", so now I can do things like
#include<list_dec.h>
int main(){return(0);}
but when I try to do something like
#include<iostream>
#include<list_dec.h>
int main(){return(0);}
I get an e... | Generally speaking it should not, however it may be possible for there to be conflicting definitions of symbols or preprocessor macros that end up confusing the compiler. Try to narrow down the size of the problem by removing pieces and includes from the conflicting header until you can see what is causing it.
In respo... |
866,012 | 866,283 | Is there a way to define variables of two different types in a for loop initializer? | You can define 2 variables of the same type in a for loop:
int main() {
for (int i = 0, j = 0; i < 10; i += 1, j = 2*i) {
cout << j << endl;
}
}
But it is illegal to define variables of different types:
int main() {
for (int i = 0, float j = 0.0; i < 10; i += 1, j = 2*i) {
cout << j << endl;
}
}
Is th... | Here is a version using boost preprocessor (This is just for fun. For the real-world answer, see @kitchen's one above):
FOR((int i = 0)(int j = 0.0), i < 10, (i += 1, j = 2 * i)) {
}
The first part specifies a sequence of declarations: (a)(b).... The variables declared later can refer to variables declared before th... |
866,664 | 866,726 | How to organise source code in a modular manner | I'm currently working on a project that has scope to become quite large, however being relatively new to C++ and coming from a Java background I'm not sure about the best way to proceed.
I would like to have a directory structure similar to:
+ Root
- main.cpp
+ Engine
+ Core
- foo.cpp
- foo.... | You're almost certainly having trouble with include files being included. You need to add to the compile command -I flags for the directories from which you're bringing in your .h files.
Several of your directory names have spaces in them, so be careful that you're quoting the directory names correctly. Or, even bett... |
866,672 | 866,685 | Switching stacks in C++ | I have some old code written in C for 16-bit using Borland C++ that switches between multiple stacks, using longjmps. It creates a new stack by doing a malloc, and then setting the SS and SP registers to the segment and offset, resp., of the address of the malloc'd area, using inline Assembler. I would like to conver... | Removing CLI/STI still works due to the differences in the operating environment.
On 16-bit DOS, an interrupt could occur and this interrupt would be initially running on the same stack. If you got interrupted in the middle of the operation, the interrupt could crash because you only updated ss and not sp.
On Windows,... |
866,679 | 866,716 | Using OpenGL /GLUT how would I detect if two keys are held down at the same time? | Using OpenGL /GLUT how would I detect if two keys, say 'a' and 'j' are held down at the same time?
(This program needs to compile with OSX GCC, Windows GCC, Windows VS2005 so no OS dependent hacks please.)
| Try the following:
Use glutIgnoreKeyRepeat to only get physical keydown/keyup events
Use glutKeyboardFunc to register a callback listening to keydown events.
Use glutKeyboardUpFunc to register a callback listening to keyup events.
Create a bool keystates[256] array to store the state of the keyboard keys.
When receivi... |
866,718 | 866,755 | Precompiled headers supported on gcc 3.3.3? | Are precompiled headers supported on gcc 3.3.3 ?
If yes what is the syntax to generate and use precompiled headers on Linux with gcc 3.3.3.
We crosscompile our projects on Windows and Linux, on Windows we precompile stdafx.h and I'm investigating how to set it up so that it is precompiled on Linux as well.
I'm aware of... | I don't know from what version gcc supports it, but for how to use them just read the gcc documentation.
Anyway, gcc 3.3.3 is pretty old, too. Maybe there's a chance that you can upgrade to a more recent 4.X version? That should support recompiled headers.
Maybe you could try the latest 3.X GCC (GCC 3.4.6). I assume th... |
866,730 | 866,756 | Memory Efficient Methods To Find Unique Strings | I have a data set that looks like this:
000 100 200 300 010 020 030 001 002 003
001 101 201 301 011 021 031 000 002 003
002 102 202 302 012 022 032 001 000 003
003 103 203 303 013 023 033 001 002 000
010 110 210 310 000 020 030 011 012 013
020 120 220 320 010 000 030 021 022 023
030 130 230 3... | This depends a bit on the characteristics of your dataset. In the worse case, where all strings are unique, you will need either O(n) memory to record your seen-set, or O(n^2) time to re-scan the entire file on each word. However, there are improvements that can be made.
First off, if your dataset only consists of 3-di... |
866,733 | 868,359 | Monitoring storage space on windows mobile | In a native(c++) windows mobile app. There are ways to be notified of low memory, WM_HIBERNATE, and low power, RequestPowerNotifications().
Is there any way to be notified when storage space is running low? Or must an app just poll regularly with GetDiskFreeSpaceEx()?
| No, there are no system notifications for storage space.
|
866,776 | 866,782 | What does this code in "vector" mean? (C++) | I created a program, and it uses the vector.h #include, and iterators, etc... But when I run the program, under certain circumstances (I'm still trying to figure out what those would be) I get an assertion error refering me to line 98 of vector.h. I went to line 98 of vector.h and got this:
#if _HAS_ITERATOR_DEBUGGIN... | The runtime is detecting that you are dereferencing an iterator that is before begin() or after end().
Imagine if you delete the last item in the antiviral_data vector in line 7:
aI = antiviral_data.erase(aI);
aI gets set to antiviral_data.end(), and when you dereference it in line 14:
if((*aI)->x >= maxx ...
and al... |
867,135 | 867,241 | How to find the difference between two times in c? | my first time is 12:10:20 PM and second time is 7:10:20 Am of the same day how can i find diff b/w them??
My idea is convert all the time to seconds and find the difference again convert to time
is it good Approch r anything else??
| Not necessarily the best way, but if you wish to use what's available on the system, difftime() and mktime() can help -
#include <time.h>
tm Time1 = { 0 }; // Make sure everything is initialized to start with.
/* 12:10:20 */
Time1.tm_hour = 12;
Time1.tm_min = 10;
Time1.tm_sec = 20;
/* Give the function a sane date t... |
867,270 | 867,281 | Passing a **Class as an argument | I'm trying to declare a method in main.h like this:
void buildGraph(int gNum, Graph** gArray);
Where Graph is a class and I'm trying to pass a pointer to an array of pointers to Graph objects.
I get the error message: "Graph has not been declared".
Even though I have #include "graph.h" at the top of the page and I've ... | Maybe the name Graph is in a namespace? What does that graph.h file say -- is Graph at top-level, or inside a namespace statement?
|
867,462 | 867,804 | C++ implicit conversions | Several comments on a recent answer of mine, What other useful casts can be used in C++, suggest that my understanding of C++ conversions is faulty. Just to clarify the issue, consider the following code:
#include <string>
struct A {
A( const std::string & s ) {}
};
void func( const A & a ) {
}
int main() {
... | I think the answer from sharptooth is precise. The C++ Standard (SC22-N-4411.pdf) section 12.3.4 titled 'Conversions' makes it clear that only one implicit user-defined conversion is allowed.
1 Type conversions of class objects can be specified by
constructors and by conversion
functions. These
conversions a... |
867,724 | 1,446,878 | How to modify the tool rect of a CToolTipCtrl? | This question is related to this one.
In a CDockablePane derived class I have a CTreeCtrl member for which I add a ToolTip in OnCreate():
int CMyPane::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDockablePane::OnCreate(lpCreateStruct) == -1)
return -1;
const DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS... | I know no other way to do this other than calling DelTool then AddTool again in your OnSize handler:
void CMyPane::OnSize(UINT nType, int cx, int cy)
{
CDockablePane::OnSize(nType, cx, cy);
if (m_pToolTip != NULL)
{
m_pToolTip->DelTool(&m_tree, TREECTRL_ID);
CRect treeRect;
m_tree.... |
867,813 | 869,043 | How do I plot the output from a C++ Win32 console app? | I have a small Win32 console application which is essentially a test harness. I read data in, do some processing on it and currently just output some of the numbers to the console. This isn't a huge problem - I can get an idea of what the data looks like, but it would be much easier to analyse if there was a way of get... | You don't really need to touch VBA to do this
In Excel you can set up a Data Connection to a file, it supports many files type but CSV does work fine.
Go to List item
Data Tab
Click Connections
Click Add
select the file
go to the connection properties - un-tick prompt for file name
set the required period.
close the c... |
868,108 | 868,127 | Polymorphic or generic approach is better? C# | I have two classes and an interface like
interface IVehicle
{
void Drive();
}
class Benz :IVehicle
{
public void Drive()
{
Console.WriteLine("WOW! driving benz");
}
}
class Ferrari : IVehicle
{
public void Drive()
{
Console.WriteLine("WOW! driving ferrari");
}
}
I got a Dr... |
Absolutely no advantages in this case whatsoever. Except if you really want to create an instance of T in Drive(), which can be done without generics with delegate IVehicle VehicleBuilder();
It depends on the situation. But generally speaking I'd prefer first.
Again: it depends on what you want to do.
Yes, this is tru... |
868,306 | 869,597 | What is the difference between static_cast and Implicit_cast? | What is implicit_cast? when should I prefer implicit_cast rather than static_cast?
| I'm copying over from a comment i made to answer this comment at another place.
You can down-cast with static_cast. Not so with implicit_cast. static_cast basically allows you to do any implicit conversion, and in addition the reverse of any implicit conversion (up to some limits. you can't downcast if there is a virt... |
868,530 | 868,546 | Reading binary file defined by a struct | Could somebody point me in the right direction of how I could read a binary file that is defined by a C struct?
It has a few #define inside of the struct, which makes me thing that it will complicate things.
The structure looks something like this: (although its larger and more complicated than this)
struct Format {
... | Reading a binary defined by a struct is easy.
Format myFormat;
fread(&myFormat, sizeof(Format), 1, fp);
the #defines don't affect the structure at all. (Inside is an odd place to put them, though).
However, this is not cross-platform safe. It is the simplest thing that will possibly work, in situations where you are... |
868,773 | 868,969 | Central Clickable MSDN like Linux System/C/C++ Standard Library Documentation | If you are windows programmer and you want to program something new where you
are going to use some new API with which you are not that familiar then you can type MSDN on your web browser and you get immediately what you need. Nicely grouped API functions where you can see what to include and what to link.
I am lookin... | Man is broken down into sections If you type "man man" you can see them.
1 Executable programs or shell commands
2 System calls (functions provided by the kernel)
3 Library calls (functions within program libraries)
4 Special files (usually found in /dev)
5 File formats and conventions eg /etc... |
868,853 | 869,948 | Redirect barcode scanner input to specific widget in linux | I have a Symbol LS2208 barcode scanner and works OK in my linux box (Kubuntu 8.10 Intrepid Ibex). Whenever you scan a barcode the scanner (connected to an USB port) sends the reading to wherever the text caret is. I would like to redirect all the readings from the scanner to an specific widget in my application (i.e. a... | I don't know the answer, but here are some suggestions to find out what your options are:
Install an event filter on QCoreApplication::instance() (or reimplement QCoreApplication::notify())
In event filter handler, output each event looking for anything useful:
void eventFilter(QObject *obj, QEvent *evt) {
qDebug(... |
868,966 | 959,014 | Fast JPEG encoding library | anyone know of a free open-source jpeg encoding library for C/C++? Currently I'm using ImageMagick, which is easy to use, but it's pretty slow. I compared it to an evaluation of Intel Performance Primitives and the speed of IPP is insane. Unfortunately it also costs 200$, and I don't need 99% of the IPP). Also it w... | ImageMagick uses libjpeg (a.k.a Independent JPEG Group library). If you improve the speed of libjpeg, ImageMagick JPEG speed will increase.
There are a few options:
Compile an optimized libjpeg. If you have a modern gcc and at least a Pentium 4, you can try -O3 -msse2 and see if it can boost your speed. Then you can u... |
869,281 | 869,310 | passing this from constructor initializer list | Are there any issues when passing 'this' to another object in the initializer list in the following code?
class Callback { public: virtual void DoCallback() = 0; };
class B
{
Callback& cb;
public:
B(Callback& callback) : cb(callback) {}
void StartThread();
static void Thread()
{
while (!... | If you are extremely careful this will work fine. You will get into a lot of trouble if you start calling virtual methods or using methods which depend on other objects in the type. But if you're just setting a reference this should work fine.
A safer (but not completely safe) alternative is to set b later on once ... |
869,503 | 869,846 | Failsafe conversion between different character encodings | I need to convert strings from one encoding (UTF-8) to another. The problem is that in the target encoding we do not have all characters from the source encoding and libc iconv(3) function fails in such situation. What I want is to be able to perform conversion but in output string have this problematic characters been... | Try appending "//TRANSLIT" or "//IGNORE" to the end of the destination charset string. Note that this is only supported under the GNU C library.
From iconv_open(3):
//TRANSLIT
When the string "//TRANSLIT" is appended to tocode, translitera‐
tion is activated. This means that when a character ca... |
869,593 | 869,661 | compare function for upper_bound / lower_bound | I want to find the first item in a sorted vector that has a field less than some value x.
I need to supply a compare function that compares 'x' with the internal value in MyClass but I can't work out the function declaration.
Can't I simply overload '<' but how do I do this when the args are '&MyClass' and 'float' ?
f... | What function did you pass to the sort algorithm? You should be able to use the same one for upper_bound and lower_bound.
The easiest way to make the comparison work is to create a dummy object with the key field set to your search value. Then the comparison will always be between like objects.
Edit: If for some reason... |
869,648 | 869,658 | Re-throwing exception caught by pointer | In C++, what is the difference between the following examples?
Re-throw pointer:
catch (CException* ex)
{
throw ex;
}
Simple re-throw:
catch (CException* ex)
{
throw;
}
When the re-throw is caught, will the stack trace be different?
| Yes. Basically, you are throwing the object yourself in the first case. It looks like you generated the exception yourself in the throw ex line. In the second case, you are just letting the original object go up in the call stack (and thus preserving the original call stack), those are different. Usually, you should be... |
869,664 | 879,487 | Multithreading with Inheritance (C++) | I am trying to call the "Run" function in a new thread. Right now, I have this code using openMP that doesn't actually run "Run" in a new thread. NOTE: I am not asking for help using OpenMP. This code was just a quick fix. I would prefer a CreateThread() method of going about this.
vector<ICommand*>* commands;
string s... | So I figured it out after double-checking the MSDN documentation. Here's how I did it, in case any of you are interested:
static vector<ICommand*>* commands;
// This is what we pass to CommandOnThread.
struct CommandParameter
{
string strInput;
ICommand* command;
};
int CommandOnThread(CommandParameter* cp)
{
... |
870,138 | 978,112 | Statically linked unmanaged libs and C++ CLR | Is it possible to use to use libs compiled with /MT in C++ CLR? It throws me either a ton of LNK2022 "metadata operation failed (8013118D)" errors (if I use /MD in the CLR project) or " '/MT' and '/clr:pure' command-line options are incompatible" if I use /MT.
What do I need to change in the library? The library is min... | LNK2022 are a pain to pinpoint. It usually means one of your module's configuration affecting structure layout is different from the others.
Check for the following usual causes:
Make sure all your projects are using the same runtime library (/MDd or /MD) for your current solution configuration. If one project is usin... |
870,167 | 873,161 | in windows, how to have non-blocking stdin that is a redirected pipe? | I have a Windows C program that gets its data through a redirected stdin pipe, sort of like this:
./some-data-generator | ./myprogram
The problem is that I need to be able to read from stdin in a non-blocking manner. The reason for this is that (1) the input is a data stream and there is no EOF and (2) the program ne... | The order apprach, check there is input ready to read:
For console mode, you can use GetNumberOfConsoleInputEvents().
For pipe redirection, you can use PeekNamedPipe()
|
870,173 | 870,224 | Is there a limit on number of open files in Windows | I'm opening lots of files with fopen() in VC++ but after a while it fails.
Is there a limit to the number of files you can open simultaneously?
| The C run-time libraries have a 512 limit for the number of files that can be open at any one time. Attempting to open more than the maximum number of file descriptors or file streams causes program failure. Use _setmaxstdio to change this number. More information about this can be read here
Also you may have to check ... |
870,225 | 871,147 | Overview rpg tiled space | I'm trying to make it where the character is in a tile and when they move up or down it moves to the next tile but I'm not sure how to do that. Right now, I have it set up where the character moves by pixels but I want it to move by 1 square.
The code right now is this, and it works, but it's glitchy in pixel mode. I... | If you want the character to move one tile/square/block at a time, just move the sprite the number of pixels the tile is wide (or tall).
const int tile_width = 32; // or something
// and then
sprite->x += tile_width;
|
870,441 | 870,643 | How would I go about making an efficient key value store (e.g. memcache) / simple database? | For a few projects I'm working on I need a persistent key value store (something akin to memcache). It would ideally run as a server; it needs to be really efficient. I'm aware that memcachedb exists, but I'd like to have a go at writing it myself as there's going to be a lot of custom functionality that I'll need to i... | There are lots of key-value stores, from the tried and true BDB to the hip Tockyo Cabinet. If you must implement your own, i'd recommend to check Varnish sources, especially the Architecture page.
|
870,469 | 870,596 | Is there a tool for cross platform continuous integration (c++ Win32 and linux) | I looked at a couple other questions on SO - and not really sure they answer this question.
We are building C++ applications for Win32 and Linux. Right now we have some scripts (bat files for win32) that run on a schedule to do builds.
We'd like to have CI for our projects, but I'd like to have only one CI server tha... | You might want to have a go at Hudson or Jenkins . Though primarily for Java-based projects, you could tweak them to suit your needs.
They integrate with SVN smoothly, plus you could use the muti-step build feature to call your (existing) batch files, and process further.
|
870,474 | 870,514 | Burn CD/DVD from C++ program | I need to burn CD/DVD disks from my C++ program. Can you recommend me a method?
Edit: The platform is Windows.
| On Windows, I have previously used the IMAPI2 interface very successfully. This site gives a really good set of sample code for this. You may need to extensively modify the code for your implementation, but it works, and works well.
One thing about the IMAPI2 interface; it's what you pretty much need to use if you're... |
870,878 | 888,829 | Why is iplRotate() not giving me correct results? | sigh I'm sorry to say that I'm using Intel IPL (Image Processing Library) in some image processing code I'm working on. This is the tale of my struggle with getting my images to rotate correctly.
I have a source image. It has a size (w, h) which is not necessarily square.
It is going to be rotated by angle theta.
I've... | When using iplGetRotateShift you need to specify the center of rotation in the source image. This will work well if the size of the source and destination image is the same.
In your case you want an extra shift to center the image in your destination image:
xShift = (dw - w) / 2.0;
yShift = (dh - h) / 2.0;
To combine... |
871,264 | 871,280 | What does "operator = must be a non-static member" mean? | I'm in the process of creating a double-linked list, and have overloaded the operator= to make on list equal another:
template<class T>
void operator=(const list<T>& lst)
{
clear();
copy(lst);
return;
}
but I get this error when I try to compile:
container_def.h(74) : error C2801: 'operator =' must be a no... | Exactly what it says: operator overloads must be member functions. (declared inside the class)
template<class T>
void list<T>::operator=(const list<T>& rhs)
{
...
}
Also, it's probably a good idea to return the LHS from = so you can chain it (like a = b = c) - so make it
list<T>& list<T>::operator=....
|
871,267 | 871,510 | How do you transfer ownership of an element of boost::ptr_vector? | #include <boost/ptr_container/ptr_vector.hpp>
#include <iostream>
using namespace std;
using namespace boost;
struct A {
~A() { cout << "deleted " << (void*)this << endl; }
};
int main() {
ptr_vector<A> v;
v.push_back(new A);
A *temp = &v.front();
v.release(v.begin());
delete temp;
re... | ptr_vector<A>::release returns a ptr_vector<A>::auto_type, which is a kind of light-weight smart pointer in that when an auto_type item goes out of scope, the thing it points to is automatically deleted. To recover a raw pointer to the thing, and keep it from being deleted by the auto_ptr that's holding it, you need to... |
871,328 | 871,353 | Visual Studio: how do I have the debugger stop when a member variable is modified? | I have program that has a variable that should never change. However, somehow, it is being changed. Is there a way to have the debugger stop when that particular member variable is modified?
| Set a data breakpoint to stop execution whenever some variable changes.
Break on the initialization of your variable, or someplace where your variable is visible - you need to be able get its address in memory. Then, from the menus choose Debug -> New Breakpoint -> New Data Breakpoint. Enter "&var" (with var replaced b... |
871,336 | 871,358 | is there a way to combine Qt-Creator + Boost Library? | I was wondering if there was a way to use the boost library in Qt-creator (the IDE version of Qt).
Thanks,
A.
| I'm pretty sure Qt Creator doesn't require the use of Qt in your application. If you don't want to link to any Qt libraries, or run MOC on any header files (which you only need to do for subclasses of QObject), then just do QT -= core gui (to get rid of Qt libraries from the link command. Perhaps QT = would work, too)... |
871,354 | 887,999 | Adding the ! operator and sqrt(), pow(), etc. to a calculator example application | I'm doing the exercises in Stroustrup's new book "Programming Principles and Practice Using C++" and was wondering if anyone on Stack Overflow has done them and is willing to share the knowledge?
Specifically about the calculator that's developed in Chap 6 and 7. For example, the questions about adding the ! operator a... |
There are a few solutions posted on Stroustrup - Programming and more will be coming over time.
Try solving exercises only with the language features and the library facilities presented so far in the book -- real novice users can't do anything else. Then return later to see how a solution can be improved.
|
871,423 | 871,614 | Cross-Platform way to get CPU/Memory utilization | Looking for a library or a fairly cross platform method to get CPU utilization, memory utilization, etc in C/C++. Something OTHER than getrusage(), I need for entire system, not one process. I've checked around, but haven't found much. I really need it on Linux, Mac Os X, and Windows, but if there's a solution for *... | The cross platform framework ACE has a wrapper for getrusage that should work on most if not all supported platforms.
|
871,435 | 871,794 | Odd/Incorrect sem_getvalue Semaphore Behavior on OS X | I have some very basic semaphore code that works great on Linux, but cannot for the life of me get it to run properly on OS X... It returns the oddest of results...
#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>
int main()
{
sem_t* test;
test = sem_open("test", O_CREAT, 0, 1);... | $ g++ sem-testing.cc -Wall
$ ./a.out
sem_getvalue: Function not implemented
$ man sem_getvalue
No manual entry for sem_getvalue
You are using a function that is not currently implemented in Mac OS X, and the integer you are printing out contains the default data that the integer was initialised with which was probabl... |
871,444 | 871,455 | Is it possible to create a "friend class" in C++? | I know it's possible to create a friend function in C++:
class box
{
friend void add(int num);
private:
int contents;
};
void add(int num)
{
box::contents = num;
return;
}
But is there a way to create friend classes?
NB: I know there are probably a lot of errors in this code, I don't use friend functions and am stil... | Yup - inside the declaration of class Box, do
friend class SomeOtherClass;
All member functions of SomeOtherClass will be able to access the contents member (and any other private members) of any Box.
|
871,475 | 871,487 | Is it possible to declare a class without implementing it? (C++) | I know the questions seems ambiguous, but I couldn't think of any other way to put it, but, Is it possible to do something like this:
#include<iostream>
class wsx;
class wsx
{
public:
wsx();
}
wsx::wsx()
{
std::cout<<"WSX";
}
?
| Yes, that is possible. The following just declares wsx
class wsx;
That kind of declaration is called a forward declaration, because it's needed when two classes refer to each other:
class A;
class B { A * a; };
class A { B * b; };
One of them needs to be forward declared then.
|
871,504 | 871,506 | What do the Items on the properties tab of MSVC++ mean? | I was playing around with my MSVC++ compiler, and the properties tab for my point class said:
IsAbstract - false
IsInjected - false
IsManaged - false
IsSealed - false
IsTemplate - false
IsValue - false
What do these mean, and why were all of them greyed out except IsAbstract and IsSealed?
| A sealed class is one that you cannot inherit. I assume IsSealed - false means that you can inherit from it.
|
871,574 | 896,655 | construct two shared_ptr objects from the same pointer | I have a problem from "The C++ Standard Library Extensions":
Exercise 6
I said in Section 2.4.2
that you shouldn't construct two
shared_ptr objects from the same
pointer. The danger is that both
shared_ptr objects or their progeny
will eventually try to delete the
resource, and that usually leads to
tr... | I got the "STANDARD" answer from boost doc :
http://www.boost.org/doc/libs/1%5F38%5F0/libs/smart%5Fptr/sp%5Ftechniques.html#another_sp
|
871,579 | 871,595 | Where is this code dereferencing an invalid iterator? (C++) | I have a loop
for(aI = antiviral_data.begin(); aI != antiviral_data.end();)
{
for(vI = viral_data.begin(); vI != viral_data.end();)
{
if((*aI)->x == (*vI)->x && (*aI)->y == (*vI)->y)
{
vI = viral_data.erase(vI);
aI = antiviral_data.erase(aI);
}
else
... | What are the sizes of the vectors?
If viral_data has more elements then antiviral_data, then, since you increment aI and vI at the same rate, aI would go out of bounds before the vI loop would end.
Take a short example here:
for(int i = 0; i < 5;)
{
for(int j = 0; j < 10;)
{
i++;
j++;
}
}
I... |
871,644 | 871,972 | Eclipse Ganymede and MinGW in Windows | I'm trying to get eclipse to work with MinGW.
I've done the following:
Downloaded CDT for eclipse.
Installed MinGW.
Added C:\MinGW\bin to my path.
Opening a command prompt (CMD) and typing g++ or alike works fine.
I run eclipse, create a "New C++ Project", and only get the option saying "other toolchains".
There's a ... | The distinction between managed make projects and makefile project was removed in CDT 4.x, I think. Now there is only one type of project, but you can select different builders. CDT includes an internal builder which does not use makefiles and another one which does.
First, save yourself the effort of "reinstalling in ... |
871,666 | 871,670 | Why is it better to use '!=" than '<' in a vector loop? (C++) | Why is it better to use '!=" than '<' in a vector loop? I just can't see the difference.
| Because you're using iterators, and it'll make the loop look exactly the same as other containers, should you choose to switch to other container types, such as set, list, unordered_set, etc. where < has no meaning.
|
871,888 | 872,000 | Is there any temporary created while returning an object from function? | when ever a function has a object passed by value it uses either copy constructor or bit wise copy to create a temporary to place on stack to use inside the function,How about some object returned from function ?
//just a sample code to support the qn
rnObj somefunction()
{
return rnObj();
}
and also explain how the r... | As can be judged by the other answers - the compiler can optimize this.
A concrete example generated using MSVC, to explain how this is possible (as asked in one of the comments) -
Take a class -
class AClass
{
public:
AClass( int Data1, int Data2, int Data3 );
int GetData1();
private:
int Data1;
int Data... |
871,917 | 872,032 | Web access authentication in C++? | I'm trying to write a simple GUI application using Qt framework.
The purpose of this app is to retrieve data from my isp and parse them for presentation.
How do i authenticate my user/password with the webserver and retrieve the html page in question?
Are there any utility libs that make this task trivial?
I figure i ... | The way to authenticate depends completely on the authentication method used by the server. If it's some form to log in you need to retrieve that and send the correct data to the forms action target (usually as POST request). You could do this by constructing your request using QHttpRequestHeader and then simply sendin... |
871,952 | 1,964,446 | GCC build problem (#include_next limits.h) | When i try to
$ make depend -f gcc.mak
a middleware on my Ubuntu machine I get this
/usr/include/../include/limits.h:125:26: error: no include path in which to search for limits.h
This is the contents around limits.h:125:
/* Get the compiler's limits.h, which defines almost all the ISO constants.
We put this #inc... | the package that you need is glibc.
|
871,982 | 872,451 | Making references to classes you havn't #include'd (C++) | I'm playing around with Box2D for fun right now, and after getting the hang of some of the concepts I decided to make my own test for the test bed (Box2D comes with a set of examples and has a simple extendable Test class for making your own tests). I started by grabbing one of the other tests, ripping out everything b... | Each cpp file gets compiled. Before it is compiled though, the preprocessor runs. The preprocesser deals with all of the keywords starting with #, like #include. The preprocessor takes the text of any #include'd files and replaces the #include statement with all the text in the file it includes. If the #include'd file ... |
872,087 | 872,111 | Templates and Syntax | Working on an algorithm to look at a STL container of STL strings (or other strings, making it general)
Basically it loops through something like a std::list and returns the length of the longest beginning in common. It's for processing lists of files, like this:
C:\Windows\System32\Stuff.exe
C:\Windows\Things\InHere.... | Your parameter names in the template line need to include any types of function parameters or return types. This means that you need to mention InputIterator in your template parameter list. Try changing your function declaration to:
template <typename InputIterator>
size_t longestBegin(InputIterator firstCandidates, ... |
872,143 | 872,171 | How to force destruction order of static objects in different dlls? | I have 2 static objects in 2 different dlls:
An object Resources (which is a singleton), and an object User. Object User in its destructor has to access object Resources.
How can I force object Resources not to be destructed before object User?
| Global objects are destroyed when their corresponding DLL is unloaded. So as your 'User' dll is probably dependent of your 'Resource' dll, you are in trouble: 'resource' will always be destroyed before 'user'.
I'm also interested by a good answer to this question, if one exist. Until now, I'm using a cleanup function t... |
872,354 | 872,485 | Getting the reference of a template iterator reference | I need to get a reference to an iterator of a reference. However, my compiler is choking on this code:
template <typename InputIterator> size_t iLongestBegin(InputIterator first, InputIterator last)
{
typedef typename std::iterator_traits<InputIterator>::reference SequenceT;
//Problem is next line
typed... | Actually, just solved it :)
Problem is that SequenceT is a reference, not a type. Since you can't generally take the address of a reference type, the compiler won't generate iterators for it. I need to use value_type instead of reference:
template <typename InputIterator> size_t iLongestBegin(InputIterator first, Input... |
872,414 | 874,065 | Compiling C++ using -pthreads for Openwrt Linux-Get segmentation fault | I´m pretty new to programming in C++ and I´m using pthreads. I´m cross compiling my code for OpenWRT but for some reason I get segmentation fault when I run the program on my board but it runs fine on my PC. I suspect that the error occurs in the linking stage of the compilation because I tried a small C program and th... | This could easily be due to a low memory condition. You should try to enable some form of page file and free up any other memory.
Also, why -static? if your using a dynamic -lpthread, wouldn't linking the shared library be preferable?
Also, it could be due to your C++ lib being mis-matched, make sure your uclibc++ is ... |
872,491 | 872,534 | New unicode characters in C++0x | I'm buiding an API that allows me to fetch strings in various encodings, including utf8, utf16, utf32 and wchar_t (that may be utf32 or utf16 according to OS).
New C++ standard had introduced new types char16_t and char32_t that do not have this sizeof ambiguity and should be used in future, so I would like to support... | 1) char16_t and char32_t will be distinct new types, so overloading on them will be possible.
Quote from ISO/IEC JTC1 SC22 WG21 N2018:
Define char16_t to be a typedef to a
distinct new type, with the name
_Char16_t that has the same size and representation as uint_least16_t.
Likewise, define char32_t to be a
t... |
872,677 | 872,720 | What are all the differences between WH_MOUSE and WH_MOUSE_LL hooks? | I've found that WH_MOUSE is not always called. Could the problem be that I'm using WH_MOUSE and not WH_MOUSE_LL?
The code:
class MouseHook
{
public:
static signal<void(UINT, const MOUSEHOOKSTRUCT&)> clickEvent;
static bool install()
{
if (isInstalled()) return true;
hook = ::SetWindowsHookEx(WH_MOUSE, (... | The difference is in the behavior when the callback gets called.
If you're using the lowlevel version you don't incur in the limitations posed by lpfn because of the way the call to your hook function is performed. Please read below for more information.
Quoting from MSDN's doc for SetWindowsHookEx:
lpfn
[in] Pointer ... |
872,846 | 872,869 | Can this cause undefined behaviour? | I've been having big problems in reproducing and finding the cause of a bug. The occurence seems entirely random, so I suspected an uninitialized variable somewhere. But then I found this piece of code:
CMyClass obj; // A
obj.DoStuff();
if ( somebool )
{
CMyClass obj; // B
obj.DoStuff();
}
obj.DoOtherStuff();... | The code, as written, should work. The first call to DoStuff() and the last call to DoOtherStuff() can only be sent to A.
The call to DoStuff() inside the if(somebool) { } block can only be sent to B.
From the standard:
3.3.2 Local scope
A name declared in a block (6.3) is local to that block. Its potential scope be... |
872,996 | 873,003 | Immediate exit of 'while' loop in C++ | How do I exit a while loop immediately without going to the end of the block?
For example,
while (choice != 99)
{
cin >> choice;
if (choice == 99)
//Exit here and don't get additional input
cin>>gNum;
}
Any ideas?
| Use break?
while(choice!=99)
{
cin>>choice;
if (choice==99)
break;
cin>>gNum;
}
|
873,090 | 873,092 | Do DeleteFile() Or CopyFile() throw exceptions? | I use the DeleteFile and CopyFile methods. Do these functions throw exceptions or just set errno and lastError? Do I need to surround this code with try and catch?
| If you're referring to the Win32 API functions, the answer is no. No Win32 functions throw, because it is a C API.
|
873,101 | 873,177 | C++ class - Increment and decrement attribute every N milliseconds | This must be an easy question but I can't find a properly answer to it.
I'm coding on VS-C++. I've a custom class 'Person' with attribute 'height'. I want to call class method Grow() that starts a timer that will increment 'height' attribute every 0.5 seconds.
I'll have a StopGrow() that stops the timer and Shrink() th... | Do you really need to call the code every half second to recalculate a value? For most scenarios, there is another much simpler, faster, effective way.
Don't expose a height member, but use a method such as GetHeight(), which will calculate the height at the exact moment you need it.
Your Grow() method would set a base... |
873,210 | 873,289 | Symbols (pdb) for native dll are not loaded due to post build step | I have a native release dll that is built with symbols. There is a post build step that modifies the dll. The post build step does some compression and probably appends some data. The pdb file is still valid however neither WinDbg nor Visual Studio 2008 will load the symbols for the dll after the post build step. W... | This post led me to chkmatch. On the processed dll, chkmatch shows this info:
Executable:
TimeDateStamp: 4a086937
Debug info: 2 ( CodeView )
TimeStamp: 4a086937 Characteristics: 0 MajorVer: 0 MinorVer: 0
Size: 123 RVA: 00380460 FileOffset: 00380460
CodeView signature: sUar
Debug information file:
Format: PDB 7.... |
873,214 | 873,256 | unistd.h read() is reading more data then being written | I'm reading/writing data off of a named pipe. On the writing side it says that it's writing a constant 110 bytes. On the Reading side for the majority of time it says that it's reading 110 bytes which is correct, but other times it says its reading 220 bytes or 330 bytes. Which is right in the fact that when I print it... | This:
memset(bufpipe,'\0',5001);
is overwriting by one byte, because you have only 5000 bytes.
But the main "problem" is that read(..., 5000) will always read as much as it can up to 5000 bytes - you seem to be assuming that it will read only as much as was written in one go by the writer, which is not true. If the w... |
873,216 | 873,264 | Canonical form of += operator for classes | I know that it's a good idea to make as much of the interface of a class non-member non-friend as possible, and I've just realised that for my 3D vector class, 'Vector3', I can move the +=, -= and so on operators out of the class, leaving just constructors and the copy assignment operator.
The question is: what should ... | What you have looks good to me.
By the way, when you come to the operator+, it is common to implement that in terms of +=. (create a copy of lhs, and then call lhs += rhs and return the result)
Don't know if you're already aware of this trick, but since you're concerned about canonical ways to implement these operators... |
873,473 | 873,479 | Is there any situation in which it would be useful or necessary to "double link" header files? (C++) | I use the term "double link" because I don't know what the actual phrase is, or if there is one, but assuming you have two headers, head1.h and head2.h, with these contents:
In head1.h:
#include"head2.h"
//do stuff
In head2.h:
#include"head1.h"
//do stuff
I visualise it as two mirrors placed opposite each other, as i... | That's a "cyclic include" and no, it's not a desirable thing to do. your goto wouldn't help, because gotos are part of the program execution, while the #includes are interpreted during the preprocessing phase of compiling.
The usual thing is to make your header files have a structure like
#ifndef FOO_H
#define FOO_H
.... |
873,615 | 873,727 | Giving C++ Application a HTTP Web Server Functionality | I have a C++ app and looking for a library that would make it a HTTP Server that's able to serve static files as well as perform very simple tasks. The only constraint is that it must be Cross-platform.
What are my options.
Clarify: I need a web interface for my application. This application is a background program t... | In a question which has since been deleted, I asked:
I'm looking for a well-written, flexible library written in C or C++ (I'm writing my apps in C++) that can be used to embed an relatively simple HTTP server into my applications. Ultimately I will use this for application monitoring and control.
There are a number o... |
873,658 | 873,659 | How can I hook Windows functions in C/C++? | If I have a function foo() that windows has implemented in kernel32.dll and it always returns true, can I have my program: "bar.exe" hook/detour that Windows function and make it return false for all processes instead?
So, if my svchost, for example, calls foo(), it will return false instead of true. The same action sh... | Take a look at Detours, it's perfect for this sort of stuff.
For system-wide hooking, read this article from MSDN.
First, create a DLL which handles hooking the functions. This example below hooks the socket send and receive functions.
#include <windows.h>
#include <detours.h>
#pragma comment( lib, "Ws2_32.lib" )
#p... |
873,676 | 873,695 | disable folder virtualization in windows | I currently have a c++ application that gets built on xp and windows vista/7 virtualize some of the paths which i dont want it to do.
Some sites says to add this to manifest file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<... | Exactly the same. Create a file with the given context and add that file in your project settings:
Manifest Tool > Input and Output > Additional Manifest Files
Done!
|
873,715 | 873,725 | c++ sort with structs | I am having a hard time with this problem which requires a sort of customer names, customer ids, and finally amount due. I have the whole program figured, but cannot figure out the last prototype needed to do the sorting. i have a struct called Customers, and i will provide the int main() part also. I just need any hel... | You should use C++'s standard sort function, std::sort, declared in the <algorithm> header.
When you sort using a custom sorting function, you have to provide a predicate function that says whether the left-hand value is less than the right-hand value. So if you want to sort by name first, then by ID, then by amount du... |
873,729 | 873,742 | Watching Global Events created by a native process in a .NET process | I have a global event created and set/reset in a native C++ process that are created like this:
HANDLE hGlobalEvent = CreateEvent(NULL, TRUE, FALSE, _T("Global\\MyEvent"));
Is there any way (even if it's with a library not written by MS) to register for one of these events in a .NET (C#) process so that I standard .NE... | ThreadPool.RegisterWaitForSingleObject can be used to execute a callback when the event is signalled. Obtain a WaitHandle for the named event object by using the EventWaitHandle constructor that takes a string name.
bool createdNew;
WaitHandle waitHandle = new EventWaitHandle(false,
EventResetMode.ManualReset, @"Gl... |
873,731 | 873,804 | Object Registration in Static Library | I have implemented a very basic "plug-in system" as part of a static library. Each "plug-in" implements the support for a specific image format, e.g. GIF, JPEG, etc.. Furthermore, I have a Singleton (a class called PluginManager) that keeps a list of all available plug-ins.
The tricky part is that I want to disable/ena... | I don't know if this a solution for the way you solved this problem, but we had a similar problem with static registration of an object factory and in Visual Studio we solved it by declaring the classes involved with __declspec(dllexport) this was necessary even though the libraries involved were not dlls. But without ... |
873,745 | 873,759 | Why put a class declaration and definition in two separate files in C++? | I'm just wondering, what is the whole point of separating classes into an .h and a .cpp file? It makes it harder to edit, and if your class won't be compiled into a .lib or .dll for outside use, what's the point?
Edit:
The reason I'm asking is that the Boost libraries put everything in an .hpp file, (most of the librar... | C++ has something called the One Definition Rule. It means that (excluding inline functions), definitions can only appear in one compilation unit. Since C++ header files are just "copy and pasted" at every include file, now you are putting definitions in multiple places if you just put the definitions in header files.
... |
873,758 | 873,785 | C++ string value as another strings name | How can i convert a vartiables value int anothers name in C++? like in this php snippet.
$string = 'testVar';
${$string} = 'test';
echo $testVar; // test
| How about using a map?
#include <iostream>
#include <map>
#include <string>
using namespace std;
map<string, string> hitters;
hitters["leadoff"] = "Jeter";
hitters["second"] = "Damon";
hitters["third"] = "Teixiera";
hitters["cleanup"] = "Matsui";
string hitter = "cleanup";
cout << hitters[hitter] << endl;
|
873,976 | 874,051 | Fastest C/C++ image resizing library | I am writing a application that needs to resize massive amounts of images... and these are my requirements:
C/C++
Support jpeg/png at least
Fast
Cross-Platform
So far my options are:
OpenCV
CImg
ImageMagick
GraphicsMagick (it's said to be fast)
DevIL
GIL from Boost
CxImage
Imlib2 (it's said to be fast)
Any others?
... | Take a look at Intel IPP (Integrated Performance Primitives) (Wiki link is better then the Intel one...) it works also on AMD and has functions to resize images (bilinear, nearest neighbor, etc) and works on Linux and Windows.
It is not free (but it won't break the bank), but its the fastest that you can find.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.