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 |
|---|---|---|---|---|
1,802,929 | 1,802,952 | How can we use .NET dll in VC++? | Please suggest me the best way to use .NET dll in VC++ project.
| Make it ComVisible. See link text
|
1,803,079 | 1,803,110 | What is the advantage of using initializers for a constructor in C++? | Sphere() : theRadius(1.0)
{
}
Why is it preferable to have a constructor written with initializers (above) than a constructor that initializes the data members within its body (below)?
Sphere()
{
theRadius = 1.0;
}
| All members are initialised before entering the body of the constructor. If you don't provide an initialiser in the init list, then they're default constructed.
In your first example the following happens:
theRadius is initialised to 1.0
In your second example the following happens:
theRadius is initialised
1.0 is copied to theRadius
With simple types like ints and floats this won't matter much. however if your members are objects with non-trivial constructors / copy constructors then it's a lot more efficient to use the initialisation list approach.
|
1,803,112 | 1,803,408 | Set a QComboBox or QSpinBox to a value not allowed | I am maintaining an application which tries to help the user get his parameters to work together, as there are many interdependencies.
Now there is a default value of x for a variable Y. When the user changes some other variable Z, there might be a new minimum value for Y which is greater than x. This is set as a minimum for the spinbox. Now the spinbox can not display the current value anymore, but rather displays the minimum. I would like the user to be able to see his old value. Is there some setting I don't see in Qt to achieve something like this?
Same question goes for QComboBox.
| As one approach you may create new class, inherited from Qt standart QSpinBox(or in second case from QComboBox) and add your own logic to them: posibility to show value below the minimum, but when someone want explicitly change value in your input widgets, you will check for bounds.
|
1,803,281 | 1,803,294 | Pointer for item in iteration over std::list | I'm working on a very basic game and I have a std::list collection of objects that pertain to my game. I declared it as:
std::list<Target> targets;
When I iterate over it, using
for (std::list<Target>::iterator iter = targets.begin(); iter != targets.end(); iter++) {
Target t = *iter;
t.move();
}
My objects aren't updating on the GUI. However, replacing the iterating loop with a targets.front().move(), my one object moves correctly. I think this is because I am not iterating over the collection using pointers. Can anyone explain how that is done? Thanks.
| You are copying the objects, do it this way:
*iter.move()
If you use Target t = *iter; you are essentially making a copy of your object and moving it, instead of moving your intended object.
As xtofl said(thx) you can get the reference as well.
Target &t = *iter;
t.move();
|
1,803,590 | 7,623,152 | Waf generating Visual Studio projects? | Can the Waf build system generate Visual Studio project files for C/C++?
| An "extra" tool does now (check waflib/extras/msvs.py).
Since this is used by the waf author, I think you can rely on it.
|
1,803,887 | 1,804,079 | Locks and Mutexes in C++ | I have learnt C++ for a while and still didn't come across good book which would explain what are those beasts? Are they integral C++ feature? If so how is it that they are only mentioned in such book like The C++ Programming Language by B.S. If not, where can you get reliable information about them - prefferably a book (don't really like web tutorials), how to define them, how to use them etc.
Thank you for any valuable help.
| Locks and Mutexes are concurrency constructs used to ensure two threads won't access the same shared data at the same time, thus achieving correctness.
The current C++ standard doesn't feature concurrency tools.
Although you mentioned you prefer books to online tutorials, Herb Sutter's Effective Concurrency column is definitely a must read.
There is also Anthony Williams's upcoming book called C++ Concurrency in Action. Anthony Williams is the author of the Boost.Thread library.
Another threading library worth a look is Intel's TBB.
|
1,803,989 | 1,804,354 | Setting a column style? (Unmanaged c++) | I'm currently able to set a listview style VIA the ListView_SetExtendedListViewStyle method, however this makes all columns have the same style. My goal is to only modify one column (to basically have the LVS_EX_UNDERLINEHOT|LVS_EX_UNDERLINECOLD|LVS_EX_TWOCLICKACTIVATE style).
Is there a way to modify the style of only one column and not the entire table?
Edit: Or even a way to custom draw the cell?
| If you use the WTL framework then there is a very useful CCustomDraw class that you can use to easily intercept NM_CUSTOMDRAW messages and draw your own listview content.
There is a good CodeProject article on custom draw using WTL here.
|
1,804,148 | 1,808,002 | Runtime error: Access violation when using .push_back() with a std::vector? | I have a vector, defined by std::vector<LPDIRECT3DTEXTURE9> textures; Later, I am passing a LPDIRECT3DTEXTURE9 object to it, like so textures.push_back(texture); Here is a sample of this:
void SpriteManager::AddSprite(float x, float y, float z, LPDIRECT3DTEXTURE9 texture)
{
//snip
textures.push_back(texture);
//snip
}
This is causing a runtime error. It is breaking in the vector class at the size() function. Why might this happen?
Edit:
I also run into an identical problem performing the same operation on a vector of D3DXVECTOR3 objects. Since LPDIRECT3DTEXTURE9 is a pointer to an IDIRECT3DTEXTURE9, should I be using that instead?
| By far the most common reason is that you actually don't have a vector. In this case, textures appears to be a member of the SpriteManager class. So, that suggest you actually don't have a SpriteManager object either. Is the this pointer valid?
|
1,804,398 | 1,804,482 | Using a virtually inherited function non-virtually? | I have run into trouble trying to implement functionality for serializing some classes in my game. I store some data in a raw text file and I want to be able to save and load to/from it.
The details of this, however, are irrelevant. The problem is that I am trying to make each object that is interesting for the save file to be able to serialize itself. For this I have defined an interface ISerializable, with purely virtual declarations of operator<< and operator>>.
The class Hierarchy looks something like this
-> GameObject -> Character -> Player ...
ISerializable -> Item -> Container ...
-> Room ...
This means there are many possible situations for serializing the objects of the different classes. Containers, for instance, should call operator<< on all contained items.
Now, since operator>> is virtual, i figured if I wanted to serialize something that implements the functionality defined in ISerializable i could just do something like
ostream & Player::operator<<(ostream & os){
Character::operator<<(os);
os << player_specific_property 1 << " "
<< player_specific_property 2 << "...";
return os;
}
and then
ostream & Character::operator<<(ostream & os){
GameObject::operator<<(os);
os << character_specific_property 1 << " "
<< character_specific_property 2 << "...";
return os;
}
but I quickly learnt that this first attempt was illegal. What I'm asking here is how do I work around this?
I don't feel like implementing a function manually for each class. I guess I'm looking for something like the super functionality from Java.
Any help is appreciated.
-- COMMENTS ON EDIT ------------
Alright, last time I was in a hurry when I was writing the question. The code is now more like it was when I tried to compile it. I fixed the question and the problem I had was unrelated to the question asked. I'm ashamed to say it was caused by an error in the wake of a large refactoring of the code, and the fact that the operator was not implemented in every base class.
Many thanks for the replies however!
| The problem is not in your attempt to call a virtual function non-virtually. The problem is this line: os = Character::operator<<(os);. That is an assignment, but std::ostream doesn't have an operator=.
You don't need the assignment anyway. The stream returned is the same stream as the stream you pass in. The only reason it's returned is so you can chain them.
Hence the fix is to just change the code to
ostream & Player::operator<<(ostream & os){
Character::operator<<(os);
os << player_specific_property 1 << " "
<< player_specific_property 2 << "...";
return os;
}
|
1,804,514 | 1,809,788 | How to accept empty value in boost::program_options | I'm using boost::program_options library to process command line params.
I need to accept a file name via -r option, in case if it is empty (-r given without params) I need to use stdin.
desc.add_options()
("replay,r", boost::program_options::value<std::string>(), "bla bla bla")
In this case boost wouldn't accept -r without params and throw an exception.
default_value () option does not work as well as it would make library return value even if user didn't give -r option.
Any ideas how to work around?
| Please use the implicit_value method, e.g
desc.add_options()
("replay,r", po::value<std::string>()->implicit_value("stdin"), "bla bla bla")
This makes the option accept either 0 or 1 token, and if no tokens are provided, it will act as if 'stdin' was provided. Of course, you can pick any other implicit value -- including empty string and '-' as suggested by mch.
|
1,804,606 | 1,804,618 | Static initialization and destruction of a static library's globals not happening with g++ | Until some time ago, I thought a .a static library was just a collection of .o object files, just archiving them and not making them handled differently. But linking with a .o object and linking with a .a static library containing this .o object are apparently not the same. And I don't understand why...
Let's consider the following source code files:
// main.cpp
#include <iostream>
int main(int argc, char* argv[]) {
std::cout << "main" << std::endl;
}
// object.hpp
#include <iostream>
struct Object
{
Object() { std::cout << "Object constructor called" << std::endl; }
~Object() { std::cout << "Object destructor called" << std::endl; }
};
// object.cpp
#include "object.hpp"
static Object gObject;
Let's compile and link and run this code:
g++ -Wall object.cpp main.cpp -o main1
./main1
> Object constructor called
> main
> Object destructor called
The constructor an the destructor of the global gObject object is called.
Now let's create a static library from our code and use (link) it in another program:
g++ -Wall -c object.cpp main.cpp
ar rcs lib.a object.o
g++ -Wall -o main2 main.o lib.a
./main2
> main
gObject's constructor and destructor are not called... why?
How to have them automatically called?
Thanks.
| .a static libraries contain several .o but they are not linked in unless you reference them from the main app.
.o files standalone link always.
So .o files in the linker always go inside, referenced or not, but from .a files only referenced .o object files are linked.
As a note, static global objects are not required to be initialized till you actually reference anything in the compilation unit, most compilers will initialize all of them before main, but the only requirement is that they get initialized before any function of the compilation unit gets executed.
|
1,804,728 | 1,820,918 | How to receive drag and drop from Apple Address book in Qt 4.4 on Mac OS X 10.5/10.6 | I am trying to trap drag and drop events from the standard Apple address book app to my Qt app. This code works fine with Qt 4.4. on Mac OS X 10.4:
void
MyView::contentsDropEvent( QDropEvent* e )
{
QList<QUrl> urls = e->mimeData()->urls();
...
I can then use the URL to get the vCard. Marvellous.
But from Mac OS X 10.5 the apple address book no longer seems to support text/uri-list. So e->mimeData()->urls() returns an empty list. Worse still, e->mimeData()->formats() returns an empty list. How do I find out which vCards they dragged?
Here is a comment from a Nokia Qt engineer on this problem:
"Adressbook stopped providing drop
data as text/uri-list compatible
flavor data in OS 10.5. Not much we
can do about that. The flavor they
provide instead is 'public.vcard'. We
could put up support for this as an
implementation request, but my gut
feeling is that this is too
application specific, and can just as
well be implemented by the app
developer by subclassing QMacMimeData"
But there is no QMacMimeData in the Qt 4.4 or 4.5 documentation. Any ideas at how I can find out what they dragged?
| richardmg of Qt/Nokia kindly supplied me with some example code. I have filled in some of the gaps. This now works fine on Mac OS X 10.5.
#include <QtGui>
class VCardMime : public QMacPasteboardMime
{
public:
VCardMime() : QMacPasteboardMime(MIME_ALL)
{ }
QString convertorName()
{
return QString("VCardMime");
}
bool canConvert(const QString &mime, QString flav)
{
return mimeFor(flav) == mime;
}
QString mimeFor(QString flav)
{
if (flav == QString("public.vcard"))
return QString("application/x-mycompany-VCard");
return QString();
}
QString flavorFor(const QString &mime)
{
if (mime == QString("application/x-mycompany-VCard"))
return QString("public.vcard");
return QString();
}
QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav)
{
QByteArray all;
foreach ( QByteArray i, data )
{
all += i;
}
return QVariant( all );
}
QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav)
{
// Todo: implement!
return QList<QByteArray>();
}
};
class TestWidget : public QWidget
{
public:
TestWidget() : QWidget(0)
{
new VCardMime();
setAcceptDrops(true);
}
void contentsDropEvent(QDropEvent* e)
{
if ( e->mimeData()->hasFormat( "application/x-mycompany-VCard" ) )
{
QString s = QString( e->mimeData()->data( "application/x-mycompany-VCard" ) );
// s now contains text of vcard
e->acceptProposedAction();
}
}
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
TestWidget wid1;
wid1.show();
return app.exec();
}
|
1,804,734 | 1,804,742 | How can I perform a file search in C++ | I just started learning C++ and am currently using codeblocks.
I want to write an application that can search for files in a directory including its subdirs, but I cant seem to find any good examples for this and I've read somewhere that this is only possible through a library like boost.
Is this true?
Are there any examples for doing it without library?
Thanks in advance
| It's also possible to use it using OS system calls, readdir on linux for example. boost (and other libraries) will allow you to write portable code for several (all?) OSes.
Here u can find elaborate examples http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608
|
1,804,840 | 1,804,924 | Extending enums in C++? | Is there a way in C++ to extend/"inherit" enums?
I.E:
enum Enum {A,B,C};
enum EnumEx : public Enum {D,E,F};
or at least define a conversion between them?
| No, there is not.
enum are really the poor thing in C++, and that's unfortunate of course.
Even the class enum introduced in C++0x does not address this extensibility issue (though they do some things for type safety at least).
The only advantage of enum is that they do not exist: they offer some type safety while not imposing any runtime overhead as they are substituted by the compiler directly.
If you want such a beast, you'll have to work yourself:
create a class MyEnum, that contains an int (basically)
create named constructors for each of the interesting values
you may now extend your class (adding named constructors) at will...
That's a workaround though, I have never found a satistifying way of dealing with an enumeration...
|
1,805,209 | 1,805,316 | Multiple association problem with C++ | How would you solve this problem? (At the beginning it seemed simple, then I found it to be puzzling).
You have a class called Executor. Suppose you have many instance of it and they do different things upon call of a method do(Argument).
Argument has 2 different parameters and they are A* pa, B* pb (one of which can be null)
Now, I want a class Manager that receives Argument istances and forwards them to the appropriate instance of Executor (let's call this method Filter). This is done after, some time before, each Executor called the Manager.subscribe(A* pa, B* pb) method to say to wich one of these is interested. Note that: if pa or (not both) pb are NULL, means ANY (I mean if pa is NULL, only pb is checked). Of course there must not be more than one Executor.
The implementation must be FAST, the ideal should be a vector, or something close like an hash map... BUT THE COMPARISON HAS TO BE MADE ON THE CONTENTS OF pa and pb, not their value as pointers.
Finally,it must be possible that subscription can be cancelled by an executor (without waiting too long). Anyway I want that Filter, subscribe and cancelSubscription are very fast.
I've been thinking of many arrangements, with hash maps, lists and multimaps... But all of them lack speed or easyness, or something else. What would you do?
| I think you want to create a class called "Subscription" which represents a single subscription from an Executor to a Manager containing information on under what conditions the this Subscription would trigger, as well as some sort of GUID or name for this subscription. I'm thinking something like
class Subscription
{
GUID g;
A_filter a;
B_filter b;
Executor *e;
}
Subcription would also have a method to "Check" if it should trigger based on given values for A and B and then call the executor on those parameters if it matches.
The Manager class would then contain three maps, one of these Maps Guid to Subscription* and would allow very quick unsubcribes, basically look up the GUID in the unsubscribe request to get the Subscription object, use that object to determine what values for A and B might need to be deleted from the A map and B map, then delete the object. Subscribe is just a matter of creating the Subscription object and adding values to the Guid Map, A Map, and B Map.
Doing a look up based on (A , B), if either A or B is null, you do the look up in the other hash table and trigger the Subscription that is returned. If Neither A nor B are null, things get more tricky.
Here, the thing to do would be to find an intersection on the sets returned by looking up A and looking up B.This can be done manually, but a speedier method might just be to have one additional map which the key is B appended to A.
|
1,805,445 | 1,805,474 | Boost lib linker error Visual C++ | I downloaded the source for Launchy and am trying to build it in Visual Studio 2005. The Launchy project is built using VC7 so I had to update the project files to VC8 and that process seemed to go well. However, Launchy also uses the Boost 1.33.1 libs and what I have built are the Boost 1.41.0 libs (props to Boost for making the more recent libs much easier to build), so I also updated the project to point to my new Boost libs install. Now I get the following linker error:
fatal error LNK1104: cannot open file 'libboost_regex-vc80-mt-sgd-1_41.lib'
I had a look in the Boost lib directory and the closest match that I could find is...
libboost_regex-vc80-mt-gd-1_41.lib
Notice the missing 's'. I don't understand what the difference in libs is, and whether Visual Studio is looking for the wrong thing or my Boost build process failed to build the right libs. Can anybody point me in the right direction?
As an experiment, I made a copy of the regex lib that I have and renamed it to what the linker is looking for. That gives me a long list of linker errors about symbols already being defined in msvcrtd.lib, such as the following:
error LNK2005: "private: __thiscall type_info::type_info(class type_info const &)" (??0type_info@@AAE@ABV0@@Z) already defined in libcmtd.lib(typinfo.obj)
I will try to build the Boost 1.33.1 libs and point my Launchy project file at that instead. But I'd still like to know what is wrong with my Boost 1.41.0 libs.
Edit: I found a reference in the Boost docs to what the 's' libs are:
Use this library when linking statically to the C++ standard library and compiler runtime support libraries.
So it looks like the 's' libs are the right ones. Now I just have to figure out how to build them.
Solution: I was able to build the missing boost libs with the following command-line.
bjam --build-type=complete msvc stage
I ran that after already running boostrap.bat in the dir where boost lives.
| Difference is clearly described in Boost docs - "mt-sgd" means "debug, statically linked runtime libraries, multithreaded, with debug symbols". "mt-gd" is the same, but using dynamically linked runtime libraries (i.e. msvcrtd.lib instead of libcmtd.lib).
Either change project settings to use dynamic CRT linking (i.e. /MDd instead of /MTd), or build Boost using static linking - mixing those won't work properly.
|
1,805,666 | 1,806,759 | How to store a vector of LPD3DXSPRITE objects? | Let's say I want to store a vector of LPD3DXSPRITE objects. The line to declare this code would be std::vector<LPD3DXSPRITE> sprites; I should be able to create my sprite with:
LPD3DXSPRITE sprite = NULL;
D3DXCreateSprite(myRenderingDevice, &sprite);
Finally, I should be able to add this to the vector like so:
sprites.push_back(sprite);
At least with my understanding, that should be plausible. However, this compiles but gives runtime errors. Why is this? Am I going about it wrong? How might I fix it?
edit:
This may be helpful as well. The call stack yields for this function that vector<ID3DXSprite *, std::allocator<ID3DXSprite *>>::push_back(ID3DXSprite * const &_Val=0x0036fd38 is what is called. This is not the vector that it was passed.
However, LPD3DXSPRITE is just a typedef for ID3DXSprite *. Could this bring anything to light?
| After looking through your code, I found the problem. Something to look at when you get any breaks in your application is the "Autos" tab or the Locals tab. Here you'll notice something about the this pointer: it's null!
That means the instance that AddSprite is being called on doesn't exist. This is your SpriteManager, which I see is a singleton. In your main, you don't create an instance of it.
I had to do a couple things to get it working. I included "LudoRenderer/SpriteManager.h" in Main.cpp, and added the CreateInstance call:
SpriteManager::CreateInstance();
The only problem with this was that you had declared your constructor/destructor private, like other singletons, but never defined them, so I did that as well:
SpriteManager::SpriteManager(){}
SpriteManager::~SpriteManager(){}
After those changes, it "worked". That's in quotes because your problem is solved, but there is another error later in the code m_GameManager->SetWagon(m_Wagon);.
Here, m_GameManager is not initialized. I uncommented m_GameManager = GameManager::GetInstance(); on line 43 in LudoEngine.cpp, which put us in the same problem as before, no CreateInstance is ever called. I added the necessary header in main, called the create method. This fixed the problem, and your engine ran (cool demo, too!)
There was a crash on exit, in ErrorLogger::LogError, because ErrorLogger was null. It was being called in LudoMemory's destructor, but I'll leave this one for you. :)
Now, two tips I tihnk that would help. The first is about the issue we're solving. Normally, singletons will create themselves if they aren't already. I'd change your singleton GetInstance to something like this:
static T *GetInstance ( )
{
if (!m_Singleton) // or == NULL or whatever you prefer
{
CreateInstance();
}
return m_Singleton; // not sure what the cast was for
}
This will force creation of the singleton if it hasn't been already. Now, if you'd like users to call CreateInstance before trying to GetInstance, you could add some sort of warning:
static T *GetInstance ( )
{
if (!m_Singleton) // or == NULL or whatever you prefer
{
CreateInstance();
std::cerr << "Warning, late creation of singleton!" << std::endl;
// or perhaps:
ErrorLogger::GetInstance()->
LogError(L"Warning, late creation of singleton!");
}
return m_Singleton;
}
Since that leaves out the important information "which singleton?", you could always try to add typeinfo to it:
#include <typeinfo>
// ...
std::cerr << "Warning, late creation of singleton: "
<< typeid(T).name() << std::endl;
To try to get some type names in there.
And lastly, it's okay to delete 0, your checked delete macro is not needed.
To clarify, you have LUDO_SAFE_DELETE, which checks if it's not null before it calls delete. In C++, deleting null has no effect, so your check isn't needed. All instances of your safe delete could be replaced with just your LUDO_DELETE.
|
1,805,906 | 1,805,917 | C / C++ Library for HTTPS Client with Basic Authentication | Do you recommend any good library or examples online for implementing an HTTPS client that can connect to a website using basic authentication? This is meant to run in linux servers.
Any pointers help.
Update: Question about the unanimous libcurl - does it come bundled by default in major distributions like Debian, Ubuntu, Gentoo, Slackware, RedHat and Arch?
| libcurl supports both HTTPS and HTTP Basic Authentication. There's plenty of example code online.
All of the distributions you mention have libcurl packaged. It is not absolutely certain to be installed, but it is very common.
|
1,806,022 | 1,806,038 | Is this code legal in C++ | I just found that when it comes to templates this code compiles in g++ 3.4.2 and works unless m() is not called:
template <typename T>
class C
{
T e;
public:
C(): e(0) {};
void m()
{
e = 0;
};
};
Now one may create and use instance
C<const int> c;
Until c.m() is not called there are no compile errors but is this legal?
| Yes, this is legal. The template specification is that until a method is instantiated, it doesn't exist and therefor is not checked by the compiler. Here's the relevant bit from the spec:
14.7.1 - Implicit instantiation
-9- An implementation shall not implicitly instantiate a function
template, a member template, a
non-virtual member function, a member
class or a static data member of a
class template that does not require
instantiation.
|
1,806,074 | 1,806,116 | C++ extract polynomial coefficients | So I have a polynomial that looks like this: -4x^0 + x^1 + 4x^3 - 3x^4
I can tokenize this by space and '+' into: -4x^0, x^1, 4x^3, -, 3x^4
How could I just get the coefficients with the negative sign: -4, 1, 0, 4, -3
x is the only variable that will appear and this will alway appear in order
im planning on storing the coefficients in an array with the array index being the exponent
so: -4 would be at index 0, 1 would be at index 1, 0 at index 2, 4 at index 3, -3 at index 4
| Once you have tokenized to "-4x^0", "x^1", etc. you can use strtol() to convert the textual representation into a number. strtol will automatically stop at the first non-digit character so the 'x' will stop it; strtol will give you a pointer to the character that stoped it, so if you want to be paranoid, you can verify the character is an x.
You will need to treat implicit 1's (i.e. in "x^1" specially). I would do something like this:
long coeff;
if (*token == 'x')
{
coeff = 1;
}
else
{
char *endptr;
coeff = strtol(token, &endptr, 10);
if (*endptr != 'x')
{
// bad token
}
}
|
1,806,390 | 1,807,119 | Does a boolean condition in a for loop that is always false get optimized away? | I have the following situation
bool user_set_flag;
getFlagFromUser(&user_set_flag);
while(1){
if(user_set_flag){
//do some computation and output
}
//do other computation
}
The variable user_set_flag is only set once and only once in the code, at the very start, its essentially the user selecting what he wants to do with the program. Say that the user selects user_set_flag = false then will the compiler compile the code in such a way such that the if(user_set_flag) statement will only be checked once, or will it be always checked. Can I give the compiler hints like setting the bool to a const?
The reason I ask this is because my application is time-critical and it processes frames as fast as possible. A branch that is always false should be able to be determined at run-time somehow?
| Firstly, processors have a capability called branch prediction. After a few runs of the loop, the processor will be able to notice that your if statement always goes one way. (It can even notice regular patterns, like true false true false.) It will then speculatively execute that branch, and so long as it able to predict correctly, the extra cost of the if statement is pretty much eliminated. If you think that the user is more likely to choose true rather than false, you can even tell this to the gcc compiler (gcc-specific extension).
However, you did mention in one of your comments that you have a 'much more complicated sequence of bools'. I think it is possible that the processor doesn't have the memory to pattern-match all those jumps -- by the time it comes back to the first if statement, the knowledge of which way that jump went has been displaced from its memory. But we could help it here...
The compiler has the ability to transform loops and if-statements into what it thinks are more optimal forms. E.g. it could possibly transform your code into the form given by schnaader. This is known as loop unswitching. You can help it along by doing Profile-Guided Optimization (PGO), letting the compiler know where the hotspots are. (Note: In gcc, -funswitch-loops is only turned on at -O3.)
You should profile your code at the instruction level (VTune would be a good tool for this) to see if the if-statements are really the bottleneck. If they really are, and if by looking at the generated assembly you think the compiler has got it wrong despite PGO, you can try hoisting out the if-statement yourself. Perhaps templated code would make it more convenient:
template<bool B> void innerLoop() {
for (int i=0; i<10000; i++) {
if (B) {
// some stuff..
} else {
// some other stuff..
}
}
}
if (user_set_flag) innerLoop<true>();
else innerLoop<false>();
|
1,806,669 | 1,807,795 | Vertical Scrollbar in CListCtrl | I'm using a CListCtrl in Icon view, but it scrolls horizontally:
1 3 5 7 -->
2 4 6 8 -->
I'd rather it scroll horizontally:
1 2
3 4
5 6
| |
V V
Is there a way to do this?
| Change the Alignment style in designer from Left to Top.
|
1,806,687 | 1,806,752 | Why isn't my virtual function working? | I have an abstract class called camera which PointCamera uses as its super class. For some reason one of the virtual functions throw an error in the debugger and tells me that it is trying to execute 0x00000000. This only happens if the function in question is the last one declared in the abstract class. If I switch the declaration order, then the new last function won't work for the same reason. Why is this happening?
class Camera
{
public:
//Default constructor
Camera();
//Assignment operator
virtual Camera* clone() = 0;
//Get a ray
virtual void KeyCamera() = 0;
virtual void GetRay(float x, float y, Ray* out) = 0;
};
and
class PointCamera: Camera
{
private:
//Camera location, target, and direction
Vector loc, dir, tar, up;
//Orthonormal vectors
Vector u, v, w;
//Virtual plane size
float plane_width, plane_height;
int width, height;
//Distance from the camera point to the virtual plane
float lens_distance;
//Pixel size
float pixelSizex, pixelSizey;
public:
//Default constructor
PointCamera();
//Constructors
PointCamera(Vector& iloc, Vector& itar);
PointCamera(Vector& iloc, Vector& itar, Vector& idir);
//Destructor
~PointCamera();
//Modifiers
void SetDirection(Vector& idir);
void SetUp(Vector& iup);
void SetTarget(Vector& itar);
void SetLocation(Vector& iloc);
void SetPlane(int iheight, int iwidth, float iplane_width = -1.0f, float iplane_height = -1.0f);
void SetLensDistance(float ilens_distance);
//Implememented method
virtual void GetRay(float x, float y, Ray* out);
virtual void SetupRay(Ray* out);
//Compute orthonormal vectors
virtual void KeyCamera();
};
|
Ok I just re-compiled everything and it worked. I don't know what went wrong. Thanks for your suggestions.
Check your dependencies. I bet something that should be depending on a header file isn't. When you did a clean build, the source code file that relied on that header file was brought up to date.
|
1,806,711 | 1,806,737 | weird C++ constructor/copy constructor issues in g++ | #include <iostream>
using namespace std;
class X {
public:
X() {
cout<<"Cons"<<endl;
}
X(const X& x){
cout<<"Copy"<<endl;
}
void operator=(const X& x){
cout<<"Assignment called";
}
};
X& fun() {
X s;
return s;
}
int main(){
X s = fun();
return 0;
}
This code calls the copy constructor also. Why does this work? I recall that the first time I ran this program, it seg faulted. But after a while, it started calling this copy cons. and now works!! Wierd.
But if I replace, fun() as follows:
X fun() {
X s;
return s;
}
Then copy cons. is not called. I thought that the copy cons. would be called in this case. But as pointed out by @flyfishr64, RVO is coming into play here. But it still does not explain the case where I am returning a reference. I think it should always segfault.
Any explanations?
| To expand on @flyfishr64's answer
The copy constructor is invoked here because this:
X s = fun();
is an initialization. You are using fun() to construct the object, not invoking the default constructor. It is equivalent to:
X s(fun());
The "Cons" you see printed out is for the instance in fun(). See this article: Assignment operator in C++ for more.
|
1,807,033 | 1,807,435 | C++ GNU Linker Errors | I'm trying to complie my program on Windows via Cygwin with the compilation command:
g++ ping.cpp -I./include -L./lib -lchartdir50
I'm using an API called ChartDirector which draws charts for me. I've never linked libraries this way before (usually I do it through Visual Studio) so i'm a little new to this. I've got a really large list of errors, so I won't list them all, but i'll list one just to clarify the type of linker errors i'm getting:
(.text$_ZN9BaseChartD1Ev[BaseChart::~BaseChart()]+0x4f): undefined reference to '_CBaseChart_destroy'
All of these are undefined reference to 'xxx' errors.
I've got a bunch of header files in ./include and a library called chartdir50.lib in ./lib
Whats wrong with my compilation line?
| Hmm... thats odd. I'm using a 64-bit system, but for some reason I tried it with the 32-bit library and it compiled. Thanks!
|
1,807,110 | 1,807,117 | Is it possible to have a while loop in c++ that makes the check in the middle of the loop instead of the beginning or end? | I want to have a while loop do something like the following, but is this possible in c++? If so, how does the syntax go?
do {
//some code
while( expression to be evaluated );
// some more code
}
I would want the loop to be exited as soon as the while statement decides the expression is no longer true( i.e. if expression is false, //some more code is not executed)
| You can do:
while (1) {
//some code
if ( condition) {
break;
}
// some more code
}
|
1,807,203 | 1,807,422 | Building optimized Qt4 - "./configure" flags and their meanings | I recently followed a discussion on the Qt4-interest mailing list about whether it is legal or not to build a commercial/proprietary application and statically link Qt4 into it. While there are some non-proven ways of doing so (by providing object files and a Makefile, etc. to the customer), it doesn't sound like such a good idea afterall.
One of my projects is using the LGPL-licensed Qt4 libraries and I ship them as separate DLLs/Dylibs/so's to my customer, using a simple installer on all platforms. While this works pretty good so far, I'd like to optimize a) the size of the installer by reducing the Qt library size by just including what I need, b) increase the startup/loading speed of my application.
I'm familiar with compiling Qt myself, but Qt got a lot of flags and switches.
Right now I'm building with the following flags:
./configure \
-fast \
-opensource \
-qt-sql-sqlite \
-nomake demos examples \
-silent \
-no-qt3support \
-no-gif \
-plugin-sql-mysql \
-release \
-no-xmlpatterns \
-no-multimedia
I'm not entirely sure which effect/impact the following flags have:
-no-stl
-no-javascript-jit
-no-nis
-separate-debug-info
-no-openvg
-no-mitshm
Is there anything else I can do, for instance, by providing optimization switches for the compiler, or "stripping" unused functions out of the built Qt library to make it smaller (which would be easy with static builds). I don't have much experience with that.
Oh, just as a side-note, my compiled application size is about 600 kb (non-stripped) when linking against Qt dynamically. I experimented with it and found it to be around 4 MB in size when I link statically; but that way I wouldn't have to include 40 MB of Qt libraries anymore.
So, to put everything above into a question/request:
If you are more advanced than me on this topic, how do you optimize/deploy your own applications and make sure they start fast and only contain what is needed?
| There are few things that I can think of:
use a compiler/linker combination that does good size optimizations. MSVC is much better at this than MinGW for instance. All the Qt release DLLs built with MSVC total at ~21 MB. Built with MinGW they total at ~41 MB. By the way, do you really need to ship all the DLLs?
use the -ltcg (Link-time code generation) flag to optimize across object files.
use preprocessor flags to exclude parts of the Qt functionality. e.g: QT_NO_STL = -no-stl.
try the mmx/3d now/sse2 flags
remove some of the styles (-no-style-)
|
1,807,297 | 1,807,321 | Question about what I should have before Connect | I have this included:
#include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
/* Establish the connection to the echo server */
if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
DieWithError("connect() failed");
But I am getting this:
TCPClient.cpp:395: error: no matching
function for call to
‘ClientHandler::connect(int&,
sockaddr*, unsigned int)’
The thing is I am also using QT.
should I have somethihng before "connect"...
SOMETHING::connect(....)
Thanks :)
| I guess you have your own class ClientHandler with a connect method. To avoid confusion call connect from the global namespace:
::connect ( sock, ...
|
1,807,338 | 1,812,036 | Code leaks memory, seems to be coming from ID3DXBuffer | I load a shader with the following:
ID3DXBuffer* errors = 0;
ID3DXEffect* effect = 0;
HR(D3DXCreateEffectFromFile(
gd3dDevice, L"Shader.fx", 0, 0,
D3DXSHADER_DEBUG|D3DXSHADER_SKIPOPTIMIZATION,
0, &effect, &errors));
for (int i = 0; i < 3; i++) {
if(errors) {
errors->Release();
if (effect)
effect->Release();
errors = 0;
HR(D3DXCreateEffectFromFile(gd3dDevice, L"Shader.fx",
0, 0, D3DXSHADER_DEBUG, 0, effect, &errors));
}
else
break;
}
Which is trying to load a shader and if it gets an error/warning it tries again 3 more times before giving up.
Now I've found when I close the application D3DX gives me the following message:
D3DX: MEMORY LEAKS DETECTED: 2 allocations unfreed (486 bytes)
and this ONLY happens when there are errors (i.e. it goes into the loop). I'm really not sure why this is happening, any ideas?
OK I fixed it, was just a logic issue, 'error' didn't have 'release' called on it on the third try hence the issue.
| OK I fixed it, was just a logic issue, 'error' didn't have 'release' called on it on the third try hence the issue.
|
1,807,360 | 1,807,431 | Conditionally instantiate a template at run-time | I have a template class
template <class T>
class myClass
{
public:
/* functions */
private:
typename T::Indices myIndices;
};
Now in my main code I want to instantiate the template class depending on a condition. Like :
myFunc( int operation)
{
switch (operation) {
case 0:
// Instantiate myClass with <A>
auto_ptr < myClass <A> > ptr = new myClass<A> ();
case 1:
// Instantiate myClass with <B>
auto_ptr < myClass <B> > ptr = new myClass<B> ();
case 2:
// Instantiate myClass with <C>
....
}
// Use ptr here..
}
Now the problem with this approach is that the auto_ptr<> will die at the end of switch{}.
And I can't declare it at the beginning of the function, because I don't know the type that will be instantiated before-hand.
I know I'm trying to achieve a run-time thing at compile-time (using template), but still wanted to know if there is some better way to do this.
| Create a base class
class Base {
protected:
virtual ~Base() {}
//... functions
};
template <class T> class myClass : Base {
//...
};
myFunc( int operation){
shared_ptr < Base > ptr;
switch (operation) {
case 0:
// Instantiate myClass with <A>
ptr.reset ( new myClass<A> () );
case 1:
// Instantiate myClass with <B>
ptr.reset ( new myClass<B> () ) ;
case 2:
// Instantiate myClass with <C> ....
}
// Use ptr here..
}
|
1,807,516 | 1,807,532 | Conditional operator issue | I'm having some trouble with using the conditional operator to get a reference to an object. I have the a setup similar to this:
class D
{
virtual void bla() = 0;
};
class D1 : public D
{
void bla() {};
};
class D2 : public D
{
void bla() {};
};
class C
{
public:
C()
{
this->d1 = new D1();
this->d2 = new D2();
}
D1& getD1() {return *d1;};
D2& getD2() {return *d2;}
private:
D1 *d1;
D2 *d2;
};
int main()
{
C c;
D& d = (rand() %2 == 0 ? c.getD1() : c.getD2());
return 0;
}
When compiling, this gives me the following error:
WOpenTest.cpp: In function 'int
main()': WOpenTest.cpp:91: error: no
match for conditional 'operator?:' in
'((((unsigned int)rand()) & 1u) == 0u)
? c.C::getD1() : c.C::getD2()'
I understand this is illegal according to the C++ standard (as seen in this blog post), but I don't know how to get my reference to D without using the conditional operator.
Any ideas?
| Cast to D& within both branches:
D& d = (rand() %2 == 0 ? static_cast<D&>(c.getD1()) : static_cast<D&>(c.getD2()));
|
1,807,523 | 1,807,601 | Instantiation of function object with different inline function definitions depends on order of linkage | Please help me understand the root cause of the following behaviour.
In file a.cpp I have:
namespace NS {
struct Obj {
void pong(){ cout << "X in "__FILE__ << endl; }
double k;
};
X::X() { Obj obj; obj.pong(); }
void X::operator()() { cout << "X says hello" << endl; }
}
In file b.cpp I have:
namespace NS {
struct Obj {
void pong(){ cout << "Y in "__FILE__ << endl; }
bool m;
};
Y::Y() { Obj obj; obj.pong(); }
void Y::operator()() { cout << "Y says hello" << endl; }
}
My main creates an X, an Y and calls their operator()s:
int main( int argc, char *argv[] )
{
NS::X x;
x();
NS::Y y;
y();
return 0;
}
The output of this program depends on whether a.cpp or b.cpp gets compiled first: in the first case the Obj from a.cpp is instantiated also within NS::Y's constructor, in the second case the Obj from b.cpp is instantiated in both NS::X and NS::Y.
% g++ b.cpp a.cpp main.cpp
% ./a.out
X in a.cpp
X says hello
Y in b.cpp
Y says hello
% g++ b.cpp a.cpp main.cpp
% ./a.out
Y in b.cpp
X says hello
Y in b.cpp
Y says hello
No warnings from the linker either on Linux or Visual Studio (2005). If I define Obj::pong() outside the declaration of the struct I get a linker error telling me that the Obj::pong function is multiply defined.
I experimented a bit further and found out that the cause must be related to whether or not the inlining, because if I compile with -O3, the each object uses the Obj from his own translation unit.
So then the question changes to: what happens to the second definition of the inline function during non-optimized compilation? Are they silently ignored?
| This is undefined behavior: The your class definitions define the same class type, and so they have to be both the same. For the linker it means it can choose one arbitrary definition as the one that gets emitted.
If you want them to be separated types, you have to nest them into an unnamed namespace. This will cause anything in that namespace to be unique for that translation unit:
namespace NS {
namespace {
struct Obj {
void pong(){ cout << "Y in "__FILE__ << endl; }
bool m;
};
}
Y::Y() { Obj obj; obj.pong(); }
void Y::operator()() { cout << "Y says hello" << endl; }
}
So then the question changes to: what happens to the second definition of the inline function during non-optimized compilation? Are they silently ignored?
Yes, for inline functions (functions defined within class definitions are inline, even if not explicitly declared inline), the same principle applies: They can be defined multiple times in the program, and the program behaves as if it was defined only once. To the linker it means again it can discard all but one definition. Which one it chooses is unspecified.
|
1,807,530 | 1,807,556 | Difference between using character pointers and character arrays | Basic question.
char new_str[]="";
char * newstr;
If I have to concatenate some data into it or use string functions like strcat/substr/strcpy, what's the difference between the two?
I understand I have to allocate memory to the char * approach (Line #2). I'm not really sure how though.
And const char * and string literals are the same?
I need to know more on this. Can someone point to some nice exhaustive content/material?
| Please go through this article below:
Also see in case of array of char like in your case, char new_str[] then the new_str will always point to the base of the array. The pointer in itself can't be incremented. Yes you can use subscripts to access the next char in array eg: new_str[3];
But in case of pointer to char, the pointer can be incremented new_str++ to fetch you the next character in the array.
Also I would suggest this article for more clarity.
|
1,807,617 | 1,820,743 | C/C++ Macro expansion vs. Code generation | Both Macro expansion & Code generation have pros & cons. What's your favorite approach and why? When should we choose one over the other? Please kindly advise. Thank you!
Macro expansion can be very handy & helpful:
http://dtemplatelib.sourceforge.net/table.htm
vs
While Code generation gives you plenty of nice code:
http://code.google.com/p/protobuf/
http://incubator.apache.org/thrift/
| It's a tradeoff. Let me give an example. I stumbled on the technique of differential execution around 1985, and I think it's a really good tool for programming user interfaces. Basically, it takes simple structured programs like this:
void Foo(..args..){
x = y;
if (..some test..){
Bar(arg1, ...)
}
while(..another test..){
...
}
...
}
and mucks with the control structure like this:
void deFoo(..args..){
if (mode & 1){x = y;}
{int svmode = mode; if (deIf(..some test..)){
deBar(((mode & 1) arg1 : 0), ...)
} mode = svmode;}
{int svmode = mode; while(deIf(..another test..)){
...
} mode = svmode;}
...
}
Now, a really good way to do that would have been to write a parser for C or whatever the base language is, and then walk the parse tree, generating the code I want. (When I did it in Lisp, that part was easy.)
But who wants to write a parser for C, C++, or whatever?
So, instead, I just write macros so that I can write the code like this:
void deFoo(..args..){
PROTECT(x = y);
IF(..some test..)
deBar(PROTECT(arg1), ...)
END
WHILE(..another test..)
...
END
...
}
However, when I do this in C#, somebody in their wisdom decided macros were bad, and I don't want to write a C# parser, so I gotta do the code generation by hand. This is a royal pain, but it's still worth it compared to the usual way of coding these things.
|
1,807,663 | 1,807,729 | How to write a const_iterator in VC++6? | I have implemented my own container class and need to implement a const_iterator for it. What is the easiest way to go about implementing const_iterator begin() const_iterator end() and const_iterator::operator++ for my own container class?
Please provide examples. Thanks!
| It seems boost library has a compatible version to be used with VC6 according to this question. In that case you can use either boost::iterator_facade or boost::iterator_adaptor to easily write a const_iterator class. If you can't use boost, then the only option I see is to write a class derived from std::iterator and write all the required operator overloads.
|
1,807,816 | 1,807,842 | constructor as default argument | let's say i have 2 classes
class B
{
B() { /* BLA BLA */ };
B(int a) { /* BLA BLA */ };
B(int a,int b) { /* BLA BLA */ };
}
class A {
public :
A(B par);
}
i was wondering how can i call A's constructor with par having a deafult argument, as each of B constructors. (of course i would like see 3 examples, i don't expect all of them to exist together)
thanks
| You can do something like:
A(B par = B())
A(B par = B(1))
A(B par = B(1,2))
Full code as per comment:
class B
{
public:
B() { };
B(int a) {};
B(int a,int b) {};
};
class A {
public :
A(B par = B()/* or B(1) or B(1,2) */);
};
|
1,807,857 | 1,807,947 | repeatedly render loop with Qt and OpenGL | I've made a project with Qt and OpenGL.
In Qt paintGL() was repeatedly call I beleive, so I was able to change values outside of that function and call update() so that it would paint a new image.
I also believe that it called initializeGL() as soon as you start up the program.
Now my question is:
I want that same functionality in a different program. I do not need to draw any images, etc. I just was wondering if there was a way to make a function like paintGL() that keeps being called so the application never closes. I tried just using a while(true) loop that kept my program running, but the GUI was inactive because of the while loop.
Any tips, other than threading preferably.
Thanks.
| The exact mechanism will depend on which GUI toolkit you are using. In general, your app needs to service the run loop constantly for events to be dispatched. That is why your app was unresponsive when you had it running in a while loop.
If you need something repainted constantly, the easiest way is to create a timer when your window is created, and then in the timer even handler or callback, you invalidate your window which forces a repaint. Your paint handler can then be called at the frequency of your timer, such as 25 times per second.
|
1,807,944 | 1,808,025 | wxImage to Zip file via stream. Possible? | I'm trying to write out a zip file using the wxZipOutputStream. The code is from this forum and works with the xml file (when I used wxTextOutputStream). Now, I'm trying to include an image file but the SaveFile function in the wxImage class expects a class wxOutputStream but wxTextOutputStream/wxDataOutputStream have no base class so I can't compile it. I just want to write out a wxImage and an xml file to a zip. how do I go about it?
//convert stream to zip file.
wxFFileOutputStream out(m_loaded_filename.GetFullPath());
wxZipOutputStream zip(out);
// wxTextOutputStream txt(zip);
wxDataOutputStream txt(zip);
zip.PutNextEntry("my.xml");
txt << xmltext;
...
...
...
//value is wxImage*
//key is wxString
zip.PutNextEntry(key); //filename
if(value->IsOk())
{
value->SaveFile(zip); //compiler throws error.
}
| It looks like you have to specify the type of image in the archive, try:
value->SaveFile(zip, wxBITMAP_TYPE_PNG)
(The file extension in key should of course be .png)
|
1,807,983 | 1,808,723 | Dividing by arbitrary numbers using shifting operators | How can you divide a number n for example by 24 using shifting operators and additions?
(n % 24 == 0)
| This works by first finding the highest bit of the result, and then working back.
int div24(int value) {
// Find the smallest value of n such that (24<<n) > value
int tmp = 24;
for (int n = 0; tmp < value; ++n)
tmp <<= 1;
// Now start working backwards to find bits of the result. This is O(i).
int result = 0;
while(value != 0) {
tmp >>= 1;
result <<= 1;
if (value > tmp) { // Found one bit.
value -= tmp; // Subtract (24<<i)
result++;
}
}
return result;
}
Example:
Value = 120 : n = 2
Step 0: tmp = 96, result = 0, value = 24, result = 1
Step 1: tmp = 48, result = 2
Step 2: tmp = 24, result = 4, value = 0, result = 5
|
1,808,342 | 1,808,364 | Question about how to send images in socket programming? | I've got a couple questions about sending images over.
How do I handle different types of files, jpeg, png, etc.
If the file is large, I ave to use sequence numbers... but I don't know how to stop recving if I do not know the number of sequence numbers.
My knowledge of transfering images / files is next to none. I have never programmed anything like that before. Was hoping to get some tips and tricks =)
Thanks alot.
I am also using QT, if that helps my situation at all.
| If you use a TCP socket, you need no sequence numbers, because TCP already ensures that data arrive in the same order as they where send. Just send the data, and when done close the connection. Optionally you can use some self-defined type of packet header that gives additional information (e.g. if you want to transmit multiple files over one connection).
|
1,808,471 | 1,808,579 | Is "const LPVOID" equivalent to "void * const"? | And if so, why some Win32 headers use it?
For instance:
BOOL APIENTRY VerQueryValueA( const LPVOID pBlock,
LPSTR lpSubBlock,
LPVOID * lplpBuffer,
PUINT puLen
);
A bit more elaboration: If the API never uses references (or any other C++-only constructs) but only pointers and values, what is the point of having const LPVOID vs. LPCVOID.
Should I treat every place I see const LPVOID as some place where the real meaning is LPCVOID? (and thus it is safe to add a cast)
Further clarification: It appears that const LPVOID pBlock was indeed a mistake in this case. Windows 2008 SDK replaces it to LPCVOID in VerQueryValue signature. Wine did so quite some time ago.
| A typedef-name denotes a type, and not a sequence of tokens (as does a macro). In your case, LPVOID denotes the type also denoted by the token sequence void *. So the diagram looks like
// [...] is the type entity, which we cannot express directly.
LPVOID => [void *]
Semantically if you specify the type const LPVOID, you get the following diagram (the brackets around the specifiers mean "the type denoted by the specifier"):
// equivalent (think of "const [int]" and "[int] const"):
const LPVOID <=> LPVOID const => const [void *] <=> [void *] const
=> ["const qualified void-pointer"]
It's not the same thing as the token sequence const void * - because this one would not denote a const qualified pointer type, but rather a pointer to a const qualified type (the thing pointed to would be const).
Syntactically a parameter declaration has the following (simplified) form:
declaration-specifiers declarator
The declaration-specifiers in case of const void *p are const void - so the base-type of *p is a const qualified void, but the pointer itself is not qualified. In case of const LPVOID p however the declaration-specifiers specify a const qualified LPVOID - which means the pointer type itself is qualified, making the parameter declaration identical to void *const p.
|
1,808,485 | 1,808,700 | Division of big numbers | I need some division algorithm which can handle big integers (128-bit).
I've already asked how to do it via bit shifting operators. However, my current implementation seems to ask for a better approach
Basically, I store numbers as two long long unsigned int's in the format
A * 2 ^ 64 + B with B < 2 ^ 64.
This number is divisible by 24 and I want to divide it by 24.
My current approach is to transform it like
A * 2 ^ 64 + B A B
-------------- = ---- * 2^64 + ----
24 24 24
A A mod 24 B B mod 24
= floor( ---- ) * 2^64 + ---------- * 2^64 + floor( ---- ) + ----------
24 24.0 24 24.0
However, this is buggy.
(Note that floor is A / 24 and that mod is A % 24. The normal divisions are stored in long double, the integers are stored in long long unsigned int.
Since 24 is equal to 11000 in binary, the second summand shouldn't change something in the range of the fourth summand since it is shifted 64 bits to the left.
So, if A * 2 ^ 64 + B is divisible by 24, and B is not, it shows easily that it bugs since it returns some non-integral number.
What is the error in my implementation?
| The easiest way I can think of to do this is to treat the 128-bit numbers as four 32-bit numbers:
A_B_C_D = A*2^96 + B*2^64 + C*2^32 + D
And then do long division by 24:
E = A/24 (with remainder Q)
F = Q_B/24 (with remainder R)
G = R_C/24 (with remainder S)
H = S_D/24 (with remainder T)
Where X_Y means X*2^32 + Y.
Then the answer is E_F_G_H with remainder T. At any point you only need division of 64-bit numbers, so this should be doable with integer operations only.
|
1,808,540 | 1,808,565 | string has not been declared, QT | I am trying to change a certain text box message. It will display my output.
This is what I have in my main()
#include "form2.h"
....
string recvMSG = "random";
182:: Form2::changeOutput(recvMSG);
...
within my form2.h I have:
#include <string.h>
#include <iostream>
#include <stdlib.h>
...
void Form2::changeOutput(string s)
{
QString s1 = i18n(s);
output_box.setText(s1);
}
But i still get:
.ui/form2.h:56: error: ‘string’ has not been declared
Thanks.
Edit:: kk so now its showing::
TCPClient.cpp:182: error: cannot call member function ‘virtual void Form2::changeOutput(std::string)’ without object
| string is in the std namespace, so you either need to refer to it as std::string, or you need to make the name available in the current scope with using namespace std; or using std::string;.
Also the header is called string, not string.h, so include it this way:
#include <string>
Generally you also might want to use QT's QString instead of std::string if you are using it in connection with QT components that usually take QString parameters.
|
1,808,581 | 1,809,773 | Char * marshalling in C# | I have this function in Visual C++ DLL
char * __stdcall GetMessage(int id) {
char buffer[250];
.
.
.
strcpy(buffer, entry); // entry is a char * that has allocated 250 chars
return (char *)buffer;
}
i am trying to import this function from C# with the following code
[DllImport("mydll.dll", CharSet=CharSet.Ansi)]
public static extern string GetMessage(int id);
I am trying to present this in a MessageBox it always has strange symbols in the end of the string. Any suggestions how to overcome this problem?
| I'll re-emphasize the fact that your C++ code is invalid. You are returning a pointer to a local variable on a stack frame that is no longer valid when the function returns. That it works now is merely an accident. As soon as you call another function, the stack space will be reused, corrupting the buffer content. This is guaranteed to happen when you call this code from C#, the P/Invoke marshaller implementation will overwrite the stack frame and corrupt the buffer.
To make matters worse, the P/Invoke marshaller will try to free the buffer. It will assume that the buffer was allocated by CoTaskMemAlloc() and call CoTaskMemFree() to release the buffer. That will silently fail on Windows XP and earlier but crash your program on Vista and up.
Which is one solution to your issue, use CoTaskMemAlloc() to allocate the buffer instead of using a local variable. The all-around better solution is to let the caller of the function pass the buffer, to be filled with the string. That way, the caller can decide how to allocate the buffer and clean it up as necessary. The function signature should look like this:
extern "C" __declspec(dllexport)
void __stdcall GetMessage(int id, char* buffer, size_t bufferSize);
Use strcpy_s() to safely fill the buffer and avoid any buffer overflow. The corresponding C# declaration would then be:
[DllImport("mydll.dll")]
private static extern void GetMessage(int id, StringBuilder buffer, int bufferSize);
and called like this:
var sb = new StringBuilder(250);
GetMessage(id, sb, sb.Capacity);
string retval = sb.ToString();
|
1,808,971 | 1,809,013 | tryentercritical section undeclared identifier | I get error TryEnterCriticalSection undeclared identifier during compilation. Visual studio knows about the function but the compiler does not. Other Critical Section functions are defined. I have included #define _WIN32_WINNT 0x0400 in stdafx.h per msdn. Definition in winbase.h is surrounded by #if(_WIN32_WINNT >= 0x0400) #endif /* _WIN32_WINNT >= 0x0400 */
straight c++, XP, Visual Studio 6
What's going on?
| Where have you defined the _WIN32_WINNT symbol in the stdafx.h file? Is it before the #include <windows.h> line? If not then the symbol will be undefined in winbase.h.
|
1,808,994 | 1,809,029 | Oracle C++ linux and more weird stuff | So here is the story. I have this device that uses Linux and more open source tools(btw its an ARM). And I was given the task of creating some magic cashier application with it.
I have done it and now my boss have made a new request. He wants me to make that stuff(the device) connect to a remote database(preferably Oracle). So thats what I started doing with the light version of oracle instant client. Everything is fine and cool until I ran my first hello world:
#include <occi.h>
using namespace oracle::occi;
int main(){
Environment *env = Environment::createEnvironment();
Connection *conn = env->createConnection("HR", "password");
env->terminateConnection(conn);
Environment::terminateEnvironment(env);
return 0;
}
Linking against occi, clntsh, thread;
And setting the library search path, along other stuff to: "${workspace_loc:/OracleTest/instantclient_10_2}" that is the directory that holds my .so files;
Here is the compilation command:
ucfront-g++ -Wl,-elf2flt="r" -static -o OracleTest ./main.o -locci -lclntsh -lthread -L/usr/local/arm-elf/lib -L"C:\workspace\OracleTest\instantclient_10_2" -L/usr/local/fit-libs/lib
And here is the error:
/usr/local/arm-elf/bin/ld.real: cannot find -locci collect2: ld returned 1 exit status
And there are a few things that I would like to mention:
1- I'm running windows and compiling this for linux, the instant client version that I've downloaded is for linux x86(No Idea if that will work or if it could be the source of the problem).
2- I'm using a modified version of eclipse to develop, specific for that device.
3- I have no idea if I should move those Oracle libs to the device after the compilation, so if anyone could give me orientation on that, I would be very thankful.
TLDR: I wan't to compile the above code but it fails to link, help, please!
EDIT:
To the two first answers, no I haven't found any specific ARM libraries, I don't think there are any.
Here is the link if anyone can find anything that resemble an ARM distribution I would be thankful.
There are two RISC distribution but I don't know if they are compatible with ARM :
Instant Client for HP-UX PA-RISC (64-bit)
Instant Client for HP-UX PA-RISC (32-bit)
| If you do not have ARM versions of the Oracle library, you're totally out of luck there and would need to get one (perhaps there is a free driver?) or implement the wire protocol manually.
|
1,809,227 | 1,809,259 | How to get the first n elements of a std::map | Since there is no .resize() member function in C++ std::map I was wondering, how one can get a std::map with at most n elements.
The obvious solution is to create a loop from 0 to n and use the nth iterator as the first parameter for std::erase().
I was wondering if there is any solution that does not need the loop (at least not in my user code) and is more "the STL way to go".
| You can use std::advance( iter, numberofsteps ) for that.
|
1,809,364 | 1,812,498 | User-mode synchronization library for C++ | Does anyone know of a Windows user-mode thread synchronization library for C++ (utilizing spin locks / atomic operations)? I only need mutexes (~critical sections), but condition variables would be a plus.
| Thank you for the answers. Turns out that basing my expectations about the size of a threading library on boost was a bad idea, and writing your own synchronization code based on InterlockedExchange is dead-simple. My spinlock code achieves a performance of about 20% better than Win32 critical sections (and I mean real application performance, not a synthetic test) :)
|
1,809,381 | 1,809,481 | Break on NaNs or infs | It is often hard to find the origin of a NaN, since it can happen at any step of a computation and propagate itself.
So is it possible to make a C++ program halt when a computation returns NaN or inf? The best in my opinion would be to have a crash with a nice error message:
Foo: NaN encoutered at Foo.c:624
Is something like this possible? Do you have a better solution? How do you debug NaN problems?
EDIT: Precisions: I'm working with GCC under Linux.
| You can't do it in a completely portable way, but many platforms provide C APIs that allow you to access the floating point status control register(s).
Specifically, you want to unmask the overflow and invalid floating-point exceptions, which will cause the processor to signal an exception when arithmetic in your program produces a NaN or infinity result.
On your linux system this should do the trick:
#include <fenv.h>
...
feenableexcept(FE_INVALID | FE_OVERFLOW);
You may want to learn to write a trap handler so that you can print a diagnostic message or otherwise continue execution when one of these exceptions is signaled.
|
1,809,679 | 1,809,753 | Difference between implementing a class inside a .h file or in a .cpp file | I was wondering which are the differences between declaring and implementing a class solely in a header file, compared with normal approach in which you protype class in the header and implement in effective .cpp file.
To explain better what I'm talking about I mean differences between normal approach:
// File class.h
class MyClass
{
private:
//attributes
public:
void method1(...);
void method2(...);
...
};
//file class.cpp
#include "class.h"
void MyClass::method1(...)
{
//implementation
}
void MyClass::method2(...)
{
//implementation
}
and a just-header approach:
// File class.h
class MyClass
{
private:
//attributes
public:
void method1(...)
{
//implementation
}
void method2(...)
{
//implementation
}
...
};
I can get the main difference: in the second case the code is included in every other file that needs it generating more instances of the same implementations, so an implicit redundancy; while in the first case code is compiled by itself and then every call referred to object of MyClass are linked to the implementation in class.cpp.
But are there other differences? Is it more convenient to use an approach instead of another depending on the situation? I've also read somewhere that defining the body of a method directly into a header file is an implicit request to the compiler to inline that method, is it true?
| The main practical difference is that if the member function definitions are in the body of the header, then of course they are compiled once for each translation unit which includes that header. When your project contains a few hundred or thousand source files, and the class in question is fairly widely used, this might mean a lot of repetition. Even if each class is only used by 2 or 3 others, the more code in the header, the more work to do.
If the member function definitions are in a translation unit (.cpp file) of their own, then they are compiled once, and only the function declarations are compiled multiple times.
It's true that member functions defined (not just declared) in the class definition are implicitly inline. But inline doesn't mean what people might reasonably guess it means. inline says that it's legal for multiple definitions of the function to appear in different translation units, and later be linked together. This is necessary if the class is in a header file that different source files are going to use, so the language tries to be helpful.
inline is also a hint to the compiler that the function could usefully be inlined, but despite the name, that's optional. The more sophisticated your compiler is, the better it is able to make its own decisions about inlining, and the less need it has for hints. More important than the actual inline tag is whether the function is available to the compiler at all. If the function is defined in a different translation unit, then it isn't available when the call to it is compiled, and so if anything is going to inline the call then it's going to have to be the linker, not the compiler.
You might be able to see the differences better by considering a third possible way of doing it:
// File class.h
class MyClass
{
private:
//attributes
public:
void method1(...);
void method2(...);
...
};
inline void MyClass::method1(...)
{
//implementation
}
inline void MyClass::method2(...)
{
//implementation
}
Now that the implicit inline is out of the way, there remain some differences between this "all header" approach, and the "header plus source" approach. How you divide your code among translation units has consequences for what happens as it's built.
|
1,809,810 | 1,810,315 | QT creating my form objects, how to access that form? | I am trying to change a certain text box message. It will display my output.
This is what I have in my TCPClient()
#include "form2.h"....string recvMSG = "random";
QString s1 = QString::fromLocal8Bit(recvMSG.c_str());
182:: Form2::changeOutput(s1);
within my form2.h I have:
...
void Form2::changeOutput(QString &s)
{
output_box.setText(s1);
}
...
In my main:
#include <qapplication.h>
#include "form2.h"
#include <string.h> /* for memset() */
#include <iostream>
#include <stdlib.h> /* for atoi() and exit() */
int main( int argc, char ** argv )
{
QApplication a( argc, argv );
Form2 w;
w.show();
a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) );
return a.exec();
}
Now, I know I should be calling w.changeOutput(s1).
But problem is, w isn't declared within my TCPClient.cpp...
QT made the main() function for me. I am not sure how to solve this problem. I want to beable to call w.changeOutput(s1) from within my TCPClient.cpp.
This is the error im getting.
TCPClient.cpp:182: error: cannot call member function ‘virtual void Form2::changeOutput(std::string)’ without object
Thanks.
| If I understood the problem correctly, I think the proper "Qt-way" would be to have the TCP client send a signal when it receives a message, and then in your main function connect that signal to the changeOutputs slot.
|
1,809,816 | 1,809,885 | How to use std::transform with templates | I am struggling to find out why I can't get transform to work with a template class.
Here's a simplified version of the template class :
template<typename T>
class base
{
public :
base() : all_() {}
~base() {}
public:
bool add(T t)
{
typename vector<T>::iterator itr
= lower_bound(all_.begin(), all_.end(), t);
if ( itr == all_.end() || *itr != t )
{
all_.push_back(t);
cout << "ok" << endl;
return true;
}
cout << "failed" << endl;
return false;
}
static bool addTo(base<T> *c, T t)
{
return c->add(t);
}
private :
vector<T> all_;
};
And this is where I am trying to use transform to capture all the bool output from the add member function :
main()
{
base<int> test;
vector<bool> results;
vector<int> toAdd;
toAdd.push_back(10);
toAdd.push_back(11);
toAdd.push_back(10);
transform( toAdd.begin(), toAdd.end(),
back_inserter(results),
bind1st( (bool(*)(base<int>*,int))base<int>::addTo, &test ) );
}
The aim is to insert each member of the toAdd container using either base::add or base::addTo, and capture the bool results in the vector results
| Try:
transform( toAdd.begin(), toAdd.end(),
back_inserter(results),
bind1st( mem_fun(&base<int>::add), &test ) );
The problem isn't the template, it's that bind1st relies on extra support to work (see http://www.sgi.com/tech/stl/AdaptableBinaryFunction.html). AFAIK it can't ever operate on plain old function pointers.
boost::bind can do more things, if you want to bring that in. For this situation you don't need it, though: mem_fun turns a non-static member function into an adaptable binary function. addTo therefore isn't needed either, but if you did need to use a static member function in a similar situation then there's ptr_fun.
|
1,809,937 | 1,810,007 | How to structure a Genetic Algorithm class hierarchy? | I'm doing some work with Genetic Algorithms and want to write my own GA classes. Since a GA can have different ways of doing selection, mutation, cross-over, generating an initial population, calculating fitness, and terminating the algorithm, I need a way to plug in different combinations of these. My initial approach was to have an abstract class that had all of these methods defined as pure virtual, and any concrete class would have to implement them. If I want to try out two GAs that are the same but with different cross-over methods for example, I would have to make an abstract class that inherits from GeneticAlgorithm and implements all the methods except the cross-over method, then two concrete classes that inherit from this class and only implement the cross-over method. The downside to this is that every time I want to swap out a method or two to try out something new I have to make one or more new classes.
Is there another approach that might apply better to this problem?
| I would approach the GA as a collaboration of many objects, rather than one big Class encapsulating the whole algorithm. Basically, you could have an abstract class for every big
point of variation, and concrete classes for every implementation choice you want. You then combine the concrete classes you want into many varieties of GA.
Also, you might want to familiarize yourself with the Strategy Pattern:
http://en.wikipedia.org/wiki/Strategy_pattern
|
1,809,950 | 1,809,970 | Is the following C++ casting correct? | I read a few posts on the usage of static and dynamic casts specifically from When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
I have a doubt regarding the usage of cast in the following manner. Can someone verify the below mentioned code:-
This is upward casting in inheritance hierarchy
template<class Base, class Derived>
inline Handle<Base> STATIC_CAST(Handle<Derived> hd) {
Handle<Base> hb;
Derived* dp = hd.get(); // Assume this gives pointer of derived class object
Base* bp = static_cast<Base*> (dp);
if(bp) {
hb = Ptr2Handle(bp); // Assume this give reference to Handle
}
return hb;
}
*Derived is actually the derived class from class Base.
What about downward casting in the following code?
template<class Base, class Derived>
inline Handle<Derived> DYNAMIC_CAST(Handle<Base> hb) {
Handle<Derived> hd;
Base* bp = hb.get();
Derived* dp = dynamic_cast<Derived*> (bp);
if(dp) {
hd = Ptr2Handle(dp);
}
return hd;
}
What will be the impact if the above two MACROS are passed with Base and Derived class swapped?
| If Base is really a base class of Derived, there's absolutely no need for any cast, meaning that static_cast in the above code is absolutely superfluous. It doesn't achieve anything a mere assignment wouldn't do implicitly. Moreover, in upcasts (from derived to base), dynamic_cast is absolutely equivalent to static_cast, meaning that dynamic_cast wouldn't achieve anything new either.
Actually, by placing an explicit static_cast cast in that code, its author enabled forceful "reverse" casts (downcasts). I.e. you can use this code to cast from base classes to derived classes. I don't know whether this was the intent (I doubt it was, judging by the template parameter names), and if it wasn't it might be a good idea to remove the cast entirely, since it is dangerous.
If, despite my doubts, the code was actually supposed to support downcasts, then dynamic_cast might indeed help to catch potential errors. However, keep in mind that dynamic_cast works in downcasts with polymorphic class types only.
|
1,810,163 | 1,810,320 | C++ implicit copy constructor for a class that contains other objects | I know that the compiler sometimes provides a default copy constructor if you don't implement yourself. I am confused about what exactly this constructor does. If I have a class that contains other objects, none of which have a declared copy constructor, what will the behavior be? For example, a class like this:
class Foo {
Bar bar;
};
class Bar {
int i;
Baz baz;
};
class Baz {
int j;
};
Now if I do this:
Foo f1;
Foo f2(f1);
What will the default copy constructor do? Will the compiler-generated copy constructor in Foo call the compiler-generated constructor in Bar to copy over bar, which will then call the compiler-generated copy constructor in Baz?
| Foo f1;
Foo f2(f1);
Yes this will do what you expect it to:
The f2 copy constructor Foo::Foo(Foo const&) is called.
This copy constructs its base class and then each member (recursively)
If you define a class like this:
class X: public Y
{
private:
int m_a;
char* m_b;
Z m_c;
};
The following methods will be defined by your compiler.
Constructor (default) (2 versions)
Constructor (Copy)
Destructor (default)
Assignment operator
Constructor: Default:
There are actually two default constructors.
One is used for zero-initialization while the other is used for value-initialization. The used depends on whether you use () during initialization or not.
// Zero-Initialization compiler generated constructor
X::X()
:Y() // Calls the base constructor
// If this is compiler generated use
// the `Zero-Initialization version'
,m_a(0) // Default construction of basic PODS zeros them
,m_b(0) //
m_c() // Calls the default constructor of Z
// If this is compiler generated use
// the `Zero-Initialization version'
{
}
// Value-Initialization compiler generated constructor
X::X()
:Y() // Calls the base constructor
// If this is compiler generated use
// the `Value-Initialization version'
//,m_a() // Default construction of basic PODS does nothing
//,m_b() // The values are un-initialized.
m_c() // Calls the default constructor of Z
// If this is compiler generated use
// the `Value-Initialization version'
{
}
Notes: If the base class or any members do not have a valid visible default constructor then the default constructor can not be generated. This is not an error unless your code tries to use the default constructor (then only a compile time error).
Constructor (Copy)
X::X(X const& copy)
:Y(copy) // Calls the base copy constructor
,m_a(copy.m_a) // Calls each members copy constructor
,m_b(copy.m_b)
,m_c(copy.m_c)
{}
Notes: If the base class or any members do not have a valid visible copy constructor then the copy constructor can not be generated. This is not an error unless your code tries to use the copy constructor (then only a compile time error).
Assignment Operator
X& operator=(X const& copy)
{
Y::operator=(copy); // Calls the base assignment operator
m_a = copy.m_a; // Calls each members assignment operator
m_b = copy.m_b;
m_c = copy.m_c;
return *this;
}
Notes: If the base class or any members do not have a valid viable assignment operator then the assignment operator can not be generated. This is not an error unless your code tries to use the assignment operator (then only a compile time error).
Destructor
X::~X()
{
// First runs the destructor code
}
// This is psudo code.
// But the equiv of this code happens in every destructor
m_c.~Z(); // Calls the destructor for each member
// m_b // PODs and pointers destructors do nothing
// m_a
~Y(); // Call the base class destructor
If any constructor (including copy) is declared then the default constructor is not implemented by the compiler.
If the copy constructor is declared then the compiler will not generate one.
If the assignment operator is declared then the compiler will not generate one.
If a destructor is declared the compiler will not generate one.
Looking at your code the following copy constructors are generated:
Foo::Foo(Foo const& copy)
:bar(copy.bar)
{}
Bar::Bar(Bar const& copy)
:i(copy.i)
,baz(copy.baz)
{}
Baz::Baz(Baz const& copy)
:j(copy.j)
{}
|
1,810,277 | 1,810,297 | My http server in c++ is not sending all files back correctly | I'm working on an HTTP server in c++, and right now it works for requests of text files, but when trying to get a jpeg or something, only part of the file gets sent. The problem seems to be that when I use fgets(buffer, 2000, returned_file) it seems to increment the file position indicator much more than it actually ends up putting into the buffer. Why would this happen? I put all my code below. The problem occurs in while(true) loop that occurs when the response code is 200. Thank you to anyone who replies.
// Interpret the command line arguments
unsigned short port = 8080;
if ( (argc != 1) && (argc != 3) && (argc != 5) ) {
cerr << "Usage: " << argv[0];
cerr << " -p <port number> -d <base directory>" << endl;
return 1;
}
else {
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-p") == 0)
port = (unsigned short) atoi(argv[++i]);
else if (strcmp(argv[i], "-d") == 0)
base_directory = argv[++i];
}
}
// if base_directory was not given, set it to current working directory
if ( !base_directory ) {
base_directory = getcwd(base_directory, 100);
}
// Create TCP socket
int tcp_sock = socket(AF_INET, SOCK_STREAM, 0);
if (tcp_sock < 0) {
cerr << "Unable to create TCP socket." << endl;
return 2;
}
// Create server socket
sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons( port );
server.sin_addr.s_addr = INADDR_ANY;
// Bind the socket
if (bind(tcp_sock, (sockaddr*)&server, sizeof(server)) < 0) {
cerr << "Unable to bind TCP socket." << endl;
return 3;
}
// Listen for a connection request on TCP port
listen(tcp_sock, 5);
// Create HTTP_Request object and start a while loop of accepting connections
char buffer[2000];
int bytes_recv = 0;
int recv_len = 0;
string error_reply;
HTTP_Response* response;
while (true) {
int acc_tcp_sock = accept(tcp_sock, NULL, NULL);
if (acc_tcp_sock == -1) {
cerr << "Unable to open TCP connection with client." << endl;
}
do {
// may want to do just one recv
recv_len = recv( acc_tcp_sock, buffer + bytes_recv,
2000 - bytes_recv, 0 );
bytes_recv += recv_len;
} while (false);
bytes_recv = 0;
// may want to see if this causes a memory leak
HTTP_Request* request = HTTP_Request::Parse(buffer, 2000);
response = handle_request(request); // function to handle the request
// Put response header into buffer
response->Print( buffer, 2000 );
// if 200 and GET then send header with file
if ( response->Get_code() == 200 ) {
// send response header
if ( send( acc_tcp_sock, buffer, strlen(buffer), 0 ) < 0 ) {
cerr << "Unable to send response header to client." << endl;
}
if ( method == "GET" ) {
// send file
while ( true ) {
fgets( buffer, 2000, returned_file );
if ( feof( returned_file ) ) break;
if ( send( acc_tcp_sock, buffer, strlen(buffer), 0 ) < 0 ) {
cerr << "Unable to send file in response to client." << endl;
}
}
}
fclose( returned_file ); // close file
}
else {
if ( method == "GET" ) {
error_reply = buffer + error_page;
if ( send( acc_tcp_sock, error_reply.c_str(), error_reply.length(), 0 ) < 0 ) {
cerr << "Unable to send response to client." << endl;
}
}
else {
if ( send( acc_tcp_sock, buffer, strlen(buffer), 0 ) < 0 ) {
cerr << "Unable to send respone header to client." << endl;
}
}
}
close( acc_tcp_sock ); // close the connection
}
return 0;
| Don't use fgets() to read binary data that needs to survive bit-for-bit. You don't want record-separator translation, and some systems may assume it's text if you read it that way. For that matter, newlines and record-separators are completely meaningless so the fgets()` function of scanning for them is at best a confusing inefficiency and at worst simply not-binary-capable at all.
Use fread(3), or better yet, use the raw system call (Posix API anyway, on non-Unix) read(2). This will read a certain amount of bit-for-bit data and tell you how much it read. (Regarding which binary-capable API to use: normally, we are advised to buffer data because we typically process it in small units like lines. However, when moving an entire file from one place to another buffering just slows you down. In this case it is simpler and faster to just use read().)
You also can't strlen() binary data. You have to just use the byte count from the API call.
|
1,810,343 | 1,810,488 | Is a wide character string literal starting with L like L"Hello World" guaranteed to be encoded in Unicode? | I've recently tried to get the full picture about what steps it takes to create platform independent C++ applications that support unicode. A thing that is confusing to me is that most howtos and stuff equalize the character encoding (i.e. ANSI or Unicode) and the character type (char or wchar_t). As I've learned so far, these are different things and there may exist a character sequence encodeded in Unicode but represented by std::string as well as a character sequence encoded in ANSI but represented as std::wstring, right?
So the question that comes to my mind is whether the C++ standard gives any guarantee about the encoding of string literals starting with L or does it just say it's of type wchar_t with implementation specific character encoding?
If there is no such guaranty, does that mean I need some sort of external resource system to provide non ASCII string literals for my application in a platform independent way?
What is the prefered way for this? Resource system or proper encoding of source files plus proper compiler options?
| The L symbol in front of a string literal simply means that each character in the string will be stored as a wchar_t. But this doesn't necessarily imply Unicode. For example, you could use a wide character string to encode GB 18030, a character set used in China which is similar to Unicode. The C++03 standard doesn't have anything to say about Unicode, (however C++11 defines Unicode char types and string literals) so it's up to you to properly represent Unicode strings in C++03.
Regarding string literals, Chapter 2 (Lexical Conventions) of the C++ standard mentions a "basic source character set", which is basically equivalent to ASCII. So this essentially guarantees that "abc" will be represented as a 3-byte string (not counting the null), and L"abc" will be represented as a 3 * sizeof(wchar_t)-byte string of wide-characters.
The standard also mentions "universal-character-names" which allow you to refer to non-ASCII characters using the \uXXXX hexadecimal notation. These "universal-character-names" usually map directly to Unicode values, but the standard doesn't guarantee that they have to. However, you can at least guarantee that your string will be represented as a certain sequence of bytes by using universal-character-names. This will guarantee Unicode output provided the runtime environment supports Unicode, has the appropriate fonts installed, etc.
As for string literals in C++03 source files, again there is no guarantee. If you have a Unicode string literal in your code which contains characters outside of the ASCII range, it is up to your compiler to decide how to interpret these characters. If you want to explicitly guarantee that the compiler will "do the right thing", you'd need to use \uXXXX notation in your string literals.
|
1,810,372 | 1,812,575 | C++ serialization library that supports partial serialization? | Are there any good existing C++ serialization libraries that support partial serialization?
By "partial serialization" I mean that I might want to save the values of 3 specific members, and later be able to apply that saved copy to a different instance. I'd only update those 3 members and leave the others intact.
This would be useful for synchronizing data over a network. Say I have some object on a client and a server, and when a member changes on the server I want to send the client a message containing the updated value for that member and that member only. I don't want to send a copy of the whole object over the wire.
boost::serialization at a glance looks like it only supports all or nothing.
Edit: 3 years after originally writing this I look back at it and say to myself, 'wut?' boost::serialization lets you define what members you want saved or not, so it would support 'partial serialization' as I seem to have described it. Further, since C++ lacks reflection serialization libraries require you to explicitly specify each member you're saving anyway unless they come with some sort of external tooling to parse the source files or have a separate input file format that is used to generate C++ code (e.g. what Protocol Buffers does). I think I must have been conceptually confused when I wrote this.
| You're clearly not looking for serialization here.
Serialization is about saving an object and then recreating it from the stream of bytes. Think video games saves or the session context for a webserver.
Here what you need is messaging. Google's FlatBuffers is nice for that. Specify a message that will contain every single field as optional, upon reception of the message, update your object with the fields that do exist and leave the others untouched.
The great thing with FlatBuffers is that it handles forward and backward compatibility nicely, as well as text and binary encoding (text being great for debugging and binary being better for pure performance), on top of a zero-cost parsing step.
And you can even decode the messages with another language (say python or ruby) if you save them somewhere and want to throw together a html gui to inspect it!
|
1,810,485 | 1,810,501 | Am I incorrectly using atoi? | I was having some trouble with my parsing function so I put some cout statements to tell me the value of certain variables during runtime, and I believe that atoi is incorrectly converting characters.
heres a short snippet of my code thats acting strangely:
c = data_file.get();
if (data_index == 50)
cout << "50 digit 0 = '" << c << "' number = " << atoi(&c) << endl;
the output for this statement is:
50 digit 0 = '5' number = 52
I'm calling this code within a loop, and whats strange is that it correctly converts the first 47 characters, then on the 48th character it adds a 0 after the integer, on the 49th character it adds a 1, on the 50th (Seen here) it adds a two, all the way up to the 57th character where it adds a 9, then it continues to convert correctly all the way down to the 239th character.
Is this strange or what?
Just to clarify a little more i'll post the whole function. This function gets passed a pointer to an empty double array (ping_data):
int parse_ping_data(double* ping_data)
{
ifstream data_file(DATA_FILE);
int pulled_digits [4];
int add_data;
int loop_count;
int data_index = 0;
for (char c = data_file.get(); !data_file.eof(); c = data_file.get())
{
if (c == 't' && data_file.get() == 'i' && data_file.get() == 'm' && data_file.get() == 'e' && data_file.get() == '=')
{
loop_count = 0;
c = data_file.get();
if (data_index == 50)
cout << "50 digit 0 = '" << c << "' number = " << atoi(&c) << endl;
pulled_digits[loop_count] = atoi(&c);
while ((c = data_file.get()) != 'm')
{
loop_count++;
if (data_index == 50)
cout << "50 digit " << loop_count << " = '" << c << "' number = " << atoi(&c) << endl;
pulled_digits[loop_count] = atoi(&c);
}
add_data = 0;
for (int i = 0; i <= loop_count; i++)
add_data += pulled_digits[loop_count - i] * (int)pow(10.0,i);
if (data_index == 50)
cout << "50 index = " << add_data << endl;
ping_data[data_index] = add_data;
data_index++;
if (data_index >= MAX_PING_DATA)
{
cout << "Error parsing data. Exceeded maximum allocated memory for ping data." << endl;
return MAX_PING_DATA;
}
}
}
data_file.close();
return data_index;
}
| atoi takes a string, i.e. a null terminated array of chars, not a pointer to a single char so this is incorrect and will get you unpredictable results.
char c;
//...
/* ... */ atoi(&c) /* ... */
Also, atoi doesn't provide any way to detect errors, so prefer strtol and similar functions.
E.g.
char *endptr;
char c[2] = {0}; // initalize c to all zero
c[0] = data.file.get(); // c[1] is the null terminator
long l = strtol(c, &endptr, 10);
if (endptr == c)
// an error occured
|
1,810,529 | 1,810,540 | Memorable 32-bit value as a constant | I am looking for a memorable 32-bit value to be used as a constant. If possible, it should be somewhat funny too.
So far, I have come up with these two:
0xcafebabe
0xdeaddad
Can you please suggest some other too?
Thank you.
| A comprehensive list of magic constants is here:
Hexspeak
Magic Number
And see the links therein.
|
1,810,566 | 1,810,571 | c++ templated friend class | I'm trying to write an implementation of a 2-3-4 tree in c++. I'm it's been a while since I've used templates, and I'm getting some errors. Here's my extremely basic code framework:
node.h:
#ifndef TTFNODE_H
#define TTFNODE_H
template <class T>
class TreeNode
{
private:
TreeNode();
TreeNode(T item);
T data[3];
TreeNode<T>* child[4];
friend class TwoThreeFourTree<T>;
int nodeType;
};
#endif
node.cpp:
#include "node.h"
using namespace std;
template <class T>
//default constructor
TreeNode<T>::TreeNode(){
}
template <class T>
//paramerter receving constructor
TreeNode<T>::TreeNode(T item){
data[0] = item;
nodeType = 2;
}
TwoThreeFourTree.h
#include "node.h"
#ifndef TWO_H
#define TWO_H
enum result {same, leaf,lchild,lmchild,rmchild, rchild};
template <class T> class TwoThreeFourTree
{
public:
TwoThreeFourTree();
private:
TreeNode<T> * root;
};
#endif
TwoThreeFourTree.cpp:
#include "TwoThreeFourTree.h"
#include <iostream>
#include <string>
using namespace std;
template <class T>
TwoThreeFourTree<T>::TwoThreeFourTree(){
root = NULL;
}
And main.cpp:
#include "TwoThreeFourTree.h"
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream inFile;
string filename = "numbers.txt";
inFile.open (filename.c_str());
int curInt = 0;
TwoThreeFourTree <TreeNode> Tree;
while(!inFile.eof()){
inFile >> curInt;
cout << curInt << " " << endl;
}
inFile.close();
}
And when I try to compile from the command line with:
g++ main.cpp node.cpp TwoThreeFourTree.cpp
I get the following errors:
In file included from TwoThreeFourTree.h:1,
from main.cpp:1:
node.h:12: error: ‘TwoThreeFourTree’ is not a template
main.cpp: In function ‘int main()’:
main.cpp:13: error: type/value mismatch at argument 1 in template parameter list for ‘template<class T> class TwoThreeFourTree’
main.cpp:13: error: expected a type, got ‘TreeNode’
main.cpp:13: error: invalid type in declaration before ‘;’ token
In file included from node.cpp:1:
node.h:12: error: ‘TwoThreeFourTree’ is not a template
In file included from TwoThreeFourTree.h:1,
from TwoThreeFourTree.cpp:1:
node.h:12: error: ‘TwoThreeFourTree’ is not a template
My main question is why it's saying "error: ‘TwoThreeFourTree’ is not a template". Does anyone have any ideas? Thanks for all advice/help in advance...
Dan
| You just need to declare it as a template when you use the friend keyword. You're using incorrect syntax for a friend declaration in your code. What you want to write is:
template <class U> friend class TwoThreeFourTree;
|
1,810,622 | 1,810,630 | C++ returning nested class with template on base class problem | I am trying to create a list object, with the iterator class nested inside to understand how it works.
In some method, I am trying to return an iterator object but it doesn't work.
I created an example to show the problem :
// CLASS A
template <class T>
class A
{
public:
class B;
A(){}
};
// CLASS B
template <class T>
class A<T>::B
{
private:
int varB;
public:
B(B& b);
B(const int&);
B returnThis();
};
template <class T>
A<T>::B::B(const int& value)
{
varB = value;
}
template <class T>
A<T>::B::B(B& b)
{
varB = b.varB;
}
template <class T>
A<T>::B A<T>::B::returnThis()
{
return *this;
}
// MAIN
void main()
{
A<int>::B classB(10);
}
The error is near those lines:
template <class T>
A<T>::B A<T>::B::returnThis()
The compiler tells me I am missing a ; before A::B::returnThis()
I am trying to solve this problem for days and I can't find a way to make it work...
I would really appreciate some help.
Thanks in advance!
| You need typename:
typename A<T>::B
To indicate to the compiler that A<T>::B is a type. Here's a good explanation why.
What B is depends on what A<T> is, this is called dependency. Any time you are getting a type out of a class or struct, and it's dependent on a template, you'll need to use typename.
|
1,810,657 | 1,810,704 | C++: Iterating through a vector of vectors | Hey there! I'm doing this project and right now I'm trying to:
create some of objects and store them in vectors, which get stored in another vector V
iterate through the vectors inside V
iterate through the objects inside the individual vectors
Anyway, I was just searching the web and I came accross the stl for_each function. It seems pretty neat but I'm having problems with it. I'm trying to use it in this way:
for_each(V.begin(), V.end(), iterateThroughSmallVectors);
the iterateThroug.... simply does the same on the vector passed to it..
Now I'm getting a weird "Vector iterators incompatible" runtime error. I've looked on it and can't find any useful input on this..
I don't know if it helps, but V is a private vector<> stored in class A, which has an accessor to it, and I'm trying to iterate through it in class B by doing:
A->getV().begin(), A->getV().end(), etc..
Anyone got any idea of what is going on?
EDIT: Ok, so I think it is better to just post the code, and where problems might be arrising...
getTiles in gameState.h:
vector<vector<tile*>> getTiles();
for_each loops in main.cpp:
for_each(currState->getTiles().begin(),currState->getTiles().end(), drawTiles);
.
.
void drawTiles(vector<tile*> row)
{
for_each(row.begin(), row.end(), dTile);
}
void dTile(tile *t)
{
t->draw();
}
creating the vectors:
int tp = -1;
int bCounter = 0;
int wCounter = 0;
for (int i = 0; i < 8; i++)
{
vector<tile*> row(8);
for (int j = 0; j < 8; j++)
{
tile *t = new tile(tp, (i+(SIDELENGTH/2))*SIDELENGTH,
(j+(SIDELENGTH/2))*SIDELENGTH);
row.push_back(t);
tp *= -1;
}
currState->setTiles(row);
tp *= -1;
}
and just in case it might be relevant:
void gameState::setTiles(vector<tile*> val)
{
tiles.push_back(val);
}
Is it easier to spot the problem now? I hope so... And if you do spot any stupid stuff I might be doing, please let me know, I'm kind of new to C++ and the pointers and references still confuse me.
EDIT2: Thanks guys, that worked perfectly... well for that problem, now it seems I have an issue with the creation of the tiles and stroing them in the row vector.. it seems that even through the vector is created and passes correctly, the tiles that were supposed to be in it aren't (they are lost after the :
for (int j = 0; j < 8; j++)
{
tile *t = new tile(tp, (i+(SIDELENGTH/2))*SIDELENGTH,
(j+(SIDELENGTH/2))*SIDELENGTH);
row.push_back(t);
tp *= -1;
}
loop. If any of you has any good ideas about solving this you're welcome to help me ;) In the mean time, I'll keep trying to fix it
| What's the prototype for A::getV()?
I'm only speculating but if A::getV() doesn't return a reference then it can explain the "Vector iterators are incompatible" error message.
Indeed A->getV().begin() and A->getV().end() would be two iterators over different vectors: each A->getV() invocation returning a different copy of the private member.
Hope this will help you debug your problem.
EDIT: it looks like I anticipated it right: after editing your question providing details, I can see you're defining
vector<vector<tile*> > getTiles();
As a consequence, in the following statement:
for_each(currState->getTiles().begin(),currState->getTiles().end(), drawTiles);
As anticipated above, each call to getTiles() will return a separate temporary copy of the member vector. As a consequence the iterators returned from begin() and end() come from different vectors, hence the error message you're facing at runtime.
Also, as pointed by Charles in his detailed answer, these temporary vectors will be destroyed by the time the function body of for_each is reached.
Consider returning the vector by const reference like this:
const vector<vector<tile*> >& getTiles() const;
And you may as well change drawTiles to avoid even more copies:
void drawTiles(const vector<tile*>& row)
|
1,810,953 | 1,810,964 | Is there an easy way to tell if a File stream has opened a directory instead of a file? | I'm making an HTTP server and when I get the path of the file they request I open it with the following:
returned_file = fopen(path, "r");
this (contrary to what I would think) succeeds even if the path is a directory. Is there an easy way to check if the returned_file stream is a directory instead of a file?
| Can you check if the path points to a directory before you call fopen?
|
1,810,991 | 1,811,038 | Recommendations for naming C# classes/methods intended to replace existing APIs | Long explanation aside, I have a situation where I need to basically re-implement a .NET framework class in order to extend the behavior in a manner that is not compatible with an inheritance or composition/delegation strategy. The question is not a matter of whether the course of action I am to take is what you would do, or recommend, it is instead a question of naming/coding-style.
Is there a paradigm for naming classes and methods that have the same functionality as an existing class or method ala the convention of ClassEx/MethodEx that exists in C++?
[edit]
I understand that choosing good names for this is important... I haven't written a line of code yet, and am instead taking the time to think through the ramifications of what I am about to undertake, and that includes searching for a clear, descriptive, name while trying to be concise. The issue is that the name I have in mind is not terribly concise.
[/edit]
| Here are the ways I've seen in the .NET Framework itself:
Call it something slightly different, but don't use any specific suffix. For example, System.TimeZoneInfo was introduced to supersede System.TimeZone.
Put it in another namespace. For example, the WPF Button is in System.Windows instead of System.Windows.Forms.
Suffix it with a number. For example X509Certificate2 versus X509Certificate. (This practice was common with COM interfaces but has fallen out of favor in .NET.)
Note that the naming of TimeZoneInfo is a publicized case of Microsoft tackling this convtrovertial naming issue head on. See and http://blogs.msdn.com/kathykam/archive/2007/03/28/bye-bye-system-timezone2-hello-system-timezoneinfo.aspx and http://blogs.msdn.com/kcwalina/archive/2006/10/06/TimeZone2Naming.aspx for excellent information.
|
1,811,118 | 1,811,185 | Super basic declaring new templated class objects question | I know this is probably a first year question, but I'm having some problems with templates and I haven't found a suitable answer yet. I'm trying to instantiate a new templated class like so:
TreeNode <T>newLeft = new TreeNode(root->data[0]);
Which is refering to a constructor which looks like:
template <class T>
//paramerter receving constructor
TreeNode<T>::TreeNode(T item){
data[0] = item;
nodeType = 2;
}//end
And I'm getting the following errors:
error: expected type-specifier before ‘TreeNode’
error: expected `;' before ‘TreeNode’
What is the type-specifier? I can provide more code if necessary, and I know I asked a question about this code earlier, and I'm sure I'll get flamed for it; but I still have questions...
edit:
Here's the function it's used in:
template <class T>
void TwoThreeFourTree<T>::splitRoot(){
TreeNode <T> newRoot;
newRoot = new TreeNode(root->data[1]);
TreeNode <T>newLeft = new TreeNode(root->data[0]);
TreeNode <T>newRight = new TreeNode(root->data[2]);
newRoot.child[0] = newLeft;
newRoot.child[1] = newRight;
newLeft.child[0] = root.child[0];
newLeft.child[1] = root.child[1];
newRight.child[0] = root.child[2];
newRight.child[1] = root.child[3];
root = newRoot;
}
And I get the same two errors each time I try to create a new object in the function
| You forgot T in new, and pointers:
TreeNode<T>* newRoot;
newRoot = new TreeNode<T>(root->data[1]);
Note, you'll need to fix your usage of pointers everywhere, not just here. Remember that this isn't Java or C#, and a variable of type TreeNode<T> is not a reference to T - it is a T. And to build a tree, you need references - that is, pointers. Though you may also want to consider using std::auto_ptr here to guarantee cleanup.
|
1,811,358 | 1,811,378 | help overloading << and >> to display two values | This may be a novice question, but I can't figure it out by inspecting the book I have.
The class's constructor initializes two doubles, and I want the following code to output those two doubles with <<.
Complex x( 3.3, 1.1 );
cout << "x: " << x;
After this I need to overload >> to accept two doubles into these.
This is my first question here, so if my information provided is lacking inform me
EDIT:
I now have for the constructor and overloading statement this:
#include "Complex.h"
Complex::Complex( double realPart, double imaginaryPart )
: real( realPart ),
imaginary( imaginaryPart )
{
}
std::istream& operator>>(std::istream& strm, const Complex &c)
{
double r,i;
strm >> r >> i;
c = Complex(r,i);
return strm;
}
I know I have to change the "const Complex &c" and the "c = Complex(r,i);" but I'm not sure how to go about it.
Also, I will say here that this is not about the std library's Complex class, although it is based on the same idea. So far everyone has been a great help, but I have a case of the dumb today.
| operator<< :
std::cout is an std::ostream object, so you have to overload operator<< for ostream, which takes std::complex<double> as an argument, assuming you use std::complex<double> from the standard header complex. Since you shouldn't make internal changes to standard containers and classes, make it standalone.
#include <iostream>
#include <complex>
std::ostream& operator<<(std::ostream& strm, const std::complex<double>& c)
{
strm << "real: " << c.real() << "imag: " << c.imag();
return strm;
}
operator>> :
operator>> takes a std::istream object, which does the opposite of what std::ostream does. If you use streams for serialization like this, it's a good idea to enable exceptions for them too. Usually you only want to throw on std::ios::badbit.
#include <iostream>
#include <complex>
std::istream& operator>>(std::istream& strm, std::complex<double>& c)
{
double r,i;
strm >> r >> i;
c = std::complex<double>(r,i);
return strm;
}
If you needed access to internal members of the class, you would define the overloaded function as a friend. But since std::complex::real() and std::complex::imag() are a part of the public interface, that's not needed here. And for the istream example, we simply invoke the copy-constructor which is also a part of the public interface.
I assumed you wanted to use cin and cout here. But if you wanted to overload the operators for something else, the same applies. If you implement the operators inside a class definition, you have access to the this pointer, hence the operator function should only take one argument.
|
1,811,447 | 1,811,471 | populating int array that is a member variable | I'm using C++ to create a tile map for a game. My problem is, I want to populate a multidimensional array of ints in the Map constructor, but it's not working properly. Here's my code in "Map.h" (irrelevant code has been removed).
class Map {
private:
int mapArray[15][20];
};
And my code from Map.cpp
Map::Map()
{
mapArray = {
{ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 },
{ 20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39 },
{ 40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59 },
{ 60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79 },
{ 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99 },
{ 100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119 },
{ 120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139 },
{ 140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159 },
{ 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179 },
{ 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199 },
{ 200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219 },
{ 220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239 },
{ 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259 },
{ 260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279 },
{ 280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299 }
};
}
PS. creating the mapArray locally, within a member function using int mapArray[15][20] and populating it then is working fine, I just can't seem to get it to populate in the constructor, with a member variable.
PPS. Very rusty with C++, please be gentle.
What am I doing wrong?
| You can't use array initializers like that in a class constructor. Members can only be initialized by using the initializer list. Your best bet is to load this data from a file, or to declare the array as static.
class Map
{
private:
static int mapArray[15][20];
/* ... */
};
Then define storage for the static array in a source file (.cpp), also known as a translation unit:
int Map::mapArray[15][20] = { ... };
|
1,811,516 | 1,811,973 | Integrating Erlang with C++ | What interfaces exist to tie Erlang with C++?
|
Native implemented functions: available in the latest Erlang/OTP version, allows you to implement any of your functions in C.
Port drivers: you can link a C code to the Erlang VM, and access it using port_command.
C Nodes: With the ei library you can mimic a VM and talk to your Erlang VMs using the Erlang distribution format.
|
1,811,788 | 1,812,017 | C++: How to Perform Deep Cloning of Generic Type | To keep the long story short, I am unable to use the container from the STL and boost library and have to create my own.
My own generic container is coded in VC++6 and I need to know how to manually allocate memory for generic types before storing it in my own container. The generic types are all struct that can contain nested struct. All struct be it nested or not will contain only primitive types like char*, int, bool etc.
For example, when you call the insert function of std::vector, internally, std::vector will automatically perform a deep cloning of the generic type before storing it.
How can I duplicate this functionality (deep cloning of generic type) in my own container?
Please provide some sample code for performing deep cloning of generic type.
| First and for all: if you want to clone any object, all it's aggregates should be cloned, too. This means that every struct/class involved in the cloning action should implement cloning behavior.
Then: the stl uses so called value-semantics: containers will always contain their elements 'by value'. Copying means creating copies of all container elements.
So in order to achieve cloning/deep copy behavior, the copy constructors of every member of the container's element type should implement deep copy behavior. Members of pointer-to-object type should also be deep-copied (not just copying the member pointer).
Note: code is untested, probably contains tons of exception-unsafety etc... and is merely used as a shallow :) example.
struct WithPointer {
int* pint;
WithPointer( int value = 0 ) : pint( new int ) { *pint = value; }
WithPointer( const WithPointer& other ) {
pint = new int;
*pint = *other.pint;
}
~WithPointer( ) { delete pint; } // important!
}
This class can be 'deep-copied' using an stl container:
std::vector<WithPointer> v;
WithPointer wp(1);
v.push_back( wp );
std::vector<WithPointer> v2 = v;
|
1,812,152 | 1,812,200 | C stdlib .h's on C++ and malloc/realloc | I was really bothered by the inclusion of C stdlib functions on the global namespace and ended up writing things like ::snprintf or ::errno or struct ::stat, etc, to differentiate from some of my own functions in the enclosing namespace where those c stdlib functions were used.
Then I discovered that there is a way to declare every C stdlib function in the std namespace (as STL): just include < c(lib) > instead of < (lib).h > so I've edited my code the use those new "c for c++" includes.
On Debian/GCC 4.3.4 I had to 2 problems:
1) #error This file requires compiler and library support for the upcoming \
ISO C++ standard, C++0x. This support is currently experimental, and must be \
enabled with the -std=c++0x or -std=gnu++0x compiler options.
2) using -std=c++0x my program compiles just fine, but I have not modified ::snprintf or ::time, etc.. every C stdlib function is still on the global namespace =(! (no, I'm not using namespace std not even once)
Any thoughts?
For example.. how to stop the c stdlib from invading my global namespace? < c(lib) > is an experimental feature of the next C++ standard or could be used safely right now?
Then I've another doubt that perhaps deserves a new question.. there is no cmalloc. I know the whole history about new replacing malloc and why. but for simple plain byte buffers there is no c++ equivalent of realloc. I know that memory blocks and reallocation are implementation/so specific, but when there are contiguous free blocks of memory realloc works better than a new buffer allocation and memory copy.
Thanks =)!
| For your first question, it depends on which headers you are trying to include. Most of the C headers are available in the c(lib) form in the existing version of C++. A few aren't, and may be added in C++0x. So if you tried to include any of those, you might have gotten that error.
Second, all the headers of this form guarantee that the functions will be made available in the std namespace. But they do not promise to leave the global namespace alone. Often, they put the symbols in both namespaces.
I'm not sure why ::snprintf bothers you more than std::snprintf though. You have to specify a prefix in both cases.
As for realloc, a C++ equivalent doesn't exist, probably because it's more trouble than it's worth, especially with C++'s more complicated semantics for copying objects. (In particular, if you try to use it, don't store any non-POD objects in the buffer, as realloc will just memcpy them to a newly allocated buffer if necessary, which will break non-POD objects.)
Of course, you can still use the old realloc from C by including its header. But I'd say you're probably better off using new/delete, and simply figuring out a sensible buffer allocation strategy.
|
1,812,160 | 1,812,163 | C++: Compile Error for Template Assignment Operator Overloading | I keep getting the error "use of class template requires template argument list" when I compile the following code in VC++6. What is wrong with it?
template <class T>
class StdVector{
public:
StdVector & operator=(const StdVector &v);
};
template <typename T>
StdVector & StdVector<T>::operator=(const StdVector &v){
return *this;
}
| You need to put the template parameter in the return type:
template <typename T>
StdVector<T> & StdVector<T>::operator=(const StdVector &v)
{
return *this;
}
|
1,812,259 | 1,812,292 | C++ : Potential Issues with Custom Coded Generic Container? | I am unable to use the STL and boost library and I have to write my own container in C++. The following code compiles without error in VC++6.
I have not actually tested the code but is concerned whether this generic container will work with both primitive and non primitive types (like class). Will there be any potential issues with the copy constructor and the assignment operator especially?
Any other suggestions and comments are most welcomed. :)
template <class T>
class __declspec(dllexport) StdVector{
private:
int _pos;
int _size;
const T *_items;
public:
StdVector();
StdVector(const StdVector &v);
StdVector(int size);
virtual ~StdVector();
void Add(const T &item);
void SetSize(int size);
int GetSize();
const T * Begin();
const T * End();
const T * ConstIterator();
StdVector & operator=(const StdVector &v);
};
template <typename T>
StdVector<T>::StdVector()
: _pos(0), _size(0), _items(NULL){
}
template <typename T>
StdVector<T>::StdVector(const StdVector &v)
: _pos(0), _size(v.GetSize()), _items(new T[_size]){
std::copy(v.Begin(), v.End(), Begin());
}
template <typename T>
StdVector<T>::StdVector(int size)
: _pos(0), _size(size), _items(new T[_size]){
}
template <typename T>
StdVector<T>::~StdVector(){
if (_items != NULL)
delete[] _items;
}
template <typename T>
void StdVector<T>::Add(const T &item){
if (_pos == _size)
throw new exception("Already at max size!!!");
_items[_pos++] = item;
}
template <typename T>
void StdVector<T>::SetSize(int size){
if (_items != NULL)
delete[] _items;
_pos = 0;
_size = size;
_items = new T[_size];
}
template <typename T>
int StdVector<T>::GetSize(){
return _size;
}
template <typename T>
const T * StdVector<T>::Begin(){
return _items;
}
template <typename T>
const T * StdVector<T>::End(){
return _items + _pos;
}
template <typename T>
const T * StdVector<T>::ConstIterator(){
return _items;
}
template <typename T>
StdVector<T> & StdVector<T>::operator=(const StdVector &v){
if (this != &v){
delete[] _items;
std::copy(v.Begin(), v.End(), Begin());
}
return *this;
}
| This default constructs the new objects and assigns them (or would, if the Begin() returned T* and not const T*, see dribeas' answer), it might be more efficient if you used raw storage and constructed the new objects in place. Also as GetSize(), Begin() and End() aren't const they can't be called on the parameter v.
template <typename T>
StdVector<T>::StdVector(const StdVector &v)
: _pos(0), _size(v.GetSize()), _items(new T[_size]){
std::copy(v.Begin(), v.End(), Begin());
}
The if statement is redundant. delete[] on a NULL pointer is fine. Also, is there any point to it being virtual? It doesn't look like this is a class designed to be derived from.
template <typename T>
StdVector<T>::~StdVector(){
if (_items != NULL)
delete[] _items;
}
SetSize destroys all the objects and creates new ones. This may be 'surprising' behaviour. Also, if the new throws, the object will be left pointing at deallocated memory. Again, the if guarding the delete is redundant.
template <typename T>
void StdVector<T>::SetSize(int size){
if (_items != NULL)
delete[] _items;
_pos = 0;
_size = size;
_items = new T[_size];
}
What's the point of this? It appears to do the same as Begin. It's not even a const method.
template <typename T>
const T * StdVector<T>::ConstIterator(){
return _items;
}
Doesn't this attempt copy to _items which has just been deleted (again see the points about Begin() returning const T* and about Begin() and End() not being const)?
template <typename T>
StdVector<T> & StdVector<T>::operator=(const StdVector &v){
if (this != &v){
delete[] _items;
std::copy(v.Begin(), v.End(), Begin());
}
return *this;
}
What exception class is this? std::exception doesn't have a constructor that takes a const char*. You should also throw exception objects, not pointers to dynamically allocated exception objects. Cleaning up dynamically allocated exceptions which are 'thrown' by pointer is almost impossible to do robustly.
template <typename T>
void StdVector<T>::Add(const T &item){
if (_pos == _size)
throw new exception("Already at max size!!!");
_items[_pos++] = item;
}
|
1,812,295 | 1,812,324 | Capture bitstream into string | I'll need to capture my bitstream into a string and keep concatenating the string. However, I'm not really sure how it's to be done. Any ideas?
#include <bitset>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int i;
char data[30];
int int_arr[30];
printf("\nEnter the Data Bits to be transmitted : ");
scanf("%s",data);
// convert it into bitstream
for (i=0; i<strlen(data); i++)
{
int_arr[i] = int(data[i]);
}
for (i=0; i<strlen(data); i++)
{
cout << int_arr[i]<<endl;
cout << std::bitset<8>( int_arr[i] )<<endl; // Placeholder
}
return 0;
}
In the line where it's marked '//Placeholder', I really do not need to 'cout' it, rather, I'd have to capture the bitstream into a string and keep concatenating it.
| std::stringstream?
#include <sstream>
std::string WriteSomethingToStringStream()
{
std::ostringstream oss;
oss << "foo?\n";
oss << "bar!\n";
return oss.str();
}
|
1,812,395 | 1,812,588 | Designing a virtual machine with JIT | I'm developing a scripting language that compiles for its own virtual machine, a simple one that has instructions to work with some kind of data like points, vectors, floats and so on.. the memory cell is represented in this way:
struct memory_cell
{
u32 id;
u8 type;
union
{
u8 b; /* boolean */
double f; /* float */
struct { double x, y, z; } v; /* vector */
struct { double r, g, b; } c; /* color */
struct { double r, g, b; } cw; /* color weight */
struct { double x, y, z; } p; /* point variable */
struct { u16 length; memory_cell **cells; } l; /* list variable */
};
};
Instructions are generic and able to work on many different operands. For example
ADD dest, src1, src2
can work with floats, vectors, points, colors setting the right type of destination according to operands.
The main execution cycle just check the opcode of the instruction (which is a struct containing unions to define any kind of instruction) and executes it. I used a simplified approach in which I don't have registers but just a big array of memory cells.
I was wondering if JIT could help me in getting best performances or not and how to achieve it.
As I said the best implementation reached so far is something like that:
void VirtualMachine::executeInstruction(instr i)
{
u8 opcode = (i.opcode[0] & (u8)0xFC) >> 2;
if (opcode >= 1 && opcode <= 17) /* RTL instruction */
{
memory_cell *dest;
memory_cell *src1;
memory_cell *src2;
/* fetching destination */
switch (i.opcode[0] & 0x03)
{
/* skip fetching for optimization */
case 0: { break; }
case MEM_CELL: { dest = memory[stack_pointer+i.rtl.dest.cell]; break; }
case ARRAY_VAL: { dest = memory[stack_pointer+i.rtl.dest.cell]->l.cells[i.rtl.dest.index]; break; }
case ARRAY_CELL: { dest = memory[stack_pointer+i.rtl.dest.cell]->l.cells[(int)i.rtl.dest.value]; break; }
}
/* omitted code */
switch (opcode)
{
case ADD:
{
if (src1->type == M_VECTOR && src2->type == M_VECTOR)
{
dest->type = M_VECTOR;
dest->v.x = src1->v.x + src2->v.x;
dest->v.y = src1->v.y + src2->v.y;
dest->v.z = src1->v.z + src2->v.z;
}
/* omitted code */
Is it easy/convenient to try jit compilation? But I really don't know where to start from, that's why I'm asking some advices.
Apart from that, are there any other advices I should consider in developing it?
This virtual machine should be enough fast to do calculate shaders for a ray tracer but I sill haven't done any kind of benchmark.
| Before writing a JIT ("Just-in-time") compiler, you should at least consider how you would write a "Way-ahead-of-time" compiler.
That is, given a program consisting of instructions for your VM, how would you produce a program consisting of x86 (or whatever) instructions, that does the same as the original program? How would you optimise the output for different instruction sets, and different versions of the same architecture? The example opcode you've given has quite a complicated implementation, so which opcodes would you implement "inline" by just emitting code that does the job, and which would you implement by emitting a call to some shared code?
A JIT has to be able to do this, and it also has to make decisions while the VM is running about which code it does it to, when it does it, and how it represents the resulting mixture of VM instructions and native instructions.
If you're not already an assembly-jockey, then I don't recommend writing a JIT. That's not to say "don't do it ever", but you should become an assembly-jockey before you start in earnest.
An alternative would be to write a non-JIT compiler to convert your VM instructions (or the original scripting language) to Java bytecode, or LLVM, as Jeff Foster says. Then let the toolchain for that bytecode do the difficult, CPU-dependent work.
|
1,812,683 | 1,812,878 | SSL reverse proxy for legacy application binary transfers on sockets | I'm struggling to find a reverse proxy http->https like for binary sockets.
There is a Pound server which offers this kind of SSL tunneling but just for the http protocol.
Basically I work on 4'th layer TCP/IP with binary data. Between flex/AIR client and c++ server.
I can wrap sockets in C++ without problems, but this is a problem for flex side.
Any advice welcomed.
| Maybe you're looking for Stunnel?
|
1,812,782 | 1,814,476 | C++: Compilation Errors for Custom Coded Generic Container? | The following is based on the code that I posted on this thread. Aside from the obvious bugs, I get the following compilation errors? Any idea why?
The odd thing is that this only occurs for the template class. If I add another non template class to the same .h and .cpp file of the template class and try to instantiate just the non template class, no error is generated.
Scenario A:
I get the compilation error " error C2659: '=' : overloaded function as left operand " for the following code:
StdVector<int> a();
StdVector<int> b();
a = b;
Scenario B:
I get the compilation error " error C2664: '__thiscall StdVector::StdVector(const class StdVector &)' : cannot convert parameter 1 from 'class StdVector (__cdecl *)(void)' to 'const class StdVector &' " for the following code:
StdVector<int> a();
StdVector<int> b(a);
Scenario C:
I get the compilation error "error LNK2001: unresolved external symbol "public: __thiscall StdVector::~StdVector(void)" (??1?$StdVector@H@@QAE@XZ) " for the following code:
StdVector<int> a;
| If I am not mistaken, templates cannot be exported. That is why I am getting the linker error in Scenario C.
|
1,812,815 | 1,813,093 | How to use magnet links in LibTorrent lib | How to use magnet links in LibTorrent C/C++ lib?
I need an simple example of working with it - Something like I give him a link he gives me a file.
| While I haven't used it personally, but you could check http://www.qbittorrent.org/, it uses libtorrent internally and it is under the GPL-2 license.
|
1,812,990 | 1,812,998 | Incrementing in C++ - When to use x++ or ++x? | I'm currently learning C++ and I've learned about the incrementation a while ago.
I know that you can use "++x" to make the incrementation before and "x++" to do it after.
Still, I really don't know when to use either of the two... I've never really used "++x" and things always worked fine so far - so, when should I use it?
Example: In a for loop, when is it preferable to use "++x"?
Also, could someone explain exactly how the different incrementations (or decrementations) work? I would really appreciate it.
| It's not a question of preference, but of logic.
x++ increments the value of variable x after processing the current statement.
++x increments the value of variable x before processing the current statement.
So just decide on the logic you write.
x += ++i will increment i and add i+1 to x.
x += i++ will add i to x, then increment i.
|
1,813,259 | 1,813,264 | Generate random chars and integers in C++ | How do I generate random chars and integers within a method so that the method can be called in main() and so that the method generates random chars and integers together. I do not want a method that genrates chars and another methods that generates integers.
| You can write a method like (assuming you want only lower case English characters, you can extend it):
void generate(char& ranChar, int& ranNmber)
{
//Generate a random number in the range 0-25 and add the ascii value 'a'
ranChar = rand() % 26 + 'a';
ranNumber = rand();
}
int main()
{
//Seed the random number generator with the current time
srand(time(NULL));
char ch;
int n= 0;
generate(ch,n);
return 0;
}
|
1,813,552 | 1,813,560 | Tell C++ console to wait | What is the method to tell the console to wait for x seconds. Is there a built in method or must I make one.
| It's platform specific. On Linux/UNIX, or other POSIX-compliant operating systems, you can use the sleep function, which takes a parameter in seconds. On Windows you can use Sleep, which takes a parameter in milliseconds.
|
1,813,647 | 1,813,662 | Simplest way to read registry key value to std::string? | What's the simplest way to read a registry key value to std::String?
Say I've got :
HKEY_LOCAL_MACHINE / SOFTWARE / MyApp / value1 = "some text"
HKEY_LOCAL_MACHINE / SOFTWARE / MyApp / value2 = "some more text"
How do I get those values to std::string in a fast way ?
| I have some very old code, but it should give you a good idea:
/**
* @param location The location of the registry key. For example "Software\\Bethesda Softworks\\Morrowind"
* @param name the name of the registry key, for example "Installed Path"
* @return the value of the key or an empty string if an error occured.
*/
std::string getRegKey(const std::string& location, const std::string& name){
HKEY key;
TCHAR value[1024];
DWORD bufLen = 1024*sizeof(TCHAR);
long ret;
ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, location.c_str(), 0, KEY_QUERY_VALUE, &key);
if( ret != ERROR_SUCCESS ){
return std::string();
}
ret = RegQueryValueExA(key, name.c_str(), 0, 0, (LPBYTE) value, &bufLen);
RegCloseKey(key);
if ( (ret != ERROR_SUCCESS) || (bufLen > 1024*sizeof(TCHAR)) ){
return std::string();
}
std::string stringValue = std::string(value, (size_t)bufLen - 1);
size_t i = stringValue.length();
while( i > 0 && stringValue[i-1] == '\0' ){
--i;
}
return stringValue.substr(0,i);
}
|
1,813,671 | 1,813,720 | Problem with protected fields in base class in c++ | I have a base class, say BassClass, with some fields, which I made them protected, and some pure virtual functions. Then the derived class, say DerivedClass, like class DerivedClass : public BassClass. Shouldn't DerivedClass inherit the protected fields from BassClass? When I tried to compile the DerivedClass, the compiler complains that DerivedClass does NOT have any of those fields, what is wrong here?
thanks
| If BassClass (sic) and DerivedClass are templates, and the BassClass member you want to access from DerivedClass isn't specified as a dependent name, it will not be visible.
E.g.
template <typename T> class BaseClass {
protected:
int value;
};
template <typename T> class DerivedClass : public BaseClass<T> {
public:
int get_value() {return value;} // ERROR: value is not a dependent name
};
To gain access you need to give more information. For example, you might fully specify the member's name:
int get_value() {return BaseClass<T>::value;}
Or you might make it explicit that you're referring to a class member:
int get_value() {return this->value;}
|
1,813,758 | 1,813,940 | CMFCRibbonEdit does not get focus | I just added a CMFCRibbonEdit to my ribbon but it seems it does not get the focus.
It appears disabled.
I even copy/pasted an implementation of the creation of this control from a Microsoft sample but I get the same behaviour.
Any idea on what I may be doing wrong or forgetting to do ?
| Have you added an update handler for that ribbon element ID?
Check the RibbonGadgets and MSOffice2007Demo samples in the MFC Feature Pack to see how they do it.
The RibbonGadgets one will show you the exact code you need to use in order to add an element of the specified type to your ribbon.
|
1,813,860 | 1,813,901 | Is there any significant difference between nesting a while loop in a while loop and nesting an if-else loop in a while loop? (C++) | EDIT: I forgot to add the loop part of the second code.
Looking at the two code styles
while(some_loop_cont_val)
{
while(pre_x is not done)
{
//do action pre_x
}
//do action x
}
and
while(some_loop_cont_val)
{
if(pre_x is not done)
{
//do action pre_x
}
else
{
//do action x
}
}
The first loop does pre_x (probably an iterative action), then x, the second one does a part of pre_x, then if its not done, continues doing it until its done, then does x. So both do pre_x and then x.
I'm wondering if there are any differences between the two, both efficiency-wise, and in other ways (ie: if there is some subtle effect that would come up only rarely, &c.), or if there is any reason to use one instead of the other in a specific situation, or if it's just a matter of preference.
|
break statement from within an inner loop would not allow you to exit outer one. So you'll miss some useful functionality introduced by break/continue statements. Compare:
while(some_loop_cont_val) {
if(some_det) {
break;
}
}
//"break" takes you here
and
while(some_loop_cont_val){
while(some_det) {
break;
}
//"break" takes you here
}
Another thing is that "while" loop needs at least two comparisons: to enter it on the 1st iteration and to not enter it on the second one.
|
1,813,897 | 1,813,903 | Is there a utility to indent C++ programs | I am trying to use "indent" program to indent C++ programs. But it does not seem to work fine. It is messing up the indentation much more.
It is a Class file. Can you please suggest the right options for it or another program that works?
Thanks
| Try Artistic Style:
Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages.
|
1,813,917 | 1,814,660 | How do you include an external library in your own project for C++? | So I'm quite new to C++, I've basically been coding it all semester for a class. For our final project, we made an email client in C++ with .NET, and to do all the email sending and receiving, we went with using the POCO email client.
Now, basically in order to use the POCO library, I've compiled it and done a number of things, such as adding the includes and libraries into the project using the path to where I compiled (on the desktop..), and I also had to add the path to the windows path.
SO, my question is, if I want to be able to package the POCO libraries into my project, how am I going to be able to do that? I can't really find a tutorial for this anywhere, any help would be appreciated.
Thanks! :)
| If you're using Visual Studio, there should be some info in the MSDN Help Center. Here is the online version for VS2008 from the MSDN library.
|
1,814,189 | 1,814,194 | How to change string into QString? | What is the most basic way to do it?
| If by string you mean std::string you can do it with this method:
QString QString::fromStdString(const std::string & str)
std::string str = "Hello world";
QString qstr = QString::fromStdString(str);
If by string you mean Ascii encoded const char * then you can use this method:
QString QString::fromAscii(const char * str, int size = -1)
const char* str = "Hello world";
QString qstr = QString::fromAscii(str);
If you have const char * encoded with system encoding that can be read with QTextCodec::codecForLocale() then you should use this method:
QString QString::fromLocal8Bit(const char * str, int size = -1)
const char* str = "zażółć gęślą jaźń"; // latin2 source file and system encoding
QString qstr = QString::fromLocal8Bit(str);
If you have const char * that's UTF8 encoded then you'll need to use this method:
QString QString::fromUtf8(const char * str, int size = -1)
const char* str = read_raw("hello.txt"); // assuming hello.txt is UTF8 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const char*
QString qstr = QString::fromUtf8(str);
There's also method for const ushort * containing UTF16 encoded string:
QString QString::fromUtf16(const ushort * unicode, int size = -1)
const ushort* str = read_raw("hello.txt"); // assuming hello.txt is UTF16 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const ushort*
QString qstr = QString::fromUtf16(str);
|
1,814,241 | 1,814,251 | Trying to get signals to work in my QT. I need some advice and help | So I have in my main function:
string s = "\nWelcome to Rawr\n";
const QString output(s);
**emit output(output); <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Getting an error here**
I have set up a Signal in QT Desginer named: output(const QString &s)
My receiver for the signal is my "Form"... in my form.h i have:
The slot is called "changeOutput(const QString &s).
void Client::changeOutput(const QString &s)
{
output_box.setText(s);
}
output_box is a QTextEdit box.
The error I am receiving is :
TCPClient.cpp:122: error: no match for call to ‘(const QString) (const QString&)’
What am I doing wrong?
Thanks :)
| Since you declared a variable output, the name output refers to that variable in the local scope. The compiler doesn't know that in output(output) you want one output to refer to the variable and the other output to refer to the slot/method.
Use a different name for the local variable to avoid this collision.
|
1,814,269 | 1,814,367 | c++ Mysql C API mysql_real_escape_string | I'm building a class wrapper for the mysql c api, specifically at the moment for mysql_real_escape_string and I don't think I'm doing it quite right.
this is what I have for the function:
std::string Database::EscapeString(const char *pStr)
{
char *tStr = new char[strlen(pStr)*2+1];
mysql_real_escape_string(m_sqlCon, tStr, pStr, strlen(pStr));
string retStr(tStr);
delete [] tStr;
return retStr;
}
I tried running this through but it did not perform as expected and ended in mysql errors.
| Looks good to me. I suspect your database problem is elsewhere.
There's an easy way to check: temporarily replace Database::EscapeString with a dummy function, i.e.
std::string Database::EscapeString(const char *pStr) {return string(pStr);}
Then see if you get the same errors.
Edit:
Not knowing exactly what the error is, or what the query causing it is, it's tough to narrow down the problem. Here are some things to try:
A) Just get rid of all characters that would need to be escaped. It'll put bogus data into the database, but hopefully you're just testing anyways:
std::string Database::EscapeString(const char *pStr) {
string result;
while (*pStr) {
if (strchr("\"'\r\n\t",*pStr))
{
//bad character, skip
}
else
{
result.push_back(*pStr);
}
++pStr;
}
return result;
}
B) Look for errors elsewhere. Is Database::Execute coded well? Maybe it does a snprintf internally with a hardcoded buffer size (which you may be exceeding)
C) Try taking your debug output and entering it straight into the mysql client program (don't forget to put a semicolon at the end). Same error?
|
1,814,377 | 2,008,561 | Reverse Engineering an Apple Kext - Reconstructing the Class | Greetings!
I am currently attempting to extend the functionality of the Magic Mouse. To do this, I am hoping to write a kext that intercepts events from the multitouch driver, AppleMultitouchDriver.kext, interprets them, and either dispatches new events or forwards the actual event. This approach is similar to the approach used by DoubleCommand.
I have already created a small test kext that intercepts the mouse events (click, motion, etc) as that will be needed also.
The problem I am having now is that I am unable to intercept the events from the AppleMultitouchDevice and/or AppleMultitouchHIDEventDriver objects because there is no class definition for them. I need to be able to reassign the pointer to the callback function as I do in the mouse interceptor and as is done in DoubleCommand. As far as I know, this means I need to reconstruct the AppleMultitouchDevice class. I already am able to get a reference to the instance of the AppleMultitouchDevice object, so I just need to be able to cast it and use it.
Now that you have the background, here are my direct questions:
What methods do I need to use in order to reverse engineer the kext or reconstruct the classes in question?
What programs are available that will assist me in this effort?
Are there any tutorials or e-books that focus on this particular topic that you know of?
Is it possible for me to reassign the callback pointer without actually reconstructing the entire class?
Anything else I may have missed as I am so very new to this.
Thanks in advance for any advice or assistance!!
| I've managed to find what I needed. Now all it will take is time and effort. :)
|
1,814,531 | 1,816,913 | Absolute beginners guide to working with audio in C/C++? | I've always been curious about audio conversion software, but I have never seen a proper explanation from a beginners point of view as to how to write a simple program that converts for example, a mp3 file to a wav. I'm not asking about any of the complex algorithms involved, just a small example using a simple library. Searching on SO, I came up with several names including:
Lame
The Synthesis Toolkit
OpenAL
DirectSound
But I'm unable to find a straightforward example of any of these libraries. Usually I don't mind wading through tons of code, but here I have absolutely no knowledge about the subject and so I always feel like I'm shooting in the dark.
Anyone here have a simple example / tutorial on converting a sound file using any of these libraries? My question is specifically directed towards C/C++ because those are the two languages I'm currently learning and so I'd like to continue to focus on them.
Edit: One thing I forgot to mention: I'm on a *NIX system.
| Thanks everyone for the responses! I sort of cobbled them together to successfully make a small utility that converts a AIFF/WAV/etc file to an mp3 file. There seems to be some interest in this question, so here it what I did, step by step:
Step 1:
Download and install the libsndfile library as suggested by James Morris. This library is very easy to use – its only shortcoming is it won't work with mp3 files.
Step 2:
Look inside the 'examples' folder that comes with libsndfile and find generate.c. This gives a nice working example of converting any non-mp3 file to various file formats. It also gives a glimpse of the power behind libsndfile.
Step 3:
Borrowing code from generate.c, I created a c file that just converts an audio file to a .wav file. Here is my code: http://pastie.org/719546
Step 4:
Download and install the LAME encoder. This will install both the libmp3lame library and the lame command-line utility.
Step 5:
Now you can peruse LAME's API or just fork & exec a process to lame to convert your wav file to an mp3 file.
Step 6: Bring out the champagne and caviar!
If there is a better way (I'm sure there is) to do this, please let me know. I personally have never seen a step-by-step roadmap like this so I thought I'd put it out there.
|
1,814,548 | 1,814,618 | boost::system::(...)_category defined but not used | I'm currently getting compiler warnings that resemble the warning I gave in the question title. Warnings such as....
warning: 'boost::system::generic_category' defined but not used
warning: 'boost::system::posix_category' defined but not used
warning: 'boost::system::errno_ecat' defined but not used
warning: 'boost::system::native_ecat' defined but not used
As far as I know the program isn't being affected in any way. However, I don't like warnings hanging around, but I have no idea what these warnings are trying to tell me besides that something defined and related to boost is hanging around somewhere not being used. However, everything that I've defined, I've used. The boost libraries I'm using are the random library and the filesystem library.
When I check the source of the warning it brings up Boost's error_category.hpp file and highlights some static consts that are commented as either "predefined error categories" or "deprecated synonyms". Maybe the problem has something to do with my error handling (or lack of) when using the library?
Can anyone give some insight regarding why these warnings are popping up? Am I completely missing something?
P.S. Warnings are at max level.
| This relates to the error_code library in the Boost.System library. Boost error_codes contain two attributes: values and categories. In order to make error_codes extensible so that library users can design their own error categories, the boost designers needed some way to represent a unique error code category. A simple ID number wouldn't suffice, because this could result in two projects using conflicting ID numbers for custom error categories.
So basically, what they did was to use memory addresses, in the form of static objects that inherit from the base class error_category. These variables don't actually do anything except to serve as unique identifiers of a certain error category. Because they are essentially static dummy objects with unique addresses in memory, you can easily create your own custom error categories which won't interfere with other error category "IDs." See here for more information.
I suppose that what you're seeing is a side-effect of this design decision. Since these variables are never actually used in your program, the compiler is generating warnings. Suffice it to say, I don't think you're doing anything wrong.
|
1,814,756 | 1,814,800 | parsing argc and argv in c++ | I want to learn more C++... Usually I make a for loop to parse argv, and I wind up with a bunch a C-style strings. I want to do something similar in C++, but preferably without reading from /proc/whatever. At first, I tried to convert the C-style string to a C++ style string without results... The frustrating bit is that everyone on SO seems to want to know how to go the other way, which is what c_str() is for. What's a good C++ way to do this (ie parse argv)?
Also, one note, I'm looking for a unix style answer, all the techniques for conversion I've seen have to do with Windows, which I'm completely uniterested in.
| I'm not sure I fully understand the question.
The cleanest method I know to get all the arguments in an easy to use array is:
std::vector<std::string> v(argv, argv + argc);
But if you're looking for a way to really parse the data, check out Boost.ProgramOptions.
|
1,814,772 | 1,814,778 | C++ header file convention | I am working on a small game using C++, and I used Eclipse CDT's class generator. It created a .h file with the class definitions and a .cpp file that included body-less methods for said class.
So if I followed the template, I'd have a .cpp file filled with the methods declarations, and a .cpp file with method bodies. However, I can't include a .cpp file within another.
So what is the convention in C++ with classes and include files? What I did was fill in the method bodies right under the class declaration in the .h file, and deleted the .cpp file.
| You don't have to include the .cpp file. Including the .h file is all it takes. .h means header, ie, all it should have is function / object definitions. The actual implementations go in the .cpp file of the same name. The linker will deal with straightening it out for you.
The header file contains declarations (also known as prototype). Inclusion of the header lets the program know "I declare something that looks like this exists".
The user of headers saves us the effort of declaring methods all over the place in our code files - we just do it once, then import the file.
The .c/.cpp/.cc file includes the definition - which tells the program what the function does.
You do not have to "include" .c files because that's what the compiler does - it compiles all your .c files into machine code.
|
1,814,844 | 1,989,207 | Using tui option of GDB | I am currently working with NS-2(A network Simulator) and I wanted to use the tui option of gdb such that i can view the course code while debugging. (Just like Visual studio)
As of now the source window is blank when i run "gdb -tui" . However I can see the file when i do a "list" in gdb, but I am not able to make it go automatically to the file and point to the break location.
Any Ideas how to do this?
| While I'm not sure about the GDB TUI, if you're familiar with vi then be sure to check out CGDB. It is a TUI front-end to GDB using vi-like key bindings.
To set a break point in CGDB, just hit escape (of course), navigate to the line you want to break on, then hit the space bar!
|
1,814,993 | 1,814,999 | Does my C++ compiler optimize my code? | While using modern C++ compilers (including MSVC, GCC, ICC), how can I say if it has:
parallelized the code
vectorized the loops (or used other specific processor instructions)
unrolled the loops
detected tail-recursion
performed RVO (return-value optimization)
or optimized in some other way
without diving into the assembler code the compiler produces?
| The only way you can really tell is if you examine the assembler output (which you appear to have discounted). Other than that, you could read the doco to see what types of optimization each level of your compiler provides.
But, in all honesty, if you don't trust that the optimization levels of your compiler are doing the job, you probably won't trust the doco :-)
I would look at the assembler myself, it's the only way you could be truly certain.
|
1,814,997 | 1,815,019 | Convert from hexadecimal to binary C++ | This kind of builds up on Already asked question...
However here, say, I'm given a hexadecimal input which could be a max of '0xFFFF'
I'll need it converted to binary, so that I'd end up with a max of 16 bits.
I was wondering if using 'bitset' it'd be quite simple.. Any ideas?
EDIT :
After getting answers, improvised piece of code here : http://pastebin.com/f7a6f0a69
| Supposing by "hexadecimal input" you mean a string containing a hexadecimal number, then this would work:
const char* const str = "0xFFFF";
std::istringstream iss(str);
int i;
iss >> std::hex >> i;
if(!iss && !iss.eof()) throw "dammit!";
std::cout << '"' << str << "\": " << i << "(0x" << std::hex << i << ")\n";
|
1,815,075 | 1,815,084 | Problem with iterators for std::list of boost::shared_ptr | I'm having a problem with the following code:
#include <list>
#include <boost/shared_ptr.hpp>
#include "Protocol/IMessage.hpp"
template <typename HeaderType>
class Connection {
public:
typedef IMessage<HeaderType> MessageType;
typedef boost::shared_ptr<MessageType> MessagePointer;
template <typename Handler>
void
FlushMessageQueue(Handler handler) {
std::list<MessagePointer>::iterator ib = message_queue_.begin(); // line 69
std::list<MessagePointer>::iterator ie = message_queue_.end();
for (; ib != ie; ++ib) {
AsyncWrite(*ib, handler);
}
}
private:
std::list<MessagePointer> message_queue_;
};
gcc (4.2.1) tells me:
include/Network/Connection.hpp: In member function 'void Network::Connection<MT>::FlushMessageQueue(Handler)':
include/Network/Connection.hpp:69: error: expected `;' before 'ib'
I wonder why I can't create an iterator for a list of MessagePointer's.
Any ideas?
Thank you.
| std::list<MessagePointer> in your code is a dependent type (i.e. it depends on the type of a template argument). Consequently, you need to use typename to state that ::iterator is expected to be a type for all potential instantiations (as it can be a value for some of them, if they are specialized). So:
typename std::list<MessagePointer>::iterator ib = message_queue_.begin();
|
1,815,136 | 1,815,144 | Never ending Win32 Message loop | I have the following code:
MSG mssg;
// run till completed
while (true) {
// is there a message to process?
while(PeekMessage( &mssg, NULL, 0, 0, PM_REMOVE)) {
// dispatch the message
TranslateMessage(&mssg);
DispatchMessage(&mssg);
}
if(mssg.message == WM_QUIT){
break;
}
// our stuff will go here!!
Render();
listeners->OnUpdate();
}
Once it enters the inner loop with peekmessage it does not exit until the application is closed. Thus if I place a breakpoint at Render() and OnUpdate(), they will never be called during the lifetime of the application.
This runs contrary to what I'm being told here and here. How do I do this properly?
| A typical game loop has this form:
MSG mssg;
bool notdone = true;
// run till completed
while ( notdone ) {
// is there a message to process?
if (PeekMessage( &mssg, NULL, 0, 0, PM_REMOVE)) {
if (mssg.message == WM_QUIT) notdone = false;
// dispatch the message
TranslateMessage(&mssg);
DispatchMessage(&mssg);
} else {
// our stuff will go here!!
Render();
listeners->OnUpdate();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.