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
3,000,992
3,001,143
How C++/Qt - Memory allocation works?
I recently started investigating Qt for myself and have the following question: Suppose I have some QTreeWidget* widget. At some moment I want to add some items to it and this is done via the following call: QList<QTreeWidgetItem*> items; // Prepare the items QTreeWidgetItem* item1 = new QTreeWidgetItem(...); QTreeWidgetItem* item2 = new QTreeWidgetItem(...); items.append(item1); items.append(item2); widget->addTopLevelItems(items); So far it looks ok, but I don't actually understand who should control the objects' lifetime. I should explain this with an example: Let's say, another function calls widget->clear();. I don't know what happens beneath this call but I do think that memory allocated for item1 and item2 doesn't get disposed here, because their ownage wasn't actually transfered. And, bang, we have a memory leak. The question is the following - does Qt have something to offer for this kind of situation? I could use boost::shared_ptr or any other smart pointer and write something like shared_ptr<QTreeWidgetItem> ptr(new QTreeWidgetItem(...)); items.append(ptr.get()); but I don't know if the Qt itself would try to make explicit delete calls on my pointers (which would be disastrous since I state them as shared_ptr-managed). How would you solve this problem? Maybe everything is evident and I miss something really simple?
A quick peek into qtreewidget.cpp shows this: void QTreeWidget::clear() { Q_D(QTreeWidget); selectionModel()->clear(); d->treeModel()->clear(); } void QTreeModel::clear() { SkipSorting skipSorting(this); for (int i = 0; i < rootItem->childCount(); ++i) { QTreeWidgetItem *item = rootItem->children.at(i); item->par = 0; item->view = 0; delete item; // <<----- Aha! } rootItem->children.clear(); sortPendingTimer.stop(); reset(); } So it would appear that your call to widget->addTopLevelItems() does indeed cause the QTreeWidget to take ownership of the QTreeWidgetItems. So you shouldn't delete them yourself, or hold them in a shared_ptr, or you'll end up with a double-delete problem.
3,001,121
3,001,207
Else statement crashes when i enter a letter for a cin << int value
Alright, I have a question, I veered away from using strings for selection so now I use an integer. When the user enters a number then the game progresses. If they enter a wrong character it SHOULD give the else statement, however if I enter a letter or character the system goes into an endless loop effect then crashes. Is there a way to give the else statement even if the user defines the variable's type. // action variable; int c_action: if (c_action == 1){ // enemy attack and user attack with added effect buffer. /////////////////////////////////////////////////////// u_attack = userAttack(userAtk, weapons); enemyHP = enemyHP - u_attack; cout << " charging at the enemy you do " << u_attack << "damage" << endl; e_attack = enemyAttack(enemyAtk); userHP = userHP - e_attack; cout << "however he lashes back causing you to have " << userHP << "health left " << endl << endl << endl << endl; //end of ATTACK ACTION }else{ cout << "invalid actions" << endl; goto ACTIONS; }
Your problem is not with the else-statement, but with your input. If you do something like cin >> i; and enter a character, the streams error state is set and any subsequent try to read from the stream will fail unless you reset the error state first. You should read a string instead and convert the strings contents to integer.
3,001,266
3,001,371
Trying to zoom in on an arbitrary rect within a screen-aligned quad
I've got a screen-aligned quad, and I'd like to zoom into an arbitrary rectangle within that quad, but I'm not getting my math right. I think I've got the translate worked out, just not the scaling. Basically, my code is the following: // // render once zoomed in glPushMatrix(); glTranslatef(offX, offY, 0); glScalef(?wtf?, ?wtf?, 1.0f); RenderQuad(); glPopMatrix(); // // render PIP display glPushMatrix(); glTranslatef(0.7f, 0.7f, 0); glScalef(0.175f, 0.175f, 1.0f); RenderQuad(); glPopMatrix(); Anyone have any tips? The user selects a rect area, and then those values are passed to my rendering object as [x, y, w, h], where those values are percentages of the viewport's width and height.
When I've needed to do this, I've always just changed the parameters I passed to glOrtho, glFrustrum, gluPerspective, or whatever (whichever I was using).
3,001,336
3,001,352
C++: Delete a struct?
I have a struct that contains pointers: struct foo { char* f; int* d; wchar* m; } I have a vector of shared pointers to these structs: vector<shared_ptr<foo>> vec; vec is allocated on the stack. When it passes out of scope at the end of the method, its destructor will be called. (Right?) That will in turn call the destructor of each element in the vector. (Right?) Does calling delete foo delete just the pointers such as foo.f, or does it actually free the memory from the heap?
delete foo; will delete the memory allocated to the foo structure, which includes the three pointers. But the memory pointed to by the pointers themselves will only be deleted if you implement a destructor that explicitly deletes them.
3,001,413
3,001,887
How do I obtain a code point integer from a 1 to 4 byte UTF-8 encoded sequence in Windows?
I am Patrick Niedzielski, a programmer for the Free Software 3D adventure game Humm and Strumm. I'm working on a minimal Unicode character class in C++. I currently have an array of four bytes representing a UTF-8 sequence. On GNU/Linux, I can just convert to UTF-32 with iconv(), but on Windows, I cannot do this. Is it possible to convert the array to a single code point? Thanks, Patrick
I recently posted C/C++ code for decoding a UTF-8 sequence to UTF-32: How do I read UTF-8 characters via a pointer? Validate Unicode String and Escape if Unicode is Invalid (C/C++)
3,001,419
3,001,454
Getting input in system() function (Mac)
#include <iostream> using namespace std; int main() { short int enterVal; cout << "enter a number to say: " << endl; cin >> enterVal; system("say "%d"") << enterVal; return 0; } Is what I am currently trying. I want the user to enter a number and the system() function says it basically. The code above has an error which says " 'd' was not declared in this scope ". Thanks in advance.
You must format the string manually. #include <iostream> #include <sstream> using namespace std; int main() { short int enterVal; cin >> enterVal; stringstream ss; ss << "say \"" << enterval << "\""; system(ss.str().c_str()); }
3,001,548
3,001,749
Is there a 2003 compatibility setting in Visual Studio 2008 (compiler compatibility, not project / solution files)
I have a Visual Studio 2003 solution that I've opened with VS2008, and it converted successfully. However, it won't build because the code contains some things that were acceptable under Visual Studio 2003, but simply don't fly under Visual Studio 2008. Changing the code would be really difficult in my particular situation. Is there a flag or something that I can set which would use 2003-compatible compilation? Cheers, Frank
There is not a compatibility switch. You'll have to install VS2k3 if you can't update the source code.
3,001,579
3,001,605
C++ WCHAR: Cannot allocate an array of constant size 0
I'm trying to create a WCHAR: LONG bufferSize = foo.bar() + 1; WCHAR wszBaz[bufferSize]; The compiler issues an error: error C2057: expected constant expression error C2466: cannot allocate an array of constant size 0 error C2133: 'wszBaz' unknown size What am I doing wrong? UPDATE: I added const but it still gives the same error: const LONG bufferSize = foo.bar() + 1; WCHAR wszBaz[bufferSize];
Array sizes must be constant expression: const int foo = 10; WCHAR array1[123]; // ok - 123 is a constant expression WCHAR array2[foo + 10]; // ok too - the expression is constant WCHAR array3[bar(123)]; // not ok - it may evaluate to the same thing every time, but function calls aren't seen as constant. Note that const does not make something a const expression. A const expression is something that is constant at compile time. The compiler is smart enough to figure out that something like 5+5 is a const expression, but isn't smart enough to figure out that foo(5,5) is a const expression -- even if foo(x,y) just returns x+y. In the next C++ standard (C++0x), you will be able to define functions as const-expressions.
3,001,615
4,663,788
Qt moc with implementations inside of header files?
Is it possible to tell the Qt MOC that I would like to declare the class and implement it in a single file rather than splitting them up into an .h and .cpp file?
I believe this to be the best way. It's actually how I construct all of my objects now. Qt 4.8.7 Works.pro: SOURCES += \ main.cpp HEADERS += \ Window.h \ MyWidget.h main.cpp #include <QtGui> #include "Window.h" int main(int argc, char *argv[]) { QApplication app(argc,argv); Window window; window.show(); return app.exec(); } Window.h #ifndef WINDOW_H #define WINDOW_H #include <QtGui> #include "MyWidget.h" class Window : public QWidget { Q_OBJECT private: MyWidget *whatever; public: Window() { QHBoxLayout *layout = new QHBoxLayout; setLayout(layout); whatever = new MyWidget("Screw You"); layout->addWidget(whatever); } }; #include "moc_Window.cpp" #endif // WINDOW_H MyWidget.h #ifndef MYWIDGET_H #define MYWIDGET_H #include <QtGui> class MyWidget : public QLabel { Q_OBJECT public: MyWidget(QString text) : QLabel(text) { // Whatever } }; #include "moc_MyWidget.cpp" #endif // MYWIDGET_H Build... qmake Works.pro make
3,001,653
3,001,670
How can I access the sign bit of a number in C++?
I want to be able to access the sign bit of a number in C++. My current code looks something like this: int sign bit = number >> 31; That appears to work, giving me 0 for positive numbers and -1 for negative numbers. However, I don't see how I get -1 for negative numbers: if 12 is 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1100 then -12 is 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 0011 and shifting it 31 bits would make 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 which is 1, not -1, so why do I get -1 when I shift it?
The result of right-shifting a negative number in C++ is implementation-defined. So, no one knows what right-shifting your -12 should get on your specific platform. You think it should make the above (1), while I say that it can easily produce all-ones pattern, which is -1. The latter is called sign-extended shifting. In sign-extended shifting the sign bit is copied to the right, but never shifted out of its place. If all you are interested in is the value of the sign bit, then stop wasting time trying to use bitwise operations, like shifts etc. Just compare your number to 0 and see whether it is negative or not.
3,001,679
3,001,699
Why do I get corrupt output on my file?
I have a simple program which I have compiled in both MinGW and Visual C++ 2008 Express, and both give an output file larger than 88200. When I set s = 0, both programs work as expected. What am I doing wrong? #include <fstream> using namespace std; int main(int argc, char *argv[]) { int i; short s; fstream f; f.open("test.raw", ios_base::out); for(i = 0; i < 44100; i++) { s = i & 0xFFFF; // PROBLEM? f.write(reinterpret_cast<const char *>(&s), sizeof(s)); } f.close(); return 0; }
Try: f.open("test.raw", ios_base::out | ios_base::binary); When you write out chars that happen to match the newline character \n they are being converted to the standard windows newline sequence \r\n. Opening the file in binary mode stops this conversion from being performed.
3,001,805
3,001,817
The ** idiom in C++ for object construction
In a lot of C++ API'S (COM-based ones spring to mind) that make something for you, the pointer to the object that is constructed is usually required as a ** pointer (and the function will construct and init it for you) You usually see signatures like: HRESULT createAnObject( int howbig, Object **objectYouWantMeToInitialize ) ; -- but you seldom see the new object being passed as a return value. Besides people wanting to see error codes, what is the reason for this? Is it better to use the ** pattern rather than a returned pointer for simpler operations such as: wchar_t* getUnicode( const char* src ) ; Or would this better be written as: void getUnicode( const char* src, wchar_t** dst ) ; The most important thing I can think of is to remember to free it, and the ** way, for some reason, tends to remind me that I have to deallocate it as well.
"Besides wanting error codes"? What makes you think there is a besides. Error codes are pretty much the one and only reason. The function needs some way to indicate failure. C doesn't have exceptions, so it has to do that through either a pointer parameter, or the return value, and the return value is idiomatic, and easier to check when calling the function. (By the way, there's no universal rule that ** means you have to free the object. That's not always the case, and it's probably a bad idea to use something that arbitrary to remind you of which objects to clean up.)
3,001,938
3,002,034
get resulting verticies from a gltransformation?
I have some verticies and then I apply a glrotate(). I'd want to now what my verticies became after this transformation. How could I do this? Thanks
Again? You can't do that. There is a feedback buffer, but that's not what you are looking for. Read my previous explanation for details.
3,002,022
3,002,156
How do games move around objects (in general)
I'm sure there's not just 1 answer to this but, do game engines actually change the vectors in memory, or use gltransformations? Because pushing and popping the matrix all the time seems inefficient, but if you keep modifying the verticies you cant make use of display lists. So I'm wondering how it's done in general. Thanks
Depends on your goals/objects. Objects that never change are moved by setting matrices (it is possible to do that using glRotatef/glTranslatef and such too). It is certainly faster than transforming object vertex by vertex. Object is stored in DisplayList, VertexArray or in VBO. You CAN send entire object every time using glVertex* command, but if object never changes, there is no need for that. Characters (skinned/rigged) are transformed using multiple matrices, which is normally handled by vertex shader. You can do it on CPU, if you want, but unless you have a VERY advanced rigging/skinning engine, there is no need for that. Calculations that cannot be completely performed on Videocard, are performed on CPU. Normally it is particle systems, cloth and procedural geometry, sometimes shadows (for shadow volume calculation using stencil shadows). Objects like this are normally stored in memory, at least partially, and transformations performed on CPU. This is strictly hardware-dependent. Depending on the power of videocard and OpenGL version, it is possible to perform some or all of those tasks on videocard (without involving CPU), but not always. For example, normally it isn't possible to build shadow volume for procedural geometry (i.e. topology varies each frame as well as vertex positions) on GPU. However, there are tricks to avoid it, and situation might change with future versions.
3,002,084
3,002,662
Intra-Unicode "lean" Encoding Converters
Windows provides encoding conversion functions ("MultiByteToWideChar" and "WideCharToMultiByte") which are capable of UTF-8 to/from UTF-16 conversions, among other things. But I've seen people offer home-grown 30 to 40 line functions that claim also to perform UTF-8 / UTF-16 encoding conversions. My question is, how reliable are such tiny converters? Can such a tiny amount of code handle problems such as converting a UTF-16 surrogate pair (such as <D800 DC00>) into a UTF-8 single four byte sequence (rather than making the mistake of converting into a pair of three byte sequences)? Can they correctly spot "unpaired" surrogate input, and provide an error? In short, are such tiny converters mere toys, or can they be taken seriously? For that matter, why does unicode.org seemingly offer no advice on an algorithm for accomplishing such conversions?
The open source ICU library has 113 lines of code for ucnv_fromUnicode_UTF8 (source/common/ucnv_u8.c). Error checking included, proper surrogate handling, some comments. You should only consider using something else if you don't like the naming conventions.
3,002,101
3,004,223
How can I Violate Encapsulation property?
How can I Violate Encapsulation property without having a compile time error? (in C++) just so curious.. This was actually a question asked by one of my professor.. Please don't misunderstand. This was asked when we had a discussion over compiler error's
#define private public #define protected public #define class struct There you go :-)
3,002,110
3,002,124
#include in .h or .c / .cpp?
When coding in either C or C++, where should I have the #include's? callback.h: #ifndef _CALLBACK_H_ #define _CALLBACK_H_ #include <sndfile.h> #include "main.h" void on_button_apply_clicked(GtkButton* button, struct user_data_s* data); void on_button_cancel_clicked(GtkButton* button, struct user_data_s* data); #endif callback.c: #include <stdlib.h> #include <math.h> #include "config.h" #include "callback.h" #include "play.h" void on_button_apply_clicked(GtkButton* button, struct user_data_s* data) { gint page; page = gtk_notebook_get_current_page(GTK_NOTEBOOK(data->notebook)); ... Should all includes be in either the .h or .c / .cpp, or both like I have done here?
Put as much as you can in the .c and as little as possible in the .h. The includes in the .c are only included when that one file is compiled, but the includes for the .h have to be included by every file that uses it.
3,002,115
3,003,504
Iterator for boost::variant
Hy there, I'm trying to adapt an existing code to boost::variant. The idea is to use boost::variant for a heterogeneous vector. The problem is that the rest of the code use iterators to access the elements of the vector. Is there a way to use the boost::variant with iterators? I've tried typedef boost::variant<Foo, Bar> Variant; std::vector<Variant> bag; std::vector<Variant>::iterator it; for(it= bag.begin(); it != bag.end(); ++it){ cout<<(*it)<<endl; } But it didn't work. EDIT: Thank you for your help! But in my design, I need to get one element from the list and pass it around other parts of the code (and that can be nasty, as I'm using GSL). The idea of using an iterator is that I can pass the iterator to a function, and the function will operate on the return data from that specific element. I can't see how to do that using for_each. I need to do something similar to that: for(it=list.begin(); it!=list.end();++it) { for(it_2=list.begin(); it_2!=list.end();++it_2) { if(it->property() != it_2->property()) { result = operate(it,it_2); } } } Thanks!
Well of course there is. Dereferencing the iterators will naturally yield a boost::variant<...> reference or const-reference. However it does mean that the rest of code should be variant-aware. And notably use the boost::static_visitor to execute operations on the variants. EDIT: Easy! struct Printer: boost::static_visitor<> { template <class T> void operator()(T const& t) const { std::cout << t << std::endl; } }; std::for_each(bag.begin(), bag.end(), boost::apply_visitor(Printer()); Note how writing a visitor automatically yields a predicate for STL algorithms, miam! Now, for the issue of the return value: class WithReturn: boost::static_visitor<> { public: WithReturn(int& result): mResult(result) {} void operator()(Foo const& f) const { mResult += f.suprise(); } void operator()(Bar const& b) const { mResult += b.another(); } private: int& mResult; }; int result; std::for_each(bag.begin(), bag.end(), boost::apply_visitor(WithReturn(result))); EDIT 2: It's easy, but indeed need a bit of coaching :) First, we remark there are 2 different operations: != and operate struct PropertyCompare: boost::static_visitor<bool> { template <class T, class U> bool operator()(T const& lhs, U const& rhs) { return lhs.property() == rhs.property(); } }; struct Operate: boost::static_visitor<result_type> { result_type operator()(Foo const& lhs, Foo const& rhs); result_type operator()(Foo const& lhs, Bar const& rhs); result_type operator()(Bar const& lhs, Bar const& rhs); result_type operator()(Bar const& lhs, Foo const& rhs); }; for(it=list.begin(); it!=list.end();++it) { for(it_2=list.begin(); it_2!=list.end();++it_2) { if( !boost::apply_visitor(PropertyCompare(), *it, *it_2) ) { result = boost::apply_visitor(Operate(), *it, *it_2)); } } } For each is not that good here, because of this if. It would work if you could somehow factor the if in operate though. Also note that I pass not iterators but references.
3,002,123
3,002,182
C++: Best way to copy a section of WCHAR[] into a wstringstream?
I have a WCHAR[], a wstringstream, and an arbitrary section of the WCHAR[] that I want to copy into the wstringstream. What is the best way to do this? It seems that there must be a better way than this: for (int i = start; i < start + length; i++) { wszStringStream << wchr[i]; }
Sure. Try this: wszStringStream.write(wchr+start, length);
3,002,163
3,002,180
Using memcpy in the STL
Why does C++'s vector class call copy constructors? Why doesn't it just memcpy the underlying data? Wouldn't that be a lot faster, and remove half of the need for move semantics? I can't imagine a use case where this would be worse, but then again, maybe it's just because I'm being quite unimaginative.
Because the object needs to be notified that it is being moved. For example, there could be pointers to that given object that need to be fixed because the object is being copied. Or the reference count on a reference counted smart pointer might need to be updated. Or.... If you just memcpy'd the underlying memory, then you'd end up calling the destructor twice on the same object, which is also bad. What if the destructor controls something like an OS file handle? EDIT: To sum up the above: The copy constructor and destructor can have side effects. Those side effects need to be preserved.
3,002,183
3,002,407
Best way to render Tesselated Objects (OpenGL)
I'm using the GLUTesselator for Polygons. Right now the vertex callback does glvertex2f and gltex2f. Would it be better simply to collect the verticies from the vertex callback in a std::vector then use gldrawarrays()? Or would this actually be less efficient since it has to put the verts and texture coordinates in a vector? Thanks
If the vertex count on your tessellated objects is "sufficiently large" VAs/VBOs are almost always going to be faster than immediate-mode glBegin()/glEnd() code, especially if your geometry is static.
3,002,338
3,002,343
determining True/False
the following code #include <iostream> using namespace std; int main(){ char greeting[50] = "goodmorning everyone"; char *s1 = greeting; char *s2 = &greeting[7]; bool test = s2-s1; cout << "s1 is: " << s1 << endl; cout << "s2 is: " << s2 << endl; if (test == true ){ cout << "test is true and is: " << test << endl; } if (test == false){ cout<< "test is false and is: " << test << endl; } return 0; } outputs: s1 is: goodmorning everyone s2 is: ning everyone test is true and is: 1 here what does the line bool test = s2-s1; actually evaluate?, is it the length of the string?. If so, then seeing as s2 is a smaller than s1 it should be negative correct?, and yet the output is true?. Also if i change it to bool test = s1-s2; I still end up with the same result. So it doesnt matter whether its negative or positive the it will be true? and only false when 0?. what does the s2-s1 mean? -cheers (trying to get rid of doubts:))
If the result of the subtraction is zero, test will be false; otherwise it will be true. Any value that is of a numeric type, enumeration type, or is a pointer can be converted to a boolean; if the value is zero (or null, for pointers), the result is false; otherwise the result is true.
3,002,389
3,002,484
C++ - Basic WinAPI question
I am now working on a some sort of a game engine and I had an idea to put everything engine-related into a static library and then link it to my actual problem. Right now I achieved it and actually link that library and every functions seem to work fine, except those, which are windows-related. I have a chunk of code in my library that looks like this: hWnd = CreateWindow(className, "Name", WS_OVERLAPPED | WS_CAPTION | WS_EX_TOPMOST, 0, 0, 800, 600, NULL, NULL, GetModuleHandle(NULL), this); if (hWnd) { ShowWindow(hWnd, SW_NORMAL); UpdateWindow(hWnd); } else { MessageBox(NULL, "Internal program error", "Error", MB_OK | MB_ICONERROR); return; } When this code was not in the library, but in the actual project, it worked fine, created the window and everything was ok. Right now (when I'm linking to my library that contains this code) CreateWindow(...) call returns NULL and GetLastError() returns "Operation succesfully completed" (wtf?). Could anybody help me with this? Is it possible to create a window and display it using a static library call and why could my code fail? Thank you.
Ah, maybe you've run into this problem described in an MSDN blog: If you're writing a static library, you may have need to access the HINSTANCE of the module that you have been linked into. You could require that the module that links you in pass the HINSTANCE to a special initialization function, but odds are that people will forget to do this. If you are using a Microsoft linker, you can take advantage of a pseudovariable which the linker provides. EXTERN_C IMAGE_DOS_HEADER __ImageBase; #define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase) The pseudovariable __ImageBase represents the DOS header of the module, which happens to be what a Win32 module begins with. In other words, it's the base address of the module. And the module base address is the same as its HINSTANCE. So there's your HINSTANCE. So, instead of passing GetModuleHandle(NULL) to CreateWindow, try ((HINSTANCE)&__ImageBase) (make sure it is declared as shown in the blog first). Edit: From the comments in that blog entry, one mentions the use of GetModuleHandleEx(), perhaps this is a more Compiler/Linker-agnostic approach.
3,002,395
3,002,429
is there a way to use c++0x at xcode? I want to use gcc 4.4 or greater
I want to use gcc 4.4 or greater for iphone developement. anyone know how?
No you don't. Trust me you don't. Apple stays at gcc 4.2.1 because 4.2.2 and higher use the GPLv3 which means they'd have to give up control of their platform (a big problem for the iphone sdk). So they don't upgrade. Unfortunately for you, you can't exactly just drop in a replacement gcc either, due to custom patches, ABI changes, etc. Sorry.
3,002,433
3,002,469
function objects versus function pointers
I have two questions related to function objects and function pointers, Question : 1 When I read the different uses sort algorithm of STL, I see that the third parameter can be a function objects, below is an example class State { public: //... int population() const; float aveTempF() const; //... }; struct PopLess : public std::binary_function<State,State,bool> { bool operator ()( const State &a, const State &b ) const { return popLess( a, b ); } }; sort( union, union+50, PopLess() ); Question : Now, How does the statement, sort(union, union+50,PopLess()) work? PopLess() must be resolved into something like PopLess tempObject.operator() which would be same as executing the operator () function on a temporary object. I see this as, passing the return value of overloaded operation i.e bool (as in my example) to sort algorithm. So then, How does sort function resolve the third parameter in this case? Question : 2 Question Do we derive any particular advantage of using function objects versus function pointer? If we use below function pointer will it derive any disavantage? inline bool popLess( const State &a, const State &b ) { return a.population() < b.population(); } std::sort( union, union+50, popLess ); // sort by population PS : Both the above references(including example) are from book "C++ Common Knowledge: Essential Intermediate Programming" by "Stephen C. Dewhurst". I was unable to decode the topic content, thus have posted for help. Thanks in advance for your help.
PopLess() instantiates a temporary instance of the class PopLess to be passed to std::sort(). It's effectively the same as if you were to say (note that in this example an extra copy is made): PopLess pl = PopLess(); sort(union, union + 60, pl); Then, std::sort() will call the operator() on that instance. As for whether function objects or function pointers are better "better," it depends. Probably the most important difference is that function objects can maintain state while ordinary functions passed by pointer cannot. A compiler might be able to optimize one or the other better, but in most usage scenarios that's probably not important.
3,002,487
3,002,521
Simple/efficient text compression
What's the simplest, but efficient compression algorithm? Deflate, lzma, etc. aren't valid options. I need something that compiles really small, like: RLE, LZX, Huffman, etc.. Note: The data is 95% ASCII text Edit: Data is ~20kb at the moment, but i expect it to grow up to 1mb Edit2: Other interesting options smaz https://github.com/antirez/smaz FastLZ http://fastlz.org/
It sounds like LZO was designed to meet your requirements: Decompression is simple and very fast. Requires no memory for decompression. Compression is pretty fast.
3,002,571
3,002,588
Gradients and memory
I'm creating a drawing application with OpenGL. I'v created an algorithm that generates gradient textures. I then map these to my polygons and this works quite well. What I realized is how much memory this requires. Creating 1000 gradients takes about 800MB and that's way too much. Is there an alternative to textures, or a way to compress them, or another way to map gradients to polygons that doesn't use up as much memory? Thanks My polygons are concave, I use GLUTesselator, and they are multicolored and point to point
Yes... gradients are super easy to do in OpenGL; you don't need textures at all. Working from memory here... you'd just do something like this: glBegin(GL_POLYGON); glColor3ub(255,0,0); // red glVertex2f(-1,-1); glVertex2f(1,-1); glColor3ub(0,0,255); // blue glVertex2f(1,1); glVertex2f(-1,1); glEnd(); // draws a square that fades from red to blue If you change the color of a vertex, it just creates a gradient between those two points.
3,002,617
3,002,632
Compare List/set elements
I'm looking to compare two sets and display the missing elements in second set by iterating over the first set. I've done using lists but it seems like an overhead iterating over the unordered list to find the elements. #include <iostream> #include <list> using std::list; bool isExist(list <int> &original, int i) { list <int>::iterator iter; for (iter = original.begin(); iter != original.end(); iter++) { if (*iter == i) { original.splice(original.end(), original, iter); return true; } } return false; } void FindMissing(list <int> &original, list <int> &missing) { int count_exist = 0; list <int>::iterator iter; for (iter = missing.begin(); iter != missing.end(); iter++) {if (isExist(original, *iter)) count_exist++;} int count_missing = original.size() - count_exist; iter = original.begin(); while(count_missing > 0) { std::cout << *iter++ << std::endl; count_missing--; } } int main() { list <int> list_data_1; list <int> list_data_2; //Fill the list. for (int i = 0; i < 5; i++) list_data_1.push_back(i); //Fill second list with missing elements. list_data_2.push_back(3); list_data_2.push_back(1); list_data_2.push_back(4); FindMissing(list_data_1, list_data_2); } How would you do the same with set?
If you have two sets: std::set<int> s1; std::set<int> s2; and you want to get the set of elements that are in one but not the other, you can use std::set_difference: std::set<int> difference; std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), std::inserter(difference, difference.begin())); difference will contain all of the elements that are in s1 but not in s2. std::set_difference works for any two sorted ranges, so you could use it with other containers as well (e.g., if your std::lists were sorted, you could use std::set_difference on them to find the difference).
3,002,646
3,002,700
C++ template instantiation with identity argument
I have ran into yet another problem I do not understand. The following does not instantiate (argument instantiation fails), why? template<class E> void operator[](typename boost::mpl::identity<E>::type e) const; thank you for your help
identity can be used to force you to specify the template argument explicitly. It effectively prevents that function parameter from partaking in template argument deduction. A qualified type name is one of the non deduced contexts; that is, identity<E>::type will not be used to deduce the template parameter for E. For example, if you have: template<class E> void f(typename boost::mpl::identity<E>::type e) { } f(42); // won't work f<int>(42); // works
3,002,867
3,003,755
How to debug c++ DirectShow filter
What debugging tools are available for directshow filters? Presently, I have a project that compiles and registers a video source filter that I then setup a graph in GraphEdit. I am using c++ in visual studio 2008. Is it possible to get a debugger attached to the filter in any way where I could set break points, inspect variables, etc? Barring that is there a way to log diagnostic information somewhere that I can view in real time?
There should be no problem with attaching a debugger. Set graphedt.exe as the debug target in your filter's Visual Studio project and you should be able to set breakpoints in your code. If you're having difficulty with this, it might be because of the anti-debugging logic in some decoders — you'll have to avoid using those. You can also get useful debug information by logging the deliveries and their timestamps and latency. The best way I find to do ths is to use a pass-through filter. There is an example monitor filter like this available in source and binary form from www.gdcl.co.uk/mobile (win32 and win mobile). G
3,003,022
3,008,345
Boost ASIO async_accept compilation fails
Man... thought using ASIO in Boost was going to be easy and intuitive. :P I am starting to get it finally but I am having some trouble. Here's a snippet. I am having several compiler errors on the async_accept line. What am I doing wrong? :P I've based my code off of this page: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/tutorial/tutdaytime3/src.html Errors: Error 1 error C2780: 'void boost::asio::basic_socket_acceptor::async_accept(boost::asio::basic_socket &,boost::asio::ip::basic_endpoint &,AcceptHandler)' : expects 3 arguments - 2 provided e:\schoolcode\senior project\cplusplusport\cplusplusport\alexsocket.cpp 36 Error 2 error C2784: 'void boost::asio::basic_socket_acceptor::async_accept(boost::asio::basic_socket &,AcceptHandler)' : could not deduce template argument for 'boost::asio::basic_socket &' from 'boost::asio::ip::tcp::socket *' e:\schoolcode\senior project\cplusplusport\cplusplusport\alexsocket.cpp 36 bool TestSocket::StartListening(int port) { bool didStart = false; if (!this->listening) { //try to listen acceptor = new tcp::acceptor(this->myService, tcp::endpoint(tcp::v4(), port)); didStart = true; //probably change? tcp::socket* tempNewSocket = new tcp::socket(this->myService); acceptor->async_accept(tempNewSocket, boost::bind(&TestSocket::NewConnection, this, tempNewSocket, boost::asio::placeholders::error) ); } else //already started! return false; this->listening = didStart; return didStart; } void TestSocket::NewConnection(tcp::socket* s, const boost::system::error_code& error) { }
async_accept expects a reference to the socket, not a pointer, so try acceptor->async_accept(*tempNewSocket, ...
3,003,165
3,003,341
Why does update to a dll need recompilation and sometime not?
Why does update to a dll need recompilation and sometime not?
This is called "Binary Compatibility". Keeping this compatibility is not easy, and the information on this are very spare. You should google and test it yourself. Here are some (incomplete) guide for keeping the compatibility: http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C++ http://techbase.kde.org/Policies/Binary_Compatibility_Examples If you use COM and follow the COM guide, you should be safe all the time. note: some compiler flags also break binary compatibility.
3,003,308
3,003,423
General practice to specify a break after a default clause?
Possible Duplicate: break in a case with return.. and for default If I have a switch statement: switch() { case 1: ... case 2: ... ... default: break; } Is there any reason for the break in the default clause? I see this in quite a few places, but isn't it unnecessary? What is the general practice? Can another case label come after the default clause?
Can another case label come after the default clause? Yes, you are allowed to place the default clause anywhere within the switch block.
3,003,317
3,003,331
C++, what does this syntax mean?
i found this in this file: http://www.boost.org/doc/libs/1_43_0/boost/spirit/home/phoenix/core/actor.hpp What does this syntax means? struct actor ... { ... template <typename T0, typename T1> typename result<actor(T0&,T1&)>::type // this line I know what typename and templates are, my question is about actor(T0&,T1&) syntax thank you
So this means that there is a template called result and within result is a type called type. template <class T> class result { public: typedef ... type; }; So that line is using that type from the template. Because the compiler does not know what result<actor(T0&,T1&)>::type is, you need to use typename to tell the compiler to treat it as a type. Update actor(T0&,T1&) is a function taking a T0& and a T1& and returning an actor by value.
3,003,521
3,003,552
Why is this C or C++ macro not expanded by the preprocessor?
Can someone points me the problem in the code when compiled with gcc 4.1.0. #define X 10 int main() { double a = 1e-X; return 0; } I am getting error:Exponent has no digits. When I replace X with 10, it works fine. Also I checked with g++ -E command to see the file with preprocessors applied, it has not replaced X with 10. I was under the impression that preprocessor replaces every macro defined in the file with the replacement text with applying any intelligence. Am I wrong? I know this is a really silly question but I am confused and I would rather be silly than confused :). Any comments/suggestions?
When you write 1e-X all together like that, the X isn't a separate symbol for the preprocessor to replace - there needs to be whitespace (or certain other symbols) on either side. Think about it a little and you'll realize why.. :) Edit: "12-X" is valid because it gets parsed as "12", "-", "X" which are three separate tokens. "1e-X" can't be split like that because "1e-" doesn't form a valid token by itself, as Jonathan mentioned in his answer. As for the solution to your problem, you can use token-concatenation: #define E(X) 1e-##X int main() { double a = E(10); // expands to 1e-10 return 0; }
3,003,574
3,003,600
Explicit initialization of struct/class members
struct some_struct{ int a; }; some_struct n = {}; n.a will be 0 after this; I know this braces form of initialization is inherited from C and is supported for compatibility with C programs, but this only compiles with C++, not with the C compiler. I'm using Visual C++ 2005. In C this type of initialization struct some_struct n = {0}; is correct and will zero-initialize all members of a structure. Is the empty pair of braces form of initialization standard? I first saw this form of initialization in a WinAPI tutorial from msdn.
The empty braces form of initialization is standard in C++ (it's permitted explicitly by the grammar). See C Static Array Initialization - how verbose do I need to be? for more details if you're interested. I assume that it was added to C++ because it might not be appropriate for a 0 value to be used for a default init value in all situations.
3,003,794
3,004,187
What event (if any) does QTextEdit fire when the size of its content changes?
As the title says, how can I receive notification whenever a multi-line QTextEdit changes the size of its content? (Note: content size is different from the control size, i.e. I want to know when lines were added or removed, or changed height because of a font change).
QTextEdit has a textChanged() signal which will do what you want. From the docs: "This signal is emitted whenever the document's content changes; for example, when text is inserted or deleted, or when formatting is applied." I wasn't sure if formatting included font changes but I tested it and it does.
3,003,810
3,004,249
How to get the volume GUID
I am using win32 api with C++. I would like to know how I can get the volume GUID using a "device path". My device looks like this: \\?\usb#vid_04f2&pid_0111#5&39fe81e&0&2#{a5dcbf10-6530-11d2-901f-00c04fb951ed} Thanks.
This will be the device with device instance ID usb\VID_04f2&PID_0111\5&39fe81e&0&2. That's probably a mass storage device aka disk. Now, the problem you have is that a mass storage device doesn't actually have a drive letter; it's the volume on that disk which has a drive letter. If there are two partitions, a single USB mass storage device may have two drive letters. So, there's no direct function to get the volume. It looks like you need to enumerate the device tree rooted at usb\VID_04f2&PID_0111\5&39fe81e&0&2 to find children with device type "volume". The DEV_BROADCAST_DEVICEINTERFACE you get will have a dbcc_name field that you can pass to GetVolumeNameForVolumeMountPoint().
3,003,891
3,005,381
How to process signals in a Qt subclass?
How do I process a signal of in a subclass? Let's say my subclass is derived from QTextEdit and is interested in the signal textChanged. It seems silly to connect an object to itself, I should be able to simply override the textChange method -- but it isn't virtual. What is the accepted way to do this?
You can't implement/override a signal, so the only way is to create a new slot and connect it to textChanged(): connect( this, SIGNAL(textChanged(QString)), this, SLOT(slotTextChanged(QString)) );
3,004,001
3,004,022
Any real use case for using the calling convention fastcall?
Have you had any real use case for using the calling convention fastcall? Thanks.
Here's an article explaining when to use fastcall. It actually specifies a case when you actually have no alternative but to use it: Some VCL classes, such as TList, allow you to specify a callback function (a sort routine in the case of TList). You will have to use the __fastcall keyword in this case, too, as the VCL expects it.
3,004,040
3,004,048
What is a good idea for a list of strings?
I simply want to build an RPG and make it as neat as possible, I wish to define a pile of strings which I may want to edit later, so I tried something like this: enum { MSG_INIT = "Welcome to ...", MSG_FOO = "bar" }; But I just get errors, such as that MSG_INIT is not an integer! Why must it not be a string, are that what enums are only for? What do you think is the best way to define a pile of strings? In a struct called msg or something? I'm kinda new to all this so I'd really appreciate small examples.
enums are for groups of related numeric constants that you want to manipulate efficiently in memory. Instead, you can just use C string constants: char const *const MSG_INIT = "Welcome to ..."; char const *const MSG_FOO = "bar"; You can make them public fields if you choose. E.g. struct SomeClass { static char const *const MSG_INIT; static char const *const MSG_FOO; }; char const *const SomeClass::MSG_INIT = "Welcome to ..."; char const *const SomeClass::MSG_FOO = "bar";
3,004,095
3,004,122
Division by zero: Undefined Behavior or Implementation Defined in C and/or C++?
Regarding division by zero, the standards say: C99 6.5.5p5 - The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined. C++03 5.6.4 - The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. If we were to take the above paragraphs at face value, the answer is clearly Undefined Behavior for both languages. However, if we look further down in the C99 standard we see the following paragraph which appears to be contradictory(1): C99 7.12p4 - The macro INFINITY expands to a constant expression of type float representing positive or unsigned infinity, if available; Do the standards have some sort of golden rule where Undefined Behavior cannot be superseded by a (potentially) contradictory statement? Barring that, I don't think it's unreasonable to conclude that if your implementation defines the INFINITY macro, division by zero is defined to be such. However, if your implementation does not define such a macro, the behavior is Undefined. I'm curious what the consensus is (if any) on this matter for each of the two languages. Would the answer change if we are talking about integer division int i = 1 / 0 versus floating point division float i = 1.0 / 0.0 ? Note (1) The C++03 standard talks about the <cmath> library which includes the INFINITY macro.
I don't see any contradiction. Division by zero is undefined, period. There is no mention of "... unless INFINITY is defined" anywhere in the quoted text. Note that nowhere in mathematics it is defined that 1 / 0 = infinity. One might interpret it that way, but it is a personal, "shortcut" style interpretation, rather than a sound fact.
3,004,311
3,004,366
How to read the whole istream correctly?
Here is a simple code to print all characters of a txt file on screen: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { int **i; int j,k; char a; ifstream test("test.txt", ios::binary); while((a=test.get())!=-1)//if I use "while(!test.eof())" here, how to avoid the output of the last character(-1) to std::cout, or any ostream objects? { putchar(a);//also change this to putchar(test.get()); } getchar(); } As I noted in the code, if I use "test.eof()" to judge the end of test.txt, I'll always get an extra blank at the end of the output. How to avoid it?
You want: int a; The get() function returns an int, not a char - this is the same in C - when using getchar(), you read into an int variable not char. So your loop looks like: while( ( a = test.get() ) != EOF ) note you want EOF here, not eof(). a version using eof() would look like this: char c; while( test.get( c ) ) { putchar( c ); // or whatever } if ( test.eof() ) { // Ok, we finished because of end of file } else { // finished not because of end of file - probably an error }
3,004,501
3,004,555
Why do we need a virtual table?
I was looking for some information about virtual tables, but I can't find anything that is easy to understand. Can somebody give me good examples with explanations?
Without virtual tables you wouldn't be able to make runtime polymorphism work since all references to functions would be bound at compile time. A simple example struct Base { virtual void f() { } }; struct Derived : public Base { virtual void f() { } }; void callF( Base *o ) { o->f(); } int main() { Derived d; callF( &d ); } Inside the function callF, you only know that o points to a Base object. However, at runtime, the code should call Derived::f (since Base::f is virtual). At compile time, the compiler can't know which code is going to be executed by the o->f() call since it doesn't know what o points to. Hence, you need something called a "virtual table" which is basically a table of function pointers. Each object that has virtual functions has a "v-table pointer" that points to the virtual table for objects of its type. The code in the callF function above then only needs to look up the entry for Base::f in the virtual table (which it finds based on the v-table pointer in the object), and then it calls the function that table entry points to. That might be Base::f but it is also possible that it points to something else - Derived::f, for instance. This means that due to the virtual table, you're able to have polymorphism at runtime because the actual function being called is determined at runtime by looking up a function pointer in the virtual table and then calling the function via that pointer - instead of calling the function directly (as is the case for non-virtual functions).
3,004,796
3,004,840
C++ Using a class template argument as a template argument for another type
I'm having this problem while writing my own HashTable. It all works, but when I try to templatize the thing, it gave me errors. I recreated the problem as follows: THIS CODE WORKS: typedef double Item; class A { public: A() { v.push_back(pair<string, Item>("hey", 5.0)); } void iterate() { for(Iterator iter = v.begin(); iter != v.end(); ++iter) cout << iter->first << ", " << iter->second << endl; } private: vector<pair<string, double> > v; typedef vector< pair<string, double> >::iterator Iterator; }; THIS CODE DOES NOT: template<typename ValueType> class B { public: B(){} void iterate() { for(Iterator iter = v.begin(); iter != v.end(); ++iter) cout << iter->first << ", " << iter->second << endl; } private: vector<pair<string, ValueType> > v; typedef vector< pair<string, ValueType> >::iterator Iterator; }; the error messages: g++ -O0 -g3 -Wall -c -fmessage-length=0 -omain.o ..\main.cpp ..\main.cpp:50: error: type std::vector<std::pair<std::string, ValueType>, std::allocator<std::pair<std::string, ValueType> > >' is not derived from typeB' ..\main.cpp:50: error: ISO C++ forbids declaration of `iterator' with no type ..\main.cpp:50: error: expected `;' before "Iterator" ..\main.cpp: In member function `void B::iterate()': ..\main.cpp:44: error: `Iterator' was not declared in this scope ..\main.cpp:44: error: expected `;' before "iter" ..\main.cpp:44: error: `iter' was not declared in this scope Does anybody know why this is happening? Thanks!
This is called "dependent names" in C++. In your second code snippet, you say: typedef vector< pair<string, ValueType> >::iterator Iterator; whereas you should say: typedef typename vector< pair<string, ValueType> >::iterator Iterator; Whenever you see an error saying "is not derived...", typename is to the rescue. In general, the idea is that the compiler doesn't know if iterator is a type or a variable, because it doesn't know what vector< pair <string, ValueType> > is, as it depends on ValueType. (Afraid I'm not using the right terms here, but the idea is correct)
3,004,850
3,004,904
Portable way of counting milliseconds in C++?
Is there any portable (Windows & Linux) way of counting how many milliseconds elapsed between two calls ? Basically, I want to achieve the same functionnality than the StopWatch class of .NET. (for those who already used it) In a perfect world, I would have used boost::date_time but that's not an option here due to some silly rules I'm enforced to respect. For those who better read code, this is what I'd like to achieve. Timer timer; timer.start(); // Some instructions here timer.stop(); // Print out the elapsed time std::cout << "Elapsed time: " << timer.milliseconds() << "ms" << std::endl; So, if there is a portable (set of) function(s) that can help me implement the Timer class, what is it ? If there is no such function, what Windows & Linux API should I use to achieve this functionnality ? (using #ifdef WINDOWS-like macros) Thanks !
On Linux (and generally in POSIX), you can use gettimeofday function, which returns number of microseconds since the Epoch. On Windows, there is GetTickCount function, that return number of milliseconds since the system was started.
3,004,870
3,012,678
Can a custom MFC window/dialog be a class template instantiation?
There's a bunch of special macros that MFC uses when creating dialogs, and in my quick tests I'm getting weird errors trying to compile a template dialog class. Is this likely to be a big pain to achieve? Here's what I tried: MyDlg.h template <class W> class CMyDlg : public CDialog { typedef CDialog super; DECLARE_DYNAMIC(CMyDlg <W>) public: CMyDlg (CWnd* pParent); // standard constructor virtual ~CMyDlg (); // Dialog Data enum { IDD = IDD_MYDLG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() private: W *m_pWidget; //W will always be a CDialog }; IMPLEMENT_DYNAMIC(CMyDlg<W>, super) <------------------- template <class W> CMyDlg<W>::CMyDlg(CWnd* pParent) : super(CMyDlg::IDD, pParent) { m_pWidget = new W(this); } I get a whole bunch of errors but main one appears to be: error C2955: 'CMyDlg' : use of class template requires template argument list I tried using some specialised template versions of macros but it doesn't help much, other errors change but this one remains. Note my code is all in one file, since C++ templates don't like .h/.cpp like normal. I'm assuming someone must have done this in the past, possibly creating custom versions of macros, but I can't find it by searching, since 'template' has other meanings.
Here's a working solution, though ugly... I didn't get round to rewriting as a macro after expanding the existing one and fixing for templates: //Template-enabled expansion of IMPLEMENT_DYNAMIC(CMyDlg,super) template <class W> CRuntimeClass* PASCAL CMyDlg<W>::_GetBaseClass(){ return RUNTIME_CLASS(super); } template <class W> AFX_COMDAT const CRuntimeClass CMyDlg<W>::CMyDlg= { "CMyDlg", sizeof(CMyDlg<W>), 0xFFFF, NULL,&CMyDlg<W>::_GetBaseClass, NULL, NULL }; template <class W> CRuntimeClass* PASCAL CMyDlg<W>::GetThisClass() { return _RUNTIME_CLASS(CMyDlg); } template <class W> CRuntimeClass* CMyDlg<W>::GetRuntimeClass() const { return _RUNTIME_CLASS(CMyDlg); }
3,004,889
3,005,400
GetVolumeNameForVolumeMountPoint returns false
To get the volume GUID i tried the code like below int len = wcslen( pDetData->DevicePath); pDetData->DevicePath[len] = '\\'; pDetData->DevicePath[len+1] = 0; #define BUFFER_SIZE MAX_PATH WCHAR volume[BUFFER_SIZE]; BOOL bFlag; bFlag = GetVolumeNameForVolumeMountPoint( pDetData->DevicePath, volume, BUFFER_SIZE ); int loginErrCode = GetLastError(); printf("loginErrCode: %d\n", loginErrCode); printf("BFLAG: %d\n", bFlag); the GetLastError() also prints it as 1 . it means ERROR_INVALID_FUNCTION. The bFlag always returns zero it means false. what is the problem in my code...
This requires some crystal-ball consulting. The DevicePath string looks like it comes from SP_DEVICE_INTERFACE_DETAIL_DATA. That's a string that you don't own, modifying it corrupts the internal setupapi database at best, the heap at worst. You'll have to copy the string into your own buffer before turning it into the root directory name. This is just a theory, especially "loginErrCode" is a very strange name for what the code seems to do. Verify that the string you end up with at least looks similar to "F:\".
3,004,907
3,005,634
How can I login linux using C or C++
I need to programmely switch the current user to another,then the followed code should be executed in the environment(such as path,authority..) of another user. I've find the 'chroot()','setuid()' may be associated with my case, but these functions need the root authority, I don't have root authority, but I have the password of the second user. what should I do? I have tried shell "su - " can switch current user, can this command help me in my C++ code? Don't laugh at me if my question is very stupid, I'm a true freshman on linux. :) Thanks!
when clients connect to the server, the server transfer the data what they need,but the precondition is the correct username and password. If your primary requirement is to authenticate, then try man pam. There are also some libraries allowing to auth over LDAP. Unfortunately I have no personal experience implementing neither. Otherwise, recreating complete user environment is unreliable and error prone. Imaging a typo or endless loop but in user's ~/.profile. I haven't done that for some time, but I would also have tried to dig in direction of "su", figuring out user shell (from /etc/passwd) and trying to exec() it as if it was a login shell (with "-"). But after that you would need somehow to communicate a command for execution to it and that's a problem: shells run differently in batch more and in interactive mode. As a possible hack, expect (man expect) comes to mind, but it is still IMO too unreliable. I have in past used ssh under expect (to input the password), but it was breaking on customized user profiles every other time. With expect, to send a command, one has to recognize somehow that shell has finished initialization (execution of profile and rc files). But since many people customize the shell prompt and their profile/rc files print extra info, it was quite often that expect was recognizing shell prompt too soon. BTW, depending on number of users, one can try a setup where users manually start the server under their own account. The server would have access only to the information which is only accessible to the user.
3,004,915
3,026,808
Getting hardware floating point with android NDK
I've begun playing with the android NDK. One of the things I've just learnt is about creating an application.mk file to specify the armv7 abi. I'm building the san-angeles example with the following parameters. APP_MODULES := sanangeles APP_PROJECT_PATH := $(call my-dir)/../ APP_OPTIM := release APP_ABI := armeabi-v7a However this seems to run at exactly the same speed as it did before (ie badly). Am I just GL limited and not CPU limited or is something wrong here? I have noticed when I compile that I get the following command line options emitted: -march=armv7-a -mfloat-abi=softfp -mfpu=vfp -mthumb The thing that worries me there is the "softfp". There IS mention of the v7 abi, the VFP fpu stuff and I'm guessing the "thumb" refers to the "thumb-2" instructions (Though I don't know what exactly these are). However that "softfp" does concern me. Shouldn't it be "hardfp"? Anyone got any ideas on these questions? I think I'm probably about ready to start implementing some GL ES 2.0 code for my HTC Desire but I'd like to make sure I'm getting the best possible speed out of it :) Cheers in advance!
The options you supply to the NDK will only affect the way your code is compiled. It won't change the GL libs or anything else that's part of the platform, which are always generated in an appropriate fashion. If you're just throwing geometry at the GL hardware, you're not going to see a difference. If you want to see if your options are having an effect, download (or create) a simple benchmark that does a bunch of operations with double-precision floating point values, and time how long it takes to execute before and after. The -mfloat-abi=softp argument determines how floating-point values are passed between functions. softfp means they're always passed in integer registers or on the stack. If Android didn't specify softfp, the ARMv7-A version of the library would expect floats to show up in hardware registers, and any code built for ARMv5TE would break. "softfp" adds a little overhead to some functions, but the instructions for moving values in and out of fp registers are cheap on ARM, and the ABI compatibility provided makes it worthwhile. The "-mthumb" enables generation of Thumb/Thumb2 code. Thumb code tends to be a bit slower but a bit smaller than equivalent ARM; sometimes smaller means you'll fit better in the CPU i-cache and will actually run faster. Size is always a concern on these devices, so Thumb is enabled by default. When in doubt, "arm-eabi-objdump -d whatever.o" will show you a disassembly of your code. Update: NDK r9b added support for -mhard-float. This allows you to build NDK libraries with hard-float API conventions for armeabi-v7a targets.
3,004,963
3,005,013
Counting of objects created in stack and heap for many classes
What is the best way to count the total number of objects created in both stack and heap for different classes. I know that in C++ new and delete operators can be overloaded and hence in the default constructor and destructor the object count can be incremented or decremented as and when the objects get created or destroyed. Further if i am to extend the same thing for object counting of objects of different classes, then i can create a dummy class and write the object count code in that class and then when i create any new class i can derive it from the Dummy class. Is there any other optimal solution to the same problem.
then i can create a dummy class and write the object count code in that class and then when i create any new class i can derive it from the Dummy class. Yes, but since each class needs its own count, you have to make a base class template and use the curiously recurring template pattern (CRTP): template <class Derived> class InstanceCounter { static int count; protected: InstanceCounter() { ++count; } ~InstanceCounter() { --count; } public: static int instance_count() { return count; } }; template <class Derived> int InstanceCounter<Derived>::count = 0; class Test : public InstanceCounter<Test> { }; int main() { Test x; std::cout << Test::instance_count() << std::endl; { Test y; Test z; std::cout << Test::instance_count() << std::endl; } std::cout << Test::instance_count() << std::endl; }
3,004,979
3,005,225
C or C++: how do loaders/wrappers work?
Here's an example of what I mean... User runs LOADER.EXE program LOADER.EXE downloads another EXE but keeps it all in memory without saving it to disk Runs the downloaded EXE just as it would if it were executed from disk, but does it straight from memory I've seen a few applications like this, and I've never seen an example or an explanation of how it works. Does anyone know? Another example is having an encrypted EXE embedded in another one. It gets extracted and decrypted in memory, without ever being saved to disk before it gets executed. I've seen that one used in some applications to prevent piracy. Edit: As a side-note, do programs like UPX work like this? I looked at the code but it is hard to decipher for me, and I'm asking mainly out of curiosity, I don't have a need for it.
A lot of programs that do this just unzip to %TEMP% (I know I do), but the big boys essentially re-implement the OS executable loader, which has to: Map the executable into memory. This is not as simple as it sounds, as the .exe contains multiple 'sections', which must be loaded with page alignment (they must start at addresses that are multiples of 4K) and they each have specific requests - read only, copy on write, zero initialized, etc.... Satisfy static imports, by updating the import table section, normally using LoadLibrary() and GetProcAddress(). In the case of dlls (which are actually almost identical, the important difference is that they have exports as well as imports), the loader might also have to rebase the dll, if the memory address it was compiled to load at was already in use (which is quite common). This is normally impossible for exe's, though, because they do not include the relocation section which lists the places in the loaded code which need to be updated, because normally they are the first thing loaded into a process, and therefore can't be blocked by something. This means a loader has to have an unusual load address for it's own exe that won't block the loaded exe. In summary: this is a lot of work. If you are interested, take a look at the PE format specification, which describes .exe and .dll files, and the VirtualAlloc() function.
3,005,059
3,005,371
Throwing Exception in CTOR and Smart Pointers
Is it OK to have the following code in my constructor to load an XML document into a member variable - throwing to caller if there are any problems: MSXML2::IXMLDOMDocumentPtr m_docPtr; //member Configuration() { try { HRESULT hr = m_docPtr.CreateInstance(__uuidof(MSXML2::DOMDocument40)); if ( SUCCEEDED(hr)) { m_docPtr->loadXML(CreateXML()); } else { throw MyException("Could not create instance of Dom"); } } catch(...) { LogError("Exception when loading xml"); throw; } } Based on Scott Myers RAII implementations in More Effective C++ he cleanups if he alocates any resources i.e. pointers: BookEntry::BookEntry(const string& name, const string& address, const string& imageFileName, const string& audioClipFileName) : theName(name), theAddress(address), theImage(0), theAudioClip(0) { try { // this try block is new if (imageFileName != "") { theImage = new Image(imageFileName); } if (audioClipFileName != "") { theAudioClip = new AudioClip(audioClipFileName); } } catch (...) { // catch any exception delete theImage; // perform necessary delete theAudioClip; // cleanup actions throw; // propagate the exception } } I believe I am alright in just allowing exceptions to be thrown from CTOR as I am using a smart pointer(IXMLDOMDocumentPtr). Let me know what you think....
C++ guarantees that in case of an exception all fully constructed objects will be destroyed. Since m_docPtr is a member of class Configuration it will have been fully constructed before the class Configuration constructor body begins, so if you throw an exception from class Configuration body as you intended in your first snippet m_docPtr will be destroyed.
3,005,171
3,005,232
Receive many datagrams from several hosts using winsock
I am developing an application that distributes rendering across several devices (a university project). Each frame consists of several blocks (16x16 pixels), and each device is "assigned" a number of blocks to be rendered. These blocks, when rendered, are compressed and serialized into a buffer until the max size of this is reached, at which point it will be sent. My problem is on the receiving end, which needs to recieve several datagrams per frame from several devices. Currently I call recv for each packet, but this requires a context switch for each packet. It would be better to receive many packets with one call. A packet identify which client it is from, so the addresses of these are irrelevant. I have looked at WSARecv and WSARecvFrom but neither seems to be able to receive several packets from several hosts. Thanks in advance :) EDIT Using a separate thread to fetch packets from the OS layer does not seem to improve the situation. In fact the solution proposed by Amardeep has a performance that is lower than the previous scheme. Fetching several packets would be nice to try out too, anyone knows how to do that?
That is probably not the cause of any perceived performance issue you are trying to address. Without seeing your code, I'll take a guess that what you're doing is: 1. recv a packet 2. Process a packet 3. repeat What you should be doing is: 1. use one thread to recv packets with a pool of buffers and shove the received buffer pointers into a queue. 2. use another slightly lower priority thread to pull items from the queue and process them. This would greatly improve your system's ability to digest the data and miss fewer datagrams.
3,005,183
3,005,223
Windows DDK development with MinGW?
Is it possible to develop a Windows driver (specifically a PDF-like printer driver that displays the data on-screen instead of actually printing) without using Visual Studio? I'm thinking of using free C++ tools such as MinGW/gcc.
Both the Windows SDK and the Windows DDK come with the Visual C++ compiler. You don't need Visual Studio for this, though you may have some success with the free Express editions. I'd prefer this over MinGW anytime.
3,005,269
3,005,284
How can I concatenate two C++ maps
How can I concatenate the following two maps? map<string, map<string,string>> map1; map<string, map<string,string>> map2; I just want to add map2 to map1 and keep all elements already in map1, i.e., add map2 at the end of map1. I've tried map1.insert(map2.begin(), map2.end()), but it does not work since it overwrites old elements in map1.
The question contradicts with the concept of a map. If you insert a value in a map, you expect it to be at 'the proper place', depending on it's key. This implies there is only one entry for each key. Instead, you could use a vector< pair< mymap::key, myamap::value > > and fill it with the entries of the first resp. the second map. map< string, int > map1, map2; ... fill the maps vector< pair<string, int> > concatted; concatted.insert( map1.begin(), map1.end() ); concatted.insert( map2.begin(), map2.end() );
3,005,527
3,005,581
Return an array of a known size in C++?
If I can pass in an array of a known size: void fn(int(*intArray)[4]) { (*intArray)[0] = 7; } why can't I return one: int intArray[4] = {0}; int(*)[4] fn() { return &intArray; } here, the ")" in "(*)" generates "syntax error : )".
The [4] goes after the function name, just like it goes after the variable name in a variable definition: int (*fn())[4] { return &intArray; } Since this is very obscure syntax, prone to be confusing to everybody who reads it, I would recommend to return the array as a simple int*, if you don't have any special reason why it has to be a pointer-to-array. You could also simplify the function definition with a typedef: typedef int intarray_t[4]; intarray_t* fn() { ... }
3,005,564
3,005,673
GCC recommendations and options for fastest code
I'm distributing a C++ program with a makefile for the Unix version, and I'm wondering what compiler options I should use to get the fastest possible code (it falls into the category of programs that can use all the computing power they can get and still come back for more), given that I don't know in advance what hardware, operating system or gcc version the user will have, and I want above all else to make sure it at least works correctly on every major Unix-like operating system. Thus far, I have g++ -O3 -Wno-write-strings, are there any other options I should add? On Windows, the Microsoft compiler has options for things like fast calling convention and link time code generation that are worth using, are there any equivalents on gcc? (I'm assuming it will default to 64-bit on a 64-bit platform, please correct me if that's not the case.)
Without knowing any specifics on your program it's hard to say. O3 covers most of the optimisations. The remaining options come "at a cost". If you can tolerate some random rounding and your code isn't dependent on IEEE floating point standards then you can try -Ofast. This disregards standards compliance and can give you faster code. The remaining optimisations flags can only improve performance of certain programs, but can even be detrimental to others. Look at the available flags in the gcc documentation on optimisation flags and benchmark them. Another option is to enable C99 (-std=c99) and inline appropriate functions. This is a bit of an art, you shouldn't inline everything, but with a little work you can get your code to be faster (albeit at the cost of having a larger executable). If speed is really an issue I would suggest either going back to Microsoft's compiler, or to try Intel's. I've come to appreciate how slow some gcc compiled code can be, especially when it involves math.h. EDIT: Oh wait, you said C++? Then disregard my C99 paragraph, you can inline already :)
3,005,717
3,005,771
Getting value of LSB from Hex (C code)
I've got a code like this in C: unsigned char const data[ ] = {0x0a, 0x1d, 0xf0, 0x07}; I need to extract it such that the final value is: 0xa1df7 I have only been able to extract and get it working if the hex values that have at least 1 zero: unsigned char const data[ ] = {0x0a, 0xd0, 0xf0, 0x07}; using the code below: for(int i = 0; i < SIZE; ++i) { tmp = data[i]; if ( (data[i] <= 0x0F) && (((data[i] & 0x0F) == 0) || (data[i] & 0xF0) == 0)) // one of the hex is zero { tmp = ((tmp << 4) >> 4) << N[i]; std::cout << "foo: " << std::hex << tmp << ":" << std::endl; } else if ((data[i] >= 0x0F) && (((data[i] & 0x0F) == 0) || (data[i] & 0xF0) == 0) ) { tmp = (tmp >> 4) << N[i]; std::cout << "bar: " << std::hex << tmp << ":" << std::endl; } else { std::cout << "result: " << std::hex << result << ":" << std::endl; std::cout << "tmp << 8: " << std::hex << (tmp << 8)<< ":" << std::endl; result = result | (tmp << 8); std::cout << "result |= (tmp << 8): " << std::hex << result << ":" << std::endl; } result |= tmp; std::cout << "boo: " << std::hex << result << ":" << std::endl; } It seems the last else {...} block is troublesome for me. Any ideas? Thanks!
#include <stdio.h> #include <stdlib.h> unsigned char const data[ ] = {0x0a, 0x1d, 0xf0, 0x07}; int main(int argc, char*argv[]){ int i,r = 0; for(i=0; i<sizeof(data); i++){ if(data[i] & 0xf0) r = (r<<4) + (data[i]>>4); if(data[i] & 0x0f) r = (r<<4) + (data[i]&0x0f); } printf("%x\n",r); return 0; } outputs "a1df7"
3,005,975
3,006,047
ld returned 1 exit status
This is the code that i'm trying to run: #include <QApplication> #include <QPushButton> int main(int argc,char *argv[]) { QApplication app(argc,argv); return app.exec(); } And this is the error that i'm getting: :-1: error: collect2: ld returned 1 exit status
If you read the error message carefully, you will see the problem. ...ld.exe: cannot open output file ... The linker is trying to write the generated executable file (debug.exe) to disk, but is not allowed to (Permission denied). This is mostly due to the fact that the application you built is currently running. Close it and rebuild the application.
3,006,158
3,010,559
Resources in static library question
This isn't a duplicate of VC++ resources in a static library because it didn't help :) I have a static library with TWO .rc files in it's project. When I build my project using the Debug configuration, I retrieve the following error (MSVS2008): fatal error LNK1241: resource file res_yyy.res already specified Note, that this happens only in Debug and Release library builds without any troubles. The command line for Resources page in project configuration looks the same for every build: /fo"...(Path here)/Debug/project_name.res" /fo"...(Path here)/Release/project_name.res" and I can't understand what's the trouble. Any ideas? UPDATE I don't know why this happens, but when I turn "Use Link-Time Code Generation" option on the problem goes away. Could somebody explain why does this happen? I feel like MS-compiler is doing something really strange here. Thanks.
Solved this problem by setting EXACTLY ONE .res output file in the settings. I'm not actually sure why it was ok in Release mode though.
3,006,259
4,238,857
What time function do I need to use with pthread_cond_timedwait?
The pthread_cond_timedwait function needs an absolute time in a time timespec structure. What time function I'm suppose to use to obtain the absolute time. I saw a lot of example on the web and I found almost all time function used. (ftime, clock, gettimeofday, clock_gettime (with all possible CLOCK_...). The pthread_cond_timedwait uses an absolute time. Will this waiting time affected by changing the time of the machine? Also if I get the absolute time with one of the time function, if the time of the machine change between the get and the addition of the delta time this will affect the wait time? Is there a possibility to wait for an event with a relative time instead?
The function to use is clock_gettime() with the clock id of the condition variable. This clock id is CLOCK_REALTIME by default but can be changed (such as to CLOCK_MONOTONIC) by initializing the condition variable with a pthread_condattr_t on which pthread_condattr_setclock() has been called. Using time() is not a good idea because this is not guaranteed to equal tv_sec of a clock_gettime(CLOCK_REALTIME). In some cases this can cause your program to busy-wait for time() to reach the second that was already reached by clock_gettime(CLOCK_REALTIME) a short while ago.
3,006,413
3,006,486
Implementing operator< in C++
I have a class with a few numeric fields such as: class Class1 { int a; int b; int c; public: // constructor and so on... bool operator<(const Class1& other) const; }; I need to use objects of this class as a key in an std::map. I therefore implement operator<. What is the simplest implementation of operator< to use here? EDIT: The meaning of < can be assumed so as to guarantee uniqueness as long as any of the fields are unequal. EDIT 2: A simplistic implementation: bool Class1::operator<(const Class1& other) const { if(a < other.a) return true; if(a > other.a) return false; if(b < other.b) return true; if(b > other.b) return false; if(c < other.c) return true; if(c > other.c) return false; return false; } The whole reason behind this post is just that I found the above implementation too verbose. There ought to be something simpler.
It depends on if the ordering is important to you in any way. If not, you could just do this: bool operator<(const Class1& other) const { if(a == other.a) { if(b == other.b) { return c < other.c; } else { return b < other.b; } } else { return a < other.a; } }
3,006,438
10,466,773
Is there an online name demangler for C++?
I'm getting a fairly long and confusing link error, and would love it if I could just paste it into some textbox on some website and have the names un-mangled for me. Does anyone know of such a service?
I have created such an online serivice: https://demangler.com This is a gcc c++ symbol demangler. You just copy a stack trace, or the output of nm into a text box, and it will return the output with the names demangled. @Update: It now demangles MSVC and Java symbols also.
3,006,559
3,010,649
IOCTL_MOUNTMGR_QUERY_POINTS
when i include #include to use the IOCTL_MOUNTMGR_QUERY_POINTS i get the below error fatal error C1083: Cannot open include file: Mountmgr.h: No such file or directory How can i solve this error. Please guide me
If you need only IOCTL_MOUNTMGR_QUERY_POINTS definition it is following: #define MOUNTMGRCONTROLTYPE 0x0000006D // 'm' #define IOCTL_MOUNTMGR_QUERY_POINTS CTL_CODE(MOUNTMGRCONTROLTYPE, 2, METHOD_BUFFERED, FILE_ANY_ACCESS) all other constants are defined in WinIoCtl.h file which you find in Windows SDK installed together with Visual Studio. If you want full mountmgr.h file you will find it in the directory C:\WinDDK\7600.16385.1\inc\ddk after installation of Windows DDK (see suggestion of Hans Passant).
3,006,650
3,006,680
Expected class name before ',' or ';'
I am getting an "Expected class-name before , or ; and I dont quite get how to fix it. Here is where the error is: class FXHost : public CPLAT::CP_Application, public CPLAT::CP_M_Listener { The file is FXHost.h and CPLAT:: is obviously a namespace where CP_Application and CP_M_Listener are. I dont see why this would be wrong. This code ran fine in Metrowerks (without the CPLAT::) but in XCode CPLAT is needed due to the way the code was written by the previous developer. Can anyone shed some light on this error? UPDATE: Here is a sample of the CP_Application class template <class DOC_POLICY, class PRINT_POLICY, class UNDO_POLICY> class CP_EXPORT CP_Application : public CP_Application_Imp { public: typedef DOC_POLICY DocPolicyType; typedef PRINT_POLICY PrintPolicyType; typedef UNDO_POLICY UndoPolicyType; CP_Application(); virtual ~CP_Application() throw();
It looks like the compiler hasn't seen the class declaration for the two parent classes. The first thing I would check are your include directives. Are you sure you're including header which defines the classes CP_Application and CP_M_Listener?
3,006,690
3,007,306
keyboard layout direction
I would like to detect the direction of the current typing (input) language. I may detect the language by means of "GetKeyboardLayout", but then I'll have to check if it equals to Arabic or Hebrew and so on, is there any way just to detect the direction, i.e. left to right or right to left. thanks! mike.
check out: http://www.siao2.com/2006/03/03/542963.aspx
3,006,766
3,006,806
How to use the vtable to determine class type
I was recently on an interview for a position where C/C++ is the primary language and during one question I was told that it's possible to use the vtable to determine which class in a hierarchy a base pointer actually stores. So if, for example you have class A { public: A() {} virtual ~A() {} virtual void method1() {} }; class B : public A { public: B() {} virtual ~B() {} virtual void method1() {} }; and you instantiate A * pFoo = new B(), is it indeed possible to use the vtable to determine whether pFoo contains a pointer to an instance of A or B?
This is obviously implementation dependent but, on most implementations, the in-memory representation of an object of class A or B will start with a pointer to the vtable. You can look at this vtable pointer, compare it to vtable pointers for objects that you know to be of class A or B, and determine the class of the object in that way. To illustrate (of course this is anything but good style): A *pFoo=new B(); // pointer to object of unknown class (either A or B) A a; // Object known to be of class A B b; // Object known to be of class B void *vptrA=*((void **)&a); // Pointer to vtable of class A void *vptrB=*((void **)&b); // Pointer to vtable of class B void *vptrFoo=*((void **)pFoo); // Pointer to vtable of unknown object if(vptrFoo==vptrA) printf("Class A\n"); else printf("Class B\n"); Important: This is only an illustration of how most implementations work; besides being implementation dependent, this technique breaks down in the presence of multiple inheritance. You should never do anything like this in production code; use RTTI instead.
3,006,815
3,013,342
Most efficient way to map one fileID to another
I am in the process of localizing a game. I have roughly 1% of the game assets (around 200 of 20k files) that need to be replaced per language with different assets, 1 to 1. I am mulling over the 'best' way to do this in a very RAM starved envirnoment. Here's my current list of ideas: Hash off the file IDs to convert at nearly constant time 1 to another. Advantage is speed. Disadvantage is this can be memory hungry and is not as memory efficient as other methods. Enter each file ID to be translated into a map. Log time lookups, but perhaps more memory efficient? I'm not as experienced with this as other solutions so I cannot say how well this will work. Enter each file ID as a pair into a vector, sort the vector when done, and bsearch off it. Log time lookups and perhaps more efficicent than the map? On any step, add a bit boolean table of kIsThisAssetTranslated[] on the front end to constant time bail early if the assets is unchanged. Just looking for some experience and opinions on which methods (or something I've missed) the community would consider. I'm leaning towards the hash as this will be called per file access, but as always, the question of Ram vs performance is an interesting one.
You can pre-calculate the FileIDs that you need to convert. Look up perfect hashes; this may be what you need. However, 2log(200) is only 8. The overhead of hashing is significant, even more so for perfect hashing. And remember that files are slow - 8 memory accesses for a binary search will take perhaps a microsecond, not even flash is that fast.
3,006,918
3,013,318
Is it safe to read global data from multiple threads?
The scenario is as follows: Create an instance of a class (std::map) and sore it as global variable. Spawn threads. Threads read and use the same global instance of the class (call methods, access members etc) All spawned threads quit Global class instance is destroyed No mutex used, no spawn thread modifies the global class instance. Is this OK? Thank You
Typically yes, but it's not a hard guarantee. The core problem is that you need a memory barrier to make sure that the first thread writes back all data from registers to memory. However, it is very likely that this will happen when you create the second thread.
3,007,250
3,007,266
Should I use Qt signal/slot mechanisms over traditional callbacks?
A senior developer in my team used traditional C-style callbacks in our Qt application instead of using Qt signal/slot mechanisms. My first reflex would be to replace his code and use Qt signal/slot instead. Is there any good reasons to use callbacks in a Qt application/library? Thanks.
I think the better approach would be to embrace the framework you are using and use signal/slots. That being said, if the code in question works, and is not ugly or causing problems, then you may be best to leave it alone. Consulting the Signal/Slot documentation describes why the Signal/Slot approach is better: Callbacks have two fundamental flaws: Firstly, they are not type-safe. We can never be certain that the processing function will call the callback with the correct arguments. Secondly, the callback is strongly coupled to the processing function since the processing function must know which callback to call. Do be aware of the following though: Compared to callbacks, signals and slots are slightly slower because of the increased flexibility they provide The speed probably doesn't matter for most cases, but there may be some extreme cases of repeated calling that makes a difference.
3,007,251
3,007,677
Template operator linker error
I have a linker error I've reduced to a simple example. The build output is: debug/main.o: In function main': C:\Users\Dani\Documents\Projects\Test1/main.cpp:5: undefined reference tolog& log::operator<< (char const (&) [6])' collect2: ld returned 1 exit status It looks like the linker ignores the definition in log.cpp. I also cant put the definition in log.h because I include the file alot of times and it complains about redefinitions. main.cpp: #include "log.h" int main() { log() << "hello"; return 0; } log.h: #ifndef LOG_H #define LOG_H class log { public: log(); template<typename T> log &operator <<(T &t); }; #endif // LOG_H log.cpp: #include "log.h" #include <iostream> log::log() { } template<typename T> log &log::operator <<(T &t) { std::cout << t << std::endl; return *this; }
I guess this is your first use of templates, so I'll try to be didactic. You can think of template as some kind of type-aware macros. This type awareness is of course not to be neglected, since it grants type safety for free. This does mean however than template functions or classes are NOT functions or classes: they are model that will be used to generate functions or classes. For example: template <class T> void foo(T t) { std::cout << t << "\n"; } This is a template function, it allows me to define something once and apply it to many different types. int i; foo(i); // [1] This causes the instantiation of the template. Basically, it means that a function is created according to the model, but replacing all occurrences of T by int. double d; foo(d); // Another instantiation, this time with `T` replaced by `double` foo(d); // foo<double>() already exists, it's reused Now, this idea of model is very important. If the definition of the model is not present in the header file, then the compiler does not know how to define the method. So, you have 2 solutions here: Define it in the header Explicitly instantiate it The 2 have different uses. (1) is the classic way. It's easier because you don't restrict the user to a subset of the types. However it does mean that the user depends on the implementation (change it, she recompiles, and you need to pull the dependencies in the header) (2) is less often used. For full compliance with the standard it requires: That you declare the specialization in the header (template <> void foo<int>();) so as to let the compiler know it exists That you fully define it in one of the translation units linked The main advantage is that, like classic functions, you isolate the client from the implementation. gcc is quite lenient because you can forgo the declaration and it should work. I should also note that it is possible to define a method twice, with different implementations. This is of course an error, as it is in direct violation of the ODR: One Definition Rule. However most linkers don't report it because it's quite common to have one implementation per object, and they just pick the first and assume the others will be equivalent (it's a special rule for templates). So if you do want to use explicit instantiation, take great care to only define it once.
3,007,393
3,007,421
which is better: a lying copy constructor or a non-standard one?
I have a C++ class that contains a non-copyable handle. The class, however, must have a copy constructor. So, I've implemented one that transfers ownership of the handle to the new object (as below), class Foo { public: Foo() : h_( INVALID_HANDLE_VALUE ) { }; // transfer the handle to the new instance Foo( const Foo& other ) : h_( other.Detach() ) { }; ~Foo() { if( INVALID_HANDLE_VALUE != h_ ) CloseHandle( h_ ); }; // other interesting functions... private: /// disallow assignment const Foo& operator=( const Foo& ); HANDLE Detach() const { HANDLE h = h_; h_ = INVALID_HANDLE_VALUE; return h; }; /// a non-copyable handle mutable HANDLE h_; }; // class Foo My problem is that the standard copy constructor takes a const-reference and I'm modifying that reference. So, I'd like to know which is better (and why): a non-standard copy constructor: Foo( Foo& other ); a copy-constructor that 'lies': Foo( const Foo& other ); Edit: DuplicateHandle() only works on specific types of handles. This is not one of them. This handle cannot be duplicated, copied, or cloned. Several people have pointed out that I was mistaken in suggesting it is a non-standard copy constructor and that std::auto_ptr does this. I think that's probably the way to go. But, I end up with warnings every time I use the class when I make the copy ctor take a non-const value. For example: namespace detail { class Foo { ... }; }; class Buzz { public: typedef detail::Foo Fuzz; Fuzz bar() const { return Fuzz(); }; // warning here }; warning C4239: nonstandard extension used : 'argument' : conversion from 'Foo' to 'Foo &' 1> A non-const reference may only be bound to an lvalue; copy constructor takes a reference to non-const Can anybody suggest what I should do about them? Edit2: Everybody seems to be steering me towards std::auto_ptr<>'s method of doing things. So, I looked there and it uses an intermediate structure to get around the issue I described in the first edit. This is the solution I came up with. class Foo; struct Foo_ref { explicit Foo_ref( Foo& other ) : ref_( other ) {}; Foo& ref_; private: const Foo_ref& operator=( const Foo_ref& ); }; // struct Foo_ref class Foo { public: Foo() : h_( INVALID_HANDLE_VALUE ) { }; // transfer the handle to the new instance Foo( Foo_ref other ) : h_( other.ref_.Detach() ) { }; ~Foo() { if( INVALID_HANDLE_VALUE != h_ ) CloseHandle( h_ ); }; operator Foo_ref() { Foo_ref tmp( *this ); return tmp; }; // other interesting functions... private: /// disallow assignment const Foo& operator=( const Foo& ); HANDLE Detach() { HANDLE h = h_; h_ = INVALID_HANDLE_VALUE; return h; }; /// a non-copyable handle HANDLE h_; }; // class Foo It compiles cleanly on warning level 4 and seems to work. Please, let me know if it is somehow more irresponsible than my original post.
The first option has a well established precedent in the form of auto_ptr: http://www.cplusplus.com/reference/std/memory/auto_ptr/auto_ptr/ auto_ptr gives up its pointer and is reset when it is copied. The standard that ensures that a function doesn't change arguments passed as const is much stronger than the copy-ctor standard which is really not very formal. Also, manipulating a const value by casting away its constness is undefined behavior according to the standard. You can do it if either you are certain that the reference refers to a non-const object or you are passing a const object to a (const-incorrect) function that will not modify the value.
3,007,422
3,007,890
How to optimize this simple function which translates input bits into words?
I have written a function which reads an input buffer of bytes and produces an output buffer of words where every word can be either 0x0081 for each ON bit of the input buffer or 0x007F for each OFF bit. The length of the input buffer is given. Both arrays have enough physical place. I also have about 2Kbyte free RAM which I can use for lookup tables or so. Now, I found that this function is my bottleneck in a real time application. It will be called very frequently. Can you please suggest a way how to optimize this function? I see one possibility could be to use only one buffer and do in-place substitution. void inline BitsToWords(int8 *pc_BufIn, int16 *pw_BufOut, int32 BufInLen) { int32 i,j,z=0; for(i=0; i<BufInLen; i++) { for(j=0; j<8; j++, z++) { pw_BufOut[z] = ( ((pc_BufIn[i] >> (7-j))&0x01) == 1? 0x0081: 0x007f ); } } } Please do not offer any library-, compiler specific or CPU/Hardware specific optimization, because it is a multi-platform project.
I also have about 2Kbyte free RAM which I can use for lookup tables Your lookup tables can placed in a const array at compile time, so it could be in ROM - does this give you room for the straightforward 4KB table? If you can afford 4KB of ROM space, the only problem is building the table as an initialized array in a .c file - but that only has to be done once, and you can write a script to do it (which may help ensure it's correct and may also help if you decide that the table needs to change for some reason in the future). You'd have to profile to ensure that the copy from ROM to the destination array is actually faster than calculating what needs to go into the destination - I wouldn't be surprised if something along the lines of: /* untested code - please forgive any bonehead errors */ void inline BitsToWords(int8 *pc_BufIn, int16 *pw_BufOut, int32 BufInLen) { while (BufInLen--) { unsigned int tmp = *pc_BufIn++; *pw_BufOut++ = (tmp & 0x80) ? 0x0081 : 0x007f; *pw_BufOut++ = (tmp & 0x40) ? 0x0081 : 0x007f; *pw_BufOut++ = (tmp & 0x20) ? 0x0081 : 0x007f; *pw_BufOut++ = (tmp & 0x10) ? 0x0081 : 0x007f; *pw_BufOut++ = (tmp & 0x08) ? 0x0081 : 0x007f; *pw_BufOut++ = (tmp & 0x04) ? 0x0081 : 0x007f; *pw_BufOut++ = (tmp & 0x02) ? 0x0081 : 0x007f; *pw_BufOut++ = (tmp & 0x01) ? 0x0081 : 0x007f; } } ends up being faster. I'd expect that an optimized build of that function would have everything in registers or encoded into the instructions except for a single read of each input byte and a single write of each output word. Or pretty close to that. You might be able to further optimize by acting on more than one input byte at a time, but then you have to deal with alignment issues and how to handle input buffers that aren't a multiple of the chunk size you're dealing with. Those aren't problems that are too hard to deal with, but they do complicate things, and it's unclear what kind of improvement you might be able to expect.
3,007,559
3,008,262
How to set the correct Visual Studio version as JIT debugger?
I have VS2003, VS2005 and VS2008 installed on my machine. The C++ application is compiled with VS2005 but when it crashs and i select debug the Just-In-Time Debugging dialog comes up and only offers me "New instance of Visual Studio .NET 2003". Debugging a 2005 compiled program with 2003 is not possible. If i attach the process to VS2005 then it works well, but this is very inconvenient. How do i set .NET 2005 vor JIT debugging?
Okay i found it. BTW installing VS2003 after VS2005 kills all others JIT debuggers, this was the reason for the problem. From Visual Studio menu , select "Tools->Options->Debugging->Just-In-Time" and then check "Managed", "Native" and "Script".
3,007,724
3,008,304
Determining CPU usage in WinCE
I want to be able to get the current % CPU usage in a C++ program running under Wince. I found this link that states where the source code is but I cannot find it in my platform builder installation - I expect this is because it isn't the Windows Automotive platform. Does anyone know where I can find this source code or (even better) know how I can get this information directly? i.e. what DLL / function calls to make etc.
Since GetProcessTimes doesn't exist in CE, you have to calculate this. You have to start with the toolhelp APIs to enumerate the processes and the threads in the processes. You then call GetThreadTimes for each thread and add all that up. Bear in mind that the act of calculating this info will affect the CPU utilization.
3,007,728
3,025,835
rvalues and temporary objects in the FCD
It took me quite some time to understand the difference between an rvalue and a temporary object. But now the final committee draft states on page 75: An rvalue [...] is an xvalue, a temporary object or subobject thereof, or a value that is not associated with an object. I can't believe my eyes. This must be an error, right? To clarify, here is how I understand the terms: #include <string> void foo(std::string&& str) { std::cout << str << std::endl; } int main() { foo(std::string("hello")); } In this program, there are two expressions that denote the same temporary object: the prvalue std::string("hello") and the lvalue str. Expressions are not objects, but their evaluation might yield one. Specifically, the evaluation of a prvalue yields a temporary object, but a prvalue IS NOT a temporary object. Does anyone agree with me or have I gone insane? :)
Yes, i agree with you. This should be fixed in my opinion, and several people i deeply pay respect to have risen the exact same question about this.
3,007,971
3,009,812
SQLite problem with some parameterized queries
I am having some trouble using SQLite and parameterized queries with a few tables. I have noticed some queries using the SELECT * FROM Table WHERE row=? are returning 1 row when there should be more rows returned. If I change the parameterized query to SELECT * FROM Table WHERE row='row' then the correct number of rows is returned. Does anyone know why sqlite3_step would return only 1 row when using a parameterized query vs. using the same query in a traditional non-parameterized way? I am using a very thin C++ wrapper around SQLite3. I suspect there could be a problem with the wrapper, but this problem only exists on a few tables. It makes me wonder if there is something wrong with the way those tables are setup. Any advice is appreciated. EDIT: Here is the schema of the simplest table showing the problem: CREATE TABLE RefNums (Key TEXT PRIMARY KEY, TripNumber TEXT, RefDesc TEXT, RefNum TEXT); I am using the query: SELECT * FROM RefNums WHERE TripNumber=? and using sqlite3_bind_text. That returns SQLITE_ROW on the first call to sqlite3_step and returns SQLITE_DONE on the second call to sqlite3_step. There should be 2 rows. I have verified the rows exist using SQLDataBrowser. If I change the query to SELECT * FROM RefNumbers WHERE TripNumber='012345'; then it works as expected.
I have solved the problem. This code is running on Windows CE/Windows Mobile platform where virtually all system API are Unicode-only. I am using the ATL 7.0 conversion utility CT2A to convert between T (Unicode) to A (Ascii) before passing the variable to SQLite via the sqlite3_bind_xxx functions. This appears to be the source of the problem because the same program works correctly if I hard-code the query instead of using parameterized queries. I modified the sqlite3_bind_text wrapper to use SQLITE_TRANSIENT (SQL makes a copy of the data) instead of SQLITE_STATIC (SQLite assumes the pointer is fixed). The program now works correctly. There appears to be some problems with the lifetime of the temporary CT2A object and the lifetime of the sqlite3_stmt object.
3,008,002
3,008,031
Access specifier's and classes and objects?
Alright, im trying to understand this, so a class is simply creating a template for an object. class Bow { int arrows; }; and an object is simply creating a specific item using the class template. Bow::Bow(arrows) { arrows = 20; } also another question, public specifiers are used to make data members avaible in objects and private specifiers are used to make data memebers only avaialble inside the class?
The description you gave is mostly correct but your examples don't show what you are describing. A class describes a set of data members and member functions which can be called on those data members: class Bow { public: //Constructor Bow::Bow() { arrows = 20; } Bow::Bow(int a) { arrows = a; } //member functions (in this case also called accessors/modifiers) void getArrows(int a) const { return arrows; } void setArrows(int a) { arrows = a; } protected: int arrows; }; And an object of a class is simply an instance of that class. //b and d are objects of the class Bow. Bow b(3);//The constructor is automatically called here passing in 3 Bow d(4);//The constructor is automatically called here passing in 4 Bow e;//The constructor with no parameters is called and hence arrows = 20 Note: I purposely avoided the use of the word template that you used because it's used for something entirely different in C++ than what you meant. To understand public/private/protected specifiers: public: means that objects of the class can use the members directly. protected: means that objects of the class cannot use the members directly. Derived classes that are based on that class can use the members. private: means that objects of the class cannot use the members directly. Derived classes that are based on that class cannot use the members either. So in the above example: Bow b(3); b.arrows = 10;//Compiling error arrows is not public so can't be accessed from an object
3,008,094
3,008,136
C++: vector to stringstream
I want to know if it is possible to transform a std::vector to a std::stringstream using generic programming and how can one accomplish such a thing?
Adapting Brian Neal's comment, the following will only work if the << operator is defined for the object in the std::vector (in this example, std::string). #include <iostream> #include <sstream> #include <vector> #include <string> #include <iterator> // Dummy std::vector of strings std::vector<std::string> sentence; sentence.push_back("aa"); sentence.push_back("ab"); // Required std::stringstream object std::stringstream ss; // Populate std::copy(sentence.begin(), sentence.end(),std::ostream_iterator<std::string>(ss,"\n")); // Display std::cout<<ss.str()<<std::endl;
3,008,270
3,008,428
Declaration for object for which creation is wrapped in macro
The following macro is defined in our code: #define MSGMacro(obj, arg) MyPaymentClass obj(arg) Where MSGMacro is used to creates the object of type MyPaymentClass using code like MSGMacro(Card, 1); MSGMacro(Cash, 2); ---- ---- //removed unwanted things to keep question cleaner. All the above code is in one cpp file, Now the problem is how we can expose these two objects of MyPaymentClass to other units in my project? i.e. I want to use Card and Cash in other CPP files. Please suggest how I can give the declaration for the same in some header file?
Create another macro to declare these variables: /* example.h */ #define MSGMacroDeclare(obj) extern MyPaymentClass obj; MSGMacroDeclare(Card); MSGMacroDeclare(Cash); ... /* example.cpp */ #define MSGMacroDefine(obj, arg) extern MyPaymentClass obj(arg); MSGMacroDefine(Card, 1); MSGMacroDefine(Cash, 2); ... Eventually if you want the same file to booth declare and define them, you can use sth like this: /* example.h */ #ifndef MSGMacro #define MSGMacro(obj, arg) extern MyPaymentClass obj #endif MSGMacro(Card, 1); MSGMacro(Cash, 2); ... /* example.cpp */ #define MSGMacro(obj, arg) extern MyPaymentClass obj(arg) #include "example.h" but this makes sense only when there are many, many, many of these (many globals? hmmm...) and the list is being changed frequently, generally this is unusual
3,008,293
3,008,319
Clean Eclipse Index, it is out of sync with code
I'm using Eclipse with C++ code via linked resources on Linux. The code analysis index seems to be corrupted (Goto definition lands the cursor close to, but not on, the definition) Refreshing resources doesn't fix it, neither does restarting Eclipse. Is there a way to flush the index and rebuild it?
Right-click on your project, go under the Index submenu, and choose either "Rebuild," "Update with modified files," or "Freshen all files." I don't know the difference between those three options, but one of "Update with modified files" or "Freshen all files" usually fixes it for me. Also, I'm sure you've already done this, but make sure that you're running the latest version of the Eclipse CDT. Current versions seem to have much more reliable indexing than previous versions.
3,008,413
3,021,785
Conditional type definitions
I'm sure that boost has some functions for doing this, but I don't know the relevant libraries well enough. I have a template class, which is pretty basic, except for one twist where I need to define a conditional type. Here is the psuedo code for what I want struct PlaceHolder {}; template <typename T> class C{ typedef (T == PlaceHolder ? void : T) usefulType; }; How do I write that type conditional?
Also with the new standard: typedef typename std::conditional<std::is_same<T, PlaceHolder>::value, void, T>::type usefulType
3,008,521
3,008,905
How to safely operate on parameters in threads, using C++ & Pthreads?
I'm having some trouble with a program using pthreads, where occassional crashes occur, that could be related to how the threads operate on data So I have some basic questions about how to program using threads, and memory layout: Assume that a public class function performs some operations on some strings, and returns the result as a string. The prototype of the function could be like this: std::string SomeClass::somefunc(const std::string &strOne, const std::string &strTwo) { //Error checking of strings have been omitted std::string result = strOne.substr(0,5) + strTwo.substr(0,5); return result; } Is it correct to assume that strings, being dynamic, are stored on the heap, but that a reference to the string is allocated on the stack at runtime? Stack: [Some mem addr] pointer address to where the string is on the heap Heap: [Some mem addr] memory allocated for the initial string which may grow or shrink To make the function thread safe, the function is extended with the following mutex (which is declared as private in the "SomeClass") locking: std::string SomeClass::somefunc(const std::string &strOne, const std::string &strTwo) { pthread_mutex_lock(&someclasslock); //Error checking of strings have been omitted std::string result = strOne.substr(0,5) + strTwo.substr(0,5); pthread_mutex_unlock(&someclasslock); return result; } Is this a safe way of locking down the operations being done on the strings (all three), or could a thread be stopped by the scheduler in the following cases, which I'd assume would mess up the intended logic: a. Right after the function is called, and the parameters: strOne & strTwo have been set in the two reference pointers that the function has on the stack, the scheduler takes away processing time for the thread and lets a new thread in, which overwrites the reference pointers to the function, which then again gets stopped by the scheduler, letting the first thread back in? b. Can the same occur with the "result" string: the first string builds the result, unlocks the mutex, but before returning the scheduler lets in another thread which performs all of it's work, overwriting the result etc. Or are the reference parameters / result string being pushed onto the stack while another thread is doing performing it's task? Is the safe / correct way of doing this in threads, and "returning" a result, to pass a reference to a string that will be filled with the result instead: void SomeClass::somefunc(const std::string &strOne, const std::string &strTwo, std::string result) { pthread_mutex_lock(&someclasslock); //Error checking of strings have been omitted result = strOne.substr(0,5) + strTwo.substr(0,5); pthread_mutex_unlock(&someclasslock); } The intended logic is that several objects of the "SomeClass" class creates new threads and passes objects of themselves as parameters, and then calls the function: "someFunc": int SomeClass::startNewThread() { pthread_attr_t attr; pthread_t pThreadID; if(pthread_attr_init(&attr) != 0) return -1; if(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) return -2; if(pthread_create(&pThreadID, &attr, proxyThreadFunc, this) != 0) return -3; if(pthread_attr_destroy(&attr) != 0) return -4; return 0; } void* proxyThreadFunc(void* someClassObjPtr) { return static_cast<SomeClass*> (someClassObjPtr)->somefunc("long string","long string"); } Sorry for the long description. But I hope the questions and intended purpose is clear, if not let me know and I'll elaborate. Best regards. Chris
1 a/b: No, neither one can happen. The parameters to functions and their return values are located on the stack and each thread has his own stack. However, other things can certainly go wrong: one of the string operations could throw an exception, preventing someclasslock from ever getting unlocked and your application will hang. assuming that the strings that are passed into the function are shared between threads (if they are not, the lock is unnecessary), another thread could call the destructor on them just after the function is called and before the lock is acquired. In that case the string operation would lead to undefined behavior. I recommend that you create a new SomeClass object for each thread. In that case, all the members of these objects are accessed only by one thread and don't need to be protected by a lock. Drawback would be that you can't access them from your main thread anymore after starting the new thread. If thats required, then you do have to protect them with a lock (the lock would be a member of that class too). Having said that, the function somefunc does not seem to affect any members of the object at all, and therefore doesn't need protection. Think about the granularity of sharing between threads, it looks to me that the protective lock should be in the function that is calling somefunc.
3,008,571
3,009,891
Template specialization to use default type if class member typedef does not exist
I'm trying to write code that uses a member typedef of a template argument, but want to supply a default type if the template argument does not have that typedef. A simplified example I've tried is this: struct DefaultType { DefaultType() { printf("Default "); } }; struct NonDefaultType { NonDefaultType() { printf("NonDefault "); } }; struct A {}; struct B { typedef NonDefaultType Type; }; template<typename T, typename Enable = void> struct Get_Type { typedef DefaultType Type; }; template<typename T> struct Get_Type< T, typename T::Type > { typedef typename T::Type Type; }; int main() { Get_Type<A>::Type test1; Get_Type<B>::Type test2; } I would expect this to print "Default NonDefault", but instead it prints "Default Default". My expectation is that the second line in main() should match the specialized version of Get_Type, because B::Type exists. However, this does not happen. Can anyone explain what's going on here and how to fix it, or another way to accomplish the same goal? Thank you. Edit: Georg gave an alternate method, but I'm still curious about why this doesn't work. According the the boost enable_if docs, a way to specialize a template for different types is like so: template <class T, class Enable = void> class A { ... }; template <class T> class A<T, typename enable_if<is_integral<T> >::type> { ... }; template <class T> class A<T, typename enable_if<is_float<T> >::type> { ... }; This works because enable_if< true > has type as a typedef, but enable_if< false > does not. I don't understand how this is different than my version, where instead of using enable_if I'm just using T::Type directly. If T::Type exists wouldn't that be the same as enable_if< true >::type in the above example and cause the specialization to be chosen? And if T::Type doesn't exist, wouldn't that be the same as enable_if< false >::type not existing and causing the default version to be chosen in the above example?
To answer your addition - your specialization argument passes the member typedef and expects it to yield void as type. There is nothing magic about this - it just uses a default argument. Let's see how it works. If you say Get_Type<Foo>::type, the compiler uses the default argument of Enable, which is void, and the type name becomes Get_Type<Foo, void>::type. Now, the compiler checks whether any partial specialization matches. Your partial specialization's argument list <T, typename T::Type> is deduced from the original argument list <Foo, void>. This will deduce T to Foo and afterwards substitutes that Foo into the second argument of the specialization, yielding a final result of <Foo, NonDefaultType> for your partial specialization. That doesn't, however, match the original argument list <Foo, void> at all! You need a way to yield the void type, as in the following: template<typename T> struct tovoid { typedef void type; }; template<typename T, typename Enable = void> struct Get_Type { typedef DefaultType Type; }; template<typename T> struct Get_Type< T, typename tovoid<typename T::Type>::type > { typedef typename T::Type Type; }; Now this will work like you expect. Using MPL, you can use always instead of tovoid typename apply< always<void>, typename T::type >::type
3,008,690
3,008,730
User Defined Conversions in C++
Recently, I was browsing through my copy of the C++ Pocket Reference from O'Reilly Media, and I was surprised when I came across a brief section and example regarding user-defined conversion for user-defined types: #include <iostream> class account { private: double balance; public: account (double b) { balance = b; } operator double (void) { return balance; } }; int main (void) { account acc(100.0); double balance = acc; std::cout << balance << std::endl; return 0; } I've been programming in C++ for awhile, and this is the first time I've ever seen this sort of operator overloading. The book's description of this subject is somewhat brief, leaving me with a few unanswered questions about this feature: Is this a particularly obscure feature? As I said, I've been programming in C++ for awhile and this is the first time I've ever come across this. I haven't had much luck finding more in-depth material regarding this. Is this relatively portable? (I'm compiling on GCC 4.1) Can user-defined conversions to user defined types be done? e.g. operator std::string () { /* code */ }
Is this a particularly obscure feature? Yes, conversion operators aren't used very often. The places I've seen them are for user-defined types that can degrade to built-in ones. Things like a fixed-precision number class that supports converting to/from atomic number types. Is this relatively portable? As far as I know, it is. They've been in the standard forever. Can user-defined conversions to user defined types be done? Yes, that's one of the features of constructors. A constructor that takes a single argument effectively creates a conversion operator from the argument type to your class's type. For example, a class like this: class Foo { public: Foo(int n) { // do stuff... } } Let's you do: Foo f = 123; If you've used std::string before, odds are you've used this feature without realizing it. (As an aside, if you want to prevent this behavior, declare any single-argument constructors using explicit.)
3,008,874
3,009,317
Reverse P/Invoke tutorial?
I've a old C/C++ class that i want to refactor and access from .net using PInvoke All P/Invoke tutorials refers to call win32 api but i haven't found anything to code the other side Any tips/ideas ? my c/c++ experience is pretty rusty :( UPDATE - this is for wrapping existing C/C++ code so it can called from .net using P/Invoke How do i define the C function so from .net i can get the value using ref/out strings
Here you find help C++ Interop Walkthrough: Porting an Existing Native C++ Application to Interoperate with .NET Framework Components Use Our ManWrap Library to Get the Best of .NET in Native C++ Code How to call C++ code from Managed, and vice versa (Interop)
3,008,878
3,008,996
Gradient algorithm produces little white dots
I'm working on an algorithm to generate point to point linear gradients. I have a rough proof of concept implementation done: GLuint OGLENGINEFUNCTIONS::CreateGradient( std::vector<ARGBCOLORF> &input,POINTFLOAT start, POINTFLOAT end, int width, int height,bool radial ) { std::vector<POINT> pol; std::vector<GLubyte> pdata(width * height * 4); std::vector<POINTFLOAT> linearpts; std::vector<float> lookup; float distance = GetDistance(start,end); RoundNumber(distance); POINTFLOAT temp; float incr = 1 / (distance + 1); for(int l = 0; l < 100; l ++) { POINTFLOAT outA; POINTFLOAT OutB; float dirlen; float perplen; POINTFLOAT dir; POINTFLOAT ndir; POINTFLOAT perp; POINTFLOAT nperp; POINTFLOAT perpoffset; POINTFLOAT diroffset; dir.x = end.x - start.x; dir.y = end.y - start.y; dirlen = sqrt((dir.x * dir.x) + (dir.y * dir.y)); ndir.x = static_cast<float>(dir.x * 1.0 / dirlen); ndir.y = static_cast<float>(dir.y * 1.0 / dirlen); perp.x = dir.y; perp.y = -dir.x; perplen = sqrt((perp.x * perp.x) + (perp.y * perp.y)); nperp.x = static_cast<float>(perp.x * 1.0 / perplen); nperp.y = static_cast<float>(perp.y * 1.0 / perplen); perpoffset.x = static_cast<float>(nperp.x * l * 0.5); perpoffset.y = static_cast<float>(nperp.y * l * 0.5); diroffset.x = static_cast<float>(ndir.x * 0 * 0.5); diroffset.y = static_cast<float>(ndir.y * 0 * 0.5); outA.x = end.x + perpoffset.x + diroffset.x; outA.y = end.y + perpoffset.y + diroffset.y; OutB.x = start.x + perpoffset.x - diroffset.x; OutB.y = start.y + perpoffset.y - diroffset.y; for (float i = 0; i < 1; i += incr) { temp = GetLinearBezier(i,outA,OutB); RoundNumber(temp.x); RoundNumber(temp.y); linearpts.push_back(temp); lookup.push_back(i); } for (unsigned int j = 0; j < linearpts.size(); j++) { if(linearpts[j].x < width && linearpts[j].x >= 0 && linearpts[j].y < height && linearpts[j].y >=0) { pdata[linearpts[j].x * 4 * width + linearpts[j].y * 4 + 0] = (GLubyte) j; pdata[linearpts[j].x * 4 * width + linearpts[j].y * 4 + 1] = (GLubyte) j; pdata[linearpts[j].x * 4 * width + linearpts[j].y * 4 + 2] = (GLubyte) j; pdata[linearpts[j].x * 4 * width + linearpts[j].y * 4 + 3] = (GLubyte) 255; } } lookup.clear(); linearpts.clear(); } return CreateTexture(pdata,width,height); } It works as I would expect most of the time, but at certain angles it produces little white dots. I can't figure out what does this. This is what it looks like at most angles (good) http://img9.imageshack.us/img9/5922/goodgradient.png But once in a while it looks like this (bad): http://img155.imageshack.us/img155/760/badgradient.png What could be causing the white dots? Is there maybe also a better way to generate my gradients if no solution is possible for this? Thanks
I think you have a bug indexing into the pdata byte vector. Your x domain is [0, width) but when you multiply out the indices you're doing x * 4 * width. It should probably be x * 4 + y * 4 * width or x * 4 * height + y * 4 depending on whether you're data is arranged row or column major.
3,009,149
3,009,189
How to use a precompiled dynamic library in visual studio c++?
I want to use a precompiled library in my project. I have 3 folders: Include (.h files), Lib (with .lib files) and Bin (with .dll files and .pdb files). I've never used precompiled libraries before (I hope this is the right term. correct me if I'm wrong). I want to use this API. How to add all this stuff to my project? I use visual studio 2010 (cpp). Thanks.
It's quite easy. You just need to modify some properties: C++ / General / Additional Include Directories - add the path where the .h file lives Linker / General / Additional Library Directoreis - add the path where the .lib file lives Linker / Input / Additional Dependencies - add the full name of the .lib When you run, make sure the path where the .dll lives is part of PATH.
3,009,210
3,009,348
ebp + 6 instead of +8 in a JIT compiler
I'm implementing a simplistic JIT compiler in a VM I'm writing for fun (mostly to learn more about language design) and I'm getting some weird behavior, maybe someone can tell me why. First I define a JIT "prototype" both for C and C++: #ifdef __cplusplus typedef void* (*_JIT_METHOD) (...); #else typedef (*_JIT_METHOD) (); #endif I have a compile() function that will compile stuff into ASM and stick it somewhere in memory: void* compile (void* something) { // grab some memory unsigned char* buffer = (unsigned char*) malloc (1024); // xor eax, eax // inc eax // inc eax // inc eax // ret -> eax should be 3 /* WORKS! buffer[0] = 0x67; buffer[1] = 0x31; buffer[2] = 0xC0; buffer[3] = 0x67; buffer[4] = 0x40; buffer[5] = 0x67; buffer[6] = 0x40; buffer[7] = 0x67; buffer[8] = 0x40; buffer[9] = 0xC3; */ // xor eax, eax // mov eax, 9 // ret 4 -> eax should be 9 /* WORKS! buffer[0] = 0x67; buffer[1] = 0x31; buffer[2] = 0xC0; buffer[3] = 0x67; buffer[4] = 0xB8; buffer[5] = 0x09; buffer[6] = 0x00; buffer[7] = 0x00; buffer[8] = 0x00; buffer[9] = 0xC3; */ // push ebp // mov ebp, esp // mov eax, [ebp + 6] ; wtf? shouldn't this be [ebp + 8]!? // mov esp, ebp // pop ebp // ret -> eax should be the first value sent to the function /* WORKS! */ buffer[0] = 0x66; buffer[1] = 0x55; buffer[2] = 0x66; buffer[3] = 0x89; buffer[4] = 0xE5; buffer[5] = 0x66; buffer[6] = 0x66; buffer[7] = 0x8B; buffer[8] = 0x45; buffer[9] = 0x06; buffer[10] = 0x66; buffer[11] = 0x89; buffer[12] = 0xEC; buffer[13] = 0x66; buffer[14] = 0x5D; buffer[15] = 0xC3; // mov eax, 5 // add eax, ecx // ret -> eax should be 50 /* WORKS! buffer[0] = 0x67; buffer[1] = 0xB8; buffer[2] = 0x05; buffer[3] = 0x00; buffer[4] = 0x00; buffer[5] = 0x00; buffer[6] = 0x66; buffer[7] = 0x01; buffer[8] = 0xC8; buffer[9] = 0xC3; */ return buffer; } And finally I have the main chunk of the program: int main (int argc, char **args) { DWORD oldProtect = (DWORD) NULL; int i = 667, j = 1, k = 5, l = 0; // generate some arbitrary function _JIT_METHOD someFunc = (_JIT_METHOD) compile(NULL); // windows only #if defined _WIN64 || defined _WIN32 // set memory permissions and flush CPU code cache VirtualProtect(someFunc,1024,PAGE_EXECUTE_READWRITE, &oldProtect); FlushInstructionCache(GetCurrentProcess(), someFunc, 1024); #endif // this asm just for some debugging/testing purposes __asm mov ecx, i // run compiled function (from wherever *someFunc is pointing to) l = (int)someFunc(i, k); // did it work? printf("result: %d", l); free (someFunc); _getch(); return 0; } As you can see, the compile() function has a couple of tests I ran to make sure I get expected results, and pretty much everything works but I have a question... On most tutorials or documentation resources, to get the first value of a function passed (in the case of ints) you do [ebp+8], the second [ebp+12] and so forth. For some reason, I have to do [ebp+6] then [ebp+10] and so forth. Could anyone tell me why?
Your opcodes look suspicious: they're full of 0x66 and 0x67 address/data size override prefixes, which (in a 32-bit code segment) will turn 32-bit operations into 16-bit ones. e.g. buffer[0] = 0x66; buffer[1] = 0x55; buffer[2] = 0x66; buffer[3] = 0x89; buffer[4] = 0xE5; ... is push bp mov bp, sp rather than push ebp mov ebp, esp (which seems to explain the observed behaviour: pushing bp decrements the stack pointer by 2 instead of 4).
3,009,268
3,009,298
Clamping a vector to a minimum and maximum?
I came accross this: t = Clamp(t/d, 0, 1) but I'm not sure how to perform this operation on a vector. What are the steps to clamp a vector if one was writing their own vector implementation? Thanks clamp clamping a vector to a minimum and a maximum ex: pc = # the point you are coloring now p0 = # start point p1 = # end point v = p1 - p0 d = Length(v) v = Normalize(v) # or Scale(v, 1/d) v0 = pc - p0 t = Dot(v0, v) t = Clamp(t/d, 0, 1) color = (start_color * t) + (end_color * (1 - t))
clamp(vec, lb, ub) == min(max(vec, lb), ub) edit min and max are usually primitive operations on vectors. For example, if you're using SSE vectors, there are _mm_min_ps and _mm_max_ps intrinsics that turn into MINPS and MAXPS instructions on x86.
3,009,355
3,009,772
Overwhelmed by design patterns... where to begin?
I am writing a simple prototype code to demonstrate & profile I/O schemes (HDF4, HDF5, HDF5 using parallel IO, NetCDF, etc.) for a physics code. Since focus is on IO, the rest of the program is very simple: class Grid { public: floatArray x,y,z; }; class MyModel { public: MyModel(const int &nip1, const int &njp1, const int &nkp1, const int &numProcs); Grid grid; map<string, floatArray> plasmaVariables; }; Where floatArray is a simple class that lets me define arbitrary dimensioned arrays and do mathematical operations on them (i.e. x+y is point-wise addition). Of course, I could use better encapsulation (write accessors/setters, etc.), but that's not the concept I'm struggling with. For the I/O routines, I am envisioning applying simple inheritance: Abstract I/O class defines read & write functions to fill in the "myModel" object HDF4 derived class HDF5 HDF5 using parallel IO NetCDF etc... The code should read data in any of these formats, then write out to any of these formats. In the past, I would add an AbstractIO member to myModel and create/destroy this object depending on which I/O scheme I want. In this way, I could do something like: myModelObj.ioObj->read('input.hdf') myModelObj.ioObj->write('output.hdf') I have a bit of OOP experience but very little on the Design Patterns front, so I recently acquired the Gang of Four book "Design Patterns: Elements of Reusable Object-Oriented Software". OOP designers: Which pattern(s) would you recommend I use to integrate I/O with the myModel object? I am interested in answering this for two reasons: To learn more about design patterns in general Apply what I learn to help refactor an large old crufty/legacy physics code to be more human-readable & extensible. I am leaning towards applying the Decerator pattern to myModel, so I can attach the I/O responsibilities dynamically to myModel (i.e. whether to use HDF4, HDF5, etc.). However, I don't feel very confident that this is the best pattern to apply. Reading the Gang of Four book cover-to-cover before I start coding feels like a good way to develop an unhealthy caffeine addiction. What patterns do you recommend?
"Which pattern(s) would you recommend I use to integrate I/O with the myModel object?" You're asking the wrong question. The question you should be asking is, "How can I separate my model from I/O?" There's lots of answers. One interesting setup I've seen is Robert C. Martin's use of proxy. Your idea of using decorator also has merit. I strongly disagree with those telling you not to worry about patterns. It is true that you should let the problem dictate the solution but until you actually try to use patterns you'll never learn to recognize them nor will you be able to use them in architectural discussions; patterns are very important to being able to discuss design and architecture and if you don't have the vocabulary you'll be severely handicapped in such discussions. Perhaps more important than patterns though is to learn the principles that cause them. Learn the Open/Closed principle (the primary one) and the LSP. Also keep in mind principles like the single responsibility principle and others. Design patterns are born out of following these principles so knowing them intimately will help you recognize when a pattern can be applied and why one particular pattern can help more than another.
3,009,379
3,009,395
how to swap array-elements to transfer the array from a column-like into a row-like representation
For example: the array a1, a2, a3, b1, b2, b3, c1, c2, c3, d1, d2, d3 represents following table a1, b1, c1, d1 a2, b2, c2, d2 a3, b3, c3, d3 now i like to bring the array into following form a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3 Does an algorithm exist, which takes the array (from the first form) and the dimensions of the table as input arguments and which transfers the array into the second form? I thougt of an algorithm which doesn't need to allocate additional memory, instead i think it should be possible to do the job with element-swap operations.
The term you're looking for is in-place matrix transpose, and here's an implementation.
3,009,489
3,009,768
Creating an object in the loop
std::vector<double> C(4); for(int i = 0; i < 1000;++i) for(int j = 0; j < 2000; ++j) { C[0] = 1.0; C[1] = 1.0; C[2] = 1.0; C[3] = 1.0; } is much faster than for(int i = 0; i < 1000;++i) for(int j = 0; j < 2000; ++j) { std::vector<double> C(4); C[0] = 1.0; C[1] = 1.0; C[2] = 1.0; C[3] = 1.0; } I realize this happens because std::vector is repeatedly being created and instantiated in the loop, but I was under the impression this would be optimized away. Is it completely wrong to keep variables local in a loop whenever possible? I was under the (perhaps false) impression that this would provide optimization opportunities for the compiler. Or maybe that only applies to POD types and not something like std::vector. EDIT: I used VC++2005 (release mode) with full optimization (/Ox) on Windows XP
Is it completely wrong to keep variables local in a loop whenever possible? I was under the (perhaps false) impression that this would provide optimization opportunities for the compiler. No, that's a good rule of thumb. But it is only a rule of thumb. Minimizing the scope of a variable gives the compiler more freedom for register allocation and other optimizations, and at least as importantly, it generally yields more readable code. But it also depends on repeated creation/destruction being cheap, or being optimized away entirely. That is often the case... But not always. So as you've discovered, sometimes it's a bad idea.
3,009,533
3,009,954
Boost.Python tutorial in Ubuntu 10.04
I downloaded the latest version of Boost and I'm trying to get the Boost.python tutorial up and running on Ubuntu 10.04: http://www.boost.org/doc/libs/1_43_0/libs/python/doc/tutorial/doc/html/python/hello.html I navigated to the correct directory, ran "bjam" and it compiled using default settings. I did not yet create a bjam config file. The compilation appears to have worked, but now I have no idea how to include the files in my python script. When I try to run the python hello world script, it gives me this error: Traceback (most recent call last): File "./hello.py", line 6, in <module> import hello_ext ImportError: libboost_python.so.1.43.0: cannot open shared object file: No such file or directory Anyone know what is going on?
How did you install boost ? Assuming you have use the following: http://www.boost.org/doc/libs/1_43_0/more/getting_started/unix-variants.html#easy-build-and-install liboost_python shard library will be install in /usr/local/lib To run the hello.py example, try the following: LD_LIBRARY_PATH=/usr/local/lib python ./hello.py
3,009,543
3,009,568
Passing integers as constant references versus copying
This might be a stupid question, but I notice that in a good number of APIs, a lot of method signatures that take integer parameters that aren't intended to be modified look like: void method(int x); rather than: void method(const int &x); To me, it looks like both of these would function exactly the same. (EDIT: apparently not in some cases, see answer by R Samuel Klatchko) In the former, the value is copied and thus can't change the original. In the latter, a constant reference is passed, so the original can't be changed. What I want to know is why one over the other - is it because the performance is basically the same or even better with the former? e.g. passing a 16-bit value or 32-bit value rather than a 32-bit or 64-bit address? This was the only logical reason I could think of, I just want to know if this is correct, and if not, why and when one should prefer int x over const int &x and vice versa.
It's not just the cost of passing a pointer (that's essentially what a reference is), but also the de-referencing in the called method's body to retrieve the underlying value. That's why passing an int by value will be virtually guaranteed to be faster (Also, the compiler can optimize and simply pass the int via processor registers, eliminating the need to push it onto the stack).
3,009,676
3,010,297
connecting cell phone to computer
is it possible for me to intercept the text messages that get sent to my cellphone if i connect to my cellphone via bluetooth or USB or some other connection to my computer? i want to create a database with all of my received text messages and be able to control my cell phone through my computer by using it to send text messages i have a regular motorola flip phone
According to GSM Specification 27.005 you should be able to get indication on incoming sms. You need to open AT Command terminal to the phone (most of the times you do that by plugging the phone to the usb, and connect to the com port that was created for it). The command that you are looking for is AT+CNMI. Just read the specification. NOTE: Long time ago, I've tried to do the same thing using Nokia phone and it didn't work. The phone didn't support this feature.
3,009,699
3,009,746
How efficient is an if statement compared to a test that doesn't use an if? (C++)
I need a program to get the smaller of two numbers, and I'm wondering if using a standard "if x is less than y" int a, b, low; if (a < b) low = a; else low = b; is more or less efficient than this: int a, b, low; low = b + ((a - b) & ((a - b) >> 31)); (or the variation of putting int delta = a - b at the top and rerplacing instances of a - b with that). I'm just wondering which one of these would be more efficient (or if the difference is too miniscule to be relevant), and the efficiency of if-else statements versus alternatives in general.
(Disclaimer: the following deals with very low-level optimizations that are most often not necessary. If you keep reading, you waive your right to complain that computers are fast and there is never any reason to worry about this sort of thing.) One advantage of eliminating an if statement is that you avoid branch prediction penalties. Branch prediction penalties are generally only a problem when the branch is not easily predicted. A branch is easily predicted when it is almost always taken/not taken, or it follows a simple pattern. For example, the branch in a loop statement is taken every time except the last one, so it is easily predicted. However, if you have code like a = random() % 10 if (a < 5) print "Less" else print "Greater" then this branch is not easily predicted, and will frequently incur the prediction penalty associated with clearing the cache and rolling back instructions that were executed in the wrong part of the branch. One way to avoid these kinds of penalties is to use the ternary (?:) operator. In simple cases, the compiler will generate conditional move instructions rather than branches. So int a, b, low; if (a < b) low = a; else low = b; becomes int a, b, low; low = (a < b) ? a : b and in the second case a branching instruction is not necessary. Additionally, it is much clearer and more readable than your bit-twiddling implementation. Of course, this is a micro-optimization which is unlikely to have significant impact on your code.
3,009,744
3,009,769
What is causing this template-related compile error?
When I try to compile this: #include <map> #include <string> template <class T> class ZUniquePool { typedef std::map< int, T* > ZObjectMap; ZObjectMap m_objects; public: T * Get( int id ) { ZObjectMap::const_iterator it = m_objects.find( id ); if( it == m_objects.end() ) { T * p = new T; m_objects[ id ] = p; return p; } return m_objects[ id ]; } }; int main( int argc, char * args ) { ZUniquePool< std::string > pool; return 0; } I get this: main.cpp: In member function ‘T* ZUniquePool<T>::Get(int)’: main.cpp:12: error: expected `;' before ‘it’ main.cpp:13: error: ‘it’ was not declared in this scope I'm using GCC 4.2.1 on Mac OS X. It works in VS2008. I'm wondering whether it might be a variation of this problem: Why doesn't this C++ template code compile? But as my error output is only partially similar, and my code works in VS2008, I am not sure. Can anyone shed some light on what I am doing wrong?
You need typename: typename ZObjectMap::const_iterator it = m_objects.find( id ) Since the type of ZObjectMap is dependent on the template parameter, the compiler has no clue what ZObjectMap::const_iterator is (it could be a member variable). You need to use typename to inform the compiler to assume it will be some sort of type.
3,009,754
3,010,607
Algorithm to generate radial gradient
I have this algorithm here: pc = # the point you are coloring now p0 = # start point p1 = # end point v = p1 - p0 d = Length(v) v = Normalize(v) # or Scale(v, 1/d) v0 = pc - p0 t = Dot(v0, v) t = Clamp(t/d, 0, 1) color = (start_color * t) + (end_color * (1 - t)) to generate point to point linear gradients. It works very well for me. I was wondering if there was a similar algorithm to generate radial gradients. By similar, I mean one that solves for color at point P rather than solve for P at a certain color (where P is the coordinate you are painting). Thanks
Linerise over atan2(dy,dx) where dx is x-center, and dy is y-center. cx # center x cy # center y r1 # ring is defined by two radius r2 # r1 < r2 c1 # start color c2 # stop color ang # start angle px # currect point x,y py if( px^2 + py^2 <= r2^2 AND px^2 + py^2 >= r1^2 ) # lies in ring? t= atan2(py-cy,px-cx)+ang t= t+ pi # atan2 is from -pi to pi if (t > 2* pi) # it might over 2pi becuse of +ang t=t-2*pi t=t/(2*pi) # normalise t from 0 to 1 color = (c1 * t) + (c2 * (1 - t)) Problem whit this algorhitm is that ang is actualy wrong and should be rotated by pi and normalized between 0 and 2pi.