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 |
|---|---|---|---|---|
980,015 | 980,032 | Variable initialising and constructors | I am currently taking a c++ course and trying to get a deep understanding of the whole thing.
I came up with some theories, it would be great if somebody could confirm them:
Every variable (local,global,staic,member and non-member) is guaranteed to have its ctor called before first use
The ctors of primitives like int ... | You might find this interesting.
The difference between new Foo and new
Foo() is that former will be
uninitialized and the latter will be
default initialized (to zero) when Foo
is a POD type. So, when not using the
form with the parens, the member "a"
can contain garbage, but with the
parens "a" will alw... |
980,113 | 980,146 | Symbian: Is it possible to get access to a list of contacts through an application? | There are at least two ways that I know of to write a Symbian application:
1. J2ME
2. A native application.
My question is, does the SDK/API for either of those methods (or any other method) grant me (at least) read-only access to contact information (names/numbers/etc) on the phone itself? Does this in any way depe... | In C++, you can use e.g. the Contacts Model API. There's an example in Forum Nokia.
In J2ME, you need to be working on a phone that has JSR-75. Again, there's an example in Forum Nokia.
|
980,355 | 980,371 | How to hide an external program's windows programmatically? | I want to hide an external application, ie. not the current application. I want to give the title of the application and it will be hidden. How can I do this programmatically?
| In general terms, you could call FindWindow to get the HWND of the window in question, then ShowWindow with SW_HIDE to hide the window.
|
980,438 | 980,473 | Prevent misuse of logical operator instead of bitwise operators | In C++ it's possible to use a logical operator where a biwise operator was intended:
int unmasked = getUnmasked(); //some wide value
int masked = unmasked & 0xFF; // izolate lowest 8 bits
the second statement could be easily mistyped:
int masked = unmasked && 0xFF; //&& used instead of &
This will cause incorrect beh... | Ban in your coding standards the direct use of any bitwise operations in an arbitrary part of the code. Make it mandatory to call a function instead.
So instead of:
int masked = unmasked & 0xFF; // izolate lowest 8 bits
You write:
int masked = GetLowestByte(unmasked);
As a bonus, you'll get a code base which doesn't ... |
980,492 | 980,698 | What is metaprogramming? | With reference to this question, could anybody please explain and post example code of metaprogramming? I googled the term up, but I found no examples to convince me that it can be of any practical use.
On the same note, is Qt's Meta Object System a form of metaprogramming?
jrh
| Most of the examples so far have operated on values (computing digits of pi, the factorial of N or similar), and those are pretty much textbook examples, but they're not generally very useful. It's just hard to imagine a situation where you really need the compiler to comput the 17th digit of pi. Either you hardcode it... |
980,565 | 980,857 | Will bit-shift by zero bits work correctly? | Say I have a function like this:
inline int shift( int what, int bitCount )
{
return what >> bitCount;
}
It will be called from different sites each time bitCount will be non-negative and within the number of bits in int. I'm particularly concerned about call with bitCount equal to zero - will it work correctly th... | It is certain that at least one C++ compiler will recognize the situation (when the 0 is known at compile time) and make it a no-op:
Source
inline int shift( int what, int bitcount)
{
return what >> bitcount ;
}
int f() {
return shift(42,0);
}
Compiler switches
icpc -S -O3 -mssse3 -fp-model fast=2 bitsh.C
Intel ... |
980,573 | 980,911 | Compiler support for upcoming C++0x | Is there a compiler that has good support for the new C++0x?
I use GCC but unfortunately the current version 4.4 has a poor support for the new features.
| The only compiler that has an implementation of concepts is conceptgcc (and even that is incomplete - but it is good enough to get a good feel for the feature).
Visual C++ 2010 Beta has some useful C++0x support - you can play with lambdas, rvalue references, auto, decltype.
Comeau C++ or the EDG based compilers are su... |
980,881 | 981,357 | Passing multi-param function into a macro | Why does this not compile on VC 2005?
bool isTrue(bool, bool) { return true; }
void foo();
#define DO_IF(condition, ...) if (condition) foo(__VA_ARGS__);
void run()
{
DO_IF(isTrue(true, true)); // error C2143: syntax error : missing ')' before 'constant'
}
Running this through the preprocessor alone o... | Macros with indefinite numbers of arguments don't exist in the 1990 C standard or the current C++ standard. I think they were introduced in the 1999 C standard, and implementations were rather slow to adopt the changes from that standard. They will be in the forthcoming C++ standard (which I think is likely to come o... |
980,966 | 981,581 | Physics toolkit portability | Summary:
Have you ever made an interface between two -- or better yet even more -- different physics toolkits? For a online game (or at least with network physics)? How did it turn out? Lessons learned? Is it better to rewrite large chunks of code elsewhere, or did the investment pay off?
Bloat:
I'm using ODE physics t... | Take a look at the Physics Abstraction Layer (PAL) project hosted on SourceForge.net. They claim to support the following physics engines in addition to numerous other capabilities:
Box2D (experimental)
Bullet
Havok (experimental)
IBDS (experimental)
JigLib
Newton
ODE
OpenTissue (experimental)
PhysX (a.k.a Novodex, Ag... |
981,087 | 981,429 | Is there a QPointer specialization for boost::bind | boost::bind handles boost::shared_ptr the same way as raw pointers.
QObject * object(new QObject);
boost::shared_ptr<QObject> sharedObject(new QObject);
bind(&QObject::setObjectName, object, _1)( "name" );
bind(&QObject::setObjectName, sharedObject, _1)( "name" );
I would love to have a boost::bind that handles QPo... | Adding this overload of the get_pointer function should do the trick:
namespace boost {
template<typename T> T * get_pointer(QPointer<T> const& p)
{
return p;
}
}
|
981,139 | 981,169 | Visual Studio (C++) IntelliSense with parentheses | If I have a vector toto, when I write toto.s , IntelliSense gives me toto.size but I would like toto.size(). How to force IntelliSense to give me parentheses?
| I don't think that is possible using the visual studio's intellisense. However check out this very good third party tool which can do that: Visual Assist
|
981,147 | 981,548 | How to change Qt applications's dock icon at run-time in MacOS? | I need to change my Qt application's dock icon (in MacOS X) in run-time according to some conditions.
I've found several recipes on trolltech.com:
QApplication::setIcon()
setApplicationIcon()
qt_mac_set_app_icon()
but none of it works: there is no such methods/functions in Qt 4.5.
How can I change my application's do... | In Qt 4.5 the methods you are searching for are called
QApplication::setWindowIcon(const QIcon &)
or
QWidget::setWindowIcon(const QIcon &).
You can use every image format for icons that Qt supports (e.g. BMP, GIF, JPG, PNG, TIFF, XPM, ...).
Maybe you want to have a look at Qt's documentation at http://doc.qtsoftware... |
981,186 | 17,510,460 | Chaining iterators for C++ | Python's itertools implement a chain iterator which essentially concatenates a number of different iterators to provide everything from single iterator.
Is there something similar in C++ ? A quick look at the boost libraries didn't reveal something similar, which is quite surprising to me. Is it difficult to implement ... | Came across this question while investigating for a similar problem.
Even if the question is old, now in the time of C++ 11 and boost 1.54 it is pretty easy to do using the Boost.Range library. It features a join-function, which can join two ranges into a single one. Here you might incur performance penalties, as the l... |
981,306 | 981,356 | How to detect whether Windows is shutting down or restarting | I know that when Windows is shutting down, it sends a WM_QUERYENDSESSION message to each application. This makes it easy to detect when Windows is shutting down. However, is it possible to know if the computer going to power-off or is it going to restart after Windows has shutdown.
I am not particularly hopeful, consid... | From here:
You can read the DWORD value from
"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shutdown
Setting" to determine what the user
last selected from the Shut Down
dialog.
A bit of a roundabout solution, but it should do the trick.
|
981,400 | 981,435 | What happens if a throw; statement is executed outside of catch block? | In C++ throw; when executed inside a catch block rethrows the currently caught exception outside the block.
In this answer an idea of exception dispatcher is brought up as a solution to reducing code duplication when using complex exception handling often:
try {
CodeThatMightThrow();
} catch(...) {
ExceptionHan... | From the Standard, 15.1/8
If no exception is presently being handled, executing a throw-expression with no operand calls std::terminate().
|
981,787 | 983,153 | Good portable SIMD library | can anyone recommend portable SIMD library that provides a c/c++ API, works on Intel and AMD extensions and Visual Studio, GCC compatible. I'm looking to speed up things like scaling a 512x512 array of doubles. Vector dot products, matrix multiplication etc.
So far the only one I found is:
http://simdx86.sourceforge.... | Since you mention high-level operations on matrices and vectors, ATLAS, Intel's MKL, PLASMA, and FLAME may be of interest.
Some C++ matrix math libraries include uBLAS from Boost, Armadillo, Eigen, IT++, and Newmat. The POOMA library probably also includes some of these things. This question also refers to MTL.
If you'... |
982,081 | 1,473,602 | C++/C# callback continued | After asking this question and apparently stumping people, how's about this for a thought-- could I give a buffer from a C# application to a C++ dll, and then have a timing event in C# just copy the contents of the buffer out? That way, I avoid any delays caused by callback calling that apparently happen. Would that ... | As I said in the other thread, it seems the delay was entirely on the C++ side, so no amount of finagling on my end was going to fix the problem.
|
982,129 | 982,179 | What does __sync_synchronize do? | I saw an answer to a question regarding timing which used __sync_synchronize().
What does this function do?
And when is it necessary to be used?
| It is a atomic builtin for full memory barrier.
No memory operand will be moved across the operation, either forward
or backward. Further, instructions will be issued as necessary to
prevent the processor from speculating loads across the operation and
from queuing stores after the operation.
Check details on t... |
982,266 | 982,283 | Launch IE from a C++ program | I have a program written in C++ which does some computer diagnostics. Before the program exits, I need it to launch Internet Explorer and navigate to a specific URL. How do I do that from C++?
Thanks.
| Here you are... I am assuming that you're talking MSVC++ here...
// I do not recommend this... but will work for you
system("\"%ProgramFiles%\\Internet Explorer\\iexplore.exe\"");
// I would use this instead... give users what they want
#include <windows.h>
void main()
{
ShellExecute(NULL, "open", "http://stack... |
982,421 | 982,775 | How to write portable floating point arithmetic in c++? | Say you're writing a C++ application doing lots of floating point arithmetic. Say this application needs to be portable accross a reasonable range of hardware and OS platforms (say 32 and 64 bits hardware, Windows and Linux both in 32 and 64 bits flavors...).
How would you make sure that your floating point arithmetic ... | Non-IEEE 754
Generally, you cannot. There's always a trade-off between consistency and performance, and C++ hands that to you.
For platforms that don't have floating point operations (like embedded and signal processing processors), you cannot use C++ "native" floating point operations, at least not portably so. While ... |
982,529 | 982,650 | Old issues of "C++ Report"? | I used to receive "C++ Report" magazine (along with "C/C++ User's Journal"), both now defunct.
For the longest time, I would cart around the issues, from move to move. Regrettably, a few years ago I decided to stop carting them around & I recycled them.
There was a lot of wisdom in those pages, and now I find myself ... | The only thing I can think of is the book "C++ Gems", which is basically 42 articles from the first 7 years, published in 1996. I got a copy from a used bookstore a few years ago.
It would be nice to have a dvd - I have the Dr. Dobbs and C/C++ UJ ones. The indexing seems a little flakey, but everything is there if you ... |
982,702 | 982,724 | Is there a way to simulate Windows input with C++? | I'm wondering if its possible to make a program in C++ that can "press" keys, or make the computer think certain keys have been pressed, and do things like make a program that "plays" games, or automatically enter some long and obscure button sequence that no one could remember.
(I can't think of any right now, but sav... | http://msdn.microsoft.com/en-us/library/8c6yea83(VS.85).aspx
|
982,808 | 982,941 | C++ SFINAE examples? | I want to get into more template meta-programming. I know that SFINAE stands for "substitution failure is not an error." But can someone show me a good use for SFINAE?
| Heres one example (from here):
template<typename T>
class IsClassT {
private:
typedef char One;
typedef struct { char a[2]; } Two;
template<typename C> static One test(int C::*);
// Will be chosen if T is anything except a class.
template<typename C> static Two test(...);
public:
enum { Yes ... |
982,829 | 982,861 | Shifting from .NET to Win32 development | I have been a .NET developer since I started coding. I would like to learn Win32 programming. Need advice on where to start. What are the best resources /books for learining Win32 programming. I know a bit 'college C++'.
| If you are interested in UI development, the best book for direct Win32 development in C or C++ (no MFC) is Programming Windows by Charles Petzold
For other sorts of Win32 development, such as threading, memory, DLL's, etc., Windows via C/C++ by Jeffrey Richter is a great book.
For general Windows architecture, Windows... |
982,963 | 982,999 | Is there any overhead to declaring a variable within a loop? (C++) | I am just wondering if there would be any loss of speed or efficiency if you did something like this:
int i = 0;
while(i < 100)
{
int var = 4;
i++;
}
which declares int var one hundred times. It seems to me like there would be, but I'm not sure. would it be more practical/faster to do this instead:
int i = 0;... | Stack space for local variables is usually allocated in function scope. So no stack pointer adjustment happens inside the loop, just assigning 4 to var. Therefore these two snippets have the same overhead.
|
983,244 | 983,259 | Is this deallocation correct? | I've a 3x3 2D dynamic array allocated as below:
int** matrix = new int* [3];
matrix[0] = new int [3*3];
for (int i = 1; i < 3; ++i)
matrix[i] = matrix[i-1] + 3;
How should I deallocate it? Is this correct:
delete [] matrix;
delete [] matrix[0];
Or should I also delete matrix[1], [2]
| The way you have it, you should :
delete [] matrix[0];
delete [] matrix;
But this is a very unconventional way of allocating a dynamic 2D array. Normally you allocate an array of pointers, and then you allocate an array of your actual type for every row (column).
// allocate
int **matrix = new int*[3];
for(int i = 0;... |
983,305 | 983,343 | Can I use interlocked operations to update multiple values to avoid locking a critical section/mutex? | I have a multithreaded application (C++) where I need to increment/change a series of values.
If I use a series of Interlocked operations, are they considered to be a single atomic operation ? Like in this example:
InterlockedIncrement(&value1);
InterlockedIncrement(&value2);
InterlockedExchange(&oldValue, newValue);
... | InterlockedIncrement itself is an atomic operation but series of InterLockedIncrement are not atomic together. If your requirement is to get the atomicity for series of operation then you can use critical section.
|
983,310 | 983,329 | Calling a method from another method in the same class in C++ | I wrote a method (that works fine) for a() in a class. I want to write another method in that class that calls the first method so:
void A::a() {
do_stuff;
}
void A::b() {
a();
do_stuff;
}
I suppose I could just rewrite b() so b(A obj) but I don't want to. In java can you do something like this.a().
I want to... | That's exactly what you are doing.
|
983,376 | 983,524 | recursive folder scanning in c++ | I want to scan a directory tree and list all files and folders inside each directory. I created a program that downloads images from a webcamera and saves them locally. This program creates a filetree based on the time the picture is downloaded. I now want to scan these folders and upload the images to a webserver but ... | See man ftw for a simple "file tree walk". I also used fnmatch in this example.
#include <ftw.h>
#include <fnmatch.h>
static const char *filters[] = {
"*.jpg", "*.jpeg", "*.gif", "*.png"
};
static int callback(const char *fpath, const struct stat *sb, int typeflag) {
/* if it's a file */
if (typeflag == ... |
983,460 | 4,566,154 | C++ formatted input: how to 'skip' tokens? | Suppose I have an input file in this format:
VAL1 VAL2 VAL3
VAL1 VAL2 VAL3
I'm writing a program that would be interested only in VAL1 and VAL3. In C, if i wanted to 'skip' the second value, I'd do as follows:
char VAL1[LENGTH]; char VAL3[LENGTH];
FILE * input_file;
fscanf(input_file, "%s %*s %s", VAL1, VAL3);
Meanin... | The C++ String Toolkit Library (StrTk) has the following solution to your problem:
#include <string>
#include <deque>
#include "strtk.hpp"
int main()
{
struct line_type
{
std::string val1;
std::string val3;
};
std::deque<line_type> line_list;
const std::string file_name = "data.txt";
s... |
983,728 | 983,846 | C++ - Convert FILE* to CHAR* | I found a C++ source file which calculates expressions from a command line argument (argv[1]), however I now want to change it to read a file.
double Utvardering(char* s) {
srcPos = s;
searchToken();
return PlusMinus();
}
int main(int argc, char* argv[]) {
if (argc > 1) {
FILE* fFile = fopen(argv[1], "r");
dou... | The function fopen just opens a file. To get a string from there, you need to read the file. There are different ways to to this. If you know the max size of your string in advance, this would do:
const int MAX_SIZE = 1024;
char buf[MAX_SIZE];
if (!fgets(buf, MAX_SIZE, fFile) {
cerr << "Read error";
exit(1);
}
doub... |
983,762 | 983,914 | Fully Featured C++ Assert Dialog? | I'm looking for a good, fully featured C++ assert macro for VisualStudio. With features like be able to ignore an assert once or always, to be able to break exactly where the macro gets called (and not inside macro code), and getting a stack trace.
Before I have to hunker down and write one, I figured I'd ask if anyone... | See Charles Nicholson's blog for a good discussion of an assert macro. His solution breaks the debugger at the faulting line of code (and not inside the failed assertion handler), and he also solves the problem of not getting warnings about unused variables when assertions are disabled without incurring any runtime co... |
983,997 | 984,016 | I have an unintended delay in playing a Mix_Chunk | So I am trying to learn SDL and creating a small game. When the user presses the space bar, it should play a sound. This works, but the sound takes about .5 seconds to play... How would I fix this? I've checked the actual file to see if the delay was just part of it, and that turned out to not be the case.
SDL with c++... | There is usually a check for DirectX headers when compiling SDL (apparently)
Can you try to recompile with DirectX support?
Also, how much buffering are you enforcing at the client side? It may be a problem with that.
EDIT - After the comments below:
Try to increase the size of your buffer.
What I mean by recompiling ... |
983,999 | 984,054 | Simple 3x3 matrix inverse code (C++) | What's the easiest way to compute a 3x3 matrix inverse?
I'm just looking for a short code snippet that'll do the trick for non-singular matrices, possibly using Cramer's rule. It doesn't need to be highly optimized. I'd prefer simplicity over speed. I'd rather not link in additional libraries.
| Why don't you try to code it yourself? Take it as a challenge. :)
For a 3×3 matrix
(source: wolfram.com)
the matrix inverse is
(source: wolfram.com)
I'm assuming you know what the determinant of a matrix |A| is.
Images (c) Wolfram|Alpha and
mathworld.wolfram (06-11-09,
22.06)
|
984,107 | 984,124 | Returning STL lists as argument | I have a function that reads lines from a log file, converts these lines to a certain class and returns a STL list of instances of this class.
How should I declare this function so that the whole list is NOT copied when attributing it to the caller?
Without loss of generality, assume:
list<Request> requests = log_manip... | Returning a reference is not advisable, and returning the list object would cause copying. Best would be to change the method's signature to accept and populate a list reference:
list<Request> requests;
log_manipulator.getRequestListByRef(requests);
with void getRequestListByRef(list<Request>&) as the method's signatu... |
984,141 | 984,371 | Forcing non-cached gethostbyname() | Is there any way to prevent the gethostbyname() function not to read the nscd cache on Linux?
| Not really an answer, but use getaddrinfo(3) instead :)As far as nscd is concerned, here's from the nscd.conf(5) manual page:
enable-cache service <yes|no>
Enables or disables the specified service cache.
You'll have to find out what the correct service for DNS is.
|
984,357 | 984,401 | Path sanitization in C++ | I'm writing a small read-only FTP-like server. Client says "give me that file" and my server sends it.
Is there any standard way (a library function?!?) to make sure that the file requested is not "../../../../../etc/passwd" or any other bad thing? It would be great if I could limit all queries to a directory (and its ... | Get the inode of the root (/) directory, and that of the serving directory (say /ftp/pub). For the files they request, make sure that:
The file exists.
The parents of the file (accessed using multiple "/.." on the file path) hit the serving directory inode before it hits the root directory inode.
You can use stat to... |
984,394 | 984,597 | Why not infer template parameter from constructor? | my question today is pretty simple: why can't the compiler infer template parameters from class constructors, much as it can do from function parameters? For example, why couldn't the following code be valid:
template <typename obj>
class Variable {
obj data;
public:
Variable(obj d) { data = d; }
};
int main()... | I think it is not valid because the constructor isn't always the only point of entry of the class (I am talking about copy constructor and operator=). So suppose you are using your class like this :
MyClass m(string s);
MyClass *pm;
*pm = m;
I am not sure if it would be so obvious for the parser to know what template ... |
984,792 | 984,793 | Lighting issue in OpenGL | I have trouble developing an OpenGL application.
The weird thing is that me and a friend of mine are developing a 3d scene with OpenGL under Linux, and there is some code on the repository, but if we both checkout the same latest version, that means, the SAME code this happens: On his computer after he compiles he can ... | This can very easily be a driver problem, or one card supporting extensions that the other does not.
Try his binaries on your machine. If it continues to fail, either your drivers are whack or you're using a command not supported by your card. On the other hand if your screen looks right when using your code compiled... |
985,281 | 985,374 | What is the closest thing Windows has to fork()? | I guess the question says it all.
I want to fork on Windows. What is the most similar operation and how do I use it.
| Cygwin has fully featured fork() on Windows. Thus if using Cygwin is acceptable for you, then the problem is solved in the case performance is not an issue.
Otherwise you can take a look at how Cygwin implements fork(). From a quite old Cygwin's architecture doc:
5.6. Process Creation
The fork call in Cygwin is par... |
985,404 | 985,429 | Static libraries, linking and dependencies | I have a static library that I want to distribute that has includes Foo.c/h and someone picks it up and includes my static library in their application.
Say they also have Foo.c/h in their application. Will they have linking errors?
| The name of a source file is not significant in the linking process.
If the file has the same contents, then you'll have a problem, assuming that the .c file contains exported symbols (e.g. non-static or non-template functions, or extern variables).
|
986,021 | 986,084 | How to implement sorting method for a c++ priority_queue with pointers | My priority queue declared as:
std::priority_queue<*MyClass> queue;
class MyClass {
bool operator<( const MyClass* m ) const;
}
is not sorting the items in the queue.
What is wrong? I would not like to implement a different (Compare) class.
Answer summary:
The problem is, the pointer addresses are sorted. The onl... | Give the que the Compare functor ptr_less.
If you want the ptr_less to be compatible with the rest of the std library (binders, composers, ... ):
template<class T>
struct ptr_less
: public binary_function<T, T, bool> {
bool operator()(const T& left, const T& right) const{
return ((*left) <( *r... |
986,210 | 986,243 | undefined reference to the shared library function | I have implemented a shared library in Linux and try to test it, but I get an error "undefined reference to `CEDD(char*)'".
I use Eclipse with following parameters:
Path to include files (here is
everything ok)
Path to the library
and its name. Path is correct and the
name is WISE_C (full name:
libWISE_C.so)
My Code... | It's a linker error (although I don't think it usually includes the 'char*' bit), so it seems that it either cannot find your library or the library does not contain the function. The latter might also mean that it does contain the actual function, but with a different name; make sure both projects a compiled as C and ... |
986,321 | 986,428 | Reformat C++ braces without changing indentation? | We would like to make our C++ brace style more consistent. Right now, our code contains a mix of:
if (cond)
{
// ...
}
else
{
// ...
}
...and:
if (cond) {
// ...
} else {
// ...
}
We want to use the latter style exclusively.
However, we don't want to change the indentation of our code. I've tried... | Here's a Perl one-liner that should do what you want.
perl -pi.bak -e 'BEGIN { undef $/; } s/\s*?(\s?\/\/.*)?\r?\n\s*{/ {\1/g; s/}(\s?\/\/.*)?\r?\n\s*else\b(.*)/} else\2\1/g;'
It turns this:
int main(int argc, char *argv[])
{
int something = 0;
if (something) // 5-12-2007
{
printf("Hi!\n");
... |
986,426 | 986,584 | What do __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS mean? | I see this in the standard C++ libraries for my system, as well as some of the headers in a library I'm using.
What are the semantics of these two definitions? Is there a good reference for #defines like this other than the source itself?
| __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS are a workaround to allow C++ programs to use stdint.h macros specified in the C99 standard that aren't in the C++ standard. The macros, such as UINT8_MAX, INT64_MIN, and INT32_C() may be defined already in C++ applications in other ways. To allow the user to decide if the... |
986,610 | 986,713 | Language to write a Windows application that doesn't take up a lot of space | I need to write a Windows XP/Vista application, main requirements:
Just one .exe file, without extra runtime, like Air, .Net; posstibly a couple of dlls.
Very small file size.
The application is for network centric usage, similar to ICQ or Gtalk clients.
| It depends, I think, how much UI you require. The benefit of frameworks such as MFC is it wraps a lot of boiler plate code for you. However.. if executable size & dependencies are the major constraint, it can be quite fun to build a tiny app.
It's quite possible to build a Windows application with bare essentials (a... |
987,585 | 987,621 | C++ system function hangs application | I have the following code
void reportResults()
{
wstring env(_wgetenv(L"ProgramFiles"));
env += L"\Internet Explorer\iexplore.exe";
wstringstream url;
url << "\"\"" << env.c_str() << "\" http://yahoo.com\"";
wchar_t arg[BUFSIZE];
url.get(arg, BUFSIZE);
wcout << arg << endl;
_wsystem... | You want to use _wspawn() instead of _wsystem(). This will spawn a new process for the browser process. _wsystem() blocks on the command that you create; this is why you're not getting back to your code. _wspawn() creates a new, separate process, which should return to your code immediately.
|
987,684 | 987,718 | Does GCC have a built-in compile time assert? | Our existing compile-time assert implementation is based on negative array index, and it provides poor diagnostic output on GCC. C++0x's static_assert is a very nice feature, and the diagnostic output it provides is much better. I know GCC has already implemented some C++0x features. Does anyone know if static_assert i... | According to this page, gcc has had static_assert since 4.3.
|
987,828 | 987,864 | Is there a better way to load in a big animation? | Maybe not really big, but a hundred frames or something. Is the only way to load it in by making an array and loading each image individually?
load_image() is a function I made which loads the images and converts their BPP.
expl[0] = load_image( "explode1.gif" );
expl[1] = load_image( "explode2.gif" );
expl[2] = load_i... | A common technique is spritesheets, in which a single, large image is divided into a grid of cells, with each cell containing one frame of an animation. Often, all animation frames for any game entity are placed on a single, sometimes huge, sprite sheet.
|
987,960 | 988,110 | Dividing C++ Application into Libraries | My C++ project is growing larger. We are also moving to using cmake for building now. I want to divide the application into libraries so that they can be linked for testing, preparing the application package, etc. Right now I would divide my code into libraries as follows:
core
GUI
utilities (these are used by core an... | Sit down with a piece of paper and decide your library architecture.
The library should be designed as a set of levels.
A libary on level A (the base) should have dependencioes only on system libraries and only if it must on libraries on level A.
A library on level B can have dependencies on libraries at level A... |
988,069 | 988,084 | const int *p vs. int const *p - Is const after the type acceptable? | My co-worker is 0 for 2 on questions he has inspired (1, 2), so I thought I'd give him a chance to catch up.
Our latest disagreement is over the style issue of where to put "const" on declarations.
He is of the opinion that it should go either in front of the type, or after the pointer. The reasoning is that this is wh... | The most important thing is consistency. If there aren't any coding guidelines for this, then pick one and stick with it. But, if your team already has a de facto standard, don't change it!
That said, I think by far the more common is
const int * i;
int * const j;
because most people write
const int n;
instead of
int... |
988,158 | 988,220 | Take the address of a one-past-the-end array element via subscript: legal by the C++ Standard or not? | I have seen it asserted several times now that the following code is not allowed by the C++ Standard:
int array[5];
int *array_begin = &array[0];
int *array_end = &array[5];
Is &array[5] legal C++ code in this context?
I would like an answer with a reference to the Standard if possible.
It would also be interesting to... | Your example is legal, but only because you're not actually using an out of bounds pointer.
Let's deal with out of bounds pointers first (because that's how I originally interpreted your question, before I noticed that the example uses a one-past-the-end pointer instead):
In general, you're not even allowed to create a... |
988,334 | 988,422 | Using a DLL in Visual Studio C++ | I have a DLL that I've been using with no problem in Visual C# (simply adding the reference and using the namespace). Now I'm trying to learn C++, and I don't understand how you reference a namespace from a DLL. I can right-click on a project and select 'references' and from there click 'add new reference', but that ju... | C++ is a lot different from C#/VB.Net when it comes to processing DLL references. In C# all that is needed to do a reference is a DLL because it contains metadata describing the structures that lay inside. The compiler can read this information such that they can be used from another project.
C++ does not have the co... |
988,538 | 988,557 | Using CList in a multithreaded environment | I am using a CList in a multithreaded environment and I keep having problem with the GetHead method. I have one thread that add data to the list, and an other thread who read and remove data from the list.
Here is the reading part :
value_type get_next()
{
T t;
if(!queue.IsEmpty()) {
... | You have a race condition between inserting and retrieving the value. Add a lock that includes the entire body of get_next(), insert(), and pop_next().
|
988,588 | 988,613 | Is using unsigned integer overflow good practice? | I was reading the C Standard the other day, and noticed that unlike signed integer overflow (which is undefined), unsigned integer overflow is well defined. I've seen it used in a lot of code for maximums, etc. but given the voodoos about overflow, is this considered good programming practice? Is it in anyway insecure?... | Unsigned integer overflow (in the shape of wrap-around) is routinely taken advantage of in hashing functions, and has been since the year dot.
|
988,813 | 989,565 | App to read form document (scantron-ish) | I need to create form that will be filled in by hand and read digitally. I plan on using a sort of scantron-esque format with rows and columns that the user can just color in the a circle in the appropriate cell and the computer will know that value based on the xy position in the cell matrix. Like an excel address. ... | You want OMR (Optical Mark Recognition). Not sure what your budget is, but Abbyy is one of the leaders in this space:
If you want to try to roll your own, I wrote this article last month
http://www.codeproject.com/KB/showcase/SimpleOMRDotImage.aspx
It's based on the toolkit for the company I work for, but explains the ... |
988,848 | 988,862 | Predicting that the program will crash | I've been using Google Chrome for a while now and I noticed that it features very elegant crash control.
Just before crashing, google chrome gave a message saying "Woah! Google Chrome has crashed. Restart now?". And right after, I'd get a standard Windows XP "This program has encountered a problem and needs to close."... | Google Chrome uses a technique (often called process separation) where the 'host' UI manages child processes that it can detect becoming unresponsive (or worse, throwing an error and closing). It starts a new process for each tab you open.
Here's an article describing this in a bit more detail.
Using .net's Process cla... |
988,925 | 988,935 | How to overload a destructor? | How do I overload a destructor?
| You can't. There is only one destructor per class in C++.
What you can do is make a private destructor and then have several public methods which call the destructor in new and interesting ways.
class Foo {
~Foo() { ... }
public:
DestroyFoo(int) { ... };
DestroyFoo(std::string) { ... }
};
|
989,795 | 989,816 | Example for boost shared_mutex (multiple reads/one write)? | I have a multithreaded app that has to read some data often, and occasionally that data is updated. Right now a mutex keeps access to that data safe, but it's expensive because I would like multiple threads to be able to read simultaneously, and only lock them out when an update is needed (the updating thread could wai... | It looks like you would do something like this:
boost::shared_mutex _access;
void reader()
{
// get shared access
boost::shared_lock<boost::shared_mutex> lock(_access);
// now we have shared access
}
void writer()
{
// get upgradable access
boost::upgrade_lock<boost::shared_mutex> lock(_access);
// get e... |
989,817 | 1,589,894 | How can I make "real-time" plots with wxMathPlot? | I am thinking of using wxMathPlot for plotting/graphing some data that arrives continuously. I want to draw "Real-time" plot/graph using it. Is that possible?
I.E. I don't want just a static graph of a one-time read of a file - I want the streaming data plotted and continued out to the right of the graph - (and let ... | I think mpFXYVector is the way to go.
The simplest way to deal with this might be to write a wrapper class for mpFXYVector which holds a FIFO buffer of recent data points. Each time a new datapoint arrives, add it to the FIFO buffer, which will drop the oldest point, then load mpFXYVector with the updated buffer. The... |
989,848 | 989,869 | Is the linked list only of limited use? | I was having a nice look at my STL options today. Then I thought of something.
It seems a linked list (a std::list) is only of limited use. Namely, it only really seems
useful if
The sequential order of elements in my container matters, and
I need to erase or insert elements in the middle.
That is, if I just want a ... | Any sort of insertion/deletion is O(1). Even std::vector isn't O(1) for appends, it approaches O(1) because most of the time it is, but sometimes you are going to have to grow that array.
It's also very good at handling bulk insertion, deletion. If you have 1 million records and want to append 1 million records from ... |
989,867 | 989,914 | c++ set versus vector + heap operations for an A* priority queue | When is using a std::set more efficient (w.r.t. time) than using a std::vector along with make_heap/push_/pop_ for the priority queue in an A* operation? My guess is that if the vertices in the open list are small, using a vector is a better option. But does anyone have experience with this?
| If i had to venture a guess? I'd guess that the vector version is probably a good choice because once it grows to a certain size, there won't be very many allocs.
But I don't like guessing. I prefer hard numbers. Try both, profile!
|
989,892 | 989,902 | How to define preprocessor directives in VC++ 2008? | I'm using Visual C++ 2008 Express Edition. The WIN32 preprocessor directive doesn't appear to be defined by default, so when I surround includes with #ifndef WIN32, it still includes them.
I found someone with the exact same problem below, but it was so long ago that the location of this setting has changed:
http://www... | In VS 2008 Pro, you right-click on the project and select Properties. Then look for Preprocessor Definitions in Configuration Properties | C/C++ | Preprocessor.
|
989,980 | 990,161 | How do you handle command line options and config files? | What packages do you use to handle command line options, settings and config files?
I'm looking for something that reads user-defined options from the command line and/or from config files.
The options (settings) should be dividable into different groups, so that I can pass different (subsets of) options to different... | Well, you're not going to like my answer. I use boost::program_options. The interface takes some getting used to, but once you have it down, it's amazing. Just make sure to do boatloads of unit testing, because if you get the syntax wrong you will get runtime errors.
And, yes, I store them in a singleton object (read-o... |
990,505 | 990,608 | How to get count of next combinations for given set? |
I've edited original text to save potential readers some time and health. Maybe someone will actually use this.
I know it's basic stuff. Probably like very, very basic.
How to get all possible combinations of given set.
E.g.
string set = "abc";
I expect to get:
a b c aa ab ac aaa aab aac aba abb abc aca acb acc baa b... | Here's some C++ code that generates permutations of a power set up to a given length.
The function getPowPerms takes a set of characters (as a vector of strings) and a maximum length, and returns a vector of permuted strings:
#include <iostream>
using std::cout;
#include <string>
using std::string;
#include <vector>
... |
990,578 | 990,588 | expected asm or __attribute__ before CRenderContext | I am developing a small app under Linux using the CodeBlocks IDE.
I have defined a class with the following code:
class CRenderContext
{
public: /*instance methods*/
CRenderContext() :
m_iWidth(0), m_iHeight(0),
m_iX(0), m_iY(0),
m_bFullScreen(false), m_bShowPoint... | You are compiling it as C code, not C++. You probably need to rename the source file to have a .cpp extension. The code compiles perfectly (as C++) with g++ and comeau, although you have some superfluous semicolons. For example:
virtual ~CRenderContext () {};
No need for the semicolon ot the end there.
|
990,625 | 990,653 | C++ function pointer (class member) to non-static member function | class Foo {
public:
Foo() { do_something = &Foo::func_x; }
int (Foo::*do_something)(int); // function pointer to class member function
void setFunc(bool e) { do_something = e ? &Foo::func_x : &Foo::func_y; }
private:
int func_x(int m) { return m *= 5; }
int func_y(int n) { return n *= 6; }
};
... | The line you want is
return (f.*f.do_something)(5);
(That compiles -- I've tried it)
"*f.do_something" refers to the pointer itself --- "f" tells us where to get the do_something value from. But we still need to give an object that will be the this pointer when we call the function. That's why we need the "f." p... |
991,062 | 991,162 | Passing unnamed classes through functions | How do I pass this instance as a parameter into a function?
class
{
public:
void foo();
} bar;
Do I have to name the class?
It is copyable since I haven't made the class's copy ctor private.
So how is it possible if at all?
| Maybe it would be better if you explicit what you want to do. Why do you want to create an unnamed class? Does it conform to an interface? Unnamed classes are quite limited, they cannot be used as parameters to functions, they cannot be used as template type-parameters...
Now if you are implmenting an interface then yo... |
991,144 | 991,149 | What exactly do pointers store? (C++) | I know that pointers store the address of the value that they point to, but if you display the value of a pointer directly to the screen, you get a hexadecimal number. If the number is exactly what the pointer stores, then when saying
pA = pB; //both are pointers
you're copying the address. Then wouldn't there be a ... | A pointer is essentially just a number. It stores the address in RAM where the data is. The pointer itself is pretty small (probably the same size as an int on 32 bit architectures, long on 64 bit).
You are correct though that an int * would not save any space when working with ints. But that is not the point (no pun i... |
991,335 | 991,354 | How to erase & delete pointers to objects stored in a vector? | I have a vector that stores pointers to many objects instantiated dynamically, and I'm trying to iterate through the vector and remove certain elements (remove from vector and destroy object), but I'm having trouble. Here's what it looks like:
vector<Entity*> Entities;
/* Fill vector here */
vector<Entity*>... | You need to be careful because erase() will invalidate existing iterators. However, it will return a new valid iterator you can use:
for ( it = Entities.begin(); it != Entities.end(); ) {
if( (*it)->getXPos() > 1.5f ) {
delete * it;
it = Entities.erase(it);
}
else {
++it;
}
}
|
991,383 | 991,408 | Call a C++ function from C# | I have 2 C++ DLLs. One of them contains the following function:
void init(const unsigned char* initData, const unsigned char* key)
The other one contains this function:
BYTE* encrypt(BYTE *inOut, UINT inputSize, BYTE *secretKey, UINT secretKeySize).
Is there a way to call these 2 functions from C#? I know you can use... | Yes, you can call both of these from C# assuming that they are wrapped in extern "C" sections. I can't give you a detailed PInvoke signature because I don't have enough information on how the various parameters are related but the following will work.
[DllImport("yourdllName.dll")]
public static extern void init(IntP... |
991,496 | 991,512 | How to ignore certain socket requests | I'm currently working on a TCP socket server in C++; and I'm trying to figure out how I can ignore all browser connections made to my server. Any idea's?
Thanks.
| Need more details to give good feedback.
Are you going to be listening on port 80 but want to avoid all HTTP traffic? Or will your protocol be HTTP-based? Do you need to listen on 80 or can you pick any port?
If it's your own custom protocol (HTTP or not) you could just look at the first line sent up and if it's no... |
991,616 | 991,635 | telling when an execl() process exits | I've got a c++ application with certain items in a queue, those items then are going to be processed by a python script. I want it so that at maximum 10 instances of the python script are running. I plan on using execl() to launch the python process, Is there a way to tell that the process has quit without having to pa... | execl doesn't launch a process -- it overlays the existing process with another executable. fork does launch a process -- and returns the child process's id (aka pid) to the parent process (returns 0 to the child process, that's how the child knows it's the child so it can clean things up and exec). Use the children's ... |
991,640 | 991,911 | Where can I find, or how can I create an elegant C++ member function template wrapper mechanism without resporting to boost? | I want to be able to templatize a class on a member function without needing to repeat the arguments of the member function -- i e, derive them automatically.
I know how to do this if I name the class based on how many arguments the function takes, but I want to derive that as well.
Something like this, although this d... | I believe you'll need to take a traits approach, the most common library of which is boost's, but if you wanted to avoid boost, it wouldn't be extremely difficult to roll your own if you limited the scope of the implementation to just pointer-to-member-functions and the traits on those you need (modern c++ design is a ... |
991,671 | 991,747 | bitwise operator variations in C++ | I read C++ provides additional operators to the usual &,|, and ! which are "and","or" and "not" respectively, plus they come with automatic short circuiting properties where applicable.
I would like to use these operators in my code but the compiler interprets them as identifiers and throws an error.
I am using Visual ... | If you want to have the 'and', 'or', 'xor', etc keyword versions of the operators made available in MSVC++ then you either have to use the '/Za' option to disable extensions or you have to include iso646.h.
|
991,842 | 991,851 | How to link a static library in Visual C++ 2008? | My VC++ solution includes two projects, an application (exe) and a static library.
Both compile fine, but fail to link. I'm getting an "unresolved external symbol" error for each function from the static lib I use. They look like this:
MyApplication.obj : error LNK2019: unresolved external symbol "__declspec(dllimport)... | How are you setting it up to link? And what does your header file for MyApplication and MyStaticLibrary::accept look like?
If you have both projects in the same solution file, the best way to set it up to link is to right-click the Solution file->Properties and then set the library as a dependency of the application. ... |
991,878 | 991,884 | undefined reference within the same file | I'm getting an undefined reference to one private methods in a class. Here is a short snippet of the code (but the whole thing currently is in one source file and not separated into header and source files).
#include <iostream>
using namespace std;
struct node
{
int key_value;
node *left;
node *right;
};... | Your destroy_tree overload is not scoped to btree. The implementation is missing btree:: and is required since it is not inside the class definition:
void btree::destroy_tree(node * leaf)
{
if(leaf!=NULL)
{
destroy_tree(leaf->left);
destroy_tree(leaf->right);
delete leaf;
}
}
|
992,034 | 992,044 | How to make an "operator" variable? (C++) | I am working on making an expression class:
template<typename T, typename U>
class expression
{
public:
expression(T vala, U valb, oper o){val1 = vala; val2 = valb; op = o;}
operator bool{return(val1 op val2);}
private:
T val1;
U val2;
oper op;
};
as you can see, this is somewhat pseudocode, becaus... | Maybe a function pointer. Instead of ...
operator bool{return(val1 op val2);}
... code it as ...
operator bool{return op(val1, val2);}
... in which case op can be a pointer to a (any) function which takes two parameters and which returns bool.
template<typename T, typename U>
class expression
{
public:
//define p... |
992,069 | 992,335 | ACE vs Boost vs POCO | I have been working with the Boost C++ Libraries for quite some time. I absolutely love the Boost Asio C++ library for network programming. However I was introduced to two other libraries: POCO and Adaptive Communication Environment (ACE) framework. I would like to know the good and bad of each.
| As rdbound said, Boost has a "near STL" status. So if you don't need another library, stick to Boost. However, I use POCO because it has some advantages for my situation. The good things about POCO IMO:
Better thread library, especially a Active Method implementation. I also like the fact that you can set the thread p... |
992,176 | 992,219 | C++ tokenize a string using a regular expression | I'm trying to learn myself some C++ from scratch at the moment.
I'm well-versed in python, perl, javascript but have only encountered C++ briefly, in a
classroom setting in the past. Please excuse the naivete of my question.
I would like to split a string using a regular expression but have not had much luck findi... | The boost libraries are usually a good choice, in this case Boost.Regex. There even is an example for splitting a string into tokens that already does what you want. Basically it comes down to something like this:
boost::regex re("[\\sXY]+");
std::string s;
while (std::getline(std::cin, s)) {
boost::sregex_token_ite... |
992,209 | 992,283 | using a template class as an argument | Is there any way of creating a function that accepts any version of a given
template class?
e.g. this works:
ostream& operator << (ostream &out,const Vector<int>& vec);
but this doesn't:
ostream& operator << (ostream &out,const Vector& vec);
Is it possible to get the second line to work somehow for any version of ve... | As already pointed out something like this should work:
template <typename T>
ostream& operator << (ostream &out,const Vector<T>& vec) {
// body here
}
As for the friend requirement, that is most easily handled like this:
template <typename T>
ostream& operator << (ostream &out,const Vector<T>& vec) {
vec.prin... |
992,272 | 992,284 | operator () overload with template C++ | I have a simple class for which I want to overload operator as below
class MyClass
{
public:
int first;
template <typename T>
T operator () () const { return first; }
};
And the somewhere else I have
MyClass obj;
int i = obj(); // This gives me an error saying could not deduce
/... | If you wish the function call to be implicit then you'll have to apply the template to the class like this:
template <typename T>
class MyClass
{
public:
T first;
T operator () () const { return first; }
};
If it should be casted to another type then it should be:
template <typename T>
class MyClass
{
publi... |
992,320 | 992,361 | Can operators be used as functions? (C++) | This is similar to another question I've asked, but, I've created an expression class that works like so:
expression<int, int> exp(10, 11, GreaterThan);
//expression<typename T, typename U> exp(T val1, U val2, oper op);
//where oper is a pointer to bool function(T, U)
where GreaterThan is a previously defined function... | Instead of:
expression<int, int> exp(10, 11, >);
you could do this:
expression<int, int> exp(10, 11, operator>);
You could because it doesn't work for integers. But it will work for other types or operators that you will overload.
The operators that you overload are normal functions, so actually you are playing with ... |
992,435 | 992,445 | C++ basic constructors/vectors problem (1 constructor, 2 destructors) | Question is probably pretty basic, but can't find out what's wrong (and it leads to huge of memleaks in my app):
class MyClass {
public:
MyClass() { cout << "constructor();\n"; };
MyClass operator= (const MyClass& b){
cout << "operator=;\n"; return MyClass();
};
~MyClass() { cout << "destructo... | When the b object gets pushed onto the vector a copy is made, but not by the operator=() you have - the compiler generated copy constructor is used.
When the main() goes out of scope, the b object is destroyed and the copy in the vector is destroyed.
Add an explicit copy constructor to see this:
MyClass( MyClass const&... |
992,471 | 992,476 | how to query if(T==int) with template class | When I'm writing a function in a template class how can I find out what my T is?
e.g.
template <typename T>
ostream& operator << (ostream &out,Vector<T>& vec)
{
if (typename T == int)
}
How can I write the above if statement so it works?
| Something like this:
template< class T >
struct TypeIsInt
{
static const bool value = false;
};
template<>
struct TypeIsInt< int >
{
static const bool value = true;
};
template <typename T>
ostream& operator << (ostream &out,Vector<T>& vec)
{
if (TypeIsInt< T >::value)
// ...
}
|
992,661 | 992,917 | using checkTokenMemberShip return always true even if the process user is not administrator | the following is the code I'm using (copied from msdn) but even when the the pocess user is not a local admin it returns as if it is any ideas?
BOOL IsUserAdmin(VOID)
/*++
Routine Description: This routine returns TRUE if the caller's
process is a member of the Administrators local group. Caller is NOT
expected to be ... | In the MSDN doc here... There is a note mentioning issues when using this on VISTA (or later).
To paraphrase, if you're using this on Vista - the API will return true - because of the way Vista uses a split token for security.
Here is the original note (originally written by tchao):
When UAC is enabled in Windows
... |
992,717 | 992,780 | Error C2228 when constructing boost::function object in constructor argument list | The code below does not compile in Visual C++ 2005.
class SomeClass {
public: boost::function<void()> func;
SomeClass(boost::function<void()> &func): func(func) { }
};
void someFunc() {
std::cout << "someFunc" << std::endl;
}
int main() {
SomeClass sc(boost::function<void()>(&someFunc));
sc.func()... | It's a function declaration for a function taking a reference to a boost:function <void()> and returning a SomeClass. You can memorize the following rule, which turns out to apply to many other such disambiguation cases. You can find descriptions of these cases in section 8.2 of the C++ Standard.
Any construct that c... |
992,760 | 992,779 | Write to registry in Windows Vista | I am trying to write to the registry from my application, but when I do I get access denied. Of course, it works if i run the app as Administrator. However, with my applcation, it is not initiated by the user. It start automatically.
So, the question is, how do i read/write to my own registry key from the C++ app?
T... | Write to HKEY_CURRENT_USER
And check out this posts
Vista + VB.NET - Access Denied while writing to HKEY_LOCAL_MACHINE
Writing string (REG_SZ) values to the registry in C++
How to read registry branch HKEY_LOCAL_MACHINE in Vista?
|
992,836 | 992,876 | How to access the Java method in a C++ application | Just a simple question:
Is it possible to call a java function from c/c++ ?
| Yes you can, but it is a little convoluted, and works in a reflective/non type safe way (example uses the C++ api which is a little cleaner than the C version). In this case it creates an instance of the Java VM from within the C code. If your native code is first being called from Java then there is no need to const... |
992,919 | 993,797 | How to set up Win32 tooltips control with dynamic unicode text? | I am having some trouble provding a Win32 tooltips control with dynamic text in unicode format. I use the following code to set up the control:
INITCOMMONCONTROLSEX icc;
icc.dwSize = sizeof(INITCOMMONCONTROLSEX);
icc.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&icc);
HWND hwnd_tip = CreateWindowExW(0, TOOLTIPS_CLA... | Thanks for the Robert Scott link. I found a way to solve it now.
In short, the trick was to make sure the receiving window was a unicode window and register a unicode window procedure for it.
The problem was that I did not have a unicode WindowProc() for my parent window handling the TTN_GETDISPINFOW notification messa... |
992,924 | 992,933 | importance of freeing memory? |
Possible Duplicate:
What REALLY happens when you don’t free after malloc?
When ending a program in C/C++, you have to clean up by freeing pointers. What happens if you doesn't free the memory, like if you have a pointer to an int and doesn't delete it when ending the program? Is the memory still used and can only be... | When your program ends all of the memory will be freed by the operating system.
The reason you should free it yourself is that memory is a finite resource within your running program. Sure in very short running simple programs, failing to free memory won't have a noticable effect. However on long running programs, ... |
993,076 | 993,351 | working with fstream files in overflow chaining in c++ | I have a file that I want to read and write to a binary file using records. In the beginning I have an empty file and I want to add new record, but when I use the seekp function, then the location is at (-1) is it ok? Because when I check, I see that it hasnt written anything to the file. See code:
void Library::addBo... | Well here are a few suggestions that may help:
when you open the file, use ios_base::binary flag
make sure that Book is a POD (i.e. a C compatible type)
make sure that when you read or write that the stream is in a valid state before and after
don't use readBook.getId() == -1 to check if the read succeeded
mak... |
993,262 | 993,402 | How does the C++ runtime determine the type of a thrown exception? | If I do the following, how does the runtime determine the type of the thrown exception? Does it use RTTI for that?
try
{
dostuff(); // throws something
}
catch(int e)
{
// ..
}
catch (const char * e)
{
// ..
}
catch (const myexceptiontype * e)
{
// ..
}
catch (myexceptiontype e) // is this the same as the previ... | Unlike the concerns asked in that other questions, the answer to this question can be answered entirely by means of the Standard. Here are the rules
A handler is a match for an exception object of type E if
The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or
t... |
993,352 | 993,385 | When should I make explicit use of the `this` pointer? | When should I explicitly write this->member in a method of
a class?
| Usually, you do not have to, this-> is implied.
Sometimes, there is a name ambiguity, where it can be used to disambiguate class members and local variables. However, here is a completely different case where this-> is explicitly required.
Consider the following code:
template<class T>
struct A {
T i;
};
template<c... |
993,505 | 993,513 | Where to put the enum in a cpp program? | I have a program that uses enum types.
enum Type{a,b,};
class A
{
//use Type
};
class B
{
// also use that Type
};
2 class are located in 2 different files.
Should I put the type definition in a headfile or
in class definition for each class?
| If the enum is going to be used in more than one .cpp file, you should put it in a header file that will be included by each. If there's a common header file, you should use that, otherwise you may as well create a new header file for this enum
|
993,590 | 993,605 | Should I delete vector<string>? | I've painfully learned during last few days a lot about programming in c++.
I love it :)
I know I should release memory - the golden "each malloc=free" or "each new=delete" rules exist now in my world, but I'm using them to rather simple objects.
What about vector ? Wherever I can, I'm using vector.clear() but that cle... | The rule is that when you clear a vector of objects, the destructor of each element will be called. On the other hand, if you have a vector of pointers, vector::clear() will not call delete on them, and you have to delete them yourself.
So if all you have is a vector of strings, and not pointers to strings, then your ... |
993,630 | 993,636 | How can I configure my project to generate platform independent code? | I am writing an application that I would like to release binaries for on Mac, Windows, and Linux. I have code that compiles under Mac and Linux, but under Windows, it does not.
This is because of Windows lack of a strcasecmp. I've read a little bit about how I can create some sort of header to wrap my code, but I don't... | You could do
#ifdef WIN32
#include <windows_specific_header.h>
#else
#include <other_header.h>
There is also an MS Visual Studio-specific macro: _MSC_VER, so
#ifdef _MSC_VER
would also work here.
There is also WINVER define in windows.h.
|
993,777 | 994,241 | Cross-platform transparent windows in C++? | I'm wondering how to make a window transparent, not cutout holes or the same transparency overall.
Well, just say I want to slap a PNG image of a rose or something and have it blend nicely with stuff behind and allow stuff behind to redraw and have their changes shine through the transparent parts of the picture/window... | I found out that it's actually pretty simple to throw up a transparent picture on the screen using wxW:
wxScreenDC dc;
wxBitmap bmp(wxT("test.png"), wxBITMAP_TYPE_PNG);
dc.DrawBitmap(bmp, 250, 100, true);
Now I has to find out how to handle updates and such, it has to be ( maybe partially redrawn ) when something ben... |
993,922 | 994,026 | Weird striping in tile graphics on Nintendo DS | I'm working on a pong game for the Nintendo DS. I'm using libnds to set things up and I've come across a very strange behaviour. So far I've only tried it out in emulators, but I use three different ones and they all exhibit this behaviour so I suspect I'm doing something bad.
The actual problem is that when I use back... | a breif look at background.h makes it look like you are using BG1 and BG2. For mode 5, according to:
http://nocash.emubase.de/gbatek.htm
layer 0 and 1 are normal and 2 and 3 are extended. I dont know what extended means. If you want to just do normal tile stuff you probably want to bgInit 0 and 1 not 1 and 2.
You ca... |
994,139 | 994,186 | Advice on wrapping third party libraries | I have been working a year now as a software developer for a at the computer-vision department of a company. My main job is integration of third-party software into a framework, so i usually end up writing wrapper libraries because a lot of this third party software does not work the way we want it to work(not thread s... | I will quote an answer to another question on here the other day:
Does your current method pass testing?
Is it fast enough?
If yes, keep doing what you are doing.
As an alternative
Just ensure your new API encompasses both the intended functionality and the conventional or accidental functionality of the original. A... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.