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 |
|---|---|---|---|---|
54,047 | 54,056 | Regex's For Developers | I've been trying to figure out a regex to allow me to search for a particular string while automatically skipping comments. Anyone have an RE like this or know of one? It doesn't even need to be sophisticated enough to skip #if 0 blocks; I just want it to skip over // and /* blocks. The converse, that is only search... | This is a harder problem than it might at first appear, since you need to consider comment tokens inside strings, comment tokens that are themselves commented out etc.
I wrote a string and comment parser for C#, let me see if I can dig out something that will help... I'll update if I find anything.
EDIT:
... ok, so I f... |
54,142 | 54,146 | How does the Comma Operator work | How does the comma operator work in C++?
For instance, if I do:
a = b, c;
Does a end up equaling b or c?
(Yes, I know this is easy to test - just documenting on here for someone to find the answer quickly.)
Update: This question has exposed a nuance when using the comma operator. Just to document this:
a = b, c; ... | It would be equal to b.
The comma operator has a lower precedence than assignment.
|
54,188 | 54,444 | Are C++ Reads and Writes of an int Atomic? | I have two threads, one updating an int and one reading it. This is a statistic value where the order of the reads and writes is irrelevant.
My question is, do I need to synchronize access to this multi-byte value anyway? Or, put another way, can part of the write be complete and get interrupted, and then the read hap... | At first one might think that reads and writes of the native machine size are atomic but there are a number of issues to deal with including cache coherency between processors/cores. Use atomic operations like Interlocked* on Windows and the equivalent on Linux. C++0x will have an "atomic" template to wrap these in a... |
54,585 | 54,596 | When should you use a class vs a struct in C++? | In what scenarios is it better to use a struct vs a class in C++?
| The differences between a class and a struct in C++ are:
struct members and base classes/structs are public by default.
class members and base classes/structs are private by default.
Both classes and structs can have a mixture of public, protected and private members, can use inheritance, and can have member functio... |
54,674 | 54,742 | Any good building tools for a C++ project, which can replace make? | i'm wondering if there is any nice and neat tool to replace the GNU Autotools or Make to build a very large C++ project, which are such a complicated thing to use.
It is simple to generate all the files that de Autotools require if the project is small, but if the source code is divided in many directories, with multi... | The Google V8 JavaScript Engine is written in C++ and uses SCons, so I guess that's one vote for it.
|
55,093 | 55,149 | How to deal with arrays (declared on the stack) in C++? | I have a class to parse a matrix that keeps the result in an array member:
class Parser
{
...
double matrix_[4][4];
};
The user of this class needs to call an API function (as in, a function I have no control over, so I can't just change its interface to make things work more easily) that looks like this:
void api... | Here's a nice, clean way:
class Parser
{
public:
typedef double matrix[4][4];
// ...
const matrix& getMatrix() const
{
return matrix_;
}
// ...
private:
matrix matrix_;
};
Now you're working with a descriptive type name rather than an array, but since it's a typedef the compiler will stil... |
55,440 | 55,446 | Checking Inheritance with templates in C++ | I've a class which is a wrapper class(serves as a common interface) around another class implementing the functionality required. So my code looks like this.
template<typename ImplemenationClass> class WrapperClass {
// the code goes here
}
Now, how do I make sure that ImplementationClass can be derived from a set of ... | It's verbose, but you can do it like this:
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_of.hpp>
struct base {};
template <typename ImplementationClass, class Enable = void>
class WrapperClass;
template <typename ImplementationClass>
class WrapperClass<ImplementationClass,
typename... |
55,451 | 55,477 | Which C# project type would you use to redevelop a MFC C++ activex control? | Looking at the C# project templates in VS2008 and the offerings are WPF User Control Library, WPF Custom Control Library and Windows Forms Control Library. Which of these would you use if you wanted to move a legacy active control written in c++ into the world of C# and .NET?
| It sounds like you are trying to do several different things all at once:
Migrate your code to building in a newer version of visual studio.
Migrate your use of technology to a newer technology (ActiveX to .net)
Migrate your language (c++ to c#).
If you have a small codebase you are probably as well to start from scr... |
55,510 | 55,548 | When do function-level static variables get allocated/initialized? | I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time.
int globalgarbage;
unsigned int anumber = 42;
But what about static ones defined within a function?
void doSomething()
{
static bool globalish = true;
// ...
}
When is the space for globalish... | I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2.
include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const char *name)
: _name(name)
{
cout << _name << " created" << endl;
}
... |
55,532 | 55,660 | Casting between multi- and single-dimentional arrays | This came up from this answer to a previous question of mine.
Is it guaranteed for the compiler to treat array[4][4] the same as array[16]?
For instance, would either of the below calls to api_func() be safe?
void api_func(const double matrix[4][4]);
// ...
{
typedef double Matrix[4][4];
double* array1 = new dou... | From the C++ standard, referring to the sizeof operator:
When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.
From this, I'd say that double[4][4] and double[16] would have to have the same underlying re... |
55,641 | 55,650 | Unicode Processing in C++ | What is the best practice of Unicode processing in C++?
|
Use ICU for dealing with your data (or a similar library)
In your own data store, make sure everything is stored in the same encoding
Make sure you are always using your unicode library for mundane tasks like string length, capitalization status, etc. Never use standard library builtins like is_alpha unless that is t... |
55,753 | 55,885 | Creating Custom Performance Counters in Visual C++ | Does anybody know of a method for creating custom Performance Counters using ordinary unmanaged Visual C++?
I know that it can be done easily using managed C++, but I need to do it using an unmanaged Windows service.
I also know that you can retrieve performance counter data, but I need to create some custom counters a... | See here:
http://msdn.microsoft.com/en-us/library/aa371925.aspx
It is not really hard, but a bit tedious as the API involves extensive usage of self-referential, variable-length structures and has to employ some IPC mechanism to obtain the data from the monitored process.
|
55,859 | 55,863 | How can I catch all types of exceptions in one catch block? | In C++, I'm trying to catch all types of exceptions in one catch (like catch(Exception) in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?
| catch (...)
{
// Handle exceptions not covered.
}
Important considerations:
A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions.
catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you ... |
56,046 | 56,080 | Stop system entering 'standby' | How can i stop the host machine entering standby mode while my application is running?
Is there any win32 api call to do this?
| There are two APIs, depending on what version of Windows.
XP,2000, 2003:
http://msdn.microsoft.com/en-us/library/aa373247(VS.85).aspx
Respond to PBT_APMQUERYSUSPEND.
Vista, 2008:
http://msdn.microsoft.com/en-us/library/aa373208(VS.85).aspx
There could be many valid reasons to prevent the computer from going to sleep. ... |
56,091 | 56,111 | Pointers to C++ class methods | Whilst refactoring some legacy C++ code I found that I could potentially remove some code duplication by somehow defining a variable that could point to any class method that shared the same signature. After a little digging, I found that I could do something like the following:
class MyClass
{
protected:
bool Cas... | What you have there is a pointer-to-member-function. It will solve your problem. I am surprised that your "TestSwitch" function compiles, as the calling syntax is slightly different to what you might expect. It should be:
bool res = (this->*CaseMethod)( 999, "hello world" );
However, you might find a combination of bo... |
56,145 | 87,399 | MFC IE embedded web browser wackiness | I have this modeless MFC dialog which embeds an Internet Explorer web browser control.
The control is derived straight from CWnd with ActiveX wrappers generated by Visual Studio, and I map it to the CDialog using only a DDX_Control(pDX, IDC_EXPLORER, m_explorer);.
I have 2 problems.
Problem #1:
Being modeless, I start ... | problem 1) try myBrowser.navigate("about:blank") before destroying the window.
|
56,340 | 154,326 | Can I set a data breakpoint in runtime in System C (or in Plain Vanilla C++)? | I have a class in system-C with some data members as such:
long double x[8];
I'm initializing it in the construction like this:
for (i = 0; i < 8; ++i) {
x[i] = 0;
}
But the first time I use it in my code I have garbage there.
Because of the way the system is built I can't connect a debugger easily. Are there ... | You could try starting a second thread which spins, looking for changes in the variable:
#include <pthread.h>
void *ThreadProc(void *arg)
{
volatile long double *x = (volatile long double *)arg;
while(1)
{
for(int i = 0; i < 8; i++)
{
if(x[i] != 0)
{
__asm__ __volatile__ ("int 3"); ... |
56,347 | 56,370 | Iterators in C++ (stl) vs Java, is there a conceptual difference? | I'm returning to c++ after being away for a bit and trying to dust off the old melon.
In Java Iterator is an interface to a container having methods: hasNext(), next() and remove(). The presence of hasNext() means it has the concept of a limit for the container being traversed.
//with an Iterator
Iterator<String> iter... | Yes, there is a large conceptual difference. C++ utilizes different "classes" of iterators. Some are used for random access (unlike Java), some are used for forward access (like java). While even others are used for writing data (for use with, say, transform).
See the iterators concept in the C++ Documentation:
Input... |
56,391 | 56,418 | Automatically checking for a new version of my application | Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available.
The problem is that I have no idea about what have to be done on the server side.
I can imagine that my application (developped in C++ using Qt) has to send... | I would absolutely recommend to just do a plain HTTP request to your website. Everything else is bound to fail.
I'd make a HTTP GET request to a certain page on your site containing the version of the local application.
like
http://www.example.com/update?version=1.2.4
Then you can return what ever you want, probably a... |
56,424 | 80,707 | What can cause a reduction in frame rate when upgrading a graphics card? | We have a two-screen DirectX application that previously ran at a consistent 60 FPS (the monitors' sync rate) using a NVIDIA 8400GS (256MB). However, when we swapped out the card for one with 512 MB of RAM the frame rate struggles to get above 40 FPS. (It only gets this high because we're using triple-buffering.) The t... | Are the cards exactly the same (both GeForce 8400GS), and only the memory size differ? Quite often with different memory sizes come slightly different clock rates (i.e. your card with more memory might use slower memory!).
So the first thing to check would be GPU core & memory clock rates, using something like GPU-Z.
|
56,500 | 56,514 | Can't access variable in C++ DLL from a C app | I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put
extern "C" _declspec(dllexport) char* MyNewVariable = 0;
which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable ... | you must link against the lib generated after compiling the DLL. In the linker options of the project, you must add the .lib file. And yes, you should also declare the variable as:
extern "C" { declspec(dllimport) char MyNewVariable; }
|
56,682 | 56,768 | How to see if a subfile of a directory has changed | In Windows, is there an easy way to tell if a folder has a subfile that has changed?
I verified, and the last modified date on the folder does not get updated when a subfile changes.
Is there a registry entry I can set that will modify this behavior?
If it matters, I am using an NTFS volume.
I would ultimately like to... | This article should help. Basically, you create one or more notification object such as:
HANDLE dwChangeHandles[2];
dwChangeHandles[0] = FindFirstChangeNotification(
lpDir, // directory to watch
FALSE, // do not watch subtree
FILE_NOTIFY_CHANGE_F... |
56,741 | 56,882 | File system info - how to query it? | Is there a way to access file system info via some type of Windows API? If not what other methods are available to a user mode developer?
| Not very clean, but you can use DeviceIoControl()
Open volume as a file, pass resulting handle to DeviceIoControl() together with control code. Check MSDN for control codes, there is something like "read journal record".
|
57,840 | 57,862 | How to attach debugger to step into native (C++) code from a managed (C#) wrapper? | I have a wrapper around a C++ function call which I call from C# code. How do I attach a debugger in Visual Studio to step into the native C++ code?
This is the wrapper that I have which calls GetData() defined in a C++ file:
[DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl,
Ent... | Check the Debug tab on your project's properties page. There should be an "Enable unmanaged code debugging" checkbox. This worked for me when we developed a new .NET UI for our old c++ DLLs.
If your unmanaged DLL is being built from another project (for a while ours were being built using VS6) just make sure you have ... |
58,058 | 58,061 | Using C++ classes in .so libraries | I'm trying to write a small class library for a C++ course.
I was wondering if it was possible to define a set of classes in my shared object and then using them directly in my main program that demos the library. Are there any tricks involved? I remember reading this long ago (before I started really programming) that... | C++ classes work fine in .so shared libraries (they also work in non-MFC DLLs on Windows, but that's not really your question). It's actually easier than Windows, because you don't have to explicitly export any symbols from the libraries.
This document will answer most of your questions: http://people.redhat.com/drepp... |
58,730 | 58,737 | Open source PDF library for C/C++ application? | I want to be able to generate PDF output from my (native) C++ Windows application. Are there any free/open source libraries available to do this?
I looked at the answers to this question, but they mostly relate to .Net.
| LibHaru
Haru is a free, cross platform,
open-sourced software library for
generating PDF written in ANSI-C. It
can work as both a static-library (.a,
.lib) and a shared-library (.so,
.dll).
Didn't try it myself, but maybe it can help you
|
58,851 | 59,146 | Can I set a breakpoint on 'memory access' in GDB? | I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes.
| watch only breaks on write, rwatch let you break on read, and awatch let you break on read/write.
You can set read watchpoints on memory locations:
gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface
but one limitation applies to the rwatch and awatch commands; you can't use gdb variables
in expressions:
g... |
59,280 | 59,317 | Programmatically change combobox | I need to update a combobox with a new value so it changes the reflected text in it. The cleanest way to do this is after the comboboxhas been initialised and with a message.
So I am trying to craft a postmessage to the hwnd that contains the combobox.
So if I want to send a message to it, changing the currently select... | You want ComboBox_SetCurSel:
ComboBox_SetCurSel(hWndCombo, n);
or if it's an MFC CComboBox control you can probably do:
m_combo.SetCurSel(2);
I would imagine if you're doing it manually you would also want SendMessage rather than PostMessage. CBN_SELCHANGE is the notification that the control sends back to you when t... |
59,635 | 70,808 | App does not run with VS 2008 SP1 DLLs, previous version works with RTM versions | Since our switch from Visual Studio 6 to Visual Studio 2008, we've been using the MFC90.dll and msvc[pr]90.dlls along with the manifest files in a private side-by-side configuration so as to not worry about versions or installing them to the system.
Pre-SP1, this was working fine (and still works fine on our developer ... | I have battled this problem myself last week and consider myself somewhat of an expert now ;)
I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put
#define _BIND_TO_CURRENT_MFC_VERSION 1
#define _BIND_TO_CURRENT_CRT_VERSION 1
into every project you're using. For ever... |
59,670 | 59,687 | How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC | I'm working on an exceedingly large codebase, and recently upgraded to GCC 4.3, which now triggers this warning:
warning: deprecated conversion from string constant to ‘char*’
Obviously, the correct way to fix this is to find every declaration like
char *s = "constant string";
or function call like:
void foo(char *s... | I believe passing -Wno-write-strings to GCC will suppress this warning.
|
60,000 | 2,688,631 | C++ inheritance and member function pointers | In C++, can member function pointers be used to point to derived (or even base) class members?
EDIT:
Perhaps an example will help. Suppose we have a hierarchy of three classes X, Y, Z in order of inheritance.
Y therefore has a base class X and a derived class Z.
Now we can define a member function pointer p for clas... | C++03 std, §4.11 2 Pointer to member conversions:
An rvalue of type “pointer to member of B of type cv T,” where B is a class type, can be converted to an rvalue of type “pointer to member of D of type cv T,” where D is a derived class (clause 10) of B. If B is an inaccessible (clause 11), ambiguous (10.2) or virtual ... |
60,331 | 60,355 | C++ Quiz - Singletons | I'll soon be posting an article on my blog, but I'd like to verify I haven't missed anything first.
Find an example I've missed, and I'll cite you on my post.
The topic is failed Singleton implementations: In what cases can you accidentally get multiple instances of a singleton?
So far, I've come up with:
Race Conditi... | If you use a static instance field that you initialize in your cpp file, you can get multiple instances (and even worse behavior) if the initialization of some static/global tries to get an instance of your singleton. This is because the order of static initialization across compilation units is undefined.
|
60,422 | 930,781 | IDebugProgramProvider2.GetProviderProcessData on Vista | As part of a JavaScript Profiler for IE 6/7 I needed to load a custom debugger that I created into IE. I got this working fine on XP, but couldn't get it working on Vista (full story here: http://damianblog.com/2008/09/09/tracejs-v2-rip/).
The call to GetProviderProcessData is failing on Vista. Anyone have any sugges... | It would help to know what the error result was.
Possible problems I can think of:
If your getting permission denied, your most likely missing some requried Privilege in your ACL. New ones are sometimes not doceumented well, check the latest Platform SDK headers to see if any new ones that still out. It may be that u... |
60,507 | 60,513 | C++ function pointers and classes | Say I have:
void Render(void(*Call)())
{
D3dDevice->BeginScene();
Call();
D3dDevice->EndScene();
D3dDevice->Present(0,0,0,0);
}
This is fine as long as the function I want to use to render is a function or a static member function:
Render(MainMenuRender);
Render(MainMenu::Render);
However, I really wa... | There are a lot of ways to skin this cat, including templates. My favorite is Boost.function as I've found it to be the most flexible in the long run. Also read up on Boost.bind for binding to member functions as well as many other tricks.
It would look like this:
#include <boost/bind.hpp>
#include <boost/function.hp... |
60,570 | 60,605 | Why should the "PIMPL" idiom be used? | Backgrounder:
The PIMPL Idiom (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.
This hides internal implementation details and data from the user of the library.
When implementing t... |
Because you want Purr() to be able to use private members of CatImpl. Cat::Purr() would not be allowed such an access without a friend declaration.
Because you then don't mix responsibilities: one class implements, one class forwards.
|
60,641 | 60,691 | How to replace WinAPI functions calls in the MS VC++ project with my own implementation (name and parameters set are the same)? | I need to replace all WinAPI calls of the
CreateFile,
ReadFile,
SetFilePointer,
CloseHandle
with my own implementation (which use low-level file reading via Bluetooth).
The code, where functions will be replaced, is Video File Player and it already works with the regular hdd files.
It is also needed, that Video P... | I suggest that you follow these steps:
Write a set of wrapper functions, e.g MyCreateFile, MyReadFile, etc, that initially just call the corresponding API and pass the same arguments along, unmodified.
Use your text editor to search for all calls to the original APIs, and replace these with calls to your new wrapper f... |
60,653 | 60,655 | Is global memory initialized in C++? | Is global memory initialized in C++? And if so, how?
(Second) clarification:
When a program starts up, what is in the memory space which will become global memory, prior to primitives being initialized? I'm trying to understand if it is zeroed out, or garbage for example.
The situation is: can a singleton reference be ... | Yes global primitives are initialized to NULL.
Example:
int x;
int main(int argc, char**argv)
{
assert(x == 0);
int y;
//assert(y == 0); <-- wrong can't assume this.
}
You cannot make any assumptions about classes, structs, arrays, blocks of memory on the heap...
It's safest just to always initialize everything... |
60,673 | 60,712 | Guidelines to improve your code | What guidelines do you follow to improve the general quality of your code? Many people have rules about how to write C++ code that (supposedly) make it harder to make mistakes. I've seen people insist that every if statement is followed by a brace block ({...}).
I'm interested in what guidelines other people follow, an... | A few of my personal favorites:
Strive to write code that is const correct. You will enlist the compiler to help weed out easy to fix but sometimes painful bugs. Your code will also tell a story of what you had in mind at the time you wrote it -- valuable for newcomers or maintainers once you're gone.
Get out of the ... |
60,751 | 60,790 | c++ Having multiple graphics options | Currently my app uses just Direct3D9 for graphics, however in the future I' m planning to extend this to D3D10 and possibly OpenGL. The question is how can I do this in a tidy way?
At present there are various Render methods in my code
void Render(boost::function<void()> &Call)
{
D3dDevice->BeginScene();
Call()... | Define an interface that is sufficient for your application's graphic output demands. Then implement this interface for every renderer you want to support.
class IRenderer {
public:
virtual ~IRenderer() {}
virtual void RenderModel(CModel* model) = 0;
virtual void DrawScreenQuad(int x1, int y1, int x2, int... |
60,830 | 60,850 | What is wrong with using inline functions? | While it would be very convenient to use inline functions at some situations,
Are there any drawbacks with inline functions?
Conclusion:
Apparently, There is nothing wrong with using inline functions.
But it is worth noting the following points!
Overuse of inlining can actually make programs slower. Depending on a fun... | It worth pointing out that the inline keyword is actually just a hint to the compiler. The compiler may ignore the inline and simply generate code for the function someplace.
The main drawback to inline functions is that it can increase the size of your executable (depending on the number of instantiations). This can ... |
60,871 | 61,061 | How to solve Memory Fragmentation | We've occasionally been getting problems whereby our long-running server processes (running on Windows Server 2003) have thrown an exception due to a memory allocation failure. Our suspicion is these allocations are failing due to memory fragmentation.
Therefore, we've been looking at some alternative memory allocatio... | First, I agree with the other posters who suggested a resource leak. You really want to rule that out first.
Hopefully, the heap manager you are currently using has a way to dump out the actual total free space available in the heap (across all free blocks) and also the total number of blocks that it is divided over. I... |
60,977 | 61,105 | Resetting detection of source file changes | Sometimes I have to work on code that moves the computer clock forward. In this case some .cpp or .h files get their latest modification date set to the future time.
Later on, when my clock is fixed, and I compile my sources, system rebuilds most of the project because some of the latest modification dates are in the f... | If this was my problem, I'd look for ways to avoid mucking with the system time. Isolating the code under unit tests, or a virtual machine, or something.
However, because I love PowerShell:
Get-ChildItem -r . |
? { $_.LastWriteTime -gt ([DateTime]::Now) } |
Set-ItemProperty -Name "LastWriteTime" -Value ([Dat... |
61,071 | 61,148 | How do I disassemble a VC++ application? | I believe the application has some parts that target .NET, and some that don't. I'm particularly interested in looking at the resource files, if there are any.
| To add to aku's excellent answer, for English speakers, IDA Pro is available at http://www.hex-rays.com/.
|
61,253 | 61,283 | How to be notified of file/directory change in C/C++, ideally using POSIX | The subject says it all - normally easy and cross platform way is to poll, intelligently. But every OS has some means to notify without polling. Is it possible in a reasonably cross platform way? (I only really care about Windows and Linux, but I use mac, so I thought posix may help?)
| Linux users can use inotify
inotify is a Linux kernel subsystem
that provides file system event
notification.
Some goodies for Windows fellows:
File Change Notification on MSDN
"When Folders Change" article
File System Notification on Change
|
61,278 | 61,279 | Quick and dirty way to profile your code | What method do you use when you want to get performance data about specific code paths?
| This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.
The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).
It's not thread safe, i... |
61,402 | 61,435 | C++ Exception code lookup | Knowing an exception code, is there a way to find out more about what the actual exception that was thrown means?
My exception in question:
0x64487347
Exception address: 0x1
The call stack shows no information.
I'm reviewing a .dmp of a crash and not actually debugging in Visual Studio.
| Because you're reviewing a crash dump I'll assume it came in from a customer and you cannot easily reproduce the fault with more instrumentation.
I don't have much help to offer save to note that the exception code 0x64487347 is ASCII "dShG", and developers often use the initials of the routine or fault condition when ... |
61,669 | 61,681 | Profiling in Visual Studio 2008 PRO | How do I use the profiler in Visual Studio 2008?
I know theres a build option in Config Properties -> Linker -> Advanced -> Profile (/PROFILE), however I can't find anything about actauly using it, only articles I was able to find appear to only apply to older versions of Visual Studio (eg most say to goto Build->Profi... | The profiler is only available in the Team System editions of Visual Studio 2008. The last version that I used that included a profiler was Visual C++ 6.0.
For Visual Studio 2005, you could try Compuware DevPartner Performance Analysis Community Edition.
|
61,680 | 61,684 | How to work around a very large 2d array in C++ | I need to create a 2D int array of size 800x800. But doing so creates a stack overflow (ha ha).
I'm new to C++, so should I do something like a vector of vectors? And just encapsulate the 2d array into a class?
Specifically, this array is my zbuffer in a graphics program. I need to store a z value for every pixel on... | You need about 2.5 megs, so just using the heap should be fine. You don't need a vector unless you need to resize it. See C++ FAQ Lite for an example of using a "2D" heap array.
int *array = new int[800*800];
(Don't forget to delete[] it when you're done.)
|
61,914 | 62,239 | VS 2005 Toolbox kind of control .NET | I'm looking for a control that the Visual Studio "Toolbox" menu uses. It can be docked and can retract (pin).
Would you know where I can find a control or COM I could use which would look like this?
| I would recommend the DockPanel Suite by Weifen Luo.
|
62,340 | 62,522 | Does pop_back() really invalidate *all* iterators on an std::vector? | std::vector<int> ints;
// ... fill ints with random values
for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); )
{
if(*it < 10)
{
*it = ints.back();
ints.pop_back();
continue;
}
it++;
}
This code is not working because when pop_back() is called, it is invalidat... | The call to pop_back() removes the last element in the vector and so the iterator to that element is invalidated. The pop_back() call does not invalidate iterators to items before the last element, only reallocation will do that. From Josuttis' "C++ Standard Library Reference":
Inserting or removing elements
inval... |
62,389 | 62,416 | What are the differences between Visual C++ 6.0 and Visual C++ 2008? | What are the advantages/disadvantages between MS VS C++ 6.0 and MSVS C++ 2008?
The main reason for asking such a question is that there are still many decent programmers that prefer using the older version instead of the newest version.
Is there any reason the might prefer the older over the new?
| Well, for one thing it may be because the executables built with MSVS 6 require only msvcrt.dll (C runtime) which is shipped with Windows now.
The MSVS 2008 executables need msvcrt9 shipped with them (or already installed).
Plus, you have a lot of OSS libraries already compiled for Windows 32 bit with the 6.0 C runtime... |
62,501 | 62,560 | Remote installing of windows service | I need to remotely install windows service on number of computers, so I use CreateService() and other service functions from winapi. I know admin password and user name for machines that I need access to. In order to gain access to remote machine I impersonate calling process with help of LogonUser like this:
//all... | You can do it , the account needs to exist on the remote machine and you need to use the machine name for the domain name in the LogonUser call.
|
62,512 | 62,532 | Three dimensional arrays of integers in C++ | I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using STL techniques such as vectors.
Essentially I want my integer array dimensions to look like:
[ x ][ y ][ z ]
x and y are in the range 20-6000
z i... | Have a look at the Boost multi-dimensional array library. Here's an example (adapted from the Boost documentation):
#include "boost/multi_array.hpp"
int main() {
// Create a 3D array that is 20 x 30 x 4
int x = 20;
int y = 30;
int z = 4;
typedef boost::multi_array<int, 3> array_type;
typedef array_type::i... |
62,623 | 63,667 | Does every Linux distro ship with gcc/g++ 4.* these days? | I'm considering dumping boost as a dependency... atm the only thing that I really need is shared_ptr<>, and I can get that from std::tr1, available in gcc suite 4.*
| AFAIK, all of the distros package V 4.+ nowadays.
|
62,810 | 132,553 | Exceptions not passed correctly thru RCF (using Boost.Serialization) | I use RCF with boost.serialization (why use RCF's copy when we already use the original?) It works OK, but when an exception is thrown in the server, it's not passed correctly to the client. Instead, I get an RCF::SerializationException quoting an archive_exception saying "class name too long". When I change the protoc... | Here's a patch given by Jarl at CodeProject:
In RcfServer.cpp, before the line where RcfServer::handleSession() is defined (around line 792), insert the following code:
void serialize(SerializationProtocolOut & out, const RemoteException & e)
{
serialize(out, std::auto_ptr<RemoteException>(new RemoteException(e))... |
62,832 | 62,843 | Reading data from a log file as a separate application is writing to it | I would like to monitor a log file that is being written to by an application. I want to process the file line by line as, or shortly after, it is written. I have not found a way of detecting that a file has been extended after reaching eof.
The code needs to work on Mac and PC, and can be in any language, though I am ... | In Perl, the File::Tail module does exactly what you need.
|
62,918 | 74,675 | Using GCC from within VS 2005(8) IDE | Is there a way to utilise the GCC compiler whilst still being able to develop via the Visual Studio IDE?
Our project is cross-platform, and I quite frequently get into trouble from my colleague because I'm checking in code that's not standards compliant (this can be attributed to the VS compiler!).
I'd still like to ... | What I am about to suggest would still require a makefile, so I am partially repeating the advice from an earlier reply. Or, as was also mentioned earlier, maybe you already have a makefile, in which case you will have even fewer steps in order to accomplish what I am about to describe.
Once you know your specific win... |
62,977 | 70,751 | How to write a C++ FireFox 3 plugin (not extension) on Windows? | Could someone write-up a step by step guide to developing a C++ based plugin for FireFox on Windows?
The links and examples on http://www.mozilla.org/projects/plugins/ are all old and inaccurate - the "NEW" link was added to the page in 2004.
The example could be anything, but I was thinking a plugin that lets JavaSc... | See also http://developer.mozilla.org/en/Plugins . And yes, NPAPI plugins should work in Google Chrome as well.
[edit 2015: Chrome removes support for NPAPI soon http://blog.chromium.org/2014/11/the-final-countdown-for-npapi.html ]
|
63,147 | 63,485 | User Interface Controls for Win32 | I see many user interface control libraries for .NET, but where can I get similar stuff for win32 using simply C/C++?
Things like prettier buttons, dials, listviews, graphs, etc.
Seems every Win32 programmers' right of passage is to end up writing his own collection. :/
No MFC controls please. I only do pure C/C++. ... | I've used Trolltech's Qt framework in the past and had great success with it:
In addition, it's also cross-platform, so in theory you can target Win, Mac, & Linux (provided you don't do anything platform-specific in the rest of your code, of course ;) )
Edit: I notice that you're targeting Windows Mobile; that definite... |
63,429 | 66,514 | How do I display dynamic text at the mouse cursor via C++/MFC in a Win32 application | I would like to be able to display some dynamic text at the mouse
cursor location in a win32 app, for instance to give an X,Y coordinate that
would move with the cursor as though attached. I can do this during a
mousemove event using a TextOut() call for the window at the mouse
coordinates and invalidate a rectange... | You may want to consider a small transparent window that you move to follow the mouse. In particular, since Windows 2000, Layered windows seem to be the weapon of choice (confession: no personal experience there).
|
63,494 | 63,551 | Does anyone use template metaprogramming in real life? | I discovered template metaprogramming more than 5 years ago and got a huge kick out of reading Modern C++ Design but I never found an opertunity to use it in real life.
Have you ever used this technique in real code?
Contributors to Boost need not apply ;o)
| I once used template metaprogramming in C++ to implement a technique called "symbolic perturbation" for dealing with degenerate input in geometric algorithms. By representing arithmetic expressions as nested templates (i.e. basically by writing out the parse trees by hand) I was able to hand off all the expression ana... |
63,784 | 64,682 | Implementing scripts in c++ app | I want to move various parts of my app into simple scripts, to allow people that do not have a strong knowledge of c++ to be able to edit and implement various features.
Because it's a real time app, I need to have some kind of multitasking for these scripts. Ideally I want it so that the c++ app calls a script functio... | You can use either Lua or Python. Lua is more "lightweight" than python. It's got a smaller memory footprint than python does and in our experience was easier to integrate (people's mileage on this point might vary). It can support a bunch of scripts running simultaneously. Lua, at least, supports stopping/starting... |
64,498 | 67,478 | C++ method expansion | Can you specialize a template method within a template class without specializing the class template parameter?
Please note that the specialization is on the value of the template parameter, not its type.
This seems to compile under Visual Studio 2008 SP1 complier, but not GCC 4.2.4.
#include <iostream>
using namespace... | Here is another workaround, also useful when you need to partialy specialize a function (which is not allowed). Create a template functor class (ie. class whose sole purpose is to execute a single member function, usually named operator() ), specialize it and then call from within your template function.
I think I lear... |
64,582 | 64,622 | C++/Java Performance for Neural Networks? | I was discussing neural networks (NN) with a friend over lunch the other day and he claimed the the performance of a NN written in Java would be similar to one written in C++. I know that with 'just in time' compiler techniques Java can do very well, but somehow I just don't buy it. Does anyone have any experience th... | The Hotspot JIT can now produce code faster than C++. The reason is run-time empirical optimization.
For example, it can see that a certain loop takes the "false" branch 99% of the time and reorder the machine code instructions accordingly.
There's lots of articles about this. If you want all the details, read Sun's ... |
64,645 | 64,974 | Define an interface in C++ that needs to be implemented in C# and C++ | I have an interface that I have defined in C++ which now needs to be implemented in C#. What is the best way to go about this? I don't want to use COM at all in my interface definition. The way I have solved this right now is to to have two interface definitions, one in C++ and one in C#. I then expose the C# interface... | If you are willing to use C++/CLI for your managed code instead of C#, then you can just consume the native C++ interface definition directly via the header file. How easy this will be will depend on exactly what is in your interface - simplest case is something that you could use from C.
Take a look at Marcus Heege's ... |
64,851 | 64,911 | Macro to test whether an integer type is signed or unsigned | How would you write (in C/C++) a macro which tests if an integer type (given as a parameter) is signed or unsigned?
#define is_this_type_signed (my_type) ...
| If what you want is a simple macro, this should do the trick:
#define is_type_signed(my_type) (((my_type)-1) < 0)
|
64,958 | 65,424 | What is the best way of preventing memory leaks in a yacc-based parser? | Yacc does not permit objects to be passed around. Because the %union can only contain POD types, complex objects must be new'd and passed around by pointer. If a syntax error occurs, the yacc parser just stops running, and references to all of those created objects are lost.
The only solution I've come up with is that ... | I love Yacc, but the discriminating union stack does present a challenge.
I don't know whether you are using C or C++. I've modified Yacc to generate C++ for my own purposes, but this solution can be adapted to C.
My preferred solution is to pass an interface to the owner down the parse tree, rather than constructed ob... |
65,037 | 65,103 | is there a way to write macros with a variable argument list in visual C++? | As far as I know, in gcc you can write something like:
#define DBGPRINT(fmt...) printf(fmt);
Is there a way to do that in VC++?
| Yes but only since VC++ 2005. The syntax for your example would be:
#define DBGPRINT(fmt, ...) printf(fmt, __VA_ARGS__)
A full reference is here.
|
65,074 | 65,923 | C++ Unit Testing Legacy Code: How to handle #include? | I've just started writing unit tests for a legacy code module with large physical dependencies using the #include directive. I've been dealing with them a few ways that felt overly tedious (providing empty headers to break long #include dependency lists, and using #define to prevent classes from being compiled) and was... | The depression in the responses is overwhelming... But don't fear, we've got the holy book to exorcise the demons of legacy C++ code. Seriously just buy the book if you are in line for more than a week of jousting with legacy C++ code.
Turn to page 127: The case of the horrible include dependencies. (Now I am not even ... |
65,524 | 65,589 | Generating a Unique ID in c++ | What is the best way to generate a Unique ID from two (or more) short ints in C++? I am trying to uniquely identify vertices in a graph. The vertices contain two to four short ints as data, and ideally the ID would be some kind of a hash of them. Prefer portability and uniqueness over speed or ease.
There are a lo... | A simple solution is to use a 64 bit integer where the lower 16 bits is the first vertex coordinate, next 16 bits is the second, and so on. This will be unique for all your vertices, though not very compact.
So here's some half-assed code to do this. Hopefully I got the casts right.
uint64_t generateId( uint16_t v1, ui... |
65,724 | 66,036 | Uninitialized memory blocks in VC++ | As everyone knows, the Visual C++ runtime marks uninitialized or just freed memory blocks with special non-zero markers. Is there any way to disable this behavior entirely without manually setting all uninitialized memory to zeros? It's causing havoc with my valid not null checks, since 0xFEEEFEEE != 0.
Hrm, perhaps I ... | It is not the responsibility of delete to reset all the pointers to the object to NULL.
Also you shouldn't change the default memory fill for the windows DEBUG runtime and you should use some thing like boost::shared_ptr<> for pointers any way.
That said, if you really want to shoot your self in the foot you can.
You c... |
66,166 | 66,239 | C++ web service framework | We are looking for a C++ Soap web services framework that support RPC, preferably open source.
Any recommendations?
| WSO2 Web Services Framework for C++ (WSO2 WSF/C++), a binding of WSO2 WSF/C into C++ is a C++ extension for consuming Web Services in C++.
http://wso2.org/projects/wsf/cpp
Apache Axis is an open source, XML based Web service framework. It consists of a Java and a C++ implementation of the SOAP server, and various utili... |
67,174 | 78,553 | Find memory leaks caused by smart pointers | Does anybody know a "technique" to discover memory leaks caused by smart pointers? I am currently working on a large project written in C++ that heavily uses smart pointers with reference counting. Obviously we have some memory leaks caused by smart pointers, that are still referenced somewhere in the code, so that the... | Note that one source of leaks with reference-counting smart pointers are pointers with circular dependancies. For example, A have a smart pointer to B, and B have a smart pointer to A. Neither A nor B will be destroyed. You will have to find, and then break the dependancies.
If possible, use boost smart pointers, and u... |
67,273 | 67,307 | How do you iterate through every file/directory recursively in standard C++? | How do you iterate through every file/directory recursively in standard C++?
| In standard C++, technically there is no way to do this since standard C++ has no conception of directories. If you want to expand your net a little bit, you might like to look at using Boost.FileSystem. This has been accepted for inclusion in TR2, so this gives you the best chance of keeping your implementation as clo... |
67,426 | 67,701 | Dynamically sorted STL containers | I'm fairly new to the STL, so I was wondering whether there are any dynamically sortable containers? At the moment my current thinking is to use a vector in conjunction with the various sort algorithms, but I'm not sure whether there's a more appropriate selection given the (presumably) linear complexity of inserting ... | If you know you're going to be sorting on a single value ascending and descending, then set is your friend. Use a reverse iterator when you want to "sort" in the opposite direction.
If your objects are complex and you're going to be sorting in many different ways based on the member fields within the objects, then you... |
67,554 | 67,577 | What's the best free C++ profiler for Windows? | I'm looking for a profiler in order to find the bottleneck in my C++ code. I'd like to find a free, non-intrusive, and good profiling tool. I'm a game developer, and I use PIX for Xbox 360 and found it very good, but it's not free. I know the Intel VTune, but it's not free either.
| CodeXL has now superseded the End Of Line'd AMD Code Analyst and both are free, but not as advanced as VTune.
There's also Sleepy, which is very simple, but does the job in many cases.
Note: All three of the tools above are unmaintained since several years.
|
67,894 | 67,930 | Why do we need extern "C"{ #include <foo.h> } in C++? | Why do we need to use:
extern "C" {
#include <foo.h>
}
Specifically:
When should we use it?
What is happening at the compiler/linker level that requires us to use it?
How in terms of compilation/linking does this solve the problems which require us to use it?
| C and C++ are superficially similar, but each compiles into a very different set of code. When you include a header file with a C++ compiler, the compiler is expecting C++ code. If, however, it is a C header, then the compiler expects the data contained in the header file to be compiled to a certain format—the C++ 'ABI... |
68,084 | 68,130 | Switching from C# to C++. Any must-reads? | I'm trying to find a least-resistance path from C# to C++, and while I feel I handle C# pretty well after two solid years, I'm still not sure I've gotten the "groove" of C++, despite numerous attempts.
Are there any particular books or websites that might be suitable for this transition?
| I recommend The C++ Programming language by Bjarne Stroustrup. It's not a suitable book for new programmers, but I found it quite effective as programmer who was experienced in other languages and didn't want to waste too much time with learning how while loops work. It's a dense but quite comprehensive book.
|
68,144 | 999,308 | Using XmlRpc in C++ and Windows | I need to use XmlRpc in C++ on a Windows platform. Despite the fact that my friends assure me that XmlRpc is a "widely available standard technology", there are not many libraries available for it. In fact I only found one library to do this on Windows, (plus another one that claims "you'll have to do a lot of work t... | I've written my own C++ library. It's available at sourceforge:
xmlrpcc4win
The reason I wrote it rather than using Chris Morley's was that:
The Windows "wininet.lib" library gives you all the functionality for handling Http requests, so I'd rather use that. As a result, I only needed 1700 LOC.
"wininet.lib", and th... |
69,112 | 69,169 | What is a symbol table? | Can someone describe what a symbol table is within the context of C and C++?
| There are two common and related meaning of symbol tables here.
First, there's the symbol table in your object files. Usually, a C or C++ compiler compiles a single source file into an object file with a .obj or .o extension. This contains a collection of executable code and data that the linker can process into a wo... |
69,115 | 69,218 | char[] to hex string exercise | Below is my current char* to hex string function. I wrote it as an exercise in bit manipulation. It takes ~7ms on a AMD Athlon MP 2800+ to hexify a 10 million byte array. Is there any trick or other way that I am missing?
How can I make this faster?
Compiled with -O3 in g++
static const char _hex2asciiU_value[256][2] =... | At the cost of more memory you can create a full 256-entry table of the hex codes:
static const char _hex2asciiU_value[256][2] =
{ {'0','0'}, {'0','1'}, /* ..., */ {'F','E'},{'F','F'} };
Then direct index into the table, no bit fiddling required.
const char *pHexVal = pHex[*pChar];
pszHex[0] = pHexVal[0];
pszHex[1... |
69,250 | 69,252 | Why does a C/C++ program often have optimization turned off in debug mode? | In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.
Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.
In "release" mode, you usually have all sorts of opt... | Without any optimization on, the flow through your code is linear. If you are on line 5 and single step, you step to line 6. With optimization on, you can get instruction re-ordering, loop unrolling and all sorts of optimizations.
For example:
void foo() {
1: int i;
2: for(i = 0; i < 2; )
3: i++;
4: return;
... |
69,539 | 12,116,668 | Have you used any of the C++ interpreters (not compilers)? | I am curious if anyone have used UnderC, Cint, Cling, Ch, or any other C++ interpreter and could share their experience.
| There is cling Cern's project of C++ interpreter based on clang - it's new approach based on 20 years of experience in ROOT cint and it's quite stable and recommended by Cern guys.
Here is nice Google Talk: Introducing cling, a C++ Interpreter Based on clang/LLVM.
|
69,738 | 69,765 | C++: how to get fprintf results as a std::string w/o sprintf | I am working with an open-source UNIX tool that is implemented in C++, and I need to change some code to get it to do what I want. I would like to make the smallest possible change in hopes of getting my patch accepted upstream. Solutions that are implementable in standard C++ and do not create more external dependenci... | I am using #3: the boost string format library - but I have to admit that I've never had any problem with the differences in format specifications.
Works like a charm for me - and the external dependencies could be worse (a very stable library)
Edited: adding an example how to use boost::format instead of printf:
sprin... |
70,013 | 70,630 | How to Detect if I'm Compiling Code with a particular Visual Studio version? | Is there any way to know if I'm compiling under a specific Microsoft Visual Studio version?
| _MSC_VER and possibly _MSC_FULL_VER is what you need. You can also examine visualc.hpp in any recent boost install for some usage examples.
Some values for the more recent versions of the compiler are:
MSVC++ 14.24 _MSC_VER == 1924 (Visual Studio 2019 version 16.4)
MSVC++ 14.23 _MSC_VER == 1923 (Visual Studio 2019 vers... |
70,643 | 72,091 | Setting Excel Number Format via xlcFormatNumber in an xll | I'm trying to set the number format of a cell but the call to xlcFormatNumber fails leaving the cell number format as "General". I can successfully set the value of the cell using xlSet.
XLOPER xRet;
XLOPER xRef;
//try to set the format of cell A1
xRef.xltype = xltypeSRef;
xRef.val.sref.count = 1;
xRef.val.sref.ref.r... | Thanks to Simon Murphy for the answer:-
Smurf on Spreadsheets
//It is necessary to select the cell to apply the formatting to
Excel4 (xlcSelect, 0, 1, &xRef);
//Then we apply the formatting
Excel4( xlcFormatNumber, 0, 1, &xFormat);
|
70,880 | 70,905 | deleting a buffer through a different type of pointer? | Say I have the following C++:
char *p = new char[cb];
SOME_STRUCT *pSS = (SOME_STRUCT *) p;
delete pSS;
Is this safe according to the C++ standard? Do I need to cast back to a char* and then use delete[]? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed t... | It's not guaranteed to be safe. Here's a relevant link in the C++ FAQ lite:
[16.13] Can I drop the [] when deleting array of some built-in type (char, int, etc.)?
http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13
|
71,108 | 71,298 | To what use is multiple indirection in C++? | Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in Foo **) in C++?
| Most common usage as @aku pointed out is to allow a change to a pointer parameter to be visible after the function returns.
#include <iostream>
using namespace std;
struct Foo {
int a;
};
void CreateFoo(Foo** p) {
*p = new Foo();
(*p)->a = 12;
}
int main(int argc, char* argv[])
{
Foo* p = NULL;
... |
71,416 | 72,599 | Forward declaring an enum in C++ | I'm trying to do something like the following:
enum E;
void Foo(E e);
enum E {A, B, C};
which the compiler rejects. I've had a quick look on Google and the consensus seems to be "you can't do it", but I can't understand why. Can anyone explain?
Clarification 2: I'm doing this as I have private methods in a class t... | The reason the enum can't be forward declared is that, without knowing the values, the compiler can't know the storage required for the enum variable. C++ compilers are allowed to specify the actual storage space based on the size necessary to contain all the values specified. If all that is visible is the forward de... |
71,475 | 1,198,602 | Virtual Files are opened from Temporary Internet Files | I have created a namespace extension that is rooted under Desktop. The main purpose of the extension is to provide a virtual list of ZIP files that represent a list of configurable directories. When the user clicks one of the those items the contents of the related directory are zipped in place and the resulting ZIP fi... | The problem was fixed by masking SFGAO_FILESYSTEM in the attributes returned by implementation of interface method IShellFolder::GetAttributesOf.
|
72,010 | 72,075 | C++ overload resolution | Given the following example, why do I have to explicitly use the statement b->A::DoSomething() rather than just b->DoSomething()?
Shouldn't the compiler's overload resolution figure out which method I'm talking about?
I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.)
class A
{
public:
... | The two “overloads” aren't in the same scope. By default, the compiler only considers the smallest possible name scope until it finds a name match. Argument matching is done afterwards. In your case this means that the compiler sees B::DoSomething. It then tries to match the argument list, which fails.
One solution wou... |
72,128 | 72,238 | Fastest way to find if a 3D coordinate is already used | Using C++ (and Qt), I need to process a big amount of 3D coordinates.
Specifically, when I receive a 3D coordinate (made of 3 doubles), I need to check in a list if this coordinate has already been processed.
If not, then I process it and add it to the list (or container).
The amount of coordinates can become very big,... | Probably the simplest way to speed up such processing is to store the already-processed points in Octree. Checking for duplication will become close to logarithmic.
Also, make sure you tolerate round-off errors by checking the distance between the points, not the equality of the coordinates.
|
72,271 | 72,409 | "No newline at end of file" compiler warning | What is the reason for the following warning in some C++ compilers?
No newline at end of file
Why should I have an empty line at the end of a source/header file?
| Think of some of the problems that can occur if there is no newline. According to the ANSI standard the #include of a file at the beginning inserts the file exactly as it is to the front of the file and does not insert the new line after the #include <foo.h> after the contents of the file. So if you include a file with... |
72,552 | 72,617 | Why does volatile exist? | What does the volatile keyword do? In C++ what problem does it solve?
In my case, I have never knowingly needed it.
| volatile is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to.
I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did th... |
72,616 | 72,786 | Embed data in a C++ program | I've got a C++ program that uses SQLite. I want to store the SQL queries in a separate file -- a plain-text file, not a source code file -- but embed that file in the executable file like a resource.
(This has to run on Linux, so I can't store it as an actual resource as far as I know, though that would be perfect if i... | You can use objcopy to bind the contents of the file to a symbol your program can use. See, for instance, here for more information.
|
72,769 | 73,075 | Static libraries with managed code issue | Problem (simplified to make things clearer):
1. there is one statically-linked static.lib that has a function that increments:
extern int CallCount = 0;
int TheFunction()
{
void *p = &CallCount;
printf("Function called");
return CallCount++;
}
2. static.lib is linked into a ... | My hunch was that, as you suspected, unmanaged DLLs are loaded in the context of the process and not in the context of the AppDomain, so any static data in unmanaged code is shared among AppDomains.
This link shows someone with the same problem you have, still not 100% verification of this, but probably this is the cas... |
72,789 | 72,877 | Change app icon in Visual Studio 2005? | I'd like to use a different icon for the demo version of my game, and I'm building the demo with a different build config than I do for the full verison, using a preprocessor define to lockout some content, use different graphics, etc. Is there a way that I can make Visual Studio use a different icon for the app Icon ... | According to this page you may use preprocessor directives in your *.rc file. You should write something like this
#ifdef _DEMO_VERSION_
IDR_MAINFRAME ICON "demo.ico"
#else
IDR_MAINFRAME ICON "full.ico"
#endif
|
73,117 | 73,537 | Making a game in C++ using parallel processing | I wanted to "emulate" a popular flash game, Chrontron, in C++ and needed some help getting started. (NOTE: Not for release, just practicing for myself)
Basics:
Player has a time machine. On each iteration of using the time machine, a parallel state
is created, co-existing with a previous state. One of the states must ... | What you should do is first to read and understand the "fixed time-step" game loop (Here's a good explanation: http://www.gaffer.org/game-physics/fix-your-timestep).
Then what you do is to keep a list of list of pairs of frame counter and action. STL example:
std::list<std::list<std::pair<unsigned long, Action> > > sta... |
73,134 | 73,163 | Will this C++ code cause a memory leak (casting array new) | I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array new thus:
STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize];
Later on however the memory is freed usin... | Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example.
More importantly if STRUCT where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the correspo... |
73,686 | 73,711 | cout prints "-0" instead of "0" | #include <iostream>
using namespace std;
int main()
{
double u = 0;
double w = -u;
cout << w << endl;
return 0;
}
Why does this great piece of code output -0 and not 0, as one would expect?
| The IEEE 754 standard for floating-point numbers has the sign bit separate from the mantissa, which allows for zero to be negative. Wikipedia should be able to help explain this.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.