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;
Do something once
}
return some int...
}
EDIT: Does the "mutable" keyword play a role here?
|
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 talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.
This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)
|
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 number, strings and data vectors. The data vectors can often be many megabytes large.
I'm worried that text/xml-based ways of doing it is too slow and I really don't want to write this myself since problems like string encoding and number endianess can make it way more complicated than it looks on the surface.
I've been looking a bit at protocol buffers and boost.serialize. According to the documents protocol buffers seems to care much about performance.
Boost seems somewhat more lightweight in the sense that you don't have an external language for specifying the data format which I find quite convenient for this particular project.
So my question comes down to this: does anyone know if the boost serialization is fast for the typical use case I described above?
Also if there are other libraries that might be right for this, I'd be happy to hear about them.
|
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 this possible or should I use dynamic arrays? Thanks!
|
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) {
a = new int[size];
}
~Test() { delete [] a; }
private:
Test(const Test& other);
Test& operator=(const Test& other);
};
|
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! Thanks
class CFileInfo
{
public:
std::string m_PackLine;
std::string m_FileDateTime;
int m_NumDownloads;
};
void main()
{
CFileInfo packInfo;
vector<CFileInfo, CFileInfo&> unsortedFiles;
vector<CFileInfo, CFileInfo&>::iterator Iter;
packInfo.m_PackLine = "Sample Line 1";
packInfo.m_FileDateTime = "06/22/2008 04:34";
packInfo.m_NumDownloads = 0;
unsortedFiles.push_back(packInfo);
packInfo.m_PackLine = "Sample Line 2";
packInfo.m_FileDateTime = "12/05/2007 14:54";
packInfo.m_NumDownloads = 1;
unsortedFiles.push_back(packInfo);
for (Iter = unsortedFiles.begin(); Iter != unsortedFiles.end(); Iter++ )
{
cout << " " << *Iter; // !!! THIS IS WHERE I GET STUMPED
// How do I output values of the object members?
}
} // end main
|
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 parentheses around *Iter, since the member-access operator binds thighter otherwise.
On a side-node, make your main function return int instead of void. making it return void is not valid in C++.
You declare the vector like this:
vector<CFileInfo, CFileInfo&> unsortedFiles;
The second argument to vector should be another thing. It's not needed for your code to give the vector a second argument at all. Just use this:
vector<CFileInfo> unsortedFiles;
Another thing i noticed is you increment the iterator using Iter++ (called postfix increment). For iterators, always prefer ++Iter, which is called prefix increment.
|
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 QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
};
#endif
// file.c
#include "tableModel.h"
TableModel::TableModel(QObject *parent)
: QAbstractTableModel(parent){}
int TableModel::rowCount(const QModelIndex & ) const
{ return 1; }
int TableModel::columnCount(const QModelIndex & ) const
{ return 1;}
when I compile I get:
In function TableModel':
/partd/unusedsvn/unusedpkg/iface/tableModel.cpp:4: undefined reference tovtable for TableModel'
/partd/unusedsvn/unusedpkg/iface/tableModel.cpp:4: undefined reference to vtable for TableModel'
collect2: ld returned 1 exit status
does anybody got the same trouble??
|
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 host UDP client on internet?
Is there any other way to do that?
any suggestions?
|
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% loss),
Approximate round trip times in milli-seconds:
Minimum = 174ms, Maximum = 174ms, Average = 174ms
|
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 _M_impl". There appears to be a nice debug toolset here but it also relies on _M_impl.
|
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_current = 0x300340
}
(gdb) p $1._M_current->c_str()
$2 = 0x3002fc "Hello"
(gdb) p $1._M_current +1
$3 = (string *) 0x300344
(gdb) p $3->c_str()
$4 = 0x30032c "world"
|
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 (declared in header
ctime) is different each second, which
is distinctive enough for most
randoming needs.
Unixtime isn't distinctive enough for my application. What's a better way to initialize this? Bonus points if it's portable, but the code will primarily be running on Linux hosts.
I was thinking of doing some pid/unixtime math to get an int, or possibly reading data from /dev/urandom.
Thanks!
EDIT
Yes, I am actually starting my application multiple times a second and I've run into collisions.
|
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 not every time you call rand()!
Side Note:
NOTE: There is a discussion in the comments below about this being insecure (which is true, but ultimately not relevant (read on)). So an alternative is to seed from the random device /dev/random (or some other secure real(er) random number generator). BUT: Don't let this lull you into a false sense of security. This is rand() we are using. Even if you seed it with a brilliantly generated seed it is still predictable (if you have any value you can predict the full sequence of next values). This is only useful for generating "pseudo" random values.
If you want "secure" you should probably be using <random> (Though I would do some more reading on a security informed site). See the answer below as a starting point: https://stackoverflow.com/a/29190957/14065 for a better answer.
Secondary note: Using the random device actually solves the issues with starting multiple copies per second better than my original suggestion below (just not the security issue).
Back to the original story:
Every time you start up, time() will return a unique value (unless you start the application multiple times a second). In 32 bit systems, it will only repeat every 60 years or so.
I know you don't think time is unique enough but I find that hard to believe. But I have been known to be wrong.
If you are starting a lot of copies of your application simultaneously you could use a timer with a finer resolution. But then you run the risk of a shorter time period before the value repeats.
OK, so if you really think you are starting multiple applications a second.
Then use a finer grain on the timer.
int main()
{
struct timeval time;
gettimeofday(&time,NULL);
// microsecond has 1 000 000
// Assuming you did not need quite that accuracy
// Also do not assume the system clock has that accuracy.
srand((time.tv_sec * 1000) + (time.tv_usec / 1000));
// The trouble here is that the seed will repeat every
// 24 days or so.
// If you use 100 (rather than 1000) the seed repeats every 248 days.
// Do not make the MISTAKE of using just the tv_usec
// This will mean your seed repeats every second.
}
|
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 HTML is normally fairly simple, but customers can create their own templates, so a "good range" of HTML should be supported.
Should be accessible for an automated process from C++ - DLL / COM / external executable with command line support are all fine.
Commercial is fine, but in the thousands is not an option right now.
So, which components do you know or can you recommend?
|
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 it modifies the next character. The token is output accordingly as the escape character or some other token (such as a tab or a newline) to the next part of the compiler (the parser). The state machine can group several characters into a token.
|
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 -o -name \*.h | xargs awk '!/^[{[:space:]}]*$/' | wc -l
|
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 reason to have the scrollbar visible all the time in a list control anyways?
|
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 compilation flags globally but can't find much documentation on how to use those macro (do you have any pointer to such a documentation ?).
Thanks in advance
|
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 rules to all Makefile.ams by just editing this file.
(2) Another solution would be to set these variables globally in your configure.ac (the name configure.in has been deprecated long ago), as in :
...
AC_SUBST([AM_CXXFLAGS], [-fpic -Wall -Wextra])
...
Then you don't even have to say anything in your Makefile.ams, they automatically inherit this global definition. The drawback is that you can't opt-out easily (with the first solution it's easy to decide not to include common.mk) and the dependency is not really explicit to third-party people (when they read the Makefile.am they have no hint about where the flags may come from).
(3) A third solution would be to do as orsogufo suggested: overwriting the user variable CXXFLAGS in configure.ac. I would advise against it, because it defeats one of the features of the GNU Build System: users are allowed to override this variable at make-time. For instance you may want to type
make CXXFLAGS='-O0 -ggdb'
when debugging a piece of code, and this will overwrite any definition of CXXFLAGS (but
not those in AM_CXXFLAGS). To be honest, most projects fails to support this correctly because they play tricks with CXXFLAGS.
Finally, I should mention that -fpic, -Wall, and -Werror are not portable options.
Depending on the scope of your project you may want to add configure check for these (gnulib recently acquired new macros to tests for warnings flags, and libtool can be used to build shared libraries).
|
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
ListNodes, and then asks for a number which it should seek in the list.
Here is my code:
#include <iostream>
using namespace std;
class ListNode
{
private:
struct Node
{
int value;
Node *next;
} *lnFirst;
public:
ListNode();
int Length();
void DisplayList();
void Insert( int num );
bool Contains( int num );
int GetValue( int num );
};
ListNode::ListNode()
{
lnFirst = NULL;
}
int ListNode::Length()
{
Node *lnTemp;
int intCount = 0;
for( lnTemp=lnFirst ; lnTemp != NULL ; lnTemp = lnTemp->next )
{
intCount++;
}
return intCount;
}
void ListNode::DisplayList()
{
Node *lnTemp;
for( lnTemp = lnFirst ; lnTemp != NULL ; lnTemp = lnTemp->next )
cout<<endl<<lnTemp->value;
}
void ListNode::Insert(int num)
{
Node *lnCurrent, *lnNew;
if( lnFirst == NULL )
{
lnFirst = new Node;
lnFirst->value = num;
lnFirst->next = NULL;
}
else
{
lnCurrent = lnFirst;
while( lnCurrent->next != NULL )
lnCurrent = lnCurrent->next;
lnNew = new Node;
lnNew->value = num;
lnNew->next = NULL;
lnCurrent->next = lnNew;
}
}
bool ListNode::Contains(int num)
{
bool boolDoesContain = false;
Node *lnTemp,*lnCurrent;
lnCurrent = lnFirst;
lnTemp = lnCurrent;
while( lnCurrent!=NULL )
{
if( lnCurrent->value == num )
{
boolDoesContain = true;
return boolDoesContain;
}
lnTemp = lnCurrent;
lnCurrent = lnCurrent->next;
}
return boolDoesContain;
}
int ListNode::GetValue(int num)
{
Node *lnTemp;
int intCount = 1;
for( lnTemp=lnFirst; lnTemp != NULL; lnTemp = lnTemp->next )
{
if (intCount == num)
{
return lnTemp->value;
}
intCount++;
}
}
int main()
{
cout << "Input integers below. Input the integer -1 to stop inputting.\n\n";
ListNode lnList;
int intNode = 1, intInput = 0;
while (intInput != -1) {
cout << "Please input integer number " << intNode << ": "; cin >> intInput;
intNode++;
if (intInput != -1) { lnList.Insert(intInput); }
}
lnList.DisplayList();
cout << "\n\n";
int intListLength = lnList.Length();
cout << "Which value do you wish to recall? (Between 1 and " << intListLength << "): "; cin >> intNode;
if ( intNode >= 1 && intNode <= intListLength ) {
cout << "Value at position " << intNode << " is " << lnList.GetValue(intNode) << ".";
} else {
cout << "No such position in the list. Positions run from 1 to " << intListLength << ". You asked for " << intNode << ".";
}
cout << "\n\nCheck if the following value is in the list: "; cin >> intNode;
bool IsThere = lnList.Contains(intNode);
if (IsThere) {
cout << intNode << " is in the list.";
} else {
cout << intNode << " is not in the list.";
}
cout << "\n\n";
system("pause");
return 0;
}
Where can we improve this?
|
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;
// was this the last node?
if(next == 0) return false;
// return whether nodes after us contain the value
return next->listcontains(v);
}
};
So, you only have the head of the list, which links to the next node in turn. The tail will have next == 0;
|
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 the described problem. Once the user minimizes the keyboard it should not appear on the screen on dialog switching.
Thanks!
|
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 MSDN page linked:
The standard method of showing and
hiding the SIP (SIPShowIM) exhibits
some problems in MFC dialogs.
|
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 business rules).
All that exists (grown over several years), "works" and is used for projects.
However, compilation of projects using that library consumes a growing amount of time and it takes quite some time to locate the source for certain bugs. Fixing often causes unexpected side effects or is quite difficult, because some interdependent templates need changing. Testing is nearly impossible due to the sheer amount of functions.
Now, I would really like to simplify the architecture to use less templates and more specialized smaller classes.
Is there any proven way to go about that task? What would be a good place to start?
|
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 classes and templates, but automatically assuming that "fewer templates will make the architecture better" is flawed imo.
I'd say that templates potentially allow you to build a much cleaner architecture than you'd get without them. Simply because you can make separate classes totally independent. Without templates, classes functions which call into another class must know about the class, or an interface it inherits, in advance. With templates, this coupling isn't necessary.
Removing templates would only lead to more dependencies, not fewer.
The added type-safety of templates can be used to detect a lot of bugs at compile-time (Sprinkle your code liberally with static_assert's for this purpose)
Of course, the added compile-time may be a valid reason to avoid templates in some cases, and if you only have a bunch of Java programmers, who are used to thinking in "traditional" OOP terms, templates might confuse them, which can be another valid reason to avoid templates.
But from an architecture point of view, I think avoiding templates is a step in the wrong direction.
Refactor the application, sure, it sounds like that's needed. But don't throw away one of the most useful tools for producing extensible and robust code just because the original version of the app misused it. Especially if you're already concerned with the amount of code, removing templates will most likely lead to more lines of code.
|
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 = VARIANT_TRUE;
pXMLDoc->preserveWhiteSpace = VARIANT_TRUE;
//load markup into XML document
vtBoolResult = pXMLDoc->loadXML(markup);
//do some changes to the XML file<-
//get back string from XML doc
markup = pXMLDoc->Getxml(); //<-- this retrieves RUBBISH
At this point my string is mangled (just a few chinese characters at the start then rubbish) . Looks like an encoding issue.
I also tried the following:
_bstr_t superMarkup = _bstr_t(markup);
//did my stuff
superMarkup = pXMLDoc->Getxml();
markup = superMarkup;
but still I am getting the same result.
Even if I call GetXML() without changing anything in the xml document I still get rubbish.
At this point if I try to assign the mangled pointer to another pointer it will trow an error:
Attempted to restore write protected
memory. this is often an indication
that other memory is corrupted.
Any suggestion?
EDIT1:
I found out this is happening in relation to the size of the XML string.
If it happens on a given XML string and I reduce the size (keeping the same schema) it will work fine. Looks like MSXML2::DOMDocument40 has a limitation on size?
In detail it happens if I have more than 16407 characters. I have one more GetXML will retrieve RUBBISH - if it's <= 16407 everything works fine.
EDIT2:
Roddy was right - I was missing that _bstr_t is a class ...
Rings any bell?
Cheers
|
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 what I suggested. Again, BSTR is just a pointer, and doesn't "own" what it points to. bstr_t, on the other hand does. I think your GetXML() function is returning a bstr_t, which is then being deleted as it goes out of scope, leaving your BSTR pointing to memory that is no longer valid.
|
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 contains nothing but garbage: "0012E708" repeated all over.
In GetHolesResults I can write
outFile << "Foo" << std:endl;
and it will output correctly in outFile.
Any suggestion on what I'm doing wrong?
|
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 read/write access to the MySQL DB.
So, (1) What is the best way to access/update a MySQL database with C++?
(2) Are there any issues/things I should be aware of with a DB that has concurrent access from both PHP and C++. I'm kinda assuming that the DB looks after all that...
Thanks,
Lehane
|
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 a video than really exist)
Trust IMediaSeeking::GetDuration (it's consistent with IMediaDet, +/- one frame)
Use IMediaControl::GetState (the filtergraph remains running even if all frames have already been processed from a file)
Background:
I am doing video processing and I have a class that creates a filtergraph with a SampleGrabber. Whenever SampleGrabber::SampleCB is called, I block it with a mutex so I can run the filtergraph in pull mode. When I'm ready for another frame, I unblock the mutex in my main thread and wait for SampleGrabber::SampleCB to send me a signal that it's done. For some videos, IMediaDet::get_StreamLength tells me that the video has more frames than really exist. Once I've extracted the final frame and request one more than actually exists, the main thread then blocks forever because SampleGrabber::SampleCB will never get called again. I'd like to be able to detect when SampleGrabber::SampleCB will never be called for file sources. Applications like Windows Media Player are able to somehow do this because the GUI reports that the video has ended after the last real frame, so apparently there's a way to do this.
EDIT:
I'm using WaitForSingleObject to implement the main thread blocking. The workaround that I've been using so far is to do what Greg suggested: have a finite timeout. Unfortunately, this gets a little tricky. The wait can fail for many reasons such as a true eof, slow network filesystem, lost network connection, slow decoder, etc.
|
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 separated by a ":".
I know I can find the position of the first ":" by find(), but I really don't know how to progress through the string, for each thing and put it into it's own string / int.
The actual input from the file looks something like this:
A:PEP:909:Inventory Item
A is going to be command I have to execute... so that will be a string.
PEP is a key, needs to be a string.
909 is an int.
and the last is a string.
So what I think I want to do is have 3 string var's, and 1 int and get all those things put into their respective variables.
So I think I'll end up wanting to conver this C++ string to a C string so I can use atoi to convert the one section to an int.
|
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( ':' ) to find the first instance, and then use find( ':', firstIndex+1 ) to find the next instances, where firstIndex is the value returned by the first call to 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 console just display "TEST IT!".
As far as I know, static member methods shouldn't be called on instanced object.
Am I wrong? Is this code correct from the standard point of view?
If it's correct, why is that? I can't find why it would be allowed, or maybe it's to help using "static or not" method in templates?
|
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 class member access syntax (5.2.5) to refer
to a static member. A static member
may
be referred to using the class member access syntax, in which
case the object-expression is
evaluated.
class process {
public:
static void reschedule();
};
process& g();
void f()
{
process::reschedule(); // OK: no object necessary
g().reschedule(); // g() is called
}
|
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",
msiOpenDatabaseModeTransact);
}
I think the reason is that behind the scene, there is MsiOpenDatabase(), which
take a LPCTSTR as second argument.
This second argument can be MSIDBOPEN_TRANSACT whose definition is
#define MSIDBOPEN_TRANSACT (LPCTSTR)1
I do not know if it is possible to give a variant with the good inner type as second argument. The _variant_t constructor does many checks, so I can't disguise an int into
a char* so easily.
Has anyone tried to use this method in C++?
Edit:
My version of msi.dll is 3.1.4000.2805, my system is XP SP 2, and the code is supposed to run on any machine with XP or Vista.
urls to MSDN articles are welcome.
On the same machine, the call to the low-level equivalent:
MsiOpenDatabase("c:\\foo\\bar.msi", MSIDBOPEN_TRANSACT);
works perfectly.
|
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 a_;
int d_;
bool b_;
std::string f_;
int c_;
.
..
};
Or do you simply have them in the order they were added?
|
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 that will save me writing code).
string stringtobesplit = "AA/BB-CC")
vector<string> tokens;
boost::split(tokens, stringtobesplit, boost::is_any_of("/-"));
// tokens now holds 3 items: AA BB CC
I am going to start looking through boost documentation looking for other functions that I will be able to use regularly, but I feel that it will be very easy to miss things.
What boost functions do you use most / would hate not to have?
|
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 anyone could suggest reading materials that helped them and any disciplines which should be encouraged?
Thanks!
|
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 it was not just a style preference rather there was a technical reason such as efficiency. The SGI STL reference simply says: "Strictly speaking, this member function is unnecessary: it exists only for convenience."
Can anybody tell me that reason, or am I just dreaming that there is one?
|
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_type(key,value));
if ( ! res.second ) {
cout << "key " << key << " already exists "
<< " with value " << (res.first)->second << endl;
} else {
cout << "created key " << key << " with value " << value << endl;
}
For most of my apps, I usually don't care if I'm creating or replacing, so I use the easier to read map[key] = 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, it shouldn't be used unless you need its extra flexibility. A CPropertySheet can also be used as a wizard by setting a few flags.
The following is an example of using a CTabCtrl:
aCTabCtrl Example http://rabien.com/image/xcolordialog1.png
If this was a CPropertySheet, then it would not be possible to put the sample colors outside of the tabs. (And the buttons would have to be at the bottom)
Tutorial on CPropertySheet
Tutorial on CTabCtrl
|
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. (...)
erase_if(myVec, myPred);
|
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 without creating class object,
or an anonymous namespace,
or maybe I need something more complicated in terms of architecture and design?
Actually, the language I am writing in is C++, but I think this question doesn't depend on what the language of development is.
|
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 differences between these solutions:
In classes, you can set some functions as private, protected or public. For example you may have private functions to do common things which are needed by your public functions.
Namespaces can be extended and their definition spread in several files.
Classes can be subclassed (and so their functionality can be extended too). You can have a model with protected static functions and client classes subclassing this class for better encapsulation.
|
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. How would I do this? I was thinking of creating one thread per row of pixels.
I have several requirements:
Executable size must be minimized. In other words, I can't use massive libraries. What's the most light-weight, portable threading library for C/C++?
Executable size must be minimized. I was thinking of having a function forEachRow(fp* ) which runs a thread for each row, or even a forEachPixel(fp* ) where fp operates on a single pixel in its own thread. Which is best?
Should I use normal functions or functors or functionoids or some lambda functions or ... something else?
Some operations use optimizations which require information from the previous pixel processed. This makes forEachRow favorable. Would using forEachPixel be better even considering this?
Would I need to lock my read-only and write-only arrays?
The input is only read from, but many operations require input from more than one pixel in the array.
The ouput is only written once per pixel.
Speed is also important (of course), but optimize executable size takes precedence.
Thanks.
More information on this topic for the curious: C++ Parallelization Libraries: OpenMP vs. Thread Building Blocks
|
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 point, using too many threads can actually make the parallel version slower than just using a linear algorithm. The optimal number of threads is a function of the number of cpus/cores available, and the percentage of time each thread spends blocked on things like I/O. Take a look at this article by Herb Sutter for some discussion on parallel performance gains.
OpenMP lets you easily adapt the number of threads created to the number of CPUs available. Using it (especially in data-processing cases) often involves simply putting in a few #pragma omps in existing code, and letting the compiler handle creating threads and synchronization.
In general - as long as data isn't changing, you won't have to lock read-only data. If you can be sure that each pixel slot will only be written once and you can guarantee that all the writing has been completed before you start reading from the result, you won't have to lock that either.
For OpenMP, there's no need to do anything special as far as functors / function objects. Write it whichever way makes the most sense to you. Here's an image-processing example from Intel (converts rgb to grayscale):
#pragma omp parallel for
for (i=0; i < numPixels; i++)
{
pGrayScaleBitmap[i] = (unsigned BYTE)
(pRGBBitmap[i].red * 0.299 +
pRGBBitmap[i].green * 0.587 +
pRGBBitmap[i].blue * 0.114);
}
This automatically splits up into as many threads as you have CPUs, and assigns a section of the array to each thread.
|
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++)
{
selectSql += columns[z]._name;
selectSql += ", ";
}
selectSql = selectSql(0, selectSql.len() - 2);
selectSql += "FROM some-table";
Another technique looks something like this
selectSql = "SELECT ";
for (z = 0; z < columns.size(); z++)
{
selectSql += columns[z]._name;
if (z < columns.size() - 1)
selectSql += ", ";
}
selectSql += "FROM some-table";
I am not particularly enthralled by either of these implementations.
I am interesting in hearing ideas for other ways to address this issue, with an eye toward making the code easier to read/understand/maintain.
What alternate techniques are available?
|
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;
}
selectSql += " FROM some-table";
|
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_LUMINANCE mode (one 8 bit channel represents brightness of all 3 channels and full alpha), but it is IMO vastly ineffective, because the onlu values in the array are 0x00 and 0xFF.
Can I (and how) use simple one-bit per pixel array of booleans instead somehow? The excessive array size slows down any other operations on the array :(
|
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. Load 8 1 bit per pixel textures as one 8 bit Alpha-only texture (image 1 gets loaded into bit 1, image 2 into bit 2 and so on). Once you've done that you can "address" each of the sub-textures using the alpha-test feature and a bit of texture environment programming to turn alpha into a color.
This will of only work if you have 8 1 bit per pixel textures and tricky to get right though.
|
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;
string fileName("C:\\Development\\Visual Studio 2008\\Projects\\OpenGL_Test\\Crate.bmp");
// Use LoadImage() to get the image loaded into a DIBSection
HBITMAP hBitmap = (HBITMAP)LoadImage( NULL, (LPCTSTR)const_cast<char*>(fileName.c_str()), IMAGE_BITMAP, 0, 0,
LR_CREATEDIBSECTION | LR_DEFAULTSIZE | LR_LOADFROMFILE );
customTexture = new GLubyte[3*256*256]; // size should be the size of the .bmp file
GetBitmapBits(hBitmap, 3*256*256, (LPVOID) customTexture);
GetBitmapDimensionEx(hBitmap,&szBitmap);
What happens is the call to LoadImage seems to be returning Undefined Value (NULL? I am not able to figure out if it's actually loading the bmp or not - a bit confused).
At the moment I am converting bmps to raw then it's all easy.
Anyone has any better and cleaner snippet?
|
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 other file (important: open it in binary mode, i.e. with the "rb" option using fopen or the ios::binary flag using the C++ ifstream), read in the bitmap dimensions, and read in the raw pixel data.
|
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 have any references?
As a secondary bonus question, what open source Python program would you suggest looking at for clean design, commenting, and use of the language as a point of reference for study?
Thanks in advance.
|
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 learning. I want to be able to take advantage of the things that make the language special and use that knowledge to expand my ways of thinking and solving problems. I don't think I would get the same sort of insights from a tutorial that was framed in the context of another language. If you can learn your first language without a tutorial geared towards something you already know you should be able to pick up a second language the same way (and in my experience, the more languages you know the easier it is to learn new ones).
With that said, I would recommend The Python Tutorial as a good, quick, and easy way to get going with Python and Dive Into Python as a more complete introduction, also available for free here. I would also agree with what others have said regarding looking at the code for the standard libraries as a source of good examples and design practices, the standard python libraries are pretty clean and easy to read.
|
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 seems not portable through differents systems.
|
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 = (pkt *) p_b;
if (pkt_a->alfa > pkt_b->alfa) return 1;
if (pkt_a->alfa < pkt_b->alfa) return -1;
if (pkt_a->x > pkt_b->x) return 1;
if (pkt_a->x < pkt_b->x) return -1;
return 0;
}
sort(wektor.begin(), wektor.end(), porownaj); // this makes loads of errors on compile time
What is to correct? How to use properly std::sort in that case?
|
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 invocation without a third argument will work; or you can rewrite your above function to accomplish the same thing.
Notice that you have to use strong typing in the arguments.
Additionally, it's good not to use a function here at all. Instead, use a function object. These benefit from inlining.
struct pkt_less {
bool operator ()(pkt const& a, pkt const& b) const {
if (a.alfa < b.alfa) return true;
if (a.alfa > b.alfa) return false;
if (a.x < b.x) return true;
if (a.x > b.x) return false;
return false;
}
};
// Usage:
sort(wektor.begin(), wektor.end(), pkt_less());
|
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 provide such information - I write my program in c++ and have troubles to find such a lib.
Should I dig in the registry for this information?
Many Thanks,
ofer
|
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'
This is apparently because this symbol is defined in libstdc++, which is missing in a free-standing environment. Fixing the problem simply requires defining this symbol somewhere:
void *__gxx_personality_v0;
Which is nice, but I don't like things that just magically work... So the question is, what is the purpose of this symbol?
|
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 probably because nothing is throwing an exception. When something tries to throw an exception, then you will see it misbehave.
Of course, if nothing is using exceptions, you can disable them with -fno-exceptions (and if nothing is using RTTI, you can also add -fno-rtti). If you are using them, you have to (as other answers already noted) link with g++ instead of gcc, which will add -lstdc++ for you.
|
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 documentation.
In a quick-and-dirty test I did with g++ 4.0.1 (i686-apple-darwin8-g++-4.0.1 to be specific), the result is that terminate() is called, which kills the entire program. The code I used follows:
#include <stdio.h>
#include <pthread.h>
void *threadproc(void *x)
{
throw 0;
return NULL;
}
int main(int argc, char **argv)
{
pthread_t t;
pthread_create(&t, NULL, threadproc, NULL);
void *ret;
pthread_join(t, &ret);
printf("ret = 0x%08x\n", ret);
return 0;
}
Compiled with g++ threadtest.cc -lpthread -o threadtest. Output was:
terminate called after throwing an instance of 'int'
|
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 believe this will be in the Windows DDK somewhere, but where do I get started? Any pointers will be highly appreciated.
|
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, Handle(), which would be called by the networking engine when one of these packets is received so that it can do it's job, several get/set functions which would read and set fields in the array of data.
So I have two problems:
The (abstract) Packet class would need to be copyable and assignable, but without slicing, keeping all the fields of the derived class. It may even be possible that the derived class will have no extra fields, only function, which would work with the array on the base class. How can I achieve that?
When serializing, I would give each sub-class an unique numeric ID, and then write it to the stream before the sub-class' own serialization. But for unserialization, how would I map the read ID to the appropriate sub-class to instanciate it?
If anyone want's any clarifications, just ask.
-- Thank you
Edit: I'm not quite happy with it, but that's what I managed:
Packet.h: http://pastebin.com/f512e52f1
Packet.cpp: http://pastebin.com/f5d535d19
PacketFactory.h: http://pastebin.com/f29b7d637
PacketFactory.cpp: http://pastebin.com/f689edd9b
PacketAcknowledge.h: http://pastebin.com/f50f13d6f
PacketAcknowledge.cpp: http://pastebin.com/f62d34eef
If someone has the time to look at it and suggest any improvements, I'd be thankful.
Yes, I'm aware of the factory pattern, but how would I code it to construct each class? A giant switch statement? That would also duplicade the ID for each class (once in the factory and one in the serializator), which I'd like to avoid.
|
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 packet is received, its data can either be copied out, or thrown away. So a assignment operator is not required. Make the assignment operator private and don't define it, which will effectively forbid assigning packages.
For de-serialization, you use the factory pattern: create a class which creates the right message type given the message id. For this, you can either use a switch statement over the known message IDs, or a map like this:
struct MessageFactory {
std::map<Packet::IdType, Packet (*)()> map;
MessageFactory() {
map[StatePacket::Id] = &StatePacket::createInstance;
// ... all other
}
Packet * createInstance(Packet::IdType id) {
return map[id]();
}
} globalMessageFactory;
Indeed, you should add check like whether the id is really known and such stuff. That's only the rough idea.
|
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 have a static variable in my header to count the number of objects of a particular class. Whenever I construct the object I increment this variable. Then in my destructor I subtract 1 from that variable, check if it's 0 (meaning it's the last object) and do something. The value seems to be off sometimes, I'm not sure why. I do have random calls in my application but I don't see why that would effect what I have described above, thanks. Any help or insight is appreciated!
[Update]: have a base class, which contains the destructor.. which is implemented in the header, then I have two derived classes, which in their constructor increment the static var.. so what can I do?
What I am trying to do is the following: In my header I have this:
class A {
public:
virtual ~A() {
count --;
if (count == 0) { /* this is the last one, do something */ }
}
class B : public A {
public:
B();
}
Then in Class B I have
B::B() {
count++;
}
Where can I define count so I don't get misleading counts? Thanks.
|
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 contains the code for class A.
int A::count(0);
You need to do this, because the header file declared that there was going to be a variable named count, but didn't allocate any storage for it. If you didn't put it in a source file, the linker would complain that it wasn't found.
|
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<DnaPairT> DnaDatabaseT;
// ....
for(DnaDatabaseT::iterator it = database.begin();
it != database.end(); it++)
{
int score = it->second.query(query);
it->first = score;
}
The reason I am doing this is so that I can sort them by score later. I have tried maps and received a compilation error about modifying first, but is there perhaps a better way than this to store all the information for sorting later?
|
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 be allowed because that value is part of the map's inner workings.
As stated by dribeas:
In maps you cannot change first as it would break the invariant of the map being a sorted balanced tree
edit: To answer your second question, I see nothing at all wrong with the way you are structuring the data, but I would have the database hold pointers to DnaPairT objects, instead of the objects themselves. This would dramatically reduce the amount of memory that gets copied around during the sort procedure.
#include <vector>
#include <utility>
#include <algorithm>
typedef std::pair<int, DnaDatabaseRow> DnaPairT;
typedef std::vector<DnaPairT *> DnaDatabaseT;
// ...
// your scoring code, modified to use pointers
void calculateScoresForQuery(DnaDatabaseT& database, queryT& query)
{
for(DnaDatabaseT::iterator it = database.begin(); it != database.end(); it++)
{
int score = (*it)->second.query(query);
(*it)->first = score;
}
}
// custom sorting function to handle DnaPairT pointers
bool sortByScore(DnaPairT * A, DnaPairT * B) { return (A->first < B->first); }
// function to sort the database
void sortDatabaseByScore(DnaDatabaseT& database)
{
sort(database.begin(), database.end(), sortByScore);
}
// main
int main()
{
DnaDatabaseT database;
// code to load the database with DnaPairT pointers ...
calculateScoresForQuery(database, query);
sortDatabaseByScore(database);
// code that uses the sorted database ...
}
The only reason you might need to look into more efficient methods is if your database is so enormous that the sorting loop takes too long to complete. If that is the case, though, I would imagine that your query function would be the one taking up most of the processing time.
|
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 probably make it hard for users to hit the right keys
It's too "ugly" for the customer, who'd like a slicker on-screen keyboard that integrates better with the custom look-and-feel of the application so far.
Therefore I'm looking for alternatives for the Windows On-Screen Keyboard (osk.exe) that allow a larger size of buttons and can be skinned. Ideally it would have a BSD-like license for unburdened integration into a commercial app, but a royalty-free commercial solution could work.
Do you know of any such applications, or have you had a similar project where you solved the issue in another way?
|
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 misspelt. This by itself would have produced a warning about "function does not return a value", but I guess I was on autopilot and added a "void" return type to 'fix' this.
Now, the bugfix was easy, but my question is this:-
What techniques could I use to prevent this type of bug recurring?
Some languages require an explicit "constructor" keyword, which should make this problem obvious. Unit testing, obviously should also have caught it. What else can I do?
|
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 resources...
Compiling...
Main.cpp
winsock.cpp
Linking...
LINK : warning LNK4098: defaultlib "LIBCMTD" conflicts with use of other libs; use /NODEFAULTLIB:library
Main.obj : error LNK2001: unresolved external symbol _socket_dontblock
Debug/MyApp.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
MyApp.exe - 2 error(s), 1 warning(s)
--------------------------------------------------------------------------
If I use /NODEFAULTLIB then I get loads of errors. The code does not actually use _socket_noblock but I can't find anything on it on the 'net. Presumably it is used by some library I am linking to but I don't know what library it is in.
--- Alistair.
|
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/mangling issues.
Compiling everything with VC9 is
currently not an option as there
appear to be some side effects.
Resolving these would be quite time
consuming.
I can modify the C++ library, however it must be compiled with VC6.
The C++ lib is essentially an OO-wrapper for another C library. The VC9-app uses some static functions as well as some non-static.
While the static functions can be handled with something like
// Header file
class DLL_API Foo
{
int init();
}
extern "C"
{
int DLL_API Foo_init();
}
// Implementation file
int Foo_init()
{
return Foo::init();
}
it's not that easy with the non-static methods.
As I understand it, Chris Becke's suggestion of using a COM-like interface won't help me because the interface member names will still be decorated and thus inaccessible from a binary created with a different compiler. Am I right there?
Would the only solution be to write a C-style DLL interface using handlers to the objects or am I missing something?
In that case, I guess, I would probably have less effort with directly using the wrapped C-library.
|
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 { /* ... */ };
extern "C" IFoo * __stdcall GetFoo() { return new CFoo(); }
This will work fine, provided that you're using a compiler that generates compatible vtables. Microsoft C++ has generated the same format vtable since (at least, I think) MSVC6.1 for DOS, where the vtable is a simple list of pointers to functions (with thunking in the multiple-inheritance case). GNU C++ (if I recall correctly) generates vtables with function pointers and relative offsets. These are not compatible with each other.
|
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::SomeFunc(int n)
{
if (n == SOME_VALUE)
{
...
}
}
The question arises out of making some code thread-safe. In the above example I need to be certain that SOME_VALUE is initialized before SomeFunc is called for the first time.
|
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 initialized before any
dynamic initialization takes place.
Objects with static storage duration
defined in namespace scope in the same
translation unit and dynamically
initialized shall be initialized in
the order in which their definition
appears in the translation unit.
This effectively means, even when another translation unit calls your SomeFunc function from outside, your SOME_VALUE constant will always be correctly initialized, because it's initialized with a constant expression.
The only way for your function being called early (before main) is while initializing an object with dynamic initialiation. But by that time, according to the standard quote, the initialization of your POD variable is already done.
|
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 application and I want to talk to a C++ API for a map that lives in the application, not a web interface. Ideally I don't want a separate server, either, and any server MUST run locally (not on the Internet). What canned map package or graphics library should I use to do this? I have no graphics programming experience.
This is strictly 2D, so I don't think something like Google Earth or WorldWind would be appropriate. Good vector graphics support would be cool, and easy drawing of bitmaps is important.
All the canned options seem web oriented. SDL is about all I know of for flexible canvas programming, but it seems like making my own map would be a lot of work for what is probably a common problem. Is there anything higher level? Maybe there's a way to interact with an adobe Flash object? I'm fairly clueless.
|
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 replacement to the MapObjects libraries
|
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 you point me in the right direction?
Worst case scenario, I suppose I can call the Rijndael algorithm from .NET using PInvoke but I would rather have a native solution.
|
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 Notes
We avoid CAPICOM like the plague as the deployment nightmares that come with it are not worth the hassle.
Byte order on the .NET side can come into play at times. For example, to consume a key that is generated on the C++ (CryptoAPI) side, you need to reverse the byte array prior to using it within the TripleDESCryptoServiceProvider.
If you would like more details please leave a comment and I can give more. Happy crypto!
|
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 extra information when an error occurs (it can be checked by calling GetLastError)... but what are some things I should consider when I'm using these functions?
I'm working with a windows application, so cross-platform compatibility is already out of the question.
I have gone through the msdn documentation and I just can't understand, for example, why anybody would decide to use _beginthread instead of CreateThread or vice versa.
Cheers!
Update:
OK, thanks for all the info, I've also read in a couple of places that I can't call WaitForSingleObject() if I used _beginthread(), but if I call _endthread() in the thread shouldn't that work? What's the deal there?
|
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 library usable & consistent in the new thread.
In C++ you should almost certainly use _beginthreadex() unless you won't be linking to the C runtime library at all (aka MSVCRT*.dll/.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 whatever it's called.)
Furthermore, can I use Unicode for strings? For example:
Wstring str=L"Strange chars: â Țđ ě €€";
|
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 way to name other characters using a way called universal-character-names and look like \uffff or \Uffffffff and can be used to refer to Unicode characters. A subset of them are usable in identifiers (listed in Annex E).
This is all nice, but the mapping from characters in the file, to source characters (used at compile time) is implementation defined. This constitutes the encoding used. Here is what it says literally (C++98 version):
Physical source file characters are
mapped, in an implementation-defined
manner, to the basic source character
set (introducing new-line characters
for end-of-line indicators) if
necessary. Trigraph sequences (2.3)
are replaced by corresponding
single-character internal
representations. Any source file
character not in the basic source
character set (2.2) is replaced by the
universal-character-name that des-
ignates that character. (An
implementation may use any internal
encoding, so long as an actual
extended character encountered in the
source file, and the same extended
character expressed in the source file
as a universal-character-name (i.e.
using the \uXXXX notation), are
handled equivalently.)
For gcc, you can change it using the option -finput-charset=charset. Additionally, you can change the execution character used to represet values at runtime. The proper option for this is -fexec-charset=charset for char (it defaults to utf-8) and -fwide-exec-charset=charset (which defaults to either utf-16 or utf-32 depending on the size of wchar_t).
|
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. I want to cast the activeWidget pointer from GUI_BASE to GUI_TEXTBOX. I assume it would look something like this:
(GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget)->function();
This isn't working, because the compiler still thinks the pointer is of type GUI_BASE. The following bit of code does work, however:
GUI_TEXTBOX *textbox_pointer;
textbox_pointer = (GUI_TEXTBOX*)mainGui.activeWindow->activeWidget;
textbox_pointer->function();
I'm hoping my problem here is just a syntax issue. Thanks for the help :)
|
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 cast
|
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 part of an object's interface, and can improve encapsulation. I agree with them.
However, after recently reading this article: http://www.gotw.ca/gotw/084.htm I find myself questioning the syntax implications.
In that article, Herb proposes having a single insert, erase, and replace member, and several non-member non-friend functions of the same name.
Does this mean, as I think it does, that Herb thinks some functions should be used with the dot notation, and others as a global function?
std::string s("foobar");
s.insert( ... ); /* One like this */
insert( s , ...); /* Others like this */
Edit:
Thanks everyone for your very useful answers, however, I think the point of my question has been overlooked.
I specifically did not mention the specific case of operators, and how they retain the "natural" notation. Nor that you should wrap everything in a namespace. These things are written in the article I linked to.
The question itself was:
In the article, Herb suggests that one insert() method be a member, while the rest are non-member non-friend functions.
This implies that to use one form of insert() you have to use dot notation, while for the others, you do not.
Is it just me, or does that sound crazy?
I have a hunch that perhaps you can use a single syntax. (Im thinking how Boost::function can take a *this parameter for mem_fun).
|
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 equivalent to define it as a non-member friend function. If mixed dot/no-dot syntax bothers you then by all means make those methods friend functions instead. There's no difference.
In the future we will also be able to write polymorphic functions like this, so maybe this is the C++ way, rather than artificially trying to force free functions into the dot syntax.
|
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 question is: Is there an equivalent concept to Windows DLLs under *nix?
|
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's call it test.c and the object file created test.o). It also adds an entry into the relocation table of that object-file:
Relocation section '.rel.text' at offset 0x308 contains 1 entries:
Offset Info Type Sym.Value Sym. Name
0000001c 00000902 R_386_PC32 00000000 bar
This would be a relocation entry for a function bar. An entry in the symbol table will be made noting the function is yet undefined:
9: 00000000 0 NOTYPE GLOBAL DEFAULT UND bar
When you link the test.o object file into a program, you need to link against the math library called libm.so . The so extension is similar to the .dll extension for windows. It means it is a shared object file. The compiler, when linking, will fix-up all the places that appear in the relocation table of test.o, replacing its entries with the proper address of the bar function. Depending on whether you use the shared version of the library or the static one (it's called libm.a then), the compiler will do that fix-up after compiling, or later, at runtime when you actually start your program. When finished, it will inject an entry in the table of shared libraries needed for that program. (can be shown with readelf -d ./test):
Dynamic section at offset 0x498 contains 22 entries:
Tag Type Name/Value
0x00000001 (NEEDED) Shared library: [libm.so.6]
0x00000001 (NEEDED) Shared library: [libc.so.6]
... ... ...
Now, if you start your program, the dynamic linker will lookup that library, and will link that library to your executable image. In Linux, the program doing this is called ld.so. Static libraries don't have a place in the dynamic section, as they are just linked to the other object files and then they are forgotten about; they are part of the executable from then on.
In reality it is actually much more complex and i also don't understand this in detail. That's the rough plan, though.
|
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 behave as doubles. Another would be using NaN (std::numeric_limits). But I see no way to check for a variable being NaN.
How can I solve the problem of needing a "special" float value to mean something other than the number?
|
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. They are a special case that has to be dealt with like NULL pointers. The difference is that a NaN will not usually cause core dumps and application failures, but they are extremely hard to track down. If you decide to use NaN's, use them as little as possible. Overuse of NaN's is an offensive coding practice.
|
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 to wchar_t as you say) mode.
|
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 variable the user enters, ex- if a user enters a char or string, I can output an error message. Here is my code:
//cubes a user entered number
#include <iostream>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
double user;
cin >> user; //user entering the number
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
Edit: I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
|
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);
int main()
{
while(true)
{
cout << "Enter the number you want to cube: ";
string user;
cin >> user;
try
{
// The following instruction tries to parse a double from the 'user' string.
// If the parsing fails, it raises an exception of type bad_lexical_cast.
// If an exception is raised within a try{ } block, the execution proceeds
// with one of the following catch() blocks
double d = lexical_cast <double> (user);
cout << "The cube of " << d << " is " << cube(d) << "." << endl;
break;
}
catch(bad_lexical_cast &e)
{
// This code is executed if the lexical_cast raised an exception; We
// put an error message and continue with the loop
cout << "The inserted string was not a valid double!" << endl;
}
}
return 0;
}
double cube (double n)
{
return n*n*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...
for(/*all elements in stuff*/)
//Something to the effect of: if(stuff[i].getClass()==Dog) {/*do something*/}
}
I hope that's sort of clear. I know about typeid, but I don't really have any Dog object to compare it to and I would like to avoid creating a Dog object if I can.
Is there a way to do this? Thanks in advance.
|
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* . So if you do **it you will get an Animal&):
for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {
if(typeid(**it) == typeid(Dog)) {
// it's a dog
} else if(typeid(**it) == typeid(Cat)) {
// it's a cat
}
}
Note you can apply the typeid operator to types itself too, as shown above. You don't need to create an object for this. Also note the typeid way doesn't work if you pass it a pointer like typeid(*it) . Using it like that will give you just typeid(Animal*) which isn't useful.
Similar, dynamic_cast can be used:
for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {
if(Dog * dog = dynamic_cast<Dog*>(*it)) {
// it's a dog (or inherited from it). use the pointer
} else if(Cat * cat = dynamic_cast<Cat*>(*it)) {
// it's a cat (or inherited from it). use the pointer.
}
}
Note that in both cases, your Animal type should be polymorph. That means it must have or inherited at least one virtual function.
|
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 query (if I change the query to select only one of the columns with the same where clause then no exception).
I assume this is because of some limitation in CRecordset, but I can't find anything telling me of any limitations. The table only has 39 columns.
Has anyone run into this problem? And if so, do you have a work around / solution?
This is a MFC project using Visual Studio 6.0 if it makes any difference.
Here's the query (formatted here so wold show up without a scrollbar):
SELECT `id`, `member_id`, `member_id_last_four`, `card_number`, `first_name`,
`mi`, `last_name`, `participant_title_id`, `category_id`, `gender`,
`date_of_birth`, `address_line_1`, `address_line_2`, `city`, `state`,
`zip`, `phone`, `work_phone`, `mobile_phone`, `fax`, `email`,
`emergency_name`, `emergency_phone`, `job_title`, `mail_code`,
`comments`, `contract_unit`, `contract_length`, `start_date`,
`end_date`, `head_of_household`, `parent_id`, `added_by`, `im_active`,
`ct_active`, `organization`, `allow_members`, `organization_category_id`,
`modified_date`
FROM `participants`
WHERE `member_id` = '27F7D0982978B470C5CF94B1B833CC93F997EE23'
Copying and pasting into my query browser gives me only one result.
More info:
Commented out each column in the select statement except for id. Ran the query and no exception.
Then I systematically went through and uncommented each column, one at a time, and re-ran query in between each uncomment.
When I uncomment the comment column then I get the error.
This is defined as the following (Using MySQL): LONGTEXT
|
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 (thereby causing the error).
So, if there is a case where you absolutely have to have these large fields. Here is a potential solution:
Give the field a default value in the database. (ie. '<blank>')
Then when displaying the value; you pass NULL/empty if you find default value.
Then when updating the value; you pass the default value if you find NULL/empty.
|
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 (more components, more CPU cycles). I have a maxComponent distance which I calculate upon creation of the ship which is basically the longest line I can draw from the center of the ship to the edge of the furthest component. I keep track of stuff onscreen and use this maxComponentDistance to see if they're even close enough to be colliding.
If they are in close proximity I start checking to see if the components of different ships intersect. Here is where my efficiency question comes in.
I have a (x,y) locations of the component relative to the ship's center, but it doesn't account for how the ship is currently rotated. I keep them relative because I don't want to have to recalculate components every single time the ship moves. So I have a little formula for the rotation calculation and I return a 2d-vector corresponding to rotation-considerate position relative to the ships center.
The collision detection is in the GameEngine and it uses the 2d-vector. My question is about the return types. Should I just create and return a 2d-vector object everytime that function is called
or
should I give that component object an additional private 2d-vector variable, edit the private variable when the function is called, and return a pointer to that object?
I'm not sure about the efficiency of memory allocation vs having a permanent, editable, private variable. I know that memory would also have to be allocated for the private variable, but not every time it was checked for collisions, only when a new component was created. Components are not constant in my environment as they are deleted when the ship is destroyed.
That's my main dilemma. I would also appreciate any pointers with the design of my actual collision detection system. It's my first time giving a hack at it (maybe should have read up a bit)
Thanks in advance.
|
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 also investigate memory pools, where you pre-allocate lots of such components and put in a pool, so you can allocate a new component in constant time.
As a general (and apologies if it's too obvious) point when doing this kind of collision-detection: square the distances, rather than computing the square roots. :)
|
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 TheManager {
public:
virtual SomeManagerClass* someManagerClass() const;
virtual SomeOtherManager* someOtherManager() const;
/** More objects... up to 10-20 */
};
Currently TheManager uses the new operator in order to create objects.
My intention is to be able to replace, using plugins, the SomeManagerClass (or any other class) implementation with another one. In order to replace the implementation, 2 steps are needed:
Define a class DerivedSomeManagerClass, which inherits SomeManagerClass [plugin]
Create the new class (DerivedSomeManagerClass) instead of the default (SomeManagerClass) [application]
I guess I need some kind of object factory, but it should be fairly simple since there's always only one type to create (the default implementation or the user implementation).
Any idea about how to design a simple factory like I just described? Consider the fact that there might be more classes in the future, so it should be easy to extend.
[*] I don't care if it happens more than once.
Edit: Please note that there are more than two objects that are contained in TheManager.
|
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 like this as it violates the DRY principle
keeping some sort of table where the key is an enum or a string; in this case the setter is a single function with parameters (of course if the key is an enum you can use a vector instead of a map)
The other problem is: what is this "way to create a class"? Unfortunately we can't store pointers to constructors directly, but we can:
create, as others have pointed out, a factory for each class
just add a static "create" function for each class; if they keep a consistent signature, you can just use their pointers to functions
Templates can help in avoiding unnecessary code duplication in both cases.
|
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 instead of
Dog sparky;
and let the destructor be called once sparky goes out of scope?
Thanks!
|
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 lifetime and avoiding leaks.
So in general, every time you need to allocate a resource, whether it's memory (by calling new), file handles, sockets or anything else, wrap it in a class where the constructor acquires the resource, and the destructor releases it. Then you can create an object of that type on the stack, and you're guaranteed that your resource gets freed when it goes out of scope. That way you don't have to track your new/delete pairs everywhere to ensure you avoid memory leaks.
The most common name for this idiom is RAII
Also look into smart pointer classes which are used to wrap the resulting pointers on the rare cases when you do have to allocate something with new outside a dedicated RAII object. You instead pass the pointer to a smart pointer, which then tracks its lifetime, for example by reference counting, and calls the destructor when the last reference goes out of scope. The standard library has std::unique_ptr for simple scope-based management, and std::shared_ptr which does reference counting to implement shared ownership.
Many tutorials demonstrate object
instantiation using a snippet such as ...
So what you've discovered is that most tutorials suck. ;)
Most tutorials teach you lousy C++ practices, including calling new/delete to create variables when it's not necessary, and giving you a hard time tracking lifetime of your allocations.
|
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 alpha channel values for pixels in an HBITMAP?
I want to be able to detect when to use ::AlphaBlend, and when to use an old-school method for treating a particular colour in the source HBITMAP as transparent.
HDC sourceHdc = ::CreateCompatibleDC(hdcDraw);
::SelectObject(sourceHdc, m_hbmp);
// This pixel has partial transparency, but ::GetPixel returns just RGB.
COLORREF c = ::GetPixel(sourceHdc, 20, 20);
// Draw the bitmap to hdcDraw
BLENDFUNCTION bf1;
bf1.BlendOp = AC_SRC_OVER;
bf1.BlendFlags = 0;
bf1.SourceConstantAlpha = 0xff;
bf1.AlphaFormat = AC_SRC_ALPHA;
::AlphaBlend(di.hdcDraw, x, 10, 64, 64, sourceHdc, 0, 0, 64, 64, bf1);
::DeleteDC(sourceHdc);
Answer
Use GetDIBits to retrieve the first (or more) scan line(s) of the image:
byte* bits[1000];// = new byte[w * 4];
BITMAPINFO bmi;
memset(&bmi, 0, sizeof(BITMAPINFO));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = w;
bmi.bmiHeader.biHeight = -h;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = 0;
bmi.bmiHeader.biXPelsPerMeter = 0;
bmi.bmiHeader.biYPelsPerMeter = 0;
bmi.bmiHeader.biClrUsed = 0;
bmi.bmiHeader.biClrImportant = 0;
int rv = ::GetDIBits(sourceHdc1, m_hbmp, 0, 1, (void**)&bits, &bmi, DIB_RGB_COLORS);
//bits[3] == alpha of topleft pixel;
//delete[] bits;
|
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?
KeyboardProc does not have any 32 bit DWORD where I can pass the 'this' pointer.
|
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 = ::SetWindowsHookEx(WH_KEYBOARD, StaticKeyboardProc, /* etc */);
}
// Trampoline
static LRESULT CALLBACK StaticKeyboardProc(int code, WPARAM wParam, LPARAM lParam)
{
ASSERT(m_pThis != NULL);
m_pThis->KeyboardProc(code, wParam, lParam);
}
LRESULT KeyboardProc(int code, WPARAM wParam, LPARAM lParam);
/* etc. */
};
You need to define the static member:
// Widget.cpp
CWidget *CWidget::m_pThis = NULL;
|
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 know all the details of the implementation and any other classes/headers needed only for that. This will reduce compilation times and also the amount of recompilation needed when something in the implementation changes.
It's not perfect, and you would usually resort to techniques like the Pimpl Idiom to properly separate interface and implementation, but it's a good start.
|
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 definitions
Code bloat due to multiple 'static' constants
requirement for header guards to prevent multiple inclusion
violation of DRY principles
and more...
Dviljoen thinks I'm being quite hard on it, and he's right. It is almost a 40-year old design, from the era of punch cards and paper tape. There's an incredible amount of high-quality software built in C/C++ using the source/header file arrangement, despite all the potential gotchas and problems listed above.
|
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, please show me wrong.
SoundEngine.cpp (from CrashLanding and TouchFighter code samples) uses OpenAL and allows to control pitch, but everytime a buffer is started, if that same buffer is playing, its playhead goes back to the start.
One dirty solution to get polyphony with SoundEngine.cpp, without diving into its implementation (which is incomprehensible to me), is to load multiple buffers for the same sound file. Let's say I want a polyphony of maximum 4 voices per sound, then I load 4 buffers for the same file. I would just have to wrap it all up in a manager class. Is it safe to go down this path? And/or is there a way to hack the SoundEngine.cpp to be polyphonic?
|
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 (obviously).
|
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 and if so what is the best way?
Is there a way to convert to const char* so I can just use standard C string manipulation.
Thanks in advance
|
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 thread(!). This seems to be a documented bug, i.e. here and here.
After some deliberation we decided to eliminate exceptions altoghether as we have reached a point where exceptions do a lot of damage to running applications. The main concern now is how to manage cases where a constructor failed.
We have tried lazy evaluation, where each method has the ability to instantiate dynamic resources and return a status value but that means that every class method has to return a return value which makes for a lot of ifs in the code and is very annoying in methods which generally would never cause an error.
We looked into adding a static create method which returns a pointer to a created object or NULL if creation failed but that means we cannot store objects on the stack anymore, and there is still need to pass in a reference to a status value if you want to act on the actual error.
According to Google's C++ Style Guide they do not use exceptions and only do trivial work in their constructors, using an init method for non-trivial work (Doing Work in Constructors). I cannot however find anything about how they handle construction errors when using this approach.
Has anyone here tried eliminating exceptions and come up with a good solution to handling construction failure?
|
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 something that returns NULL instead of throwing, to save yourself remembering to use nothrow new everywhere:
MyClassWithNoThrowConstructor *foo = new MyClassWithNoThrowConstructor();
if (foo == NULL) {
// out of memory handling code
} else if (foo->init(bar, baz, etc) != 0) {
delete foo;
// error-handling code
} else {
// success, we can use foo
}
Obviously if you possibly can, use smart pointers to save having to remember the deletes, but if your compiler doesn't support exceptions properly, then you might have trouble getting Boost or TR1. I don't know.
You also might want to structure the logic differently, or abstract the combined new and init, to avoid deeply-nested "arrow code" whenever you're handling multiple objects, and to common-up the error-handling between the two failure cases. The above is just the basic logic in its most painstaking form.
In both cases, the constructor sets everything to default values (it can take some arguments, provided that what it does with those arguments cannot possibly fail, for instance if it just stores them). The init method can then do the real work, which might fail, and in this case returns 0 success or any other value for failure.
You probably need to enforce that every init method across your whole codebase reports errors in the same way: you do not want some returning 0 success or a negative error code, some returning 0 success or a positive error code, some returning bool, some returning an object by value that has fields explaining the fault, some setting global errno, etc.
You could perhaps take a quick look at some Symbian class API docs online. Symbian uses C++ without exceptions: it does have a mechanism called "Leave" that partially makes up for that, but it's not valid to Leave from a constructor, so you have the same basic issue in terms of designing non-failing constructors and deferring failing operations to init routines. Of course with Symbian the init routine is permitted to Leave, so the caller doesn't need the error-handling code I indicate above, but in terms of splitting work between a C++ constructor and an additional init call, it's the same.
General principles include:
If your constructor wants to get a value from somewhere in a way that might fail, defer that to the init and leave the value default-initialised in the ctor.
If your object holds a pointer, set it to null in the ctor and set it "properly" in the init.
If your object holds a reference, either change it to a (smart) pointer so that it can null to start with, or else make the caller pass the value into the constructor as a parameter instead of generating it in the ctor.
If your constructor has members of object type, then you're fine. Their ctors won't throw either, so it's perfectly OK to construct your members (and base classes) in the initializer list in the usual way.
Make sure you keep track of what's set and what isn't, so that the destructor works when the init fails.
All functions other than constructors, the destructor, and init, can assume that init has succeeded, provided you document for your class that it is not valid to call any method other than init until init has been called and succeeded.
You can offer multiple init functions, which unlike constructors can call each other, in the same way that for some classes you'd offer multiple constructors.
You can't provide implicit conversions that might fail, so if your code currently relies on implicit conversions which throw exceptions then you have to redesign. Same goes for most operator overloads, since their return types are constrained.
|
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 not exist in pre-NT systems, will they receive an error message of some sort for example because in that case I will add in an OS check? Thanks
|
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 you can then use.
It's a pain, but it's the only solution I know of.
Here is an example of getting the UpdateLayeredWindow function if it exists:
typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
UpdateLayeredWinFunc updateLayeredWindow = 0;
HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
|
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 order of their declaration.
|
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);
with a call of
func(mySprite);
|
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 mySprite passed by value or by reference? You can't tell
// without looking at the definition of func()
func(mySprite);
// func2 passes "by pointer" - no need to look up function definition
func2(&mySprite);
|
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 static class variables, but not member attributes.
The fact that it is bound at compile time and in the place where the function is declared also means that if it makes use of a variable, that variable will be used even if a different variable shadows the original at the place of the function call.
// Code 1: Valid and invalid default parameters
int global = 0;
int free_function( int x );
class Test
{
public:
static int static_member_function();
int member_function();
// Valid default parameters
void valid1( int x = free_function( 5 ) );
void valid2( int x = free_function( global ) );
void valid3( int x = free_function( static_int ) );
void valid4( int x = static_member_function() );
// Invalid default parameters
void invalid1( int x = free_function( member_attribute ) );
void invalid2( int x = member_function() );
private:
int member_attribute;
static int static_int;
};
int Test::static_int = 0;
// Code 2: Variable scope
int x = 5;
void f( int a );
void g( int a = f( x ) ); // x is bound to the previously defined x
void h()
{
int x = 10; // shadows ::x
g(); // g( 5 ) is called: even if local x values 10, global x is 5.
}
|
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" int CLRDUMP_API RegisterFilter( LPCWSTR pDumpFileName, unsigned long DumpType );
Also, in the makeexe.mak, the library is being linked in as:
$(COMPILEBASE)\lib\clrdump.lib \
To be honest, I am not an expert at makefiles, and I am changing over a system from Microsoft Visual C++ 6.0 to 2008. This change-over may have something to do with the link errors, as the system used to work before.
Any help would really be appreciated.
Thanks in Advance,
Sincerely,
Joseph
-- Edit 1 --
Does anyone know how to turn verbose on in the makefile system of pvcs?
Note that the above function is already a compiler-decorated version, having
__imp__RegisterFilter@8
whereas the C++ function is just
RegisterFilter
Thanks for the help, but if anyone can post a more complete solution, that would also be very appreciated.
Sincerely, Joseph
-- Edit 2 --
Some kind person posted this, but when I signed in it disappeared:
The imp prefix indicates that this function is imported from a DLL. Check the definition of CLRDUMP_API - is it __declspec(dllimport)? See this article for more information.
There was a working link, but I've lost that, however I suppose one can always search the topic.
Thanks, whoever you were!
-- Edit 3 --
Thanks ChrisN (I'm not yet allowed to vote). Despite using the refresh button, your answer disappeared, but then re-appeared after I posted a cut-n-paste.
This is my definition of that:
define CLRDUMP_API __declspec(dllimport) __stdcall
I assume that the __stdcall is OK?
-- Edit 4 --
While I appreciate the efforts of those who answered, particularly ChrisN, at least on my particular system, the link error remains. So if anyone has any further insight, I'd appreciate it. Thanks again.
|
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→Linker→General, I set Additional Library Directories to "C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\Lib".
Also in program Properties→Configuration Properties→Linker→Command line for the Additional Options, I added ComCtl32.Lib ComDlg32.Lib.
My program is now compiling without any problems. My two cents: you need to identify all the libraries that your program requires. Hint: check all the headers you have included, you need to make sure that your linker can see them.
|
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 mousePressEvent of the QTreeWidget class like this:
void MyQTreeWidget::mousePressEvent(QMouseEvent *e){
QTreeView::mousePressEvent(e);
const QModelIndex index = indexAt(e->pos());
if (!index.isValid())
{
const Qt::KeyboardModifiers modifiers = QApplication::keyboardModifiers();
if (!(modifiers & Qt::ShiftModifier) && !(modifiers & Qt::ControlModifier))
clearSelection();
}
}
I didn't try it yet. Is the only solution or is there any easier way?
|
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 works just fine
if (FAILED(hr))
return hr;
SAFEARRAY *args =
SafeArrayCreateVector(VT_VARIANT, 1, 1); // create an array of the length of 1 ( Main(string[]) )
int argc;
LPWSTR cmdLine = GetCommandLineW();
LPWSTR *argv = CommandLineToArgvW(cmdLine, &argc); // get an array of arguments to this function
VARIANT vtPsa;
vtPsa.vt = (VT_ARRAY | VT_BSTR);
vtPsa.parray = SafeArrayCreateVector(VT_BSTR, 1, argc); // create an array of strings
for (long i = 0; i < argc; i++)
{
SafeArrayPutElement(vtPsa.parray, &i, SysAllocString(argv[i])); // insert the string from argv[i] into the safearray
}
long idx[1] = {0};
SafeArrayPutElement(args, idx, &vtPsa); // insert an array of BSTR into the VT_VARIANT args array
VARIANT obj, result;
VariantInit(&obj);
VariantInit(&result);
try
{
hr = entryPoint->Invoke_3(obj, args, &result); // call the entry point
}
catch(_com_error ex)
{
MessageBox(NULL, ex.ErrorMessage(), "Error", 0);
}
if(FAILED(hr))
{
hr = hr; // added just so I can set a breakpoint
}
The errorcode I'm getting is -2146233032, which according to corerror.h corresponds to:
for decimal -2146233032 / hex
0x80131538 :
COR_E_SAFEARRAYRANKMISMATCH
A mismatch has occured between the
runtime rank of the array and the rank
recorded in the metadata.
Can anyone see the problem?
|
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 PARGB pixel format.
Use LockBits to get hold of the pixelData memory of your new Bitmap.
If you got the pixels from GetObject, copy the ARGB values across using memcpy.
Call UnlockBits on the new Bitmap.
In my case, the format of the input HBITMAP is correct for doing a straight memcpy from input bitmap pixel data to the new Bitmap pixel data.
If you didnt get the input pixel data from GetObject, use GetDIBits to get a copy in the correct format.
|
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 when. When we made the switch I believed it was the right thing to do, but it bothered me that we had to include something from a third-party library in our public interface - generally you avoid that kind of thing if you can. I rationalized it that boost was practically part of the C++ language now, and our use case requires that both the client code and the library hold pointers to the objects. However recently one of our clients has asked us if we could switch to using a neutral smart pointer class in the interface, because our library is essentially forcing them to a particular version of boost- a point which I certainly understand and appreciate. So now I am wondering what the best course of action might be. I have thought about it a little bit, and wondered about creating a simple smart pointer class that simply held a real boost smart pointer. But then the clients would probably immediately stuff one of those into their flavor of boost::sharedptr, and then we'd be three shared pointers deep - which might be a problem, or it might not. Anyway, I'd love to hear some opinions from the community about the best way to solve this problem.
Edit: I originally said transfer of ownership, but I should have specified that code on both sides of the API boundary need to hold a pointer to the object.
|
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 directories?
|
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.
In new versions of Visual Studio (2015+) the above option is deprecated and a list of default include directories is available at Project Properties → Configuration → VC++ Directories
In your case, add the directory that the header is to the project properties (Project Properties → Configuration → C/C++ → General → Additional Include 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://stupefydeveloper.blogspot.com/2008/10/c-function-try-catch-block.html
|
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::exception(?)
{
public:
enum Status
{
ERROR_FOO,
ERROR_BAR,
...
};
MyException(const std::string& error, Status code) :
error_(error), code_(code)
{
...
}
virtual const char* what() const
{
return error_.c_str();
}
Status code() const
{
return code_;
}
private:
std::string error_;
Status code_;
};
Then in the code:
throw MyException("Ooops!", MyException::ERROR_BAR);
|
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 pointer to a const MyStructure".
I looked for an answer in the C++ spec, but apparently I'm not very good at that...
What does in mean in C++, and does it mean the same thing in C?
|
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.