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 |
|---|---|---|---|---|
321,377 | 321,387 | In C++, I want my interface, .h to say int GetSomeInt() const;.... but actually the method *DOES* update "this". | I'm adding some lazy initialization logic to a const method, which makes the method in fact not const. Is there a way for me to do this without having to remove the "const" from the public interface?
int MyClass::GetSomeInt() const
{
// lazy logic
if (m_bFirstTime)
{
m_bFirstTime = false;
D... | Make m_bFirstTime mutable:
class MyClass
{
: :
mutable bool m_bFirstTime;
};
...but this is also very often an indication of a design flaw. So beware.
|
321,413 | 321,448 | LPCSTR, LPCTSTR and LPTSTR | What the difference between LPCSTR, LPCTSTR and LPTSTR?
Why do we need to do this to convert a string into a LV / _ITEM structure variable pszText:
LV_DISPINFO dispinfo;
dispinfo.item.pszText = LPTSTR((LPCTSTR)string);
| To answer the first part of your question:
LPCSTR is a pointer to a const string (LP means Long Pointer)
LPCTSTR is a pointer to a const TCHAR string, (TCHAR being either a wide char or char depending on whether UNICODE is defined in your project)
LPTSTR is a pointer to a (non-const) TCHAR string
In practice when talki... |
321,619 | 323,047 | C++ Serialization Performance | I'm building a distributed C++ application that needs to do lots of serialization and deserialization of simple data structures that's being passed between different processes and computers.
I'm not interested in serializing complex class hierarchies, but more of sending structures with a few simple members such as num... | I would strongly suggest protocol buffers. They're incredibly simple to use, offer great performance, and take care of issues like endianness and backwards compatibility. To make it even more attractive, serialized data is language-independent thanks to numerous language implementations.
|
321,793 | 321,812 | Date/time conversion: string representation to time_t | How do I convert a date string, formatted as "MM-DD-YY HH:MM:SS", to a time_t value in either C or C++?
| Use strptime() to parse the time into a struct tm, then use mktime() to convert to a time_t.
|
321,849 | 321,877 | strptime() equivalent on Windows? | Is there a good equivalent implementation of strptime() available for Windows? Unfortunately, this POSIX function does not appear to be available.
Open Group description of strptime - summary: it converts a text string such as "MM-DD-YYYY HH:MM:SS" into a tm struct, the opposite of strftime().
| An open-source version (BSD license) of strptime() can be found here: http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD
You'll need to add the following declaration to use it:
char *strptime(const char * __restrict, const char * __restrict, struct tm * __restrict);
|
322,086 | 322,095 | c++ array declaration in a header | I was wondering if it is possible to declare an array (size not known at this time), as a private member of a class and later set the size in the constructor of the class. For example:
class Test {
int a[];
public:
Test(int size);
};
Test::Test(int size) {
a[size]; // this is wrong, but what can i do here?
}
Is th... | No this is not possible. Array declarations in headers must have constant sized value. Otherwise it's impossible for constructs like "sizeof" to function properly. You'll need to declare the array as a pointer type and use new[] in the constructor. Example.
class Test {
int *a;
public:
Test(int size) {
... |
322,128 | 322,153 | C++ STL Vector Iterator accessing members of an Object | I think I've declared a Vector with an object correctly. But, I don't know how to access it's members when looping with Iterator.
In my code, the line --->> cout << " " << *Iter;
How do I print the contents of the members? Like *Iter.m_PackLine ???
Not sure if I used the correct terminology, but appreciate the help!... | cout << " " << *Iter;
will only work if CFileInfo has an overloaded operator<< that can output your struct. You can output individual members of the struct instead like this:
cout << " " << Iter->m_PackLine;
Alternatively, the following is equivalent to that:
cout << " " << (*Iter).m_PackLine;
You have to put parent... |
322,147 | 333,817 | QAbstractTableModel inheritance vtable problem | Here's another problem with qt:
I extend a QAbstractTableModel, but I get a compiling error ( I'm using cmake)
// file.h
#ifndef TABLEMODEL_H
#define TABLEMODEL_H
#include <QAbstractTableModel>
class TableModel : public QAbstractTableModel
{
Q_OBJECT
public:
TableModel(QObject *parent = 0);
int rowCount(const QModel... | Solved adding to CMakeLists.txt the needed cpp file.
set(tutorial_SRCS app.cpp mainWin.cpp tableModel.cpp)
When I'll run cmake, the moc* will be automatically created
|
322,225 | 322,297 | Send data over Internet | I have a requirement to send some 100 bytes data over internet .My machine is connected to internet.
I can do this with HTTP by sending requests and receiving responses.
But my requirement is just to send data not receive response.
I am thinking of doing this using UDP Client server program. But to do that I need to ho... | Cheap answer to send 100 bytes of data on the internet.
C:\Windows\system32>ping -n 1 -l 100 -4 google.com
Pinging google.com [209.85.171.99] with 100 bytes of data:
Reply from 209.85.171.99: bytes=56 (sent 100) time=174ms TTL=233
Ping statistics for 209.85.171.99:
Packets: Sent = 1, Received = 1, Lost = 0 (0% lo... |
322,390 | 322,562 | How do I examine the contents of an std::vector in gdb, using the icc compiler? | I want to examine the contents of a std::vector in gdb but I don't have access to _M_impl because I'm using icc, not gcc, how do I do it? Let's say it's a std::vector for the sake of simplicity.
There is a very nice answer here but this doesn't work if I use icc, the error message is "There is no member or method named... | Not sure this will work with your vector, but it worked for me.
#include <string>
#include <vector>
int main() {
std::vector<std::string> vec;
vec.push_back("Hello");
vec.push_back("world");
vec.push_back("!");
return 0;
}
gdb:
(gdb) break source.cpp:8
(gdb) run
(gdb) p vec.begin()
$1 = {
_M_cu... |
322,938 | 322,995 | Recommended way to initialize srand? | I need a 'good' way to initialize the pseudo-random number generator in C++. I've found an article that states:
In order to generate random-like
numbers, srand is usually initialized
to some distinctive value, like those
related with the execution time. For
example, the value returned by the
function time (d... | The best answer is to use <random>. If you are using a pre C++11 version, you can look at the Boost random number stuff.
But if we are talking about rand() and srand()
The best simplest way is just to use time():
int main()
{
srand(time(nullptr));
...
}
Be sure to do this at the beginning of your program, and... |
323,354 | 324,340 | Export HTML to PDF (C++, Windows) | I am looking for a redistributable component to convert HTML to PDF.
I would - at the moment - like to avoid using a "PDF printer", as this requires a printer installation and some user "playing around" in the printers panel might break that feature.
The HTML is available in a Browser control or as external file. The H... | PDFCreator can function as a virtual printer but it's also usable via COM. The default setup even includes COM examples.
You can check the COM samples in the SourceForge SVN repository right here: http://pdfcreator.svn.sourceforge.net/viewvc/pdfcreator/trunk/COM/
|
323,407 | 323,418 | What's the Magic Behind Escape(\) Character | How does the C/C++ compiler manipulate the escape character ["\"] in source code? How is compiler grammar written for processing that character? What does the compiler do after encountering that character?
| Most compilers are divided into parts: the compiler front-end is called a lexical analyzer or a scanner. This part of the compiler reads the actual characters and creates tokens. It has a state machine which decides, upon seeing an escape character, whether it is genuine (for example when it appears inside a string) or... |
323,419 | 365,787 | Simple script to count NLOC? | Do you know a simple script to count NLOCs (netto lines of code). The script should count lines of C Code. It should not count empty lines or lines with just braces. But it doesn't need to be overly exact either.
| I would do that using awk & cpp (preprocessor) & wc . awk removes all braces and blanks, the preprocessor removes all comments and wc counts the lines:
find . -name \*.cpp -o -name \*.h | xargs -n1 cpp -fpreprocessed -P |
awk '!/^[{[:space:]}]*$/' | wc -l
If you want to have comments included:
find . -name \*.cpp... |
323,774 | 323,873 | How can I make a CListCtrl keep its scrollbar? | In MFC, a CListBox has a "disable no scroll" property. When you set it to true, the vertical scrollbar is always there, no matter how many items you have. How can I do the same thing with CListCtrl?
| The standard control does not seem to support your desired behavior.
You could either create enough entries to make the scroll bar visible or you could create your own control implementing it the way you like. Inbetween would be the ownerdrawn style, but that does not apply to the scroll bar.
BTW: what would be a reaso... |
323,790 | 325,436 | Autotools : how to set global compilation flag | I have a project with several sources directories :
src/A
/B
/C
In each, the Makefile.am contains
AM_CXXFLAGS = -fPIC -Wall -Wextra
How can avoid repeating this in each source folder ?
I tried to modifiy src/Makefile.am and the configure.in, but without success. I thought I could use AC_PROG_CXX to set the c... | You can do several things:
(1) One solution is to include a common makefile fragment on all your Makefile.ams:
include $(top_srcdir)/common.mk
...
bin_PROGRAMS = foo
foo_SOURCES = ...
in that case you would write
AM_CXXFLAGS = -fpic -Wall -Wextra
to common.mk and in the future it will be easier to add more macros or ... |
323,816 | 323,848 | C++ Pointers / Lists Implementation |
Write a class ListNode which has the following properties:
int value;
ListNode *next;
Provide the following functions:
ListNode(int v, ListNode *l)
int getValue();
ListNode* getNext();
void insert(int i);
bool listcontains(int j);
Write a program which asks the user to enter some integers and stores them as
ListNo... | What unwind and ckarmann say. Here is a hint, i implement listcontains for you to give you the idea how the assignment could be meant:
class ListNode {
private:
int value;
ListNode * next;
public:
bool listcontains(int v) {
// does this node contain the value?
if(value == v) return true;
... |
323,874 | 324,623 | how to show/hide SIP on Pocket PC | I have the following problem:
I open the dialog, open the SIP keyboard to fill the form and then minimize the SIP. Then when I close the current dialog and return to the main dialog the SIP keyboard appears again. Does anyone know how could I show/hide SIP keyboard programatically or better what could be done to solve ... | We use SHSipPreference to control the display of the SIP in our applications. I know it works with MFC and it sets the state of the SIP for the window so you can set it once and you know the SIP state will be restored to your set state every time the window is shown.
I've never heard of SipShowIM but I did see on the ... |
324,043 | 324,123 | How best to switch from template mess to clean classes architecture (C++)? | Assuming a largish template library with around 100 files containing around 100 templates with overall more than 200,000 lines of code. Some of the templates use multiple inheritance to make the usage of the library itself rather simple (i.e. inherit from some base templates and only having to implement certain busines... | I'm not sure I see how/why templates are the problem, and why plain non-templated classes would be an improvement. Wouldn't that just mean even more classes, less type safety and so larger potential for bugs?
I can understand simplifying the architecture, refactoring and removing dependencies between the various classe... |
324,168 | 324,343 | MSXML2::IXMLDOMDocument2Ptr->GetXML() messing up my string! | All,
this is my code
//declare string pointer
BSTR markup;
//initialize markup to some well formed XML <-
//declare and initialize XML Document
MSXML2::IXMLDOMDocument2Ptr pXMLDoc;
HRESULT hr;
hr = pXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument40));
pXMLDoc->async = VARIANT_FALSE;
pXMLDoc->validateOnParse = VARI... | Try replacing
BSTR Markup;
with
bstr_t Markup;
BSTR is pretty much a dumb pointer, and I think that the return result of GetXML() is being converted to a temporary which is then destroyed by the time you get to see it. bstr_t wraps that with some smart-pointer goodness...
Note: Your "SuperMarkup" thing did NOT do ... |
324,711 | 324,975 | Writing stringstream contents into ofstream | I'm currently using std::ofstream as follows:
std::ofstream outFile;
outFile.open(output_file);
Then I attempt to pass a std::stringstream object to outFile as follows:
GetHolesResults(..., std::ofstream &outFile){
float x = 1234;
std::stringstream ss;
ss << x << std::endl;
outFile << ss;
}
Now my outFile con... | You can do this, which doesn't need to create the string. It makes the output stream read out the contents of the stream on the right side (usable with any streams).
outFile << ss.rdbuf();
|
324,722 | 324,725 | C++ MySQL database connection | I not a DB expert, so am looking for advice for a web-based system I'm thinking of setting up.
The general set up of the system I have is that it will have a web-based interface (possibly in PHP) for logging in etc, and some C++ code running on the server doing some processing. Both the PHP and the C++ code will need r... | The DB should take care of concurrent access. You can consider using MySQL++ as a library to access mysql from C++ code. I only know of its existence, with no usage experience, so I cannot tell you about usability.
|
324,803 | 324,853 | eof detection for DirectShow | Is there a way to detect that a DirectShow filtergraph has reached the end of its file? By end of its file, I mean that a filtergraph with a SampleGrabber filter will never receive another SampleCB call.
Here are some things that don't work:
Trust IMediaDet::get_StreamLength (it's often says there are more frames in ... | Maybe using the IMediaEventEx interface? One of the event codes is EC_COMPLETE documented as 'All data from a particular stream has been rendered.'
|
324,867 | 324,873 | C++ Strings Modifying and Extracting based on Separators | Kind of a basic question but I'm having troubles thinking of a solution so I need a push in the right direction.
I have an input file that I'm pulling in, and I have to put it into one string variable. The problem is I need to split this string up into different things. There will be 3 strings and 1 int. They are se... | With C-style strings you can use strtok() to do this. You could also use sscanf()
But since you're dealing with C++, you probably want to stick with built in std::string functions. As such you can use find(). Find has a form which takes a second argument which is the offset to start searching. So you can do find( '... |
325,555 | 325,572 | C++ Static member method call on class instance | Here is a little test program:
#include <iostream>
class Test
{
public:
static void DoCrash(){ std::cout<< "TEST IT!"<< std::endl; }
};
int main()
{
Test k;
k.DoCrash(); // calling a static method like a member method...
std::system("pause");
return 0;
}
On VS2008 + SP1 (vc9) it compiles fine:... | The standard states that it is not necessary to call the method through an instance, that does not mean that you cannot do it. There is even an example where it is used:
C++03, 9.4 static members
A static member s of class X may be referred to using the
qualified-id expression X::s; it is
not necessary to use the ... |
325,706 | 507,783 | Installer::OpenDatabase() produces a type error with msiOpenDatabaseModeTransact | The following code produces an error hr=0x80020005 (wrong type).
#import <msi.dll>
using namespace WindowsInstaller;
main()
{
::CoInitialize(NULL);
InstallerPtr pInstaller("WindowsInstaller.Installer");
DatabasePtr pDB = pInstaller->OpenDatabase(
"c:\\foo\\bar.msi",
msiOpenData... | I finally got the answer on msdn forums
DatabasePtr pDB = pInstaller->OpenDatabase(
"c:\\foo\\bar.msi",
(long)msiOpenDatabaseModeTransact);
|
325,734 | 325,740 | Grouping similar types of member variables together | When writing a class do you group members variables of the same type together? Is there any benefit to doing so? For example:
class Foo
{
private:
bool a_;
bool b_;
int c_;
int d_;
std::string e_;
std::string f_;
...
};
As opposed to:
class Bar
{
private:
std::string e_;
bool ... | I group them according to semantics, i.e.
class Foo
{
private:
std::string peach;
bool banana;
int apple;
int red;
std::string green;
std::string blue;
...
};
The more readable, the better.
|
325,906 | 325,911 | Most used parts of Boost | When I discovered boost::lexical_cast I thought to myself "why didn't I know about this sooner!" - I hated having to write code like
stringstream ss;
ss << anIntVal;
mystring = ss.str();
Now I write
mystring = boost::lexical_cast<string>(anIntVal);
Yesterday, on stackoverflow, I came across boost split (another gem... | Probably the most used part of boost for me is boost::shared_ptr.
|
325,988 | 325,992 | Developing as a programmer | I have been learning C++ for three months now and in that time created a number of applications for my company. I consider myself fairly comfortable with C++ / MFC and STL, however I don't just want to be an OK programmer, I want to be a good programmer. I have a few books on best practices but I was wondering if anyon... | For C++, Scott Meyers books are very good, and will help take you to the next level.
If you don't already have it C++ by Bjarne Stroustrup, 3rd Edition
|
326,062 | 327,289 | In STL maps, is it better to use map::insert than []? | A while ago, I had a discussion with a colleague about how to insert values in STL maps. I preferred map[key] = value; because it feels natural and is clear to read whereas he preferred map.insert(std::make_pair(key, value)).
I just asked him and neither of us can remember the reason why insert is better, but I am sure... | When you write
map[key] = value;
there's no way to tell if you replaced the value for key, or if you created a new key with value.
map::insert() will only create:
using std::cout; using std::endl;
typedef std::map<int, std::string> MyMap;
MyMap map;
// ...
std::pair<MyMap::iterator, bool> res = map.insert(MyMap::value... |
326,079 | 326,347 | Which is preferred CTabCtrl vs. CPropertySheet in MFC? | I don't know how to use both of them. So a sample code with pros and cons is perfect. Which one is preferred? Why?
| Neither is preferred, they serve different purposes. If you want a dialog with several pages, use a CPropertySheet. If you need a dialog with several pages while part of the dialog remains fixed, use a CTabCtrl. A CTabCtrl can be used do everything a CPropertySheet can do, but since the CTabCtrl is more complex to use,... |
326,112 | 326,166 | Single statement method to remove elements from container | Is there a single algorithm that removes elements from a container as happens in the following code?
vec_it = std::remove_if( vec.begin(), vec.end(), pred );
vec.erase( vec_it, vec.end() );
| The idiomatic way to do it is like jalf has said. You can build your own function to do that more easily:
template<typename T, typename Pred> void erase_if(T &vec, Pred pred)
{
vec.erase(std::remove_if(vec.begin(), vec.end(), pred), vec.end());
}
So you can use
std::vector<int> myVec;
// (...) fill the vector. (..... |
326,125 | 330,394 | Is there a way to run ActiveX components in Firefox through the use of a plugin? | I have an ActiveX plugin that we need (if possible) to run in Firefox. Is there a plugin (or other way) for Firefox that will allow this?
| I seem to have found a solution:
http://code.google.com/p/ff-activex-host/
"This Firefox plugin makes it possible to use ActiveX controls in Firefox. It is based on the Gecko NPAPI and provides full access to the hosted control (events, functions, properties)."
|
326,179 | 326,197 | I need to combine several methods without adding some data members. Any ideas? | Lets say I need to write several functions processing some data. These functions are performing a single task - some mathematical calculations. I suppose there is no need to combine them with some data members.
Shall I use:
a class without data members and declare these functions as static methods so I can use them wi... | I don't see why you would put them in an anonymous namespace. It is done to make sure these functions are only used in one compilation unit, which has nothing to do with your question.
Now, to choose between static functions in a class or free functions in a utility namespace, it's up to your needs. There is a few diff... |
326,487 | 326,524 | Multithreaded image processing in C++ | I am working on a program which manipulates images of different sizes. Many of these manipulations read pixel data from an input and write to a separate output (e.g. blur). This is done on a per-pixel basis.
Such image mapulations are very stressful on the CPU. I would like to use multithreading to speed things up. ... | If your compiler supports OpenMP (I know VC++ 8.0 and 9.0 do, as does gcc), it can make things like this much easier to do.
You don't just want to make a lot of threads - there's a point of diminishing returns where adding new threads slows things down as you start getting more and more context switches. At some poin... |
327,010 | 327,070 | using a vector of column names, to generate a sql statement | A problem that we need to solve regularly at my workplace is how to build sql statements based on user supplied table/column names. The issue I am trying to address is the commas between column names.
One technique looks something like this.
selectSql = "SELECT ";
for (z = 0; z < columns.size(); z++)
{
selectS... | In your case it is probably safe to assume that there is at least one column since otherwise there is no point in doing the select. In that case you could do:
selectSql = "SELECT ";
selectSql += columns[0]._name;
for (z = 1; z < columns.size(); z++) {
selectSql += ", ";
selectSql += columns[z]._name;
}
select... |
327,218 | 327,399 | Spline, B-Spline and NURBS C++ library | Does anyone know of a library or set of classes for splines - specifically b-splines and NURBS (optional).
A fast, efficient b-spline library would be so useful for me at the moment.
| 1.) For B Splines - You should check Numerical Recipes in C (there is book for that and it is also available online for reference)
2.) Also check: sourceforge.net/projects/einspline/
& this
-AD
|
327,642 | 327,648 | OpenGL and monochrome texture | Is it possible to pump monochrome (graphical data with 1 bit image depth) texture into OpenGL?
I'm currently using this:
glTexImage2D( GL_TEXTURE_2D, 0, 1, game->width, game->height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, game->culture[game->phase] );
I'm pumping it with square array of 8 bit unsigned integers in GL_LUMIN... | The smallest uncompressed texture-format for luminance images uses 8 bits per pixel.
However, 1 bit per pixel images can be compressed without loss to the S3TC or DXT format. This will still not be 1 bit per pixel but somewhere between 2 and 3 bits.
If you really need 1 bit per pixel you can do so with a little trick.... |
328,019 | 328,043 | How to load bmp into GLubyte array? | All,
I am trying to load up a bmp file into a GLubyte array (without using aux).
It is unbelievable how what I thought would have been a trivial task is sucking up hours of my time.
Can't seem to find anything on Google!
This is what I hacked together but it's not quite working:
// load texture
GLubyte *customTexture;... | LoadImage() can only load bitmaps that are embedded into your executable file with the resource compiler - it can't load external bitmaps from the filesystem. Fortunately, bitmap files are really simple to read yourself. See Wikipedia for a description of the file format.
Just open up the file like you would with any... |
328,577 | 328,587 | Python for C++ Developers | I'm a long time C++/Java developer trying to get into Python and am looking for the stereotypical "Python for C++ Developers" article, but coming up blank. I've seen these sort of things for C#, Java, etc, and they're incredibly useful for getting up to speed on language features and noteworthy differences. Anyone ha... | I never really understood the "Language X for Language Y developers" approach. When I go looking to learn Language X I want to learn how to program in it the way that Language X programmers do, not the way Language Y programmers do. I want to learn the features, idioms, etc. that are unique to the language that I am ... |
328,944 | 328,948 | How do i check if a file is a regular file? | How do i check in C++ if a file is a regular file (and is not a directory, a pipe, etc.)? I need a function isFile().
DIR *dp;
struct dirent *dirp;
while ((dirp = readdir(dp)) != NULL) {
if ( isFile(dirp)) {
cout << "IS A FILE!" << endl;
i++;
}
I've tried comparing dirp->d_type with (unsigned char)0x8, but it s... | You need to call stat(2) on the file, and then use the S_ISREG macro on st_mode.
Something like (adapted from this answer):
#include <sys/stat.h>
struct stat sb;
if (stat(pathname, &sb) == 0 && S_ISREG(sb.st_mode))
{
// file exists and it's a regular file
}
|
328,955 | 328,959 | How to use std::sort with a vector of structures and compare function? | Thanks for a solution in C,
now I would like to achieve this in C++ using std::sort and vector:
typedef struct
{
double x;
double y;
double alfa;
} pkt;
vector< pkt > wektor; filled up using push_back(); compare function:
int porownaj(const void *p_a, const void *p_b)
{
pkt *pkt_a = (pkt *) p_a;
pkt *pkt_b =... | std::sort takes a different compare function from that used in qsort. Instead of returning –1, 0 or 1, this function is expected to return a bool value indicating whether the first element is less than the second.
You have two possibilites: implement operator < for your objects; in that case, the default sort invocatio... |
329,039 | 329,046 | Get machine properties | I would like to write a program that will identify a machine( for licensing purposes), I tought about getting the following information and to compile an xml file with this data:
MAC address.
CPU data (serial, manufacture, etc)
MotherBoard Identification. (serial, manufacture, etc)
can someone refer me to a lib that ... | Using WMI and getting the motherboard's serial number should be enough (the other options are less secure, since an old computer may not have a network adapter and/or the CPU can be changed more likely than the motherboard).
|
329,059 | 329,195 | What is __gxx_personality_v0 for? | This is a second-hand question from an OS development site, but it made me curious since I couldn't find a decent explanation anywhere.
When compiling and linking a free-standing C++ program using gcc, sometimes a linker error like this occurs:
out/kernel.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0... | It is used in the stack unwiding tables, which you can see for instance in the assembly output of my answer to another question. As mentioned on that answer, its use is defined by the Itanium C++ ABI, where it is called the Personality Routine.
The reason it "works" by defining it as a global NULL void pointer is proba... |
329,061 | 329,084 | Writing Multithreaded Exception-Safe Code | What are the tensions between multithreading and exception-safety in C++? Are there good guidelines to follow? Does a thread terminate because of an uncaught exception?
| I believe the C++ standard does not make any mention of multithreading - multithreading is a platform-specific feature.
I'm not exactly sure what the C++ standard says about uncaught exceptions in general, but according to this page, what happens is platform-defined, and you should find out in your compiler's documenta... |
329,164 | 329,234 | Detecting (unknown) hardware in .NET | I need some pointers on how to detect unknown hardware using .NET and C++/C#. I'm looking for the technique to use under NET to do this.
What I basically want is to identify the PCIID/USBID and so on for all the hardware in the machine. Of course I also need this for the hardware that doesn't yet has a driver installed... | I think you'll be in for a lot of P/Invoke-ing, but I would indeed start with the WDK (formerly known as the DDK).
I'd start with taking a look at devcon.exe. Binary is at tools\devcon; sources are at src\setup\devcon.
|
329,517 | 329,527 | There is a function to use pattern matching (using regular expressions) in C++? | There is a simple C++ method to use pattern matching on strings? The code should sound like this:
if (regexpcmp("l?nole*[0-9]", "linoleum1")) {
//we have a match!
} else {
//no match
}
| Not in the core language. Use Boost.Regex or an external library like pcre. In a unix environment you almost certainly have access to the BSD regular expression tools (regcomp, regerror, regexec, regfree) which are c-like rather than c++-like but do work.
|
329,838 | 329,851 | C++ design - Network packets and serialization | I have, for my game, a Packet class, which represents network packet and consists basically of an array of data, and some pure virtual functions
I would then like to have classes deriving from Packet, for example: StatePacket, PauseRequestPacket, etc. Each one of these sub-classes would implement the virtual functions,... | For copying you need to write a clone function, since a constructor cannot be virtual:
virtual Packet * clone() const = 0;
Which each Packet implementation implement like this:
virtual Packet * clone() const {
return new StatePacket(*this);
}
for example for StatePacket. Packet classes should be immutable. Once a... |
329,925 | 329,937 | Extracting MAC addresses from UUIDs | A program that I work on assumes that the UUID generated by the Windows RPC API call UuidCreateSequential() contains the MAC address of the primary ethernet adapter. Is this assumption correct or should I use a different method to get the MAC address?
| I wouldn't rely on this - the only reason that UuidCreateSequential has the MAC address is it's trying to guarantee that the UUID is unique across the network. Plus, why would you use such a weird way to get a MAC address? Use WMI and actually ask for the MAC address instead of a side-effect of a UUID creation function... |
329,962 | 330,048 | Static Variables, Separate Compilation | I wrote a program out, which was all in one file, and the methods were forward declared in a header. The program initially worked perfectly when it was in one file. But when I separated the program, I kept getting random occurrences for the destructor of one of the classes which was declared in the header file.
I h... | class A {
public:
virtual ~A() {
count --;
if (count == 0) { // this is the last one, do something }
}
protected:
static int count;
};
class B : public A{
public:
B();
};
And then, in one and only one of your source files you need to put the following. It should go in the source file that ... |
330,186 | 330,196 | Safe To Modify std::pair<U, V>::first in vector of pairs? | I'm currently working on a DNA database class and I currently associate each row in the database with both a match score (based on edit distance) and the actual DNA sequence itself, is it safe to modify first this way within an iteration loop?
typedef std::pair<int, DnaDatabaseRow> DnaPairT;
typedef std::vector<DnaPair... | To answer your first question, yes. It is perfectly safe to modify the members of your pair, since the actual data in the pair does not affect the vector itself.
edit: I have a feeling that you were getting an error when using a map because you tried to modify the first value of the map's internal pair. That would not ... |
330,348 | 330,407 | Which On-Screen Keyboard for Touch Screen Application? | I'm developing an application in C++ that's partially driven by touch-screen on Windows XP Embedded. Some text entry will be necessary for the user. So far we've been using the standard Windows On-Screen Keyboard (osk.exe), but there are two main problems:
It's rather small on a higher resolution screen which will p... | We are using Click-N-Type for our systems. It is completely resizable. It has some customization possibilities, but I never tried them. We use it on "normal" Windows XP, but it should work on Windows XP embedded also.
|
330,374 | 330,380 | long long implementation in 32 bit machine | As per c99 standard, size of long long should be minimum 64 bits. How is this implemented in a 32 bit machine (eg. addition or multiplication of 2 long longs). Also, What is the equivalent of long long in C++.
| On the IA32 architecture, 64-bit integer are implemented in using two 32-bit registers (eax and edx).
There are platform specific equivalents for C++, and you can use the stdint.h header where available (boost provides you with one).
|
330,497 | 330,553 | C++ Constructor coding errors | I just stumbled across this bug in some legacy code:
class MyAPIHandler
{
private:
int handle;
public:
void MyApiHandler() // default constructor
{
handle = 42;
};
};
It compiles fine, with no warnings - but the behaviour wasn't what I intended, because the constructor name is misspel... | If you always use initialiser lists in your constructors:
MyApiHandler() // default constructor
: handle(42)
{
}
the misnamed constructor bug would be even more unlikely, and it's better style anyway.
Edit: thanks to commenter for the link
|
330,500 | 330,531 | How to resolve this VC++ 6.0 linker error? | This is a Windows Console application (actually a service) that a previous guy built 4 years ago and is installed and running. I now need to make some changes but can't even build the current version! Here is the build output:
--------------------Configuration: MyApp - Win32 Debug--------------------
Compiling resource... | Sorry, this turns out to be an internal problem. A combination of a maverick coder 4 years ago and a rusty no-nothing (me!) now.
The code does not use _socket_noblock but it does use socket_noblock and I just need to link to one of our own libraries.
|
331,045 | 331,064 | Using C++ DLLs with different compiler versions | This question is related to "How to make consistent dll binaries across VS versions ?"
We have applications and DLLs built
with VC6 and a new application built
with VC9. The VC9-app has to use
DLLs compiled with VC6, most of
which are written in C and one in
C++.
The C++ lib is problematic due to
name decoration/mangl... | Interface member names will not be decorated -- they're just offsets in a vtable. You can define an interface (using a C struct, rather than a COM "interface") in a header file, thusly:
struct IFoo {
int Init() = 0;
};
Then, you can export a function from the DLL, with no mangling:
class CFoo : public IFoo { /* ..... |
331,068 | 331,145 | When is anonymous namespace data initialized? | I have been using anonymous namespaces to store local data and functions and wanted to know when the data is initialized? Is it when the application starts in the same way as static data or is it compiler dependent? For example:
// foo.cpp
#include "foo.h"
namespace {
const int SOME_VALUE = 42;
}
void foo::SomeFu... | C++ Standard, 3.6.2/1 :
Zero-initialization and
initialization with a constant
expression are collectively called
static initialization; all other
initialization is dynamic
initialization. Objects of POD types
(3.9) with static storage duration
initialized with constant expressions
(5.19) shall be init... |
331,148 | 331,155 | Does C++ allow default return types for functions? | In C the following horror is valid:
myFunc()
{
return 42; // return type defaults to int.
}
But, what about in C++? I can't find a reference to it either way...
My compiler (Codegear C++Builder 2007) currently accepts it without warning, but I've had comments that this is an error in C++.
| It's ill-formed in C++. Meaning that it doesn't compile with a standard conforming compiler. Paragraph 7.1.5/4 in Annex C of the Standard explains the change "Banning implicit int".
|
331,355 | 333,008 | Need a client-side interactive 2D world map: best map package? Or best C++ graphics/canvas library to make one? | I need a 2d political map of the world on which I will draw icons, text, and lines that move around. Users will interact with the map, placing and moving the icons, and they will zoom in and out of the map.
The Google Maps interface isn't very far from what I need, but this is NOT web related; it's a Windows MFC appli... | Perhaps:
http://www.codeplex.com/SharpMap
ESRI MapObjects
http://www.esri.com/software/mapobjects/index.html
ESRI MapObjects LT
http://www.esri.com/software/mapobjectslt/index.html
See
http://www.esri.com/software/mapobjectslt/about/mo_vs_lt.html
for a comparison of the two MapObjects feature sets.
ESRI may have a repl... |
331,468 | 331,932 | Encryption algorithm/library for .NET 2.0 + C++ | I need a standard, Microsoft delivered, encryption library that works for both .NET 2.0 and C++. What would you suggest?
We find that AES is only offered in .NET 3.5 (and available in C++)
We find that Rijndael is used in .NET 2.0 but not available in the standard C++ libraries.
If I am wrong (very good chance), can yo... | We successfully do a similar thing that I hope might help you:
C++ CryptoAPI
CryptoAPI is pure Win32 (c/c++), native to all Microsoft OS's.
Use Enhanced Cryptographic Provider (MS_ENHANCED_PROV)
Use Triple DES (CALG_3DES) algorithm
.NET TripleDes Provider
Use TripleDESCryptoServiceProvider on the .NET side.
Side No... |
331,536 | 331,567 | Windows threading: _beginthread vs _beginthreadex vs CreateThread C++ | What's a better way to start a thread, _beginthread, _beginthreadx or CreateThread?
I'm trying to determine what are the advantages/disadvantages of _beginthread, _beginthreadex and CreateThread. All of these functions return a thread handle to a newly created thread, I already know that CreateThread provides a little... | CreateThread() is a raw Win32 API call for creating another thread of control at the kernel level.
_beginthread() & _beginthreadex() are C runtime library calls that call CreateThread() behind the scenes. Once CreateThread() has returned, _beginthread/ex() takes care of additional bookkeeping to make the C runtime lib... |
331,690 | 331,935 | Using Unicode in C++ source code | What is the standard encoding of C++ source code? Does the C++ standard even say something about this? Can I write C++ source in Unicode?
For example, can I use non-ASCII characters such as Chinese characters in comments? If so, is full Unicode allowed or just a subset of Unicode? (e.g., that 16-bit first page or whate... | Encoding in C++ is quite a bit complicated. Here is my understanding of it.
Every implementation has to support characters from the basic source character set. These include common characters listed in §2.2/1 (§2.3/1 in C++11). These characters should all fit into one char. In addition implementations have to support a... |
331,866 | 331,872 | Events in cpp/opengl | I would like to create infrastructure to handle events for my opengl project.
It should be similar to what wpf has - 3 types of events - direct, tunneling, bubbling.
I then want to handle events such as mouse up, down, move etc.
How should i approach this problem? Is there any library to handle this.
thanks
| The OpenGL Utility Toolkit (GLUT) provides precisely this - you set up a bunch of event handlers for things like keyboard input, mouse input, redrawing the display, and window resizing, call the glutMainLoop() function, and you're good to go.
|
331,937 | 331,948 | What am I doing wrong with this pointer cast? | I'm building a GUI class for C++ and dealing a lot with pointers. An example call:
mainGui.activeWindow->activeWidget->init();
My problem here is that I want to cast the activeWidget pointer to another type. activeWidget is of type GUI_BASE. Derived from BASE I have other classes, such as GUI_BUTTON and GUI_TEXTBOX... | The problem is that casts have lower precedence than the . -> () [] operators. You'll have to use a C++ style cast or add extra parentheses:
((GUI_TEXTBOX*)mainGui.activeWindow->activeWidget)->function(); // Extra parentheses
dynamic_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget)->function(); // C++ style ca... |
332,111 | 332,132 | How do I convert a double into a string in C++? | I need to store a double as a string. I know I can use printf if I wanted to display it, but I just want to store it in a string variable so that I can store it in a map later (as the value, not the key).
| The boost (tm) way:
std::string str = boost::lexical_cast<std::string>(dbl);
The Standard C++ way:
std::ostringstream strs;
strs << dbl;
std::string str = strs.str();
Note: Don't forget #include <sstream>
|
332,460 | 333,349 | non-member non-friend function syntax | Is their a way to use a non-member non-friend function on an object using the same "dot" notation as member functions?
Can I pull a (any) member out of a class, and have users use it in the same way they always have?
Longer Explanation:
Scott Meyers, Herb Sutter, et all, argue that non-member non-friend functions are a... | You can use a single syntax, but perhaps not the one you like. Instead of placing one insert() inside your class scope, you make it a friend of your class. Now you can write
mystring s;
insert(s, "hello");
insert(s, other_s.begin(), other_s.end());
insert(s, 10, '.');
For any non-virtual, public method, it's equivalen... |
332,554 | 332,572 | Includes with the Linux GCC Linker | I don't understand how GCC works under Linux. In a source file, when I do a:
#include <math.h>
Does the compiler extract the appropriate binary code and insert it into the compiled executable OR does the compiler insert a reference to an external binary file (a-la Windows DLL?)
I guess a generic version of this quest... | Well. When you include math.h the compiler will read the file that contains declarations of the functions and macros that can be used. If you call a function declared in that file (header), then the compiler inserts a call instruction into that place in your object file that will be made from the file you compile (let'... |
332,705 | 332,725 | Float or Double Special Value | I have double (or float) variables that might be "empty", as in holding no valid value. How can I represent this condition with the built in types float and double?
One option would be a wrapper that has a float and a boolean, but that can´t work, as my libraries have containers that store doubles and not objects that ... | In Visual C++, there is a non-standard _isnan(double) function that you can import through float.h.
In C, there is a isnan(double) function that you can import through math.h.
In C++, there is a isnan(double) function that you can import through cmath.
As others have pointed out, using NaN's can be a lot of hassle. The... |
332,849 | 332,900 | Parsing command line arguments in a unicode C++ application | How can I parse integers passed to an application as command line arguments if the app is unicode?
Unicode apps have a main like this:
int _tmain(int argc, _TCHAR* argv[])
argv[?] is a wchar_t*. That means i can't use atoi. How can I convert it to an integer? Is stringstream the best option?
| if you have a TCHAR array or a pointer to the begin of it, you can use std::basic_istringstream to work with it:
std::basic_istringstream<_TCHAR> ss(argv[x]);
int number;
ss >> number;
Now, number is the converted number. This will work in ANSI mode (_TCHAR is typedef'ed to char) and in Unicode (_TCHAR is typedef`ed t... |
332,852 | 332,910 | Check variable type in C++ | So I am currently learning C++ and decided to make a program that tests my skills I have learned so far. Now in my code I want to check if the value that the user enters is a double, if it is not a double I will put a if loop and ask them to reenter it. The problem I have is how do I go about checking what type of vari... | There is no suitable way to check if a string really contains a double within the standard library. You probably want to use Boost. The following solution is inspired by recipe 3.3 in C++ Cookbook:
#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
double cube(double n);
... |
333,029 | 333,069 | C++ class identification question | I'll phrase this in the form of an example to make it more clear.
Say I have a vector of animals and I want to go through the array and see if the elements are either dogs or cats?
class Dog: public Animal{/*...*/};
class Cat: public Animal{/*...*/};
int main()
{
vector<Animal*> stuff;
//cramming the dogs and cats in.... | As others has noted, you should neither use the typeid, nor the dynamic_cast operator to get the dynamic type of what your pointer points to. virtual functions were created to avoid this kind of nastiness.
Anyway here is what you do if you really want to do it (note that dereferencing an iterator will give you Animal*... |
333,169 | 333,234 | "out of memory" exception in CRecordset when selecting a LONGTEXT column from MySQL | I am using CODBCRecordset (a class found on CodeProject) to find a single record in a table with 39 columns. If no record is found then the call to CRecordset::Open is fine. If a record matches the conditions then I get an Out of Memory exception when CRecordset::Open is called. I am selecting all the columns in the qu... | Read Pax's response. It gives a you a great understanding about why the problem happens.
Work Around:
This error will only happen if the field defined as (TEXT, LONGTEXT, etc) is NULL (and maybe empty). If there is data in the field then it will only allocate for the size the data in the field and not the max size (the... |
333,285 | 333,289 | Simple efficiency question C++ (memory allocation)..and maybe some collision detection help? | I'm writing a little arcade-like game in C++ (a multidirectional 2d space shooter) and I'm finishing up the collision detection part.
Here's how I organized it (I just made it up so it might be a shitty system):
Every ship is composed of circular components - the amount of components in each ship is sort of arbitrary (... | You should absolutely try to avoid doing memory allocations for your component-vector on each call to the getter-function. Do the allocation as seldom as possible, instead. For instance, you could do it when the component composition of the ship changes, or even more seldom (by over-allocating).
You could of course als... |
333,400 | 545,276 | How to design a simple C++ object factory? | In my application, there are 10-20 classes that are instantiated once[*]. Here's an example:
class SomeOtherManager;
class SomeManagerClass {
public:
SomeManagerClass(SomeOtherManager*);
virtual void someMethod1();
virtual void someMethod2();
};
Instances of the classes are contained in one object:
class ... | I think there are two separate problems here.
One problem is: how does TheManager name the class that it has to create? It must keep some kind of pointer to "a way to create the class". Possible solutions are:
keeping a separate pointer for each kind of class, with a way to set it, but you already said that you don't ... |
333,443 | 333,541 | C++ Object Instantiation | I'm a C programmer trying to understand C++. Many tutorials demonstrate object instantiation using a snippet such as:
Dog* sparky = new Dog();
which implies that later on you'll do:
delete sparky;
which makes sense. Now, in the case when dynamic memory allocation is unnecessary, is there any reason to use the above... | On the contrary, you should always prefer stack allocations, to the extent that as a rule of thumb, you should never have new/delete in your user code.
As you say, when the variable is declared on the stack, its destructor is automatically called when it goes out of scope, which is your main tool for tracking resource ... |
333,559 | 333,574 | C++/Win32: How to get the alpha channel from an HBITMAP? | I have an HBITMAP containing alpha channel data. I can successfully render this using the ::AlphaBlend GDI function.
However, when I call the ::GetPixel GDI function, I never get back values with an alpha component. The documentation does say that it returns the RGB value of the pixel.
Is there a way to retrieve the a... | Use GetDIBits. That way you get an array of RGBQUAD's which have as you can probably guess an alpha channel next to the R, G and B components.
|
333,575 | 333,597 | SetWindowsHookEx, KeyboardProc and Non-static members | I am creating a keyboard hook, wherein KeyboardProc is a static member of a class CWidget.
class CWidget
{
static LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam );
};
I want to call the non-static members of CWidget inside the CWidget::KeyboardProc.
What is the best way to do it?
KeyboardPr... | Given that you probably only want one keyboard hook installed at a time, just add a static pThis member to your class:
// Widget.h
class CWidget
{
static HHOOK m_hHook;
static CWidget *m_pThis;
public:
/* NOT static */
bool SetKeyboardHook()
{
m_pThis = this;
m_hHook = ::SetWindowsH... |
333,889 | 333,902 | Why have header files and .cpp files? | Why does C++ have header files and .cpp files?
| Well, the main reason would be for separating the interface from the implementation. The header declares "what" a class (or whatever is being implemented) will do, while the cpp file defines "how" it will perform those features.
This reduces dependencies so that code that uses the header doesn't necessarily need to kn... |
333,927 | 333,937 | Why didn't header files catch on in other programming languages? | Based on the response to this question: Why does C++ have header files and CPP
I have seen the responses and understand the answers - so why didn't this catch on? C# Java?
| Because it's a quick, dirty and inelegant solution to the problem of interface vs. implementation.
It relies entirely on the C Preprocessor, which is about the bluntest tool in the drawer.
Other solutions avoid the following problems:
Two files where one will do
Duplicate symbols at link-time due to multiple definitio... |
334,148 | 369,252 | Polyphonic sound playback | I need audio playback with these features: good performance (for game), pitch control, and ability to layer the same sample multiple times at the same time (polyphony). What would be a quick way to get this on the iphone sdk?
Here's what I found out so far:
There's no available libraries or sample code that does this,... | FMOD (www.fmod.org) provides all these features. Check out their virtualvoices sample for polyphony and the pitch shift DSP effect in the docs.
I'm just a customer, not otherwise affiliated with them.
|
334,243 | 334,433 | Get active window without global hooks or polling GetActiveWindow? | How can I get notifications about what is the currect active window and when this changes without polling GetActiveWindow or using global hooks?
I don't like polling, and I'm working in C# and global hooks don't work (mostly).
| I have never found a clean way to get notified. I use GetForegroundWindow with a timer. :(
|
334,277 | 334,470 | understanding dll dependencies | I'm building a c++ DLL in visual studio 2008.
For some reason, even when I build in release mode, my dll still depends on msvcr90d.dll.
I can see that using depends.exe
Is there any way to figure out what is causing this dependency?
My run-time library setting is /MD
Thanks,
Dan
| In the Project properties go to the "Configuration Properties"/Linker/General panel. Change the "Show Progress" property to "Display All Progress Messages (/VERBOSE)".
The linker will now tell you exactly why it's pulling in msvcr90d.dll
If you're building from the command line, use the /VERBOSE linker option (obviou... |
334,292 | 334,372 | Symbian C++ - Substring operations on descriptors | What is the preferred/easiest way to manipulate TDesC strings, for example to obtain a substring.
I will give you an example of my scenario.
RBuf16 buf;
...
CEikLabel label;
...
label->SetTextL(buf); // (SetTextL takes a const TDesC&)
I want to get a substring from buf. So do I want to manipulate the RBuf16 directly a... | Read descriptors.blogspot.com (scroll down once loaded).
You can use TDes::LeftTPtr, TDes::RightTPtr or TDes::MidTPtr which will give you a substring as a TPtr (i.e. a descriptor which manipulates the original data).
You can use the TDes::Copy function if you want to create a copy of your substring.
|
334,439 | 334,484 | Exception elimination in C++ constructors | We have recently been faced with the problem of porting our C++ framework to an ARM platform running uClinux where the only vendor supported compiler is GCC 2.95.3. The problem we have run into is that exceptions are extremely unreliable causing everything from not being caught at all to being caught by an unrelated th... | Generally you end up with code like this for objects on the stack:
MyClassWithNoThrowConstructor foo;
if (foo.init(bar, baz, etc) != 0) {
// error-handling code
} else {
// phew, we got away with it. Now for the next object...
}
And this for objects on the heap. I assume you override global operator new with s... |
334,674 | 334,690 | Calling NT function on pre-NT system | So I don't do a lot of Win32 calls, but recently I have had to use the GetFileTime() and SetFileTime() functions. Now although Win98 and below are not officially supported in my program people do use it there anyway, and I try to keep it as usable as possible. I was just wondering what will happen as those functions do... | If you call the functions directly, then your program will not load on Win98.
What you can do is use LoadLibrary() / GetProcAddress() to get a pointer to GetFileTime() / SetFileTime(). On Win98 this will fail, giving you a null pointer which you can test for and ignore. On 2000 and later you will get a pointer which yo... |
334,780 | 334,781 | Are goto and destructors compatible? | This code leads to undefined behavior:
void some_func() {
goto undefined;
{
T x = T();
undefined:
}
}
The constructor is not called.
But what about this code? Will the destructor of x be called? I think it will be, but I want to be sure. :)
void some_func() {
{
T x = T();
goto out;
}
out... | Yes, destructors will be called as expected, the same as if you exited the scope early due to an exception.
Standard 6.6/2 (Jump statements):
On exit from scope (however accomplished), destructors are called for all constructed objects with automatic storage duration that are declared in that scope, in the reverse ord... |
334,813 | 334,819 | Do parameter or return type implicit conversions take priority in C++? | If I have the code:
int f(int a) { return a; }
double f(double g) { return g; }
int main()
{
int which = f(1.0f);
}
Which overload of f is called, and why?
| The return type is not considered for overload purposes at all, thus you'll get the double version.
|
334,856 | 334,873 | Are there benefits of passing by pointer over passing by reference in C++? | What are the benefits of passing by pointer over passing by reference in C++?
Lately, I have seen a number of examples that chose passing function arguments by pointers instead of passing by reference. Are there benefits to doing this?
Example:
func(SPRITE *x);
with a call of
func(&mySprite);
vs.
func(SPRITE &x);
w... | A pointer can receive a NULL parameter, a reference parameter can not. If there's ever a chance that you could want to pass "no object", then use a pointer instead of a reference.
Also, passing by pointer allows you to explicitly see at the call site whether the object is passed by value or by reference:
// Is mySprit... |
334,882 | 335,289 | Must default function parameters be constant in C++? | void some_func(int param = get_default_param_value());
| Default parameter can be a subset of the full set of expressions. It must be bound at compile time and at the place of declaration of the default parameter. This means that it can be a function call or a static method call, and it can take any number of arguments as far as they are constants and/or global variables or ... |
334,896 | 2,552,230 | Clrdump (C++) error LNK2019: unresolved external symbol __imp__RegisterFilter@8 referenced in function _main | I am using a makefile system with the pvcs compiler (using Microsoft Visual C++, 2008 compiler) and I am getting several link errors of the form:
error LNK2019: unresolved external symbol __imp__RegisterFilter@8 referenced in function _main
This is happening DESPITE using the extern "C" declaration, viz.:
extern "C" ... | I was creating a simple Win32 c++ application in VS2005 and I was getting this error:
LNK2019: unresolved external symbol __imp__somefunction
This application was using property sheets, hence it required this header (prsht.h).
The solution to my problem was as follows: in program Properties→Configuration Properties→Li... |
334,952 | 344,284 | How can I find the selected item in a QTreeWidget? | I have a class that inherits QTreeWidget. How can I find the currently selected row?
Usually I connect signals to slots this way:
connect(myButton, SIGNAL(triggered(bool)), this, SLOT(myClick()));
However, I can't find anything similar for QTreeWidget->QTreeWidgetItem.
The only way I found is to redefine the mousePres... | Using the itemClicked() signal will miss any selection changes made using the keyboard. I'm assuming that's a bad thing in your case.
|
335,085 | 490,131 | Hosting CLR - Bad parameters | I'm trying to host the CLR inside my C++ application and I'm having problems invoking the entry point of the managed application.
The entry point is defined as usual:
static void Main(string[] args)
And here's the actual C++ code:
CComPtr<_MethodInfo> entryPoint;
hr = assembly->get_EntryPoint(&entryPoint); // this wor... | Shouldn't the second parameter to SafeArrayCreateVector be 0 in both cases? MSDN lists that value as "The lower bound for the array. Can be negative."
|
335,273 | 342,212 | How to Create a Gdiplus::Bitmap from an HBITMAP, retaining the alpha channel information? | When I create a new Gdiplus::Bitmap using the Bitmap::FromHBITMAP function,
the resulting Bitmap is opaque - none of the partial transparency from the original HBITMAP is preserved.
Is there a way to create a Gdiplus::Bitmap from an HBITMAP which brings across the alpha channel data?
| It turns out that GDI+ never brings across the alpha channel when creating a Bitmap from an HBITMAP.
The answer is to:
Use GetObject passing in a BITMAP and the HBITMAP, to get the width and height (and if the input bitmap is a DIB, the pixel data) of the input HBITMAP.
Create a Bitmap of the correct size with 32 bit ... |
335,330 | 335,391 | Using boost::shared_ptr in a library's public interface | We have a C++ library that we provide to several different clients. Recently we made the switch from using raw pointers in the public interface to using boost::sharedptr instead. This has provided an enormous benefit, as you might guess, in that now the clients no longer have to worry about who needs to delete what and... | shared_ptr<> is part of the language, as of the release of TR1.
See: (TR1)
|
335,378 | 335,385 | How do you flag code so that you can come back later and work on it? | In C# I use the #warning and #error directives,
#warning This is dirty code...
#error Fix this before everything explodes!
This way, the compiler will let me know that I still have work to do. What technique do you use to mark code so you won't forget about it?
| Mark them with // TODO, // HACK or other comment tokens that will show up in the task pane in Visual Studio.
See Using the Task List.
|
335,408 | 335,426 | Where does Visual Studio look for C++ header files? | I checked out a copy of a C++ application from SourceForge (HoboCopy, if you're curious) and tried to compile it.
Visual Studio tells me that it can't find a particular header file. I found the file in the source tree, but where do I need to put it, so that it will be found when compiling?
Are there special directori... | Visual Studio looks for headers in this order:
In the current source directory.
In the Additional Include Directories in the project properties (Project -> [project name] Properties, under C/C++ | General).
In the Visual Studio C++ Include directories under Tools → Options → Projects and Solutions → VC++ Directories.
... |
335,494 | 335,510 | How do you find the least optimized parts of a program? | Are there any tools to give some sort of histogram of where most of the execution time of the program is spent at?
This is for a project using c++ in visual studio 2008.
| The name you're after is a profiler. Try Find Application Bottlenecks with Visual Studio Profiler
|
335,839 | 335,850 | Can you really have a function/method without a body but just a try/catch block? | Note that this function does not have a "{" and "}" body. Just a try/catch block:
void func( void )
try
{
...
}
catch(...)
{
...
}
Is this intentionally part of C++, or is this a g++ extension?
Is there any purpose to this other than bypass 1 level of {}?
I'd never heard of this until I ran into http://stupef... | Yes, it is standard. Function try blocks, as they're called, aren't that much use for regular functions, but for constructors, they allow you to catch exceptions thrown in the initialiser list.
Note that, in the constructor case, the exception will always be rethrown at the end of any catch blocks.
|
336,475 | 336,543 | Rolling my own exceptions | I am writing some new code that will throw a custom exception - I want to include an error string and a status code. Which class should be exception derive from? std::exception? std::runtime_error? Any other 'gotchas' to worry about? I'm thinking of something like the following:
class MyException : public std::exce... | Boost has a great document on error and exception handling which talks about common gotchas and how to properly inherit from std::exception(s).
|
336,585 | 336,621 | What does a const pointer-to-pointer mean in C and in C++? | I know the rule-of-thumb to read declarations right-to-left and I was fairly sure I knew what was going on until a colleague told me that:
const MyStructure** ppMyStruct;
means "ppMyStruct is a pointer to a const pointer to a (mutable) MyStructure" (in C++).
I would have thought it meant "ppMyStruct is a pointer to a ... | Your colleague is wrong. That is a (non-const) pointer to a (non-const) pointer to a const MyStructure. In both C and C++.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.