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 |
|---|---|---|---|---|
336,759 | 336,918 | How loader Maps DLL in to Process Address Space | I am curious to know How the Loader Maps DLL in to Process Address Space. How loader does that magic. Example is highly appreciated.
Thanks in advance.
| What level of detail are you looking for? On the basic level, all dynamic linkers work pretty much the same way:
Dynamic libraries are compiled to relocatable code (using relative jumps instead of absolute, for example).
The linker finds an appropriately-sized empty space in the memory map of the application, and read... |
336,771 | 917,695 | How can I run code on Windows Mobile while being suspended? | I'd like to run some C++ code while the Windows Mobile PocketPC is (or seems) being suspended. An example what I mean is the HTC Home plugin that shows (among others) a tab where the HTC Audio Manager can be used to play back mp3 files. When I press the on/off button, the display goes black, but the audio keeps playing... | I found sourcecode on the xda-developers forum that explains what to do, and it works as thought. The main points are:
Set the device to send a notification when going into "unattended" mode. This is done with PowerPolicyNotify(PPN_UNATTENDEDMODE, TRUE)
For every device that you need during unattended mode, call SetPo... |
336,801 | 338,456 | Memory management practices and tools for Symbian C++ | I have pretty much finished my first working Symbian application, but in my hastened learning have paid little attention to memory management and pushing to and cleaning up the stack?
Could somebody please point me in the direction of some of the best practises to use here, and maybe some of the best leak detection/mem... | I have in the past used HookLogger from Symbian to trace and investigate memory leaks. It is not the best, but it sure does help. Also, the heap markers raise ALLOC panics in case of memory leaks whenever your exit your application. The information those panics provide is barely helpful, but it is good indication that ... |
337,620 | 337,652 | Matrix Template Library matrix inversion | I'm trying to inverse a matrix with version Boost boost_1_37_0 and MTL mtl4-alpha-1-r6418. I can't seem to locate the matrix inversion code. I've googled for examples and they seem to reference lu.h that seems to be missing in the above release(s). Any hints?
@Matt suggested copying lu.h, but that seems to be from MTL2... | Looks like you use lu_factor, and then lu_inverse. I don't remember what you have to do with the pivots, though. From the documentation.
And yeah, like you said, it looks like their documentations says you need lu.h, somehow:
How do I invert a matrix?
The first question you should ask
yourself is whether you want ... |
338,400 | 338,418 | Warnings using format strings with sprintf() in C++ | Compiling this lines
long int sz;
char tmpret[128];
//take substring of c, translate in c string, convert to int,
//and multiply with 1024
sz=atoi(c.substr(0,pos).c_str())*1024;
snprintf(tmpret,128,"%l",sz);
I read two warning on snprintf line:
warning: conversion lacks type at end of form... | Your format lacks type, because l is a "sizeof" modifier. Should be %ld
|
338,427 | 338,447 | How to find out if a pointer is on the stack on PC/Visual C++ | [This is for PC/Visual C++ specifically (although any other answers would be quite illuminating :))]
How can you tell if a pointer comes from an object in the stack? For example:
int g_n = 0;
void F()
{
int *pA = &s_n;
ASSERT_IS_POINTER_ON_STACK(pA);
int i = 0;
int *pB = &i;
ASSERT_IS_POINTER_ON_ST... | Technically speaking, in portable C you can't know. A stack for arguments is a hardware detail that is honored on many but not all compilers. Some compilers will use registers for arguments when they can (ie, fastcall).
If you are working specifically on windows NT, you want to grab the Thread Execution Block from ca... |
338,467 | 338,507 | Is there a tutorial on C++ programming in Visual Studio 2008? | Can anyone link me to a decent c++ tutorial that's actually currently in date? Almost everything I find applies to 2005 and the code examples are riddled with errors which won't run in my 2008 version of the visual compiler.
| The book Accelerated C++ is a good start to learn C++.
|
338,509 | 338,553 | When will C++0x be released? |
Possible Duplicates:
C++0X when?
When will C++0x be finished?
When will C++0x be released? Anyone here know anything?
| Edit: We have a new standard now : http://herbsutter.com/2011/08/12/we-have-an-international-standard-c0x-is-unanimously-approved/
Edit: The FDIS is done, so officially it should be released in few months. See : http://herbsutter.com/2011/03/25/we-have-fdis-trip-report-march-2011-c-standards-meeting/
Herb Sutter is ... |
338,809 | 338,819 | How to insert a null value with Qt? | Tip me plase, how to insert a null value into table using Trolltech Qt 4.x SQL classes? QSqlQuery, I guess, or something else from QtNetwork.
As analog of it, in .NET there is the System.DbNull class, which represents sql NULL.
And what type should I use for some object's property, that can hold both null-value and QSt... | From QSqlQuery::addBindValue documentation:
To bind a NULL value, use a null
QVariant; for example, use
QVariant(QVariant::String) if you are
binding a string.
|
339,150 | 339,161 | Extracting individual digits from a float | I have been banging my head on this one all day. The C++ project I am currently working on has a requirement to display an editable value. The currently selected digit displays the incremented value above and decremented value below for said digit. It is useful to be able to reference the editable value as both a nu... | Internal representation of the float point numbers aren't like was you see. You can only cast to a stirng.
To cast, do this:
char string[99];
sprintf(string,"%f",floatValue);
Or see this : http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1
The wikipedia article can explain more on the representa... |
339,971 | 339,988 | How to include sub-directories in Visual Studio? | I have to include many header files, which are in different sub-directories. Is there a way in Visual Studio (I am using 2005 edition) to set one include path that Visual Studio will search also the sub-directories for header files?
| Setting the folder search paths in the Visual Studio settings to fix an include issue is generally not really a good idea from a design point of view. Your code will be less portable to different machines with different directory lay-outs.
My suggestion would be to settle on an organisation of your code so that the re... |
340,003 | 340,117 | What is the C++ equivalent to GetObject in JavaScript and VBScript? | What is the C++ equivalent to GetObject in JavaScript and VBScript?
The closest match I found to my question is:
http://codewiz51.blogspot.com/2008/06/vb-script-getobject-c-api-cogetobject.html
However the sample use an unexisting interface and asking for the IUnknown returns null. Did someone have an example that work... | I figured out the issue. The object I wanted to access was
winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv
I mistakenly took \\ for an escapement. In C++ the correct query is :
::CoGetObject(L"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\default:StdRegProv", NULL, IID_IUnknown, (void... |
340,071 | 340,103 | Looking for OSS for OSI Layer 2 Traffic Generator | I am looking for layer 2 traffic generator [open source].
Some OSS using winpcap or libpcap.
Thanks a lot.
|
Scapy
bittwist
any from perl's Net::Pcap, python's or ruby's pcap interface...
|
340,122 | 340,291 | ::FindWindow fails from Service application | Windows API ::FindWindow function fails when called from Service application. GetLastError() also returns 0 (success?). Is this some privilege\access right problem? Do you think it's design problem and I should use another IPC method?
| leppie's right, Windows services are usually denied in interaction with desktop. You can bypass that in XP and earlier versions but won't be able to do in Vista and above. You'd better delegate desktop and user interactions to a GUI application. See this document for details.
|
340,185 | 389,332 | using GDAL/OGR api to read vector data (shapefile)--How? | I am working on an application that involves some gis stuff. There would be some .shp files to be read and plotted onto an opengl screen. The current opengl screen is using the orthographic projection as set from glOrtho() and is already displaying a map using coordinates from a simple text file..
Now the map to be pl... |
Shapefile rendering is quite straight forward in OpenGL. You may require "shapelib",a free shapefile parsing library in C(Google it). Use GL_POINTS for point shapefile,
GL_LINES for line shapefile and GL_LINE_LOOP for polygon shapefile. Set your bounding box coords to the Ortho.
What you read from the .prj file is pro... |
340,282 | 340,305 | i = ++i + ++i; in C++ | Can someone explain to me why this code prints 14? I was just asked by another student and couldn't figure it out.
int i = 5;
i = ++i + ++i;
cout<<i;
| The order of side effects is undefined in C++. Additionally, modifying a variable twice in a single expression has no defined behavior (See the C++ standard, §5.0.4, physical page 87 / logical page 73).
Solution: Don't use side effects in complex expression, don't use more than one in simple ones. And it does not hurt ... |
340,345 | 342,657 | Web service can't open named pipe - access denied | I've got a C++ service which provides a named pipe to clients with a NULL SECURITY_ATTRIBUTES as follows:
hPipe = CreateNamedPipe( lpszPipename, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES, BUFS... | The default ACL for named pipes (what you get with a null security descriptor) grants write access only to LocalSystem, Administrators, and the pipe's owner/creator. Unless your web application is running under one of those accounts (which by default it would not be) you won't be able to get write access. (I'm assuming... |
340,413 | 341,330 | How do C/C++ compilers handle type casting between types with different value ranges? | How do type casting happen without loss of data inside the compiler?
For example:
int i = 10;
UINT k = (UINT) k;
float fl = 10.123;
UINT ufl = (UINT) fl; // data loss here?
char *p = "Stackoverflow Rocks";
unsigned char *up = (unsigned char *) p;
How does the compiler handle this type of typecasting? A low-le... | Well, first note that a cast is an explicit request to convert a value of one type to a value of another type. A cast will also always produce a new object, which is a temporary returned by the cast operator. Casting to a reference type, however, will not create a new object. The object referenced by the value is reint... |
340,437 | 340,446 | Missing 'virtual' qualifier in function declarations | Whilst trawling through some old code I came across something similar to the following:
class Base
{
public:
virtual int Func();
...
};
class Derived : public Base
{
public:
int Func(); // Missing 'virtual' qualifier
...
};
The code compiles fine (MS VS2008) with no warnings (level 4) and it works as ... | The virtual will be carried down to all overriding functions in derived classes. The only real benefit to adding the keyword is to signify your intent a casual observer of the Derived class definition will immediately know that Func is virtual.
Even classes that extend Derived will have virtual Func methods.
Reference:... |
340,687 | 341,989 | Unable to load C++ DLL in C# application in Vista x64 | I have a DLL written in C++ that needs to be used by an application in C#. It works great under Vista x86, but under x64 it fails to load. So I build an x64 version of the DLL and I detect whether the OS is x86 or x64 and use the appropriate interop call to the appropriate DLL. This works fine under Vista x86, but unde... | The redist for VC90 for x64 will need to be installed on the client machine. As far as the manifest goes, I think you can alter it to remove the processorArchitecture tag. Either that or have it say "any".
|
340,943 | 340,990 | C++ Multi-dimensional Arrays on the Heap | How would I go about dynamically allocating a multi-dimensional array?
| If you know the size of nested dimensions already, you can also literally allocate a multi dimensional array using new:
typedef int dimensions[3][4];
dimensions * dim = new dimensions[10];
dim[/* from 0 to 9 */][/* from 0 to 2 */][/* from 0 to 3 */] = 42;
delete [] dim;
instead of 10, a runtime determined value can b... |
341,117 | 1,754,941 | Display Outlook icon in notification area for messages, not in inbox | I have rules set to move some email messages into different folders. I would like this to still show the envelope in the notification area but there is no option in the rules wizard to do this. It looks like I would either have to have the rule "run a script" or "perform a custom action" allowing either vba or c/c++ re... | You can also achieve it not by using a rule, but doing the rule-like action in code. For example:
Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
Dim mai As Object
Dim strEntryId
For Each strEntryId In Split(EntryIDCollection, ",")
Set mai = Application.Session.GetItemFromID(str... |
341,130 | 341,170 | Hide Comments in Code in Unix Environment | I work in a Unix environment with the typical Unix tools (emacs, vim, gvim, sunstudio, etc)
My project has huge gross boilerplate comments on every method. It makes the files thousands of lines long, with a couple hundred lines of actual code. I may be exagerrating a bit but you get the idea. I am looking for a way whe... | It all depends on which editor you use. In vim, you can enable folding with :
set foldenable
Then, you'll be able to use different of folding methods, for mainstream languages, you can set :
set foldmethod=syntax
which will enable syntax folding.
There are half a dozen folding methods, I think the best would be to re... |
341,192 | 341,833 | Segmentation fault using SDL with C++, trying to Blit images | OK - I have an interesting one here. I'm working on a tetris clone (basically to "level-up" my skills). I was trying to refactor my code to get it abstracted the way I wanted it. While it was working just fine before, now I get a segmentation fault before any images can be blitted. I've tried debugging it to no ava... | Look at line 15 to 18 of Surface.cpp:
surface = SDL_DisplayFormatAlpha( tempSurface );
surface = tempSurface;
}
SDL_FreeSurface( tempSurface );
I assume it segfaults because when you use this surface later, you are actually operating on tempSurface because of this line:
surface = tempSurface;
and not the surf... |
341,345 | 342,305 | Viewing language (C/C++) reference/documentation in CodeBlocks | My first question on StackOverflow...
Does anybody know a way of viewing the reference/documentation manual of a language through CodeBlocks? Specifically for C/C++.
Example:
Say I want to look up the reference for strncpy(). In a very old Borland system (which we use at school) I would write the word and middle-click ... | Yes, it is possible. I'm not sure about the help files themselves though.
The procedure seems to be documented here.
from the forums.
Re: F1 - help and function reference
« Reply #1 on: September 15, 2008, 02:07:59 pm »
if you have the help plugin installed, you can set help files through "Settings->Environment" and c... |
341,462 | 343,590 | What's the difference between BSTR and _bstr_t? | Can anyone explain the difference between the types mentioned above and some sample usage to clearly explain the difference between the two?
Any help would be highly appreciated!
Note: this question is a spin-off from this other question
| BSTR is the string data type used with COM.
_bstr_t is a wrapper class that works like a smart pointer, so it will free the allocated memory when the variable is destroyed or goes out of scope.
_bstr_t also has reference counting, which increases every time you pass the _bstr_t variable by value (avoiding unnecessary c... |
341,536 | 341,563 | Is it possible to build a DLL in C++ that has no dependencies? | I would like to deploy a very simple DLL with my C# application, but any DLL that I build in Visual Studio 2008 seems to have a dependency on "Microsoft.VC90.CRT". Is it possible to build a DLL using VS2008 without this dependency? How can I tell what is causing the dependency?
| I'm not sure about the latest VC++ versions, but previously you could tell the linker to link with a static version of the MSVCRT runtime library instead of the dynamic (DLL) version. It's possible this option still exists.
|
341,550 | 341,627 | On Windows, when should you use the "\\\\?\\" filename prefix? | I came across a c library for opening files given a Unicode filename. Before opening the file, it first converts the filename to a path by prepending "\\?\". Is there any reason to do this other than to increase the maximum number of characters allowed in the path, per this msdn article?
It looks like these "\\?\" pat... | Yes, it's just for that purpose. However, you will likely see compatibility problems if you decide to creating paths over MAX_PATH length. For example, the explorer shell and the command prompt (at least on XP, I don't know about Vista) can't handle paths over that length and will return errors.
|
341,594 | 341,613 | How do I read system information in C++? | I'm trying to get information like OS version, hard disk space, disk space available, and installed RAM on a Linux system in C++. I know I can use system() to run different Linux commands and capture their output (which is what I'm currently doing) but I was wondering if there's a better way? Is there something in th... | If you are using *nix commands via system.
Then do man scroll to the bottom of the man page and it will usually show you what relevant C system calls are related.
Example: man uname:
SEE ALSO
uname(2), getdomainname(2), gethostname(2)
Explanation of numbers:
(1): User UNIX Command
(2): Unix and C system cal... |
341,668 | 341,686 | C++: invalid conversion from ‘BaseNode*’ to ‘Match*’ | All objects in my program inherit from a Container class. The Container class has a virtual BaseNode* getParent() const; method and a virtual void setParent(BaseNode *p); method.
I have a Set class (Set in a tennis match, not a data structure) which has the Match class as it's parent (via setParent()) but since Set in... | The problem is that getParent() returns a BaseNode*, which could be a pointer to any type of BaseNode - it might point to an unrelated class that also derives from BaseNode. If you're 100% sure that the parent must be of type Match, you should cast the parent to a Match* first, and then you can call getPlayer() on tha... |
341,743 | 341,774 | C++ string that can be NULL | I'm used to passing around string like this in my C++ applications:
void foo(const std::string& input)
{
std::cout << input.size() << std::endl;
}
void bar()
{
foo("stackoverflow");
}
Now I have a case where I want the string to be NULL:
void baz()
{
foo("stackoverflow");
foo(NULL); // very bad with foo imple... | If you want the type to be null, then make it a pointer. Pass string pointers around instead of references, since this is precisely what pointers can do, and references cant. References always point to the same valid object. Pointers can be set to null, or be reseated to point to another object. Thus, if you need the t... |
341,817 | 826,027 | Is there a replacement for unistd.h for Windows (Visual C)? | I'm porting a relatively simple console program written for Unix to the Windows platform (Visual C++ 8.0). All the source files include "unistd.h", which doesn't exist. Removing it, I get complaints about misssing prototypes for 'srandom', 'random', and 'getopt'.
I know I can replace the random functions, and I'm pret... | Since we can't find a version on the Internet, let's start one here.
Most ports to Windows probably only need a subset of the complete Unix file.
Here's a starting point. Please add definitions as needed.
#ifndef _UNISTD_H
#define _UNISTD_H 1
/* This is intended as a drop-in replacement for unistd.h on Windows.
* ... |
342,152 | 342,192 | Why can't variable names start with numbers? | I was working with a new C++ developer a while back when he asked the question: "Why can't variable names start with numbers?"
I couldn't come up with an answer except that some numbers can have text in them (123456L, 123456U) and that wouldn't be possible if the compilers were thinking everything with some amount of a... | Because then a string of digits would be a valid identifier as well as a valid number.
int 17 = 497;
int 42 = 6 * 9;
String 1111 = "Totally text";
|
342,167 | 342,260 | Keyboard Hook... not getting Lower or Upper case characters | The function below is logging the "0", "z" and the "1" ok... but its not capturing the "Z" (shift-z)... any help would be appreciated...
__declspec(dllexport)
LRESULT CALLBACK HookProc (UINT nCode, WPARAM wParam, LPARAM lParam)
{
if ((nCode == HC_ACTION) && (wParam == WM_KEYUP))
{
// This Struct gets in... | The keyboard does not send characters. It sends keys. Whether you're typing z or Z, you're still pressing the same key, and that key has the same VK code both times.
You should also get notification when the Shift key is pressed or released. You can use those notifications to translate the keystrokes into characters. T... |
342,171 | 342,372 | multiple CComboBox sharing the same data | I have a MFC dialog with 32 CComboBoxes on it that all have the same data in the listbox. Its taking a while to come up, and it looks like part of the delay is the time I need to spend using InsertString() to add all the data to the 32 controls. How can I subclass CComboBox so that the 32 instances share the same dat... | Turn off window redrawing when filling the combos. e.g.:
m_wndCombo.SetRedraw(FALSE);
// Fill combo here
...
m_wndCombo.SetRedraw(TRUE);
m_wndCombo.Invalidate();
This might help.
|
342,772 | 342,787 | Convert lptstr to char* | Would anyone happen to know how to convert type LPTSTR to char * in C++?
| Depends if it is Unicode or not it appears. LPTSTR is char* if not Unicode, or w_char* if so.
Discussed better here (accepted answer worth reading)
|
342,839 | 342,869 | Problem with SDL_DisplayFormatAlpha (c++) | As I stated in this question, I am using SDL for a small game I'm developing. Now I am having problems with SDL_DisplayFormatAlpha. I am trying to create a surface with an alpha channel from a PNG image. It was working before, but now that I've done some slight refactoring something got broken. I've narrowed it dow... | IMG_Load should handle transparent PNG's automatically, as the end of your post notes. What is the actual exception/error being thrown? Your stack trace doesn't show that.
|
343,025 | 343,132 | Need of Formula for Accurate Bandwith for 1 Gigabit NIC Card | I am Need of Formula to Accurately Calculate Bandwith for 1 Gig Nic Card. What i am doing is send Layer 2 Packets @ 1Gbps but my software is showing 6oo Mbps.
The whole experiment is Back to Back. No switch No Router.
Here is what i did.
// LinkSpeed = 1Gb
UINT nBandwidth = LinkSpeed/100;//Mbps
nBandwidth = nBandw... | In ethernet, you also have to take into account the interframe gap, which is at minimum, 96 quantum time, that is, the quantum time being the time to send a bit, which is, 1ns in GigaEthernet (1 second / 1,000,000,000).
Also, if you get a collision, there will be backoff time, which quantum is chosen randomly between 0... |
343,219 | 344,495 | Is it possible to use signal inside a C++ class? | I am doing something like this:
#include <signal.h>
class myClass {
public:
void myFunction ()
{
signal(SIGIO,myHandler);
}
void myHandler (int signum)
{
/**
* Handling code
*/
}
}
I am working on Ubuntu, using gcc.
But it won't compile. It is complaining w... | The second parameter of signal should be a pointer to a function accepting an int and returning void. What you're passing to signal is a pointer to a member function accepting an int and returning void (its type being void (myClass::*)(int)). I can see three possibilities to overcome this issue:
1 - Your method myHandl... |
343,368 | 343,467 | error LNK2005: _DllMain@12 already defined in MSVCRT.lib | I am getting this linker error.
mfcs80.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined in MSVCRT.lib(dllmain.obj)
Please tell me the correct way of eliminating this bug. I read solution on microsoft support site about this bug but it didnt helped much.
I am using VS 2005 with Platform SDK
| If you read the linker error thoroughly, and apply some knowledge, you may get there yourself:
The linker links a number of compiled objects and libraries together to get a binary.
Each object/library describes
what symbols it expects to be present in other objects
what symbols it defines
If two objects define the sa... |
343,437 | 343,456 | Memcached client for Windows in C or C++? | I need a portable C/C++ solution, so I'm looking for a C/C++ client library for Memcached that work on both Windows and Unix. Any suggestions?
| There's libmemcached in C. Should be most portable :)
|
343,488 | 1,470,091 | Signing data with smartcards on Mac in C++ | is there any support in Mac OS X for signing data using smartcards? I have looked through the system headers and found only vauge references to smart card support (in SecKeychain.h), which didn't really take me anywhere.
If there's no built-in support, which are my options (ie. what free/non-free libraries exist that c... | I'm answering my own question here, for reference.
The OpenSC libraries provides everything you need to deal with smartcards, and it is cross-platform (Windows, Linux and Mac), and its license is good for commercial projects.
|
343,605 | 343,640 | How do you validate an object's internal state? | I'm interested in hearing what technique(s) you're using to validate the internal state of an object during an operation that, from it's own point of view, only can fail because of bad internal state or invariant breach.
My primary focus is on C++, since in C# the official and prevalent way is to throw an exception, an... | The question is best considered in combination with how you test your software.
It's important that hitting a broken invariant during testing is filed as a high severity bug, just as a crash would be. Builds for testing during development can be made to stop dead and output diagnostics.
It can be appropriate to add def... |
343,946 | 373,970 | Fixed width font - Symbian C++ CEikLabel | I want to change the font I am using in a CEikLabel on S60 device
I believe I can do the following
const CFont* aPlainFont = LatinPlain12();
aLabel->SetFont(aPlainFont);
where LatinPlain12 is one from this list..
Albi12
Alp13
Alpi13
Albi13
alp17
Alb17b
albi17b
alpi17
Aco13
Aco21
Acalc21
LatinBold12
LatinBold13
LatinBo... | Programatically, you can determine if a font is proportional using:
const CFont* myFont;
// Initialize your font
// ....
TBool isProportional = (myFont->FontSpecInTwips().iTypeface.Attributes() & TTypeFace::EProportional);
BTW you might be better off enumerating the fonts on the device and/or using the logical font A... |
344,012 | 344,029 | How do I replace this preprocessor macro with a #include? | UPDATE:
Obviously, you'd want to do this using templates or a base class rather than macros. Unfortunately for various reasons I can't use templates, or a base class.
At the moment I am using a macro to define a bunch of fields and methods on various classes, like this:
class Example
{
// Use FIELDS_AND_METHODS macr... | This cries out for a template.
class Example<class T>
{
...class definition...
};
The direct answer to the last part of your question - "given that I'm not in a macro definition any more, how do I get pasting and stringizing operators to work" - is "You can't". Those operators only work in macros, so you'd have t... |
344,031 | 344,087 | shared_ptr: what's it used for | I make a lot of use of boost::scoped_ptr in my code and it is great but I'm currently working with software that uses shared_ptr all over the place and I'm wondering if I'm missing something.
AFAIK a shared_ptr is only useful if different threads are going to be accessing the same data and you don't know what order th... | Threads are irrelevant here. What's relevant is whether it's easy to specify a point at which the object is no longer of use.
Suppose several different objects want to use the same object. It might be a pack of data, or for input/output, or some geometric object, or whatever. You want the shared object to be deleted... |
344,101 | 344,726 | Multithreading using the boost library | Wish to simultaneously call a function multiple times. I wish to use threads to call a function which will utilize the machines capability to the fullest. This is a 8 core machine, and my requirement is to use the machine cpu from 10% to 100% or more.
My requirement is to use the boost class. Is there any way I can a... | I suggest that you read up on the documentation for the functions you use. From your comment in James Hopkin's answer, it seems like you don't know what boost::bind does, but simply copy-pasted the code.
boost::bind takes a function (call it f), and optionally a number of parameters, and returns a function which, when ... |
344,317 | 344,525 | Where does gcc look for C and C++ header files? | On a Unix system, where does gcc look for header files?
I spent a little time this morning looking for some system header files, so I thought this would be good information to have here.
| `gcc -print-prog-name=cc1plus` -v
This command asks gcc which C++ preprocessor it is using, and then asks that preprocessor where it looks for includes.
You will get a reliable answer for your specific setup.
Likewise, for the C preprocessor:
`gcc -print-prog-name=cpp` -v
|
344,715 | 344,738 | Getting control of the main thread in windows c++ app | I'm writing some code that id like to be able to work with any window, such as a window created through the windows API, MFC, wxWidgets, etc.
The problem is that for some things I need to use the same thread that created the window, which in many cases is just sat in a message loop.
My first thought was to post a callb... | If you are in the same process as the window you can hook its messages by subclassing it. Check out http://msdn.microsoft.com/en-us/library/ms633570(VS.85).aspx
The key API is SetWindowLong.
// Subclass the edit control.
wpOrigEditProc = (WNDPROC) SetWindowLong(hwndEdit, GWL_WNDPROC, (LONG)EditSubclassProc);
// Rem... |
344,829 | 344,841 | What is __kernel_vsyscall? | I got a core that looks very different from the ones I usually get - most of the threads are in __kernel_vsyscall() :
9 process 11334 0xffffe410 in __kernel_vsyscall ()
8 process 11453 0xffffe410 in __kernel_vsyscall ()
7 process 11454 0xffffe410 in __kernel_vsyscall ()
6 process 11455 0xffffe410 in __kerne... | __kernel_vsyscal is the method used by linux-gate.so (a part of the Linux kernel) to make a system call using the fastest available method, preferably the sysenter instruction. The thing is properly explained by Johan Petersson.
|
345,003 | 345,474 | Is it safe to use STL (TR1) shared_ptr's between modules (exes and dlls) | I know that new-ing something in one module and delete-ing it in another can often cause problems in VC++. Problems with different runtimes. Mixing modules with staticly linked runtimes and/or dynamically linked versioning mismatches both can screw stuff up if I recall correctly.
However, is it safe to use VC++ 2008's ... | Freeing the memory is safe, so long as it all came from the same memory management context. You've identified the most common issue (different C++ runtimes); having separate heaps is another less-common issue you can run into.
Another issue which you didn't mention, but which can be exascerbated by shared pointers, is... |
345,045 | 345,213 | accessing bitmap resources in a C++ DLL from VB6 | I have a C++ DLL including bitmap resources created by Visual Studio.
Though I can load the DLL in VB6 using LoadLibrary, I cannot load the image resources either by using LoadImage or by using LoadBitmap. When I try to get the error using GetLastError(), it doesnot return any errors.
I have tried using LoadImage and L... | Since you are using the numeric ID of the bitmap as a string, you have to add a "#" in front of it:
DLLHandle = LoadLibrary("Mydll.dll")
myimage = LoadBitmap(DLLHandle, "#101") ' note the "#"
In C++ you could also use the MAKEINTRESOURCE macro, which is simply a cast to LPCTSTR:
imagehandle = LoadBitmap(DLLHandle, MA... |
345,305 | 345,339 | Could anyone suggest a good packet sniffer class for c++? | Could anyone suggest a good packet sniffer class for c++? Looking for a easy insertable class I can use in my c++ program, nothing complicated.
| You will never be able to intercept network traffic just by inserting a class into your project. Packet capture functionality requires kernel mode support, hence you will at the very least need to have your application require or install libpcap/WinPcap, as Will Dean pointed out.
Most modern Unix-like distributions inc... |
345,382 | 345,446 | Capturing MSN Chat via Memory | Is it possible, or does anyone know the best way to capture MSN chats? I was thinking about attaching to the MSN process, and messing about searching for static addresses for conversations, to capture them.
(This is all on the windows platform using c++)
| It would probably be easiest to sniff packets on the ports known to be used by MSN. That has the added benefit of working with clients other than the Microsoft one (such as Pidgin).
|
345,610 | 346,224 | Remove all but the last 500,000 bytes from a file with the STL | Our logging class, when initialised, truncates the log file to 500,000 bytes. From then on, log statements are appended to the file.
We do this to keep disk usage low, we're a commodity end-user product.
Obviously keeping the first 500,000 bytes is not useful, so we keep the last 500,000 bytes.
Our solution has some se... |
"I would probably create a new file, seek in the old file, do a buffered read/write from old file to new file, rename the new file over the old one."
I think you'd be better off simply:
#include <fstream>
std::ifstream ifs("logfile"); //One call to start it all. . .
ifs.seekg(-512000, std::ios_base::end); // One ca... |
345,930 | 346,671 | Efficient Methods for a Life Simulation | Having read up on quite a few articles on Artificial Life (A subject I find very interesting) along with several questions right here on SO, I've begun to toy with the idea of designing a (Very, very, very) simple simulator. No graphics required, even. If I've overlooked a question, please feel free to point it out to ... | If you were doing this as a hard-core development project, I'd suggest using the equivalent of Java reflection (substitute the language of your choice there). If you want to do a toy project as a starter effort, I'd suggest at least rolling your own simple version of reflection, per the following rationale.
Each artifa... |
345,936 | 345,961 | Will .NET take over C/C++ any time? | This is a subjective question.
I worked in Visual Basic 6.0 before coming into the .NET space.
One thing I see that there are a lot of things, for which there is a need to deal with the Win32 API. As a Visual Basic 6.0 developer, there were a lot of limitations. .NET fixes some of the old problems however the need to ... | It can't go away any time soon, but in Windows, at least, new projects are going less and less with C/C++. You can even see examples of Microsoft starting to eat their own dog food.
A great example of this is the C# compiler. Currently, it is written in C/C++. The C# team is currently working on re-writing it purely ... |
346,012 | 346,036 | What is the usefulness of project1st<Arg1, Arg2> in the STL? | I was browsing the SGI STL documentation and ran into project1st<Arg1, Arg2>. I understand its definition, but I am having a hard time imagining a practical usage.
Have you ever used project1st or can you imagine a scenario?
| My guess is that if you were using the strategy pattern and had a situation where you needed to pass an identity object, this would be a good choice. For example, there might be a case where an algorithm takes several such objects, and perhaps it is possible that you want one of them to do nothing under some situation... |
346,024 | 346,082 | If CHttpConnection::OpenRequest returns NULL how do I find out why | c++
mfc
if CHttpConnection::OpenRequest returns a null what can I use to get the internet error.
The mfc artical doesn't say what a bad responce looks like. I just said it returns a handle to a CHttpFile.
| Did you see what is the error code returned by GetLastError() ? Get the error code and perform a error lookup (Tools->Error Lookup) to get the description about the code. Normally you will get the exact reason for the failure using this.
|
346,058 | 346,098 | C++ class header files organization | What are the C++ coding and file organization guidelines you suggest for people who have to deal with lots of interdependent classes spread over several source and header files?
I have this situation in my project and solving class definition related errors crossing over several header files has become quite a headache... | Some general guidelines:
Pair up your interfaces with implementations. If you have foo.cxx, everything defined in there had better be declared in foo.h.
Ensure that every header file #includes all other necessary headers or forward-declarations necessary for independent compilation.
Resist the temptation to create an... |
346,613 | 346,616 | How do you exit from a void function in C++? | How can you prematurely exit from a function without returning a value if it is a void function? I have a void method that needs to not execute its code if a certain condition is true. I really don't want to have to change the method to actually return a value.
| Use a return statement!
return;
or
if (condition) return;
You don't need to (and can't) specify any values, if your method returns void.
|
346,622 | 346,764 | Opinions on type-punning in C++? | I'm curious about conventions for type-punning pointers/arrays in C++. Here's the use case I have at the moment:
Compute a simple 32-bit checksum over a binary blob of data by treating it as an array of 32-bit integers (we know its total length is a multiple of 4), and then summing up all values and ignoring overflow... | As far as the C++ standard is concerned, litb's answer is completely correct and the most portable. Casting const char *data to a const uint3_t *, whether it be via a C-style cast, static_cast, or reinterpret_cast, breaks the strict aliasing rules (see Understanding Strict Aliasing). If you compile with full optimiza... |
346,650 | 347,100 | Is there a "nice" way to deal with reassembling multicasts from multiple sources? | I'm currently reworking our existing proprietary socket wrapper code to use boost asio so that it can do some of the heavy lifting for us. Perhaps the most complex area of our existing code is the multicast handling code. The code allows our middle-tier servers (of which there can me many in one system) to send mult... | It doesn't sound like you've given enough information for detailed answers, but there are a few general pointers to consider for realtime handling of multicast data.
If you're using raw UDP multicast, you're probably doing some sort of protocol sequencing in userspace in order to deal with lost or duplicated packets. ... |
346,697 | 346,713 | Can the "using" declaration be used with templates? | Is it possible to use the "using" declaration with template base classes? I have read it isn't here but is that because of a technical reason or is it against the C++ standard, and does it apply to gcc or other compilers? If it is not possible, why not?
Example code (from the link above):
struct A {
template<class... | What you linked to is a using directive. A using declaration can be used fine with templated base classes (haven't looked it up in the standard, but just tested it with a compiler):
template<typename T> struct c1 {
void foo() { std::cout << "empty" << std::endl; }
};
template<typename T> struct c2 : c1<T> {
... |
346,814 | 346,890 | how to check performance of a c++ api | my web server has a lot of dependencies for sending back data, when it gets a request. i am testing one of these dependency applications within the web server. the application is decoupled from the main web server, and only queries are going to it in the form of api's exposed.
my question is, if i wish to check these a... | It depends on whether your app deails with data that's shared if it is run in parallel processes because that'll most likely determine where the speed bottleneck awaits.
E.g, if the app accesses a database or disk files, you'll probably have to simulate multiple threads/processes querying the app in order to see how th... |
346,858 | 346,867 | How do you search a std::string for a substring in C++? | I'm trying to parse a simple string in C++. I know the string contains some text with a colon, followed immediately by a space, then a number. I'd like to extract just the number part of the string. I can't just tokenize on the space (using sstream and <<) because the text in front of the colon may or may not have s... | std::string strInput = "Total disk space: 9852465";
std::string strNumber = "0";
size_t iIndex = strInput.rfind(": ");
if(iIndex != std::string::npos && strInput.length() >= 2)
{
strNumber = strInput.substr(iIndex + 2, strInput.length() - iIndex - 2)
}
|
347,031 | 347,041 | Accessing a bidimensional(or tridimensional) array through a pointer | When you have an array like this:
int foo[3][2][2];
and you make:
int *bar = &foo[0][0][0];
Is this the way it works?
*bar == foo[0][0][0];
*(bar+1) == foo[0][0][1];
*(bar+2) == foo[0][1][0];
*(bar+3) == foo[0][1][1];
*(bar+4) == foo[1][0][0];
I'm not sure and have a bit of code dependent on if that works.
| Yes, that's called row major ordering, and is what C is using.
|
347,096 | 347,107 | How can I get a specialized template to use the unspecialized version of a member function? | Consider the following code:
template <int dim>
struct vec
{
vec normalize();
};
template <>
struct vec<3>
{
vec cross_product(const vec& second);
vec normalize();
};
template <int dim>
vec<dim> vec<dim>::normalize()
{
// code to normalize vector here
return *this;
}
int main()
{
vec<3> dire... | You can't :) What you want is to specialize the member functions instead:
template <int dim>
struct vec
{
// leave the function undefined for everything except dim==3
vec cross_product(const vec& second);
vec normalize();
};
template<>
vec<3> vec<3>::cross_product(const vec& second) {
// ...
}
templat... |
347,132 | 347,140 | Append an int to char* | How would you append an integer to a char* in c++?
| First convert the int to a char* using sprintf():
char integer_string[32];
int integer = 1234;
sprintf(integer_string, "%d", integer);
Then to append it to your other char*, use strcat():
char other_string[64] = "Integer: "; // make sure you allocate enough space to append the other string
strcat(other_string, integ... |
347,187 | 347,217 | Best Flags for Crash dumps | I currently have some code that will produce a crash dump when my application crashes however I can't work out what are the best flags to use for it are.
At the moment I have it using Full Memory (MiniDumpWithFullMemory) but this produces 32mg crash files. What flags should I use as to not make the crash file huge but ... | This is not always such a general answer. The flags desired will depend somewhat on what you are trying to accomplish or for what you may be searching.
Perhaps you are having threading issues, MiniDumpWithThreadInfo or MiniDumpWithProcessThreadData would be appropriate. If your program is corrupting its in-memory dat... |
347,191 | 347,215 | How do I get the source IP address from a datagram's IP header with Winsock? | I have a port that is bind()'d to INADDR_ANY. I am receiving datagrams successfully. After receipt, I need to read the IP header to get the source IP address.
| I don't believe you can get it if you're using the standard recv or read function calls. The recvfrom call as follows:
int recvfrom(
__in SOCKET s,
__out char *buf,
__in int len,
__in int flags,
__out struct sockaddr *from,
__inout_opt int *fromlen
);
includes a stru... |
347,358 | 434,784 | Inheriting constructors | Why does this code:
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
};
int main(void)
{
B *b = new B(5);
delete b;
}
Result in these errors:
main.cpp: In function ‘int main()’:
main.cpp:13: error: no matching function for call to ‘B::B(int)’
main.cpp:8: note: candidates are: B::B(... | If your compiler supports C++11 standard, there is a constructor inheritance using using (pun intended). For more see Wikipedia C++11 article. You write:
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
using A::A;
};
This is all or nothing - you cannot inherit only some constructors, i... |
347,441 | 347,478 | Erasing elements from a vector | I want to clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be present multiple times and I need to clear all of them. My code is something like this:
void erase(std::vector<int>& myNumbers_in, int number_in)
{
s... | Use the remove/erase idiom:
std::vector<int>& vec = myNumbers; // use shorter name
vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());
What happens is that remove compacts the elements that differ from the value to be removed (number_in) in the beginning of the vector and returns the iterator to the ... |
347,736 | 351,037 | How to get file list from a Debian package using eptlib libraries? | Simple question: I have loaded an Apt package record with libept. There is a method to get file list? It should sound like
record.GetFileList();
and it should return a vector string like the output of
dpkg -L packagename
| The libept main developer (Petr Rockai) explain me that unfortunately, at this time, libept have no such method. What they do in Adept is this:
QString flfilename = "/var/lib/dpkg/info/" + u8(t.package()) + ".list";
QFile flfile(flfilename);
QTextStream flInStream(&flfile);
while (!flInStream.atEnd()) {
QString lin... |
347,747 | 383,887 | IDebugControl::WaitForEvent works once then returns E_HANDLE | I'm trying to make a small tool that makes use of the Debugger Engine API, but I'm having very limited success.
I can get my IDebugClient and IDebugControl instances, and from there I am able to attach into an already running user process. I then enter a main loop where I call WaitForEvent, OutputStackTrace, SetExecut... | The problem turned out to be that I was compiling, linking, and running against an old version of the SDK. Now that I've upgraded my SDK to the latest version (which I presume is the version that the online docs refer to) I get behaviour that is at least consistent with the docs.
I still have problems, but no longer t... |
347,920 | 347,940 | What do 1.#INF00, -1.#IND00 and -1.#IND mean? | I'm messing around with some C code using floats, and I'm getting 1.#INF00, -1.#IND00 and -1.#IND when I try to print floats in the screen. What does those values mean?
I believe that 1.#INF00 means positive infinity, but what about -1.#IND00 and -1.#IND? I also saw sometimes this value: 1.$NaN which is Not a Number, b... | From IEEE floating-point exceptions in C++ :
This page will answer the following questions.
My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
How can I tell if a number is really a number and not a NaN or an infinity?
How can I find out more details at runtime about ki... |
347,949 | 347,959 | How to convert a std::string to const char* or char* | How can I convert an std::string to a char* or a const char*?
| If you just want to pass a std::string to a function that needs const char *, you can use .c_str():
std::string str;
const char * c = str.c_str();
And if you need a non-const char *, call .data():
std::string str;
char * c = str.data();
.data() was added in C++17. Before that, you can use &str[0].
Note that if the st... |
347,951 | 347,999 | Simple anonymous pipes - what wrapper model you use? (WinAPI, C++) | I have two running processes in Windows, and each process has a pipe to the other.
I want to serialize a complicated class and transmit it from one process to the other. I already have the serialization procedure worked out, and I understand that the pipes are sending binary streams. How should I go about sending my se... | Here is the tutorial for boost::serialization. I could imagine it would work fine sending the data over the pipe and deserializing on the other side: http://www.boost.org/doc/libs/1_37_0/libs/serialization/doc/tutorial.html
|
348,320 | 348,350 | In C++ is it possible to have a defined purely virtual function? | Here's the deal. I have a big class hierarchy and I have this one method that is extended all the way through. The method always has to look at one or two more variable at each new level and these variable depend on the actual class in the hierarchy. What I want to do is check those two extra variables then call the su... | Actually you can declare a function as purely virtual and still define an implementation for it in the base class.
class Abstract {
public:
virtual void pure_virtual(int x) = 0;
};
void Abstract::pure_virtual(int x) {
// do something
}
class Child : public Abstract {
virtual void pure_virtual(int x);
};
v... |
348,616 | 348,624 | Domain Specific Language in C/C++, does this Kosher? | I was just fooling around with some Domain Specific Language designs for a new project in C/C++ when I thought up this "odd" solution:
define DSL(...) MakeCommand(#__VA_ARGS__\
)->Exec()->GetResults()
MyResults results = DSL( for p in people do something );
The nice part is this is cor... | Hmm, while variadic macros are C99, they are not possible in C++. I wouldn't do it like that :) A simple dsl function taking a std::string or whatever string class your framework uses, and returning MakeCommand(str)->Exec()->GetResults() would be my preferred option, since it's more debug friendly, and you can put it i... |
348,730 | 348,740 | Why is there "class" in "template <class x>"? | What does the "class" part of a template statement do?
Example:
template <class T>
class Something
{
public:
Something(const T &something);
}
And what else can go there? I usually only see "class".
| The class keyword means the same thing as the typename keyword for the most part. They both indicates that T is a type.
The only difference between the keywords class and typename is that class can be used to provide class template template arguments to a template, whereas typename can't. Consider:
template<template <c... |
348,763 | 348,780 | c++ template instantiation | I have a template class like below.
template<int S> class A
{
private:
char string[S];
public:
A()
{
for(int i =0; i<S; i++)
{
.
.
}
}
int MaxLength()
{
return S;
}
};
If i instantiate the above class with different values of S, will the compiler create different instances o... | The template will be instantiated for each different values of S.
If you move the method implementations to a different file, you'll need to #include that file. (Boost for instance uses the .ipp convention for such source files that need to be #included).
If you want to minimise the amount of code that is generated wit... |
348,833 | 350,378 | How to know the exact line of code where an exception has been caused? | If I generate an exception on my own, I can include any info into the exception: a number of code line and name of source file. Something like this:
throw std::exception("myFile.cpp:255");
But what's with unhandled exceptions or with exceptions that were not generated by me?
| It seems everyone is trying to improve your code to throw exceptions in your code, and no one is attempting the actual question you asked.
Which is because it can't be done. If the code that's throwing the exception is only presented in binary form (e.g. in a LIB or DLL file), then the line number is gone, and there's... |
348,953 | 348,972 | How do I resolve: "error C2039: '{ctor}' : is not a member of" in Visual Studio 2005? | I am extending a template class using C++ in Visual Studio 2005.
It is giving me an error when I try to extend the template base class with:
template <class K, class D>
class RedBlackTreeOGL : public RedBlackTree<K, D>::RedBlackTree // Error 1
{
public:
RedBlackTreeOGL();
~RedBlackTreeOGL();
and a second error w... | The code is trying to inherit a constructor, not a class :-)
The start of the class declaration should be
template <class K, class D>
class RedBlackTreeOGL : public RedBlackTree<K, D>
|
349,004 | 349,015 | Why won't my program run unless Visual Studio 2008 is installed? | I have written a game that uses GLUT, OpenGL and FMOD. The problem is that the binary won't run, unless Visual Studio 2008 is installed on the computer.
Why is this?
| Most likely you're linking with DLL versions of the C/C++ runtime. Go to project properties -> C++ -> Code Generation, and set Runtime Library to not be one of "DLL" kinds.
Alternatively, you can link to DLL runtimes, but then you have to redistribute the runtime with your application.
MSDN has more information on vari... |
349,025 | 349,030 | Is a string literal in С++ created in static memory? | Is a string literal in C++ created in static memory and destroyed only when the program exits?
| Where it's created is an implementation decision by the compiler writer, really. Most likely, string literals will be stored in read-only segments of memory since they never change.
In the old compiler days, you used to have static data like these literals, and global but changeable data. These were stored in the TEXT... |
349,446 | 349,501 | adjacency matrix in java or c++ to find connected nodes | I am given a problem where I have been given N nodes in a graph that are interconnected to each other then given a matrix which lists down a node being connected to another (1 if it is, 0 if not). I am wondering how to best approach this problem. I think these are adjacency matrix? But how would I implement that ...
... | You can implement this using a 2-dimensional array of booleans. So, if node i is connected to node j, then myarray[i][j] would be true. If your edges are not directional, then myarray[j][i] would be true whenever myarray[i][j] is.
This can also be extended to weighted edges by using integers (or another numeric type) i... |
349,544 | 349,599 | Threading issue (chase your own tail) | There is ConnectionManager which waits for incoming connections. For each incoming connection it creates a Connection instance which handles the inbound and outbound traffic on this connection. Each Connection has a Watchdog which handles "bad connection" conditions and calls registered "Listerners". One "Listener" is ... | If the watchdog is running in a different thread, then the problem isn't too bad - the watchdog signals the ConnectionManager to delete with a asynchronous message, then exits it's own thread.
Mean-while, the ConnectionManager thread gets the delete message, and starts deleting the watchdog.
To avoid race-conditions th... |
349,835 | 350,137 | WM_GETTEXT button action | I would like to tie an action to a PocketPC button (biggest button at the center - don't know how it is called).
I tried to tie the action to WM_GETTEXT message, but this message is sent on every key press and don't know how to add an action just to the specific button.
Does anyone know how this could be done?
Thanks!... | Are you talking about the Action button in the middle of a "d-pad"?
Each device has its own hardware layout; there's no such thing as the "biggest button at the center" common to all devices. Prehaps you can post a picture?
Anyway, take a look at this page: Keys and Key Codes for Windows Mobile.
Also, WM_GETTEXT is def... |
349,889 | 350,046 | How do you determine the amount of Linux system RAM in C++? | I just wrote the following C++ function to programmatically determine how much RAM a system has installed. It works, but it seems to me that there should be a simpler way to do this. Am I missing something?
getRAM()
{
FILE* stream = popen("head -n1 /proc/meminfo", "r");
std::ostringstream output;
int bufsi... | On Linux, you can use the function sysinfo which sets values in the following struct:
#include <sys/sysinfo.h>
int sysinfo(struct sysinfo *info);
struct sysinfo {
long uptime; /* Seconds since boot */
unsigned long loads[3]; /* 1, 5, and 15 minute load averages */
unsigned l... |
349,899 | 349,906 | What C++ compilers are supporting lambda already? | Are there C++ compilers already supporting C++0x lambda expressions?
| Visual Studio 2010 CTP supports it already.
Update: It is now Visual Studio 2010 Beta 2
|
350,419 | 350,448 | How do you reconcile common C++ naming conventions with those of the libraries | Most C++ naming conventions dictate the use of camelCaseIdentifiers: names that start with an uppercase letter for classes (Person, Booking) and names that start with a lowercase letter for fields and variables (getPrice(), isValid(), largestValue). These recommendations are completely at odds with the naming conventi... | One way it to adopt the C++ naming_convention, this is what most code examples in the literature do nowadays.
I slowly see these conventions move into production code but it's a battle against MFC naming conventions that still prevail in many places.
Other style differences that fight against old standards are using tr... |
350,507 | 350,545 | Starting an application under windows using start | I noticed that I can start a program with it's associated handler by writing start filename. However, for some files, all I get is a console, and I don't know why. I'm trying to populate a list control in MFC, and I want to have the program and it's associated handler to run when I double click the selection. Is there ... | If the first parameter on the start command line is enclosed in double-quotes, it uses that as the window title instead of the command. It's lame, but that's what it does...
Try
string st = string("start \"\" \"")+std_str+string("\"");
instead.
But if you're trying to get the shell handler for a file to execute from ... |
350,586 | 351,809 | Set a default cursor for an application | In a Qt application, is there an equivalent to QApplication::setFont that sets the applications default cursor, to be overwritten by setting one on a specific widget?
QApplication::setOverrideCursor overrides all widget specific ones, I want local ones to take precidene over this one, but still use my cursor if I didn... | A QWidget either uses the cursor specified with QWidget::setCursor or falls-back it's parents' cursor setting. So, simply setting the cursor for your main windows should do the trick.
New top level windows and dialogs will need to have the cursor set when created since their is no parent from which to inherit.
|
350,811 | 351,200 | MFC Equivalent to Java File#isDirectory() | Is there an equivalent to the Java File method isDirectory() in MFC? I tried using this :
static bool isDirectory(CString &path) {
return GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY;
}
but it doesn't seem to work.
| Sorry for possibly "inconsistency" of answer to question but may be you'll see it useful because anytime I need something like this in Windows I am NOT using MFC but regular Windows API:
//not completely tested but after some debug I'm sure it'll work
bool IsDirectory(LPCTSTR sDirName)
{
//First define special str... |
351,122 | 351,233 | Size of data obtained from SQL query via ODBC API | Does anybody know how I can get the number of the elements (rows*cols) returned after I do an SQL query? If that can't be done, then is there something that's going to be relatively representative of the size of data I get back?
I'm trying to make a status bar that indicates how much of the returned data I have proces... | That is frequently a problem when you wan to reserve dynamic memory to hold the entire result set.
One technique is to return the count as part of the result set.
WITH
data AS
(
SELECT interesting-data
FROM interesting-table
WHERE some-condition
)
SELECT COUNT(*), data.*
from data
If you don't know be... |
351,236 | 351,255 | copy hdc contents to bitmap | How could you copy the contents of an HDC to a bitmap?
| Off the top of my head I think you need to:
Create a new DC compatible with the source DC. Call this the memory DC.
Create a new bitmap of the correct size.
Select the bitmap into the memory DC.
BitBlt the source DC into the memory DC.
The bitmap should now contain a copy of the source DC.
I'm at home so can't give y... |
351,360 | 351,414 | An algorithm to get the next weekday set in a bitmask | I've got this small question - given a bitmask of weekdays (e.g., Sunday = 0x01, Monday = 0x02, Tuesday = 0x04, etc...) and today's day (in a form of Sunday = 1, Monday = 2, Tuesday = 3, etc...) - what's the most elegant way to find out the next day from today, that's set in the bitmask? By elegant I mean, is there a w... | int getNextDay(int days_mask, int today) {
if (!days_mask) return -1; // no days set
days_mask |= days_mask << 7; // duplicate days into next week
mask = 1 << (today % 7); // keep track of the day
while (!(mask & days_mask)) {
mask <<= 1;
++today;
}
return today % 7;
}
So that's just one ... |
351,522 | 351,548 | C++ Huffman Code Header | basically, I've got my Huffman table as
std::map<std::string, char> ciMap;
Where string is the bit pattern and char is the value represented by said pattern.
The problem is how do I store that as a header of my compressed file so I can build again the same map when I want to decode it?
Trying to store it as binary:
s... | You can do it yourself, or you can do it with boost: http://www.boost.org/doc/libs/1_37_0/libs/serialization/doc/index.html. What you currently try is just view the map as a plain old datatype, which essentially means it's a C datatype. But it isn't, so it fails to save/load. boost serialization does it correctly. Have... |
351,582 | 351,601 | How can I discover/control the level of internal buffering in a C++ fstream? | Say I do this (a contrived example):
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
ifstream ifs(argv[1]);
char ch;
while(ifs.read(&ch, 1)) {
cout << ch;
}
}
I assume(hope) that the iostream library does some internal buffering here and doesn't... | You can use ios::rdbuf() to get a pointer to a streambuf object. This object represents the internal buffer for the stream.
You can call streambuf::pubsetbuf(char * s, streamsize n) to set a new internal buffer with a given size.
See this link for more details.
edit: Here is how it would look in your case:
#include <i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.