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 |
|---|---|---|---|---|
507,971 | 508,010 | Do STL maps initialize primitive types on insert? | I have a std::map like this:
map<wstring,int> Scores;
It stores names of players and scores. When someone gets a score I would simply do:
Scores[wstrPlayerName]++;
When there is no element in the map with the key wstrPlayerName it will create one, but does it initialize to zero or null before the increment or is it l... | operator[] looks like this:
Value& map<Key, Value>::operator[](const Key& key);
If you call it with a key that's not yet in the map, it will default-construct a new instance of Value, put it in the map under key you passed in, and return a reference to it. In this case, you've got:
map<wstring,int> Scores;
Scores[wst... |
508,370 | 508,971 | quaternion libraries in C/C++ | Any good libraries for quaternion calculations in C/C++ ?
Side note: any good tutorials/examples? I've google it and been to the first few pages but maybe you have have some demos/labs from compsci or math courses you could/would share?
Thanks
| I'm a fan of the Irrlicht quaternion class. It is zlib licensed and is fairly easy to extract from Irrlicht:
Irrlicht Quaternion Documentation
quaternion.h
|
508,441 | 523,199 | Problems linking static Intel IPP libraries on Linux with g++ | I've been trying to move a project over from Xcode to Linux (Ubuntu x86 for now, but hopefully the statically-linked executable will run on an x86 CentOS machine? I hope I hope?). I have the whole project compiling but it fails at the linking stage-- it's giving me undefined references for all functions defined by IPP... | Your linking problem is likely due to the fact that your link line is completely backwards: archive libraries should follow source and object files on command line, not precede them. To understand why the order matters, read this.
Also note that on Linux statically linked executables are significantly less portable tha... |
508,844 | 508,891 | Having trouble initializing an SDL_Surface | I'm trying to set up something in SDL [in C++] where I can draw a one pixel big rectangle. I've got everything in my code working except my second SDL_Surface called rectangle. I'm having trouble initializing it. Here's the line where I try to initialize it:
rectangle = SDL_Surface(SDL_DOUBLEBUF | SDL_HWACCEL |
... | I think that the main problem you are having is that there is no SDL_Surface function. To create a new surface, use SDL_CreateRGBSurface. Be sure to call SDL_FreeSurface on the returned surface after you are done with it or you will leak memory.
Additionally, I am not sure why you are creating a surface for the recta... |
509,642 | 509,650 | C++ 'true' and 'false' keywords suddenly not true or false in Visual C++ 6.0 | My compiler (VC++ 6.0 sp6) has apparently gone insane. In certain pieces of code I'm seeing that 'bool mybool = true;' evalutes to and assigns false, and vice versa for true. Changing the true/false keywords to 1/0 makes it work fine. The same code compiles elsewhere fine without changing the true/false keywords.
Wh... | A preprocessor macro could certainly do it, although that would be pretty surprising. One way to check if that is the case would be
#ifdef true
# error "true is defined as a macro"
#endif
#ifdef false
# error "false is defined as a macro"
#endif
Response to comments:
Find a non-header file where you see this behavio... |
509,863 | 513,575 | Transferring vector of objects between C++ DLL and Cpp/CLI console project | I have a C++ library app which talks to a C++ server and I am creating a vector of my custom class objects. But my Cpp/CLI console app(which interacts with native C++ ), throws a memory violation error when I try to return my custom class obj vector.
Code Sample -
In my native C++ class -
std::vector<a> GetStuff(int x)... | I'll assume that the native code is in a separately compiled unit, like a .dll. First thing the worry about is the native code using a different allocator (new/delete), you'll get that when it is compiled with /MT or linked to another version of the CRT.
Next thing to worry about is STL iterator debugging. You should... |
509,989 | 514,406 | How to allow 32 bit apps on 64 bit windows to execute 64 bit apps provided in Windows\System32 | Say you have an app, that you want to provide users ability to browse the system32 directory and execute programs in (like telnet).
What is the best method for supporting this when you need to support XP onwards as a client and 2k onwards for server?
Having written all this up I wonder if it's just too much time/effort... | I've gone with option 2,
For those who might be interested; here is my quick hack at a scoped version of managing the disabling of Wow64 redirection based on notes from MS. Will redirect if the API is available, expects that kernel32.dll is already available.
class Wow64RedirectOff {
typedef BOOL (WINAPI *FN_Wow64... |
510,085 | 511,740 | How to call a python function from a foreign language thread (C++) | I am developing a program that use DirectShow to grab audio data from
media files. DirectShow use thread to pass audio data to the callback
function in my program, and I let that callback function call another
function in Python.
I use Boost.Python to wrapper my library, the callback function :
class PythonCallback {
p... | Take a look at PyGILState_Ensure()/PyGILState_Release(), from PEP 311
http://www.python.org/dev/peps/pep-0311/
Here is an example taken from the PEP itself:
void SomeCFunction(void)
{
/* ensure we hold the lock */
PyGILState_STATE state = PyGILState_Ensure();
/* Use the Python API */
...
/* Restore ... |
510,098 | 510,151 | g++ include all /usr/include recursively | I'm trying to compile a simple program, with
#include <gtkmm.h>
The path to gtkmm.h is /usr/include/gtkmm-2.4/gtkmm.h. g++ doesn't see this file unless I specifically tell it -I /usr/include/gtkmm-2.4.
My question is, how can I have g++ automatically look recursively through all the directories in /usr/include for al... | In this case, the correct thing to do is to use pkg-config in your Makefile or buildscripts:
# Makefile
ifeq ($(shell pkg-config --modversion gtkmm-2.4),)
$(error Package gtkmm-2.4 needed to compile)
endif
CXXFLAGS += `pkg-config --cflags gtkmm-2.4`
LDLIBS += `pkg-config --libs gtkmm-2.4`
BINS = program
program_OBJ... |
510,198 | 513,617 | How to implement RFC 3393 (Ipdv packet delay varation) in C? | I am building an Ethernet Application in which i will be sending packets from one side and receiving it on the other side. I want to calculate delay in packets at the receiver side as in RFC 3393. So I have to put a timestamps in the packet at the sender side and then take the timestamps at the receiver side as soon as... | RFC 3393 is for measuring the variance in the packet delay, not for measuring the delay itself.
To give an example: you're writing a video streaming application. You want to buffer as little video data as possible (so that the video starts playing as soon as possible). Let's say that data always always always takes... |
510,441 | 510,501 | How many threads to create and when? | I have a networking Linux application which receives RTP streams from multiple destinations, does very simple packet modification and then forwards the streams to the final destination.
How do I decide how many threads I should have to process the data? I suppose, I cannot open a thread for each RTP stream as there cou... | It is important to understand the purpose of using multiple threads on a server; many threads in a server serve to decrease latency rather than to increase speed. You don't make the cpu more faster by having more threads but you make it more likely a thread will always appear at within a given period to handle a reques... |
510,788 | 510,800 | How to pass an interface pointer to a thread? | Note:
Using raw Win32 CreateTheard() API
No MFC
An interface is simply a pointer to a vtable
Question:
How to pass an interface pointer to a thread?
Illustration:
IS8Simulation *pis8 = NULL;
...
CoCreateInstance(
clsid,
NULL,
CLSCTX_LOCAL_SERVER,
... | As was stated below, passing a COM interface pointer between threads in not safe.
Assuming you know what you are doing:
hThread = CreateThread(
NULL,
0,
SecondaryThread,
(LPVOID) pis8
0,
... |
510,845 | 510,936 | How to determine if the current window is the active window? | How can I tell if my window is the current active window?
My current guess is to do GetForegroundWindow and compare the HWND with that of my window.
Is there a better method than that?
I'm using Win32 API / MFC.
| Yes, that's the only way that I'm aware of.
But you have to handle the fact that GFW can return NULL. Typically, this happens when another desktop (e.g. the screen saver desktop) is active. Note that use of a saver password can affect whether a different desktop is used (this is windows version-dependent and I can't r... |
511,019 | 511,044 | Mac OS X: Where should I store save games for a game delivered as a bundle? | I'm porting a windows game to Mac OS X. I was wondering where I should store game data such as saved games, user profiles, etc and how I can retrieve that path programmatically in C++?
The game will be delivered as a "modern bundle" as specified here
| Save it under
~/Library/Application Support/Your Game Name/
where "~" stands for the home directory of the user playing your game.
You may want to give this a read: http://cocoadevcentral.com/articles/000084.php
|
511,768 | 511,779 | How to use my logging class like a std C++ stream? | I've a working logger class, which outputs some text into a richtextbox (Win32, C++).
Problem is, i always end up using it like this:
stringstream ss;
ss << someInt << someString;
debugLogger.log(ss.str());
instead, it would be much more convenient to use it like a stream as in:
debugLogger << someInt << someStrin... | You need to implement operator << appropriately for your class. The general pattern looks like this:
template <typename T>
logger& operator <<(logger& log, T const& value) {
log.your_stringstream << value;
return log;
}
Notice that this deals with (non-const) references since the operation modifies your logger... |
511,998 | 512,175 | How can I capture a stack trace on the QA computers | I am writing a Qt/C++ application, up until this month I have been using Mingw for compiling and drmingw for getting the stack trace from the QA people.
However I recently converted over to MSVC++ 9 so that I can use the phonon framework.
The downside is that now the stack traces from drmingw are useless. What do othe... | You can use Dr Watson to catch unhandled exceptions and generate a dump file.
The dump can then be opened in Visual Studio or WinDBG to see the stack of all threads, as long as you have the symbol files.
http://msdn.microsoft.com/en-us/library/cc265791.aspx
|
512,804 | 512,829 | C++ Newbie: Having all sorts of problems linking | I am having several problems with tessdll in Visual Studio 2008. FYI, I created this app as an MFC application, I did this just to take advantage of the simple GUI I needed. It is just straight C++ and win32 from there on out.
This builds fine as a debug release for some reason (as I have included the header files and ... | Without seeing the project settings, this is tough.
Things to check (differences between debug and release settings):
1) Are you including the .lib in the release build?
2) Did you accidentally define the preprocessor directive for tessdll?
I'd walk through the settings, switching back-and-forth between debug and relea... |
512,915 | 513,706 | Wanted: a C++ template idea to catch an issue, but at compile time? | We have a const array of structs, something like this:
static const SettingsSuT _table[] = { {5,1}, {1,2}, {1,1}, etc };
the structure has the following:
size_bytes:
num_items:
Other "meta data" members
So the "total size" is size_bytes*num_items for a single element. All of this information is in the const array, a... | Your problem is that they are constant, but they are not constant expressions when evaluated:
// f is constant, but its value not known at compile-time
int const f = rand() % 4;
What you need are true constant expressions. You can use boost::mpl to make up a mpl vector of mpl pairs, each with a pair of integral consta... |
512,941 | 512,965 | C/C++ read a byte from an hexinput from stdin | Can't exactly find a way on how to do the following in C/C++.
Input : hexdecimal values, for example: ffffffffff...
I've tried the following code in order to read the input :
uint16_t twoBytes;
scanf("%x",&twoBytes);
Thats works fine and all, but how do I split the 2bytes in 1bytes uint8_t values (or maybe even read t... | %x reads an unsigned int, not a uint16_t (thought they may be the same on your particular platform).
To read only one byte, try this:
uint32_t byteTmp;
scanf("%2x", &byteTmp);
uint8_t byte = byteTmp;
This reads an unsigned int, but stops after reading two characters (two hex characters equals eight bits, or one byte).... |
513,033 | 513,100 | How to create type-safe int - enum in C++? | I need to create many classes that are somewhere between integer and enum.
I.e. have the arithmetics of integer but also are not implicitly converted to int.
| Have a look at the answer to this question - BOOST_STRONG_TYPEDEF did exactly what I wanted.
// macro used to implement a strong typedef. strong typedef
// guarentees that two types are distinguised even though the
// share the same underlying implementation. typedef does not create
// a new type. BOOST_STRONG_TYPED... |
513,508 | 513,520 | Simple way to validate command line arguments | How to check if argv (argument vector) contains a char, i.e.: A-Z
Would like to make sure that argv only contains unsigned intergers
For example:
if argv[1] contained "7abc7\0" - ERROR
if argv[1] contains "1234\0" - OK
| bool isuint(char const *c) {
while (*c) {
if (!isdigit(*c++)) return false;
}
return true;
}
...
if (isuint(argv[1])) ...
Additional error checking could be done for a NULL c pointer and an empty string, as desired.
update: (added the missing c++)
|
514,194 | 514,205 | Using enum inside types - Compiler warning C4482 C++ | I am using fully qualified name of the enum inside a method in one of my class. But I am getting compiler warning which says "warning C4482: nonstandard extension used: enum 'Foo' used in qualified name". In C++, do we need to use enums without the qualified name? But IMO, that looks ugly.
Any thoughts?
| Yes, enums don't create a new "namespace", the values in the enum are directly available in the surrounding scope. So you get:
enum sample {
SAMPLE_ONE = 1,
SAMPLE_TWO = 2
};
int main() {
std::cout << "one = " << SAMPLE_ONE << std::endl;
return 0;
}
|
514,199 | 514,250 | Example of using FindFirstFIleEx() with specific search criteria | I asked about finding in subdirs with criteria. First answer was use FindFirstFileEx(). It seems the function is no good for this purpose or I'm using it wrong.
So can someone explain how I would go about searching in a folder, and all it's subfolders for files that match (to give some sample criteria) .doc;.txt;*.wr... | From MSDN:
If you refer to the code fragment in that page:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
void _tmain(int argc, TCHAR *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
if( argc != 2 )
{
_tprintf(TEXT("Usage: %s [target_file]\n"), argv[0]);
return;
}
_tpr... |
514,239 | 514,415 | MS SQL stored procedure returned result sets with ODBC | I have a stored procedure and if the stored procedure does this:
SELECT 0 As Ret
DELETE FROM table where value1 = 1
Returns 1 row result with its value of 0 and column name Ret
But if I do this:
DELETE FROM table where value1 = 1
SELECT 0 As Ret
I get no returned results.
My question is, how do I get the second vari... | Ok I found that you can use the ODBC call SQLMoreResults to get the next result set. So you can keep calling this SQLMoreResults function until there are no more result sets left.
In my case after calling SQLMoreResults I got my expected result set.
This is pretty cool because it means that a single stored procedure... |
514,420 | 514,495 | How to validate numeric input in C++ | I'd like to know how to limit an input value to signed decimals using std::cin.
| double i;
//Reading the value
cin >> i;
//Numeric input validation
if(!cin.eof())
{
peeked = cin.peek();
if(peeked == 10 && cin.good())
{
//Good!
count << "i is a decimal";
}
else
{
count << "i is not a decimal";
cin.clear();
... |
514,435 | 514,468 | Templatized branchless int max/min function | I'm trying to write a branchless function to return the MAX or MIN of two integers without resorting to if (or ?:). Using the usual technique I can do this easily enough for a given word size:
inline int32 imax( int32 a, int32 b )
{
// signed for arithmetic shift
int32 mask = a - b;
// mask < 0 means MSB is... | EDIT: This answer is from before C++11. Since then, C++11 and later has offered make_signed<T> and much more as part of the standard library
Generally, looks good, but for 100% portability, replace that 8 with CHAR_BIT (or numeric_limits<char>::max()) since it isn't guaranteed that characters are 8-bit.
Any good compi... |
514,637 | 514,686 | Is it more efficient to branch or multiply? | I am trying to optimize a small, highly used function which uses the high bits in an unsigned short int to indicate the values of an array to sum together. At first I was using the obvious approach shown below. Please note that loop unrolling is not explicitly shown as it should be done by the compiler.
int total = 0;
... | You could make it branchless without a multiply. It looks like for each bit set you are using that bit position as an index into an array.
First, you can easily extract bits set with:
unsigned short set_mask= i & -i;
i&= i - 1;
Then, you can get the bit index by counting the bits set in (set_mask - 1). There's a const... |
514,824 | 514,902 | Does C++ deep-initialize class members? | I have a class in C++ with the following member:
map< someEnum, vector<SomeObject*>* > someMap
So I have a map that gives me a vector of objects for each enumeration I have. For the life of me, I cannot understand how C++ is initializing these objects. Does it deep initialize them by default? If not, what do I need to... | The rule is: If an STL container contains pointers to objects, it it does not create objects on heap and assign them to these pointers. If, however, it contains objects themselves, it does call the default constructor of each contained object and thus initialises them.
What you have here is a map containing pointers (n... |
514,908 | 514,925 | Best way to return list of objects in C++? | It's been a while since I programmed in C++, and after coming from python, I feel soooo in a straight jacket, ok I'm not gonna rant.
I have a couple of functions that act as "pipes", accepting a list as input, returning another list as output (based on the input),
this is in concept, but in practice, I'm using std::ve... | The only thing I can see is that your forcing a copy of the list you return. It would be more efficient to do something like:
void DoSomething(const std::vector<SomeType>& in, std::vector<SomeType>& out)
{
...
// no need to return anything, just modify out
}
Because you pass in the list you want to return, ... |
514,977 | 514,991 | calling base class functions | I have following classes.
class A
{
public:
void fun();
}
class B: public A
{
}
class C: public A
{
}
A * ptr = new C;
Is it ok to do something like below? Will i have some problems if introduce some virtual functions in the baseclass?
((B *)ptr)->fun();
This may look stupid, but i have a function that calls ... | You can't cast an A* pointing to Class C as a B* because Class C doesn't have any relation with Class B. You'll get undefined behavior which will probably be the wrong function called and stack corruption.
If you intended for class C to derive from class B then you could. However, you wouldn't need to. If class C do... |
514,981 | 515,014 | Suggestion for template book for C++? | I am learning templates. Which book is worth buying for doing template programming?
I already have The C++ Programming Language and Effective C++.
| Those two books are pretty good in my opinion and they helped me a lot
C++ Templates: The Complete Guide by David Vandevoorde and Nicolai M.
Josuttis
Modern C++ Design by Andrei Alexandrescu
The first one explains how templates work. The second book is more about how to use them. I recommend you to... |
515,071 | 515,082 | Destructor called on object when adding it to std::list | I have a Foo object, and a std::list holding instances of it. My problem is that when I add a new instance to the list, it first calls the ctor but then also the dtor. And then the dtor on another instance (according to the this pointer).
A single instance is added to the list but since its dtor (along with its parents... | When you push_back() your Foo object, the object is copied to the list's internal data structures, therefore the Dtor and the Ctor of another instance are called.
All standard STL container types in C++ take their items by value, therefore copying them as needed. For example, whenever a vector needs to grow, it is poss... |
515,100 | 515,143 | Why does GCC look at private constructors when matching functions? | I'm very busy write now debugging some code, so I can't cookup a complete example, but this basically describes my problem
class Base{};
class MyX:public Base
{
...
};
class Derived:Base
{
...
};
template<class X>
class MyClass:Derived
{
private:
MyClass(const MyClass& )
:x()
{}
public:
MyClass(const... | MyClass<MyX>(x);
is parsed as
MyClass<MyX> x;
But MyClass<MyX> does not have a default constructor. Try giving it a name:
MyClass<MyX> p(x);
|
515,149 | 515,437 | Try/Catch a segmentation fault on Linux | I have a Linux C++ application and I'd like to test an object pointer for validity before dereferencing it. However try/catch doesn't work for this on Linux because of the segmentation fault. How can this be done?
| If you have a scenario where many pointers across your app reference the same limited-lifetime objects, a popular solution is to use boost smart pointers. Edit: in C++11, both of these types are available in the standard library
You would want to use shared_ptr for pointer(s) that are responsible for the lifetime of y... |
515,480 | 515,883 | How to set up headers and libraries for Linux development | I recently set up, for a learning exercise, an Ubuntu desktop PC with KDE 4.2, installed Eclipse and started to look for information on how to develop for KDE. I know there's KDevelop and will probably have a look at that at some time in the future. Right now, however, I don't have the correct headers and libraries for... | Make sure you have installed the build-essential package. For more documentation available from the command line, install glibc-doc, manpages-dev, gcc-*-doc, libstdc++*-doc (replace '*' with suitable version numbers for your system)
Getting Started/Build/KDE4/Kubuntu and Debian had a pair of sudo aptitude install comma... |
515,587 | 515,621 | Do I need to lock STL list with mutex in push_back pop_front scenario? | I have a thread push-backing to STL list and another thread pop-fronting from the list. Do I need to lock the list with mutex in such case?
| From SGI's STL on Thread Safety:
If multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses.
Since both your threads modify the list, I guess you have to lock it.
|
515,763 | 515,772 | How can Derived class inherit a static function from Base class? | struct TimerEvent
{
event Event;
timeval TimeOut;
static void HandleTimer(int Fd, short Event, void *Arg);
};
HandleTimer needs to be static since I'm passing it to C library (libevent).
I want to inherit from this class. How can this be done?
Thanks.
| You can easily inherit from that class:
class Derived: public TimerEvent {
...
};
However, you can't override HandleTimer in your subclass and expect this to work:
TimerEvent *e = new Derived();
e->HandleTimer();
This is because static methods don't have an entry in the vtable, and can't thus be virtual. You can ... |
515,788 | 516,742 | Deduction of reference types in template functions | Do I have to explicitly instantiate a function template's type when it comes to reference type deduction. If that is the case, where is the ambiguity? Let's compare following 2 code snippets:
1st: link for the code
template <typename T>
void foo(T& var, void(*func)(T&)) // T must be instantiated with int and it does ... | As highlighted in Fionn's answer, the problem is that the compiler deduces two distinct types for T, int and int&. 18.8.2.4/2 has the following:
In some cases, the deduction is done using a single set of types P and A, in other cases, there will be a set of
corresponding types P and A. Type deduction is done indepe... |
516,007 | 516,041 | std::map, pointer to map key value, is this possible? | std::map<std::string, std::string> myMap;
std::map<std::string, std::string>::iterator i = m_myMap.find(some_key_string);
if(i == m_imagesMap.end())
return NULL;
string *p = &i->first;
Is the last line valid?
I want to store this pointer p somewhere else, will it be valid for the whole program life?
But what w... | First, maps are guaranteed to be stable; i.e. the iterators are not invalidated by element insertion or deletion (except the element being deleted of course).
However, stability of iterator does not guarantee stability of pointers! Although it usually happens that most implementations use pointers - at least at some le... |
516,200 | 520,951 | Relative Paths Not Working in Xcode C++ | There are numerous post over the net that detail how relative paths don't work in Xcode. I do have an Xcode template that I downloaded where the relative paths DO work, however I have not been able to figure out why nor replicate it in other projects.
Firstly, I am using C++ in Xcode 3.1. I am not using Objective-C, no... | Took me about 5 hours of Google and trying different things to FINALLY find the answer!
#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif
// ----------------------------------------------------------------------------
// This makes relative paths work in C++ in Xcode by changing directory to the Resou... |
516,237 | 516,253 | When should I use typedef in C++? | In my years of C++ (MFC) programming in I never felt the need to use typedef, so I don't really know what is it used for. Where should I use it? Are there any real situations where the use of typedef is preferred? Or is this really more a C-specific keyword?
| Template Metaprogramming
typedef is necessary for many template metaprogramming tasks -- whenever a class is treated as a "compile-time type function", a typedef is used as a "compile-time type value" to obtain the resulting type. E.g. consider a simple metafunction for converting a pointer type to its base type:
temp... |
516,395 | 516,601 | When don't I need a typedef? | I encountered some code reading
typedef enum eEnum { c1, c2 } tagEnum;
typedef struct { int i; double d; } tagMyStruct;
I heard rumours that these constructs date from C. In C++ you can easily write
enum eEnum { c1, c2 };
struct MyStruct { int i; double d; };
Is that true? When do you need the first variant?
| First, both declarations are legal in both C and C++. However, in C, they have slightly different semantics. (In particular, the way you refer to the struct later varies).
The key concept to understand is that in C, structs exist in a separate namespace.
All built-in types, as well as typedefs exist in the "default" na... |
516,411 | 516,537 | raw function pointer from a bound method | I need to bind a method into a function-callback, except this snippet is not legal as discussed in demote-boostfunction-to-a-plain-function-pointer.
What's the simplest way to get this behavior?
struct C {
void m(int x) {
(void) x;
_asm int 3;
}};
typedef void (*cb_t)(int);
int main() {
C c;
boost::fun... | You can make your own class to do the same thing as the boost bind function. All the class has to do is accept the function type and a pointer to the object that contains the function. For example, this is a void return and void param delegate:
template<typename owner>
class VoidDelegate : public IDelegate
{
public:
... |
516,662 | 516,690 | Why can't I put an iterator in map? | I have a map defined like this
std::map<some_key_type, std::string::iterator> mIteratorMap;
And a huge string named "mHugeString". Then I walk trough the string collecting iterators like this:
std::string::iterator It=mHugeString.begin();
std::string::iterator EndIt=mHugeString.end();
for(;It!=EndIt;++It){
...defini... | I haven't tried it but I would have expected that, of course you can store iterator values as values in a map.
Do you know that if you change the contents of mHugeString then any iterators into it which you have previously stored are now invalid?
You might choose to store the index into the string, instead of the itera... |
516,763 | 517,576 | Open a socket using CreateFile | We've got some old serial code which checks whether a serial port is available simply by opening it and then closing it. Now we are adding network support to the app I want to reuse the function by supplying the ip address as a string.
/**
* So far I have tried:
* A passed in portPath normally looks like:
\\?\acpi#pn... | You can not create a socket via CreateFile. You should use the windows socket API for this purpose. For creating the SOCKET handle, you use WSASocket. Note that the SOCKET returned by this function can be used as a Windows Handle with some Windows functions, such as ReadFile and WriteFile.
|
517,003 | 517,165 | Matrix implementation benchmarks, should I whip myself? | I'm trying to find out some matrix multiplication/inversion benchmarks online. My C++ implementation can currently invert a 100 x 100 matrix in 38 seconds, but compared to this benchmark I found, my implementation's performances really suck. I don't know if it's a super-optimized something or if really you can easily i... | This sort of operation is extremely cache sensitive. You want to be doing most of your work on variables that are in your L1 & L2 cache. Check out section 6 of this doc:
http://people.redhat.com/drepper/cpumemory.pdf
He walks you through optimizing a matrix multiply in a cache-optimized way and gets some big perf imp... |
517,386 | 517,394 | the returned SDL_cursor from SDL_GetCursor() can't be used with SDL_GetMouseState()? | I'm trying to get the x, y, and state of my mouse in SDL. I tried using the lines
int mstate, mx, my = 0;
mstate, mx, my = SDL_GetCursor().SDL_GetMouseState();
But it gives me the error
C:[path]\particletest2\main.cpp|107|error: request for member SDL_GetMouseState' inSDL_GetCursor()', which is of non-class type `SDL... | http://www.libsdl.org/docs/html/sdlgetcursor.html
SDL_GetCursor() returns a pointer and so you need to use the -> operator to access its member.
Responding to your reply:
I think
mstate, mx, my = SDL_GetCursor()->SDL_GetMouseState();
is a problem if it wasn't incorrectly pasted. I do not think that this is doing what ... |
517,563 | 523,991 | C/C++ linker CALL16 reloc at xxxxx not against global symbol | I'm getting these errors while linking, both messages have to do with the same object file.
CALL16 reloc at 0x5f8 not against global symbol
and
could not read symbols: Bad value
The 2nd message seems to be the reason I'm getting the CALL16 error, but the file compiles just fine.
Any tips on fixing this?
FYI, I'm cros... | Aha!
Thanks to a colleague of mine, we found the issue.
Here was the issue:
There was a forward declaration/prototype of a function.
void FooBarIsBest(void);
Later on in the file the function was defined.
static void FooBarIsBest(void)
{
// do the best
}
The issue here was that in the prototype the keyword stati... |
518,028 | 518,081 | In c++ making a function that always runs when any other function of a class is called | C++ has so much stuff that I don't know.
Is there any way to create a function within a class, that will always be called whenever any other function of that class is called? (like making the function attach itself to the first execution path of a function)
I know this is tricky but I'm curious.
| Yes-ish, with a bit of extra code, some indirection and another class and using the -> instead of the . operator.
// The class for which calling any method should call PreMethod first.
class DogImplementation
{
public:
void PreMethod();
void Bark();
private:
DogImplementation(); // constructor private so can o... |
518,206 | 518,327 | Is there a way to allow a Windows service (unmanaged c++) to write files on a shared network folder? | I tried running the service in the "Local System" : didn't work.
I tried running the service in an account having rights on the network shared folder : didn't work.
Do I have to create a standalone application for this and launch this application as a user with rights on the network shared folder?
Thanks,
Nic
| Both your scenarios should work. The "local system" is the computer account in the active directory that you can give share permissions to. I have no idea why it doesn't work for you. But here is what you can do.
Use an regualar account (its just easier).
Test your application as console application.
Tweak the auditin... |
518,959 | 519,059 | Why does this dynamic_cast of auto_ptr fail? | #include "iostream"
class A {
private:
int a;
public :
A(): a(-1) {}
int getA() {
return a;
}
};
class A;
class B : public A {
private:
int b;
public:
B() : b(-1) {}
int getB() {
re... | Well, std::auto_ptr<B> is not derived from std::auto_ptr<A>. But B is derived from A. The auto_ptr does not know about that (it's not that clever). Looks like you want to use a shared ownership pointer. boost::shared_ptr is ideal, it also provides a dynamic_pointer_cast:
boost::shared_ptr<A> a = new A();
boost::shared_... |
518,995 | 519,021 | CUDA compiler (nvcc) macro | Is there a #define compiler (nvcc) macro of CUDA which I can use? (Like _WIN32 for Windows and so on.)
I need this for header code that will be common between nvcc and VC++ compilers. I know I can go ahead and define my own and pass it as an argument to the nvcc compiler (-D), but it would be great if there is one alre... | __CUDACC__
I don't think it will be that trivial. Check the following thread
http://forums.nvidia.com/index.php?showtopic=32369&st=0&p=179913&#entry179913
|
519,180 | 519,195 | C++ function that returns string doesn't work unless there's an endl involved...? | I've got a function inside of a class that returns a string. Inside this function, I can only get it to work when I add cout<<endl to the function before the return statement. Any idea why this is, or how I can fix it? I'm running this in Eclipse on a Mac
In "main.cpp":
#include <iostream>
#include <fstream>
#include... | actually getName() function is probably working correctly. However, the cout 'caches' the output (i.e. it prints the output on screen when it's internal text buffer is full). 'endl' flushes the buffer and forces cout to dump the text (in cache) to screen.
Try cout.flush() in main.cpp
|
519,558 | 545,207 | How to force parent window to draw "under" children windows? | The environment is plain-old win32 under C/C++ without any fancy MFC or similar mumbo-jumbo. I have a window, which has several children and grandchildren. Some children are oddly-shaped icons, and I need them to have transparent background (oddly-shaped icons). Consider a this pseudo-structure:
Parent1
Child1 (norm... | GWES will not paint the rectangle of any child window with contents of the parent window. Ever. Period. That's by design.
You can either paint in the child rectangle in response to WM_CTL... in the parent, or subclass the child and override its WM_PAINT completely. That will be really tough for certain windows, such as... |
519,685 | 531,364 | What is the best Framework to use for developing a skinned application? | I need to develop an application for windows, and it needs to support skins. I am looking for a framework to use. I would much prefer to not use QT, because of it's licensing - GPL is not an option for me, and it is otherwise to expensive (and I can't put off developing this application till March, when QT is suppose... | I've ended up writing my own custom skinning support, specific to my application.
Using a wxNO_BORDER with wxWidgets, and writing lots of controls from scratch, has given me the abilities I need.
In the future, I'll probably use QT, when it is under LGPL, or else WPF, when and if DotNet 3 is an option for me.
Thanks fo... |
519,808 | 519,812 | How to call a constructor on an already allocated memory? | How can I call a constructor on a memory region that is already allocated?
| You can use the placement new constructor, which takes an address.
Foo* foo = new (your_memory_address_here) Foo ();
Take a look at a more detailed explanation at the C++ FAQ lite or the MSDN. The only thing you need to make sure that the memory is properly aligned (malloc is supposed to return memory that is properly... |
519,836 | 519,898 | What is the "metadata operation failed" VS2008 linker error? | I have a big project that was first created in Borland C++ 6.
We're porting the program gradually to VS2008. There are many projects, which all compile to .lib, and I'm trying to build the exe of the test project for a set of projects.
After fixing the compiler errors, I got this crazy linker error:
1>av_geos_core_doma... | Have you tried searching for duplicated symbols? In my opinion PtoGrad is defined in two or more places, perhaps in different .lib, making the symbol resolving when building the .exe crash.
|
519,976 | 525,374 | Any recommendations for a PDF 3D SDK with C++ interface | I'm on the look out for a Cor C++ library / SDK that will allow me to either write a 3d PDF directly, or convert a DXF or DWG into a 3D PDF. So far I have come up with the PDF3d library which fits the bill, but is reasonably costly and has an expensive per user run time license. I don't mind a reasonable SDK cost, bu... | I use PDF XChange a lot for 2D CAD plots to PDF and it works well. I don't know if (I don't think so) it does 3D. I could find no mention of it at first glance on their site.
Your other option is a 3D DWF. Also consider that DWG TrueView is a free viewer and printer that handles 3D DWGs natively. You used to be able to... |
520,035 | 520,060 | Why can't you overload the '.' operator in C++? | It would be very useful to be able to overload the . operator in C++ and return a reference to an object.
You can overload operator-> and operator* but not operator.
Is there a technical reason for this?
| See this quote from Bjarne Stroustrup:
Operator . (dot) could in principle be overloaded using the same
technique as used for ->. However, doing so can lead to questions
about whether an operation is meant for the object overloading . or an
object referred to by . For example:
class Y {
public:
void f();
... |
520,599 | 520,620 | Suggestion on book to read about refactoring? | Will it be easy for a C++ developer to read Refactoring: Improving the Design of Existing Code
Is there any other book that I should read about refactoring? Feel free to add any articles on refactoring.
| If you work with legacy code then it may be worth getting Working Effectively with Legacy Code by Michael Feathers.
|
520,893 | 521,650 | C/C++ private array initialization in the header file | I have a class called Cal and it's .cpp and .h counterpart
Headerfile has
class Cal {
private:
int wa[2][2];
public:
void do_cal();
};
.cpp file has
#include "Cal.h"
void Cal::do_cal() {
print(wa) // where print just itterates and prints the elements in wa
}
My question is how do I initial... | If it can be static, you can initialize it in your .cpp file. Add the static keyword in the class declaration:
class Cal {
private:
static int wa[2][2];
public:
void do_cal();
};
and at file scope in the .cpp file add:
#include "Cal.h"
int Cal::wa[2][2] = { {5,2}, {7,9} };
void Cal::do_cal() {... |
521,083 | 521,092 | How can I tell the compiler not to create a temporary object? | I'm changing an old routine that used to take an integer parameter so that it now takes a const reference to an object. I was hoping that the compiler would tell me where the function is called from (because the parameter type is wrong), but the object has a constructor that takes an integer, so rather than failing, th... | Use the explicit keyword in the thing constructor.
class thing {
public:
explicit thing( int x ) {
printf( "Creating a thing(%d)\n", x );
}
};
This will prevent the compiler from implicitly calling the thing constructor when it finds an integer.
|
521,133 | 521,192 | Are "#define new DEBUG_NEW" and "#undef THIS_FILE" etc. actually necessary? | When you create a new MFC application, the wizard creates the following block of code in almost every CPP file:
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
and sometimes it also adds this:
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
I would like to remove this code from my CPP files if it is redundant. I am u... | It is perfectly safe to delete this. It's a debugging aid; leaving it in will generate better details in the warnings in the output window of any memory leaks you have when the program exits. If you delete it, you still get the memory leak report, but just without any details about where in your source code they occu... |
521,147 | 821,742 | The curious problem of the missing WM_NCLBUTTONUP message when a window isn't maximised | I've got a window that I handle WM_NCLBUTTONUP messages, in order to handle clicks on custom buttons in the caption bar. This works great when the window is maximised, but when it's not, the WM_NCLBUTTONUP message never arrives! I do get a WM_NCLBUTTONDOWN message though. Strangely WM_NCLBUTTONUP does arrive if I click... | I've had this same problem. The issue is indeed that a left button click on the window caption starts a drag, and thus mouse capture, which prevents WM_NCLBUTTONUP from arriving.
The solution is to override WM_NCHITTEST:
LRESULT CALLBACK WndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
switch (nMsg)
... |
521,220 | 529,090 | Decrypting RijndaelManaged Encrypted strings with CryptDecrypt | Ok I'm trying to use the Win32 Crypto API in C++ to decrypt a string encrypted in C# (.NET 2) with the RijndaelManaged Class. But I'm having no luck at all i get jibberish or a bad data Win32 error code. All my keys, IV and salt match, I've looked in the watch for both test apps. I've spent all say looking at it and... | Ok my fault, I didn't include the Struct def for the keyblob in the C++ and it turns out you need a contigous block of data for the key with the header but I was using the MSDN example that had a pointer to the key data. Which is wrong!
|
521,338 | 527,545 | Unexplainable crash in DirectX app in Windows XP that uses English language | The app was working fine but now a few weeks later when the new version begun testing, it crashes. Tried it on five of the workstations, it crashes only on two of them. And the only common about them I can find is that those two have Windows installed with English language.
Its a DirectX 8.1 application, written in C++... | Problem solved. And as a note to others having the same problem, I found the answer in this question. We installed the VS2005 CRT alright, but not the SP1 one.
Edit: Although, I still have no idea why this only affected the english workstations. Maybe it was a coincidence after all.
|
521,493 | 521,612 | Creating a linear gradient in 2D array | I have a 2D bitmap-like array of let's say 500*500 values. I'm trying to create a linear gradient on the array, so the resulting bitmap would look something like this (in grayscale):
(source: showandtell-graphics.com)
The input would be the array to fill, two points (like the starting and ending point for the Gradien... | In your example image, it looks like you have a radial gradient. Here's my impromtu math explanation for the steps you'll need. Sorry for the math, the other answers are better in terms of implementation.
Define a linear function (like y = x + 1) with the domain (i.e. x) being from the colour you want to start with to... |
521,518 | 521,600 | Visual Studio C++ Debugger: No hex dump? | Why is the integrated vs debugger so... barely functional? I cannot see the contents of an object in memory. For example, I am working with bitmaps and I would like to see them in memory. Do I need a better debugger for this? If so I am interested in recommendations. Nothing too powerful like a disassembler, just the d... | I've never found it to be "barely functional". VS gives you disassembly by default when it can't find source, and it's pretty easy to get to the memory view. Debug-> Windows -> Memory. Type "this" into the Address: box to get the memory of your current object. To view a specific member type '&this->member_name'. It'll ... |
521,754 | 521,875 | When to use friend class in C++ |
Possible Duplicate:
When should you use 'friend' in C++?
I was brushing up on my C++ (I'm a Java developer) and I came across the friend class keyword which I had forgotten about for a while. Is this one of those features that's just part of the kitchen sink, or is there a good reason for doing this rather than just... | I agree with the comments that say the friend keyword can improve encapsulation if used wisely. I'd just add that the most common (legitimate!) use for friend classes may be testing. You may want a tester class to have a greater degree of access than other client classes would have. A tester class could have a good ... |
521,809 | 710,741 | Creating a C++ Class Diagram | In Visual Studio .NET projects you can add a "Class Diagram" to the project which renders a visual representation of all namespaces, classes, methods, and properties. Is there any way to do this for Win32 (not .NET) C++ projects? Either through Visual Studio itself or with a 3rd party tool?
| If you have a Visual Studio 2008 solution composed of multiple C++ projects, you can only generate one class diagram per project.
For example, if you have one application project linking to 10 library projects, you'll have to generate 11 separate class diagrams.
There are two ways to work around this, neither of which ... |
521,824 | 526,693 | event notifications not received as described | Problem:
Event notifications (From COM object - Server) are not received as listed in the Sink (class) implementation.
One event notification is received (Event_one), however, others are not received accordingly
If order is changed - in IDispatch::Invoke, that is:
if Event_one is swapped to Event_two then Event_two ... | SOLVED:
After reviewing the corresponding IDL FILE (generated by the MIDL compiler), it was evident that each method contained in the IEvent interface, has a unique ID. For instance, Event_one has an ID of 2. For example:
methods:
[id(0x00000002)]
HRESULT Event_one();
Therefore, making a change as followings -... |
521,957 | 522,998 | How to develop a DirectFB app without leaving X.11 environment | I'm trying to develop a GUI application for an embedded platform, without any windowing whatsoever and I'm doing that with DirectFB, and it suits my needs very fine.
Since the embedded I develop for is not that powerful, I would really like to try to develop on my own Ubuntu desktop. The problem is Framebuffer is confl... | DirectFB has a X11 backend.
$ sudo apt-get install libdirectfb-extra # for Debian and Ubuntu, anyhow
$ cat ~/.directfbrc
system=x11
force-windowed
Also, DirectFB has a SDL backend, and SDL has a X11 backend. Also, SDL has a GGI backend, and GGI has an X backend. That's a bit circuitous, but it should work :)
I teste... |
521,972 | 523,092 | Why is runtime library a compiler option rather than a linker option? | I'm trying to build a C/C++ static library using visual studio 2005. Since the selection of the runtime library is a compile option, I am forced to build four variations of my library, one for each variation of the runtime library:
/MT - static runtime library
/MD - DLL runtime library
/MTd - debug static runtime l... | One side effect of the C preprocessor definitions like _DLL and _DEBUG that zdan mentioned:
Some data structures (such as STL containers and iterators) may be sized differently in the debug runtime, possibly due to features such as _HAS_ITERATOR_DEBUGGING and _SECURE_SCL. You must compile your code with structure defin... |
522,278 | 522,476 | Trouble examining byte code in MSVC++ | I've been messing around with the free Digital Mars Compiler at work (naughty I know), and created some code to inspect compiled functions and look at the byte code for learning purposes, seeing if I can learn anything valuable from how the compiler builds its functions. However, recreating the same method in MSVC++ ha... | I can only guess, but I'm pretty sure you are inspecting a debug build.
In debug mode the MSVC++ compiler replaces all calls by calls to jump stubs. This means, that every function starts with a jump to the real function and this is exactly what you are facing here.
The surrounding 0xCC bytes are indeed breakpoint ins... |
522,637 | 522,701 | Should objects delete themselves in C++? | I've spent the last 4 years in C# so I'm interested in current best practices and common design patterns in C++. Consider the following partial example:
class World
{
public:
void Add(Object *object);
void Remove(Object *object);
void Update();
}
class Fire : Object
{
public:
virtual void Update()
... | The problem with this is that you're really creating an implicit coupling between the object and the World class.
If I try to call Update() outside the World class, what happens? I might end up with the object being deleted, and I don't know why. It seems the responsibilities are badly mixed up. This is going to cause ... |
522,919 | 522,925 | Is this a reasonable use of the ternary operator? | Are there any understanding / maintainability issues that result from code like
inVar1 == 0 ? NULL : v.push_back(inVar1);
inVar2 == 0 ? NULL : v.push_back(inVar2);
and so forth.
The possibly confusing idea is using the ternary operator for program flow rather than variable assignment, which is the usual explanation.
I... | I think it's confusing and a lot harder to read than simply typing;
if (inVar != 0)
v.push_back(inVar);
I had to scan your example several times to figure out what the result would be with any certainty. I'd even prefer a single-line if() {} statement than your example - and I hate single-line if statements :)
|
522,931 | 522,939 | Creating variables / vectors based on runtime | I am working on a program that "encodes" a file based on a supplied bookfile. The resulting file has each letter replaced with a number. This number corresponds to the offset of that letters appearence in the bookfile. So if we had "hello" it would pick an 'h' from the bookfile, find its location number and replace it ... | You could use a std::map<unsigned int, std::vector<unsigned int> >, so that the character of interest is the key to the vector of offsets. That way, you don't have to code up N different vectors for each possible character in the file.
|
523,385 | 523,472 | How do I limit an external DLL to one CPU? | I have a program that I would like to run on just one CPU so it doesn't take up too much system resources. The problem is, it makes a call into an external DLL that automatically uses all available CPU cores. I do not have the source code to the external DLL. How can I limit the DLL to only using one CPU?
EDIT: Thanks ... | Setting processor affinity is the wrong approach. Let the OS handle scheduling.
If the machine is sitting idle, you want to use as much processor as you can. Otherwise you're doing less work for no reason. If the machine is busy, then you want to make use of "free" cycles and not adversely affect other processes.
Wi... |
523,724 | 523,737 | C/C++ check if one bit is set in, i.e. int variable | int temp = 0x5E; // in binary 0b1011110.
Is there such a way to check if bit 3 in temp is 1 or 0 without bit shifting and masking.
Just want to know if there is some built in function for this, or am I forced to write one myself.
| In C, if you want to hide bit manipulation, you can write a macro:
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
and use it this way to check the nth bit from the right end:
CHECK_BIT(temp, n - 1)
In C++, you can use std::bitset.
|
523,827 | 523,833 | C++0x atomic template implementation | I know that similar template exits in Intel's TBB, besides that I can't find any implementation on google or in Boost library.
| You can find discussions about this feature implementation in boost there : http://lists.boost.org/Archives/boost/2008/11/144803.php
> Can the N2427 - C++ Atomic Types and Operations be implemented
> without the help of the compiler?
No.
They don't need to be intrinsics if you can write inline assembler (or separatel... |
523,872 | 523,882 | How do you serialize an object in C++? | I have a small hierarchy of objects that I need to serialize and transmit via a socket connection. I need to both serialize the object, then deserialize it based on what type it is. Is there an easy way to do this in C++ (as there is in Java)?
Just to be clear, I'm looking for methods on converting an object into an ar... | Talking about serialization, the boost serialization API comes to my mind. As for transmitting the serialized data over the net, I'd either use Berkeley sockets or the asio library.
If you want to serialize your objects to a byte array, you can use the boost serializer in the following way (taken from the tutorial site... |
523,894 | 523,906 | Overloading . -> and :: for use in multiplatform classes | Say I have three window classes, one for each OS I want to support:
WindowsWindow
OSXWindow
LinuxWindow
They all inherit from the Window class. This is also the class you instantiate.
The Window class have the . -> and :: operators overloaded, and depending on which OS were running on (based on IFDEFs) it casts the... | You can't overload the scope resolution operator :: at all. You could overload the -> operator, but when you invoke that operator, you already have to have an object of the requisite type. For creating your windows, just use a simple factory method:
class Window
{
public:
static Window *CreateWindow(...)
{
#i... |
524,028 | 524,054 | Enum bitfield container class | Im trying to write a small class to better understand bit flags in c++. But something isnt working out. It prints the wrong values. Where is the problem? Have I misunderstood how to add flags? Or check if the bit field has them?
Heres the code:
#include <iostream>
enum flag
{
A = 1, B = 2, C = 4
};
class Holder
{... | personally I would use std::vector< bool > to handle flags, since it is a specialization that packs bools into bit.
However:
I think your remove flag is a bit complex, try this instead
void remove_flag( flag f )
{
if ( has_flag( f ) == true )
{
m_flags ^= f; // toggle the bit leaving all other unchanged
... |
524,137 | 524,167 | Get icons for common file types | I want to get the icons of common file types in my dll. I am using vc++. I only have the file extension and mime type of the file based on which I want to get the icon for the file.
Can someone please tell me how I can do that? (The method available in vc++ needs the user to give the path of the file for which the icon... | Shell API
You can get them from the shell by calling SHGetFileInfo() along with the SHGFI_USEFILEATTRIBUTES flag - this flag allows the routine to work without requiring the filename passed in to actually exist, so if you have a file extension just make up a filename, append the extension, and pass it in.
By combining ... |
524,342 | 524,350 | How to store a hash table in a file? | How can I store a hash table with separate chaining in a file on disk?
Generating the data stored in the hash table at runtime is expensive, it would be faster to just load the HT from disk...if only I can figure out how to do it.
Edit:
The lookups are done with the HT loaded in memory. I need to find a way to store th... | What language are you using? The common method is to do some sort binary serialization.
Ok, I see you have edited to add the language. For C++ there a few options. I believe the Boost serialization mechanism is pretty good. In addition, the page for Boost's serialization library also describes alternatives. Here is the... |
524,453 | 795,370 | boost asio and endian | I cant tell, does boost asio handle endian?
| Asio does convert things like port into network order. The conversion functions are not exposed as part of the official interface and are hidden in the detail namespace instead (e.g. boost::asio::detail::socket_ops::host_to_network_short).
|
524,495 | 524,510 | Is this code threadsafe? | I'm writing some code where the UI thread need to communicate with the background thread doing network communication. The code works, but would it be considered thread safe?
I would feel a lot better if someone experienced could lead me on to the right path on this...
static Mutex^ mut_currentPage = gcnew Mutex;
static... | It looks thread-safe, but you might want to think about exception handling; setting a field shouldn't error (except perhaps ThreadAbortException), but if the code was more complex, you'd want to ensure you release the mutex upon exception.
I'd also look at Monitor ("lock" in C#)
One other thought: even if you lock the ... |
524,512 | 524,550 | Most suitable asynchronous socket model for an instant messenger client? | I'm working on an instant messenger client in C++ (Win32) and I'm experimenting with different asynchronous socket models. So far I've been using WSAAsyncSelect for receiving notifications via my main window. However, I've been experiencing some unexpected results with Winsock spawning additionally 5-6 threads (in addi... | There are four basic ways to handle multiple concurrent sockets.
Multiplexing, that is using select() to poll the sockets.
AsyncSelect which is basically what you're doing with WSAAsyncSelect.
Worker Threads, creating a single thread for each connection.
IO Completion Ports, or IOCP. dp mentions them above, but basic... |
524,548 | 524,624 | Regular expression to detect semi-colon terminated C++ for & while loops | In my Python application, I need to write a regular expression that matches a C++ for or while loop that has been terminated with a semi-colon (;). For example, it should match this:
for (int i = 0; i < 10; i++);
... but not this:
for (int i = 0; i < 10; i++)
This looks trivial at first glance, until you realise that... | You could write a little, very simple routine that does it, without using a regular expression:
Set a position counter pos so that is points to just before the opening bracket after your for or while.
Set an open brackets counter openBr to 0.
Now keep incrementing pos, reading the characters at the respective positio... |
524,591 | 524,843 | Performance of creating a C++ std::string from an input iterator | I'm doing something really simple: slurping an entire text file from disk into a std::string. My current code basically does this:
std::ifstream f(filename);
return std::string(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
It's very unlikely that this will ever have any kind of performance impa... | I benchmarked your implementation(1), mine(2), and two others(3 and 4) that I found on stackoverflow.
Results (Average of 100 runs; timed using gettimeofday, file was 40 paragraphs of lorem ipsum):
readFile1: 764
readFile2: 104
readFile3: 129
readFile4: 402
The implementations:
string readFile1(const string &fileName... |
524,633 | 524,636 | How can i avoid name mangling? | How can I avoid name mangling in C++?
| You can't. It's built into compilers to allow you overloading functions and to have functions with the same name in different classes and such stuff. But you can write functions that are mangled like C functions. Those can be called from C code. But those can't be overloaded and can't be called by "normal" C++ function... |
524,641 | 528,661 | How do I create my own ostream/streambuf? | For educational purposes I want to create a ostream and stream buffer to do:
fix endians when doing << myVar;
store in a deque container instead of using std:cout or writing to a file
log extra data, such as how many times I did <<, how many times I did .write, the amount of bytes I written and how many times I flu... | The canonical approach consists in defining your own streambuf.
You should have a look at:
Angelika LAnger's articles on IOStreams derivation
James Kanze's articles on filtering streambufs
boost.iostream for examples of application
|
524,805 | 524,862 | How do I enlarge a picture so that it is 300 DPI? | The accepted answer to the question C++ Library for image recognition: images containing words to string recommended that you:
Upsize/Downsize your input image to 300 DPI.
How would I do this... I was under the impression that DPI was for monitors, not image formats.
| I think the more accurate term here is resampling. You want a pixel resolution high enough to support accurate OCR. Font size (e.g. in points) is typically measured in units of length, not pixels. Since 72 points = 1 inch, we need 300/72 pixels-per-point for a resolution of 300 dpi ("pixels-per-inch"). That means a typ... |
524,919 | 524,944 | Will Garbage Collected C be Faster Than C++? | I had been wondering for quite some time on how to manager memory in my next project. Which is writing a DSL in C/C++.
It can be done in any of the three ways.
Reference counted C or C++.
Garbage collected C.
In C++, copying class and structures from stack to stack and managing strings separately with some kind of GC.... | It all depends! That's a pretty open question. It needs an essay to answer it!
Hey.. here's one somebody prepared earlier:
http://lambda-the-ultimate.org/node/2552
http://www.hpl.hp.com/personal/Hans_Boehm/gc/issues.html
It depends how big your objects are, how many of them there are, how fast they're being allocated a... |
524,999 | 525,060 | C++ What's the max number of bytes you can dynamically allocate using the new operator in Windows XP using VS2005? | I have c++ code that attempts to dynamically allocate a 2d array of bytes that measures approx 151MB in size. When I attempt to go back and index through the array, my program crashes in exactly the same place every time with an "Access violation reading location 0x0110f000" error, but the indicies appear to be in ran... | Some possibilities to look at or things to try:
It may be that the pHDVideo->VideoData[iFrame] or pHDVideo->VideoData is being freed somewhere. I doubt this is the case but I'd check all the places this can happen anyway. Output a debug statement each time you free on of those AND just before your crash statement.
Som... |
525,227 | 525,270 | Console menu updating OpenGL window | I am making an application that does some custom image processing. The program will be driven by a simple menu in the console. The user will input the filename of an image, and that image will be displayed using openGL in a window. When the user selects some processing to be done to the image, the processing is done, a... | I've had this problem before - it's pretty annoying. The problem is that all of your OpenGL calls must be done in the thread where you started the OpenGL context. So when you want your main (input) thread to change something in the OpenGL thread, you need to somehow signal to the thread that it needs to do stuff (set a... |
525,365 | 525,377 | Does std::stack expose iterators? | Does the std::stack in the C++ STL expose any iterators of the underlying container or should I use that container directly?
| Stack does not have iterators, by definition of stack. If you need stack with iterators, you'll need to implement it yourself on top of other container (std::list, std::vector, etc).
Stack doc is here.
P.S. According to a comment i got from Iraimbilanja, std::stack by default uses std::deque for implementation.
|
525,609 | 529,017 | Use C++ with Cocoa Instead of Objective-C? | I would like to write applications that use C++ and the Cocoa frameworks because Apple is not making Carbon 64-bit capable. C++ seems to be pretty vanilla in its implementation on Linux and Windows but on Mac OS X it seems like additional Apple specific pieces of code are required (like an Obj-C wrapper). It also seems... | You cannot write a Cocoa application entirely in C++. Cocoa relies heavily on the late binding capabilities of Objective-C for many of its core technologies such as Key-Value Bindings, delegates (Cocoa style), and the target-action pattern. The late binding requirements make it very difficult to implement the Cocoa API... |
525,677 | 525,712 | Is there a way to disable all warnings with a pragma? | I've started a new project and have decided to make sure it builds cleanly with the /Wall option enabled. The only problem is not all 3rd party libraries (like boost) compile without warnings, so I've resorted to doing this in a shared header:
#pragma warning(push)
#pragma warning(disable:4820)
#pragma warning(disable... | You can push/pop a low level of warning, like this:
#pragma warning(push, 0)
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
// ...
#pragma warning(pop)
But know that it's not possible to disable all warnings. For example, some linker warnings are impossible to turn off.
|
525,803 | 525,915 | How can I trust the behavior of C++ functions that declare const? | This is a C++ disaster, check out this code sample:
#include <iostream>
void func(const int* shouldnotChange)
{
int* canChange = (int*) shouldnotChange;
*canChange += 2;
return;
}
int main() {
int i = 5;
func(&i);
std::cout << i;
return 0;
}
The output was 7!
So, how can we make sure of ... | Based on your edit, your question is "how can I trust 3rd party code not to be stupid?"
The short answer is "you can't." If you don't have access to the source, or don't have time to inspect it, you can only trust the author to have written sane code. In your example, the author of the function declaration specifical... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.