question_id
int64 25
74.7M
| answer_id
int64 332
74.7M
| title
stringlengths 20
150
| question
stringlengths 23
4.1k
| answer
stringlengths 20
4.1k
|
|---|---|---|---|---|
980,015
| 980,032
|
Variable initialising and constructors
|
I am currently taking a c++ course and trying to get a deep understanding of the whole thing.
I came up with some theories, it would be great if somebody could confirm them:
Every variable (local,global,staic,member and non-member) is guaranteed to have its ctor called before first use
The ctors of primitives like int are essentially no-ops, so we have explicitly assign a value, there is no default zero value.
the following classes are semantically the same (and should generate identical code)
class A
{
int n;
};
and
class A
{
int n;
public:
A() : n() {}
};
and
class A
{
int n;
public:
A() { n = int(); }
};
The variable n is in every case still uninitialized.
EDIT:
It seem that I absolutetly underestimated the complexity of this subject, most of my assumptions were wrong. Now Iam still trying to find out the basic rules of object initialisation.
|
You might find this interesting.
The difference between new Foo and new
Foo() is that former will be
uninitialized and the latter will be
default initialized (to zero) when Foo
is a POD type. So, when not using the
form with the parens, the member "a"
can contain garbage, but with the
parens "a" will always be initialized
to 0.
|
980,113
| 980,146
|
Symbian: Is it possible to get access to a list of contacts through an application?
|
There are at least two ways that I know of to write a Symbian application:
1. J2ME
2. A native application.
My question is, does the SDK/API for either of those methods (or any other method) grant me (at least) read-only access to contact information (names/numbers/etc) on the phone itself? Does this in any way depend on the specific phone being used?
|
In C++, you can use e.g. the Contacts Model API. There's an example in Forum Nokia.
In J2ME, you need to be working on a phone that has JSR-75. Again, there's an example in Forum Nokia.
|
980,355
| 980,371
|
How to hide an external program's windows programmatically?
|
I want to hide an external application, ie. not the current application. I want to give the title of the application and it will be hidden. How can I do this programmatically?
|
In general terms, you could call FindWindow to get the HWND of the window in question, then ShowWindow with SW_HIDE to hide the window.
|
980,438
| 980,473
|
Prevent misuse of logical operator instead of bitwise operators
|
In C++ it's possible to use a logical operator where a biwise operator was intended:
int unmasked = getUnmasked(); //some wide value
int masked = unmasked & 0xFF; // izolate lowest 8 bits
the second statement could be easily mistyped:
int masked = unmasked && 0xFF; //&& used instead of &
This will cause incorrect behaviour - masked will now be either 0 or 1 when it is inteded to be from 0 to 255. And C++ will not ever complain.
Is is possible to design code in such a way that such errors are detected at compiler level?
|
Ban in your coding standards the direct use of any bitwise operations in an arbitrary part of the code. Make it mandatory to call a function instead.
So instead of:
int masked = unmasked & 0xFF; // izolate lowest 8 bits
You write:
int masked = GetLowestByte(unmasked);
As a bonus, you'll get a code base which doesn't have dozens of error prone bitwise operations spread all over it.
Only in one place (the implementation of GetLowestByte and its sisters) you'll have the actual bitwise operations. Then you can read these lines two or three times to see if you blew it. Even better, you can unit test that part.
|
980,492
| 980,698
|
What is metaprogramming?
|
With reference to this question, could anybody please explain and post example code of metaprogramming? I googled the term up, but I found no examples to convince me that it can be of any practical use.
On the same note, is Qt's Meta Object System a form of metaprogramming?
jrh
|
Most of the examples so far have operated on values (computing digits of pi, the factorial of N or similar), and those are pretty much textbook examples, but they're not generally very useful. It's just hard to imagine a situation where you really need the compiler to comput the 17th digit of pi. Either you hardcode it yourself, or you compute it at runtime.
An example that might be more relevant to the real world could be this:
Let's say we have an array class where the size is a template parameter(so this would declare an array of 10 integers: array<int, 10>)
Now we might want to concatenate two arrays, and we can use a bit of metaprogramming to compute the resulting array size.
template <typename T, int lhs_size, int rhs_size>
array<T, lhs_size + rhs_size> concat(const array<T, lhs_size>& lhs, const array<T, rhs_size>& rhs){
array<T, lhs_size + rhs_size> result;
// copy values from lhs and rhs to result
return result;
}
A very simple example, but at least the types have some kind of real-world relevance. This function generates an array of the correct size, it does so at compile-time, and with full type safety. And it is computing something that we couldn't easily have done either by hardcoding the values (we might want to concatenate a lot of arrays with different sizes), or at runtime (because then we'd lose the type information)
More commonly, though, you tend to use metaprogramming for types, rather than values.
A good example might be found in the standard library. Each container type defines its own iterator type, but plain old pointers can also be used as iterators.
Technically an iterator is required to expose a number of typedef members, such as value_type, and pointers obviously don't do that. So we use a bit of metaprogramming to say "oh, but if the iterator type turns out to be a pointer, its value_type should use this definition instead."
There are two things to note about this. The first is that we're manipulating types, not values We're not saying "the factorial of N is so and so", but rather, "the value_type of a type T is defined as..."
The second thing is that it is used to facilitate generic programming. (Iterators wouldn't be a very generic concept if it didn't work for the simplest of all examples, a pointer into an array. So we use a bit of metaprogramming to fill in the details required for a pointer to be considered a valid iterator).
This is a fairly common use case for metaprogramming. Sure, you can use it for a wide range of other purposes (Expression templates are another commonly used example, intended to optimize expensive calculations, and Boost.Spirit is an example of going completely overboard and allowing you to define your own parser at compile-time), but probably the most common use is to smooth over these little bumps and corner cases that would otherwise require special handling and make generic programming impossible.
|
980,565
| 980,857
|
Will bit-shift by zero bits work correctly?
|
Say I have a function like this:
inline int shift( int what, int bitCount )
{
return what >> bitCount;
}
It will be called from different sites each time bitCount will be non-negative and within the number of bits in int. I'm particularly concerned about call with bitCount equal to zero - will it work correctly then?
Also is there a chance that a compiler seeing the whole code of the function when compiling its call site will reduce calls with bitCount equal to zero to a no-op?
|
It is certain that at least one C++ compiler will recognize the situation (when the 0 is known at compile time) and make it a no-op:
Source
inline int shift( int what, int bitcount)
{
return what >> bitcount ;
}
int f() {
return shift(42,0);
}
Compiler switches
icpc -S -O3 -mssse3 -fp-model fast=2 bitsh.C
Intel C++ 11.0 assembly
# -- Begin _Z1fv
# mark_begin;
.align 16,0x90
.globl _Z1fv
_Z1fv:
..B1.1: # Preds ..B1.0
movl $42, %eax #7.10
ret #7.10
.align 16,0x90
# LOE
# mark_end;
.type _Z1fv,@function
.size _Z1fv,.-_Z1fv
.data
# -- End _Z1fv
.data
.section .note.GNU-stack, ""
# End
As you can see at ..B1.1, Intel compiles "return shift(42,0)" to "return 42."
Intel 11 also culls the shift for these two variations:
int g() {
int a = 5;
int b = 5;
return shift(42,a-b);
}
int h(int k) {
return shift(42,k*0);
}
For the case when the shift value is unknowable at compile time ...
int egad(int m, int n) {
return shift(42,m-n);
}
... the shift cannot be avoided ...
# -- Begin _Z4egadii
# mark_begin;
.align 16,0x90
.globl _Z4egadii
_Z4egadii:
# parameter 1: 4 + %esp
# parameter 2: 8 + %esp
..B1.1: # Preds ..B1.0
movl 4(%esp), %ecx #20.5
subl 8(%esp), %ecx #21.21
movl $42, %eax #21.10
shrl %cl, %eax #21.10
ret #21.10
.align 16,0x90
# LOE
# mark_end;
... but at least it's inlined so there's no call overhead.
Bonus assembly: volatile is expensive. The source ...
int g() {
int a = 5;
volatile int b = 5;
return shift(42,a-b);
}
... instead of a no-op, compiles to ...
..B3.1: # Preds ..B3.0
pushl %esi #10.9
movl $5, (%esp) #12.18
movl (%esp), %ecx #13.21
negl %ecx #13.21
addl $5, %ecx #13.21
movl $42, %eax #13.10
shrl %cl, %eax #13.10
popl %ecx #13.10
ret #13.10
.align 16,0x90
# LOE
# mark_end;
... so if you're working on a machine where values you push on the stack might not be the same when you pop them, well, this missed optimization is likely the least of your troubles.
|
980,573
| 980,911
|
Compiler support for upcoming C++0x
|
Is there a compiler that has good support for the new C++0x?
I use GCC but unfortunately the current version 4.4 has a poor support for the new features.
|
The only compiler that has an implementation of concepts is conceptgcc (and even that is incomplete - but it is good enough to get a good feel for the feature).
Visual C++ 2010 Beta has some useful C++0x support - you can play with lambdas, rvalue references, auto, decltype.
Comeau C++ or the EDG based compilers are surprisingly not as advanced I would have expected them to be in their implementation of C++0x.
GCC 4.4 (variadic templates, initializer lists, inline namespaces, autor, decltype) probably has the most features implemented out of any of the other compilers, but is lagging in concepts and lambdas (separate branch development is ongoing).
|
980,881
| 981,357
|
Passing multi-param function into a macro
|
Why does this not compile on VC 2005?
bool isTrue(bool, bool) { return true; }
void foo();
#define DO_IF(condition, ...) if (condition) foo(__VA_ARGS__);
void run()
{
DO_IF(isTrue(true, true)); // error C2143: syntax error : missing ')' before 'constant'
}
Running this through the preprocessor alone outputs:
bool isTrue(bool, bool) { return true; }
void foo();
void run()
{
if (isTrue(true true)) foo();;
}
Notice the missing comma in the penultimate line.
Last Edit:
LOL!
bool isTrue(bool, bool) { return true; }
void foo();
#define DO_IF(condition, ...) if (condition) { foo(__VA_ARGS__); }
void run()
{
DO_IF(isTrue(true ,, true)); // ROTFL - This Compiles :)
}
|
Macros with indefinite numbers of arguments don't exist in the 1990 C standard or the current C++ standard. I think they were introduced in the 1999 C standard, and implementations were rather slow to adopt the changes from that standard. They will be in the forthcoming C++ standard (which I think is likely to come out next year).
I haven't bothered to track C99 compliance in Visual Studio, mostly because the only things I use C for anymore require extreme portability, and I can't get that with C99 yet. However, it's quite likely that VS 2005 lacked parts of C99 that VS2008 had.
Alternately, it could be that you were compiling the program as C++. Check your compiler properties.
|
980,966
| 981,581
|
Physics toolkit portability
|
Summary:
Have you ever made an interface between two -- or better yet even more -- different physics toolkits? For a online game (or at least with network physics)? How did it turn out? Lessons learned? Is it better to rewrite large chunks of code elsewhere, or did the investment pay off?
Bloat:
I'm using ODE physics toolkit for my indie game engine, but through a facade wrapper. The original idea was to be able to easily port to another physics toolkit (Havok, Bullet, whatever) if/when necessary/possible. This seemed like a good idea for starters, but now it's starting to look like there's a quite a few devils in the nitty-gritty details. Such as the need for individual per-root-object gravitation (which isn't even currently supported by ODE). Or callbacks when an object/island is disabled (not supported by ODE either).
The fact that Havok (which I really know nothing about) constantly grows with new tools and toolkits makes me fear that one eventually ends up with a framework rather than a toolkit. And that would not be good for portability, but perhaps my fears are totally unfounded.
|
Take a look at the Physics Abstraction Layer (PAL) project hosted on SourceForge.net. They claim to support the following physics engines in addition to numerous other capabilities:
Box2D (experimental)
Bullet
Havok (experimental)
IBDS (experimental)
JigLib
Newton
ODE
OpenTissue (experimental)
PhysX (a.k.a Novodex, Ageia PhysX, nVidia PhysX)
Simple Physics Engine (experimental)
Tokamak
TrueAxis
Perhaps the developer, Adrian Boeing, could provide with further insight if you contact him directly.
|
981,087
| 981,429
|
Is there a QPointer specialization for boost::bind
|
boost::bind handles boost::shared_ptr the same way as raw pointers.
QObject * object(new QObject);
boost::shared_ptr<QObject> sharedObject(new QObject);
bind(&QObject::setObjectName, object, _1)( "name" );
bind(&QObject::setObjectName, sharedObject, _1)( "name" );
I would love to have a boost::bind that handles QPointers as raw pointers pointer.
QPointer<QObject> guardedObject(new QObject);
// i want to write it like this
bind(&QObject::setObjectName, guardedObject, _1)( "name" );
//now i have to do it like this
bind(&QObject::setObjectName, bind(&QPointer<QObject>::data, guardedObject), _1)( "name" );
Is there anyone who has made the specialization for QPointer?
If not do you know where to start or what needs to be specialized, so I can do it myself.
|
Adding this overload of the get_pointer function should do the trick:
namespace boost {
template<typename T> T * get_pointer(QPointer<T> const& p)
{
return p;
}
}
|
981,139
| 981,169
|
Visual Studio (C++) IntelliSense with parentheses
|
If I have a vector toto, when I write toto.s , IntelliSense gives me toto.size but I would like toto.size(). How to force IntelliSense to give me parentheses?
|
I don't think that is possible using the visual studio's intellisense. However check out this very good third party tool which can do that: Visual Assist
|
981,147
| 981,548
|
How to change Qt applications's dock icon at run-time in MacOS?
|
I need to change my Qt application's dock icon (in MacOS X) in run-time according to some conditions.
I've found several recipes on trolltech.com:
QApplication::setIcon()
setApplicationIcon()
qt_mac_set_app_icon()
but none of it works: there is no such methods/functions in Qt 4.5.
How can I change my application's dock icon and what icon formats can I use?
Thank you.
|
In Qt 4.5 the methods you are searching for are called
QApplication::setWindowIcon(const QIcon &)
or
QWidget::setWindowIcon(const QIcon &).
You can use every image format for icons that Qt supports (e.g. BMP, GIF, JPG, PNG, TIFF, XPM, ...).
Maybe you want to have a look at Qt's documentation at http://doc.qtsoftware.com/4.5/index.html or use the Qt Assistant.
Hope that helps you.
|
981,186
| 17,510,460
|
Chaining iterators for C++
|
Python's itertools implement a chain iterator which essentially concatenates a number of different iterators to provide everything from single iterator.
Is there something similar in C++ ? A quick look at the boost libraries didn't reveal something similar, which is quite surprising to me. Is it difficult to implement this functionality?
|
Came across this question while investigating for a similar problem.
Even if the question is old, now in the time of C++ 11 and boost 1.54 it is pretty easy to do using the Boost.Range library. It features a join-function, which can join two ranges into a single one. Here you might incur performance penalties, as the lowest common range concept (i.e. Single Pass Range or Forward Range etc.) is used as new range's category and during the iteration the iterator might be checked if it needs to jump over to the new range, but your code can be easily written like:
#include <boost/range/join.hpp>
#include <iostream>
#include <vector>
#include <deque>
int main()
{
std::deque<int> deq = {0,1,2,3,4};
std::vector<int> vec = {5,6,7,8,9};
for(auto i : boost::join(deq,vec))
std::cout << "i is: " << i << std::endl;
return 0;
}
|
981,306
| 981,356
|
How to detect whether Windows is shutting down or restarting
|
I know that when Windows is shutting down, it sends a WM_QUERYENDSESSION message to each application. This makes it easy to detect when Windows is shutting down. However, is it possible to know if the computer going to power-off or is it going to restart after Windows has shutdown.
I am not particularly hopeful, considering the documentation at MSDN has this to say about WM_QUERYENDSESSION: "...it is not possible to determine which event is occurring," but the cumulative cleverness of stackoverflow never ceases to amaze me.
|
From here:
You can read the DWORD value from
"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shutdown
Setting" to determine what the user
last selected from the Shut Down
dialog.
A bit of a roundabout solution, but it should do the trick.
|
981,400
| 981,435
|
What happens if a throw; statement is executed outside of catch block?
|
In C++ throw; when executed inside a catch block rethrows the currently caught exception outside the block.
In this answer an idea of exception dispatcher is brought up as a solution to reducing code duplication when using complex exception handling often:
try {
CodeThatMightThrow();
} catch(...) {
ExceptionHandler();
}
void ExceptionHandler()
{
try {
throw;
} catch( FileException* e ) {
//do handling with some complex logic
delete e;
} catch( GenericException* e ) {
//do handling with other complex logic
delete e;
}
}
Throwing a pointer or a value doesn't make any difference so it's out of the question.
What happens if ExceptionHandler() is called not from a catch block?
I tried this code with VC7:
int main( int, char** )
{
try {
throw;
} catch( ... ) {
MessageBox( 0, "", "", 0 );
}
return 0;
}
First it causes the debugger to indicate a first-chance exception, then immediately an unhandled exception. If I run this code outside the debugger the program crashes the same way as if abort() has been called.
What is the expected behaviour for such situations?
|
From the Standard, 15.1/8
If no exception is presently being handled, executing a throw-expression with no operand calls std::terminate().
|
981,787
| 983,153
|
Good portable SIMD library
|
can anyone recommend portable SIMD library that provides a c/c++ API, works on Intel and AMD extensions and Visual Studio, GCC compatible. I'm looking to speed up things like scaling a 512x512 array of doubles. Vector dot products, matrix multiplication etc.
So far the only one I found is:
http://simdx86.sourceforge.net/ but as the very first page says it doesn't compile on visual studio.
There's also Intel IPP which doesn't work on AMD from what I gather. And there's Framewave from AMD, but I was having some problems compiling and linking their library and their forums are completely dead. Anyone managed to use Framewave anywhere?
Thanks.
|
Since you mention high-level operations on matrices and vectors, ATLAS, Intel's MKL, PLASMA, and FLAME may be of interest.
Some C++ matrix math libraries include uBLAS from Boost, Armadillo, Eigen, IT++, and Newmat. The POOMA library probably also includes some of these things. This question also refers to MTL.
If you're looking for lower-level portability primitives, a colleague of mine has developed a wrapper around SSE2, Altivec, VSX, Larrabee, and Cell SPE vector operations. It can be found in our source repository, but its licensing (academic) may not be appropriate if you want to distribute it as part of your work. It is also still under significant development to cover the range of application needs that it's targeted at.
|
982,081
| 1,473,602
|
C++/C# callback continued
|
After asking this question and apparently stumping people, how's about this for a thought-- could I give a buffer from a C# application to a C++ dll, and then have a timing event in C# just copy the contents of the buffer out? That way, I avoid any delays caused by callback calling that apparently happen. Would that work, or does marshalling prevent that kind of buffer access? Or would I have to go to unsafe mode, and if I do or don't, what would be the magic words to make it work?
To recap from that other question:
I have a driver written in C++ and an app written in C#.
I need to get data from the driver in a preview-style manner.
C++ applications interact with the C++ dll just fine; the C# app has a large delay for copying the data over.
The delay does not appear to be caused by release/debug differences on the C# side
I need to get around the delay. Could this proposed buffer scheme work? Could a C# app consume from a buffer written to by a C++ dll, or do I need to do something else?
|
As I said in the other thread, it seems the delay was entirely on the C++ side, so no amount of finagling on my end was going to fix the problem.
|
982,129
| 982,179
|
What does __sync_synchronize do?
|
I saw an answer to a question regarding timing which used __sync_synchronize().
What does this function do?
And when is it necessary to be used?
|
It is a atomic builtin for full memory barrier.
No memory operand will be moved across the operation, either forward
or backward. Further, instructions will be issued as necessary to
prevent the processor from speculating loads across the operation and
from queuing stores after the operation.
Check details on the link above.
|
982,266
| 982,283
|
Launch IE from a C++ program
|
I have a program written in C++ which does some computer diagnostics. Before the program exits, I need it to launch Internet Explorer and navigate to a specific URL. How do I do that from C++?
Thanks.
|
Here you are... I am assuming that you're talking MSVC++ here...
// I do not recommend this... but will work for you
system("\"%ProgramFiles%\\Internet Explorer\\iexplore.exe\"");
// I would use this instead... give users what they want
#include <windows.h>
void main()
{
ShellExecute(NULL, "open", "http://stackoverflow.com/questions/982266/launch-ie-from-a-c-program", NULL, NULL, SW_SHOWNORMAL);
}
|
982,421
| 982,775
|
How to write portable floating point arithmetic in c++?
|
Say you're writing a C++ application doing lots of floating point arithmetic. Say this application needs to be portable accross a reasonable range of hardware and OS platforms (say 32 and 64 bits hardware, Windows and Linux both in 32 and 64 bits flavors...).
How would you make sure that your floating point arithmetic is the same on all platforms ? For instance, how to be sure that a 32 bits floating point value will really be 32 bits on all platforms ?
For integers we have stdint.h but there doesn't seem to exist a floating point equivalent.
[EDIT]
I got very interesting answers but I'd like to add some precision to the question.
For integers, I can write:
#include <stdint>
[...]
int32_t myInt;
and be sure that whatever the (C99 compatible) platform I'm on, myInt is a 32 bits integer.
If I write:
double myDouble;
float myFloat;
am I certain that this will compile to, respectively, 64 bits and 32 bits floating point numbers on all platforms ?
|
Non-IEEE 754
Generally, you cannot. There's always a trade-off between consistency and performance, and C++ hands that to you.
For platforms that don't have floating point operations (like embedded and signal processing processors), you cannot use C++ "native" floating point operations, at least not portably so. While a software layer would be possible, that's certainly not feasible for this type of devices.
For these, you could use 16 bit or 32 bit fixed point arithmetic (but you might even discover that long is supported only rudimentary - and frequently, div is very expensive). However, this will be much slower than built-in fixed-point arithmetic, and becomes painful after the basic four operations.
I haven't come across devices that support floating point in a different format than IEEE 754. From my experience, your best bet is to hope for the standard, because otherwise you usually end up building algorithms and code around the capabilities of the device. When sin(x) suddenly costs 1000 times as much, you better pick an algorithm that doesn't need it.
IEEE 754 - Consistency
The only non-portability I found here is when you expect bit-identical results across platforms. The biggest influence is the optimizer. Again, you can trade accuracy and speed for consistency. Most compilers have a option for that - e.g. "floating point consistency" in Visual C++. But note that this is always accuracy beyond the guarantees of the standard.
Why results become inconsistent?
First, FPU registers often have higher resolution than double's (e.g. 80 bit), so as long as the code generator doesn't store the value back, intermediate values are held with higher accuracy.
Second, the equivalences like a*(b+c) = a*b + a*c are not exact due to the limited precision. Nonetheless the optimizer, if allowed, may make use of them.
Also - what I learned the hard way - printing and parsing functions are not necessarily consistent across platforms, probably due to numeric inaccuracies, too.
float
It is a common misconception that float operations are intrinsically faster than double. working on large float arrays is faster usually through less cache misses alone.
Be careful with float accuracy. it can be "good enough" for a long time, but I've often seen it fail faster than expected. Float-based FFT's can be much faster due to SIMD support, but generate notable artefacts quite early for audio processing.
|
982,529
| 982,650
|
Old issues of "C++ Report"?
|
I used to receive "C++ Report" magazine (along with "C/C++ User's Journal"), both now defunct.
For the longest time, I would cart around the issues, from move to move. Regrettably, a few years ago I decided to stop carting them around & I recycled them.
There was a lot of wisdom in those pages, and now I find myself wishing I could bring them into the workplace so that others can peruse them. A lot of what I know & use came from those pages.
Does anyone know if back issues, or a DVD/CD-rom compilation of "C++ Report" exists?
I know for example that Dr. Dobbs has a DVD with 14 years of back issues of "C/C++ User's Journal". I'd love to find something similar (or the dead tree equivalent) for "C++ Report".
(At the risk of sounding like a jerk, I'm not looking for a few articles by 1 or 2 authors from googling, I'm looking for the "whole shebang").
|
The only thing I can think of is the book "C++ Gems", which is basically 42 articles from the first 7 years, published in 1996. I got a copy from a used bookstore a few years ago.
It would be nice to have a dvd - I have the Dr. Dobbs and C/C++ UJ ones. The indexing seems a little flakey, but everything is there if you look hard enough.
|
982,702
| 982,724
|
Is there a way to simulate Windows input with C++?
|
I'm wondering if its possible to make a program in C++ that can "press" keys, or make the computer think certain keys have been pressed, and do things like make a program that "plays" games, or automatically enter some long and obscure button sequence that no one could remember.
(I can't think of any right now, but savegame passwords might be an example, especially when you can't just type it, but have to move a cursor to the letter you want, then press enter or something).
Just wondering.
|
http://msdn.microsoft.com/en-us/library/8c6yea83(VS.85).aspx
|
982,808
| 982,941
|
C++ SFINAE examples?
|
I want to get into more template meta-programming. I know that SFINAE stands for "substitution failure is not an error." But can someone show me a good use for SFINAE?
|
Heres one example (from here):
template<typename T>
class IsClassT {
private:
typedef char One;
typedef struct { char a[2]; } Two;
template<typename C> static One test(int C::*);
// Will be chosen if T is anything except a class.
template<typename C> static Two test(...);
public:
enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 };
enum { No = !Yes };
};
When IsClassT<int>::Yes is evaluated, 0 cannot be converted to int int::* because int is not a class, so it can't have a member pointer. If SFINAE didn't exist, then you would get a compiler error, something like '0 cannot be converted to member pointer for non-class type int'. Instead, it just uses the ... form which returns Two, and thus evaluates to false, int is not a class type.
|
982,829
| 982,861
|
Shifting from .NET to Win32 development
|
I have been a .NET developer since I started coding. I would like to learn Win32 programming. Need advice on where to start. What are the best resources /books for learining Win32 programming. I know a bit 'college C++'.
|
If you are interested in UI development, the best book for direct Win32 development in C or C++ (no MFC) is Programming Windows by Charles Petzold
For other sorts of Win32 development, such as threading, memory, DLL's, etc., Windows via C/C++ by Jeffrey Richter is a great book.
For general Windows architecture, Windows Internals by David Solomon and Mark Russinovich is a great resource.
|
982,963
| 982,999
|
Is there any overhead to declaring a variable within a loop? (C++)
|
I am just wondering if there would be any loss of speed or efficiency if you did something like this:
int i = 0;
while(i < 100)
{
int var = 4;
i++;
}
which declares int var one hundred times. It seems to me like there would be, but I'm not sure. would it be more practical/faster to do this instead:
int i = 0;
int var;
while(i < 100)
{
var = 4;
i++;
}
or are they the same, speedwise and efficiency-wise?
|
Stack space for local variables is usually allocated in function scope. So no stack pointer adjustment happens inside the loop, just assigning 4 to var. Therefore these two snippets have the same overhead.
|
983,244
| 983,259
|
Is this deallocation correct?
|
I've a 3x3 2D dynamic array allocated as below:
int** matrix = new int* [3];
matrix[0] = new int [3*3];
for (int i = 1; i < 3; ++i)
matrix[i] = matrix[i-1] + 3;
How should I deallocate it? Is this correct:
delete [] matrix;
delete [] matrix[0];
Or should I also delete matrix[1], [2]
|
The way you have it, you should :
delete [] matrix[0];
delete [] matrix;
But this is a very unconventional way of allocating a dynamic 2D array. Normally you allocate an array of pointers, and then you allocate an array of your actual type for every row (column).
// allocate
int **matrix = new int*[3];
for(int i = 0; i < 3; ++i)
matrix[i] = new int[3];
// deallocate
for(int i = 0; i < 3; ++i)
delete [] matrix[i];
delete [] matrix;
|
983,305
| 983,343
|
Can I use interlocked operations to update multiple values to avoid locking a critical section/mutex?
|
I have a multithreaded application (C++) where I need to increment/change a series of values.
If I use a series of Interlocked operations, are they considered to be a single atomic operation ? Like in this example:
InterlockedIncrement(&value1);
InterlockedIncrement(&value2);
InterlockedExchange(&oldValue, newValue);
Or it would be better to us a lock to perform the synchronization ? Like this:
EnterCriticalSection(&cs);
value1++;
value2++;
oldValue = newValue;
LeaveCriticalSection(&cs);
I think a lock is required, but I'm not sure... it's very important that all the values to be either in the old state, or in the new one, together.
|
InterlockedIncrement itself is an atomic operation but series of InterLockedIncrement are not atomic together. If your requirement is to get the atomicity for series of operation then you can use critical section.
|
983,310
| 983,329
|
Calling a method from another method in the same class in C++
|
I wrote a method (that works fine) for a() in a class. I want to write another method in that class that calls the first method so:
void A::a() {
do_stuff;
}
void A::b() {
a();
do_stuff;
}
I suppose I could just rewrite b() so b(A obj) but I don't want to. In java can you do something like this.a().
I want to do obj.b() where obj.a() would be called as a result of obj.b().
|
That's exactly what you are doing.
|
983,376
| 983,524
|
recursive folder scanning in c++
|
I want to scan a directory tree and list all files and folders inside each directory. I created a program that downloads images from a webcamera and saves them locally. This program creates a filetree based on the time the picture is downloaded. I now want to scan these folders and upload the images to a webserver but I´m not sure how I can scan the directories to find the images.
If anyone could post some sample code it would be very helpful.
edit: I´m running this on an embedded linux system and don´t want to use boost
|
See man ftw for a simple "file tree walk". I also used fnmatch in this example.
#include <ftw.h>
#include <fnmatch.h>
static const char *filters[] = {
"*.jpg", "*.jpeg", "*.gif", "*.png"
};
static int callback(const char *fpath, const struct stat *sb, int typeflag) {
/* if it's a file */
if (typeflag == FTW_F) {
int i;
/* for each filter, */
for (i = 0; i < sizeof(filters) / sizeof(filters[0]); i++) {
/* if the filename matches the filter, */
if (fnmatch(filters[i], fpath, FNM_CASEFOLD) == 0) {
/* do something */
printf("found image: %s\n", fpath);
break;
}
}
}
/* tell ftw to continue */
return 0;
}
int main() {
ftw(".", callback, 16);
}
(Not even compile-tested, but you get the idea.)
This is much simpler than dealing with DIRENTs and recursive traversal yourself.
For greater control over traversal, there's also fts. In this example, dot-files (files and directories with names starting with ".") are skipped, unless explicitly passed to the program as a starting point.
#include <fts.h>
#include <string.h>
int main(int argc, char **argv) {
char *dot[] = {".", 0};
char **paths = argc > 1 ? argv + 1 : dot;
FTS *tree = fts_open(paths, FTS_NOCHDIR, 0);
if (!tree) {
perror("fts_open");
return 1;
}
FTSENT *node;
while ((node = fts_read(tree))) {
if (node->fts_level > 0 && node->fts_name[0] == '.')
fts_set(tree, node, FTS_SKIP);
else if (node->fts_info & FTS_F) {
printf("got file named %s at depth %d, "
"accessible via %s from the current directory "
"or via %s from the original starting directory\n",
node->fts_name, node->fts_level,
node->fts_accpath, node->fts_path);
/* if fts_open is not given FTS_NOCHDIR,
* fts may change the program's current working directory */
}
}
if (errno) {
perror("fts_read");
return 1;
}
if (fts_close(tree)) {
perror("fts_close");
return 1;
}
return 0;
}
Again, it's neither compile-tested nor run-tested, but I thought I'd mention it.
|
983,460
| 4,566,154
|
C++ formatted input: how to 'skip' tokens?
|
Suppose I have an input file in this format:
VAL1 VAL2 VAL3
VAL1 VAL2 VAL3
I'm writing a program that would be interested only in VAL1 and VAL3. In C, if i wanted to 'skip' the second value, I'd do as follows:
char VAL1[LENGTH]; char VAL3[LENGTH];
FILE * input_file;
fscanf(input_file, "%s %*s %s", VAL1, VAL3);
Meaning, I'd use the "%*s" formatter to make fscanf() read this token and skip it. How do I do this with C++'s cin? Is there a similar command? Or do I have to read to a dummy variable?
Thanks in advance.
|
The C++ String Toolkit Library (StrTk) has the following solution to your problem:
#include <string>
#include <deque>
#include "strtk.hpp"
int main()
{
struct line_type
{
std::string val1;
std::string val3;
};
std::deque<line_type> line_list;
const std::string file_name = "data.txt";
strtk::for_each_line(file_name,
[&line_list](const std::string& line)
{
strtk::ignore_token ignore;
line_type temp_line;
const bool result = strtk::parse(line,
" ",
temp_line.val1,
ignore,
temp_line.val3);
if (!result) return;
line_list.push_back(temp_line);
});
return 0;
}
More examples can be found Here
|
983,728
| 983,846
|
C++ - Convert FILE* to CHAR*
|
I found a C++ source file which calculates expressions from a command line argument (argv[1]), however I now want to change it to read a file.
double Utvardering(char* s) {
srcPos = s;
searchToken();
return PlusMinus();
}
int main(int argc, char* argv[]) {
if (argc > 1) {
FILE* fFile = fopen(argv[1], "r");
double Value = Utvardering(fopen(argv[1], "r"));
cout << Value << endl;
}else{
cout << "Usage: " << argv[0] << " FILE" << endl;
}
cin.get();
return 0;
}
However the Utvardering function requires a char* parameter. How can I convert the data read from a file, fopen to a char*?
|
The function fopen just opens a file. To get a string from there, you need to read the file. There are different ways to to this. If you know the max size of your string in advance, this would do:
const int MAX_SIZE = 1024;
char buf[MAX_SIZE];
if (!fgets(buf, MAX_SIZE, fFile) {
cerr << "Read error";
exit(1);
}
double Value = Utvardering(buf);
Note: this method is typical for C, not for C++. If you want more idiomatic C++ code, you can use something like this (instead of FILE and fopen):
ifstream in;
in.open(argv[1]);
if (!in) { /* report an error */ }
string str;
in >> str;
|
983,762
| 983,914
|
Fully Featured C++ Assert Dialog?
|
I'm looking for a good, fully featured C++ assert macro for VisualStudio. With features like be able to ignore an assert once or always, to be able to break exactly where the macro gets called (and not inside macro code), and getting a stack trace.
Before I have to hunker down and write one, I figured I'd ask if anyone knows about any available ones out there.
Any suggestions?
Thanks!
|
See Charles Nicholson's blog for a good discussion of an assert macro. His solution breaks the debugger at the faulting line of code (and not inside the failed assertion handler), and he also solves the problem of not getting warnings about unused variables when assertions are disabled without incurring any runtime costs.
|
983,997
| 984,016
|
I have an unintended delay in playing a Mix_Chunk
|
So I am trying to learn SDL and creating a small game. When the user presses the space bar, it should play a sound. This works, but the sound takes about .5 seconds to play... How would I fix this? I've checked the actual file to see if the delay was just part of it, and that turned out to not be the case.
SDL with c++ on win vista.
Here's some relevant code:
...
Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 )
...
main()
{
...
Mix_PlayMusic( BG_Music, 0 ); //background music
while( quit == false )
{
fps.start();
fire.handleInput( event, ship.get_x_pos() );
...
}
the handle input function:
void lasersC::handleInput( SDL_Event &event, int x )
{
Uint8 *keystates = SDL_GetKeyState( NULL );
if ( keystates[ SDLK_SPACE ] && delay == 0)
{
Mix_PlayChannel(-1, laser, 0);
fired * F = new fired( NULL, S_HEIGHT - 50, x + 20 );
F->shot = lasers;
F->y_pos = S_HEIGHT - 50;
F->x_pos = x + 20;
weps.push_back( F );
delay = 10;
}
}
If more is needed, let me know.
|
There is usually a check for DirectX headers when compiling SDL (apparently)
Can you try to recompile with DirectX support?
Also, how much buffering are you enforcing at the client side? It may be a problem with that.
EDIT - After the comments below:
Try to increase the size of your buffer.
What I mean by recompiling with DirectX support is, try to include headers from the following source so that SDL skips checking for them.
http://www.libsdl.org/extras/win32/common/directx-devel.tar.gz
|
983,999
| 984,054
|
Simple 3x3 matrix inverse code (C++)
|
What's the easiest way to compute a 3x3 matrix inverse?
I'm just looking for a short code snippet that'll do the trick for non-singular matrices, possibly using Cramer's rule. It doesn't need to be highly optimized. I'd prefer simplicity over speed. I'd rather not link in additional libraries.
|
Why don't you try to code it yourself? Take it as a challenge. :)
For a 3×3 matrix
(source: wolfram.com)
the matrix inverse is
(source: wolfram.com)
I'm assuming you know what the determinant of a matrix |A| is.
Images (c) Wolfram|Alpha and
mathworld.wolfram (06-11-09,
22.06)
|
984,107
| 984,124
|
Returning STL lists as argument
|
I have a function that reads lines from a log file, converts these lines to a certain class and returns a STL list of instances of this class.
How should I declare this function so that the whole list is NOT copied when attributing it to the caller?
Without loss of generality, assume:
list<Request> requests = log_manipulator.getAsRequestList();
How should I declare getAsRequestList()? Should I return a reference to a list or just return a list?
This is a serious issue because in this particular assignment the lists will contain circa 1.5M elements, and thus a mistake like that can screw up memory usage.
|
Returning a reference is not advisable, and returning the list object would cause copying. Best would be to change the method's signature to accept and populate a list reference:
list<Request> requests;
log_manipulator.getRequestListByRef(requests);
with void getRequestListByRef(list<Request>&) as the method's signature.
|
984,141
| 984,371
|
Forcing non-cached gethostbyname()
|
Is there any way to prevent the gethostbyname() function not to read the nscd cache on Linux?
|
Not really an answer, but use getaddrinfo(3) instead :)As far as nscd is concerned, here's from the nscd.conf(5) manual page:
enable-cache service <yes|no>
Enables or disables the specified service cache.
You'll have to find out what the correct service for DNS is.
|
984,357
| 984,401
|
Path sanitization in C++
|
I'm writing a small read-only FTP-like server. Client says "give me that file" and my server sends it.
Is there any standard way (a library function?!?) to make sure that the file requested is not "../../../../../etc/passwd" or any other bad thing? It would be great if I could limit all queries to a directory (and its subdirectories).
Thank you!
|
Get the inode of the root (/) directory, and that of the serving directory (say /ftp/pub). For the files they request, make sure that:
The file exists.
The parents of the file (accessed using multiple "/.." on the file path) hit the serving directory inode before it hits the root directory inode.
You can use stat to find the inode of any directory. Put this in one function, and call it before serving the file.
Of course using a user/group with appropriate privilege will work as well.
|
984,394
| 984,597
|
Why not infer template parameter from constructor?
|
my question today is pretty simple: why can't the compiler infer template parameters from class constructors, much as it can do from function parameters? For example, why couldn't the following code be valid:
template <typename obj>
class Variable {
obj data;
public:
Variable(obj d) { data = d; }
};
int main() {
int num = 2;
Variable var(num); // would be equivalent to Variable<int> var(num),
return 0; // but actually a compile error
}
As I say, I understand that this isn't valid, so my question is why isn't it? Would allowing this create any major syntactic holes? Is there an instance where one wouldn't want this functionality (where inferring a type would cause issues)? I'm just trying to understand the logic behind allowing template inference for functions, yet not for suitably-constructed classes.
|
I think it is not valid because the constructor isn't always the only point of entry of the class (I am talking about copy constructor and operator=). So suppose you are using your class like this :
MyClass m(string s);
MyClass *pm;
*pm = m;
I am not sure if it would be so obvious for the parser to know what template type is the MyClass pm;
Not sure if what I said make sense but feel free to add some comment, that's an interesting question.
C++ 17
It is accepted that C++17 will have type deduction from constructor arguments.
Examples:
std::pair p(2, 4.5);
std::tuple t(4, 3, 2.5);
Accepted paper.
|
984,792
| 984,793
|
Lighting issue in OpenGL
|
I have trouble developing an OpenGL application.
The weird thing is that me and a friend of mine are developing a 3d scene with OpenGL under Linux, and there is some code on the repository, but if we both checkout the same latest version, that means, the SAME code this happens: On his computer after he compiles he can see the full lighting model, whilst on mine, I have only the ambient lights activated but not the diffuse or specular ones.
Can it be a problem of drivers ?(since he uses an ATi card and I use an nVIDIA one)
Or the static libraries ?
I repeat, it is the same code, compiled in different machines.. that's the strange thing, it should look the same.
Thanks for any help or tip given.
|
This can very easily be a driver problem, or one card supporting extensions that the other does not.
Try his binaries on your machine. If it continues to fail, either your drivers are whack or you're using a command not supported by your card. On the other hand if your screen looks right when using your code compiled on his machine, then your static libraries have a problem.
|
985,281
| 985,374
|
What is the closest thing Windows has to fork()?
|
I guess the question says it all.
I want to fork on Windows. What is the most similar operation and how do I use it.
|
Cygwin has fully featured fork() on Windows. Thus if using Cygwin is acceptable for you, then the problem is solved in the case performance is not an issue.
Otherwise you can take a look at how Cygwin implements fork(). From a quite old Cygwin's architecture doc:
5.6. Process Creation
The fork call in Cygwin is particularly interesting
because it does not map well on top of
the Win32 API. This makes it very
difficult to implement correctly.
Currently, the Cygwin fork is a
non-copy-on-write implementation
similar to what was present in early
flavors of UNIX.
The first thing that happens when a
parent process forks a child process
is that the parent initializes a space
in the Cygwin process table for the
child. It then creates a suspended
child process using the Win32
CreateProcess call. Next, the parent
process calls setjmp to save its own
context and sets a pointer to this in
a Cygwin shared memory area (shared
among all Cygwin tasks). It then fills
in the child's .data and .bss sections
by copying from its own address space
into the suspended child's address
space. After the child's address space
is initialized, the child is run while
the parent waits on a mutex. The child
discovers it has been forked and
longjumps using the saved jump buffer.
The child then sets the mutex the
parent is waiting on and blocks on
another mutex. This is the signal for
the parent to copy its stack and heap
into the child, after which it
releases the mutex the child is
waiting on and returns from the fork
call. Finally, the child wakes from
blocking on the last mutex, recreates
any memory-mapped areas passed to it
via the shared area, and returns from
fork itself.
While we have some ideas as to how to
speed up our fork implementation by
reducing the number of context
switches between the parent and child
process, fork will almost certainly
always be inefficient under Win32.
Fortunately, in most circumstances the
spawn family of calls provided by
Cygwin can be substituted for a
fork/exec pair with only a little
effort. These calls map cleanly on top
of the Win32 API. As a result, they
are much more efficient. Changing the
compiler's driver program to call
spawn instead of fork was a trivial
change and increased compilation
speeds by twenty to thirty percent in
our tests.
However, spawn and exec present their
own set of difficulties. Because there
is no way to do an actual exec under
Win32, Cygwin has to invent its own
Process IDs (PIDs). As a result, when
a process performs multiple exec
calls, there will be multiple Windows
PIDs associated with a single Cygwin
PID. In some cases, stubs of each of
these Win32 processes may linger,
waiting for their exec'd Cygwin
process to exit.
Sounds like a lot of work, doesn't it? And yes, it is slooooow.
EDIT: the doc is outdated, please see this excellent answer for an update
|
985,404
| 985,429
|
Static libraries, linking and dependencies
|
I have a static library that I want to distribute that has includes Foo.c/h and someone picks it up and includes my static library in their application.
Say they also have Foo.c/h in their application. Will they have linking errors?
|
The name of a source file is not significant in the linking process.
If the file has the same contents, then you'll have a problem, assuming that the .c file contains exported symbols (e.g. non-static or non-template functions, or extern variables).
|
986,021
| 986,084
|
How to implement sorting method for a c++ priority_queue with pointers
|
My priority queue declared as:
std::priority_queue<*MyClass> queue;
class MyClass {
bool operator<( const MyClass* m ) const;
}
is not sorting the items in the queue.
What is wrong? I would not like to implement a different (Compare) class.
Answer summary:
The problem is, the pointer addresses are sorted. The only way to avoid this is a class that 'compares the pointers'.
Now implemented as:
std::priority_queue<*MyClass, vector<*MyClass>, MyClass::CompStr > queue;
class MyClass {
struct CompStr {
bool operator()(MyClass* m1, MyClass* m2);
}
}
|
Give the que the Compare functor ptr_less.
If you want the ptr_less to be compatible with the rest of the std library (binders, composers, ... ):
template<class T>
struct ptr_less
: public binary_function<T, T, bool> {
bool operator()(const T& left, const T& right) const{
return ((*left) <( *right));
}
};
std::priority_queue<MyClass*, vector<MyClass*>, ptr_less<MyClass*> > que;
Otherwise you can get away with the simplified version:
struct ptr_less {
template<class T>
bool operator()(const T& left, const T& right) const {
return ((*left) <( *right));
}
};
std::priority_queue<MyClass*, vector<MyClass*>, ptr_less > que;
|
986,210
| 986,243
|
undefined reference to the shared library function
|
I have implemented a shared library in Linux and try to test it, but I get an error "undefined reference to `CEDD(char*)'".
I use Eclipse with following parameters:
Path to include files (here is
everything ok)
Path to the library
and its name. Path is correct and the
name is WISE_C (full name:
libWISE_C.so)
My Code:
Test programm I use for tests:
#include <iostream>
#include <Descriptor.h>
int main() {
char* path = "/export/home/pdmazubi3/workspace/proj1/src/pic.jpg";
double * cedd = CEDD(path); ///// <-ERROR!
std::cout << "!!!Hello World!!!" << cedd[1];
return 0;
}
Header Descriptor.h:
double* CEDD(char* path);
A part of Descriptor.c with desirable function:
#include "Descriptor.h"
#include "highgui.h"
#include "cv.h"
double* CEDD(char* path)
{
IplImage* srcImg;
IplImage* ImageGrid;
...
}
What I am doing wrog? I have raed a lot of articles in the Internet but I didn't found a solution.
undefined reference to `CEDD(char*)' is a compiler or linker error?
|
It's a linker error (although I don't think it usually includes the 'char*' bit), so it seems that it either cannot find your library or the library does not contain the function. The latter might also mean that it does contain the actual function, but with a different name; make sure both projects a compiled as C and not C++.
Edit: I missed that you program is C++ (which also explains the more detailed linker message). In this case you should add extern "C" (conditionally, so it is only used when using C++) to the declaration of CEDD if the library is in C.
|
986,321
| 986,428
|
Reformat C++ braces without changing indentation?
|
We would like to make our C++ brace style more consistent. Right now, our code contains a mix of:
if (cond)
{
// ...
}
else
{
// ...
}
...and:
if (cond) {
// ...
} else {
// ...
}
We want to use the latter style exclusively.
However, we don't want to change the indentation of our code. I've tried using astyle, bcpp, GNU indent and Uncrustify (and I've looked at the command-line options for GreatCode). Unfortunately, each of these tools insists on reindenting our code, and most of them mangle C++ constructor initializer lists and preprocessor macros pretty badly.
Are there any C++ code beautifiers which can fix braces while leaving indentation alone? It doesn't have to be a pre-existing tool--if you know how to do this using some crazy Perl one-liner, that's also good. Thank you!
Update: Yes, we aware that this will make it hard to read diffs against older code. This is a long-postponed code cleanup, and we've decided that the day-to-day advantages of consistent formatting outweigh any version-control difficulties.
|
Here's a Perl one-liner that should do what you want.
perl -pi.bak -e 'BEGIN { undef $/; } s/\s*?(\s?\/\/.*)?\r?\n\s*{/ {\1/g; s/}(\s?\/\/.*)?\r?\n\s*else\b(.*)/} else\2\1/g;'
It turns this:
int main(int argc, char *argv[])
{
int something = 0;
if (something) // 5-12-2007
{
printf("Hi!\n");
}
else // 5-13-2007
{
printf("Bye\n");
}
return 0;
}
into this:
int main(int argc, char *argv[]) {
int something = 0;
if (something) { // 5-12-2007
printf("Hi!\n");
} else { // 5-13-2007
printf("Bye\n");
}
return 0;
}
|
986,426
| 986,584
|
What do __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS mean?
|
I see this in the standard C++ libraries for my system, as well as some of the headers in a library I'm using.
What are the semantics of these two definitions? Is there a good reference for #defines like this other than the source itself?
|
__STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS are a workaround to allow C++ programs to use stdint.h macros specified in the C99 standard that aren't in the C++ standard. The macros, such as UINT8_MAX, INT64_MIN, and INT32_C() may be defined already in C++ applications in other ways. To allow the user to decide if they want the macros defined as C99 does, many implementations require that __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS be defined before stdint.h is included.
This isn't part of the C++ standard, but it has been adopted by more than one implementation.
|
986,610
| 986,713
|
Language to write a Windows application that doesn't take up a lot of space
|
I need to write a Windows XP/Vista application, main requirements:
Just one .exe file, without extra runtime, like Air, .Net; posstibly a couple of dlls.
Very small file size.
The application is for network centric usage, similar to ICQ or Gtalk clients.
|
It depends, I think, how much UI you require. The benefit of frameworks such as MFC is it wraps a lot of boiler plate code for you. However.. if executable size & dependencies are the major constraint, it can be quite fun to build a tiny app.
It's quite possible to build a Windows application with bare essentials (a dialog, etc) and make use of common dialog resources which will already be installed (e.g commdlg.dll).
To keep it as small as possible I'd recommend writing It with C++, preferably with the MSVC runtime for ease. The Win32 API is pretty easy to pick up in terms of the essential steps, e.g. registering windows and creating a message proc.
Can you be a bit more specific with what you'd like to know more about?
|
987,585
| 987,621
|
C++ system function hangs application
|
I have the following code
void reportResults()
{
wstring env(_wgetenv(L"ProgramFiles"));
env += L"\Internet Explorer\iexplore.exe";
wstringstream url;
url << "\"\"" << env.c_str() << "\" http://yahoo.com\"";
wchar_t arg[BUFSIZE];
url.get(arg, BUFSIZE);
wcout << arg << endl;
_wsystem(arg);
}
Where arg is:
""C:\Program Files\Internet Explorer\iexplore.exe" http://yahoo.com"
The program functions as expected, launching IE and navigating to Yahoo, but the calling function (reportResults) never exits. How do I get the program to exit leaving the browser alive?
Thanks.
|
You want to use _wspawn() instead of _wsystem(). This will spawn a new process for the browser process. _wsystem() blocks on the command that you create; this is why you're not getting back to your code. _wspawn() creates a new, separate process, which should return to your code immediately.
|
987,684
| 987,718
|
Does GCC have a built-in compile time assert?
|
Our existing compile-time assert implementation is based on negative array index, and it provides poor diagnostic output on GCC. C++0x's static_assert is a very nice feature, and the diagnostic output it provides is much better. I know GCC has already implemented some C++0x features. Does anyone know if static_assert is among them and if it is then since what GCC version?
|
According to this page, gcc has had static_assert since 4.3.
|
987,828
| 987,864
|
Is there a better way to load in a big animation?
|
Maybe not really big, but a hundred frames or something. Is the only way to load it in by making an array and loading each image individually?
load_image() is a function I made which loads the images and converts their BPP.
expl[0] = load_image( "explode1.gif" );
expl[1] = load_image( "explode2.gif" );
expl[2] = load_image( "explode3.gif" );
expl[3] = load_image( "explode4.gif" );
...
expl[99] = load_image( "explode100.gif" );
Seems like their should be a better way.. at least I hope.
|
A common technique is spritesheets, in which a single, large image is divided into a grid of cells, with each cell containing one frame of an animation. Often, all animation frames for any game entity are placed on a single, sometimes huge, sprite sheet.
|
987,960
| 988,110
|
Dividing C++ Application into Libraries
|
My C++ project is growing larger. We are also moving to using cmake for building now. I want to divide the application into libraries so that they can be linked for testing, preparing the application package, etc. Right now I would divide my code into libraries as follows:
core
GUI
utilities (these are used by core and other components)
io (xml parsing/outputing using print functions of classes in core)
tests (unit tests)
simulator (tests the core)
An alternative would be to divide based on the directory structure - one library for each directory. But from my past experience it leads to too many libraries and then library dependencies become tough to handle during linking.
Are there any best practices in this regard?
|
Sit down with a piece of paper and decide your library architecture.
The library should be designed as a set of levels.
A libary on level A (the base) should have dependencioes only on system libraries and only if it must on libraries on level A.
A library on level B can have dependencies on libraries at level A and system libararies and only if it must on libraries on level B.
etc
Each library should represent a complete job at its particular level. Things at lower level generally have smaller jobs but lots of them. A library at a higher level should reresent a complete task. ie don't have a lib for windows objects and a lib for events. At this level the job here is handline all interaction with a window (this includes how it interacts with events).
You seem to have identified some resonable functional groups. The only one that see a bit suspicious is io. If you truly have some generic IO routines that provide real functionality fine. But if it is just grouping the IO for a bunch of different objects then I would scrap that (it all depends on the usage).
So the next step is to identify the relationship between them.
As for using directory structures. Usually everything in one directory will be present within the same library, but that does not exclude the posability of other directories also being present. I would avoid putting half the classes in directory in libA and the other half of the classes in libB etc.
|
988,069
| 988,084
|
const int *p vs. int const *p - Is const after the type acceptable?
|
My co-worker is 0 for 2 on questions he has inspired (1, 2), so I thought I'd give him a chance to catch up.
Our latest disagreement is over the style issue of where to put "const" on declarations.
He is of the opinion that it should go either in front of the type, or after the pointer. The reasoning is that this is what is typically done by everyone else, and other styles are liable to be confusing. Thus a pointer to a constant int, and a constant pointer to int would be respectively:
const int *i;
int * const i;
However, I'm confused anyway. I need rules that are consistent and easy to understand, and the only way I can make sense of "const" is that it goes after the thing it is modifying. There's an exception that allows it to go in front of the final type, but that's an exception, so it's easier on me if I don't use it.
Thus a pointer to a constant int, and a constant pointer to int would be respectively:
int const * i;
int * const i;
As an added benefit, doing things this way makes deeper levels of indirection easier to understand. For example, a pointer to a constant pointer to int would clearly be:
int * const * i;
My contention is that if someone just learns it his way, they'll have little trouble figuring out what the above works out to.
The ultimate issue here is that he thinks that putting const after int is so unspeakably ugly, and so harmful to readability that it should be banned in the style guide. Of course, I think if anything the guide should suggest doing it my way, but either way we shouldn't be banning one approach.
Edit:
I've gotten a lot of good answers, but none really directly address my last paragraph ("The ultimate issue"). A lot of people argue for consistency, but is that so desirable in this case that it is a good idea to ban the other way of doing it, rather that just discouraging it?
|
The most important thing is consistency. If there aren't any coding guidelines for this, then pick one and stick with it. But, if your team already has a de facto standard, don't change it!
That said, I think by far the more common is
const int * i;
int * const j;
because most people write
const int n;
instead of
int const n;
A side note -- an easy way to read pointer constness is to read the declaration starting at the right.
const int * i; // pointer to an int that is const
int * const j; // constant pointer to a (non-const) int
int const * aLessPopularWay; // pointer to a const int
|
988,158
| 988,220
|
Take the address of a one-past-the-end array element via subscript: legal by the C++ Standard or not?
|
I have seen it asserted several times now that the following code is not allowed by the C++ Standard:
int array[5];
int *array_begin = &array[0];
int *array_end = &array[5];
Is &array[5] legal C++ code in this context?
I would like an answer with a reference to the Standard if possible.
It would also be interesting to know if it meets the C standard. And if it isn't standard C++, why was the decision made to treat it differently from array + 5 or &array[4] + 1?
|
Your example is legal, but only because you're not actually using an out of bounds pointer.
Let's deal with out of bounds pointers first (because that's how I originally interpreted your question, before I noticed that the example uses a one-past-the-end pointer instead):
In general, you're not even allowed to create an out-of-bounds pointer. A pointer must point to an element within the array, or one past the end. Nowhere else.
The pointer is not even allowed to exist, which means you're obviously not allowed to dereference it either.
Here's what the standard has to say on the subject:
5.7:5:
When an expression that has integral
type is added to or subtracted from a
pointer, the result has the type of
the pointer operand. If the pointer
operand points to an element of an
array object, and the array is large
enough, the result points to an
element offset from the original
element such that the difference of
the subscripts of the resulting and
original array elements equals the
integral expression. In other words,
if the expression P points to the i-th
element of an array object, the
expressions (P)+N (equivalently,
N+(P)) and (P)-N (where N has the
value n) point to, respectively, the
i+n-th and i−n-th elements of the
array object, provided they exist.
Moreover, if the expression P points
to the last element of an array
object, the expression (P)+1 points
one past the last element of the array
object, and if the expression Q points
one past the last element of an array
object, the expression (Q)-1 points to
the last element of the array object.
If both the pointer operand and the
result point to elements of the same
array object, or one past the last
element of the array object, the
evaluation shall not produce an
overflow; otherwise, the behavior is
undefined.
(emphasis mine)
Of course, this is for operator+. So just to be sure, here's what the standard says about array subscripting:
5.2.1:1:
The expression E1[E2] is identical (by definition) to *((E1)+(E2))
Of course, there's an obvious caveat: Your example doesn't actually show an out-of-bounds pointer. it uses a "one past the end" pointer, which is different. The pointer is allowed to exist (as the above says), but the standard, as far as I can see, says nothing about dereferencing it. The closest I can find is 3.9.2:3:
[Note: for instance, the address one past the end of an array (5.7) would be considered to
point to an unrelated object of the array’s element type that might be located at that address. —end note ]
Which seems to me to imply that yes, you can legally dereference it, but the result of reading or writing to the location is unspecified.
Thanks to ilproxyil for correcting the last bit here, answering the last part of your question:
array + 5 doesn't actually
dereference anything, it simply
creates a pointer to one past the end
of array.
&array[4] + 1 dereferences
array+4 (which is perfectly safe),
takes the address of that lvalue, and
adds one to that address, which
results in a one-past-the-end pointer
(but that pointer never gets
dereferenced.
&array[5] dereferences array+5
(which as far as I can see is legal,
and results in "an unrelated object
of the array’s element type", as the
above said), and then takes the
address of that element, which also
seems legal enough.
So they don't do quite the same thing, although in this case, the end result is the same.
|
988,334
| 988,422
|
Using a DLL in Visual Studio C++
|
I have a DLL that I've been using with no problem in Visual C# (simply adding the reference and using the namespace). Now I'm trying to learn C++, and I don't understand how you reference a namespace from a DLL. I can right-click on a project and select 'references' and from there click 'add new reference', but that just provides me with an empty 'projects' window. What am I missing?
|
C++ is a lot different from C#/VB.Net when it comes to processing DLL references. In C# all that is needed to do a reference is a DLL because it contains metadata describing the structures that lay inside. The compiler can read this information such that they can be used from another project.
C++ does not have the concept of metadata in the DLL in the sense that C# does. Instead you must explicitly provide the metadata in the form of a header file. These files are included in your C++ project and then the DLL is delay loaded at runtime. You don't actually "add a reference" so to speak in C++ but include a header file instead.
Once the header file is included, you can then access the namespace by including it in your CPP files
using namespace SomeNamespace;
|
988,538
| 988,557
|
Using CList in a multithreaded environment
|
I am using a CList in a multithreaded environment and I keep having problem with the GetHead method. I have one thread that add data to the list, and an other thread who read and remove data from the list.
Here is the reading part :
value_type get_next()
{
T t;
if(!queue.IsEmpty()) {
t = queue.GetHead();
}
return t; //If the queue is empty we return an empty element
}
Here is the inserting part :
inline void insert(T &_in)
{
queue.AddTail(_in);
}
Here is the removing part
inline void pop_next()
{
if(!queue.IsEmpty()) {
queue.RemoveHead();
}
}
Why do I get a runtime error when I run this. It always fail at
t = queue.GetHead();
With this assertion :
template<class TYPE, class ARG_TYPE>
AFX_INLINE TYPE& CList<TYPE, ARG_TYPE>::GetHead()
{ ENSURE(m_pNodeHead != NULL);
return m_pNodeHead->data; }
While the m_pNodeHead value is :
pNext 0x00000000 {pNext=??? pPrev=??? data={...}
} CList > >,ATL::CStringT > > &>::CNode *
pPrev 0x00000000 {pNext=??? pPrev=??? data={...}
} CList > >,ATL::CStringT > > &>::CNode *
data "" TESTSETSE ATL::CStringT > >
|
You have a race condition between inserting and retrieving the value. Add a lock that includes the entire body of get_next(), insert(), and pop_next().
|
988,588
| 988,613
|
Is using unsigned integer overflow good practice?
|
I was reading the C Standard the other day, and noticed that unlike signed integer overflow (which is undefined), unsigned integer overflow is well defined. I've seen it used in a lot of code for maximums, etc. but given the voodoos about overflow, is this considered good programming practice? Is it in anyway insecure? I know that a lot of modern languages like Python do not support it- instead they continue to extend the size of large numbers.
|
Unsigned integer overflow (in the shape of wrap-around) is routinely taken advantage of in hashing functions, and has been since the year dot.
|
988,813
| 989,565
|
App to read form document (scantron-ish)
|
I need to create form that will be filled in by hand and read digitally. I plan on using a sort of scantron-esque format with rows and columns that the user can just color in the a circle in the appropriate cell and the computer will know that value based on the xy position in the cell matrix. Like an excel address.
| Sys | TV | printer
---------------------------
6/12 | | X |
---------------------------
6/13 | X | |
---------------------------
6/14 | | | X
Based on the example above I would have a tv on 6/12, a Sys on 6/13, etc.
So the question is, do any of you know an app that reads stuff like this; which I can automate to read the doc and save the output without user intervention?
Thanks
I played around with a couple OCRs and they try so hard to recognise all the text on the screen that they mess up the layout filling it with their odd interpretations of the 'unreadable' characters. This might be the answer, but the ocr would have to let me limit what it tries to read or format.
|
You want OMR (Optical Mark Recognition). Not sure what your budget is, but Abbyy is one of the leaders in this space:
If you want to try to roll your own, I wrote this article last month
http://www.codeproject.com/KB/showcase/SimpleOMRDotImage.aspx
It's based on the toolkit for the company I work for, but explains the core concepts so that you can try to implement it with whatever imaging toolkit you have.
|
988,848
| 988,862
|
Predicting that the program will crash
|
I've been using Google Chrome for a while now and I noticed that it features very elegant crash control.
Just before crashing, google chrome gave a message saying "Woah! Google Chrome has crashed. Restart now?". And right after, I'd get a standard Windows XP "This program has encountered a problem and needs to close." with the "Debug", "Don't send" and "Send Error Report" buttons.
My question is how can you program your compiled application to detect a crash condition in advance? If you have knowledge of how to do it in any programming language / platform would be great.
Thanks
|
Google Chrome uses a technique (often called process separation) where the 'host' UI manages child processes that it can detect becoming unresponsive (or worse, throwing an error and closing). It starts a new process for each tab you open.
Here's an article describing this in a bit more detail.
Using .net's Process class, you can start processes, check if they're responsive and even kill them.
If you want to embed a process' window within your own, you can use platform functions such as SetParent to move one window within another. I'm afraid I'm not aware of a managed alternative to SetParent when working with Forms, but I suspect one exists so it's worth searching for that before using SetParent.
If the host process crashes, simply using something like AppDomain.CurrentDomain.UnhandledException will allow you to receive a notification that a top-level exception has occurred, but by this stage you're unlikely to be able to predict the state of objects within your app and restarting (along with some logging and a notification to the user) is probably your only sensible option.
Handling top-level exceptions is covered in detail here.
|
988,925
| 988,935
|
How to overload a destructor?
|
How do I overload a destructor?
|
You can't. There is only one destructor per class in C++.
What you can do is make a private destructor and then have several public methods which call the destructor in new and interesting ways.
class Foo {
~Foo() { ... }
public:
DestroyFoo(int) { ... };
DestroyFoo(std::string) { ... }
};
|
989,795
| 989,816
|
Example for boost shared_mutex (multiple reads/one write)?
|
I have a multithreaded app that has to read some data often, and occasionally that data is updated. Right now a mutex keeps access to that data safe, but it's expensive because I would like multiple threads to be able to read simultaneously, and only lock them out when an update is needed (the updating thread could wait for the other threads to finish).
I think this is what boost::shared_mutex is supposed to do, but I'm not clear on how to use it, and haven't found a clear example.
Does anyone have a simple example I could use to get started?
|
It looks like you would do something like this:
boost::shared_mutex _access;
void reader()
{
// get shared access
boost::shared_lock<boost::shared_mutex> lock(_access);
// now we have shared access
}
void writer()
{
// get upgradable access
boost::upgrade_lock<boost::shared_mutex> lock(_access);
// get exclusive access
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
// now we have exclusive access
}
|
989,817
| 1,589,894
|
How can I make "real-time" plots with wxMathPlot?
|
I am thinking of using wxMathPlot for plotting/graphing some data that arrives continuously. I want to draw "Real-time" plot/graph using it. Is that possible?
I.E. I don't want just a static graph of a one-time read of a file - I want the streaming data plotted and continued out to the right of the graph - (and let the left side fall off/scroll out of view)
EDIT
I still have not gotten an answer for this. There is an interesting class in the wxmathPlot library called mpFXYVector but that appears just to draw one plot from a vector of data. What I want is something that can be fed a stream and scroll the graph horizontally (and also resize the scale if needed)
|
I think mpFXYVector is the way to go.
The simplest way to deal with this might be to write a wrapper class for mpFXYVector which holds a FIFO buffer of recent data points. Each time a new datapoint arrives, add it to the FIFO buffer, which will drop the oldest point, then load mpFXYVector with the updated buffer. The wxMathPlot class mpWindow will look after the rest of what you need.
A more elegant approach would be a specialization of mpFXYVector which implements the FIFO buffer, using the simple vectors in mpFXYVector. The advantage of this would be that you are holding just one copy of the display data. Unless you are displaying many thousands of points, I doubt the advantage is worth the extra trouble of inheriting from mpFXYVector, rather than simply using the mpFXYVector documented interface.
After looking at the details, the only tricky bit is to replace mpFXYVector::SetData() with a new method Add() to add data points as they arrive. The new method needs to manage the mpFXYVector vectors as FIFO buffers, and to re-implement the code to update the bounding box ( which unfortunately was not written with inheritance in mind ).
The result is that specialization gives a solution with a smaller memory requirement and more flexibility than using a wrapper.
|
989,848
| 989,869
|
Is the linked list only of limited use?
|
I was having a nice look at my STL options today. Then I thought of something.
It seems a linked list (a std::list) is only of limited use. Namely, it only really seems
useful if
The sequential order of elements in my container matters, and
I need to erase or insert elements in the middle.
That is, if I just want a lot of data and don't care about its order, I'm better off using an std::set (a balanced tree) if I want O(log n) lookup or a std::unordered_map (a hash map) if I want O(1) expected lookup or a std::vector (a contiguous array) for better locality of reference, or a std::deque (a double-ended queue) if I need to insert in the front AND back.
OTOH, if the order does matter, I am better off using a std::vector for better locality of reference and less overhead or a std::deque if a lot of resizing needs to occur.
So, am I missing something? Or is a linked list just not that great? With the exception of middle insertion/erasure, why on earth would someone want to use one?
|
Any sort of insertion/deletion is O(1). Even std::vector isn't O(1) for appends, it approaches O(1) because most of the time it is, but sometimes you are going to have to grow that array.
It's also very good at handling bulk insertion, deletion. If you have 1 million records and want to append 1 million records from another list (concat) it's O(1). Every other structure (assuming stadard/naive implementations) are at least O(n) (where n is the number of elements added).
|
989,867
| 989,914
|
c++ set versus vector + heap operations for an A* priority queue
|
When is using a std::set more efficient (w.r.t. time) than using a std::vector along with make_heap/push_/pop_ for the priority queue in an A* operation? My guess is that if the vertices in the open list are small, using a vector is a better option. But does anyone have experience with this?
|
If i had to venture a guess? I'd guess that the vector version is probably a good choice because once it grows to a certain size, there won't be very many allocs.
But I don't like guessing. I prefer hard numbers. Try both, profile!
|
989,892
| 989,902
|
How to define preprocessor directives in VC++ 2008?
|
I'm using Visual C++ 2008 Express Edition. The WIN32 preprocessor directive doesn't appear to be defined by default, so when I surround includes with #ifndef WIN32, it still includes them.
I found someone with the exact same problem below, but it was so long ago that the location of this setting has changed:
http://www.gamedev.net/community/forums/topic.asp?topic_id=418604
|
In VS 2008 Pro, you right-click on the project and select Properties. Then look for Preprocessor Definitions in Configuration Properties | C/C++ | Preprocessor.
|
989,980
| 990,161
|
How do you handle command line options and config files?
|
What packages do you use to handle command line options, settings and config files?
I'm looking for something that reads user-defined options from the command line and/or from config files.
The options (settings) should be dividable into different groups, so that I can pass different (subsets of) options to different objects in my code.
I know of boost::program_options, but I can't quite get used to the API. Are there light-weight alternatives?
(BTW, do you ever use a global options object in your code that can be read from anywhere? Or would you consider that evil?)
|
Well, you're not going to like my answer. I use boost::program_options. The interface takes some getting used to, but once you have it down, it's amazing. Just make sure to do boatloads of unit testing, because if you get the syntax wrong you will get runtime errors.
And, yes, I store them in a singleton object (read-only). I don't think it's evil in that case. It's one of the few cases I can think of where a singleton is acceptable.
|
990,505
| 990,608
|
How to get count of next combinations for given set?
|
I've edited original text to save potential readers some time and health. Maybe someone will actually use this.
I know it's basic stuff. Probably like very, very basic.
How to get all possible combinations of given set.
E.g.
string set = "abc";
I expect to get:
a b c aa ab ac aaa aab aac aba abb abc aca acb acc baa bab ...
and the list goes on (if no limit for length is set).
I'm looking for a very clean code for that - all that I've found was kind of dirty and not working correctly. The same I can say about code I wrote.
I need such code because I'm writing brute force (md5) implementation working on multiple threads. The pattern is that there's Parent process that feeds threads with chunks of their very own combinations, so they would work on these on their own.
Example: first thread gets package of 100 permutations, second gets next 100 etc.
Let me know if I should post the final program anywhere.
EDIT #2
Once again thank you guys.
Thanks to you I've finished my Slave/Master Brute-Force application implemented with MPICH2 (yep, can work under linux and windows across for example network) and since the day is almost over here, and I've already wasted a lot of time (and sun) I'll proceed with my next task ... :)
You shown me that StackOverflow community is awesome - thanks!
|
Here's some C++ code that generates permutations of a power set up to a given length.
The function getPowPerms takes a set of characters (as a vector of strings) and a maximum length, and returns a vector of permuted strings:
#include <iostream>
using std::cout;
#include <string>
using std::string;
#include <vector>
using std::vector;
vector<string> getPowPerms( const vector<string>& set, unsigned length ) {
if( length == 0 ) return vector<string>();
if( length == 1 ) return set;
vector<string> substrs = getPowPerms(set,length-1);
vector<string> result = substrs;
for( unsigned i = 0; i < substrs.size(); ++i ) {
for( unsigned j = 0; j < set.size(); ++j ) {
result.push_back( set[j] + substrs[i] );
}
}
return result;
}
int main() {
const int MAX_SIZE = 3;
string str = "abc";
vector<string> set; // use vector for ease-of-access
for( unsigned i = 0; i < str.size(); ++i ) set.push_back( str.substr(i,1) );
vector<string> perms = getPowPerms( set, MAX_SIZE );
for( unsigned i = 0; i < perms.size(); ++i ) cout << perms[i] << '\n';
}
When run, this example prints
a b c aa ba ca ab bb cb ... acc bcc ccc
Update: I'm not sure if this is useful, but here is a "generator" function called next that creates the next item in the list given the current item.
Perhaps you could generate the first N items and send them somewhere, then generate the next N items and send them somewhere else.
string next( const string& cur, const string& set ) {
string result = cur;
bool carry = true;
int loc = cur.size() - 1;
char last = *set.rbegin(), first = *set.begin();
while( loc >= 0 && carry ) {
if( result[loc] != last ) { // increment
int found = set.find(result[loc]);
if( found != string::npos && found < set.size()-1 ) {
result[loc] = set.at(found+1);
}
carry = false;
} else { // reset and carry
result[loc] = first;
}
--loc;
}
if( carry ) { // overflow
result.insert( result.begin(), first );
}
return result;
}
int main() {
string set = "abc";
string cur = "a";
for( int i = 0; i < 20; ++i ) {
cout << cur << '\n'; // displays a b c aa ab ac ba bb bc ...
cur = next( cur, set );
}
}
|
990,578
| 990,588
|
expected asm or __attribute__ before CRenderContext
|
I am developing a small app under Linux using the CodeBlocks IDE.
I have defined a class with the following code:
class CRenderContext
{
public: /*instance methods*/
CRenderContext() :
m_iWidth(0), m_iHeight(0),
m_iX(0), m_iY(0),
m_bFullScreen(false), m_bShowPointer(false) {};
CRenderContext (int iWidth,
int iHeight,
int iX,
int iY,
bool bFullScreen,
bool bShowPointer)
:
m_iWidth(iWidth), m_iHeight(iHeight),
m_iX(iX), m_iY(iY),
m_bFullScreen(bFullScreen), m_bShowPointer(bShowPointer) {};
virtual ~CRenderContext () {};
public: /*instance data*/
int m_iWidth;
int m_iHeight;
int m_iX;
int m_iY;
bool m_bFullScreen;
bool m_bShowPointer;
};
I always get the following error when compiling the above code:
error: expected '=', ',', ';', 'asm' or 'attribute' before CRenderContext
Any ideas about how to solve the error?
Thanks in advance,
Eugenio
|
You are compiling it as C code, not C++. You probably need to rename the source file to have a .cpp extension. The code compiles perfectly (as C++) with g++ and comeau, although you have some superfluous semicolons. For example:
virtual ~CRenderContext () {};
No need for the semicolon ot the end there.
|
990,625
| 990,653
|
C++ function pointer (class member) to non-static member function
|
class Foo {
public:
Foo() { do_something = &Foo::func_x; }
int (Foo::*do_something)(int); // function pointer to class member function
void setFunc(bool e) { do_something = e ? &Foo::func_x : &Foo::func_y; }
private:
int func_x(int m) { return m *= 5; }
int func_y(int n) { return n *= 6; }
};
int
main()
{
Foo f;
f.setFunc(false);
return (f.*do_something)(5); // <- Not ok. Compile error.
}
How can I get this to work?
|
The line you want is
return (f.*f.do_something)(5);
(That compiles -- I've tried it)
"*f.do_something" refers to the pointer itself --- "f" tells us where to get the do_something value from. But we still need to give an object that will be the this pointer when we call the function. That's why we need the "f." prefix.
|
991,062
| 991,162
|
Passing unnamed classes through functions
|
How do I pass this instance as a parameter into a function?
class
{
public:
void foo();
} bar;
Do I have to name the class?
It is copyable since I haven't made the class's copy ctor private.
So how is it possible if at all?
|
Maybe it would be better if you explicit what you want to do. Why do you want to create an unnamed class? Does it conform to an interface? Unnamed classes are quite limited, they cannot be used as parameters to functions, they cannot be used as template type-parameters...
Now if you are implmenting an interface then you can pass references to that interface:
class interface {
public:
virtual void f() const = 0;
};
void function( interface const& o )
{
o.f();
}
int main()
{
class : public interface {
public:
virtual void f() const {
std::cout << "bar" << std::endl;
}
} bar;
function( bar ); // will printout "bar"
}
NOTE: For all those answers that consider template arguments as an option, unnamed classes cannot be passed as template type arguments.
C++ Standard. 14.3.1, paragraph 2:
2 A local type, a type with no
linkage, an unnamed type or a type
compounded from any of these types
shall not be used as a
template-argument for a template
type-parameter.
If you test with comeau compiler (the link is for the online tryout) you will get the following error:
error: a template argument may not
reference an unnamed type
As a side note, comeau compiler is the most standard compliant compiler I know of, besides being the one with the most helpful error diagnostics I have tried.
NOTE: Comeau and gcc (g++ 4.0) give an error with the code above. Intel compiler (and from other peoples comments MSVS 2008) accept using unnamed classes as template parameters, against the standard.
|
991,144
| 991,149
|
What exactly do pointers store? (C++)
|
I know that pointers store the address of the value that they point to, but if you display the value of a pointer directly to the screen, you get a hexadecimal number. If the number is exactly what the pointer stores, then when saying
pA = pB; //both are pointers
you're copying the address. Then wouldn't there be a bigger overhead to using pointers when working with very small items like ints and bools?
|
A pointer is essentially just a number. It stores the address in RAM where the data is. The pointer itself is pretty small (probably the same size as an int on 32 bit architectures, long on 64 bit).
You are correct though that an int * would not save any space when working with ints. But that is not the point (no pun intended). Pointers are there so you can have references to things, not just use the things themselves.
|
991,335
| 991,354
|
How to erase & delete pointers to objects stored in a vector?
|
I have a vector that stores pointers to many objects instantiated dynamically, and I'm trying to iterate through the vector and remove certain elements (remove from vector and destroy object), but I'm having trouble. Here's what it looks like:
vector<Entity*> Entities;
/* Fill vector here */
vector<Entity*>::iterator it;
for(it=Entities.begin(); it!=Entities.end(); it++)
if((*it)->getXPos() > 1.5f)
Entities.erase(it);
When any of the Entity objects get to xPos>1.5, the program crashes with an assertion error...
Anyone know what I'm doing wrong?
I'm using VC++ 2008.
|
You need to be careful because erase() will invalidate existing iterators. However, it will return a new valid iterator you can use:
for ( it = Entities.begin(); it != Entities.end(); ) {
if( (*it)->getXPos() > 1.5f ) {
delete * it;
it = Entities.erase(it);
}
else {
++it;
}
}
|
991,383
| 991,408
|
Call a C++ function from C#
|
I have 2 C++ DLLs. One of them contains the following function:
void init(const unsigned char* initData, const unsigned char* key)
The other one contains this function:
BYTE* encrypt(BYTE *inOut, UINT inputSize, BYTE *secretKey, UINT secretKeySize).
Is there a way to call these 2 functions from C#? I know you can use [DllImport] in C# to call C++ functions, but the pointers are giving me a hard time.
Any help would be appreciated!
|
Yes, you can call both of these from C# assuming that they are wrapped in extern "C" sections. I can't give you a detailed PInvoke signature because I don't have enough information on how the various parameters are related but the following will work.
[DllImport("yourdllName.dll")]
public static extern void init(IntPtr initData, IntPtr key);
[DllImport("yourdllName.dll")]
public static extern IntPtr encrpyt(IntPtr inout, unsigned inuputSize, IntPtr key, unsigned secretKeySize);
Pieces of information that would allow us to create a better signature
Is the return of encrypt allocated memory?
If #1 is true, how is the memory allocated
Can you give a basic description on how the parameters work?
I'm guessing that all of the pointer values represents arrays / groups of elements instead of a single element correct?
|
991,496
| 991,512
|
How to ignore certain socket requests
|
I'm currently working on a TCP socket server in C++; and I'm trying to figure out how I can ignore all browser connections made to my server. Any idea's?
Thanks.
|
Need more details to give good feedback.
Are you going to be listening on port 80 but want to avoid all HTTP traffic? Or will your protocol be HTTP-based? Do you need to listen on 80 or can you pick any port?
If it's your own custom protocol (HTTP or not) you could just look at the first line sent up and if it's not to your liking just close() the socket.
EDIT:
Since you're going to be listening on a custom port, you probably won't get any browser traffic anyhow. Further, since you're going to be writing your own protocol, just require a handshake which establishes your client speaks your custom protocol and then ignore (close()) everything else.
Bonus points: depending on your goal, send back an HTTP error message which can be displayed to the user.
|
991,616
| 991,635
|
telling when an execl() process exits
|
I've got a c++ application with certain items in a queue, those items then are going to be processed by a python script. I want it so that at maximum 10 instances of the python script are running. I plan on using execl() to launch the python process, Is there a way to tell that the process has quit without having to pass a message back to the parent process?
|
execl doesn't launch a process -- it overlays the existing process with another executable. fork does launch a process -- and returns the child process's id (aka pid) to the parent process (returns 0 to the child process, that's how the child knows it's the child so it can clean things up and exec). Use the children's pids to check if they're finished or not, or trap SIGCHLD to keep track of that.
I recommend the SIGCHLD so you don't have to "poll" to see if some process has terminated, but the latter approach isn't too hard either -- just execute once in a while:
def whosdone(pids):
nope = []
done = []
for pid in pids:
try: os.kill(pid, 0)
except OSError: nope.append(pid)
else: done.append(pid)
return done, nope
i.e. you can periodically call done, pidslist = whosdone(pidslist) and do whatever you need to do about the PIDs that are done. Of course, when you fork, use the idiom:
pid = os.fork()
if pid: # we're the parent process
pidslist.append(pid)
else: # we're the child process
# clean things up, etc, then exec
|
991,640
| 991,911
|
Where can I find, or how can I create an elegant C++ member function template wrapper mechanism without resporting to boost?
|
I want to be able to templatize a class on a member function without needing to repeat the arguments of the member function -- i e, derive them automatically.
I know how to do this if I name the class based on how many arguments the function takes, but I want to derive that as well.
Something like this, although this doesn't work (at least in MSVC 2008 sp1, which is my target compiler):
class Foo {
void func0();
int func2(char *, float);
};
template<typename T> class Wrapper;
// specialize for zero-argument void func
template<typename Host, void (Host::*Func)()> class Wrapper<Func> : public Base {
... specialization goes here ...
};
// specialize for two-argument value func
template<typename Host, typename Ret, typename Arg0, typename Arg1, Ret (Host::*Func)(Arg0, Arg1)> class Wrapper<Func> : public Base {
... specialization goes here ...
};
Through "Base" I can then treat these polymorphically. In the end, I want to use this to create a simple wrapper syntax for a scripting language:
WrapClass<Bar> wrap(
MemberFunction<&Bar::func0>("func0") +
MemberFunction<&Bar::func2>("func2")
);
However, that doesn't work: the specialization syntax is wrong, because you can't match a function pointer to a typename argument.
|
I believe you'll need to take a traits approach, the most common library of which is boost's, but if you wanted to avoid boost, it wouldn't be extremely difficult to roll your own if you limited the scope of the implementation to just pointer-to-member-functions and the traits on those you need (modern c++ design is a great book explaining the theory). Here's how I would do it with boost's function_traits and enable_if.
You could use a generic template argument, enable_if it for function pointers, then use function types (or type traits) to pull out out the information you need:
#include <boost/function_types/function_arity.hpp>
#include <boost/function_types/is_member_pointer.hpp>
template<typename T, class Enable = void> class Wrapper;
/* other specializations... */
// For member functions:
template <class T>
class Wrapper<T, typename enable_if<is_member_pointer<T> >::type>
{ /* function_arity<T>::value has the number of arguments */ };
See this and this
|
991,671
| 991,747
|
bitwise operator variations in C++
|
I read C++ provides additional operators to the usual &,|, and ! which are "and","or" and "not" respectively, plus they come with automatic short circuiting properties where applicable.
I would like to use these operators in my code but the compiler interprets them as identifiers and throws an error.
I am using Visual C++ 2008 Express Edition with SP1. How do I activate these operators to use in my code?
|
If you want to have the 'and', 'or', 'xor', etc keyword versions of the operators made available in MSVC++ then you either have to use the '/Za' option to disable extensions or you have to include iso646.h.
|
991,842
| 991,851
|
How to link a static library in Visual C++ 2008?
|
My VC++ solution includes two projects, an application (exe) and a static library.
Both compile fine, but fail to link. I'm getting an "unresolved external symbol" error for each function from the static lib I use. They look like this:
MyApplication.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) int __cdecl MyStaticLibrary::accept(int,struct sockaddr *,int *)"
The app find's the .lib just fine, so that is not the issue. I'm thinking the "dllimport" is the problem -- why would it be there when I'm trying to build a static library? Both the app and library use the "Multi-threaded (/MT)" runtime library, not "Multi-threaded DLL (/MD)".
EDIT:
I think some of the answers are right. The library, which is called UDT, has this in the main header file:
#ifdef UDT_EXPORTS
#define UDT_API __declspec(dllexport)
#else
#define UDT_API __declspec(dllimport)
#endif
Does this mean it wasn't meant to be used as a static library?
|
How are you setting it up to link? And what does your header file for MyApplication and MyStaticLibrary::accept look like?
If you have both projects in the same solution file, the best way to set it up to link is to right-click the Solution file->Properties and then set the library as a dependency of the application. Visual Studio will handle the linking automatically, and also make sure that the library build is up to date when you build your application.
That error kinda sounds like you have it defined as a DLL import/export in your header file though.
Edit:
Yes, that's the problem. You probably created it as a dynamic library first? (or whoever wrote it did.)
There are a few options.
1) You can just delete all of that stuff, and any UDT_API modifiers in the code.
2) You can delete that stuff and add this line:
#define UDT_API
3) A more robust solution is to change it to this:
#ifdef UDT_STATIC
#define UDT_API
#else
#ifdef UDT_EXPORTS
#define UDT_API __declspec(dllexport)
#else
#define UDT_API __declspec(dllimport)
#endif
#endif
And then add the preprocessor directive UDT_STATIC to your projects when you want to use it as a static library, and remove it if you want to use it as a dynamic library. (Will need to be added to both projects.)
|
991,878
| 991,884
|
undefined reference within the same file
|
I'm getting an undefined reference to one private methods in a class. Here is a short snippet of the code (but the whole thing currently is in one source file and not separated into header and source files).
#include <iostream>
using namespace std;
struct node
{
int key_value;
node *left;
node *right;
};
class btree
{
node *root;
btree();
~btree();
void destroy_tree(node *leaf);
public:
void destroy_tree();
};
btree::btree()
{
root = NULL;
}
btree::~btree()
{
destroy_tree();
}
void btree::destroy_tree()
{
destroy_tree(root);
}
void destroy_tree(node *leaf)
{
if(leaf!=NULL)
{
destroy_tree(leaf->left);
destroy_tree(leaf->right);
delete leaf;
}
}
int main()
{
return 0;
}
The compiler outputs "undefined reference to `btree::destroy_tree(node*)' for this line:
destroy_tree(root);
but isn't the definition of that function immediately right below it?
|
Your destroy_tree overload is not scoped to btree. The implementation is missing btree:: and is required since it is not inside the class definition:
void btree::destroy_tree(node * leaf)
{
if(leaf!=NULL)
{
destroy_tree(leaf->left);
destroy_tree(leaf->right);
delete leaf;
}
}
|
992,034
| 992,044
|
How to make an "operator" variable? (C++)
|
I am working on making an expression class:
template<typename T, typename U>
class expression
{
public:
expression(T vala, U valb, oper o){val1 = vala; val2 = valb; op = o;}
operator bool{return(val1 op val2);}
private:
T val1;
U val2;
oper op;
};
as you can see, this is somewhat pseudocode, because I need an operator class. My original thought was to create an array of all possible operators, and then convert it through a string, but that wouldn't work because of the sheer number of operators, and how to convert it to a string except through a two dimensional array, where n[0][0] has the first operator, and n[0][1] has that operators string.
Does anybody have any suggestions to adding an operator value to my expression class?
|
Maybe a function pointer. Instead of ...
operator bool{return(val1 op val2);}
... code it as ...
operator bool{return op(val1, val2);}
... in which case op can be a pointer to a (any) function which takes two parameters and which returns bool.
template<typename T, typename U>
class expression
{
public:
//define pointer-to-function type
typedef bool *oper(const T& val1, const U& val2);
... etc ...
|
992,069
| 992,335
|
ACE vs Boost vs POCO
|
I have been working with the Boost C++ Libraries for quite some time. I absolutely love the Boost Asio C++ library for network programming. However I was introduced to two other libraries: POCO and Adaptive Communication Environment (ACE) framework. I would like to know the good and bad of each.
|
As rdbound said, Boost has a "near STL" status. So if you don't need another library, stick to Boost. However, I use POCO because it has some advantages for my situation. The good things about POCO IMO:
Better thread library, especially a Active Method implementation. I also like the fact that you can set the thread priority.
More comprehensive network library than boost::asio. However boost::asio is also a very good library.
Includes functionality that is not in Boost, like XML and database interface to name a few.
It is more integrated as one library than Boost.
It has clean, modern and understandable C++ code. I find it far easier to understand than most of the Boost libraries (but I am not a template programming expert :)).
It can be used on a lot of platforms.
Some disadvantages of POCO are:
It has limited documentation. This somewhat offset by the fact that the source is easy to understand.
It has a far smaller community and user base than, say, Boost. So if you put a question on Stack Overflow for example, your chances of getting an answer are less than for Boost
It remains to be seen how well it will be integrated with the new C++ standard. You know for sure that it will not be a problem for Boost.
I never used ACE, so I can't really comment on it. From what I've heard, people find POCO more modern and easier to use than ACE.
Some answers to the comments by Rahul:
I don't know about versatile and advanced. The POCO thread library provides some functionality that is not in Boost: ActiveMethod and Activity, and ThreadPool. IMO POCO threads are also easier to use and understand, but this is a subjective matter.
POCO network library also provides support for higher level protocols like HTTP and SSL (possibly also in boost::asio, but I am not sure?).
Fair enough.
Integrated library has the advantage of having consistent coding, documentation and general "look and feel".
Being cross-platform is an important feature of POCO, this is not an advantage in relation to Boost.
Again, you should probably only consider POCO if it provides some functionality you need and that is not in Boost.
|
992,176
| 992,219
|
C++ tokenize a string using a regular expression
|
I'm trying to learn myself some C++ from scratch at the moment.
I'm well-versed in python, perl, javascript but have only encountered C++ briefly, in a
classroom setting in the past. Please excuse the naivete of my question.
I would like to split a string using a regular expression but have not had much luck finding
a clear, definitive, efficient and complete example of how to do this in C++.
In perl this is action is common, and thus can be accomplished in a trivial manner,
/home/me$ cat test.txt
this is aXstringYwith, some problems
and anotherXY line with similar issues
/home/me$ cat test.txt | perl -e'
> while(<>){
> my @toks = split(/[\sXY,]+/);
> print join(" ",@toks)."\n";
> }'
this is a string with some problems
and another line with similar issues
I'd like to know how best to accomplish the equivalent in C++.
EDIT:
I think I found what I was looking for in the boost library, as mentioned below.
boost regex-token-iterator (why don't underscores work?)
I guess I didn't know what to search for.
#include <iostream>
#include <boost/regex.hpp>
using namespace std;
int main(int argc)
{
string s;
do{
if(argc == 1)
{
cout << "Enter text to split (or \"quit\" to exit): ";
getline(cin, s);
if(s == "quit") break;
}
else
s = "This is a string of tokens";
boost::regex re("\\s+");
boost::sregex_token_iterator i(s.begin(), s.end(), re, -1);
boost::sregex_token_iterator j;
unsigned count = 0;
while(i != j)
{
cout << *i++ << endl;
count++;
}
cout << "There were " << count << " tokens found." << endl;
}while(argc == 1);
return 0;
}
|
The boost libraries are usually a good choice, in this case Boost.Regex. There even is an example for splitting a string into tokens that already does what you want. Basically it comes down to something like this:
boost::regex re("[\\sXY]+");
std::string s;
while (std::getline(std::cin, s)) {
boost::sregex_token_iterator i(s.begin(), s.end(), re, -1);
boost::sregex_token_iterator j;
while (i != j) {
std::cout << *i++ << " ";
}
std::cout << std::endl;
}
|
992,209
| 992,283
|
using a template class as an argument
|
Is there any way of creating a function that accepts any version of a given
template class?
e.g. this works:
ostream& operator << (ostream &out,const Vector<int>& vec);
but this doesn't:
ostream& operator << (ostream &out,const Vector& vec);
Is it possible to get the second line to work somehow for any version of vector?
e.g. vector<int> and vector<double> without having to write 2 separate functions?
Added to question:
I've made op<< a template function like you've suggested. In order to make it a friend function of the vector class I tried adding the following to the Vector class definition, but it didn't work:
friend ostream& operator << (ostream &out, const Vector<T>& vec);
any ideas what can be done to fix it?
|
As already pointed out something like this should work:
template <typename T>
ostream& operator << (ostream &out,const Vector<T>& vec) {
// body here
}
As for the friend requirement, that is most easily handled like this:
template <typename T>
ostream& operator << (ostream &out,const Vector<T>& vec) {
vec.print_on( out );
return out;
}
However, normally I would think of any output operator like this that requires access to the internals of the class to be showing you a mistake in your Vector class. It really only ought to need to use the public interface to do the display.
The other thing is that you might also want to template the output stream itself so that you can preserve its type:
template <typename O, typename C, typename T>
std::basic_ostream<O, C>& operator << (std::basic_ostream<O, C> &out,const Vector<T>& vec) {
vec.print_on( out );
return out;
}
The Vector's print_on can still use ostream.
|
992,272
| 992,284
|
operator () overload with template C++
|
I have a simple class for which I want to overload operator as below
class MyClass
{
public:
int first;
template <typename T>
T operator () () const { return first; }
};
And the somewhere else I have
MyClass obj;
int i = obj(); // This gives me an error saying could not deduce
// template argument for T
Can someone help me with this error, much appreciated. Thank you.
edit:
This has something to do with the operator(), for example if i replace the function with
template <typename T>
T get() const { return first;}
it works. Appreciate all the responses.
|
If you wish the function call to be implicit then you'll have to apply the template to the class like this:
template <typename T>
class MyClass
{
public:
T first;
T operator () () const { return first; }
};
If it should be casted to another type then it should be:
template <typename T>
class MyClass
{
public:
T first;
template <typename U>
U operator () () const { return (U)first; }
};
|
992,320
| 992,361
|
Can operators be used as functions? (C++)
|
This is similar to another question I've asked, but, I've created an expression class that works like so:
expression<int, int> exp(10, 11, GreaterThan);
//expression<typename T, typename U> exp(T val1, U val2, oper op);
//where oper is a pointer to bool function(T, U)
where GreaterThan is a previously defined function. And I am wondering why I can't do this:
expression<int, int> exp(10, 11, >);
particularily when > is overloaded as
bool operator>(int a, int a){return (a > b);}
which is identical to GreaterThan:
bool GreaterThan(int a, int b){return (a > b);}
A function that returns bool and takes two arguments.
|
Instead of:
expression<int, int> exp(10, 11, >);
you could do this:
expression<int, int> exp(10, 11, operator>);
You could because it doesn't work for integers. But it will work for other types or operators that you will overload.
The operators that you overload are normal functions, so actually you are playing with function pointers.
|
992,435
| 992,445
|
C++ basic constructors/vectors problem (1 constructor, 2 destructors)
|
Question is probably pretty basic, but can't find out what's wrong (and it leads to huge of memleaks in my app):
class MyClass {
public:
MyClass() { cout << "constructor();\n"; };
MyClass operator= (const MyClass& b){
cout << "operator=;\n"; return MyClass();
};
~MyClass() { cout << "destructor();\n"; };
};
main() {
cout << "1\n";
vector<MyClass> a;
cout << "2\n";
MyClass b;
cout << "3\n";
a.push_back(b);
cout << "4\n";
}
The output is:
1
2
constructor();
3
4
destructor();
destructor();
Why are there 2 destructors?
If it's because a copy is created to be inserted into vector - how come "operator=" is never called?
|
When the b object gets pushed onto the vector a copy is made, but not by the operator=() you have - the compiler generated copy constructor is used.
When the main() goes out of scope, the b object is destroyed and the copy in the vector is destroyed.
Add an explicit copy constructor to see this:
MyClass( MyClass const& other) {
cout << "copy ctor\n";
};
|
992,471
| 992,476
|
how to query if(T==int) with template class
|
When I'm writing a function in a template class how can I find out what my T is?
e.g.
template <typename T>
ostream& operator << (ostream &out,Vector<T>& vec)
{
if (typename T == int)
}
How can I write the above if statement so it works?
|
Something like this:
template< class T >
struct TypeIsInt
{
static const bool value = false;
};
template<>
struct TypeIsInt< int >
{
static const bool value = true;
};
template <typename T>
ostream& operator << (ostream &out,Vector<T>& vec)
{
if (TypeIsInt< T >::value)
// ...
}
|
992,661
| 992,917
|
using checkTokenMemberShip return always true even if the process user is not administrator
|
the following is the code I'm using (copied from msdn) but even when the the pocess user is not a local admin it returns as if it is any ideas?
BOOL IsUserAdmin(VOID)
/*++
Routine Description: This routine returns TRUE if the caller's
process is a member of the Administrators local group. Caller is NOT
expected to be impersonating anyone and is expected to be able to
open its own process and process token.
Arguments: None.
Return Value:
TRUE - Caller has Administrators local group.
FALSE - Caller does not have Administrators local group. --
*/
{
BOOL b;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
b = AllocateAndInitializeSid(
&NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&AdministratorsGroup);
if(b)
{
if (!CheckTokenMembership( NULL, AdministratorsGroup, &b))
{
b = FALSE;
}
FreeSid(AdministratorsGroup);
}
return(b);
}
|
In the MSDN doc here... There is a note mentioning issues when using this on VISTA (or later).
To paraphrase, if you're using this on Vista - the API will return true - because of the way Vista uses a split token for security.
Here is the original note (originally written by tchao):
When UAC is enabled in Windows
Vista--which is the default setup, a
thread in an administrator account
will have a pair of split tokens: a
filtered token and an elevated token.
The filtered token will have the local
administrators group SID in its group,
but that SID is not enabled until the
thread gets the elevated token after
user's approval via the UAC dialog or
programmatically. The above sample
code shows that both a filtered
administrator token and an elevated
administrator token as having the
local administrators group SID
"enabled," but that is not the case
with the filtered administrator token
which has its TOKEN_ELEVATION_TYPE as
TokenElevationTypeLimited.
If you look at the local
administrators group association with
the administrator filtered token, it's
for deny only, but
CheckTokenMembership() will show that
the administrator filtered token is a
member (enabled?) of the local
administrators group. Perhaps this is
also a function implementation bug?!
|
992,717
| 992,780
|
Error C2228 when constructing boost::function object in constructor argument list
|
The code below does not compile in Visual C++ 2005.
class SomeClass {
public: boost::function<void()> func;
SomeClass(boost::function<void()> &func): func(func) { }
};
void someFunc() {
std::cout << "someFunc" << std::endl;
}
int main() {
SomeClass sc(boost::function<void()>(&someFunc));
sc.func(); // error C2228: left of '.func' must have class/struct/union
return 0;
}
If I put parentheses around the argument to the SomeClass constructor or constructs the boost::function object outside the argument list it compiles fine.
SomeClass sc((boost::function<void()>(&someFunc)));
// or
boost::function<void()> f(&someFunc);
SomeClass sc(f);
What is the problem with the previous code?
|
It's a function declaration for a function taking a reference to a boost:function <void()> and returning a SomeClass. You can memorize the following rule, which turns out to apply to many other such disambiguation cases. You can find descriptions of these cases in section 8.2 of the C++ Standard.
Any construct that could possibly be a declaration will be taken as a declaration
That means, the following will be taken as a parameter declaration, with superfluous parentheses
boost::function<void()>(&someFunc)
If you remove the parentheses, this will become clear
boost::function<void()> &someFunc
And thus, the whole declaration will not anymore declare an object, but a function
SomeClass sc(boost::function<void()> &someFunc);
To fix it, use the cast-notation
SomeClass sc((boost::function<void()>)&someFunc);
Or put parentheses around the whole expression, like you did.
Here is the Standard in all its glory from 8.2:
The ambiguity arising from the similarity between a function-style cast and a declaration mentioned in 6.8 can also occur in the context of a declaration. In that context, the choice is between a function declaration with a redundant set of parentheses around a parameter name and an object declaration with a function-style cast as the initializer. Just as for the ambiguities mentioned in 6.8, the resolution is to consider any construct that could possibly be a declaration a declaration. [Note: a declaration can be explicitly disambiguated by a nonfunction-style cast, by a = to indicate initialization or by removing the redundant parentheses around the parameter name. ]
Note that for controlling precedence, you are allowed to introduce parentheses just about anywhere, like in the following
int (((((((a))))))) = 3;
int (*(pa)) = &a;
|
992,760
| 992,779
|
Write to registry in Windows Vista
|
I am trying to write to the registry from my application, but when I do I get access denied. Of course, it works if i run the app as Administrator. However, with my applcation, it is not initiated by the user. It start automatically.
So, the question is, how do i read/write to my own registry key from the C++ app?
Thanks for any help.
|
Write to HKEY_CURRENT_USER
And check out this posts
Vista + VB.NET - Access Denied while writing to HKEY_LOCAL_MACHINE
Writing string (REG_SZ) values to the registry in C++
How to read registry branch HKEY_LOCAL_MACHINE in Vista?
|
992,836
| 992,876
|
How to access the Java method in a C++ application
|
Just a simple question:
Is it possible to call a java function from c/c++ ?
|
Yes you can, but it is a little convoluted, and works in a reflective/non type safe way (example uses the C++ api which is a little cleaner than the C version). In this case it creates an instance of the Java VM from within the C code. If your native code is first being called from Java then there is no need to construct a VM instance
#include<jni.h>
#include<stdio.h>
int main(int argc, char** argv) {
JavaVM *vm;
JNIEnv *env;
JavaVMInitArgs vm_args;
vm_args.version = JNI_VERSION_1_2;
vm_args.nOptions = 0;
vm_args.ignoreUnrecognized = 1;
// Construct a VM
jint res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args);
// Construct a String
jstring jstr = env->NewStringUTF("Hello World");
// First get the class that contains the method you need to call
jclass clazz = env->FindClass("java/lang/String");
// Get the method that you want to call
jmethodID to_lower = env->GetMethodID(clazz, "toLowerCase",
"()Ljava/lang/String;");
// Call the method on the object
jobject result = env->CallObjectMethod(jstr, to_lower);
// Get a C-style string
const char* str = env->GetStringUTFChars((jstring) result, NULL);
printf("%s\n", str);
// Clean up
env->ReleaseStringUTFChars(jstr, str);
// Shutdown the VM.
vm->DestroyJavaVM();
}
To compile (on Ubuntu):
g++ -I/usr/lib/jvm/java-6-sun/include \
-I/usr/lib/jvm/java-6-sun/include/linux \
-L/usr/lib/jvm/java-6-sun/jre/lib/i386/server/ -ljvm jnitest.cc
Note: that the return code from each of these methods should be checked in order to implement correct error handling (I've ignored this for convenience). E.g.
str = env->GetStringUTFChars(jstr, NULL);
if (str == NULL) {
return; /* out of memory */
}
|
992,919
| 993,797
|
How to set up Win32 tooltips control with dynamic unicode text?
|
I am having some trouble provding a Win32 tooltips control with dynamic text in unicode format. I use the following code to set up the control:
INITCOMMONCONTROLSEX icc;
icc.dwSize = sizeof(INITCOMMONCONTROLSEX);
icc.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&icc);
HWND hwnd_tip = CreateWindowExW(0, TOOLTIPS_CLASSW, NULL,
WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hinst, NULL
);
SetWindowPos(hwnd_tip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
TOOLINFOW ti;
memset(&ti, 0, sizeof(TOOLINFOW));
ti.cbSize = sizeof(TOOLINFOW);
ti.hwnd = hwnd_main;
ti.uId = (UINT) hwnd_control;
ti.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
ti.lpszText = L"This tip is shown correctly, including unicode characters.";
SendMessageW(hwnd_tip, TTM_ADDTOOLW, 0, (LPARAM) &ti);
This works fine as long as I provide the tooltip text in ti.lpszText. However, I want the text to be dynamic, so instead I set ti.lpszText to LPSTR_TEXTCALLBACKW and handle the callback in my WindowProc(), like this:
...
case WM_NOTIFY:
{
NMHDR *nm = (NMHDR *) lParam;
switch (nm->code)
{
case TTN_GETDISPINFOW:
{
static std::wstring tip_string = L"Some random unicode string.";
NMTTDISPINFOW *nmtdi = (NMTTDISPINFOW *) lParam;
nmtdi->lpszText = (LPWSTR) tip_string.c_str();
}
break;
}
}
break;
...
Which does not work, as I never receive the TTN_GETDISPINOW message. (Note: It works if I handle TTN_GETDISPINFO instead and use NMTTDISPINFO to provide a char array, but then no unicode support...)
I'm guessing I'm doing something wrong in my setup or message handling here? Any suggestions on how to do it properly?
Update
Also note that my project is not compiled in unicoe mode (i.e. _UNICODE is not defined and the project is set to use multi-byte character set). This is intentional and I would like to keep it like that as, I have no desire to rewrite the entire application to be unicode-aware (at least not yet). Since the _UNICODE define is used to select *W versions of various functions and data structures I was hoping I could achieve the same result by using these explicitly in my code, as shown above.
|
Thanks for the Robert Scott link. I found a way to solve it now.
In short, the trick was to make sure the receiving window was a unicode window and register a unicode window procedure for it.
The problem was that I did not have a unicode WindowProc() for my parent window handling the TTN_GETDISPINFOW notification message. Since this window (class) was created with RegisterClassEx()/CreateWindowEx() and not RegisterClassExW()/CreateWindowExW(), it did not have registered window procedure for unicode messages.
To get around the problem I changed ti.hwnd from hwnd_main to hwnd_control when sending TTM_ADDTOOLW, resulting in the control's window procedure receving the notifications instead of its parent. In order to intercept the unicode events now sent to the control's window procedure, I subclassed it using SetWindowLongW(hwnd_control, GWL_WNDPROC, (LONG) NewControlWndProc).
Note that hwnd_control is a standard "LISTBOX" window created with CreateWindowExW() and is therefore unicode-aware, since all buildt-in Windows classes are automatically registered in both unicode and ANSI version by the system.
|
992,924
| 992,933
|
importance of freeing memory?
|
Possible Duplicate:
What REALLY happens when you don’t free after malloc?
When ending a program in C/C++, you have to clean up by freeing pointers. What happens if you doesn't free the memory, like if you have a pointer to an int and doesn't delete it when ending the program? Is the memory still used and can only be freed by restart, or is it automatically freed when the program ends? And in the last case, why free it, if the operating system does it for you?
|
When your program ends all of the memory will be freed by the operating system.
The reason you should free it yourself is that memory is a finite resource within your running program. Sure in very short running simple programs, failing to free memory won't have a noticable effect. However on long running programs, failing to free memory means you will be consuming a finite resource without replenishing it. Eventually it will run out and your program will rudely crash. This is why you must free memory.
|
993,076
| 993,351
|
working with fstream files in overflow chaining in c++
|
I have a file that I want to read and write to a binary file using records. In the beginning I have an empty file and I want to add new record, but when I use the seekp function, then the location is at (-1) is it ok? Because when I check, I see that it hasnt written anything to the file. See code:
void Library::addBook(Book newBook)
{
fstream dataFile;
dataFile.open("BookData.dat", ios::in | ios::out);
if (!dataFile)
{
cerr << "File could not be opened" << endl;
}
int hashResult = newBook.getId() % 4 + 1; // The result of the hash function
// Find the right place to place the new book
dataFile.seekg((hashResult - 1) * sizeof(Book), ios::beg);
Book readBook;
dataFile.read(reinterpret_cast<char*>(&readBook), sizeof(Book));
// The record doesnt exist or it has been deleted
if (readBook.getId() == -1)
{
// The record doesnt exist
if (readBook.getIdPtr() == -1)
{
dataFile.seekp((hashResult - 1) * sizeof(Book));
dataFile.write(reinterpret_cast<char*>(&newBook), sizeof(Book));
}
// The record has been deleted or there is already such record with such hash function
// so we need to follow the pointer to the overflow file
else
{
newBook.setIsBookInData(false); // New book is in overflow file
overflowFile.seekg((readBook.getIdPtr() - 1) * sizeof(Book));
overflowFile.read(reinterpret_cast<char*>(&readBook), sizeof(Book));
// Follow the chain
while (readBook.getIdPtr() != -1)
{
overflowFile.seekg((readBook.getIdPtr() - 1) * sizeof(Book));
overflowFile.read(reinterpret_cast<char*>(&readBook), sizeof(Book));
}
readBook.setIdPtr(header); // Make the pointer to point to the new book
overflowFile.seekp((header - 1) * sizeof(Book));
overflowFile.write(reinterpret_cast<char*>(&newBook), sizeof(Book));
header++;
}
}
If anyone can tell me why I cant write anything to the file I will really appriciate it.
Thanks in advance,
Greg
|
Well here are a few suggestions that may help:
when you open the file, use ios_base::binary flag
make sure that Book is a POD (i.e. a C compatible type)
make sure that when you read or write that the stream is in a valid state before and after
don't use readBook.getId() == -1 to check if the read succeeded
make sure that when you seek into the stream you're not going past the end of file
use the buffer to get the total number of bytes in the file and then ensure that you don't exceed it before seeking
whenever you seek, do a relative seek (use ios_base::beg for e.g)
use static_cast<char*>(static_cast<void*>(&book)) vs reinterpret cast<char*>
If you have any specific questions about any of those suggestions, let us know and perhaps we can guide you better.
|
993,262
| 993,402
|
How does the C++ runtime determine the type of a thrown exception?
|
If I do the following, how does the runtime determine the type of the thrown exception? Does it use RTTI for that?
try
{
dostuff(); // throws something
}
catch(int e)
{
// ..
}
catch (const char * e)
{
// ..
}
catch (const myexceptiontype * e)
{
// ..
}
catch (myexceptiontype e) // is this the same as the previous handler?
{
// ..
}
See also:
How is the C++ exception handling runtime implemented?
|
Unlike the concerns asked in that other questions, the answer to this question can be answered entirely by means of the Standard. Here are the rules
A handler is a match for an exception object of type E if
The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or
the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or
the handler is of type cv1 T* cv2 and E is a pointer type that can be converted to the type of the handler by either or both of
a standard pointer conversion (4.10) not involving conversions to pointers to private or protected or ambiguous classes
a qualification conversion
[Note: a throw-expression which is an integral constant expression of integer type that evaluates to zero
does not match a handler of pointer type; that is, the null pointer constant conversions (4.10, 4.11) do not
apply. ]
As i'm not quite sure about your level of understanding of the Standard, i will leave this unexplained, and answer as you ask.
With regard to whether it uses RTTI or not - well, the type of the exception object being thrown is the static type of the expression you hand over to the throw statement (some time ago, i had fun figuring this out in GCC). So it does not need to do runtime type identification. So it happens, with g++, that at the side where the throw appears, it hands over a std::type_info object representing the type of the exception object, the object itself and a destructor function.
It's then thrown and frames are searched for a matching handler. Using information found in big tables (located in a section called .eh_frame), and using the return address, it looks what function is responsible for the next handling. The function will have a personality routine installed that figures out whether it can handle the exception or not. This whole procedure is described (and in more detail, of course) in the Itanium C++ ABI (implemented by G++) linked by @PaV.
So, to conclude
myexceptiontype e
and
const myexceptiontype *e
Do not handle the same type, of course.
|
993,352
| 993,385
|
When should I make explicit use of the `this` pointer?
|
When should I explicitly write this->member in a method of
a class?
|
Usually, you do not have to, this-> is implied.
Sometimes, there is a name ambiguity, where it can be used to disambiguate class members and local variables. However, here is a completely different case where this-> is explicitly required.
Consider the following code:
template<class T>
struct A {
T i;
};
template<class T>
struct B : A<T> {
T foo() {
return this->i; //standard accepted by all compilers
//return i; //clang and gcc will fail
//clang 13.1.6: use of undeclared identifier 'i'
//gcc 11.3.0: 'i' was not declared in this scope
//Microsoft C++ Compiler 2019 will accept it
}
};
int main() {
B<int> b;
b.foo();
}
If you omit this->, some compilers do not know how to treat i. In order to tell it that i is indeed a member of A<T>, for any T, the this-> prefix is required.
Note: it is possible to still omit this-> prefix by using:
template<class T>
struct B : A<T> {
int foo() {
return A<T>::i; // explicitly refer to a variable in the base class
//where 'i' is now known to exist
}
};
|
993,505
| 993,513
|
Where to put the enum in a cpp program?
|
I have a program that uses enum types.
enum Type{a,b,};
class A
{
//use Type
};
class B
{
// also use that Type
};
2 class are located in 2 different files.
Should I put the type definition in a headfile or
in class definition for each class?
|
If the enum is going to be used in more than one .cpp file, you should put it in a header file that will be included by each. If there's a common header file, you should use that, otherwise you may as well create a new header file for this enum
|
993,590
| 993,605
|
Should I delete vector<string>?
|
I've painfully learned during last few days a lot about programming in c++.
I love it :)
I know I should release memory - the golden "each malloc=free" or "each new=delete" rules exist now in my world, but I'm using them to rather simple objects.
What about vector ? Wherever I can, I'm using vector.clear() but that clearly isn't enough, because I'm having huge memory leaks.
Could you guide me on how should I treat this thing?
*Edit
Thanks, your comments made me think about the alghorithm of this application and I'll be able to eliminate the vector totally. :O
Sorry - I started explaining what is my use case here and I found out what I really need. It's like that when you code last 3 days for 18 hours a day :|
*Edit 2
This is crazy. By small changes in code, I've eliminated memory usage from 2x130 mb (constantly growing) into 2x 13,5mb, constant size. Thanks for making me think about that in another way.
Btw. such self code review got a name - anyone remember that? It's when you ask anyone (even your mother or dog) and start explaining what's your problem - and suddenly you solve this 5 hour problem yourself, just by trying to look at it from other point of view, or just by trying to summarize what's it all about. I often find myself being catched on that...
|
The rule is that when you clear a vector of objects, the destructor of each element will be called. On the other hand, if you have a vector of pointers, vector::clear() will not call delete on them, and you have to delete them yourself.
So if all you have is a vector of strings, and not pointers to strings, then your memory leaks must be caused by something else.
|
993,630
| 993,636
|
How can I configure my project to generate platform independent code?
|
I am writing an application that I would like to release binaries for on Mac, Windows, and Linux. I have code that compiles under Mac and Linux, but under Windows, it does not.
This is because of Windows lack of a strcasecmp. I've read a little bit about how I can create some sort of header to wrap my code, but I don't really understand this concept too well. I've worked on the code on my Mac with just vim and make, but now I'm trying to switch it all over to Visual Studio.
Is there some way I can set my project up to include Windows wrapper headers when I'm building on Windows, but omit them when I'm building on my Mac or Linux box?
This problem is really giving me a headache and I'd appreciate any suggestions!
|
You could do
#ifdef WIN32
#include <windows_specific_header.h>
#else
#include <other_header.h>
There is also an MS Visual Studio-specific macro: _MSC_VER, so
#ifdef _MSC_VER
would also work here.
There is also WINVER define in windows.h.
|
993,777
| 994,241
|
Cross-platform transparent windows in C++?
|
I'm wondering how to make a window transparent, not cutout holes or the same transparency overall.
Well, just say I want to slap a PNG image of a rose or something and have it blend nicely with stuff behind and allow stuff behind to redraw and have their changes shine through the transparent parts of the picture/window.
I could (or would like to) use something like wxWidgets or OpenGL. But rather not Qt or GTK.
|
I found out that it's actually pretty simple to throw up a transparent picture on the screen using wxW:
wxScreenDC dc;
wxBitmap bmp(wxT("test.png"), wxBITMAP_TYPE_PNG);
dc.DrawBitmap(bmp, 250, 100, true);
Now I has to find out how to handle updates and such, it has to be ( maybe partially redrawn ) when something beneath updates.
As it is right now it just redraws itself ontop of itself, making it become fully opacue in a while.
There was another version of wxScreenDC::DrawBitmap that took a window as an argument, maybe it's that one solves this?
|
993,922
| 994,026
|
Weird striping in tile graphics on Nintendo DS
|
I'm working on a pong game for the Nintendo DS. I'm using libnds to set things up and I've come across a very strange behaviour. So far I've only tried it out in emulators, but I use three different ones and they all exhibit this behaviour so I suspect I'm doing something bad.
The actual problem is that when I use background layer 1 or above for my tiled graphics, I get weird stripes all over that layer. If I use background layer 0 the problem goes away, but since that is rendered last, I cannot actually draw over it in another layer, which I want to.
My setup code:
void pong::setup_engine()
{
// Setup DS graphics engine.
// -------------------------
videoSetMode(MODE_5_2D | DISPLAY_BG0_ACTIVE | DISPLAY_BG1_ACTIVE | DISPLAY_BG2_ACTIVE);
vramSetBankA(VRAM_A_MAIN_BG_0x06000000);
vramSetBankB(VRAM_B_MAIN_BG_0x06020000);
u8 *tileMemory = reinterpret_cast<u8 *>(BG_TILE_RAM(1));
u16 *mapMemory = reinterpret_cast<u16 *>(BG_MAP_RAM(0));
int bg0 = bgInit(1, BgType_Text8bpp, BgSize_T_256x256, 0, 1);
int bg1 = bgInit(2, BgType_Bmp16, BgSize_B16_256x256, 0, 0);
//bgScroll(bg0, 256, 256);
u16 *ptr = bgGetGfxPtr(bg1);
for (int y = 10; y < 128*60; y++)
{
ptr[y] = 0xFFFF;
}
BG_PALETTE[1] = grey0;
BG_PALETTE[2] = grey1;
BG_PALETTE[3] = grey2;
BG_PALETTE[4] = grey3;
BG_PALETTE[5] = grey4;
BG_PALETTE[6] = grey5;
BG_PALETTE[7] = grey6;
// 32 here is not 32 bytes but 32 half-words, which is 64 bytes.
swiCopy(CORNER_TILE, tileMemory, 32);
swiCopy(TOP_TILE, tileMemory + 64, 32);
swiCopy(SIDE_TILE, tileMemory + (64 * 2), 32);
swiCopy(MAIN_TILE, tileMemory + (64 * 3), 32);
swiCopy(MAP, mapMemory, 32*24);
}
In the above code I use layer 1 for bg0, which is my tiled graphics layer. This makes the weird stripes appear; if I were to change it to 0 like this, it would show up as expected:
int bg0 = bgInit(0, BgType_Text8bpp, BgSize_T_256x256, 0, 1);
Any ideas what causes the problem, and what the solution is?
|
a breif look at background.h makes it look like you are using BG1 and BG2. For mode 5, according to:
http://nocash.emubase.de/gbatek.htm
layer 0 and 1 are normal and 2 and 3 are extended. I dont know what extended means. If you want to just do normal tile stuff you probably want to bgInit 0 and 1 not 1 and 2.
You can change the priorities around at will, layer 0 is not necessarily on top of 1, etc. Look at the BGxCNT registers (BG0CNT, BG1CNT,...) and the priority bits. Now if the priority is a tie then yes the layer number determines who wins.
|
994,139
| 994,186
|
Advice on wrapping third party libraries
|
I have been working a year now as a software developer for a at the computer-vision department of a company. My main job is integration of third-party software into a framework, so i usually end up writing wrapper libraries because a lot of this third party software does not work the way we want it to work(not thread safe, pain in the a** to use etc.).
Normally i just wrap the whole library and guard the calls to the library with mutual exclusions(thread safety is somehow the major problem with most extern libraries). I really enjoy doing this, as it puts you into a lot of interesting situations and you get to see a lot of interesting code. However i often think that i am not doing it properly or that my implementation is not really good. I feel like i am lacking some sort of design knowledge on how to properly do stuff like that.
Basically i want to know if there are any good guidelines or hints about designing a proper 'API ontop of broken API', or if this is always bound to be quite hackish and ugly.
|
I will quote an answer to another question on here the other day:
Does your current method pass testing?
Is it fast enough?
If yes, keep doing what you are doing.
As an alternative
Just ensure your new API encompasses both the intended functionality and the conventional or accidental functionality of the original. Also ensure it presents a 'fit-for-purpose' re-presentation. Take a peek at the C++ wrapping of C libraries in FOSS projects such as GTK/GTK for C++ (which just wraps the former).
If the API is broken, fix it and submit a patch ... get involved with the third-parties (I am assuming having access to the source means they won't mind this) ... You could re-write some of their API to be 'wrapping friendly' and suggest they merge some changes. If there is a problem, be the one to fix it.
Not much to it, just wrap A with B and ensure B does what A was supposed to, or is used for.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.