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
2,348,788
2,348,820
write a C or C++ library with "template"
(1). When using C++ template, is it correct that the compiler (e.g. g++) will not compile the template definition (which can only be in header file not source file) directly, but generate the code based on template definition for each of its instantiations and then compile the generated code for its instantiations? (2...
When using C++ template, is it correct that the compiler (e.g. g++) will not compile the template definition. Yes. It's a correct assumption. A template definition is incomplete code. You need to fill in the template parameters before compiling it. If I want to write a C++ library which provide template classes ...
2,348,960
2,376,513
How can I use Boost::Python to add a method to an exported class without modifying the base class?
I have a class in C++ that I can't modify. However, that class holds an std::list<> of items that I need to be able to access in a Python extension. Since Boost::Python doesn't seem to have a built-in conversion between an std::list and a Python list, I was hoping to be able to write a method in C++ that could do thi...
Boost provides a helper to wrap iterators which is documented here: http://www.boost.org/doc/libs/1_42_0/libs/python/doc/v2/iterator.html The example hear the end of that page worked for me, you just need to explicitly create the conversion, for example: class_<std::list<Item> >("ItemList") .def("__iter__", itera...
2,349,069
2,349,257
Issue with Freetype and OpenGL
Hey, i'm having a weird issue with drawing text in openGL loaded with the Freetype 2 library. Here is a screenshot of what I'm seeing. example http://img203.imageshack.us/img203/3316/freetypeweird.png Here are my code bits for loading and rendering my text. class Font { Font(const String& filename) { if ...
I'm not familiar with FreeType, but from the picture, it looks like the width of the characters is not directly related to the size of the buffers (ie. glyph->buffer does not point to an array of glyph->width*glyth->height bytes). As a guess, I'd say that all the chars have a single width in memory (as opposed to the s...
2,349,098
2,349,103
C++ Linked list behavior
I have some C code, where in there are two linked lists(say A and B) and A is inserted at a particular position into B and A still has elements. How do I simulate the same behavior effectively using the C++ STL? If I try splice, it makes the second one empty. Thanks, Gokul.
You need to copy the elements. Consider something like this: std::copy(a.begin(), a.end(), std::inserter(b, b_iterator)); If you want the same nodes shared by two lists, this is simply not supported by std::list (STL containers always have exclusive ownership). You can avoid duplicating the elements by storing pointer...
2,349,114
2,349,117
How do I work with nested vectors in C++?
I'm trying to work with vectors of vectors of ints for a sudoku puzzle solver I'm writing. Question 1: If I'm going to access a my 2d vector by index, do I have to initialize it with the appropriate size first? For example: typedef vector<vector<int> > array2d_t; void readAPuzzle(array2d_t grid) { for(int i = 0; i...
Q1: Yes, that is the correct way to handle it. However, notice that nested vectors are a rather inefficient way to implement a 2D array. One vector and calculating indices by x + y * width is usually a better option. Q2A: Calculating grid[i][j] + " " does not concatenate two strings (because the left hand side is int, ...
2,349,283
2,349,303
Is it possible to have an instance of a class as a data member of another class?
I have a Board class where the constructor takes in the dimensions of the board as the parameter. I also have a Puzzle class that holds pieces and I want it to have a Board as a data member. I want it like this so that when I create an instance of Puzzle, I will have my instance of Board created as well so I don't ha...
If I understand correctly, the problem is that you need to instantiate your board correctly: class Puzzle { public: Board theBoard; Puzzle(int height, int width) : theBoard(height, width) // Pass this into the constructor here... { }; };
2,349,366
2,349,386
Returning a copy of an Object's self in C++
Ok, So I've googled this problem and I have searched stack overflow but I can't seem to find a good answer. So, I am asking the question on here that is particular to my problem. If it is an easy answer, please be nice, I am new to the language. Here is my problem: I am trying to write a method for a C++ class that is ...
The problem is in your function signature. You really do have to return the entire object and not just a reference. Your function will look like this BigInt operator+() const //returns a positive of the number { BigInt returnValue = *this; returnValue.makepositve(); //for examples sake return returnValue;...
2,349,578
2,349,616
Conditional typedefs
If I have a little peice o' code as such... template <typename _T> class Foo { public: typedef const T& ParamType; void DoStuff(ParamType thingy); }; This can be non-optimal if sizeof(_T) <= sizeof(_T*). Therefore, I want to have a conditional typedef. If the size of _T is less than or equal to that of a point...
Quite easy to achieve using partial template specialization. template< typename _T, bool _ByVal > struct FooBase { typedef const _T& ParamType; }; template< typename _T > struct FooBase< _T, true > { typedef const _T ParamType; }; template< typename _T, bool _ByVal = sizeof(_T) <= sizeof(void*) > class Foo : publ...
2,349,698
2,349,745
C++: binary search compile error
I have the following lines of code: if(std::binary_search(face_verts.begin(), face_verts.end(), left_right_vert[0]) && std::binary_search(face_verts.begin(), face_verts.end(), left_right_vert[1])) And when I compile my code, I get the following errors: In file included from /usr/include/c++/4.4/algorithm:62, ...
In order to use binary_search you input siquence must be sorted in accordance with certain comparison predicate. Later, this very same comparison predicate must be given (explicitly or implicitly) to binary_search to be used during searching. So, the questions you should answer in this case are the following Is the in...
2,349,727
2,349,974
TInyOS 1.x Generating an error when compiling BLINK
root@everton-laptop:/opt/tinyos-1.x/apps/Blink# make pc compiling Blink to a pc binary ncc -o build/pc/main.exe -g -O0 -board=micasb -pthread -target=pc -Wall -Wshadow -DDEF_TOS_AM_GROUP=0x7d -Wnesc-all -fnesc-nido-tosnodes=1000 -fnesc-cfile=build/pc/app.c Blink.nc -lm In file included from /opt/tinyos-1.x/tos/p...
Looking at the CVS repository for tos/types/AM.h, it looks like it's choking on the following code: 154: enum { 155: MSG_DATA_SIZE = offsetof(struct TOS_Msg, crc) + sizeof(uint16_t), // 36 by default 156: TINYSEC_MSG_DATA_SIZE = offsetof(struct TinySec_Msg, mac) + TINYSEC_MAC_LENGTH, // 41 by default 157: DATA...
2,349,783
2,349,792
Can I do pointer arithmetic on an STL::vector::iterator
Currently I use an iterator to search through a vector and test its elements. I access the elements using std::vector<int>::iterator it; if (*it == 0); Can I use the same pointer arithmetic style logic to also test the next element (without altering my iterator)? I first need to see if it will push the iterator out of...
Yes, the iterators for std::vector are random access iterators so you add/subtract integral values to get other valid iterators. Technically, it may not be pointer arithmetic, but they act just like pointers.
2,349,801
2,349,809
Modelling a network with a vector of vectors
I am trying to model a network using C++. I have a struct called NetworkConnection: struct NetworkConnection { int i, j, weight; } and I have a class called Network class Network { public: std::vector<NetworkConnection> connections_for(int i) { return connections[i]; } void connect(int i, int j, ...
You want to use a map: class Network { public: std::vector<NetworkConnection> connections_for(int i) { return connections[i]; } void connect(int i, int j, int weight) { NetworkConnection connection; connection.i = i; connection.j = j; connection.weight = weight; connect...
2,349,827
2,349,840
The difference between a program in C++ developed under Windows and Linux
What's the difference between a program developed in C++ under Windows and Linux? Why can't a program developed under Windows in C++ be used under Linux?
Windows and Linux use different container formats to hold the executable code (PE vs ELF). Windows and Linux have completely different APIs (except for trivial programs that only use the CRT and STL) Windows and Linux have a completely different directory structure You could write a program that can use either set of...
2,349,867
2,349,878
How can it be useful to overload the "function call" operator?
I recently discovered that in C++ you can overload the "function call" operator, in a strange way in which you have to write two pair of parenthesis to do so: class A { int n; public: void operator ()() const; }; And then use it this way: A a; a(); When is this useful?
This can be used to create "functors", objects that act like functions: class Multiplier { public: Multiplier(int m): multiplier(m) {} int operator()(int x) { return multiplier * x; } private: int multiplier; }; Multiplier m(5); cout << m(4) << endl; The above prints 20. The Wikipedia article linked above...
2,349,887
2,350,914
Is it worth cutting down a 540 byte class into smaller chunks? (C++)
So I've been developing a UI toolkit for the past year, and my Window class has gotten to a point where the size of the class (through sizeof) is 540 bytes). I was thinking, that since not all windows have children, I might split parts of the code that handles having children (its alignment etc) into a separate class a...
First, the size of an object instance in itself doesn't really matter. The class should be designed to have a single responsibility, and if that requires 540 bytes of data, then so be it. However, 540 bytes is a unusually big number. It's 135 integers or pointers. It's something like 22 std::vectors. I have a hard time...
2,349,897
2,350,040
C++ - Verifying correct input type
I've got the following piece of code: ... int x = 0; int y = 0; cin >> x >> y; if (x == -1 && y == -1) { cout << "exit!"; } else { doSomething(); } ... And it works, but only if I enter 2 numbers. If I were to enter a letter, like 'n', the program gets thrown into an infinite loop. How do I check to make sure ...
Once cin sees a type disagreement between the input data and the variables you're trying to read into, it enters a "fail" state. The conflicting variables won't be updated. Observe: 2010-02-27 22:54:27 ~/tmp/ $ cat ju3.cpp #include <iostream> using namespace std; int main() { int x = 0; int ...
2,349,978
2,350,003
Variables after the colon in a constructor
I am still learning C++ and trying to understand it. I was looking through some code and saw: point3(float X, float Y, float Z) : x(X), y(Y), z(Z) // <----- what is this used for { } What is the meaning of the "x(X), y(Y), z(Z)" sitting beside the constructor's parameters?
It's a way of invoking the constructors of members of the point3 class. if x,y, and z are floats, then this is just a more efficient way of writing this point3( float X, float Y, float Z): { x = X; y = Y; z = Z; } But if x, y & z are classes, then this is the only way to pass parameters into their constructor...
2,349,995
2,350,055
Template class, function specialization
I want to have a template class that looks something like what I have down below. Then, I want a function in it with a template specialization depending on a CLASS template parameter. How do I make this work? I realize the code I provided is wrong on many levels, but it's just to illustrate the concept. template <typen...
struct Otherwise { }; template<size_t> struct C : Otherwise { }; // don't use _Uppercase - those names are reserved for the implementation // (i removed the '_' char) template <typename T, size_t num> class Foo { public: void Func() { Func(C<num>()); } private: // If num == 1, I want to call this function... ...
2,350,056
2,350,059
How could I do frequency analysis on a string without using a switch
I am working a school project to implement a Huffman code on text. The first part of course requires a frequency analysis on the text. Is there a better way aside from a giant switch and an array of counters to do it? ie: int[] counters for(int i = 0; i <inString.length(); i++) { switch(inString[i]) case 'A': ...
Why not: int counters[256] = {0}; for(int i = 0; i <inString.length(); i++) counters[inString[i]]++; } std::cout << "Count occurences of \'a\'" << counters['a'] << std::endl;
2,350,248
2,350,263
Difference in performance between map and unordered_map in c++
I have a simple requirement, i need a map of type . however i need fastest theoretically possible retrieval time. i used both map and the new proposed unordered_map from tr1 i found that at least while parsing a file and creating the map, by inserting an element at at time. map took only 2 minutes while unordered_map...
Insertion for unordered_map should be O(1) and retrieval should be roughly O(1), (its essentially a hash-table). Your timings as a result are way OFF, or there is something WRONG with your implementation or usage of unordered_map. You need to provide some more information, and possibly how you are using the container...
2,350,466
2,350,474
How to assign / retrieve base class?
Suppose I have: class Foo { ... }; class Bar : public Foo { ... }; Foo foo; Bar bar; Is there anyway to do the following: foo_part_of_bar(bar) = foo; foo = foo_part_of_bar(bar); ? Thanks!
Assuming you meant class Bar : public Foo, the following should work. For foo_part_of_bar(bar) = foo; *(static_cast<Foo *>(&bar)) = foo; For foo = foo_part_of_bar(bar); foo = bar;
2,350,489
2,350,530
How to catch segmentation fault in Linux?
I need to catch segmentation fault in third party library cleanup operations. This happens sometimes just before my program exits, and I cannot fix the real reason of this. In Windows programming I could do this with __try - __catch. Is there cross-platform or platform-specific way to do the same? I need this in Linux,...
On Linux we can have these as exceptions, too. Normally, when your program performs a segmentation fault, it is sent a SIGSEGV signal. You can set up your own handler for this signal and mitigate the consequences. Of course you should really be sure that you can recover from the situation. In your case, I think, you...
2,350,531
2,350,562
Problem with D3D & COM
all the D3D interfaces are derived from COM's IUnknown interface, so I though I'd take an easy route for releasing D3D objects and use something like this: __inline BOOL SafeRelease(IUnknown*& pUnknown) { if(pUnknown != NULL && FAILED(pUnknown->Release())) return FALSE; pUnknown = NULL; return TRUE...
A template function solves your problem: template<class T> __inline bool SafeRelease(T*& pUnknown) { if (pUnknown == NULL) return false; if (0 == pUnknown->Release()) pUnknown = NULL; return true; }
2,350,544
2,351,513
In what situation do you use a semaphore over a mutex in C++?
Throughout the resources I've read about multithreading, mutex is more often used and discussed compared to a semaphore. My question is when do you use a semaphore over a mutex? I don't see semaphores in Boost thread. Does that mean semaphores no longer used much these days? As far as I've understand, semaphores allow ...
Boost.Thread has mutexes and condition variables. Purely in terms of functionality, semaphores are therefore redundant[*], although I don't know if that's why they're omitted. Semaphores are a more basic primitive, simpler, and possibly implemented to be faster, but don't have priority-inversion avoidance. They're argu...
2,350,621
2,350,677
Write a *.doc or *.rtf file from a c/c++ application
How can I write to/generate a *.doc file programmatically using c or c++? Is there a (open source/cross platform) library to do this? If this is not possible, can write an *.odt file and then convert it to *.doc? Thanks in advance! EDIT: Anders Abel commented that *.rtf file type is an option, so any suggestions on thi...
Joel has an interesing article about this topic: http://www.joelonsoftware.com/items/2008/02/19.html Basically he suggest either: Use MS Word via COM to create the document. Generate another format that MS Word will load, such as RTF. RTF has the advantage that it is a text format. So you can generate a template docum...
2,350,830
2,350,846
do i consider (int, double...) as classes
i'm new to c++ and having a little problem understanding about c++'s casting. According to "C++ Primer", the old style cast is like: int(variable) or (int) variable, and new ones introduced by c++ standard includes static_cast<>, const_cast<>, reinterpret_cast<> and dynamic_cast<>. Is the static_cast<> equivalent to "...
1. Old style cast is equivalent of different casts: int i; double d = 3.14; i = static_cast<double>(d); //(double)d; const char* p = reinterpret_cast<char*>(&d); //(char*) &d; char* q = const_cast<char*>(p); //(char*) p; 2. Basic data types are not classes (e.g you can't inherit from them) but they support the constru...
2,350,933
2,350,950
Pointers and Variables
I just need some clarification on variables A normal variable has 2 "parts" to it? one part is the actual value and the other part is the location of that value in the memory Is that right? So a pointer variable is just the location part of a normal variable, and it doesn't have value itself?
If you're talking about C, then pointers simply represent another level of indirection. If you consider the variable a as an integer, &a (address of a) is the location and it contains the value of a in that location. When you use a, you will get the value from the address. A pointer variable p, when used, will also get...
2,350,940
2,351,479
Streaming to QTextEdit via QTextStream
I have often wanted to use QTextEdit as a quick means of displaying what is being written to a stream. That is, rather than writing to QTextStream out(stdout), I want to do something like: QTextEdit qte; QTextStream out(qte); I could do something similar if I emit a signal after writing to a QTextStream attac...
You can subclass the QTextEdit and implement the << operator to give it the behaviour you want ; something like: class TextEdit : public QTextEdit { .../... TextEdit & operator<< (QString const &str) { append(str); return *this; } };
2,350,997
2,351,024
templates and inheritance issue!
I have a tempated base class check and publically derived class childcheck. the base class also have a partial specializatin but i inherit the childcheck class from the general templated class( not from the partial specialization of the class check). when i call the constructor of the base class from the initialization...
The check<t*>::check(t*,int); c'tor takes two parameters, but you are calling it ascheck<t>(element+1) from the derived class initialization list (with t==int*, so the partial specialization is instanced).
2,351,148
2,351,155
Explicit template instantiation - when is it used?
After few weeks break, I'm trying to expand and extend my knowlege of templates with the book Templates – The Complete Guide by David Vandevoorde and Nicolai M. Josuttis, and what I'm trying to understand at this moment is explicit instantiation of templates. I don't actually have a problem with the mechanism as such, ...
Directly copied from https://learn.microsoft.com/en-us/cpp/cpp/explicit-instantiation: You can use explicit instantiation to create an instantiation of a templated class or function without actually using it in your code. Because this is useful when you are creating library (.lib) files that use templates for distribu...
2,351,437
2,351,485
When do you use function objects in C++?
I see function objects used often together with STL algorithms. Did function objects came about because of these algorithms? When do you use a function object in C++? What is its benefits?
As said jdv, functors are used instead of function pointers, that are harder to optimize and inline for the compiler; moreover, a fundamental advantage of functors is that they can easily preserve a state between calls to them1, so they can work differently depending on the other times they have been called, keep track...
2,351,516
2,351,631
How to avoid reallocation using the STL (C++)
This question is derived from the topic: vector reserve c++ I am using a datastructure of the type vector<vector<vector<double> > >. It is not possible to know the size of each of these vector (except the outer one) before items (doubles) are added. I can get an approximate size (upper bound) on the number of items in ...
your example will cause a lot of copying and allocations. vector<vector<vector<double>>> A; A.reserve(500+1); vector<vector<double>> temp2; vector<double> temp1 (666,666); for(int i=0;i<500;i++) { A.push_back(temp2); for(int j=0; j< 10000;j++) { A.back().push_back(temp1); } } Q: Will this ensure that no...
2,351,544
2,351,595
Is array name a constant pointer in C++?
I have a question about the array name a int a[10] How is the array name defined in C++? A constant pointer? It is defined like this or just we can look it like this? What operations can be applied on the name?
The C++ standard defines what an array is and its behaviour. Take a look in the index. It's not a pointer, const or otherwise, and it's not anything else, it's an array. To see a difference: int a[10]; int *const b = a; std::cout << sizeof(a); // prints "40" on my machine. std::cout << sizeof(b); // prints "4" on my m...
2,351,616
2,351,632
is there any easy way to expose methods of private parent class c++
Is there any way to directly expose some methods of private parent class. In the following example if I have an object of type Child I want to be able to directly call method a() of its parent, but not b(); Current solution spawns a lot of boilerplate code especially if there are a lot of arguments. class Parent { ...
You can use the using declaration. class Child : private Parent { public: using Parent::a; };
2,351,786
2,352,208
dynamic_cast fails when used with dlopen/dlsym
Intro Let me apologise upfront for the long question. It is as short as I could make it, which is, unfortunately, not very short. Setup I have defined two interfaces, A and B: class A // An interface { public: virtual ~A() {} virtual void whatever_A()=0; }; class B // Another interface { public: virtual ~B() {}...
I found the answer to my question here. As I understand it, I need to make the typeinfo available in 'testc' available to the library 'testd'. To do this when using dlopen(), two extra things need to be done: When linking the library, pass the linker the -E option, to make sure it exports all symbols to the executable...
2,351,794
2,351,856
C++: Any way to 'jail function'?
Well, it's a kind of a web server. I load .dll(.a) files and use them as program modules. I recursively go through directories and put '_main' functors from these libraries into std::map under name, which is membered in special '.m' files. The main directory has few directories for each host. The problem is that I need...
As C++ is low level language and the DLLs are compiled to machine code they can do anything. Even if you wrap the standard library functions the code can do the system calls directly, reimplementing the functionality you have wrapped. Probably the only way to effectively sandbox such a DLL is some kind of virtualisatio...
2,351,823
2,351,843
c++ round floating numbers to set precision
I wish to round a floating point number to set precision and return the result from a function. For example, I currently have the following function: inline bool R3Point:: operator==(const R3Point& point) const { // Return whether point is equal return ((v[0] == point.v[0]) && (v[1] == point.v[1]) && (v[2] == point...
Generally, == should not be used to compare doubles, you should do something like : if(v[0] - point.v[0] < 1e-9) { } You can use abs or fabs if you are not sure of the sign and change the precision 1e-9 accordingly.
2,351,826
2,351,885
inheriting a class from a partial specialization of a template class
I have a templated class named check and its partial specialization, now i am publically inheriting a class named childcheck from the partial specialization of the class check. but compiler gives following error message no matching function for call to `check::check()' candidates are: check::check(const check&) check...
You inherit from check<t*> yet call a base class constructor check<t> as if you inherited from check<t>. Which check<> do you want to inherit from? I believe that what you really want do is this: template<class t> class childcheck:public check<t> If t is int*, then childcheck<int*> will inherit from check<int*> whic...
2,351,936
2,351,968
create an object in switch-case
i use visual studi 2008. (c++) in my switch case a wanted to create an object, but i doens't work. is it right, that i can't create an object in a switch case? if that's right,whats the best way to work around it, a new method that's creates that object? edit the code: switch (causwahl){ case '1': cAccount *oAccount = ...
I can't say for sure with such a vague question, but I'm guessing that you're doing something like this: switch(foo) { case 1: MyObject bar; // ... break; case 2: MyObject bar; // ... break; } This isn't allowed because each case statement has the same scope. You need to provide more scope if you want to ...
2,351,972
2,351,982
What's the right way to overload the stream operators << >> for my class?
I'm a bit confused about how to overload the stream operators for my class in C++, since it seems they are functions on the stream classes, not on my class. What's the normal way to do this? At the moment, for the "get from" operator, I have a definition istream& operator>>(istream& is, Thing& thing) { // etc... whi...
Your implementation is fine. The only additional step you need to perform is to declare your operator as a friend in Thing: class Thing { public: friend istream& operator>>(istream&, Thing&); ... }
2,352,090
2,353,039
CUDA with map<value, key> & atomic operations
As far as I know I can use C++ templates in CUDA device code. So If i'm using map to create a dictionary will the operation of inserting new values be atomic? I want to count the number of appearances of a certain values, i.e. create a code-dictionary with probabilities of the codes. Thanks Macs
You cannot use STL within device code. You could check thrust for similar functionality (check the experimental namespace in particular). Templates are fine in device code, CUDA C currently supports quite a few C++ features although some of the big ones such as virtual functions and exceptions are not yet possible ( an...
2,352,160
2,352,193
C++: How to improve performance of custom class that will be copied often?
I am moving to C++ from Java and I am having a lot of trouble understanding the basics of how C++ classes work and best practices for designing them. Specifically I am wondering if I should be using a pointer to my class member in the following case. I have a custom class Foo which which represents the state of a game ...
Ideally you'd have all the information necessary to setup Bar at the time Foo is constructed. The best solution would be something like: class Foo { Bar b; public: Foo() : b() { ... }; Foo(const Foo& f) : b(f.a, f.b) { ... }; } Read more about constructor initialization lists (which has no direct eq...
2,352,220
2,352,245
Alternative http port?
I want to write a browser-chat and write an own server in c++, because you can not send text between the different instances (chat user) in php and other languages. I have apache running with port 80 and that's why I cant run the "chat http server" on port 80. Some browsers block connection to a http site if it does no...
You can use mod_proxy (or mod_proxy_balancer) to forward requests on some branch of your Apache site to the other web server that listens to localhost on some other port.
2,352,235
2,352,253
c++ development on Mac
I have till now mainly concentrated on web programming thus far and now want to enter application programming space. I use a mac, and wanted to know what sort of compilers, IDEs etc people generally use for c++ dev. extremely n00b One more thing immensely bothering me was the fact that c++ compilers generally output ....
C++ is not restricted to .exe files.... window PE files are one container format for machine code. A C++ binary can be encased in any low-level container format you can think of. Objective-C on the mac can be a very pleasant language to learn, also Java. Do you really need to learn C++ at this junction ? C++ is suited ...
2,352,342
2,352,356
The difference between python dict and tr1::unordered_map in C++
I have a question related to understanding of how python dictionaries work. I remember reading somewhere strings in python are immutable to allow hashing, and it is the same reason why one cannot directly use lists as keys, i.e. the lists are mutable (by supporting .append) and hence they cannot be used as dictionary ...
Keys in all C++ map/set containers are const and thus immutable (after added to the container). Notice that C++ containers are not specific to string keys, you can use any objects, but the constness will prevent modifications after the key is copied to the container.
2,352,533
2,352,657
Adding virtual functions without modifying the original classes
Let's say we already have a hierarchy of classes, e.g. class Shape { virtual void get_area() = 0; }; class Square : Shape { ... }; class Circle : Shape { ... }; etc. Now let's say that I want to (effectively) add a virtual draw() = 0 method to Shape with appropriate definitions in each sub-class. However, let's say I ...
(I do propose a solution down further... bear with me...) One way to (almost) solve your problem is to use a Visitor design pattern. Something like this: class DrawVisitor { public: void draw(const Shape &shape); // dispatches to correct private method private: void visitSquare(const Square &square); void visitC...
2,352,601
2,352,620
C++: Compiler warning for large unsigned int
I have following array, that I need to operate by hand on bitmaps. const unsigned int BITS[32] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, ...
Integer literals in C are, by default, of type "signed int" (edit: but see comments for caveats). The last number there is too large to be represented as a signed 32-bit integer, and so you need to tell the compiler that it's an unsigned integer by suffixing it with "U", as: 2147483648U Note that you can also add a s...
2,352,683
2,352,912
How to return a const QString reference in case of failure?
consider the following code: const QString& MyClass::getID(int index) const { if (i < myArraySize && myArray[i]) { return myArray[i]->id; // id is a QString } else { return my_global_empty_qstring; // is a global empty QString } } How can I avoid to have an empty QString without changing th...
You can't. Either do not return a const reference or use a local static variable like this: const QString& MyClass::getID(int index) const { if (i < myArraySize && (myArray[i] != 0)) { return myArray[i]->id; // id is a QString } static const QString emptyString; return emptyString; } The advan...
2,353,124
2,353,133
Segfault when I delete an object - GDB says in free()
I am working on an assignment for networking where we are supposed to create a networking library in C and then use it in our C++ program. My C++ isn't as strong as my C so I got started on that first so I could tackle any problems that came up, and I present you my first one. :D I have a base class and an inherited cl...
string objects were not allocated using new operator. Do not delete them, they will be freed automatically
2,353,142
2,353,160
Overloading Operator + in C++
Ok, I am working through a book and trying to learn C++ operator overloading. I created a BigInt class that takes a single int (initially set to 0) for the constructor. I overloaded the += method and it works just fine in the following code: BigInt x = BigInt(2); x += x; x.print( cout ); The code will output 4. So, th...
most likely problem is in += operator. Post code for it.
2,353,178
2,388,967
Disable alt-enter in a Direct3D (DirectX) application
I'm reading Introduction to 3D Game Programming with DirectX 10 to learn some DirectX, and I was trying to do the proposed exercises (chapter 4 for the ones who have the book). One exercise asks to disable the Alt+Enter functionality (toggle full screen mode) using IDXGIFactory::MakeWindowAssociation. However it toggle...
I think the problem is this. Since you create the device by yourself (and not through the factory) any calls made to the factory you created won't change anything. So either you: a) Create the factory earlier and create the device through it OR b) Retrieve the factory actually used to create the device through the code...
2,353,431
2,355,711
How can a script retain its values through different script loading in Lua?
My current problem is that I have several enemies share the same A.I. script, and one other object that does something different. The function in the script is called AILogic. I want these enemies to move independently, but this is proving to be an issue. Here is what I've tried. 1) Calling dofile in the enemy's constr...
The lua interpreter runs each line as its own chunk which means that locals have line scope, so the example code can't be run as-is. It either needs to be run all at once (no line breaks), without locals, or run in a do ... end block. As to the question in the OP. If you want to share the exact same function (that is t...
2,353,514
2,354,571
Implementing pImpl with minimal amount of code
What kind of tricks can be used to minimize the workload of implementing pImpl classes? Header: class Foo { struct Impl; boost::scoped_ptr<Impl> self; public: Foo(int arg); ~Foo(); // Public member functions go here }; Implementation: struct Foo::Impl { Impl(int arg): something(arg) {} // A...
Implementation of pimpl from Loki may be a good answer. See also a DDJ Article on this.
2,353,613
2,353,626
Best way to programatically check for existence of header file?
Is it just to test compile a simple program, with that header file #included in it? To better understand the compilation process I'm writing my own "configure", which tests for the existence of a few header and library files.
Yes, use the compiler to compile your simple test program. That's the best and easiest way to see if the compiler can find the header. If you hard code #include search paths you'll always have to modify and adapt for different compilers.
2,353,615
2,353,627
How to create a window based on only the size of the screen not including the windows border with C++/Windows?
When creating a window using CreateWindow(...), which requires the window width and height, I have to enter the values 656 and 516, instead of 640 and 480, so as to account for the windows border. I'm wondering if there is a way to create a window based only on the portion of the window not including the border, especi...
Have a look at AdjustWindowRectEx. You pass this function a rectangle containing the desired size of your windows' client area, and the window style flags, and it calculates how big to make the overall window so that the client area is the desired size.
2,353,633
2,353,969
Auto resizing of contents of QDockWidget
I've created a dock widget which contains a QTreeView. The size of the tree view remains static when the dock is resized. How can I get it to change it's size automatically to fill the dock area? I've created the dock widget using the designer and use multiple inheritance to include it in the main app. Inherited class:...
In the designer, right click on the dock widget, go to Layout, and click Layout Horizontally.
2,353,980
2,354,049
At what exact moment is a local variable allocated storage?
Suppose we have the following: void print() { int a; // declaration a = 9; cout << a << endl; } int main () { print(); } Is the storage for variable a allocated at the moment function print is called in main or is it when execution reaches the declaration inside the function?
This is very much compiler dependent under the covers, but logically the storage is assigned as soon as the variable is declared. Consider this simplistic C++ example: // junk.c++ int addtwo(int a) { int x = 2; return a + x; } When GCC compiles this, the following code is generated (; comments mine): .file ...
2,354,046
2,354,108
Variadic Macros : how to solve "too many actual parameters for macro.."
Ive been working on getting some of my code originally built on the mac to run under Visual Studio 2008 Express and have run into a weird problem with the variadic macros i use for my assert code : The macro is defined as : #define SH_ASSERT( assertID, exp, description, ... ) shAssertBasic( int(exp), assertID, descrip...
Change the argument order (put description with the ... part) to do something like this: #define SH_ASSERT( assertID, exp, ... ) shAssertBasic( int(exp), assertID, __LINE__, __FILE__, __VA_ARGS__ ) It should do the trick, You also have the possibility to suppress the warning in windows: #pragma warning (push) #pragma ...
2,354,103
2,354,116
typedef struct problem
I'm new in c++, how to made code below work (compile without a syntax error)? typedef struct _PersonA{ char name[128]; LPPersonB rel; }PersonA, *LPPersonA; typedef struct _PersonB{ char name[128]; LPPersonA rel; }PersonB, *LPPersonB; Please, don't ask me why I need to do it like this, because it is j...
You have to forward declare: struct _PersonB; typedef struct _PersonA{ char name[128]; _PersonB* rel; // no typedef }PersonA, *LPPersonA; typedef struct _PersonB{ char name[128]; LPPersonA rel; }PersonB, *LPPersonB; That said, this is very...ugly. Firstly, there is no need for the typedef in C++: struct PersonB; st...
2,354,138
2,354,192
Printing messages to console from C++ DLL
I have an application which uses C# for front end and C++ DLL for the logic part. I would want to print error messages on console screen from my C++ DLL even when the C# GUI is present. Please let me know how to do this. Thanks, Rakesh.
You can use AllocConsole() to create a console window and then write to standard output. If you are using C or C++ standard I/O functions (as opposed to direct win32 calls), there are some extra steps you need to take to associate the new console with the C/C++ standard library's idea of standard output. http://www.hal...
2,354,145
2,354,150
how to remove what setpixel put on the window?? (c++)
im using SetPixel to make stuff on my window which is the easyest because i only want to set one pixel at a time. SetPixel is great but i need to remove the color every time i update it, i could overwrite the color by black but.. it's a really big waste of time is there some way i can over write all of the colors to bl...
You should typically create a bitmap, lock it, set and unset its pixels directly - possibly by direct access rather than using API calls, if there are a lot of updates - unlock and then invalidate the window so that your paint handler can blit the bitmap later. If you want to restore pixels, you can keep two bitmaps an...
2,354,152
2,354,222
P/Invoke a purely C++ library?
Is it possible to P/Invoke a pure C++ library, or does it have to be wrapped in C?
C++ libraries can be P/invoked, but you'll need to use "depends" to find the mangled method names (names like "@0!classname@classname@zz") and for instance methods use "ThisCall" calling convention in the p/invoke and pass the reference of the instance as the first argument (you can store the result of the constructor ...
2,354,302
2,374,047
Static source code analysis with LLVM
I recently discover the LLVM (low level virtual machine) project, and from what I have heard It can be used to performed static analysis on a source code. I would like to know if it is possible to extract the different function call through function pointer (find the caller function and the callee function) in a progra...
You should take a look at Elsa. It is relatively easy to extend and lets you parse an AST fairly easily. It handles all of the parsing, lexing and AST generation and then lets you traverse the tree using the Visitor pattern. class CallGraphGenerator : public ASTVisitor { //... virtual bool visitFunction(Function ...
2,354,701
2,356,242
Deleting an std::map (Visual C++)
I have a pointer to a map that I am trying to delete (this map was allocated with new). This map is valid I think, when I hover on it while debugging, it shows pMap: [0]() .. When I try to delete this empty map, my app just quits and I get a First-chance exception at 0xsomelocation in myapp.exe: 0xsomenumber: The ob...
honestly i think we are going no where without real code posted. there might be 101 place where the code went wrong, not limited to the snippet posted. from the object insertion and removal implementation shown, there are no syntax nor logical error. if the source code was so valuable to be shared on here, try create a...
2,354,768
2,354,841
C++ equivalent for java final member data
First, my latest coding is Java, and I do not want to "write Java in C++". Here's the deal, I have to create an immutable class. It's fairly simple. The only issue is that getting the initial values is some work. So I cannot simply call initializes to initialize my members. So what's the best way of creating such a ...
C++ offers some nice mechanisms to make your class immutable. What you must do is: declare all your public (and maybe protected) methods const declare (but not define) operator= as private This will ensure that your objects cannot be modified after they have been created. Now, you can provide access to your now immut...
2,354,784
2,354,807
__attribute__((format(printf, 1, 2))) for MSVC?
With GCC, I can specify __attribute__((format(printf, 1, 2))) , telling the compiler that this function takes vararg parameters that are printf format specifiers. This is very helpful in the cases where I wrap e.g. the vsprintf function family. I can have extern void log_error(const char *format, ...) __attribute__((...
While GCC checks format specifiers when -Wformat is enabled, VC++ has no such checking, even for standard functions so there is no equivalent to this __attribute__ because there is no equivalent to -Wformat. I think Microsoft's emphasis on C++ (evidenced by maintaining ISO compliance for C++ while only supporting C89) ...
2,354,834
2,354,948
Alternative way to capture the screen? (c++, windows OS)
keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY, 0); keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); HBITMAP h; OpenClipboard(NULL); h = (HBITMAP)GetClipboardData(CF_BITMAP); CloseClipboard(); ... normally this works well. but if the foreground window changes and locks the clipboard t...
A simple scheme to capture the screen of monitor 1, that served me well but doesn't cover all corner cases: Get the screen device context. Create a device context compatible with the screen device context. Create a device independent bitmap (needed to get at the pixel data) that is as large as the screen resolution. S...
2,354,901
2,355,117
C++ Lib/Headers in Emacs
Where could I find C++ libraries in my emacs? I have already installed emacs on my computer and already using it lately. I just want to add boost libraries in emacs so I could use them.
Emacs is a text editor, it doesn't compile your code. It doesn't know (or need to know) anything about your libraries. However, there are commands for running the compiler from inside emacs, I've never done it myself, I use command line compiling and makefiles for bigger projects. I would write the program using the bo...
2,354,905
2,354,958
Reading from the serial port from C++ or Python on windows
I need to read the serial port from windows, using either Python or C++. What API/Library should I use? Can you direct me to a tutorial? Thanks!
In python you've excellent package pyserial that should be cross-platform (I've used only in GNU/Linux environment). Give it a look, it's very simple to use but very powerful! Of course examples are provided! By the way, if it can be useful here you can find a project of mine which use pyserial, as an extended example....
2,355,056
2,355,084
How to mix Qt, C++ and Obj-C/Cocoa
I have a pure C++/Qt project on a Mac, but I now find that I need to call a few methods only available in the Cocoa API. Following instructions listed here: http://el-tramo.be/blog/mixing-cocoa-and-qt I have a C++ class implementation in a ".m" file. As a test, my "foo.m" file contains the following code (relevant #inc...
It's compiling your .m file as Objective-C. You want it to be a .mm file for Objective-C++.
2,355,195
2,355,213
Check for derived type (C++)
How do I check at runtime if an object is of type ClassA or of derived type ClassB? In one case I have to handle both instances separately ClassA* SomeClass::doSomething ( ClassA* ) { if( /* parameter is of type base class */) { } else if { /* derived class */ ) { } } Maybe I could say that the derived c...
It's generally a very bad idea to switch on the exact type like that. By doing this, you are tightly coupling your method to derived classes of ClassA. You should use polymorphism. Introduce a virtual method in class A, override it in class B and simply call it in your method. Even if I was forced to handle the functio...
2,355,273
2,355,315
Overloading << operator and recursion
I tried the following code: #include <iostream> using std::cout; using std::ostream; class X { public: friend ostream& operator<<(ostream &os, const X& obj) { cout << "hehe"; // comment this and infinite loop is gone return (os << obj); } }; int main() { X x; cout << x; ...
Optimizer decides all your remaining activity has no effect and optimizes it away. Whether it's right or wrong is a different matter. In particular: X x; creates empty object "x" cout << x; calls: return (os << obj); which is appending empty object; the compiler notices 'os' hasn't grown any since the last call and ...
2,355,300
2,355,335
conditional compilation statement in limits.h
I am not able to understand the following statement from the file limits.h. What is the use of this statement and what does it accomplishes? /* If we are not using GNU CC we have to define all the symbols ourself. Otherwise use gcc's definitions (see below). */ #if !defined __GNUC__ || __GNUC__ < 2
It checks if your program is compiled by some other compiler than GCC, or some very old GCC version.
2,355,433
2,355,452
c++ variable initialization in a class to send it using mpi
I got stuck in a programming task. I want the elements of my stl vector to be placed in a contiguous memory to send it with MPI_Send() routine. here is an example: class Tem { //... private: vector<double> lenghtVector (4500);//this gives a compilation error but I need to have a fixed sized vector }; how can I h...
The elements of a vector are stored contiguously according to C++ Standard (23.2.4/1). To resize it you could use appropriate constructor in the initializer list of Tem class.: class Tem { Tem() : lenghtVector(4500) {}; private: vector<double> lenghtVector; };
2,355,454
2,355,494
Segmentation fault from std::_Rb_tree_const_iterator<Type>::operator++
I get a segmentation fault when iterating over a set. The stack trace points to std::_Rb_tree_const_iterator<Type>::operator++ std::_Rb_tree_increment() but I get nothing more informative. The iterator is over a set returned by a function for (FactSet::factset_iterator fact_it = (*binSet_it).getDependencyGraph().getE...
You don't want to be iterating over the return value like that. The middle termination condition is re-evaluated every iteration, so your end() will be for a different set every time, which means your iterator will never reach it. Cache the set in a local variable and then use the begin() and end() from that.
2,355,585
2,355,614
Error in using vector pointer in a function
I have this code, but it won't compile and i can't understand what is wrong - i guess the pointering of the vector is not correct. My idea was to collect some numbers in main() and store them in a vector and array, and then pass the memory address of them to a function, and using a pointers to print the data stored. I...
You should pass the vector by reference, not by pointer: void function(vector<int>& a, int *s) And then function(m, ...); Using [] on a pointer to a vector would certainly cause strange problems because it behaves as if a pointed to an array of std::vectors (while it actually only points to one). The vectors itself a...
2,355,592
2,359,728
typecasting to unsigned in C
int a = -534; unsigned int b = (unsigned int)a; printf("%d, %d", a, b); prints -534, -534 Why is the typecast not taking place? I expected it to be -534, 534 If I modify the code to int a = -534; unsigned int b = (unsigned int)a; if(a < b) printf("%d, %d", a, b); its not printing anything... after all a is less t...
First, you don't need the cast: the value of a is implicitly converted to unsigned int with the assignment to b. So your statement is equivalent to: unsigned int b = a; Now, an important property of unsigned integral types in C and C++ is that their values are always in the range [0, max], where max for unsigned int ...
2,355,816
2,355,850
Transferring signature of the method as template parameter to a class
I'd like to create a template interface for data-handling classes in my projects. I can write something like this: template <class T> class DataHandler { public: void Process(const& T) = 0; }; Then, suppose, I define a class this way: class MyClass: public DataHandler<int> { void Process(const int&) ...
Yep you can. But in C++03, you are bound to do copy/paste code for every number of parameters (not too bad, since here you won't need overloads for const/non-const etc. The constnes is already known!). template<typename FnType> struct parm; template<typename R, typename P1> struct parm<R(P1)> { typedef R ret_type; ...
2,355,876
2,398,248
Windows Spooler Events API doesn't generate events for network printers
the context i use Spooler Events API to capture events generated by the spooler when a user prints a document ie. FindFirstPrinterChangeNotification FindNextPrinterChangeNotification the problem When I print a document on the network printers from my machine no events are captured by the monitor (uses the functions a...
From the documentation: Note: In Windows XP with Service Pack 2 (SP2) and later, the Internet Connection Firewall (ICF) blocks printer ports by default, but an exception for File and Print Sharing can be enabled. If a user makes a printer connection to another machine, and the exception is not enabled, then the user w...
2,356,001
2,359,579
How to load a Windows icon using a pixel buffer?
I'm trying to create a Windows-compatible icon using a pixel buffer. The Surface class loads an image and saves it as an unsigned int array internally (0xRRGGBB). I'm trying to create an icon like so: Surface m_Test("Data/Interface/CursorTest.png"); HICON result = CreateIconFromResourceEx( (PBYTE)m_Test.GetBuffer(), ...
Use CreateIcon if you want to pass the raw bytes data from the AND and XOR mask. If instead you want to be able to use HBITMAPs, you can use CreateIconIndirect. Using this API, you can can even create icons with an alpha channel if you so desire.
2,356,116
2,356,205
Recommend crossplatform C++ UI and networking libraries
Things to take into consideration: - easy to use - fast - use underlying OS as much as feasable (like wxWidgets for UI) Ones I am leaning towards are wxWidgets for UI and Boost for networking - how do they compare to others?
I've had good look with wxWidgets on the front end and boost::asio on the network end. wxWidgets does have network classes built in, but you hit the wall quickly on them, and there's one or two big limitations. If you want to stay in the wx world, there's a package called wxCurl which is a fine package (I used it in t...
2,356,120
2,356,722
Documenting preprocessor defines in Doxygen
Is it possible to document preprocessor defines in Doxygen? I expected to be able to do it just like a variable or function, however the Doxygen output appears to have "lost" the documentation for the define, and does not contain the define itself either. I tried the following /**My Preprocessor Macro.*/ #define TEST_D...
Yes, it is possible. The Doxygen documentation says: To document global objects (functions, typedefs, enum, macros, etc), you must document the file in which they are defined. In other words, there must at least be a /*! \file */ or a /** @file */ line in this file. You can use @defgroup, @addtogroup, and @ing...
2,356,136
2,356,175
Can you create a start-up window in console program?
I want to a create dialog box like window before displaying the console window. I haven't actually tried anything yet but was just wondering if it can be displayed as a start-up window.
If you compile your win32 application as a console app, the console window will appear before you get a chance to do anything else. To get around this, you need to use a windows application - this won't display a console window at all by default. Some time after startup you can then call AllocConsole to create a consol...
2,356,168
2,356,393
Force GCC to notify about undefined references in shared libraries
I have a shared library that is linked with another (third-party) shared library. My shared library is then loaded using dlopen in my application. All this works fine (assuming files are in the proper path etc). Now, the problem is that I don't even need to specify to link against the third-party shared library when I ...
-Wl,--no-undefined linker option can be used when building shared library, undefined symbols will be shown as linker errors. g++ -shared -Wl,-soname,libmylib.so.5 -Wl,--no-undefined \ -o libmylib.so.1.1 mylib.o -lthirdpartylib
2,356,402
2,379,938
Unique controls identification
Is there any way to uniquely identify controls using Accessibility? Once control is identified - I should be able to get its current position on screen (rectangle). Tried to do this with IAccIdentity, but don't know what to do with that string of bytes which it returns - is there any way I can extract necessary informa...
Is this identity supposed to last across multiple invocations of the process? For the lifetime of a control its HWND is a unique identifer. OTOH, controls can be moved around the screen like any child window -- either moved relative to the parent or the parent may move taking the child with it. They can be created an...
2,356,450
2,356,748
Create C# bindings for complex system of C++ classes?
I have existing C++ lib containing many different classes working together. Some example usage should include something like passing an instance of one class to constructor/method of another class. I am planning to provide a C# binding for these C++ classes using C++/CLI therefore I don't have to port the whole C++ cod...
A lot of this is going to depend on the factoring of your classes. In the work that I do, I try to treat the C++ classes I model as hidden implementation details that I wrap into appropriate C++/CLI classes. For the most part, I can get away with that by having managed interfaces that are NOT particularly granular. W...
2,356,475
2,363,818
Getting shared_ptr refs to appear in doxygen collaboration diagrams
I've done enough Googling to know that if I have something like class SubObject { public: //blah blah blah }; class Aggregate { public: boost::shared_ptr<SubObject> m_ptr; }; I can get Doxygen to create the "correct" collaboration diagram if I have a dummy declaration like namespace boost { template<class T> cl...
Heh.... I feel stupid answering my own questions, but I figure this one out pretty much right after posting it: Put the code snippet namespace boost { template<class T> class shared_ptr { T *dummy; }; } in a header file, called something like "doxygen_dummy.h", and make sure it's included in your project's workspace o...
2,356,636
2,356,686
Reading binary data without reinterpret_cast
Just because I've never read binary files before I wrote a program that reads binary STL files. I use ifstreams read member that takes a char* a parameter. To cast my struct to a char* I use a reinterpret_cast. But as far as I remember every book about C++ I read said something like "don't use reinterpret_cast except y...
Well, that code looks fine. You are even caring about the padding issue. I don't see how you can avoid casting here. You can do this sequence: static_cast<char*>(static_cast<void*>(t)) But really, i don't do that in my code. It's just a more noisy way of doing a direct reinterpret_cast to char*. (See casting via void*...
2,356,778
2,357,003
Closing a QMainWindow on startup?
I have a Qt application that uses a QMainWindow-derived class for the main UI. On startup I want to make some security checks and, if they fail, display a message to the user and close the main window. Currently I make these checks in the QMainWindow constructor, but if I call the close method, nothing happens and th...
The event loop needs to be running before you can successfully close the main window. Since you probably first construct a window, and then start the event loop the close() call has no effect. Try the following solution instead: QTimer::singleShot(0, this, SLOT(close())); The QTimer::singleShot() will fire as soon as ...
2,357,091
2,357,105
thread-safety question
A simple situation here, If I got three threads, and one for window application, and I want them to quit when the window application is closed, so is it thread-safe if I use one global variable, so that three threads will quit if only the global variable is true, otherwise continue its work? Does the volatile help in ...
If you only want to "read" from the shared variable from the other threads, then it's ok in the situation you describe. Yes the volatile hint is required or the compiler might "optimize out" the variable. Waiting for the threads to finish (i.e. join) would be good too: this way, any clean-up (by the application) that s...
2,357,284
2,357,548
C++ concurrent associative containers?
I'm looking for a associative container of some sort that provides safe concurrent read & write access provided you're never simultaneously reading and writing the same element. Basically I have this setup: Thread 1: Create A, Write A to container, Send A over the network. Thread 2: Receive response to A, Read A from c...
The STL won't provide any solid guarantees about threads, since the C++ standard doesn't mention threads at all. I don't know about boost, but I'd be surprised if its containers made any concurrency guarantees. What about concurrent_hash_map from TBB? I found this in this related SO question.
2,357,596
2,357,637
HTTP stream server: threads?
I already wrote here about the http chat server I want to create: Alternative http port? This http server should stream text to every user in the same chat room on the website. The browser will stay connected and wait for further html code. (yes that works, the browser won't reject the connection). I got a new question...
I think easiest pattern for this simple app is to have pool of threads and then for each client pick available thread or make it wait until one becomes available. If you want serious understanding of http server architecture concepts google following: apache architecture nginx architecture
2,357,633
2,357,666
Windows Mobile development: C++ or C# -- which one is better? why?
While doing Windows Mobile development, which language should I use? C# or C++ or something else? Why one is better than others?
It depends what you're coding. Making native calls to the OS are possible via P/Invoke from C#, but extensive use is probably easier via native C++. You'll also require C++ for using some hardware that has not been wrapped by the Compact Framework. Most hardware (GPS, camera, etc.), is available via CF. If you're wor...
2,357,720
2,357,786
Network byte order conversion with "char"
I've always been taught that if an integer is larger than a char, you must solve the byte ordering problem. Usually, I'll just wrap it in the hton[l|s] and convert it back with ntoh[l|s]. But I'm confused why this doesn't apply to single byte characters. I'm sick of wondering why this is, and would love for a seasoned ...
What you are looking for is endianness. A big-endian architecture stores the bytes of a multibyte data type like so: while a little-endian architecture stores them in reverse: When data is transferred from one machine to another, the bytes of a single data type must be reordered to correspond with the endianness of t...
2,357,746
2,357,777
Interview question; what is the main theme of Effective C++?
I was asked the following question at a recent job interview: What do you think is the main theme / single word that sums up the Effective C++ series from Scott Meyers? What would be your answer to this question?
In one word it's Advice
2,357,798
2,357,902
C++ using precalculated limiters in for loops
In scripting languages like PHP having a for loop like this would be a very bad idea: string s("ABCDEFG"); int i; for( i = 0; i < s.length(); i ++ ) { cout << s[ i ]; } This is an example, i'm not building a program like this. (For the guys that feel like they have to tell me why this piece of code <insert bad thin...
It's all relative. PHP is interpreted, but if s.length drops into a compiled part of the PHP interpreter, it will not be slow. But even if it is slow, what about the time spent in s[i], and what about the time spent in cout <<? It's really easy to focus on loop overhead while getting swamped with other stuff. Like if y...
2,357,879
2,358,220
c++ d3d hooking - COM vtable
Trying to make a Fraps type program. See comment for where it fails. #include "precompiled.h" typedef IDirect3D9* (STDMETHODCALLTYPE* Direct3DCreate9_t)(UINT SDKVersion); Direct3DCreate9_t RealDirect3DCreate9 = NULL; typedef HRESULT (STDMETHODCALLTYPE* CreateDevice_t)(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusW...
The signature for the C interface of IDirect3D9::CreateDevice is: STDMETHOD(CreateDevice)( THIS_ UINT Adapter,D3DDEVTYPE DeviceType,HWND hFocusWindow, DWORD BehaviorFlags,D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface) PURE; Which expands to: typedef HRESU...
2,358,049
2,360,069
How do I rewrite equations from matlab for use in c++
I have derived and simplified an equation in Matlab and want to use it in a c++ program. Matlab likes to use powers, the ^ sign but c++ doesn't like it one bit. How can I get Matlab to rewrite the equation so that it outputs a c++ friendly equation?
If the equation is really so long that you don't want to go through by hand, one option you might consider for reformatting the equation to make it C++ friendly is to parse the text of the MATLAB code for the equation using the REGEXPREP function in MATLAB. Here's an example of how you could replace expressions of the ...
2,358,056
2,358,299
Is there a way to reduce ostringstream malloc/free's?
I am writing an embedded app. In some places, I use std::ostringstream a lot, since it is very convenient for my purposes. However, I just discovered that the performance hit is extreme since adding data to the stream results in a lot of calls to malloc and free. Is there any way to avoid it? My first thought was makin...
Well, Booger's solution would be to switch to sprintf(). It's unsafe, and error-prone, but it is often faster. Not always though. We can't use it (or ostringstream) on my real-time job after initialization because both perform memory allocations and deallocations. Our way around the problem is to jump through a lot of...
2,358,131
2,358,295
Mapping between two sets of classes
I have a requirement where in i have a set of classes and they have a one on one correspondence with another set of classes. Consider something like this a) template < class A > class Walkers { int walk( Context< A >* context ); }; The set of Context classes are not templates. They are individual classes. I nee...
I am not sure to understand what you want to do, what your requirements or goal are, but you could try to use traits to define the relationship: // direct mapping template <typename T> struct context_of; template <> struct context_of<A> { typedef ContextA type; }; // reverse mapping template <typename T> struct fr...