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
|
---|---|---|---|---|
142,602 | 142,683 |
How to revive C++ skills
|
I was a C++ developer (mostly ATL/COM stuff) until, as many of us, I switched to C# in 2001. I didn't do much C++ programming since then.
Do you have any tips on how to revive my C++ skills? What has changed in C++ in the last years? Are there good books, articles or blogs covering the language. The problem is that most material I could find either targets people who are new to the language or those with a lot of experience.
Which C++ libraries are popular these days? I guess I will need to read on the STL because I didn't use it much. What else? Boost? ATL? WTL?
|
I personally find that syntax is where i mostly need to catch up when i wander back to a language i havent used in a long time. But the concepts and what the language is about stays the same in memory.
Assuming its the same with you, i would say its a good idea to relook at the texts you remember to have been useful to you while learning C++. I would recommned Thinking in C++ for getting up fast on the syntax.
STL would be really useful yes. Thats one thing i have found commonly appreciated by all mature C++ programmers. It would be useful to know the libraries that Boost provides.
The changes to C++ world, depends on the changes your favourite compiler has decided to implement. Since you mentioned ATl/COM i assume it would be VC++. The changes to MFC would be support for Windows Forms (2005 vc++) and Vista compliant uI's and ribbon support(?) (2008 Vc++)
VC++ now supports managed C++ -i'm sure you know what that is coming from the C# world - 2008 adds supports for managed STL too.
VC++ is trying to be more standards compliant and are making some progress in that area.
They have introduced lots of secure functions that depreciate the old stds like strcpy and the compilers will also give warnings if you use the old fns.
VC++2005 also has something called function attributes, which it uses to describe the parameters so that it can do more checking on the inputs you pass in and statically flag a warning if it sees soething amiss. Usefuli would say though our shop has not progressed to using the 2005 compiler.
MSDN has the list of breaking changes for each releases. Oh & Support for Windows 95, Windows 98, Windows Millennium Edition, and Windows NT 4.0 has been removed from 2005 version of VC++. Additionally the core libraries you required till now (CRT, ATL, MFC etc) now support a new deployment model which makes them shared side sy side assemblies and requires a manifest.
This link should get you going - http://msdn.microsoft.com/en-us/library/y8bt6w34.aspx
2008 adds even more like Tr1 recommendations, more optimizning compiler, parallel compilation(/mp), support for new processor architectures etc. Open Mp support has also been enhanced in one of these versions is what i remember.
Again refer MSDN - thats the suthentic source for all the answers.
Good luck.
|
142,804 | 143,131 |
Network Multithreading
|
I'm programming an online game for two reasons, one to familiarize myself with server/client requests in a realtime environment (as opposed to something like a typical web browser, which is not realtime) and to actually get my hands wet in that area, so I can proceed to actually properly design one.
Anywho, I'm doing this in C++, and I've been using winsock to handle my basic, basic network tests. I obviously want to use a framelimiter and have 3D going and all of that at some point, and my main issue is that when I do a send() or receive(), the program kindly idles there and waits for a response. That would lead to maybe 8 fps on even the best internet connection.
So the obvious solution to me is to take the networking code out of the main process and start it up in its own thread. Ideally, I would call a "send" in my main process which would pass the networking thread a pointer to the message, and then periodically (every frame) check to see if the networking thread had received the reply, or timed out, or what have you. In a perfect world, I would actually have 2 or more networking threads running simultaneously, so that I could say run a chat window and do a background download of a piece of armor and still allow the player to run around all at once.
The bulk of my problem is that this is a new thing to me. I understand the concept of threading, but I can see some serious issues, like what happens if two threads try to read/write the same memory address at the same time, etc. I know that there are already methods in place to handle this sort of thing, so I'm looking for suggestions on the best way to implement something like this. Basically, I need thread A to be able to start a process in thread B by sending a chunk of data, poll thread B's status, and then receive the reply, also as a chunk of data., ideally without any major crashing going on. ^_^ I'll worry about what that data actually contains and how to handle dropped packets, etc later, I just need to get that happening first.
Thanks for any help/advice.
PS: Just thought about this, may make the question simpler. Is there a way to use the windows event handling system to my advantage? Like, would it be possible to have thread A initialize data somewhere, then trigger an event in thread B to have it pick up the data, and vice versa for thread B to tell thread A it was done? That would probably solve a lot of my problems, since I don't really need both threads to be able to work on the data at the same time, more of a baton pass really. I just don't know if this is possible between two different threads. (I know one thread can create its own messages for the event handler.)
|
The easiest thing
for you to do, would be to simply invoke the windows API QueueUserWorkItem. All you have to specify is the function that the thread will execute and the input passed to it. A thread pool will be automatically created for you and the jobs executed in it. New threads will be created as and when is required.
http://msdn.microsoft.com/en-us/library/ms684957(VS.85).aspx
More Control
You could have a more detailed control using another set of API's which can again manage the thread pool for you -
http://msdn.microsoft.com/en-us/library/ms686980(VS.85).aspx
Do it yourself
If you want to control all aspects of your thread creation and the pool management you would have to create the threads yourself, decide how they should end , how many to create etc (beginthreadex is the api you should be using to create threads. If you use MFC you should use AfxBeginThread function).
Send jobs to worker threads - Io completion Ports
In this case, you would also have to worry about how to communicate your jobs - i would recommend IoCOmpletionPorts to do that. It is the most scalable notification mechanism that i currently know of made for this purpose. It has the additional advantage that it is implemented in the kernel so you avoid all kinds of dead loack sitautions you would encounter if you decide to handroll something yourself.
This article will show you how with code samples -
http://blogs.msdn.com/larryosterman/archive/2004/03/29/101329.aspx
Communicate Back - Windows Messages
You could use windows messages to communicate the status back to your parent thread since it is doing the message wait anyway. use the PostMessage function to do this. (and check for errors)
ps : You could also allocate the data that needs to be sent out on a dedicated pointer and then the worker thread could take care of deleting it after sending it out. That way you avoid the return pointer traffic too.
|
142,877 | 142,921 |
Can the C preprocessor be used to tell if a file exists?
|
I have a very large codebase (read: thousands of modules) that has code shared across numerous projects that all run on different operating systems with different C++ compilers. Needless to say, maintaining the build process can be quite a chore.
There are several places in the codebase where it would clean up the code substantially if only there were a way to make the pre-processor ignore certain #includes if the file didn't exist in the current folder. Does anyone know a way to achieve that?
Presently, we use an #ifdef around the #include in the shared file, with a second project-specific file that #defines whether or not the #include exists in the project. This works, but it's ugly. People often forget to properly update the definitions when they add or remove files from the project. I've contemplated writing a pre-build tool to keep this file up to date, but if there's a platform-independent way to do this with the preprocessor I'd much rather do it that way instead. Any ideas?
|
Generally this is done by using a script that tries running the preprocessor on an attempt at including the file. Depending on if the preprocessor returns an error, the script updates a generated .h file with an appropriate #define (or #undef). In bash, the script might look vaguely like this:
cat > .test.h <<'EOM'
#include <asdf.h>
EOM
if gcc -E .test.h
then
echo '#define HAVE_ASDF_H 1' >> config.h
else
echo '#ifdef HAVE_ASDF_H' >> config.h
echo '# undef HAVE_ASDF_H' >> config.h
echo '#endif' >> config.h
fi
A pretty thorough framework for portably working with portability checks like this (as well as thousands others) is autoconf.
|
143,006 | 143,007 |
Why does my MFC app hang when I throw an exception?
|
If you throw an exception from inside an MFC dialog, the app hangs, even if you have a catch block in your code. It refuses to respond to the mouse or keyboard, and the only way to shut it down is to use Task Manager.
Why I'm posting this question
To my shame, there is a popular shrink-wrapped application that hangs every time it encounters an exceptional error in a modal dialog. When we made a massive shift from integer error codes to exceptions, I was responsible for choosing std::exception as the base class for the thrown exceptions. It wasn't until a huge amount of work went into the conversion that our testing uncovered this problem, and by then it was too late to change. Hopefully this question/answer will keep someone from making the same mistake.
|
The code for CDialog::DoModal makes the dialog modal by disabling the parent window. When the dialog code returns, the window is reenabled. There is an explicit catch for CException* errors, but not for any other kind of thrown exception; thus the parent window never gets reenabled.
Change your code to throw a pointer to any exception derived from CException, and you'll fix the problem.
|
143,073 | 206,081 |
Debugging C++ STL containers in Windbg
|
Windbg fans claim that it is quite powerful and I tend to agree. But when it comes to debugging STL containers, I am always stuck. If the variable is on the stack, the !stl extension sometimes figures it out, but when a container with a complex type (e.g. std::vector<TemplateField, std::allocator<TemplateField> >) is on the heap or part of some other structure, I just don't know how to view its contents.
Appreciate any tips, pointers.
|
You might also want to give this debugger extension a try. It is a library called SDbgExt, developed by Skywing.
|
143,174 | 198,099 |
How do I get the directory that a program is running from?
|
Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're standard ones like clib or STL.)
(If there's no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.)
|
Here's code to get the full path to the executing app:
Variable declarations:
char pBuf[256];
size_t len = sizeof(pBuf);
Windows:
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;
Linux:
int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '\0';
return bytes;
|
143,233 | 143,239 |
How to redirect data to stdin within a single executable?
|
I am using cxxtest as the test framework for my C++ classes, and would like to figure out a way to simulate sending data to classes which would normally expect to receive it from standard input. I have several different files which I would like to send to the classes during different tests, so redirection from the command line to the test suite executable is not an option.
Basically, what I would really like to do is find a way to redefine or redirect the 'stdin' handle to some other value that I create inside of my program, and then use fwrite() from these tests so that the corresponding fread() inside of the class pulls the data from within the program, not from the actual standard I/O handles associated with the executable.
Is this even possible? Bonus points for a platform-independent solution, but at a very minimum, I need this to work with Visual Studio 9 under Windows.
|
The appropriate method is to rewrite your classes so that they are testable. They should accept as a parameter the handle, stream or file from which they are supposed to read data - in your test framework, you can then mock in the stream or supply the path to the file containing the test data.
|
143,285 | 143,298 |
How much memory do Enums take?
|
For example if I have an Enum with two cases, does it make take more memory than a boolean? Languages: Java, C++
|
In Java, an enum is a full-blown class:
Java programming language enum types
are much more powerful than their
counterparts in other languages. The
enum declaration defines a class
(called an enum type). The enum class
body can include methods and other
fields.
In order to see the actual size of each enum, let's make an actual enum and examine the contents of the class file it creates.
Let's say we have the following Constants enum class:
public enum Constants {
ONE,
TWO,
THREE;
}
Compiling the above enum and disassembling resulting class file with javap gives the following:
Compiled from "Constants.java"
public final class Constants extends java.lang.Enum{
public static final Constants ONE;
public static final Constants TWO;
public static final Constants THREE;
public static Constants[] values();
public static Constants valueOf(java.lang.String);
static {};
}
The disassembly shows that that each field of an enum is an instance of the Constants enum class. (Further analysis with javap will reveal that each field is initialized by creating a new object by calling the new Constants(String) constructor in the static initialization block.)
Therefore, we can tell that each enum field that we create will be at least as much as the overhead of creating an object in the JVM.
|
143,788 | 143,806 |
when to pass function arguments by reference and when by address?
|
Could anyone explain with some examples when it is better to call functions by reference and when it is better to call by address?
|
Pass your arguments to function using reference whenever possible.
Passing arguments by reference eliminate the chance of them being NULL.
If you want it to be possible to pass NULL value to a function then use pointer.
|
143,808 | 145,386 |
How to improve link performance for a large C++ application in VS2005
|
We have fairly large C++ application which is composed of about 60 projects in Visual Studio 2005. It currently takes 7 minutes to link in Release mode and I would like to try to reduce the time. Are there any tips for improving the link time?
Most of the projects compile to static libraries, this makes testing easier since each one also has a set of associated unit tests. It seems the use of static libraries prevents VS2005 from using incremental linking, so even with incremental linking turned on it does a full link every time.
Would using DLLs for the sub projects make any difference? I don't really want to go through all the headers and add macros to export the symbols (even using a script) but if it would do something to reduce the 7 minute link time I will certainly consider it.
For some reason using nmake from the command line is slightly faster and linking the same application on Linux (with GCC) is much faster.
Visual Studio IDE 7 minutes
Visual C++ using nmake from the command line - 5 minutes
GCC on Linux 34 seconds
|
If you're using the /GL flag to enable Whole Program Optimization (WPO) or the /LTCG flag to enable Link Time Code Generation, turning them off will improve link times significantly, at the expense of some optimizations.
Also, if you're using the /Z7 flag to put debug symbols in the .obj files, your static libraries are probably huge. Using /Zi to create separate .pdb files might help if it prevents the linker from reading all of the debug symbols from disk. I'm not sure if it actually does help because I have not benchmarked it.
|
143,850 | 143,853 |
How does Multiple C++ Threads execute on a class method
|
let's say we have a c++ class like:
class MyClass
{
void processArray( <an array of 255 integers> )
{
int i ;
for (i=0;i<255;i++)
{
// do something with values in the array
}
}
}
and one instance of the class like:
MyClass myInstance ;
and 2 threads which call the processArray method of that instance (depending on how system executes threads, probably in a completely irregular order). There is no mutex lock used in that scope so both threads can enter.
My question is what happens to the i ? Does each thread scope has it's own "i" or would each entering thread modify i in the for loop, causing i to be changing weirdly all the time.
|
i is allocated on the stack. Since each thread has its own separate stack, each thread gets its own copy of i.
|
144,285 | 144,336 |
State of C++ Standard
|
I haven't kept up lately with the C++ world. Exactly where do things stand these days regarding the standard?
Is TR1 adopted?
Is there a TR2?
How do these relate to C++0x? Are the subsumed?
Has a decision been reached on threading yet?
|
You can find an extensive article about the upcoming C++0x on wikipedia and the current state of C++ evolution here. It is also worth giving a look at the current GNU implementation in gcc
|
144,583 | 144,655 |
Windows C++ dialog resizer class
|
I'm looking for a really good dialog resizer class that will stretch and shrink individual items as needed as the screen is resized. Stephan Keil has a good one (DlgResizeHelper) which basically resizes everything by a set ratio, but I'm looking for something smarter.
For example:
Icons should not resize
Single-line text boxes should not be stretched vertically
Buttons should probably stay the same size
Basically I'm looking for something to look at all of the controls, figure out that a static text field is related to a control next/below it and anchor the two together, and resize large controls in a 'smart' way so it looks good.
Are there such frameworks out there? I've been working on one but something ready-made would probably be better.
FOLLOW UP: I'm looking at the suggested solutions. Many of them require you to go in an anchor each control on the dialog. I'm looking for something smart that will figure out what the anchors ought to be, with the ability to manually anchor if the guesses are wrong. Seems like it should be possible -- most humans would agree a static text field next to an edit field should be anchored together. Guess I'm almost looking for a little AI here :)
|
You can use wxWidgets. It completely replaces MFC, is multi-platform, and gives you a layout-based dialog mechanism.
|
144,761 | 144,804 |
How to remove accents and tilde in a C++ std::string
|
I have a problem with a string in C++ which has several words in Spanish. This means that I have a lot of words with accents and tildes. I want to replace them for their not accented counterparts. Example: I want to replace this word: "había" for habia. I tried replace it directly but with replace method of string class but I could not get that to work.
I'm using this code:
for (it= dictionary.begin(); it != dictionary.end(); it++)
{
strMine=(it->first);
found=toReplace.find_first_of(strMine);
while (found!=std::string::npos)
{
strAux=(it->second);
toReplace.erase(found,strMine.length());
toReplace.insert(found,strAux);
found=toReplace.find_first_of(strMine,found+1);
}
}
Where dictionary is a map like this (with more entries):
dictionary.insert ( std::pair<std::string,std::string>("á","a") );
dictionary.insert ( std::pair<std::string,std::string>("é","e") );
dictionary.insert ( std::pair<std::string,std::string>("í","i") );
dictionary.insert ( std::pair<std::string,std::string>("ó","o") );
dictionary.insert ( std::pair<std::string,std::string>("ú","u") );
dictionary.insert ( std::pair<std::string,std::string>("ñ","n") );
and toReplace strings is:
std::string toReplace="á-é-í-ó-ú-ñ-á-é-í-ó-ú-ñ";
I obviously must be missing something. I can't figure it out.
Is there any library I can use?.
Thanks,
|
First, this is a really bad idea: you’re mangling somebody’s language by removing letters. Although the extra dots in words like “naïve” seem superfluous to people who only speak English, there are literally thousands of writing systems in the world in which such distinctions are very important. Writing software to mutilate someone’s speech puts you squarely on the wrong side of the tension between using computers as means to broaden the realm of human expression vs. tools of oppression.
What is the reason you’re trying to do this? Is something further down the line choking on the accents? Many people would love to help you solve that.
That said, libicu can do this for you. Open the transform demo; copy and paste your Spanish text into the “Input” box; enter
NFD; [:M:] remove; NFC
as “Compound 1” and click transform.
(With help from slide 9 of Unicode Transforms in ICU. Slides 29-30 show how to use the API.)
|
145,096 | 145,098 |
Is it true that there is no need to learn C because C++ contains everything?
|
I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features. However, some others have told me that this is not necessarily true. Can anyone shed some light on this?
|
Overview:
It is almost true that C++ is a superset of C, and your professor is correct in that there is no need to learn C separately.
C++ adds the whole object oriented aspect, generic programming aspect, as well as having less strict rules (like variables needing to be declared at the top of each function). C++ does change the definition of some terms in C such as structs, although still in a superset way.
Examples of why it is not a strict superset:
This Wikipedia article has a couple good examples of such a differences:
One commonly encountered difference is
that C allows implicit conversion from
void* to other pointer types, but C++
does not. So, the following is valid C
code:
int *i = malloc(sizeof(int) * 5);
... but to make it work in both C and
C++ one would need to use an explicit
cast:
int *i = (int *) malloc(sizeof(int) * 5)
Another common portability issue is
that C++ defines many new keywords,
such as new and class, that may be
used as identifiers (e.g. variable
names) in a C program.
This wikipedia article has further differences as well:
C++ compilers prohibit goto from crossing an initialization, as in the following C99 code:
void fn(void)
{
goto flack;
int i = 1;
flack:
;
}
What should you learn first?
You should learn C++ first, not because learning C first will hurt you, not because you will have to unlearn anything (you won't), but because there is no benefit in learning C first. You will eventually learn just about everything about C anyway because it is more or less contained in C++.
|
145,110 | 145,122 |
C++ performance vs. Java/C#
|
My understanding is that C/C++ produces native code to run on a particular machine architecture. Conversely, languages like Java and C# run on top of a virtual machine which abstracts away the native architecture. Logically it would seem impossible for Java or C# to match the speed of C++ because of this intermediate step, however I've been told that the latest compilers ("hot spot") can attain this speed or even exceed it.
Perhaps this is more of a compiler question than a language question, but can anyone explain in plain English how it is possible for one of these virtual machine languages to perform better than a native language?
|
Generally, C# and Java can be just as fast or faster because the JIT compiler -- a compiler that compiles your IL the first time it's executed -- can make optimizations that a C++ compiled program cannot because it can query the machine. It can determine if the machine is Intel or AMD; Pentium 4, Core Solo, or Core Duo; or if supports SSE4, etc.
A C++ program has to be compiled beforehand usually with mixed optimizations so that it runs decently well on all machines, but is not optimized as much as it could be for a single configuration (i.e. processor, instruction set, other hardware).
Additionally certain language features allow the compiler in C# and Java to make assumptions about your code that allows it to optimize certain parts away that just aren't safe for the C/C++ compiler to do. When you have access to pointers there's a lot of optimizations that just aren't safe.
Also Java and C# can do heap allocations more efficiently than C++ because the layer of abstraction between the garbage collector and your code allows it to do all of its heap compression at once (a fairly expensive operation).
Now I can't speak for Java on this next point, but I know that C# for example will actually remove methods and method calls when it knows the body of the method is empty. And it will use this kind of logic throughout your code.
So as you can see, there are lots of reasons why certain C# or Java implementations will be faster.
Now this all said, specific optimizations can be made in C++ that will blow away anything that you could do with C#, especially in the graphics realm and anytime you're close to the hardware. Pointers do wonders here.
So depending on what you're writing I would go with one or the other. But if you're writing something that isn't hardware dependent (driver, video game, etc), I wouldn't worry about the performance of C# (again can't speak about Java). It'll do just fine.
One the Java side, @Swati points out a good article:
https://www.ibm.com/developerworks/library/j-jtp09275
|
145,270 | 145,436 |
Calling C/C++ from Python?
|
What would be the quickest way to construct a Python binding to a C or C++ library?
(I am using Windows if this matters.)
|
You should have a look at Boost.Python. Here is the short introduction taken from their website:
The Boost Python Library is a framework for interfacing Python and
C++. It allows you to quickly and seamlessly expose C++ classes
functions and objects to Python, and vice-versa, using no special
tools -- just your C++ compiler. It is designed to wrap C++ interfaces
non-intrusively, so that you should not have to change the C++ code at
all in order to wrap it, making Boost.Python ideal for exposing
3rd-party libraries to Python. The library's use of advanced
metaprogramming techniques simplifies its syntax for users, so that
wrapping code takes on the look of a kind of declarative interface
definition language (IDL).
|
145,563 | 145,576 |
Finding Frequency of numbers in a given group of numbers
|
Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job.
example:
int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2}
the output is 4 because 2 occurs 4 times. That is the maximum number of times 2 occurs.
|
Sort the array and then do a quick pass to count each number. The algorithm has O(N*logN) complexity.
Alternatively, create a hash table, using the number as the key. Store in the hashtable a counter for each element you've keyed. You'll be able to count all elements in one pass; however, the complexity of the algorithm now depends on the complexity of your hasing function.
|
145,570 | 145,604 |
Existing Standard Style and Coding standard documents
|
The following have been proposed for an upcoming C++ project.
C++ Coding Standards, by Sutter and Alexandrescu
JSF Air Vehicle C++ coding standards
The Elements of C++ Style
Effective C++ 3rd Edition, by Scott Meyers
Are there other choices? Or is the list above what be should used on a C++ project?
Some related links
Do you think a software company should impose developers a coding-style?
https://stackoverflow.com/questions/66268/what-is-the-best-cc-coding-style-closed
|
I really think it does not matter which one you adopt, as long as everyone goes along with it. Sometimes that can be hard as it seems that some styles don't agree with peoples tases. I.e. it comes down to arguing about whether prefixing all member variable with m_ is pretty or not.
I have been using and modifying the Geosoft standards for a while, these are for C++. There are some other at the what-is-your-favorite-coding-guidelines-checklist thread
|
145,586 | 145,763 |
What continuous integration tool is best for a C++ project?
|
Cruisecontrol and Hudson are two popular continuous integration systems. Although both systems are able to do the automated continuous builds nicely, it just seems a lot easier to create a batch or bash build script, then use Windows scheduler or cron to schedule builds.
Are there better continuous integration systems available for C++ projects? Or is just using a script and a scheduler the simpler way?
|
We have been using CruiseControl for CI on a C++ project. While it is the only thing we use ant for, the ant build script for CruiseControl just starts our normal build script, so it is very simple and we haven't really needed to update it in a long while. Therefore the fact that CrusieControl is Java based has not really been an issue at all for us.
The main benefits of using something like cruise control are
A nice web page showing build status
Email after each build or after failed builds
Automatically build after a commit to the source control system
A firefox plugin to monitor the build status
Shows the output for any build errors.
Shows what files have changed since the last build (good for seeing which developer broke the buid)
Of course you can write a script yourself which does all of this, but why do all that work? In the long run the extra initial cost of setting up CruiseControl (or something similar) is probably much less than the cost of maintaining and updating a custom CI build script.
If all you need is to launch a daily build and a simple script started by cron is sufficient for your needs then by all means do that. However, one of the advantages of CI is that you get a build status report after every check in. Writing a script to do that takes more work and CruiseControl already does it.
|
145,621 | 145,648 |
What are some recommendations for porting C++ code to the MacOS?
|
For a upcoming project, there are plans to port the existing C++ code that compiles on Windows and Linux to the MacOS(leopard). The software is command line application, but a GUI front end might be planned. The MacOS uses the g++ compiler. By having the same compiler as Linux, it does not seem like there would be any issues, but there always are.
Are there any recommendations or problems to watch out for during the port?
|
Does your app have a GUI, and which one (native / Qt / Gtk+)?
If not, the issues to watch out for (compared to Linux) are mainly in the dynamic linkage area. OS X uses '-dylib' and '-bundle' and in fact has two kinds of dynamic libraries (runtime loadable and the normal ones). Linux has only one kind (-shared), and is looser on this anyways.
If your app has a GUI, you'll need to recode the whole thing in Cocoa, using Objective-C. Meaning you'll be into a new language as well. Some people (like MS) have used Carbon (C++ API), but it's being phased out. I wouldn't recommend that to new projects.
Your best luck is using Qt or Gtk+. A native Gtk+ port has been (re)announced just some days ago (see Imendio).
p.s.
OS X does of course run X11 binaries, too, but pushing that to any of your customers might be a hard road. They're used to Aqua interface, and productive with that. Consider X11 only a very short term solution.
p.p.s. The number of open source addon libs coming with OS X is limited, and their versions might lack behind. Whereas in Linux you can easily require users to have 'libxxx v.y.y' installed, in OS X there are multiple packaging approaches (fink, macports) and for a commercial tool the required libraries are expected to be contained in the application. OS X offers 'application bundles' and 'frameworks' for this (local copies, making the application self-sufficient). Linux does not have such a concept. This will have a great effect on your build system as well; maybe you'll want to try something like SCons for all platforms?
|
145,814 | 145,944 |
Compile-time type based dispatch
|
Following techniques from 'Modern C++ Design', I am implementing a persistence library with various compile-time optimisations. I would like the ability to dispatch a function to a templated member variable if that variable derives from a given class:
template<class T, template <class> class Manager = DefaultManager> class Data
{
private:
T *data_;
public:
void Dispatch()
{
if(SUPERSUBCLASS(Container, T))
{
data_->IKnowThisIsHere();
}
else
{
Manager<T>::SomeGenericFunction(data_);
}
}
}
Where SUPERSUBCLASS is a compile-time macro to determine object inheritance. Of course, this fails in all cases where T does to inherit from Container (or T is an intrinsic type etc etc) because the compiler rightly complains that IKnowThisIsHere() is not a data member, even though this code path will never be followed, as shown here after preprocessing with T = int:
private:
int *data_;
public:
void Dispatch()
{
if(false)
{
data_->IKnowThisIsHere();
Compiler clearly complains at this code, even though it will never get executed. A suggestion of using a dynamic_cast also does not work, as again a type conversion is attempted at compile time that is not possible (for example with T=double, std::string):
void Dispatch()
{
if(false)
{
dynamic_cast<Container*>(data_)->IKnowThisIsHere();
error: cannot dynamic_cast '((const Data<double, DefaultManager>*)this)->Data<double, DefaultManager>::data_' (of type 'double* const') to type 'class Container*' (source is not a pointer to class)
error: cannot dynamic_cast '((const Data<std::string, DefaultManager>*)this)->Da<sttad::string, DefaultManager>::data_' (of type 'struct std::string* const') to type 'class Container*' (source type is not polymorphic)
I really need to emulate (or indeed persuade!) having the compiler emit one set of code if T does inherit from Container, and another if it does not.
Any suggestions?
|
Overloading can be useful to implement compile-time dispatching, as proposed by Alexandrescu in his book "Modern C++ Design".
You can use a class like this to transform at compile time a boolean or integer into a type:
template <bool n>
struct int2type
{ enum { value = n}; };
The following source code shows a possible application:
#include <iostream>
#define MACRO() true // <- macro used to dispatch
template <bool n>
struct int2type
{ enum { value = n }; };
void method(int2type<false>)
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
void method(int2type<true>)
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
int
main(int argc, char *argv[])
{
// MACRO() determines which function to call
//
method( int2type<MACRO()>());
return 0;
}
Of course what really makes the job is the MACRO() or a better implementation as a metafunction
|
145,838 | 145,841 |
Benefits of inline functions in C++?
|
What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980< where memory was scarce and everything had to fit in 100KB of memory) what advantages do they really have today?
|
Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.
Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people.
Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it.
I could see a situation like this making a detectable difference:
inline int aplusb_pow2(int a, int b) {
return (a + b)*(a + b) ;
}
for(int a = 0; a < 900000; ++a)
for(int b = 0; b < 900000; ++b)
aplusb_pow2(a, b);
|
146,275 | 146,309 |
Function pointer to template class member functions
|
I have a templated class defined (in part) as
template <class T> MyClass
{
public:
void DoSomething(){}
};
If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way.
My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place.
Has anyone any suggestions?
|
Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a common base "Interface" class. And then you use a vector of those.
Something like this:
class Base {
public:
virtual ~Base(){}
virtual void DoSomething() = 0;
}
template <class T> class MyClass : public Base {
public:
void DoSomething(){}
};
std::vector<Base *> objects;
objects.push_back(new MyClass<int>);
objects.push_back(new MyClass<char>);
|
146,381 | 146,419 |
Visual Studio support for new C / C++ standards?
|
I keep reading about C99 and C++11 and all these totally sweet things that are getting added to the language standard that might be nice to use someday. However, we currently languish in the land of writing C++ in Visual Studio.
Will any of the new stuff in the standard ever get added to visual studio, or is Microsoft more interested in adding new C# variants to do that?
Edit: In addition to the accepted answer, I found the Visual C++ team blog:
http://blogs.msdn.com/vcblog/
And specifically, this post in it:
https://web.archive.org/web/20190109064523/https://blogs.msdn.microsoft.com/vcblog/2008/02/22/tr1-slide-decks/
Very useful. Thanks!
|
MS has a series of public replies to this, most of them blaming their users. Like this one:
https://devblogs.microsoft.com/cppblog/iso-c-standard-update/
Now, the Visual C++ compiler team receives the occasionally question as to why we haven’t implemented C99. It’s really based on interest from our users. Where we’ve received many requests for certain C99 features, we’ve tried to implement them (or analogues). A couple examples are variadic macros, long long, __pragma, __FUNCTION__, and __restrict. If there are other C99 features that you’d find useful in your work, let us know! We don’t hear much from our C users, so speak up and make yourselves heard
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=345360
Hi: unfortunately the overwhelming feadback we get from the majority of our users is that they would prefer that we focus on C++-0x instead of on C-99. We have "cherry-picked" certain popular C-99 features (variadic macros, long long) but beyond this we are unlikely to do much more in the C-99 space (at least in the short-term).
Jonathan Caves
Visual C++ Compiler Team.
This is a pretty sad state of affairs, but also makes sense if you suspect MS wants to lock users in: it makes it very hard to port modern gcc-based code into MSVC, which at least I find extremely painful.
A workaround exists, though: Note that Intel is much more enlightened on this. the Intel C compiler can handle C99 code and even has the same flags as gcc, making it much easier to port code between platforms. Also, the Intel compiler works in visual studio. So by scrapping MS COMPILER you can still use the MS IDE that you seem to think has some kind of value, and use C99 to your hearts content.
A more sensible approach is honestly to move over to Intel CC or gcc, and use Eclipse for your programming environment. Portability of code across Windows-Linux-Solaris-AIX-etc is usually important in my experience, and that is not at all supported by MS tools, unfortunately.
|
146,387 | 149,814 |
What is the best way to produce random double on POSIX?
|
I'd like to get uniform distribution in range [0.0, 1.0)
If possible, please let the implementation make use of random bytes from /dev/urandom.
It would also be nice if your solution was thread-safe. If you're not sure, please indicate that.
See some solution I thought about after reading other answers.
|
This seems to be pretty good way:
unsigned short int r1, r2, r3;
// let r1, r2 and r3 hold random values
double result = ldexp(r1, -48) + ldexp(r2, -32) + ldexp(r3, -16);
This is based on NetBSD's drand48 implementation.
|
146,452 | 146,454 |
What are POD types in C++?
|
I've come across this term POD-type a few times.
What does it mean?
|
POD stands for Plain Old Data - that is, a class (whether defined with the keyword struct or the keyword class) without constructors, destructors and virtual members functions. Wikipedia's article on POD goes into a bit more detail and defines it as:
A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.
Greater detail can be found in this answer for C++98/03. C++11 changed the rules surrounding POD, relaxing them greatly, thus necessitating a follow-up answer here.
|
146,480 | 146,509 |
How do I get the resolution of the main monitor in Mac OS X in C++?
|
I have a graphical app that needs to test the resolution of the display it is starting up on in Mac OS X to ensure it is not larger than the resolution. This is done before the window itself is initialized.
If there is more than one display, it needs to be the primary display. This is the display that hardware accelerated (OpenGL) apps will start up on in Full Screen, and is typically the display that has the menu bar at the top.
In Windows, I can successfully use GetSystemMetrics(). How can I do this on OS X?
|
Using CoreGraphics:
CGRect mainMonitor = CGDisplayBounds(CGMainDisplayID());
CGFloat monitorHeight = CGRectGetHeight(mainMonitor);
CGFloat monitorWidth = CGRectGetWidth(mainMonitor);
More information at Apple's Quartz Display Services Reference.
|
146,795 | 146,932 |
How to read config file entries from an INI file
|
I can't use the Get*Profile functions because I'm using an older version of the Windows CE platform SDK which doesn't have those. It doesn't have to be too general.
[section]
name = some string
I just need to open the file, check for the existence of "section", and the value associated with "name". Standard C++ is preferred.
|
What I came up with:
std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
bool section=false;
while (!file.eof())
{
WCHAR _line[256];
file.getline(_line, ELEMENTS(_line));
std::wstringstream lineStm(_line);
std::wstring &line=lineStm.str();
if (line.empty()) continue;
switch (line[0])
{
// new header
case L'[':
{
std::wstring header;
for (size_t i=1; i<line.length(); i++)
{
if (line[i]!=L']')
header.push_back(line[i]);
else
break;
}
if (header==L"Section")
section=true;
else
section=false;
}
break;
// comments
case ';':
case ' ':
case '#':
break;
// var=value
default:
{
if (!section) continue;
std::wstring name, dummy, value;
lineStm >> name >> dummy;
ws(lineStm);
WCHAR _value[256];
lineStm.getline(_value, ELEMENTS(_value));
value=_value;
}
}
}
}
|
146,850 | 146,886 |
Is D a credible alternative to Java and C++?
|
Is the D language a credible alternative to Java and C++? What will it take to become a credible alternative? Should I bother learning it? Does it deserve evangelizing?
The main reason I ask is that with the new C++ standard (c++0x) almost here, it's clear to me that the language has gone well past the point of no return with respect to anyone ever understanding it. I know that C/C++ will never die but at some point we need to move on. Even COBOL had its day and Java has in many respects undone C++. So what's next? Does D fill the bill?
|
What determines the success and popularity of a programming language for real-world software development is only partially related to the quality of the language itself. As a pure language, D arguably has many advantages over C++ and Java. At the very least it is a credible alternative as a pure language, all other things being equal.
However, other things matter for software development - almost more than the language itself: portability (how many platforms does it run on), debugger support, IDE support, standard library quality, dynamic library support, bindings for common APIs, documentation, the developer community, momentum, and commercial support, just to name a few. In every one of those regards, D is hopelessly behind Java, C++, and C#. In fact, I'd argue it's even behind so-called "scripting" languages like Python, Perl, PHP, Ruby, and even JavaScript in these regards.
To be blunt, you simply can't build a large-scale, cross-platform application using D. With an immature standard library, no support in any modern IDEs (there are plugins for both Visual Studio and Xamarin Studio/MonoDevelop), limited dynamic/shared library support, and few bindings to other languages, D is simply not an option today.
If you like what you see of D, by all means, learn it - it shouldn't take long if you already know Java and C++. I don't think evangelism would be helpful - at this point if D is going to succeed, what it really needs is more people quietly using it and addressing its major shortcomings like standard library and IDE support.
Finally, as for C++, while most agree the language is too complex, thousands of companies are successfully using C++ as part of a healthy mix of languages by allowing only a smaller, well-defined subset of the language. It's still hard to beat C++ when both raw performance and small memory usage are required.
|
146,873 | 147,031 |
How does the UTF-8 support of TinyXML work?
|
I'm using TinyXML to parse/build XML files. Now, according to the documentation this library supports multibyte character sets through UTF-8. So far so good I think. But, the only API that the library provides (for getting/setting element names, attribute names and values, ... everything where a string is used) is through std::string or const char*. This has me doubting my own understanding of multibyte character set support. How can a string that only supports 8-bit characters contain a 16 bit character (unless it uses a code page, which would negate the 'supports Unicode' claim)? I understand that you could theoretically take a 16-bit code point and split it over 2 chars in a std::string, but that wouldn't transform the std::string to a 'Unicode' string, it would make it invalid for most purposes and would maybe accidentally work when written to a file and read in by another program.
So, can somebody explain to me how a library can offer an '8-bit interface' (std::string or const char*) and still support 'Unicode' strings?
(I probably mixed up some Unicode terminology here; sorry about any confusion coming from that).
|
First, utf-8 is stored in const char * strings, as @quinmars said. And it's not only a superset of 7-bit ASCII (code points <= 127 always encoded in a single byte as themselves), it's furthermore careful that bytes with those values are never used as part of the encoding of the multibyte values for code points >= 128. So if you see a byte == 44, it's a '<' character, etc. All of the metachars in XML are in 7-bit ASCII. So one can just parse the XML, breaking strings where the metachars say to, sticking the fragments (possibly including non-ASCII chars) into a char * or std::string, and the returned fragments remain valid UTF-8 strings even though the parser didn't specifically know UTF-8.
Further (not specific to XML, but rather clever), even more complex things genrally just work (tm). For example, if you sort UTF-8 lexicographically by bytes, you get the same answer as sorting it lexicographically by code points, despite the variation in # of bytes used, because the prefix bytes introducing the longer (and hence higher-valued) code points are numerically greater than those for lesser values).
|
146,924 | 146,934 |
How can I tell if a given path is a directory or a file? (C/C++)
|
I'm using C and sometimes I have to handle paths like
C:\Whatever
C:\Whatever\
C:\Whatever\Somefile
Is there a way to check if a given path is a directory or a given path is a file?
|
Call GetFileAttributes, and check for the FILE_ATTRIBUTE_DIRECTORY attribute.
|
146,943 | 147,169 |
Help improve this INI parsing code
|
This is something simple I came up with for this question. I'm not entirely happy with it and I saw it as a chance to help improve my use of STL and streams based programming.
std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
bool section=false;
while (!file.eof())
{
std::wstring line;
std::getline(file, line);
if (line.empty()) continue;
switch (line[0])
{
// new header
case L'[':
{
std::wstring header;
size_t pos=line.find(L']');
if (pos!=std::wstring::npos)
{
header=line.substr(1, pos);
if (header==L"Section")
section=true;
else
section=false;
}
}
break;
// comments
case ';':
case ' ':
case '#':
break;
// var=value
default:
{
if (!section) continue;
// what if the name = value does not have white space?
// what if the value is enclosed in quotes?
std::wstring name, dummy, value;
lineStm >> name >> dummy;
ws(lineStm);
WCHAR _value[256];
lineStm.getline(_value, ELEMENTS(_value));
value=_value;
}
}
}
}
How would you improve this? Please do not recommend alternative libraries - I just want a simple method for parsing out some config strings from an INI file.
|
// what if the name = value does not have white space?
// what if the value is enclosed in quotes?
I would use boost::regex to match for every different type of element, something like:
boost::smatch matches;
boost::regex name_value("(\S+)\s*=\s*(\S+)");
if(boost::regex_match(line, matches, name_value))
{
name = matches[1];
value = matches[2];
}
the regular expressions might need some tweaking.
I would also replace de stream.getline with std::getline, getting rid of the static char array.
|
147,130 | 147,137 |
Why doesn't C++ have a garbage collector?
|
I'm not asking this question because of the merits of garbage collection first of all. My main reason for asking this is that I do know that Bjarne Stroustrup has said that C++ will have a garbage collector at some point in time.
With that said, why hasn't it been added? There are already some garbage collectors for C++. Is this just one of those "easier said than done" type things? Or are there other reasons it hasn't been added (and won't be added in C++11)?
Cross links:
Garbage collectors for C++
Just to clarify, I understand the reasons why C++ didn't have a garbage collector when it was first created. I'm wondering why the collector can't be added in.
|
Implicit garbage collection could have been added in, but it just didn't make the cut. Probably due to not just implementation complications, but also due to people not being able to come to a general consensus fast enough.
A quote from Bjarne Stroustrup himself:
I had hoped that a garbage collector
which could be optionally enabled
would be part of C++0x, but there were
enough technical problems that I have
to make do with just a detailed
specification of how such a collector
integrates with the rest of the
language, if provided. As is the case
with essentially all C++0x features,
an experimental implementation exists.
There is a good discussion of the topic here.
General overview:
C++ is very powerful and allows you to do almost anything. For this reason it doesn't automatically push many things onto you that might impact performance. Garbage collection can be easily implemented with smart pointers (objects that wrap pointers with a reference count, which auto delete themselves when the reference count reaches 0).
C++ was built with competitors in mind that did not have garbage collection. Efficiency was the main concern that C++ had to fend off criticism from in comparison to C and others.
There are 2 types of garbage collection...
Explicit garbage collection:
C++0x has garbage collection via pointers created with shared_ptr
If you want it you can use it, if you don't want it you aren't forced into using it.
For versions before C++0x, boost:shared_ptr exists and serves the same purpose.
Implicit garbage collection:
It does not have transparent garbage collection though. It will be a focus point for future C++ specs though.
Why Tr1 doesn't have implicit garbage collection?
There are a lot of things that tr1 of C++0x should have had, Bjarne Stroustrup in previous interviews stated that tr1 didn't have as much as he would have liked.
|
147,298 | 147,465 |
Multithreaded Memory Allocators for C/C++
|
I currently have heavily multi-threaded server application, and I'm shopping around for a good multi-threaded memory allocator.
So far I'm torn between:
Sun's umem
Google's tcmalloc
Intel's threading building blocks allocator
Emery Berger's hoard
From what I've found hoard might be the fastest, but I hadn't heard of it before today, so I'm skeptical if its really as good as it seems. Anyone have personal experience trying out these allocators?
|
I've used tcmalloc and read about Hoard. Both have similar implementations and both achieve roughly linear performance scaling with respect to the number of threads/CPUs (according to the graphs on their respective sites).
So: if performance is really that incredibly crucial, then do performance/load testing. Otherwise, just roll a dice and pick one of the listed (weighted by ease of use on your target platform).
And from trshiv's link, it looks like Hoard, tcmalloc, and ptmalloc are all roughly comparable for speed. Overall, tt looks like ptmalloc is optimized for taking as little room as possible, Hoard is optimized for a trade-off of speed + memory usage, and tcmalloc is optimized for pure speed.
|
147,323 | 149,352 |
CScrollView and window size
|
(MFC Question) What's the best way to determine the current displayed client area in a CScrollView? I only need the size of the visible portion, so GetClientRect() won't work here.
|
You do need to use GetClientRect(), but I think you're asking the wrong question. It is not so that in a scrolled view there is a very big client window that is physically scrolled. Instead, when you scroll, the DC's viewportext and mapping mode are adjusted, which make it seem like your view is bigger than it actually is. So, if you want to draw a line from the top left corner of the bottom right corner of the current viewport, you do need GetViewPortOrg() and GetViewportExt(). If these return the wrong values, something is wrong in your use of CScrollView. Did you call SetScrollSizes()?
|
147,372 | 147,374 |
How does this C++ function use memoization?
|
#include <vector>
std::vector<long int> as;
long int a(size_t n){
if(n==1) return 1;
if(n==2) return -2;
if(as.size()<n+1)
as.resize(n+1);
if(as[n]<=0)
{
as[n]=-4*a(n-1)-4*a(n-2);
}
return mod(as[n], 65535);
}
The above code sample using memoization to calculate a recursive formula based on some input n. I know that this uses memoization, because I have written a purely recursive function that uses the same formula, but this one much, much faster for much larger values of n. I've never used vectors before, but I've done some research and I understand the concept of them. I understand that memoization is supposed to store each calculated value, so that instead of performing the same calculations over again, it can simply retrieve ones that have already been calculated.
My question is: how is this memoization, and how does it work? I can't seem to see in the code at which point it checks to see if a value for n already exists. Also, I don't understand the purpose of the if(as[n]<=0). This formula can yield positive and negative values, so I'm not sure what this check is looking for.
Thank you, I think I'm close to understanding how this works, it's actually a bit more simple than I was thinking it was.
I do not think the values in the sequence can ever be 0, so this should work for me, as I think n has to start at 1.
However, if zero was a viable number in my sequence, what is another way I could solve it? For example, what if five could never appear? Would I just need to fill my vector with fives?
Edit: Wow, I got a lot of other responses while checking code and typing this one. Thanks for the help everyone, I think I understand it now.
|
if (as[n] <= 0) is the check. If valid values can be negative like you say, then you need a different sentinel to check against. Can valid values ever be zero? If not, then just make the test if (as[n] == 0). This makes your code easier to write, because by default vectors of ints are filled with zeroes.
|
147,378 | 225,281 |
Options for refactoring bits of code away from native C++?
|
So, one commonly heard comment when talking about performance is that you write your code with whatever language gets the job done fastest. If performance in specific areas is a problem, then rewrite those bits in C/C++.
But, what if you're starting with a native C++ app? What options do you have if you want to write the easy bits, or refactor the old bits, in a language like Python, Ruby, C#, or whatever? Keep in mind that transferring data between the native and other sides is a must. Being able to simply call a function written in an "easier" language, while passing C++ classes as data, would be beautiful.
We've got a crusty Win32 app that would benefit greatly if we could crank out new code, or refactor old code, in C# or something. Very little of it requires the complexity of C++, and dealing with the little fiddly bits is dragging down the programming process.
|
As Aaron Fischer suggests, try recompiling your C++ application with the /clr option turned on and then start leveraging the .Net platform.
CLI/C++ is pretty easy to pick up if you know C# and C++ already and it provides the bridge between the .Net world and native C++.
If your current C++ code can't compile cleanly with /clr turned on then I'd suggest trying to build your application as a static lib (without /clr enabled) and then have your main() be in a CLI/C++ project that calls your legacy app entry point. That way you can at least start leveraging .Net for new functionality.
For examples of "legacy" C/C++ apps that have been "ported" to .Net CLI/C++ check out the .Net ports of Quake 2 and Quake 3: Arena.
|
147,391 | 147,406 |
Using boost::random as the RNG for std::random_shuffle
|
I have a program that uses the mt19937 random number generator from boost::random. I need to do a random_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers.
I tried something like this:
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
struct bar {
boost::mt19937 &_state;
unsigned operator()(unsigned i) {
boost::uniform_int<> rng(0, i - 1);
return rng(_state);
}
bar(boost::mt19937 &state) : _state(state) {}
} rand(state);
std::random_shuffle(vec.begin(), vec.end(), rand);
}
But i get a template error calling random_shuffle with rand. However this works:
unsigned bar(unsigned i)
{
boost::mt19937 no_state;
boost::uniform_int<> rng(0, i - 1);
return rng(no_state);
}
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
std::random_shuffle(vec.begin(), vec.end(), bar);
}
Probably because it is an actual function call. But obviously this doesn't keep the state from the original mersenne twister. What gives? Is there any way to do what I'm trying to do without global variables?
|
In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the function, it should work fine (disclaimer: not tested, there could be other sinister bugs).
This requirement has been relaxed in C++0x, but I don't know whether the change has been implemented in GCC's C++0x mode yet, and I would be highly surprised to find it present in any other compiler.
|
147,572 | 147,589 |
Will the below code cause memory leak in c++
|
class someclass {};
class base
{
int a;
int *pint;
someclass objsomeclass;
someclass* psomeclass;
public:
base()
{
objsomeclass = someclass();
psomeclass = new someclass();
pint = new int();
throw "constructor failed";
a = 43;
}
}
int main()
{
base temp();
}
In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?
int main()
{
base *temp = new base();
}
How about in the above code? How can the memory leaks be avoided after the constructor throws?
|
Yes it will leak memory. When the constructor throws, no destructor will be called (in this case you don't show a destructor that frees the dynamically allocated objects, but lets assume you had one).
This is a major reason to use smart pointers - since the smart poitners are full fledged objects, they will get destructors called during the exception's stack unwind and have the opportunity to free the memory.
If you use something like Boost's scoped_ptr<> template, your class could look more like:
class base{
int a;
scoped_ptr<int> pint;
someclass objsomeclass;
scoped_ptr<someclass> psomeclass;
base() :
pint( new int),
objsomeclass( someclass()),
psomeclass( new someclass())
{
throw "constructor failed";
a = 43;
}
}
And you would have no memory leaks (and the default dtor would also clean up the dynamic memory allocations).
To sum up (and hopefully this also answers the question about the
base* temp = new base();
statement):
When an exception is thrown inside a constructor there are several things that you should take note of in terms of properly handling resource allocations that may have occured in the aborted construction of the object:
the destructor for the object being constructed will not be called.
destructors for member objects contained in that object's class will be called
the memory for the object that was being constructed will be freed.
This means that if your object owns resources, you have 2 methods available to clean up those resources that might have already been acquired when the constructor throws:
catch the exception, release the resources, then rethrow. This can be difficult to get correct and can become a maintenance problem.
use objects to manage the resource lifetimes (RAII) and use those objects as the members. When the constructor for your object throws an exception, the member objects will have desctructors called and will have an opportunity to free the resource whose lifetimes they are responsible for.
|
147,902 | 147,915 |
Linux configuration file libraries
|
Are there any good configuration file reading libraries for C\C++ that can be used for applications written on the linux platform. I would like to have a simple configuration file for my application. At best i would like to steer clear of XML files that might potentially confuse users.
|
You could try glib's key-value-file-parser
|
147,920 | 147,954 |
Can you create collapsible #Region like scopes in C++ within VS 2008?
|
I miss it so much (used it a lot in C#). can you do it in C++?
|
Yes, you can. See here.
#pragma region Region_Name
//Your content.
#pragma endregion Region_Name
|
148,003 | 148,030 |
Algorithm for finding the maximum difference in an array of numbers
|
I have an array of a few million numbers.
double* const data = new double (3600000);
I need to iterate through the array and find the range (the largest value in the array minus the smallest value). However, there is a catch. I only want to find the range where the smallest and largest values are within 1,000 samples of each other.
So I need to find the maximum of: range(data + 0, data + 1000), range(data + 1, data + 1001), range(data + 2, data + 1002), ...., range(data + 3599000, data + 3600000).
I hope that makes sense. Basically I could do it like above, but I'm looking for a more efficient algorithm if one exists. I think the above algorithm is O(n), but I feel that it's possible to optimize. An idea I'm playing with is to keep track of the most recent maximum and minimum and how far back they are, then only backtrack when necessary.
I'll be coding this in C++, but a nice algorithm in pseudo code would be just fine. Also, if this number I'm trying to find has a name, I'd love to know what it is.
Thanks.
|
The algorithm you describe is really O(N), but i think the constant is too high. Another solution which looks reasonable is to use O(N*log(N)) algorithm the following way:
* create sorted container (std::multiset) of first 1000 numbers
* in loop (j=1, j<(3600000-1000); ++j)
- calculate range
- remove from the set number which is now irrelevant (i.e. in index *j - 1* of the array)
- add to set new relevant number (i.e. in index *j+1000-1* of the array)
I believe it should be faster, because the constant is much lower.
|
148,024 | 149,641 |
Why is my parameter passed by reference not modified within the function?
|
I have got a C function in a static library, let's call it A, with the following interface :
int A(unsigned int a, unsigned long long b, unsigned int *y, unsigned char *z);
This function will change the value of y an z (this is for sure). I use it from within a dynamic C++ library, using extern "C".
Now, here is what stune me :
y is properly set, z is not changed. What I exactly mean is that if both are initialized with a (pointed) value of 666, the value pointed by y will have changed after the call but not the value pointed by z (still 666).
when called from a C binary, this function works seamlessly (value
pointed by z is modified).
if I create a dummy C library with a function having the same prototype, and I use it from within my dynamic C++ library, it works very well. If I re-use the same variables to call A(..), I get the same result as before, z is not changed.
I think that the above points show that it is not a stupid mistake with the declaration of my variables.
I am clearly stuck, and I can't change the C library. Do you have any clue on what can be the problem ?
I was thinking about a problem on the C/C++ interface, per instance the way a char* is interpreted.
Edit : I finally found out what was the problem. See below my answer.
|
First of all, I am very grateful to everyone for your help.
Thanks to the numerous ideas and clues you gave me, I have been able to finally sort out this problem. Your advices helped me to question what I took for granted.
Short answer to my problem : The problem was that my C++ library used an old version of the C library. This old version missed the 4th argument. As a consequence, the 4th argument was obviously never changed.
I am a bit ashamed now that I realised this was the problem. However, I was misslead by the fact that my code was compiling fine. This was due to the fact that the C++ library compiled against the correct version of the C lib, but at runtime it used the old version statically linked with another library that I was using.
C++ Lib (M) ---> dyn C++ lib (N) ---> C lib (P) v.1.0
|
------> C lib (P) v.1.1
(N) is a dynamic library which is statically linked with (P) version 1.0.
The compiler accepted the call from (M) to the function with 4 arguments because I linked against (P) version 1.1, but at runtime it used the old version of (P).
Feel free to edit this answer or the question or to ask me to do so.
|
148,071 | 174,086 |
Problem using large binary segment in OOXML
|
System Description
A plotting component that uses OOXML to generate a document.
Plotting component consists of several parts.
All parts are written in C++ as exe + dll's, with the exception of the interface to the OOXML document.
The latter component is a COM component that was created in C#/.NET. The main reason for this is that the .NET framework contains System.IO.Packaging. This is a very handy built-in facility for dealing with OOXML documents.
We create a document out of a template OOXML document where certain bits and pieces are replaced by their actual content.
One of these bits is an OLE Server component. Basically this is a binary segment within the OOXML file. For writing this binary segment, the Packaging component apparently uses isolated storage.
Problem
Writing a segment > 8MB results in an exception being thrown "Unable to determine the identity of the domain".
On the C++ side this exception contains the error ISS_E_ISOSTORE ( 0x80131450 ).
We have analyzed this and as far as we can tell, this is a security feature that prevents semi-untrusted third-party component from completely ruining your HD by writing immense files.
We have then tried a lot of things in the .NET/COM component ( creating custom AppDomains, setting Attributes for maximum permissivity, Creating our own Streams and passing those to the Packaging component ) but every time it resulted in the same exception being thrown.
What could we do to make this work?
Could it be that when the .NET component is instantiated as a COM component, its AppDomain is alway untrusted?
|
You might try to unzip the package yourself (instead of using the .NET package API), write directly to the file which represents the binary segment and zip it again.
|
148,225 | 148,230 |
How to extract four unsigned short ints from one long long int?
|
Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it.
Particular order doesn't matter much here.
I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask.
|
#include <stdint.h>
#include <stdio.h>
union ui64 {
uint64_t one;
uint16_t four[4];
};
int
main()
{
union ui64 number = {0x123456789abcdef0};
printf("%x %x %x %x\n", number.four[0], number.four[1],
number.four[2], number.four[3]);
return 0;
}
|
148,281 | 150,158 |
Eclipse C++ pretty printing?
|
The output we get when printing C++ sources from Eclipse is rather ugly.
Is there are way/a plugin to pretty print C++ source code like e.g. with a2ps (which is probably using yet another filter for C source code)?
|
I also use enscript for this. Here's an alias I often use:
alias cpp2ps='enscript --color --pretty-print=cpp --language=PostScript'
and I use it like this:
cpp2ps -P main.ps main.cpp
There are several other great options in enscript including rotating, 2-column output, line numbers, headers/footers, etc. Check out the enscript man page.
Also, on Macs, XCode prints C++ code very nicely.
|
148,298 | 148,302 |
How to check for equals? (0 == i) or (i == 0)
|
Okay, we know that the following two lines are equivalent -
(0 == i)
(i == 0)
Also, the first method was encouraged in the past because that would have allowed the compiler to give an error message if you accidentally used '=' instead of '=='.
My question is - in today's generation of pretty slick IDE's and intelligent compilers, do you still recommend the first method?
In particular, this question popped into my mind when I saw the following code -
if(DialogResult.OK == MessageBox.Show("Message")) ...
In my opinion, I would never recommend the above. Any second opinions?
|
I prefer the second one, (i == 0), because it feel much more natural when reading it. You ask people, "Are you 21 or older?", not, "Is 21 less than or equal to your age?"
|
148,373 | 148,408 |
Restrict Template Function
|
I wrote a sample program at http://codepad.org/ko8vVCDF that uses a template function.
How do I retrict the template function to only use numbers? (int, double etc.)
#include <vector>
#include <iostream>
using namespace std;
template <typename T>
T sum(vector<T>& a)
{
T result = 0;
int size = a.size();
for(int i = 0; i < size; i++)
{
result += a[i];
}
return result;
}
int main()
{
vector<int> int_values;
int_values.push_back(2);
int_values.push_back(3);
cout << "Integer: " << sum(int_values) << endl;
vector<double> double_values;
double_values.push_back(1.5);
double_values.push_back(2.1);
cout << "Double: " << sum(double_values);
return 0;
}
|
The only way to restrict a template is to make it so that it uses something from the types that you want, that other types don't have.
So, you construct with an int, use + and +=, call a copy constructor, etc.
Any type that has all of these will work with your function -- so, if I create a new type that has these features, your function will work on it -- which is great, isn't it?
If you want to restrict it more, use more functions that only are defined for the type you want.
Another way to implement this is by creating a traits template -- something like this
template<class T>
SumTraits
{
public:
const static bool canUseSum = false;
}
And then specialize it for the classes you want to be ok:
template<>
class SumTraits<int>
{
public:
const static bool canUseSum = true;
};
Then in your code, you can write
if (!SumTraits<T>::canUseSum) {
// throw something here
}
edit: as mentioned in the comments, you can use BOOST_STATIC_ASSERT to make it a compile-time check instead of a run-time one
|
148,407 | 148,423 |
Why does the code below return true only for a = 1?
|
Why does the code below return true only for a = 1?
main(){
int a = 10;
if (true == a)
cout<<"Why am I not getting executed";
}
|
When a Bool true is converted to an int, it's always converted to 1. Your code is thus, equivalent to:
main(){
int a = 10;
if (1 == a)
cout<<"y i am not getting executed";
}
This is part of the C++ standard, so it's something you would expect to happen with every C++ standards compliant compiler.
|
148,511 | 148,551 |
Limiting range of value types in C++
|
Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such:
LimitedValue< float, 0, 360 > someAngle( 45.0 );
someTrigFunction( someAngle );
so that 'someTrigFunction' knows that it is guaranteed to be supplied a valid input (The constructor would throw an exception if the parameter is invalid).
Copy-construction and assignment are limited to exactly equal types, though. I'd like to be able to do:
LimitedValue< float, 0, 90 > smallAngle( 45.0 );
LimitedValue< float, 0, 360 > anyAngle( smallAngle );
and have that operation checked at compile-time, so this next example gives an error:
LimitedValue< float, -90, 0 > negativeAngle( -45.0 );
LimitedValue< float, 0, 360 > postiveAngle( negativeAngle ); // ERROR!
Is this possible? Is there some practical way of doing this, or any examples out there which approach this?
|
You can do this using templates -- try something like this:
template< typename T, int min, int max >class LimitedValue {
template< int min2, int max2 >LimitedValue( const LimitedValue< T, min2, max2 > &other )
{
static_assert( min <= min2, "Parameter minimum must be >= this minimum" );
static_assert( max >= max2, "Parameter maximum must be <= this maximum" );
// logic
}
// rest of code
};
|
148,540 | 149,207 |
Creating my own Iterators
|
I'm trying to learn C++ so forgive me if this question demonstrates a lack of basic knowledge, you see, the fact is, I have a lack of basic knowledge.
I want some help working out how to create an iterator for a class I have created.
I have a class 'Shape' which has a container of Points.
I have a class 'Piece' which references a Shape and defines a position for the Shape.
Piece does not have a Shape it just references a Shape.
I want it to seem like Piece is a container of Points which are the same as those of the Shape it references but with the offset of the Piece's position added.
I want to be able to iterate through the Piece's Points just as if Piece was a container itself. I've done a little reading around and haven't found anything which has helped me. I would be very grateful for any pointers.
|
You should use Boost.Iterators. It contains a number of templates and concepts to implement new iterators and adapters for existing iterators. I have written an article about this very topic; it's in the December 2008 ACCU magazine. It discusses an (IMO) elegant solution for exactly your problem: exposing member collections from an object, using Boost.Iterators.
If you want to use the stl only, the Josuttis book has a chapter on implementing your own STL iterators.
|
148,807 | 152,642 |
How to find unused attributes/methods in Visual C++ 2008
|
Is there a way to identify unused attributes/methods in Visual C++ 2008 Professional? If it's not possible by default, recommendations of 3rd-party tools are also much appreciated.
Thanks,
Florian
Edit: nDepend only works for .NET assemblies. I'm looking for something that can be used with native C++ applications.
|
Try PC-Lint. It's pretty good at finding redundant code.
I haven't tried version 9 yet. Version 8 does take some time to configure.
Try the online interactive demo.
|
148,881 | 1,617,173 |
How do I append a large amount of rich content (images, formatting) quickly to a control without using tons of CPU?
|
I am using wxWidgets and Visual C++ to create functionality similar to using Unix "tail -f" with rich formatting (colors, fonts, images) in a GUI. I am targeting both wxMSW and wxMAC.
The obvious answer is to use wxTextCtrl with wxTE_RICH, using calls to wxTextCtrl::SetDefaultStyle() and wxTextCtrl::WriteText().
However, on my 3ghz workstation, compiled in release mode, I am unable to keep tailing a log that grows on average of 1 ms per line, eventually falling behind. For each line, I am incurring:
Two calls to SetDefaultStyle()
Two calls two WriteText()
A call to Freeze() and Thaw() the widget
When running this, my CPU goes to 100% on one core using wxMSW after filling up roughly 20,000 lines. The program is visibly slower once it reaches a certain threshold, falling further behind.
I am open to using other controls (wxListCtrl, wxRichTextCtrl, etc).
|
Derive from wxVListBox. From the docs:
wxVListBox is a listbox-like control with the following two main differences from a regular listbox: it can have an arbitrarily huge number of items because it doesn't store them itself but uses OnDrawItem() callback to draw them (so it is a Virtual listbox) and its items can have variable height as determined by OnMeasureItem() (so it is also a listbox with the lines of Variable height).
|
149,268 | 149,305 |
Benefits and portability of Boost Library
|
Since I have started using this site, I keep hearing about the Boost library. I am wondering what are some of the major benefits of the Boost library (hence why should I use it) and how portable is the Boost library?
|
Boost is organized by several members of the standard committee.
So it is a breeding ground for libraries that will be in the next standard.
It is an extension to the STL (it fills in the bits left out)
It is well documented.
It is well peer-reviewed.
It has high activity so bugs are found and fixed quickly.
It is platform neutral and works everywhere.
It is free to use.
With tr1 coming up soon it is nice to know that boost already has a lot of the ground covered. A lot of the libraries in tr1 are basically adapted directly from boost originals and thus have been tried and tested. The difference is that they have been moved into the std::tr1 namespace (rather than boost).
All that you need to do is add the following to your compilers default include search path:
<boost-install-path>/boost/tr1/tr1
Then when you include the standard headers boost will automatically import all the required stuff into the namespace std::tr1
For Example:
To use std::tr1::share_ptr you just need to include <memory>. This will give you all the smart pointers with one file.
|
149,336 | 149,377 |
Practical Uses for the "Curiously Recurring Template Pattern"
|
What are some practical uses for the "Curiously Recurring Template Pattern"? The "counted class" example commonly shown just isn't a convincing example to me.
|
Simulated dynamic binding.
Avoiding the cost of virtual function calls while retaining some of the hierarchical benefits is an enormous win for the subsystems where it can be done in the project I am currently working on.
|
149,488 | 151,612 |
Disk-backed STL container classes?
|
I enjoy developing algorithms using the STL, however, I have this recurring problem where my data sets are too large for the heap.
I have been searching for drop-in replacements for STL containers and algorithms which are disk-backed, i.e. the data structures on stored on disk rather than the heap.
A friend recently pointed me towards stxxl. Before I get too involved with it... Are any other disk-backed STL replacements available that I should be considering?
NOTE: I'm not interested in persistence or embedded databases. Please don't mention boost::serialization, POST++, Relational Template Library, Berkeley DB, sqlite, etc. I am aware of these projects and use them when they are appropriate for my purposes.
UPDATE: Several people have mentioned memory-mapping files and using a custom allocator, good suggestions BTW, but I would point them to the discussion here where David Abraham suggests that custom iterators would be needed for disk-backed containers. Meaning the custom allocator approach isn't likely to work.
|
I have implemented some thing very similar. Implementing the iterators is the most challenging. I used boost::iterator_facade to implement the iterators. Using boost::iterator_facade you can easy adapt any cached on disk data structures to have a STL container interface.
|
149,500 | 149,514 |
What does the comma operator do?
|
What does the following code do in C/C++?
if (blah(), 5) {
//do something
}
|
Comma operator is applied and the value 5 is used to determine the conditional's true/false.
It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression.
Note that the , operator could be overloaded for the return type of the blah() function (which wasn't specified), making the result non-obvious.
|
149,710 | 149,717 |
Interlocked equivalent on Linux
|
In a C++ Linux app, what is the simplest way to get the functionality that the Interlocked functions on Win32 provide? Specifically, a lightweight way to atomically increment or add 32 or 64 bit integers?
|
Upon further review, this looks promising. Yay stack overflow.
|
149,995 | 150,009 |
Getting different header size by changing window size
|
I have a C++ program representing a TCP header as a struct:
#include "stdafx.h"
/* TCP HEADER
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Port | Destination Port |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Acknowledgment Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Data | |U|A|P|R|S|F| |
| Offset| Reserved |R|C|S|S|Y|I| Window |
| | |G|K|H|T|N|N| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | Urgent Pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options | Padding |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| data |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
typedef struct { // RFC793
WORD wSourcePort;
WORD wDestPort;
DWORD dwSequence;
DWORD dwAcknowledgment;
unsigned int byReserved1:4;
unsigned int byDataOffset:4;
unsigned int fFIN:1;
unsigned int fSYN:1;
unsigned int fRST:1;
unsigned int fPSH:1;
unsigned int fACK:1;
unsigned int fURG:1;
unsigned int byReserved2:2;
unsigned short wWindow;
WORD wChecksum;
WORD wUrgentPointer;
} TCP_HEADER, *PTCP_HEADER;
int _tmain(int argc, _TCHAR* argv[])
{
printf("TCP header length: %d\n", sizeof(TCP_HEADER));
return 0;
}
If I run this program I get the size of this header as 24 bytes, which is not the size I was expecting. If I change the type of the field "wWindow" to "unsigned int wWindow:16", which has the same number of bits as an unsigned short, the program tells me the size of the struct is now 20 bytes, the correct size. Why is this?
I am using Microsoft Visual Studio 2005 with SP1 on a 32-bit x86 machine.
|
See this question: Why isn't sizeof for a struct equal to the sum of sizeof of each member? .
I believe that compiler takes a hint to disable padding when you use the "unsigned int wWindow:16" syntax.
Also, note that a short is not guaranteed to be 16 bits. The guarantee is that: 16 bits <= size of a short <= size of an int.
|
150,186 | 150,249 |
How to order headers in .NET C++ projects
|
I'm trying to build a new .NET C++ project from scratch. I am planning to mix managed and unmanaged code in this project.
this forum thread
IDataObject : ambiguous symbol error answers a problem I've seen multiple times.
Post #4 states
"Move all 'using namespace XXXX' from .h to .cpp"
this looks like a good idea but now in my header files I need to reference parameters from the .NET Framework like
void loadConfigurations(String^ pPathname);
How am I supposed to move using statements in the .cpp file and use the according namespaces in the .h file?
|
It's a good idea to always use fully qualified names in header files. Because the using statement affects all following code regardless of #include, putting a using statement in a header file affects everybody that might include that header.
So you would change your function declaration in your header file to:
void loadConfigurations(SomeNamespace::String^ pPathname);
where SomeNamespace is the name of the namespace you were using previously.
|
150,294 | 150,300 |
How to programmatically get the CPU cache page size in C++?
|
I'd like my program to read the cache line size of the CPU it's running on in C++.
I know that this can't be done portably, so I will need a solution for Linux and another for Windows (Solutions for other systems could be usefull to others, so post them if you know them).
For Linux I could read the content of /proc/cpuinfo and parse the line begining with cache_alignment. Maybe there is a better way involving a call to an API.
For Windows I simply have no idea.
|
On Win32, GetLogicalProcessorInformation will give you back a SYSTEM_LOGICAL_PROCESSOR_INFORMATION which contains a CACHE_DESCRIPTOR, which has the information you need.
|
150,355 | 150,971 |
Programmatically find the number of cores on a machine
|
Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)?
|
C++11
#include <thread>
//may return 0 when not able to detect
const auto processor_count = std::thread::hardware_concurrency();
Reference: std::thread::hardware_concurrency
In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate #ifdef lines):
Win32
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
int numCPU = sysinfo.dwNumberOfProcessors;
Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards)
int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
FreeBSD, MacOS X, NetBSD, OpenBSD, etc.
int mib[4];
int numCPU;
std::size_t len = sizeof(numCPU);
/* set the mib for hw.ncpu */
mib[0] = CTL_HW;
mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;
/* get the number of CPUs from the system */
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU < 1)
{
mib[1] = HW_NCPU;
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU < 1)
numCPU = 1;
}
HPUX
int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);
IRIX
int numCPU = sysconf(_SC_NPROC_ONLN);
Objective-C (Mac OS X >=10.5 or iOS)
NSUInteger a = [[NSProcessInfo processInfo] processorCount];
NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];
|
150,726 | 150,768 |
C++ having cin read a return character
|
I was wondering how to use cin so that if the user does not enter in any value and just pushes ENTER that cin will recognize this as valid input.
|
You will probably want to try std::getline:
#include <iostream>
#include <string>
std::string line;
std::getline( std::cin, line );
if( line.empty() ) ...
|
150,803 | 150,874 |
Side effects of calling RegisterWindow multiple times with same window class?
|
I'm working on a little test application at the minute and I have multiple window objects floating around and they each call RegisterWindowEx with the same WNDCLASSEX structure (mainly because they are all an instance of the same class).
The first one registers ok, then multiple ones fail, saying class already registered - as expected.
My question is - is this bad? I was thinking of using a hash table to store the ATOM results in, to look up before calling RegisterWindow, but it seems Windows does this already?
|
You can test if the window class was previously registered calling GetClassInfoEx.
If the function finds a matching class
and successfully copies the data, the
return value is nonzero.
http://msdn.microsoft.com/en-us/library/ms633579(VS.85).aspx
This way you can conditionally register the window class based on the return of GetClassInfoEx.
|
151,046 | 151,078 |
How can I detect the last iteration in a loop over std::map?
|
I'm trying to figure out the best way to determine whether I'm in the last iteration of a loop over a map in order to do something like the following:
for (iter = someMap.begin(); iter != someMap.end(); ++iter) {
bool last_iteration;
// do something for all iterations
if (!last_iteration) {
// do something for all but the last iteration
}
}
There seem to be several ways of doing this: random access iterators, the distance function, etc. What's the canonical method?
Edit: no random access iterators for maps!
|
Canonical? I can't claim that, but I'd suggest
final_iter = someMap.end();
--final_iter;
if (iter != final_iter) ...
Edited to correct as suggested by KTC. (Thanks! Sometimes you go too quick and mess up on the simplest things...)
|
151,124 | 151,126 |
Which is correct? catch (_com_error e) or catch (_com_error& e)?
|
Which one should I use?
catch (_com_error e)
or
catch (_com_error& e)
|
The second. Here is my attempt at quoting Sutter
"Throw by value, catch by reference"
Learn to catch properly: Throw exceptions by value (not pointer) and
catch them by reference (usually to const). This is the combination
that meshes best with exception semantics. When rethrowing the same
exception, prefer just throw; to throw e;.
Here's the full Item 73. Throw by value, catch by reference.
The reason to avoid catching exceptions by value is that it implicitly makes a copy of the exception. If the exception is of a subclass, then information about it will be lost.
try { throw MyException ("error") }
catch (Exception e) {
/* Implies: Exception e (MyException ("error")) */
/* e is an instance of Exception, but not MyException */
}
Catching by reference avoids this issue by not copying the exception.
try { throw MyException ("error") }
catch (Exception& e) {
/* Implies: Exception &e = MyException ("error"); */
/* e is an instance of MyException */
}
|
151,299 | 151,445 |
Embedding SVN Revision number at compile time in a Windows app
|
I'd like my .exe to have access to a resource string with my svn version. I can type this in by hand, but I'd prefer an automated way to embed this at compile time. Is there any such capability in Visual Studio 2008?
|
I wanted a similar availability and found $Rev$ to be insufficient because it was only updated for a file if that file's revision was changed (which meant it would have to be edited and committed very time: not something I wanted to do.) Instead, I wanted something that was based on the repository's revision number.
For the project I'm working on now, I wrote a Perl script that runs svnversion -n from the top-most directory of my working copy and outputs the most recent revision information to a .h file (I actually compare it to a saved reversion in a non-versioned file in my working copy so that I'm not overwriting current revision information at every compile but whether you chose to do so is up to you.) This .h file (or a number of files if necessary, depending on your approach) is referenced both in my application code and in the resource files to get the information where I'd like it.
This script is run as a pre-build step so that everything is up-to-date before the build kicks off and the appropriate files are automatically rebuilt by your build tool.
|
151,418 | 151,758 |
Calling a C++ function pointer on a specific object instance
|
I have a function pointer defined by:
typedef void (*EventFunction)(int nEvent);
Is there a way to handle that function with a specific instance of a C++ object?
class A
{
private:
EventFunction handler;
public:
void SetEvent(EventFunction func) { handler = func; }
void EventOne() { handler(1); }
};
class B
{
private:
A a;
public:
B() { a.SetEvent(EventFromA); } // What do I do here?
void EventFromA(int nEvent) { // do stuff }
};
Edit: Orion pointed out the options that Boost offers such as:
boost::function<int (int)> f;
X x;
f = std::bind1st(
std::mem_fun(&X::foo), &x);
f(5); // Call x.foo(5)
Unfortunately Boost is not an option for me. Is there some sort of "currying" function that can be written in C++ that will do this kind of wrapping of a pointer to a member function in to a normal function pointer?
|
I highly recommend Don Clugston's excellent FastDelegate library. It provides all the things you'd expect of a real delegate and compiles down to a few ASM instructions in most cases. The accompanying article is a good read on member function pointers as well.
http://www.codeproject.com/KB/cpp/FastDelegate.aspx
|
151,728 | 151,751 |
Developing for different platforms individually, does anyone recommend it?
|
I know it is easy to recommend several cross platform libraries.
However, are there benefits to treating each platform individually for your product?
Yes there will be some base libraries used in all platforms, but UI and some other things would be different on each platform.
I have no restriction that the product must be 100% alike on each platform.
Mac, Linux, and Windows are the target platforms.
Heavy win32 API, MFC is already used for the Windows version.
The reason I'm not fully for cross platform libraries is because I feel that the end product will suffer a little in trying to generalize it for all platforms.
|
I would say that the benefits of individual development for each platform are:
- native look and feel
- platform knowledge acquired by your developers
-... i'm out of ideas
Seriously, the cost of developing and maintaining 3 separate copies of your application could be huge if you're not careful.
If it's just the GUI code you're worried about then by all means separate out the GUI portion into a per-platform development effort, but you'll regret not keeping the core "business logic" type code common.
And given that keeping your GUI from your logic separate is generally considered a good idea, this would force your developers to maintain that separation when the temptation to put 'just a little bit' of business logic into the presentation layer inevitably arises.
|
151,841 | 151,847 |
High-level Compare And Swap (CAS) functions?
|
I'd like to document what high-level (i.e. C++ not inline assembler ) functions or macros are available for Compare And Swap (CAS) atomic primitives...
E.g., WIN32 on x86 has a family of functions _InterlockedCompareExchange in the <_intrin.h> header.
|
I'll let others list the various platform-specific APIs, but for future reference in C++09 you'll get the
atomic_compare_exchange()
operation in the new "Atomic operations library".
|
151,919 | 151,998 |
When should I use __forceinline instead of inline?
|
Visual Studio includes support for __forceinline. The Microsoft Visual Studio 2005 documentation states:
The __forceinline keyword overrides
the cost/benefit analysis and relies
on the judgment of the programmer
instead.
This raises the question: When is the compiler's cost/benefit analysis wrong? And, how am I supposed to know that it's wrong?
In what scenario is it assumed that I know better than my compiler on this issue?
|
The compiler is making its decisions based on static code analysis, whereas if you profile as don says, you are carrying out a dynamic analysis that can be much farther reaching. The number of calls to a specific piece of code is often largely determined by the context in which it is used, e.g. the data. Profiling a typical set of use cases will do this. Personally, I gather this information by enabling profiling on my automated regression tests. In addition to forcing inlines, I have unrolled loops and carried out other manual optimizations on the basis of such data, to good effect. It is also imperative to profile again afterwards, as sometimes your best efforts can actually lead to decreased performance. Again, automation makes this a lot less painful.
More often than not though, in my experience, tweaking alogorithms gives much better results than straight code optimization.
|
152,005 | 152,020 |
How can currying be done in C++?
|
What is currying?
How can currying be done in C++?
Please Explain binders in STL container?
|
In short, currying takes a function f(x, y) and given a fixed Y, gives a new function g(x) where
g(x) == f(x, Y)
This new function may be called in situations where only one argument is supplied, and passes the call on to the original f function with the fixed Y argument.
The binders in the STL allow you to do this for C++ functions. For example:
#include <functional>
#include <iostream>
#include <vector>
using namespace std;
// declare a binary function object
class adder: public binary_function<int, int, int> {
public:
int operator()(int x, int y) const
{
return x + y;
}
};
int main()
{
// initialise some sample data
vector<int> a, b;
a.push_back(1);
a.push_back(2);
a.push_back(3);
// here we declare a function object f and try it out
adder f;
cout << "f(2, 3) = " << f(2, 3) << endl;
// transform() expects a function with one argument, so we use
// bind2nd to make a new function based on f, that takes one
// argument and adds 5 to it
transform(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5));
// output b to see what we got
cout << "b = [" << endl;
for (vector<int>::iterator i = b.begin(); i != b.end(); ++i) {
cout << " " << *i << endl;
}
cout << "]" << endl;
return 0;
}
|
152,064 | 152,332 |
How to measure performance in a C++ (MFC) application?
|
What good profilers do you know?
What is a good way to measure and tweak the performance of a C++ MFC application?
Is Analysis of algorithms really neccesary? http://en.wikipedia.org/wiki/Algorithm_analysis
|
I strongly recommend AQTime if you are staying on the Windows platform. It comes with a load of profilers, including static code analysis, and works with most important Windows compilers and systems, including Visual C++, .NET, Delphi, Borland C++, Intel C++ and even gcc. And it integrates into Visual Studio, but can also be used standalone. I love it.
|
152,084 | 154,267 |
Fixed point combinators in C++
|
I'm interested in actual examples of using fixed point combinators (such as the y-combinator in C++. Have you ever used a fixed point combinator with egg or bind in real live code?
I found this example in egg a little dense:
void egg_example()
{
using bll::_1;
using bll::_2;
int r =
fix2(
bll::ret<int>(
// \(f,a) -> a == 0 ? 1 : a * f(a-1)
bll::if_then_else_return( _2 == 0,
1,
_2 * lazy(_1)(_2 - 1)
)
)
) (5);
BOOST_CHECK(r == 5*4*3*2*1);
}
Can you explain how this all works?
Is there a nice simple example perhaps using bind with perhaps fewer dependancies than this one?
|
Here is the same code converted into boost::bind notice the y-combinator and its application site in the main function. I hope this helps.
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
// Y-combinator compatible factorial
int fact(boost::function<int(int)> f,int v)
{
if(v == 0)
return 1;
else
return v * f(v -1);
}
// Y-combinator for the int type
boost::function<int(int)>
y(boost::function<int(boost::function<int(int)>,int)> f)
{
return boost::bind(f,boost::bind(&y,f),_1);
}
int main(int argc,char** argv)
{
boost::function<int(int)> factorial = y(fact);
std::cout << factorial(5) << std::endl;
return 0;
}
|
152,216 | 3,308,176 |
Boost Range Library: Traversing Two Ranges Sequentially
|
Boost range library (http://www.boost.org/doc/libs/1_35_0/libs/range/index.html) allows us to abstract a pair of iterators into a range. Now I want to combine two ranges into one, viz:
given two ranges r1 and r2, define r which traverses [r1.begin(), r1.end()[ and then [r2.begin(), r2.end()[. Is there some way to define r as a range using r1 and r2?
|
I needed this again so I had a second look. There is a way to concat two ranges using boost/range/join.hpp. Unluckily the output range type is not included in the interface:
#include "boost/range/join.hpp"
#include "boost/foreach.hpp"
#include <iostream>
int main() {
int a[] = {1, 2, 3, 4};
int b[] = {7, 2, 3, 4};
boost::iterator_range<int*> ai(&a[0], &a[4]);
boost::iterator_range<int*> bi(&b[0], &b[4]);
boost::iterator_range<
boost::range_detail::
join_iterator<int*, int*, int, int&,
boost::random_access_traversal_tag> > ci = boost::join(ai, bi);
BOOST_FOREACH(int& i, ci) {
std::cout << i; //prints 12347234
}
}
I found the output type using the compiler messages. C++0x auto will be relevant there as well.
|
152,318 | 152,343 |
Learning C++ Templates
|
Can anyone recommend any good resources for learning C++ Templates?
Many thanks.
|
I've found cplusplus.com to be helpful on numerous occasions. Looks like they've got a pretty good intro to templates.
If its an actual book you're looking for, Effective C++ is a classic with a great section on templates.
|
152,387 | 152,476 |
What technologies do C++ programmers need to know?
|
C++ was the first programming language I really got into, but the majority of my work on it was academic or for game programming. Most of the programming jobs where I live require Java or .NET programmers and I have a fairly good idea of what technologies they require aside from the basic language. For example, a Java programmer might be required to know EJB, Servlets, Hibernate, Spring, and other technologies, libraries, and frameworks.
I'm not sure about C++, however. In real life situations, for general business programming, what are C++ programmers required to know beyond the language features? Stuff like Win32 API, certain libraries, frameworks, technologies, tools, etc.
Edit: I was thinking of the standard library as well when I said basic language, sorry if it was wrong or not clear. I was wondering if there are any more specific domain requirements similar to all the technologies Java or .NET programmers might be required to learn as apposed to what C++ programmers need to know in general. I do agree that the standard library and Boost are essential, but is there anything beyond that or is it different for every company/project/domain?
|
As for every language, I believe there are three interconnected levels of knowledge :
Master your language. Every programmer should (do what it takes to) master the syntax. Good references to achieve this are :
The C++ Programming Language by Bjarne Stroustrup.
Effective C++ series by Scott Meyers.
Know your libraries extensively.
STL is definitely a must as it has been included in the C++ Standard Library, so knowing it is very close to point 1 : you have to master it.
Knowing boost can be very interesting, as a multi-platform and generic library.
Know the libraries you are supposed to work with, whether it is Win32 API, OCCI, XPCOM or UNO (just a few examples here). No need to know a database library if you develop purely graphic components...
Develop your knowledge of patterns. Cannot avoid Design Patterns: Elements of Reusable Object-Oriented Software here...
So, my answer to your updated question would be : know your language, know your platform, know your domain. I think there is enough work by itself here, especially in C++. It's an evergoing work that should never be overlooked.
|
152,436 | 152,461 |
Do you recommend Native C++ to C++\CLI shift?
|
I have been working as a native C++ programmer for last few years. Now we are starting a new project from the scratch. So what is your thoughts on shifting to C++\CLI at the cost of losing platform independent code. Are there are any special advantages that one can gain by shifting to C++\CLI?
|
I would recommend the following, based on my experience with C++, C# and .NET:
If you want to go the .NET way, use C#.
If you do not want .NET, use traditional C++.
If you have to bridge traditional C++ with .NET code, use C++/CLI. Works both with .NET calling C++ classes and C++ calling .NET classes.
I see no sense in just going to C++/CLI if you don't need it.
|
152,555 | 152,671 |
*.h or *.hpp for your class definitions
|
I've always used a *.h file for my class definitions, but after reading some boost library code, I realised they all use *.hpp. I've always had an aversion to that file extension, I think mainly because I'm not used to it.
What are the advantages and disadvantages of using *.hpp over *.h?
|
Here are a couple of reasons for having different naming of C vs C++ headers:
Automatic code formatting, you might have different guidelines for formatting C and C++ code. If the headers are separated by extension you can set your editor to apply the appropriate formatting automatically
Naming, I've been on projects where there were libraries written in C and then wrappers had been implemented in C++. Since the headers usually had similar names, i.e. Feature.h vs Feature.hpp, they were easy to tell apart.
Inclusion, maybe your project has more appropriate versions available written in C++ but you are using the C version (see above point). If headers are named after the language they are implemented in you can easily spot all the C-headers and check for C++ versions.
Remember, C is not C++ and it can be very dangerous to mix and match unless you know what you are doing. Naming your sources appropriately helps you tell the languages apart.
|
152,643 | 152,665 |
Idiomatic C++ for reading from a const map
|
For an std::map<std::string, std::string> variables, I'd like to do this:
BOOST_CHECK_EQUAL(variables["a"], "b");
The only problem is, in this context variables is const, so operator[] won't work :(
Now, there are several workarounds to this; casting away the const, using variables.count("a") ? variables.find("a")->second : std::string() or even making a function wrapping that. None of these seem to me to be as nice as operator[]. What should I do? Is there a standard way of doing this (beautifully)?
Edit: Just to state the answer that none of you want to give: No, there is no convenient, beautiful, standard way of doing this in C++. I will have to implement a support function.
|
template <typename K, typename V>
V get(std::map<K, V> const& map, K const& key)
{
std::map<K, V>::const_iterator iter(map.find(key));
return iter != map.end() ? iter->second : V();
}
Improved implementation based on comments:
template <typename T>
typename T::mapped_type get(T const& map, typename T::key_type const& key)
{
typename T::const_iterator iter(map.find(key));
return iter != map.end() ? iter->second : typename T::mapped_type();
}
|
152,745 | 152,784 |
Optimising C++ 2-D arrays
|
I need a way to represent a 2-D array (a dense matrix) of doubles in C++, with absolute minimum accessing overhead.
I've done some timing on various linux/unix machines and gcc versions. An STL vector of vectors, declared as:
vector<vector<double> > matrix(n,vector<double>(n));
and accessed through matrix[i][j] is between 5% and 100% slower to access than an array declared as:
double *matrix = new double[n*n];
accessed through an inlined index function matrix[index(i,j)], where index(i,j) evaluates to i+n*j. Other ways of arranging a 2-D array without STL - an array of n pointers to the start of each row, or defining the whole thing on the stack as a constant size matrix[n][n] - run at almost exactly the same speed as the index function method.
Recent GCC versions (> 4.0) seem to be able to compile the STL vector-of-vectors to nearly the same efficiency as the non-STL code when optimisations are turned on, but this is somewhat machine-dependent.
I'd like to use STL if possible, but will have to choose the fastest solution. Does anyone have any experience in optimising STL with GCC?
|
If you're using GCC the compiler can analyze your matrix accesses and change the order in memory in certain cases. The magic compiler flag is defined as:
-fipa-matrix-reorg
Perform matrix flattening and
transposing. Matrix flattening tries
to replace a m-dimensional matrix with
its equivalent n-dimensional matrix,
where n < m. This reduces the level of
indirection needed for accessing the
elements of the matrix. The second
optimization is matrix transposing
that attemps to change the order of
the matrix's dimensions in order to
improve cache locality. Both
optimizations need fwhole-program
flag. Transposing is enabled only if
profiling information is avaliable.
Note that this option is not enabled by -O2 or -O3. You have to pass it yourself.
|
153,046 | 153,058 |
Launch web page from my application
|
Ok, this probably has a really simple answer, but I've never tried to do it before: How do you launch a web page from within an app? You know, "click here to go to our FAQ", and when they do it launches their default web browser and goes to your page. I'm working in C/C++ in Windows, but if there's a broader, more portable way to do it I'd like to know that, too.
|
#include <windows.h>
void main()
{
ShellExecute(NULL, "open", "http://yourwebpage.com",
NULL, NULL, SW_SHOWNORMAL);
}
|
153,065 | 153,077 |
Converting a pointer into an integer
|
I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void* argument that is converted into suitable type in the function itself. A short example:
void function(MESSAGE_ID id, void* param)
{
if(id == FOO) {
int real_param = (int)param;
// ...
}
}
Of course, on a 64 bit machine, I get the error:
error: cast from 'void*' to 'int' loses precision
I would like to correct this so that it still works on a 32 bit machine and as cleanly as possible. Any idea ?
|
Use intptr_t and uintptr_t.
To ensure it is defined in a portable way, you can use code like this:
#if defined(__BORLANDC__)
typedef unsigned char uint8_t;
typedef __int64 int64_t;
typedef unsigned long uintptr_t;
#elif defined(_MSC_VER)
typedef unsigned char uint8_t;
typedef __int64 int64_t;
#else
#include <stdint.h>
#endif
Just place that in some .h file and include wherever you need it.
Alternatively, you can download Microsoft’s version of the stdint.h file from here or use a portable one from here.
|
153,074 | 153,122 |
Tool to visualise code flow (C/C++)
|
Do you have any sugestions of tools to ease the task of understanding C/C++ code? We just inherited a large piece of software written by others and we need to quickly get up to speed on it. Any advice on tools that might simplify this task?
|
SourceInsight and Understand for C++ are the best tools you can get for c/c++ code analysis including flow charts.
|
153,134 | 153,239 |
How do I get a multi line tooltip in MFC
|
Right now, I have a tool tip that pops up when I hover over an edit box. The problem is that this tool tip contains multiple error messages and they are all in one long line. I need to have each error message be on its own line. The error messages are contained in a CString with a new line seperating them.
My existing code is below.
BOOL OnToolTipText(UINT, NMHDR* pNMHDR, LRESULT* pResult)
{
ASSERT(pNMHDR->code == TTN_NEEDTEXTA || pNMHDR->code == TTN_NEEDTEXTW);
// need to handle both ANSI and UNICODE versions of the message
TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
// TCHAR szFullText[256];
CString strTipText=_T("");
UINT nID = pNMHDR->idFrom;
if (pNMHDR->code == TTN_NEEDTEXTA && (pTTTA->uFlags & TTF_IDISHWND) ||
pNMHDR->code == TTN_NEEDTEXTW && (pTTTW->uFlags & TTF_IDISHWND))
{
// idFrom is actually the HWND of the tool
nID = ::GetDlgCtrlID((HWND)nID);
}
//m_errProjAccel[ch] contains 1 or more error messages each seperated by a new line.
if((int)nID >= ID_PROJECTED_ACCEL1 && (int)nID < ID_PROJECTED_ACCEL1 + PROJECTED_ROWS -1 ) {
int ch = nID - ID_PROJECTED_ACCEL1;
strTipText = m_errProjAccel[ch];
}
#ifndef _UNICODE
if (pNMHDR->code == TTN_NEEDTEXTA)
lstrcpyn(pTTTA->szText, strTipText, sizeof(pTTTA->szText)/sizeof(pTTTA->szText[0]));
else
_mbstowcsz(pTTTW->szText, strTipText, sizeof(pTTTA->szText)/sizeof(pTTTA->szText[0]));
#else
if (pNMHDR->code == TTN_NEEDTEXTA)
_wcstombsz(pTTTA->szText, strTipText, sizeof(pTTTA->szText)/sizeof(pTTTA->szText[0]));
else
lstrcpyn(pTTTW->szText, strTipText, sizeof(pTTTA->szText)/sizeof(pTTTA->szText[0]));
#endif
*pResult = 0;
// bring the tooltip window above other popup windows
::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, 0, 0, 0, 0,
SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOMOVE|SWP_NOOWNERZORDER);
return TRUE; // message was handled
}
|
Creating multiline tooltips is explained here in the MSDN library - read the "Implementing Multiline ToolTips" section. You should send a TTM_SETMAXTIPWIDTH message to the ToolTip control in response to a TTN_GETDISPINFO notification to force it to use multiple lines. In your string you should separate lines with \r\n.
Also, if your text is more than 80 characters, you should use the lpszText member of the NMTTDISPINFO structure instead of copying into the szText array.
|
153,257 | 153,525 |
Random MoveFileEx failures on Vista
|
I noticed that writing to a file, closing it and moving it to destination place randomly fails on Vista. Specifically, MoveFileEx() would return ERROR_ACCESS_DENIED for no apparent reason. This happens on Vista SP1 at least (32 bit). Does not happen on XP SP3.
Found this thread on the internets about exactly the same problem, with no real solutions. So far it looks like the error is caused by Vista's search indexer, see below.
The code example given there is enough to reproduce the problem. I'm pasting it here as well:
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
bool test() {
unsigned char buf[] = {
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99
};
HANDLE h;
DWORD nbytes;
LPCTSTR fn_tmp = "aaa";
LPCTSTR fn = "bbb";
h = CreateFile(fn_tmp, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_ALWAYS, 0, 0);
if (h == INVALID_HANDLE_VALUE) return 0;
if (!WriteFile(h, buf, sizeof buf, &nbytes, 0)) goto error;
if (!FlushFileBuffers(h)) goto error;
if (!CloseHandle(h)) goto error;
if (!MoveFileEx(fn_tmp, fn, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) {
printf("error=%d\n", GetLastError());
return 0;
}
return 1;
error:
CloseHandle(h);
return 0;
}
int main(int argc, char** argv) {
unsigned int i;
for (i = 0;; ++i) {
printf("*%u\n", i);
if (!test()) return 1;
}
return 0;
}
Build this as console app with Visual Studio. Correct behaviour would be infinite loop that prints test numbers. On Vista SP1, the program exits after random number of iterations (usually before 100 iterations are made).
This does not happen on Windows XP SP2. There's no antivirus running at all; and no other strange background processes (machine is pretty much vanilla OS install + Visual Studio).
Edit: Digging further via Process Monitor (thanks @sixlettervariables), I can't see anything particularly bad. Each test iteration results in 176 disk operations, majority of them coming from SearchProtocolHost.exe (search indexer). If search indexing service is stopped, no errors occur, so it looks like it's the culprit.
At the time of failure (when the app gets ERROR_ACCESS_DENIED), SearchProtocolHost.exe has two CreateFile(s) to the detination file (bbb) open with read/write/delete share modes, so it should be ok. One of the opens is followed by opportunistic lock (FSCTL_REQUEST_FILTER_OPLOCK), maybe that's the cause?
Anyway, I found out that I can avoid the problem by setting FILE_ATTRIBUTE_TEMPORARY and FILE_ATTRIBUTE_NOT_CONTENT_INDEXED flags on the file. It looks like FILE_ATTRIBUTE_NOT_CONTENT_INDEXED is enough by itself, but marking file as temporary also dramatically cuts down disk operations caused by search indexer.
But this is not a real solution. I mean, if an application can't expect to be able to create a file and rename it because some Vista's search indexer is messing with it, it's totally crazy! Should it keep retrying? Yell at the user (which is very undesirable)? Do something else?
|
I suggest you use Process Monitor (edit: the artist formerly known as FileMon) to watch and see which application exactly is getting in the way. It can show you the entire trace of file system calls made on your machine.
(edit: thanks to @moocha for the change in application)
|
153,559 | 154,190 |
What are some good profilers for native C++ on Windows?
|
I'm looking for a profiler to use with native C++. It certainly does not have to be free, however cost does factor into the purchase decision. This is for commercial work so I can't use personal or academic licensed copies.
The key features I'm looking for are:
Process level metrics
Component level metrics
Line-level metrics
Supports Multi-threaded code
Usability
Cost
Visual Studio 2005 Professional support required (VS 2008 Professional support highly
desirable)
I've used Intel's VTune and Compuware's Devpartner Performance Analysis Community Edition.
VTune seemed very powerful but it has a steep learning curve. It also is very "modular" so you have to figure out what parts are you need to buy.
DevPartner PACE was pretty easy to use and provides all of the key features however it's only a 45-day trial. The licensed version (DevPartner for Visual C++ BoundsChecker Suite) is about $1400 a seat, which is doable but a bit high imo.
What are some good profilers for native C++ and WHY?
See also:
What's Your Favorite Profiling Tool For C++
|
On Windows, GlowCode is affordable, fairly easy to use, and offers a free trial so you can see if it works for you.
|
153,676 | 153,704 |
GUIDs in a C++ Linux GCC app
|
I've got a bunch of servers running this Linux app. I'd like for them to be able to generate a GUID with a low probability of collision. I'm sure I could just pull 128 bytes out of /dev/urandom and that would probably be fine, but is there a simple & easy way to generate a GUID that is more equivalent to the Win32 one? Specifically, one that takes into account space (well, MAC address), time, and randomness? I don't want to call off the box for it, I just want something like CreateGuid()
|
This Internet Draft describes one type of UUID in great details and I have used a similar approach with great success when I needed a UUID implementation and could not link to an existing library for architectural reasons.
This article provides a good overview.
|
153,685 | 153,738 |
Managing Window Z-Order Like Photoshop CS
|
So I've got an application whose window behavior I would like to behave more like Photoshop CS. In Photoshop CS, the document windows always stay behind the tool windows, but are still top level windows. For MDI child windows, since the document window is actually a child, you can't move it outside of the main window. In CS, though, you can move your image to a different monitor fine, which is a big advantage over docked applications like Visual Studio, and over regular MDI applications.
Anyway, here's my research so far. I've tried to intercept the WM_MOUSEACTIVATE message, and use the DeferWindowPos commands to do my own ordering of the window, and then return MA_NOACTIVATEANDEAT, but that causes the window to not be activated properly, and I believe there are other commands that "activate" a window without calling WM_MOUSEACTIVATE (like SetFocus() I think), so that method probably won't work anyway.
I believe Windows' procedure for "activating" a window is
1. notify the unactivated window with the WM_NCACTIVATE and WM_ACTIVATE messages
2. move the window to the top of the z-order (sending WM_POSCHANGING, WM_POSCHANGED and repaint messages)
3. notify the newly activated window with WM_NCACTIVATE and WM_ACTIVATE messages.
It seems the cleanest way to do it would be to intercept the first WM_ACTIVATE message, and somehow notify Windows that you're going to override their way of doing the z-ordering, and then use the DeferWindowPos commands, but I can't figure out how to do it that way. It seems once Windows sends the WM_ACTIVATE message, it's already going to do the reordering its own way, so any DeferWindowPos commands I use are overridden.
Right now I've got a basic implementation quasy-working that makes the tool windows topmost when the app is activated, but then makes them non-topmost when it's not, but it's very quirky (it sometimes gets on top of other windows like the task manager, whereas Photoshop CS doesn't do that, so I think Photoshop somehow does it differently) and it just seems like there would be a more intuitive way of doing it.
Anyway, does anyone know how Photoshop CS does it, or a better way than using topmost?
|
I would imagine they've, since they're not using .NET, rolled their own windowing code over the many years of its existence and it is now, like Amazon's original OBIDOS, so custom to their product that off-the-shelf (aka .NET's MDI support) just aren't going to come close.
I don't like answering without a real answer, but likely you'd have to spend a lot of time and effort to get something similar if Photoshop-like is truly your goal. Is it worth your time? Just remember many programmers over many years and versions have come together to get Photoshop's simple-seeming windowing behavior to work just right and to feel natural to you.
It looks like you're already having to delve pretty deep into Win32 API functions and values to even glimpse at a "solution" and that should be your first red flag. Is it eventually possible? Probably. But depending on your needs and your time and a lot of other factors only you could decide, it may not be practical.
|
153,707 | 153,830 |
Inheriting from protected classes in C+++
|
Suppose I have the following declaration:
class Over1
{
protected:
class Under1
{
};
};
I know that I could do the following:
class Over2 : public Over1
{
protected:
class Under2 : public Under1
{
};
};
But is there a way to declare Under2 without Over2?
Since you would have to extend Over1 to use any derivative of Under1 this may seem silly, but in this situation there might be 30 different flavors of Under. I can either:
Put them all inside Over1 : Not
attractive since Over2 may only use
1 or 2 of them
Put them each in
their own version of Over : Not
attractive since then you will have
to multiply inherit from almost the
same class.
Find a way to create
children of Under1 without creating
children of Over1
So is this possible?
Thanks.
|
Using templates and explicit specializations you can do this with just one additional class declaration in Over1.
class Over1
{
protected:
class Under1
{
};
template <typename T>
class UnderImplementor;
};
struct Under2Tag;
struct Under3Tag;
struct Under4Tag;
template <>
class Over1::UnderImplementor<Under2Tag> : public Over1::Under1
{
};
template <>
class Over1::UnderImplementor<Under3Tag> : public Over1::Under1
{
};
template <>
class Over1::UnderImplementor<Under4Tag> : public Over1::Under1
{
};
Hope this helps.
|
154,060 | 708,982 |
Overriding namespaces in gSOAP
|
I am using gSOAP as a Web Service toolkit and have generated the stub and proxy classes through soapcpp2 from multiple WSDLs all at once. Thus all the namespace bindings are in a single .nsmap file.
Now the problem is that all the namespace bindings are being sent with all the method calls I make. The HTTP POST packet is unusually large and ugly.
Is there a way to programatically override the namespace bindings ?
|
Check soapcpp2 and its -q flag, it will help you.
Other than that, the -penv flag will pack basic gSOAP-related methods within the executable, not including any service objects.
Therefore the files generated with -penv can be shared across multiple namespaces, pertaining to different generated gSOAP Web Services.
|
154,136 | 154,138 |
Why use apparently meaningless do-while and if-else statements in macros?
|
In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless do while loop. Here are examples.
#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else
I can't see what the do while is doing. Why not just write this without it?
#define FOO(X) f(X); g(X)
|
The do ... while and if ... else are there to make it so that a
semicolon after your macro always means the same thing. Let's say you
had something like your second macro.
#define BAR(X) f(x); g(x)
Now if you were to use BAR(X); in an if ... else statement, where the bodies of the if statement were not wrapped in curly brackets, you'd get a bad surprise.
if (corge)
BAR(corge);
else
gralt();
The above code would expand into
if (corge)
f(corge); g(corge);
else
gralt();
which is syntactically incorrect, as the else is no longer associated with the if. It doesn't help to wrap things in curly braces within the macro, because a semicolon after the braces is syntactically incorrect.
if (corge)
{f(corge); g(corge);};
else
gralt();
There are two ways of fixing the problem. The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression.
#define BAR(X) f(X), g(X)
The above version of bar BAR expands the above code into what follows, which is syntactically correct.
if (corge)
f(corge), g(corge);
else
gralt();
This doesn't work if instead of f(X) you have a more complicated body of code that needs to go in its own block, say for example to declare local variables. In the most general case the solution is to use something like do ... while to cause the macro to be a single statement that takes a semicolon without confusion.
#define BAR(X) do { \
int i = f(X); \
if (i > 4) g(i); \
} while (0)
You don't have to use do ... while, you could cook up something with if ... else as well, although when if ... else expands inside of an if ... else it leads to a "dangling else", which could make an existing dangling else problem even harder to find, as in the following code.
if (corge)
if (1) { f(corge); g(corge); } else;
else
gralt();
The point is to use up the semicolon in contexts where a dangling semicolon is erroneous. Of course, it could (and probably should) be argued at this point that it would be better to declare BAR as an actual function, not a macro.
In summary, the do ... while is there to work around the shortcomings of the C preprocessor. When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they're worried about.
|
154,245 | 155,098 |
Editing a text buffer
|
Ok, this is a bit of a cheeky question. I want to build a simple text editor (using my own text mode screen handling). I just want a good example of data structures that can be used to represent the text buffer, and some simple examples of char/text insertion/deletion. I can handle all the rest of the code myself (file i/o, console i/o etc). A link to a nice simple editor source would be great (C or C++).
|
This is 2008. Don't write a text editor; you're reinventing fire.
Still here? I'm not sure if this applies or what platforms you plan to support, but the Neatpad series of tutorials is a great place to start thinking about writing a text editor. They focus on Win32 as the basic platform, but many of the lessons learned will apply anywhere.
|
154,365 | 154,379 |
search 25 000 words within a text
|
I need to find occurrences of ~ 25 000 words within a text. What is the most suitable algorithm/library for this purpose?
target language is C++
|
build a hashtable with the words, and scan throuhgt the text, for each word lookup in the wordtable and stuff the needed info (increment count, add to a position list, whatever).
|
154,469 | 154,482 |
Unnamed/anonymous namespaces vs. static functions
|
A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:
namespace {
int cannotAccessOutsideThisFile() { ... }
} // namespace
You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces are accessible within the file they're created in, as if you had an implicit using-clause to them.
My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?
|
The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:
The use of the static keyword is
deprecated when declaring objects in a
namespace scope, the unnamed-namespace
provides a superior alternative.
Static only applies to names of objects, functions, and anonymous unions, not to type declarations.
Edit:
The decision to deprecate this use of the static keyword (affecting visibility of a variable declaration in a translation unit) has been reversed (ref). In this case using a static or an unnamed namespace are back to being essentially two ways of doing the exact same thing. For more discussion please see this SO question.
Unnamed namespace's still have the advantage of allowing you to define translation-unit-local types. Please see this SO question for more details.
Credit goes to Mike Percy for bringing this to my attention.
|
154,547 | 156,115 |
Control for getting hotkeys like tab and space
|
I have a dialog box that allows users to set hotkeys for use in a 3d program on windows. I'm using CHotKeyCtrl, which is pretty good, but doesn't handle some keys that the users would like to use - specifically, tab and space.
The hotkey handling is smart enough to be able to fire on those keys, I just need a UI to let them be set. A control similar to CHotKeyCtrl would be ideal, but other workarounds are also appreciated.
|
One workarounds option would be to use a stock standard edit control with a message hook function.
This would allow you to trap the keyboard WM_KEYDOWN messages sent to that edit control.
The hook function would look something like this:
LRESULT CALLBACK MessageHook(int code, WPARAM wParam, LPMSG lpMsg)
{
LRESULT lResult = 0;
if ((code >= 0) && (code == MSGF_DIALOGBOX))
{
if (lpMsg->message == WM_KEYDOWN)
{
//-- process the key down message
lResult = 1;
}
}
// do default processing if required
if (lResult == 0)
{
lResult = CallNextHookEx(MessageFilterHook, code, wParam, (LPARAM)lpMsg);
}
return lResult;
}
The hook can then be attached to edit control when the edit control gets focus as follows:
//-- create an instance thunk for our hook callback
FARPROC FilterProc = (FARPROC) MakeProcInstance((HOOKPROC)(MessageHook),
hInstance);
//-- attach the message hook
FilterHook = SetWindowsHookEx(WH_MSGFILTER,
(HOOKPROC)FilterProc,
hInstance, GetCurrentThreadId());
and removed when the edit control when looses focus as follows:
//-- remove a message hook
UnhookWindowsHookEx(MessageFilterHook);
Using this approach every key press will be sent to the hook, provided the edit control has focus.
|
154,730 | 154,809 |
Capturing video out of an OpenGL window in Windows
|
I am supposed to provide my users a really simple way of capturing video clips out of my OpenGL application's main window. I am thinking of adding buttons and/or keyboard shortcuts for starting and stopping the capture; when starting, I could ask for a filename and other options, if any. It has to run in Windows (XP/Vista), but I also wouldn't like to close the Linux door which I've so far been able to keep open.
The application uses OpenGL fragment and shader programs, the effects due to which I absolutely need to have in the eventual videos.
It looks to me like there might be even several different approaches that could potentially fulfill my requirements (but I don't really know where I should start):
An encoding library with functions like startRecording(filename), stopRecording, and captureFrame. I could call captureFrame() after every frame rendered (or every second/third/whatever). If doing so makes my program run slower, it's not really a problem.
A standalone external program that can be programmatically controlled from my application. After all, a standalone program that can not be controlled almost does what I need... But as said, it should be really simple for the users to operate, and I would appreciate seamlessness as well; my application typically runs full-screen. Additionally, it should be possible to distribute as part of the installation package for my application, which I currently prepare using NSIS.
Use the Windows API to capture screenshots frame-by-frame, then employ (for example) one of the libraries mentioned here. It seems to be easy enough to find examples of how to capture screenshots in Windows; however, I would love a solution which doesn't really force me to get my hands super-dirty on the WinAPI level.
Use OpenGL to render into an offscreen target, then use a library to produce the video. I don't know if this is even possible, and I'm afraid it might not be the path of least pain anyway. In particular, I would not like the actual rendering to take a different execution path depending on whether video is being captured or not. Additionally, I would avoid anything that might decrease the frame rate in the normal, non-capture mode.
If the solution were free in either sense of the word, then that would be great, but it's not really an absolute requirement. In general, the less bloat there is, the better. On the other hand, for reasons beyond this question, I cannot link in any GPL-only code, unfortunately.
Regarding the file format, I cannot expect my users to start googling for any codecs, but as long as also displaying the videos is easy enough for a basic-level Windows user, I don't really care what the format is. However, it would be great if it were possible to control the compression quality of the output.
Just to clarify: I don't need to capture video from an external device like camcorder, nor am I really interested in mouse movements, even though getting them does not harm either. There are no requirements regarding audio; the application makes no noise whatsoever.
I write C++ using Visual Studio 2008, for this very application also taking benefit of GLUT and GLUI. I have a solid understanding regarding C++ and linking in libraries and that sort of stuff, but on the other hand OpenGL is quite new for me: so far, I've really only learnt the necessary bits to actually get my job done.
I don't need a solution super-urgently, so feel free to take your time :)
|
There are two different questions here - how to grab frames from an OpenGL application, and how to turn them into a movie file.
The first question is easy enough; you just grab each frame with glReadPixels() (via a PBO if you need the performance).
The second question is a little harder since the cross-platform solutions (ffmpeg) tend to be GPL'd or LGPL'd. Is LGPL acceptable for your project? The Windows way of doing this (DirectShow) is a bit of a headache to use.
Edit: Since LGPL is ok and you can use ffmpeg, see here for an example of how to encode video.
|
154,780 | 154,833 |
Is there a way to handle a variable number of parameters in a template class?
|
I have a set of callback classes that I use for handling callbacks with variable numbers of parameters. Right now I have about 6 different instances of it to handle differing numbers of arguments. Is there a way to make one instance than can handle a variable number of arguments?? Ultimately I would love to have each parameter be a POD type or a class pointer, or a struct pointer. Any ideas?
template <class T>
class kGUICallBackPtr
{
public:
kGUICallBackPtr() {m_obj=0;m_func=0;}
void Set(void *o,void (*f)(void *,T *));
inline void Call(T *i) {if(m_func) m_func(m_obj,i);}
inline bool IsValid(void) {return (m_func!=0);}
private:
void *m_obj;
void (*m_func)(void *,T *);
};
template <class T,class U>
class kGUICallBackPtrPtr
{
public:
kGUICallBackPtrPtr() {m_obj=0;m_func=0;}
void Set(void *o,void (*f)(void *,T *,U *));
inline void Call(T *i, U *j) {if(m_func) m_func(m_obj,i,j);}
inline bool IsValid(void) {return (m_func!=0);}
private:
void *m_obj;
void (*m_func)(void *,T *,U *j);
};
|
Not yet in the language itself but C++0x will have support for variadic templates.
|
155,191 | 155,213 |
Windows API commctrl.h using application doesn't work on machines without the Platform SDK
|
I have written something that uses the following includes:
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <commctrl.h>
This code works fine on 2 machines with the Platform SDK installed, but doesn't run (neither debug nor release versions) on clean installs of windows (VMs of course). It dies with the quite familiar:
---------------------------
C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe
---------------------------
C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe
This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
---------------------------
OK
---------------------------
How can I make it run on clean installs? Which dll is it using which it can't find? My bet is on commctrl, but can someone enlighten me on why it's isn't with every windows?
Further more, if anyone has tips on how to debug such a thing, as my CPP is already rusty, as it seems :)
Edit - What worked for me is downloading the Redistributable for Visual Studio 2008. I don't think it's a good solution - downloading a 2MB file and an install to run a simple 11K tool. I think I'll change the code to use LoadLibrary to get the 2 or 3 functions I need from comctl32.dll. Thanks everyone :)
|
Use Dependency Walker. Download and install from http://www.dependencywalker.com/ (just unzip to install). Then load up your executable. The tool will highlight which DLL is missing. Then you can find the redistributable pack which you need to ship with your executable.
If you use VS2005, most cases will be covered by http://www.microsoft.com/downloads/details.aspx?FamilyId=32BC1BEE-A3F9-4C13-9C99-220B62A191EE&displaylang=en which includes everything needed to run EXEs created with VS2005. Using depends.exe you may find a more lightweight solution, though.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.