question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,402,522 | 1,402,554 | shared_ptr and references in C++ | References in C++ are a conveneint construct that allow us to simplify the following C code:
f(object *p){
//do something
}
int main(){
object* p = (object*) calloc(sizeof(object));
f(p);
}
to
f(object& o){
//do something
}
int main(){
object o = object();
f(o);
}
Shared pointers are another convenienc... | Take a shared_ptr by value, and the reference count will increase. This is easier when you typedef it:
typedef boost:shared_ptr<object> object_ptr;
void foo(object_ptr obj)
{
obj->/* stuff*/;
obj.reset(); //only resets this local copy, that means:
// reduce reference count (back to 1), and
... |
1,402,948 | 1,402,973 | which is the most efficient XML Parser for C++? | I need to write an application that fetches element name value (time-series data) pair from any xml source, be it file, web server, any other server. the application would consume the XML and take out values of interest, it has to be very very fast (lets say 50000 events/seconds or more) also the XML document size woul... | If you use SAX parsing, your bottleneck is the I/O involved, not the XML string processing. And given your 500 MB number, I'd say you'd have to do SAX parsing instead of DOM parsing. So, anything with a SAX type interface should be just fine.
|
1,403,150 | 1,403,157 | How do you dynamically allocate a matrix? | How do you dynamically allocate a 2D matrix in C++?
I have tried based on what I already know:
#include <iostream>
int main(){
int rows;
int cols;
int * arr;
arr = new int[rows][cols];
}
It works for one parameter, but now for two. What should I do?
| A matrix is actually can be represented as an array of arrays.
int rows = ..., cols = ...;
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
Of course, to delete the matrix, you should do the following:
for (int i = 0; i < rows; ++i)
delete [] matrix[i];
delete [] matrix;... |
1,403,251 | 1,405,366 | Unicode Input Handling in Games | I have a game that requires me to allow players to chat with each other via network. All is well, except the part where players can type in Unicode input.
So, the question can be split into two parts:
When players type, how do I capture input? I have done this before via the game input handling (polling), however, it ... | For Input
Use SDL_EnableUNICODE to enable unicode input handling
Receive the SDL_KeyboardEvent as usual
Use the unicode member of SDL_keysym to get the unicode
For Rendering
If the needed font size is reasonably small, say 16px, you actually could just render it all to a single texture, you can fit a minimum of 4096... |
1,403,410 | 1,403,576 | How to solve the problem of global access? | I'm building an app, and I need the wisdom of the SO community on a design issue.
In my application, there needs to be EXACTLY one instance of the class UiConnectionList, UiReader and UiNotifier.
Now, I have figured two ways to do this:
Method 1:
Each file has a global instance of that class in the header file itself.
... | With your usage in globals.h you are going to have a multiple definition of Globals::UiConnectionList and Globals::UiNotifier for each compilation unit (.cc or .cpp file) that you use. This is not the way to make exactly one instance of those clases. You should use the singleton pattern as previous posters suggested.
I... |
1,403,465 | 1,403,512 | What is boost's shared_ptr(shared_ptr<Y> const & r, T * p) used for? | boost::shared_ptr has an unusual constructor
template<class Y> shared_ptr(shared_ptr<Y> const & r, T * p);
and I am a little puzzled as to what this would be useful for. Basically it shares ownership with r, but .get() will return p. not r.get()!
This means you can do something like this:
int main() {
boost::share... | It is useful when you want to share a class member and an instance of the class is already a shared_ptr, like the following:
struct A
{
int *B; // managed inside A
};
shared_ptr<A> a( new A );
shared_ptr<int> b( a, a->B );
they share the use count and stuff. It is optimization for memory usage.
|
1,403,501 | 1,403,546 | STL map onto itself? | I'd like to create a std::map that contains a std::vector of iterators into itself, to implement a simple adjacency list-based graph structure.
However, the type declaration has me stumped: it would seem you need the entire map type definition to get the iterator type of said map, like so:
map< int, Something >::iter... | You could use forward declaration of a new type.
class MapItContainers;
typedef map<int, MapItContainers>::iterator MyMap_it;
class MapItContainers
{
public:
vector<MyMap_it> vec;
};
With this indirection the compiler should let you get away with it.
It is not so very pretty but honestly I don't think you can break ... |
1,403,517 | 1,403,545 | C++ Stack Implementation | Hey all! Having a little trouble with my stack. Im trying to print each element that I've pushed onto the stack.
Starting with the stack ctor we know that we have a fixed size for the array. So I allocate the items struct object to hold just that much space:
stack::stack(int capacity)
{
items = new item[capacity];... | In the overloaded << operator in the for loop you are iterating maxsize times. But you might not have pushed maxsize elements into the stack. You should iterate top times. Also, write a default constructor for item structure and initialize all the variblaes so that you do not get garbage values when you try to print th... |
1,403,873 | 1,403,908 | Rundll32 load order problem | My product consists of two dlls (A.dll and B.dll for clarity), A.dll depends on B.dll. Both A and B dlls are in the same folder (say c:\app). At the same time old version of B.dll is in Windows\System32 folder. When I try to run following command from command prompt (current folder is c:\app):
rundll32.exe "c:\app\A.dl... | DLL Hell on SO
Well, it's kind of cool in a retro sort of way. Here is a thought: try copying rundll32.exe into the same folder as the new dll's and your product, and run it from there. It might work...
|
1,404,189 | 1,405,412 | How to read/redirect output of a dos command to a program variable in C/C++? | I want to run a dos command from my program for example "dir" command.
I am doing it like,
system("dir");
Is there any way to read the output of that command directly into a program variable?
We can always redirect the output to a file and then read that file, by doing
system("dir > command.out");
And then reading ... | Found an alternate way or rather windows equivalent of popen. It is _popen(). This works just right for me and moreover it's easy to use.
char psBuffer[128];
FILE *pPipe;
if( (pPipe = _popen( "dir", "rt" )) != NULL)
{
while(fgets(psBuffer, 128, pPipe))
{
printf(psBuffer);
}
}
Fi... |
1,404,305 | 1,404,333 | C++ reference in constructor | I have a class whose constructor takes a const reference to a string. This string acts as the name of the object and therefore is needed throughout the lifetime of an instance of the class.
Now imagine how one could use this class:
class myclass {
public:
myclass(const std::string& _name) : name(_name) {}
private:
... | Yes, Reference becomes invalid in your case. Since you are using the string it is better to keep a copy of the string object in myclass class.
|
1,404,394 | 1,404,473 | g++ external reference error | I have issue that is reproduced on g++. VC++ doesn't meet any problems.
So I have 2 cpp files:
1.cpp:
#include <string>
#include <iostream>
extern const std::string QWERTY;
int main()
{
std::cout << QWERTY.c_str() << std::endl;
}
2.cpp:
#include <string>
const std::string QWERTY("qwerty");
No magic, I just wan... | It looks like you are probably running into this bit of the standard:
In C, a const-qualified object at file
scope without an explicit storage
class specifier has external linkage.
In C++, it has internal linkage.
Make this change to 2.cpp:
#include <string>
extern const std::string QWERTY("qwerty");
There is... |
1,404,638 | 1,404,710 | During which phase of building a binary is activation record defined? | Is it during a pre-processing or compilation stage, say on gcc? Is it different on other compilers?
| The stack frame is created at runtime by modifying the stack register of the processor (esp for Intel x86).
The compiler only dump specific instructions to reserve space on the stack at each function call. This space is then recovered when the function exits.
|
1,404,717 | 1,412,936 | Thread safe C++ std::set that supports add, remove and iterators from multple threads | I'm looking for something similar to the CopyOnWriteSet in Java, a set that supports add, remove and some type of iterators from multiple threads.
| there isn't one that I know of, the closest is in thread building blocks which has concurrent_unordered_map
The STL containers allow concurrent read access from multiple threads as long as you don't aren't doing concurrent modification. Often it isn't necessary to iterate while adding / removing.
The guidance about pr... |
1,404,797 | 1,404,843 | In C++, is a function automatically virtual if it overrides a virtual function? | I would expect that if foo is declared in class D, but not marked virtual, then the following code would call the implementation of foo in D (regardless of the dynamic type of d).
D& d = ...;
d.foo();
However, in the following program, that is not the case. Can anyone explain this? Is a method automatically virtual if... | Standard 10.3.2 (class.virtual) says:
If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared... |
1,404,885 | 1,405,327 | Is mysql_close required on connection failure? | I have a code snippet which connects to a MySQL database like this (not directly from code so there might be typos):
m_connectionHandler = mysql_init(NULL);
if (m_connectionHandler == NULL)
{
// MySQL initialization failed
return;
}
MYSQL *tmp = mysql_real_connect(m_connectionHandler,
... | Your call to mysql_init(NULL) allocates memory. Regardless of whether you're able to really connect to the server, you've still allocated memory, so you need to free it with mysql_close, which not only closes connections but also releases memory. I see no indication in the documentation that mysql_real_connect would fr... |
1,404,942 | 1,404,960 | How to optimize the layers of pointer indirection | I am trying to optimize this sort of things in a heavy computing application:
say I have a
double d[500][500][500][500];
and the following is quite costly at least from compiler perspective
double d[x][y][j][k]
I want to tell compiler is that it's contiguous memory, to facilitate computing the offset.
In my exampl... | I suspect that the problem is not the offset calculation but the actual access to memory. When you declare a 4-dimensional array and access elements with adjacent indices at any level except the last one memory addresses are actually quite far from each other and this leads to lots of cache misses and significant slowd... |
1,405,091 | 1,405,359 | Handling relations between multiple subversion projects | In my company we are using one SVN repository to hold our C++ code. The code base is composed from a common part (infrastructure and applications), and client projects (developed as plugins).
The repository layout looks like this:
Infrastructure
App1
App2
App3
project-for-client-1
App1-plugin
App2-plugin
Configurati... | You could handle this with svn:externals. This is the url to a spot in an svn repo
This lets you pull in parts of a different repository (or the same one). One way to use this is under project-for-client2, you add an svn:externals link to the branch of infrastructure you need, the branch of app1 you need, etc. So whe... |
1,405,132 | 1,405,214 | UNIX/OSX version of semtimedop | GLibC has a method semtimedop which allows you to perform an operation (a semaphore acquire in this case) which times out after a certain amount of time. Win32 also provides WaitForSingleObject which provides similar functionalty.
As far as I can see there is no equivalent on OSX or other Unices. Can you suggest either... | You can break out of a semop() call (and most other blocking calls) by getting a signal, such as one caused by alarm().
untested example:
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
volatile int alarm_triggered = 0;
void alarm_handler(int sig)
{
alarm_tri... |
1,405,205 | 1,405,285 | How could this manner of writing code be called? | I'm reviewing a quite old project and see code like this for the second time already (C++ - like pseudocode):
if( conditionA && conditionB ) {
actionA();
actionB();
} else {
if( conditionA ) {
actionA();
}
if( conditionB ) {
actionB();
}
}
in this code conditionA evaluates to the same res... | I would call it 'twice is better'. It's made like that to be sure that the runtime really understood the question ;).
(although in multi-threaded, not-safe environment, the result may differ between the two variants.)
|
1,405,502 | 1,405,605 | How to handle NAT traversal in c++ peer to peer application ( please code examples not theory ) | I need to develop simple game that will be using peer to peer connection using centralize index manager server.
I know there is a problem when a client is trying to connect to another client that is behind a router. I was reading about NAT traversal that explains using mainly theory, but what I would really like to see... | NAT traversal is not that simple to get right.
STUN might help: http://en.wikipedia.org/wiki/STUN
|
1,405,766 | 1,405,816 | Can I make make a HALT_ONCE macro? | I'm trying to figure out a transparent solution for debug halts that repeatedly get hit in my game.
For a trivial example; say I have a halt in my renderer that tells me when I'm trying to use a NULL material. My renderer handles this fine but I still want to know what I'm doing wrong.
This halt will hit every frame no... | anything wrong with this?
#define HALT_ONCE(err_msg) \
do { \
static bool hitOnce = false; \
if (!hitOnce) { \
hitOnce = true; \
printf(err_msg); \
__asm { int 3 }; \
} \
} while(0)
Then you can just do this in your code:
HALT_ONCE("its all gone wrong!");
The do/while creates its o... |
1,405,911 | 1,406,049 | Initializing and assigning values,from pass by reference | Okay, this is just a minor caveat. I am currently working with the lovely ArcSDK from ESRI. Now to get a value from any of their functions, you basically have to pass the variable, you want to assign the value to.
E.g.:
long output_width;
IRasterProps->get_Width(&output_width);
Its such a minor thing, but when you hav... | I know I've already answered, but here's another way. It's better in that it's faster (no boost::function overhead) and avoids the binders (since people seem to have an aversion to them), but is worse in that it's much less general (since it only works for one-argument member functions).
template <typename P, typename... |
1,406,635 | 1,406,647 | parsing proc/pid/cmdline to get function parameters | I'm trying to extract the parameter with which an app was called by using the data inside cmdline.
If I start an application instance like this:
myapp 1 2
and then cat the cmdline of myapp I will see something like myapp12.
I needed to extract these values and I used this piece of code to do it
pid_t proc_id = getpi... | All of the command line parameters (what would come through as the argv[] array) are actually null-separated strings in /proc/XXX/cmdline.
abatkin@penguin:~> hexdump -C /proc/28460/cmdline
00000000 70 65 72 6c 00 2d 65 00 31 20 77 68 69 6c 65 20 |perl.-e.1 while |
00000010 74 72 75 65 00 ... |
1,406,643 | 1,406,664 | retval = false && someFunction(); // Does someFunction() get called? | I'm currently working with the Diab 4.4 C++ compiler. It's a total POS, non ANSI-compliant, and I've found problems with it in the past.
I'm wondering if the following problem is an issue with the compiler, or a shortcoming in my knowledge of C++
I realize that the form of x = x && y; will short-circuit the y part if x... | The && and || operators are defined to evaluate lazily, this is the way the language works. If you want the side effects to always happen, invoke the function first and stash the result, or refactor the function to split the work from the state query.
|
1,406,649 | 1,406,703 | Wanted: Elegant solution to race condition | I have the following code:
class TimeOutException
{};
template <typename T>
class MultiThreadedBuffer
{
public:
MultiThreadedBuffer()
{
InitializeCriticalSection(&m_csBuffer);
m_evtDataAvail = CreateEvent(NULL, TRUE, FALSE, NULL);
}
~MultiThreadedBuffer()
{
CloseHandle(m_evt... | You need to create a auto-reset event instead of a manual reset event. This guarantees that if multiple threads are waiting on an event, and when the event is set only one thread will be released. All other threads will remain in waiting state. You can create auto-reset event by passing FALSE to the second parameter of... |
1,406,941 | 1,406,950 | Question about "using" keyword | I'm well aware of using namespaces however, every now and then I'm stumbling upon a using, which uses a specific class. For instance :
#include <string>
using namespace std;
(...)
However - every now and then, I'm seeing :
using std::string;
How should I interpret the "using" in this case ?
Cheers
| using std::string simply imports std::string into the current scope (aka, you can just use 'string' rather than 'std::string') without importing everything from ::std into the current scope.
edit: clarification after comment.
|
1,406,995 | 1,407,225 | Using STL/Boost to find and modify matching elements in a vector | Let's say I have a vector declared like this:
struct MYSTRUCT
{
float a;
float b;
};
std::vector<MYSTRUCT> v;
Now, I want to find all elements of v that share the same a, and average their b, i.e.
Say v contains these five elements {a, b}: {1, 1}, {1, 2}, {2, 1}, {1, 3}, {2, 2}
I want to get v[0], v[1], v[3] (where... | Just thinking aloud, this may end up fairly silly:
struct Average {
Average() : total(0), count(0) {}
operator float() const { return total / count; }
Average &operator+=(float f) {
total += f;
++count;
}
float total;
int count;
};
struct Counter {
Counter (std::map<int, Ave... |
1,407,023 | 1,407,077 | Progress indication with HTTP file download using WinHTTP | I want to implement an progress bar in my C++ windows application when downloading a file using WinHTTP. Any idea how to do this? It looks as though the WinHttpSetStatusCallback is what I want to use, but I don't see what notification to look for... or how to get the "percent downloaded"...
Help!
Thanks!
| Per the docs:
WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
Data is available to be retrieved with
WinHttpReadData. The
lpvStatusInformation parameter points
to a DWORD that contains the number of
bytes of data available. The
dwStatusInformationLength parameter
itself is 4 (the size of a DWORD).
and
WINHTTP_CALL... |
1,407,081 | 1,408,503 | Converting a C# class library to C++ on Red Hat Linux | We have developed a C# class library on VS 2008. We want the same functionality as a C++ library on Red Hat Linux. How do we accomplish that?
I am sure we are not the first to migrate C# to C++. Are there any automated tools to convert the source code?
We know about Mono, but we would very much prefer C++ source code.
... | You can get a head start by first converting to C++/CLI (the .NET flavor of C++). Red Gate's .NET Reflector supports conversions between .NET languages (you need a plugin to decompile to C++/CLI) and there are other tools as well.
|
1,407,197 | 1,407,206 | Using binary flags to represent states, options, etc | If I wanted to represent states or options or something similar using binary "flags" so that I could pass them and store them to an object like OPTION1 | OPTION2 where OPTION1 is 0001 and OPTION2 is 0010, so that what gets passed is 0011, representing a mix of the options.
How would I do this in C++? I was thinking som... | This is a common way these things are done. doSomething can use bitwise and operator to see if an option is selected:
if (options & Option_1){
// option 1 is selected
}
Alternatively, you can consider using bit fields:
struct Options {
unsigned char Option_1 : 1;
unsigned char Option_2 : 1;
};
Options o;
o... |
1,407,354 | 1,949,894 | Is there a C++ unit testing library that is similar to NUnit? | We need to migrate a unit test harness developed with C# and NUnit to C++ running on Red Hat Linux.
We want to minimize the efforts in migration.
We are reading resources such as this:
http://gamesfromwithin.com/exploring-the-c-unit-testing-framework-jungle
But we don't see anything similar to NUnit.
| Expanding on Mark Bessey's answer: I really like cxxTest because it's just a set of C++ header files & Perl scripts. As long as you have a C++ compiler & Perl, it will work on nearly any system. It also has features to integrate with your IDE (although I haven't used them).
Also, here's a good article Exploring the ... |
1,407,996 | 1,408,110 | Send a key to another Windows application with C++ | I'm sort of new to c++. I'm trying to send a key to another application, which I know the HWND of. I was thinking of doing ::SendMessage but I'm not sure what parameters to use. I'm trying to send the space key. Thanks.
| SendInput might be what you want.
|
1,408,056 | 1,408,077 | Should I write one method to convert distances or a bunch of methods? | I'm just learning C++ and programming. I'm creating a class called Distance. I want to allow the user (programmer using), my class the ability to convert distances from one unit of measure to another. For example: inches -> centimeters, miles -> kilometers, etc...
My problem is that I want to have one method called Con... | Break it up into functions. What you have there is going to be very difficult to maintain and to use. It would be more convenient to the user and the programmer to have functions with descriptive names like:
double inchesToCentimeters(double inches);
double centimetersToInches(double cent);
The function names tell y... |
1,408,361 | 1,408,370 | Unsigned Integer to BCD conversion? | I know you can use this table to convert decimal to BCD:
0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
Is there a equation for this conversion or you have to just use the table? Im trying to write some code for this conversion but Im not sure how to do the math for it. Sugg... | You know the Binary numeral system, don't you?
Especially have a look at this chapter.
EDIT: Also note KFro's comment that the lower nibble (= 4 bits) of the binary ASCII representation of numerals is in BCD. This makes conversions BCD <-> ASCII very easy as you just have to add/remove the leading 4 bits:
Number AS... |
1,408,513 | 1,408,540 | "LNK1104: cannot open file 'X'": How to find out who wants X linked in? | Okay, I'm stumped. I'm fiddling with some project settings, trying to start linking against library Y instead of library X. When I search through the project file (.vcproj) and all the inherited property sheets (.vsprops), there are no references left to library X. I've closed and reopened Visual Studio to make sure i... | Under project settings / linker / general there's a setting called "show progress", if you set it to "/VERBOSE" the linker will show you all kinds of stuff including the "/DEFAULTLIB" items it finds. This can be helpful, depending on whether the import is coming from a lib file, or not.
You should also search your sol... |
1,408,600 | 1,408,608 | delete [] char *, memory issues | I have a global pointer variable
char* pointer = new char[500];
/* some operations... */
there is a seperate FreeGlobal() function that does free up the pointer as below:
delete[] pointer;
First time when the function is called, it actually frees up the memory and now the pointer is a bad pointer. But when we call th... | Set pointer to null after you delete it. You should not try to delete the same data more than once.
As mentioned by GRB in the comments for this post, it is perfectly safe to call delete[] NULL.
|
1,408,651 | 1,408,892 | Is optimizing certain functions with Assembler in a C/C++ program really worth it? | In certain areas of development such as game development, real time systems, etc., it is important to have a fast and optimized program. On the other side, modern compilers do a lot of optimization already and optimizing in Assembly can be time consuming in a world where deadlines are a factor to take into consideratio... | I'd say it's not worth it. I work on software that does real-time 3D rendering (i.e., rendering without assistance from a GPU). I do make extensive use of SSE compiler intrinsics -- lots of ugly code filled with __mm_add_ps() and friends -- but I haven't needed to recode a function in assembly in a very long time.
My... |
1,408,695 | 1,408,915 | B+ tree implementation, * * vs * | I am writing a B+ tree for a variety of reasons and I am come here to ask a question about implementation of its nodes. My nodes currently look like:
struct BPlusNode
{
public:
//holds the list of keys
keyType **keys;
//stores the number of slots used
size_t size;
//holds the array of pointers to lo... | I would define another struct for the key and pointer data. I would commit to using fixed size nodes which should match your on-disk structure. This makes memory mapping the tree a lot easier.
Your BPlusNode struct becomes a handle class that points to these mapped data nodes and synthesizes the things like prev and ne... |
1,408,823 | 1,408,834 | int and string parsing | If i have a int say 306. What is the best way to separate the numbers 3 0 6, so I can use them individually? I was thinking converting the int to a string then parsing it?
int num;
stringstream new_num;
new_num << num;
Im not sure how to do parse the string though. Suggestions?
| Without using strings, you can work backwards. To get the 6,
It's simply 306 % 10
Then divide by 10
Go back to 1 to get the next digit.
This will print each digit backwards:
while (num > 0) {
cout << (num % 10) << endl;
num /= 10;
}
|
1,408,866 | 1,408,946 | C++ dynamically allocated array of statically dimensioned arrays | I need to create a structure that holds a variable number of 'char[2]'s, i.e. static arrays of 2 chars.
My question is, how do I allocate memory for x number of char[2].
I tried this (assuming int x is defined):
char** m = NULL;
m = new char[x][2];
...
delete [] m;
(it didn't work)
I realise I could use std::vector<ch... | In your code, the type of 'm' doesn't match your 'new' call. What you want is:
char (*m)[2] = NULL;
m = new char[x][2];
...
delete [] m;
m is a pointer to arrays of 2 chars, and you call new to get an array of x arrays of 2 chars and point m at the first one.
|
1,408,908 | 1,408,916 | Looking for a free source code analyzer (Function depedency tree) | Does anybody know where I can find a utility/application running on Windows that analyses C source and outputs a functional dependency tree?
What I'm looking for is something along these lines:
PrintString->PrintCharacter->PrintByte->Printf
| It's almost certainly overkill, but you can do this for C, C++, PHP, Java, C#, and more with Doxygen (if you have Graphviz dot installed). Here's a page with a sample call tree generated by Doxygen/dot.
Doxygen runs on Windows fine, and can output HTML and a few other formats.
|
1,409,006 | 1,413,714 | State Machine Implementation | I'm looking for some general
Optimization
Correctness
Extensibility
advice on my current C++ Hierarchical State Machine implementation.
Sample
variable isMicOn = false
variable areSpeakersOn = false
variable stream = false
state recording
{
//override block for state recording
isMicOn = true //here, ... | Two things:
1: For most cases just represent the state of your program as a Model, and interact with it directly or through the MVC pattern.
2: If you really need a FSM, i.e. you want to randomly make a bunch of actions to your model, only some of which are allowed at certain times. Then....
Still keep the state of you... |
1,409,305 | 1,409,319 | Best Practices: Should I create a typedef for byte in C or C++? | Do you prefer to see something like t_byte* (with typedef unsigned char t_byte) or unsigned char* in code?
I'm leaning towards t_byte in my own libraries, but have never worked on a large project where this approach was taken, and am wondering about pitfalls.
| If you're using C99 or newer, you should use stdint.h for this. uint8_t, in this case.
C++ didn't get this header until C++11, calling it cstdint. Old versions of Visual C++ didn't let you use C99's stdint.h in C++ code, but pretty much every other C++98 compiler did, so you may have that option even when using old co... |
1,409,395 | 1,409,406 | Creating Property grid in MFC | I want to create a property grid (the one which is similar to the one used in the resource editor in VS) using MFC. Does anybody whether there is any built in support in MFC for this?
| You need VS2008 and the feature pack, it's called CMFCPropertyGridCtrl
|
1,409,454 | 1,409,465 | c++ map find() to possibly insert(): how to optimize operations? | I'm using the STL map data structure, and at the moment my code first invokes find(): if the key was not previously in the map, it calls insert() it, otherwise it does nothing.
map<Foo*, string>::iterator it;
it = my_map.find(foo_obj); // 1st lookup
if(it == my_map.end()){
my_map[foo_obj] = "some value"; // 2nd l... | Normally if you do a find and maybe an insert, then you want to keep (and retrieve) the old value if it already existed. If you just want to overwrite any old value, map[foo_obj]="some value" will do that.
Here's how you get the old value, or insert a new one if it didn't exist, with one map lookup:
typedef std::map<F... |
1,409,562 | 1,409,943 | Assigning Unique Numerical Identifiers to Instances of a Templated Class | Core problem:
I want to be able to take an instance of a templated class, say:
template<class a, class b, class c> class foo;
foo<int, float, double>;
and then do something like:
foo<int, float, double>::value; //Evaluates to a unique number
foo<long, float, double>::value; //Evaluates to a different unique number
f... | If you want to put things in a map, and need a per-type key, the proper solution is to use std::type_info::before(). It may be worthwhile to derive a class so you can provide operator<, alternatively wrap std::type_info::before() in a binary predicate.
|
1,409,597 | 1,409,695 | Shared Memory Semaphore | I have 10 processes running, each writing to the same file. I don't want multiple writers, so basically I am looking for a mutex/binary semaphore to protect file writes. The problem is I can't share the semaphore amongst 10 processes, so I am looking at using shared memory between 10 processes, and putting the semaphor... | It sounds like you'd be better off using flock(2):
flock(fd, LOCK_EX);
n = write(fd, buf, count);
flock(fd, LOCK_UN);
|
1,409,701 | 1,409,710 | Pattern for fast copy in C | I once saw a programming pattern (not design), how to implement a fast copy of buffers. It included an interleaved loop and switch. The thing was, it copied 4 bytes most of the time, only the last few bytes of the buffer were copied using smaller datatypes.
Can someone tell me the name of it? It's named after a person.... | It sounds like you're thinking of Duff's device.
|
1,409,729 | 1,434,353 | library for remote desktop | I'm working on porting a windows-only application to Linux, and eventually to Mac OSX. Part of this program is a remote-desktop-like feature - you can share a desktop space with several clients. The network protocol is very similar to the RDP protocol. The original author wrote everything from scratch. It works very we... | Pick a cross-platform open-source VNC client you like and co-opt it's input handling code, replacing the VNC bits with your protocol.
I'm unaware of any generic library for handling VNC client tasks.
|
1,409,890 | 1,409,924 | Run-time type information in C++ | What is runtime type control in C++?
| It enables you to identify the dynamic type of a object at run time. For example:
class A
{
virtual ~A();
};
class B : public A
{
}
void f(A* p)
{
//b will be non-NULL only if dynamic_cast succeeds
B* b = dynamic_cast<B*>(p);
if(b) //Type of the object is B
{
}
else //type is A
{
}
}
int main()
{... |
1,409,920 | 1,417,827 | Calling a function in child thread in Qt? | I have a main thread that invokes a child thread function at different times but I am not sure whether that is right way of doing it in Qt.What is wrong with the below code and looking for better alternative
There is a main thread running infinitly when ever main thread releases the lock child does a piece of work.
#i... | Edit: rework of entire post to cover basics as well.
Background.h:
#ifndef BACKGROUND_H
#define BACKGROUND_H
#include <QThread>
#include <QObject>
class Background : public QThread
{
Q_OBJECT
public:
Background(QObject* parent = 0):QThread(parent){}
protected:
void run()
{
qDebug(qPrintable(QString("C... |
1,410,226 | 1,410,255 | Is there any use for C++ throw decoration? | I've started using C++ exceptions in a uniform manner, and now I'd like the compiler (g++) to check that there are no "exception leaks". The throw decoration should do this, like const does for constness of class methods.
Well, it doesn't.
Using throw is still documentary, but may even be dangerously misleading if othe... | It doesn't check compile-time, but a conforming compiler should ensure it at run-time.
If a function throws anything outside of its throw-declaration, the C++ run-time should call std::unexpected, if I recall correctly.
|
1,410,649 | 1,410,718 | waiting for multiple condition variables in boost? | I'm looking for a way to wait for multiple condition variables.
ie. something like:
boost::condition_variable cond1;
boost::condition_variable cond2;
void wait_for_data_to_process()
{
boost::unique_lock<boost::mutex> lock(mut);
wait_any(lock, cond1, cond2); //boost only provides cond1.wait(lock);
p... | I don't believe you can do anything like this with boost::thread. Perhaps because POSIX condition variables don't allow this type of construct. Of course, Windows has WaitForMultipleObjects as aJ posted, which could be a solution if you're willing to restrict your code to Windows synchronization primitives.
Another o... |
1,410,706 | 1,410,744 | Why does this generate compiler warning "Signed/Unsigned mismatch" only when compiled under x64? | Consider this code:
LARGE_INTEGER l;
size_t s;
if (s < l.QuadPart) return 1;
return 0;
When this is compiled under x64 it generates the C4018 signed/unsigned mismatch compiler warning (Ignore the uninitialized local variable warning).
The warning is fine, since QuadPart is LONGLONG which is signed and size_t is unsign... | On 32-bit LONGLONG is equivalent to signed __int64 and size_t is equivalent to unsigned int. unsigned int has range that completely fits into signed __int64 range, so the compiler widens (does integer promotion) size_t to signed __int64 before the comparison and there's no warning.
On 64-bit LONGLONG is again equivalen... |
1,411,101 | 1,411,127 | Debugging a 2D array in VS2008 | I have a 2D array which contains height information. I want to see it in the debugger to a certain point if the values are correct. I know we can see a 1D array using "myArray,5", but it doesn't work when i write "myArray,5,5" or "myArray[0],5", without the quotation marks.
Does anybody know how to do this? Or is this... | As first, you can view memory block contents at specified address (myArray).
As second you can mouseover your array, and from pop-up menu show array members.
|
1,411,110 | 1,413,165 | Access Violation Exception/Crash from C++ callback to C# function | So I have a native 3rd party C++ code base I am working with (.lib and .hpp files) that I used to build a wrapper in C++/CLI for eventual use in C#.
I've run into a particular problem when switching from Debug to Release mode, in that I get an Access Violation Exception when a callback's code returns.
The code from... | I think the stack got crushed because of mismatching calling conventions:
try out to put the attribute
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
on the callback delegate declaration.
|
1,411,222 | 1,411,288 | Giving an instance of a class a pointer to a struct | I am trying to get SSE functionality in my vector class (I've rewritten it three times so far. :\) and I'm doing the following:
#ifndef _POINT_FINAL_H_
#define _POINT_FINAL_H_
#include "math.h"
namespace Vector3D
{
#define SSE_VERSION 3
#if SSE_VERSION >= 2
#include <emmintrin.h> // SSE2
#if SSE_VERSION ... | How about:
__declspec( align( 16 ) ) VectorData vd;
?
You can also create your own version of operator new as follows
void* operator new( size_t size, size_t alignment )
{
return __aligned_malloc( size, alignment );
}
which can then make allocationas follows
AlignedData* pData = new( 16 ) AlignedData;
to align ... |
1,411,230 | 1,411,993 | thread-safe function pointers in C++ | I'm writing a network library that a user can pass a function pointer to for execution on certain network events. In order to keep the listening loop from holding up the developer's application, I pass the event handler to a thread. Unfortunately, this creates a bit of a headache for handling things in a thread-safe ma... | Function pointers can not be thread safe as they declare a point to call. So they are just pointers.
Your code always runs in the thread it was called from (via the function pointer).
What you want to achieve is that your code runs in a specific thread (maybe the UI thread).
For this you must use some kind of queue to ... |
1,411,279 | 1,411,468 | Using boost::shared_ptr within inheritance hierarchy | Imagine the following situation:
class IAlarm : public boost::enable_shared_from_this<IAlarm> {
boost::shared_ptr<IAlarm> getThisPointerForIAlarm() {
return shared_from_this();
}
void verifyThis(int); // called by Device
};
class Alarm : public IAlarm {
Alarm( boost::shared_ptr< Device > attached... | The call to shared_from_this() is only valid if it is called on a dynamically allocated object that is owned by a shared_ptr (See the requirements listed in the docs). This means that there must exist a shared_ptr that owns the object, else shared_from_this() will not work.
Especially this means that you can't (success... |
1,411,505 | 1,421,063 | Mystery pthread problem with fork() | I have a program which:
has a main thread (1) which starts a server thread (2) and another (4).
the server thread (2) does an accept(), then creates a new thread (3) to handle the connection.
At some point, thread (4) does a fork/exec to run another program which should connect to the socket that thread (2) is liste... | I came to the conclusion that it was probably this phenomenon:
http://kerneltrap.org/mailarchive/linux-kernel/2008/8/15/2950234/thread
as the bug is difficult to trigger on our development systems but is generally reported by users running on large shared machines; also the forked application starts a JVM, which itself... |
1,411,526 | 1,411,791 | How can I debug a program when debugger fails | I am debugging an Iphone program with the simulator in xCode and I have one last issue to resolve but I need help resolving it for the following reason: when it happens the program goes into debugging mode but no errors appear (no BAD ACCESS appears) and it does not show where the code fails. Putting some variables as... | My favourite is always to add debugging code and log it to a file. This allows me so report any and all information I need to resolve the issue if the debugger is not working properly.
I normally control the debugging code by use of a flag which I can manipulate at run time or by the command line.
|
1,411,652 | 1,411,705 | Is MySQL C++ Connector access to remote database possible? | I am accessing a MySQL database within a C++ app using MySQL C++ Connector. It works fine if I have the C++ and the MySQL on the same machine. So, something like the following code works fine:
sql::Connection *_con;
sql::mysql::MySQL_Driver *_driver;
_driver = sql::mysql::get_mysql_driver_instance();
_... | Did you accidentally setup your users so that they can only access your DB from the local machine?
Did you do
create user 'user'@'127.0.0.1' ...
or
create user 'user'@'%' ....
If you did the first then you won't be able to log on from a different machine.
Did you also grant the privileges correctly?
See the MySQL doc... |
1,411,667 | 1,411,708 | c++ debugging in vis studio 2008, how to break when a variable becomes zero | I can detect when a variable changes, but it changes so often that its no use - what I want is to detect the moment that a variable becomes zero.
Thanks,
| That's not possible in Visual Studio. Visual Studio supports a number of debugging features in that particular area but I don't think you can combine them into a feature to get what you want
Data Changing Breakpoints: break when a value changes (only supported in native C++)
Conditionally breakpoints: break when the ... |
1,411,806 | 1,411,963 | Determining size of a polymorphic C++ class | Using the sizeof operator, I can determine the size of any type – but how can I dynamically determine the size of a polymorphic class at runtime?
For example, I have a pointer to an Animal, and I want to get the size of the actual object it points to, which will be different if it is a Cat or a Dog. Is there a simple... | If you know the set of possible types, you can use RTTI to find out the dynamic type by doing dynamic_cast. If you don't, the only way is through a virtual function.
|
1,411,813 | 1,411,961 | Safely moving a C++ object | I’ve heard some words of warning against shipping an object to another memory location via memcpy, but I don’t know the specific reasons. Unless its contained members do tricky things that depend on memory location, this should be perfectly safe … or not?
EDIT: The contemplated use case is a data structure like a vect... | For the sake of discussion, I assume you mean moving to mean that the original object "dropped" (is no longer used, didn't have it's destructor run) rather than have two copies (which would lead to a lot more problems, reference counts being off, etc). I generally refer to the property of being able to do this being bi... |
1,411,821 | 1,412,368 | What would be the purpose of using the reference and dereference operators immediately in sequence "&*B"? | I have seen this in our code a couple times and it immediately makes me suspicious. But since I don't know the original intent I am hesitant to remove it.
//requires double indirection which I won't go into
FooClass::FooFunction(void ** param)
{
//do something
}
SomeClass * A = new SomeClass();
SomeClass **B = &A;
... | I can see only one reason for this: B has overloaded operator*() to return an X, but whoever wrote the code needed an X*. (Note that in your code, X is A*.) The typical case for this is smart pointers and iterators.
If the above isn't the case, maybe the code was written to be generic enough to deal with smart pointer... |
1,411,844 | 1,411,891 | Polymorphism & Pointers to arrays | I have a class A:
class A
{
public:
virtual double getValue() = 0;
}
And a class B:
class B : public A
{
public:
virtual double getValue() { return 0.0; }
}
And then in main() I do:
A * var;
var = new B[100];
std::cout << var[0].getValue(); //This works fine
std::cout << var[1].getValue(); //T... | You can't treat arrays polymorphically, so while new B[100] creates an array of B objects and returns a pointer to the array - or equivalently the first element of the array - and while it is valid to assign this pointer to a pointer to a base class, it is not valid to treat this as a pointer into an array of A objects... |
1,412,016 | 1,412,036 | Best way to create large hashmap at compile time (C++)? | In my application, I need a hash map mapping strings to a large number of static objects. The mappings remain fixed for the duration of the application. Is there an easy way to pre-generate the mappings at compile time rather than building it element-by-element when the application starts?
| Look up gperf, it generates code for you that will perfectly hash.
|
1,412,080 | 1,412,289 | Distributing with Boost Library? | I'm quite new to using boost and I can't seem to find documentation anywhere on how to distribute your application when using boost?
Many of the libraries are shared libraries, I'm not expecting my users to have boost installed, I'm only using a single library (regex) so is there an easy way to package the regex librar... | Linux
For binary distribution, I recommend using the distribution's package management, which should take care of any dependencies.
Some commercial apps just use binary blobs and you need to install a version of boost by yourself.
Finding libraries is a bit more difficult on linux. It does not automatically load shared... |
1,412,081 | 1,412,094 | Are do-while-false loops common? | A while back I switched the way I handled c style errors.
I found a lot of my code looked like this:
int errorCode = 0;
errorCode = doSomething();
if (errorCode == 0)
{
errorCode = doSomethingElse();
}
...
if (errorCode == 0)
{
errorCode = doSomethingElseNew();
}
But recently I've been writing it like this:
i... | The second snippet just looks wrong. You're effectively re-invented goto.
Anyone reading the first code style will immediately know what's happening, the second style requires more examination, thus makes maintenance harder in the long run, for no real benefit.
Edit, in the second style, you've thrown away the error c... |
1,412,338 | 1,421,291 | Win32 C/C++ checking if two instances of the same program use the same arguments | I have an application and I want to be able to check if (for instance) two instances of it used the same arguments on execution. To make it clearer:
myapp 1 2
myapp 1 3
This isn't a Singleton design pattern problem as I can have more than one instance running. I though about checking the running processes, but it see... | After some thinking I decided to do things a bit simpler...
Implementing a mutex and checking it's existence is. As I needed to check if the instances started with the same parameters and not if the same application was started, I just needed to decide on the mutex name in runtime!
so...
sprintf(cmdstr,"myapp_%i_%i",ar... |
1,412,348 | 1,412,451 | Is it possible to return a derived class from a base class method in C++? | I would like to do this:
class Derived;
class Base {
virtual Derived f() = 0;
};
class Derived : public Base {
};
Of course this doesn't work since I can't return an incomplete type. But neither can I define Derived before base, since I can't inherit from an incomplete type either. I figure that I could use temp... | There's nothing wrong with the code in your question. This
class Derived;
class Base {
virtual Derived f() = 0;
};
class Derived : public Base {
virtual Derived f() {return Derived();}
};
should compile just fine. However, callers of 'Base::f()' will need to have seen the definition of 'Derived`.
|
1,412,737 | 1,412,769 | Templated class function T: How to find out if T is a pointer? | As a follow-up to this question: I need to decide in a class function like this:
template< typename T > bool Class::Fun <T*> ( T& variable ) {...}
whether T is a pointer or not.
In the question cited above the answer was to use partial template specialization. As far as I've found out this is not possible for class fu... | No need to specialize member function. In that answer used stand-alone structure. You're still free to use it in class member functions.
// stand-alone helper struct
template<typename T>
struct is_pointer { static const bool value = false; };
template<typename T>
struct is_pointer<T*> { static const bool value = tr... |
1,412,751 | 1,412,792 | Find largest and second largest element in a range | How do I find the above without removing the largest element and searching again? Is there a more efficient way to do this? It does not matter if the these elements are duplicates.
| for (e: all elements) {
if (e > largest) {
second = largest;
largest = e;
} else if (e > second) {
second = e;
}
}
You could either initialize largest and second to an appropriate lower bound, or to the first two items in the list (check which one is bigger, and don't forget to check if the list has at lea... |
1,412,885 | 1,412,904 | Basic doubt in QT using C++ about making objects | int main (int argc, char* argv[])
{
QApplication app(argc, argv);
QTextStream cout(stdout, QIODevice::WriteOnly);
// Declarations of variables
int answer = 0;
do {
// local variables to the loop:
int factArg = 0;
int fact(1);
factArg = QInputDialog::getInte... | Read the docs. Basically - first is a parent widget (NULL in this case), and the 1 after label is a default value.
|
1,413,158 | 1,413,347 | Partial specialization of a class template in derived class affects base class | I have a metafunction:
struct METAFUNCION
{
template<class T>
struct apply
{
typedef T type;
};
};
Then I define a helper:
template<class T1, class T2>
struct HELPER
{
};
And then I have second metafunction which derives from the METAFUNCTION above and defines partial specialization of apply struct:
struc... | The following code is illegal:
struct METAFUNCION2 : METAFUNCION
{
template<class T1, class T2>
struct apply<HELPER<T1, T2> > : METAFUNCION::apply<T2>
{
};
};
According to C++ Standard 14.7.3/3:
A declaration of a function template or class template being explicitly specialized shall be in scope at the
poin... |
1,413,171 | 1,413,191 | What is "strip" (GCC application) used for? | what is this little application for?
When using it without any options reduces the size of the executables, but how/what it does?
| From the (Mac OS X, but others are similar) man page:
strip removes or modifies the symbol table attached to the output of
the assembler and link editor. This is useful to save space after a
program has been debugged and to limit dynamically bound symbols.
Note the bit about "after a program ... |
1,413,193 | 1,413,302 | Deterministic handle allocation algorithm | I'm trying to find an efficient deterministic way of allocating a 32-bit handle in such a way that it will operate indefinitely. A simple incrementing counter will not work because it will eventually loop around. Extending to 64-bits isn't possible because the values will be used in a network protocol which is expectin... | You can't allocate more than 2^32. But you can reallocate used handles if they are released and the problem is to keep track of the free handles.
A tree is a good way to store the free handles. Each node has a lowest and a highest handle, the left subtree contains the handles that are lesser than the lowest and the rig... |
1,413,239 | 1,413,246 | const char* to LPTSTR | I am trying to call a function that accepts an LPTSTR as a parameter. I am calling it with a string literal, as in foo("bar");
I get an error that I "cannot convert parameter 1 from 'const char [3]' to 'LPTSTR'", but I have no idea why or how to fix it. Any help would be great.
| You probably has UNICODE defined, and LPTSTR expands into wchar_t*. Use TEXT macro for string literals to avoid problems with that, e.g. foo(TEXT("bar")).
|
1,413,256 | 1,413,469 | execl pipe without dup | I am trying to execute a program from a parent using execl. I do the normal pipe setup and fork. Here is the trick... I need my children (there can be an arbitrary number of children) to all communicate with the parent.
Program "A" (parent) creates pipe forks and execl into "B" (child). In the main() function of pr... | execl(3) has no effect on file descriptors, with one exception
It is possible to mark a file descriptor close-on-exec with fcntl(2), but generally the various flavors of execve(2) have no effect on open file descriptors and they remain open in children.
|
1,413,445 | 1,455,007 | Reading a password from std::cin | I need to read a password from standard input and wanted std::cin not to echo the characters typed by the user...
How can I disable the echo from std::cin?
here is the code that I'm currently using:
string passwd;
cout << "Enter the password: ";
getline( cin, passwd );
I'm looking for a OS agnostic way to do this.
Her... | @wrang-wrang answer was really good, but did not fulfill my needs, this is what my final code (which was based on this) look like:
#ifdef WIN32
#include <windows.h>
#else
#include <termios.h>
#include <unistd.h>
#endif
void SetStdinEcho(bool enable = true)
{
#ifdef WIN32
HANDLE hStdin = GetStdHandle(STD_INPUT_HAND... |
1,413,486 | 1,413,495 | Where to get peer review of code and how to get my code attention? | I'm just now learning to programming at age 17. It's hard for me to talk to other programmers as I'm just out of high school (which means I can't take programming courses). I know that I write terrible code, and not like Jeff Atwood terrible code, my code actually sucks. So where can I post some of my code and get real... | Look to the open source community. There are plenty of existing and new projects that would love an eager (if inexperienced) developer to offer support.
Going this route offers two advantages:
You get to see great code in action and learn from it
Any changes you submit will be reviewed by an experienced developer and... |
1,413,588 | 1,413,627 | Ambiguous template, Code Warrior | The following code compiles in Visual C++ and gcc, but fails with Code Warrior
The complaint is that the call to the template is ambiguous -- can't decide between doIt( M* ) and doIt( M const* ), even though in each case, the parameter is unambiguously cost or non-const. Irritatingly, if I supply the second template ar... | It is an error with the codewarrior compiler.
This is what should happen:
template< typename T1, typename T2 >
T1 const* doIt( T2 const* ); // 1
template< typename T1, typename T2 >
T1* doIt( T2* ); // 2
class M {};
class N : public M {};
void f()
{
M* m1 = 0;
M const* m2 = 0;
doIt<N>( m1 );
// In th... |
1,413,744 | 1,413,824 | Help with boost bind/functions | I have this function signature I have to match
typedef int (*lua_CFunction) (lua_State *L);//target sig
Here's what I have so far:
//somewhere else...
...
registerFunction<LuaEngine>("testFunc", &LuaEngine::testFunc, this);
...
//0 arg callback
void funcCallback0(boost::function<void ()> func, lua_St... | This cannot be solved directly. Lua API wants a plain function pointers from you - that's just a code pointer, and nothing else. Meanwhile, boost::function is a function object, and there's no way it could possibly be convertible to a plain function pointer, because - roughly speaking - it captures not just the code, b... |
1,413,768 | 1,420,326 | I want to start developing CGI, but I am very new at this | I want to develop my next web project in C++ as FastCGI but I don't know how to start and google wasn't very friendly about this.
I really don't know much about fastCGI or others libraries that makes cgi persistent... Tried to read some stuff, but it seems to be used along Linux with all those .configure Makefiles etc.... | I would not recommend you to use FastCGI with IIS. IIS support of FastCGI is very limited -- it allows communication only over pipes and only one request is passed to process.
FastCGI was added to IIS to somehow connect PHP and several other technologies to IIS.
If you want to create web applications in C++ I would rec... |
1,413,832 | 1,413,850 | Calling constructor from another class | If I have a class like this:
typedef union { __m128 quad; float numbers[4]; } Data
class foo
{
public:
foo() : m_Data() {}
Data m_Data;
};
and a class like this:
class bar
{
public:
bar() : m_Data() {}
foo m_Data;
}
is foo's constructor called when making an instance of bar?
Because when I try to us... | You have to declare your constructor to be public, otherwise you are not allowing anyone to instantiate your class if you declare it as private member.
|
1,413,878 | 1,413,886 | Is it ok to use wcout to print char*? | Consider this line:
std::wcout << "Hello World!";
Is it OK to pass char* or char to wide stream?
| Both are ok because the wide stream has multiple overloads.
|
1,414,043 | 1,414,353 | How to hide "Cancel" button in QInputDialog in QT using C++? | #include <QtGui>
int main (int argc, char* argv[])
{
QApplication app(argc, argv);
QTextStream cout(stdout, QIODevice::WriteOnly);
// Declarations of variables
int answer = 0;
do {
// local variables to the loop:
int factArg = 0;
int fact(1);
factArg = QIn... | QInputDialog is given as a convenience class that provides a quick and easy way to ask for an input and as such, does not allow for much customization. I don't see anything in the documentation to indicate that you can change the layout of the window. I would suggest just designing your own dialog by extending QDialo... |
1,414,187 | 1,415,424 | PostMessage for cross application messages | I'm trying to send a keystroke to another application. I can successfully find the window handle since using SendMessage worked exactly as intended.
However, when I switched the SendMessage over to PostMessage, the application no longer received the messages.
I did, however, find a workaround by using HWND_BROADCAST as... | The PostMessage function does not work when the message numbers between 0 and WM_USER-1. Use RegisterWindowMessage function to register your own messages.
|
1,414,506 | 1,414,520 | Protected data in parent class not available in child class? | I am confused: I thought protected data was read/writable by the children of a given class in C++.
The below snippet fails to compile in MS Compiler
class A
{
protected:
int data;
};
class B : public A
{
public:
B(A &a)
{
data = a.data;
}
};
int main()
{
A a;
B b = a;
return 0;
}
Error Message:
... | According to TC++PL, pg 404:
A derived class can access a base class’ protected members only for objects of its own type.... This prevents subtle errors that would otherwise occur when one derived class corrupts data belonging to other derived classes.
Of course, here's an easy way to fix this for your case:
class A
... |
1,414,897 | 1,432,272 | Using GCC's C++0x mode in production? | Is anyone using the GCC 4.4.0 C++0x support in production? I'm thinking about using it with the latest MinGW, but I'm not sure if it's mature enough.
I'm interested in:
TR1 support
auto
initializer lists
| IMHO, TR1 support and auto are safe to use. In the case of auto it was one of the first features to be included into the standard and is a relatively small change to the language. I would therefore have no problem using it.
I would be a bit more hesitant about using initializer lists. On some other forums (eg. comp.... |
1,415,095 | 1,415,103 | DoEvents equivalent for C++? | I'm new to native c++. Right now, I made it so when I press the left mouse button, it has a for loop that does InvalidateRect and draws a rectangle, and increments X by the box size each time it iterates. But, C++ is so much faster and efficient at drawing than C# that, it draws all this instantly. What I would like is... | DoEvents basically translates as:
void DoEvents()
{
MSG msg;
BOOL result;
while ( ::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE ) )
{
result = ::GetMessage(&msg, NULL, 0, 0);
if (result == 0) // WM_QUIT
{
::PostQuitMessage(msg.wParam);
break... |
1,415,388 | 1,415,406 | C++ class dependencies | I'm having some problems with my class because they both depends on each other, to one can't be declared without the other one being declared.
class block: GtkEventBox {
public:
block(board board,guint x,guint y): image("block.png") {
this.board = board;
this.x = x;
this... | Define "board" before "block" and forward declare the "block" class. Also, move the implementation of the board functions out of the class definition.
// forward declare block class
class block;
// declare board class
class board: Gtk::Table {
public:
board();
void addBlock(guint x,guint y);
... |
1,415,538 | 5,034,489 | Using #include to load OpenCL code | I've seen this done long ago with hlsl/glsl shader code -- using an #include on the source code file that pastes the code into a char* so that no file IO happens at runtime.
If I were to represent it as pseudo-code, it would look a little like this:
#define CLSourceToString(filename) " #include "filename" "
const char*... | See the bullet physics engines use of OpenCL for how to do this to a kernel.
In C++ / C source
#define MSTRINGIFY(A) #A
char* stringifiedSourceCL =
#include "VectorAddKernels.cl"
In the OpenCL source
MSTRINGIFY(
__kernel void VectorAdd(__global float8* c)
{
// snipped out OpenCL code...
return;
}
);
... |
1,415,569 | 1,415,686 | String table encoding vs. gzip compression | In my application, I need to store and transmit data that contains many repeating string values (think entity names in an XML document). I have two proposed solutions:
A) create a string table to be stored along the document, and then use index references (using multi-byte encoding) in the document body, or
B) simpl... | gzip is only a good algorithm when the transmission/storage cost is not too high compared to the cost of CPU time. You can get better compression ratios with bzip2, 7zip, and especialy for natural language, various PPM algorithms.
Of course, it's not only computation (and static vs. dynamic memory requirement) vs. com... |
1,415,608 | 1,415,639 | C++ Custom compare function for list::sort | Hi I'm having trouble compiling a simple piece of code. I am creating a class which implements a Deck of cards, and I want to create a shuffle method using the list::short method.
Relevant code:
deck.h
#ifndef _DECK_H
#define _DECK_H
#include <list>
#include <ostream>
#include "Card.h"
#include "RandomGenerator.h"
u... | Can I say something :)
First, don't store a pointer to Card, just store the cards directly in the container. If you insist on storing pointers to them for any reason, use shared_ptr<Card> from Boost. Second, you can use std::random_shuffle and pass your random-number-generator to it instead of implementing your your sh... |
1,415,656 | 1,415,953 | Simple Qt Application won't compile on OS X | I've downloaded the Qt SDK and am trying to get started on my first Qt application using Qt Creator.
Using the wizard from the opening splash screen I selected "Qt4 Gui Application" and it threw together a little project for me.
When I try to build that project (without making any changes) I get build errors:
Running ... | I managed to solve this by reinstalling the developer tools. I guess something had messed up my version of ld.
|
1,415,690 | 1,415,735 | Problem solving in C++ with STL | I am preparing for a programming competition in witch we solve programming problems in c++.
Looking at the former year solutions, they seem quite easy (not more than ~30 lines of code). I realised that they are widely using the STL for easy manipulating - vectors, sets, maps, lists and also the algorithms available in... | As well as Scott Meyer's excellent book "Effective STL" which has been recommended above, I can't recommend highly enough the excellent book Accelerated C++ by Andrew Koenig and Barbara E. Moo.
The book starts by having you use STL very early in the book explaining their uses in the context of initially simple problems... |
1,415,755 | 1,415,780 | How to read and write bits to a byte array | I have a unsigned char buffer, and I'm wondering how I would write and read signed and unsigned bits to this byte buffer.
In the Source Engine there is a class named bf_write, which two main methods (used by WriteString, WriteChar, WriteLong, etc.) use two functions named WriteUBitLong and WriteSBitLong.
Thanks in adva... | If the number of bits is a compile-time constant:
#include <bitset>
...
std::bitset<100> b;
b[2]=true;
If it's not, use Boost.dynamic_bitset
Or, if you're desperate, std::vector, which is indeed a packed bit vector:
#include <vector>
...
std::vector<bool> b(100);
b[2]=true;
You seem to want to use a library that requ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.