question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,546,494
1,546,538
Google Earth and Windows application
I have a C++ Windows application continually updating lat, long and altitude. I would like my application to incorporate Google Earth to visually "track it". Any advice or pointing in the right direction would be appreciated. Thanks.
You can embed the Google Earth plugin into your application as an ActiveX control. The API for the control can be found here. You need to instantiate your GEPlugin control and from here you can retrieve all the other COM objects. There is no need to register with Google for the development key. This is not supported by Google as it bypasses the official method of development using Javascript.
1,546,789
1,669,254
Clean code to printf size_t in C++ (or: Nearest equivalent of C99's %z in C++)
I have some C++ code that prints a size_t: size_t a; printf("%lu", a); I'd like this to compile without warnings on both 32- and 64-bit architectures. If this were C99, I could use printf("%z", a);. But AFAICT %z doesn't exist in any standard C++ dialect. So instead, I have to do printf("%lu", (unsigned long) a); which is really ugly. If there's no facility for printing size_ts built into the language, I wonder if it's possible to write a printf wrapper or somesuch such that will insert the appropriate casts on size_ts so as to eliminate spurious compiler warnings while still maintaining the good ones. Any ideas? Edit To clarify why I'm using printf: I have a relatively large code base that I'm cleaning up. It uses printf wrappers to do things like "write a warning, log it to a file, and possibly exit the code with an error". I might be able to muster up enough C++-foo to do this with a cout wrapper, but I'd rather not change every warn() call in the program just to get rid of some compiler warnings.
Most compilers have their own specifier for size_t and ptrdiff_t arguments, Visual C++ for instance use %Iu and %Id respectively, I think that gcc will allow you to use %zu and %zd. You could create a macro: #if defined(_MSC_VER) || defined(__MINGW32__) //__MINGW32__ should goes before __GNUC__ #define JL_SIZE_T_SPECIFIER "%Iu" #define JL_SSIZE_T_SPECIFIER "%Id" #define JL_PTRDIFF_T_SPECIFIER "%Id" #elif defined(__GNUC__) #define JL_SIZE_T_SPECIFIER "%zu" #define JL_SSIZE_T_SPECIFIER "%zd" #define JL_PTRDIFF_T_SPECIFIER "%zd" #else // TODO figure out which to use. #if NUMBITS == 32 #define JL_SIZE_T_SPECIFIER something_unsigned #define JL_SSIZE_T_SPECIFIER something_signed #define JL_PTRDIFF_T_SPECIFIER something_signed #else #define JL_SIZE_T_SPECIFIER something_bigger_unsigned #define JL_SSIZE_T_SPECIFIER something_bigger_signed #define JL_PTRDIFF_T_SPECIFIER something-bigger_signed #endif #endif Usage: size_t a; printf(JL_SIZE_T_SPECIFIER, a); printf("The size of a is " JL_SIZE_T_SPECIFIER " bytes", a);
1,546,997
1,547,287
Will accessing a class object through a pointer to its derived class break strict aliasing rules?
void foobar(Base* base) { Derived* derived = dynamic_cast<Derived*>(base); // or static_cast derived->blabla = 0xC0FFEE; if (base->blabla == 0xC0FFEE) ... } On compilers with strict aliasing, is "derived" an alias for "base"?
Two pointers are aliased whenever it is possible to access the same object through them. Paragraph 3.10/15 of the standard specifies when an access to an object is valid. If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined: the dynamic type of the object, a cv-qualified version of the dynamic type of the object, a type that is the signed or unsigned type corresponding to the dynamic type of the object, a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object, an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), a type that is a (possibly cv-qualified) base class type of the dynamic type of the object, a char or unsigned char type. In your case, *derived is either an l-value of the dynamic type of the object or it is of a type that is a base class type of the dynamic type of the object. *base is of a type that is a base class type of the dynamic type of the object. Therefore, you are allowed to access the object through both derived and base, making the two pointers aliased.
1,547,010
1,547,243
When to use OOP instead of Arrays
When should I use OOP instead of an array? Does the size of my project matter? To provide a little background: I'm making a small program for my friend. Basically, he wants to add different scores to each other to be able to see his grade. (Yes, I know there's commercial software, but this is also a fun exercise.) Anyways, from time to time, he might want the program to recalculate all the scores, so I would have to read the previous entries in. I'm more familiar with arrays, so I was going to use those, but OOP might be an equally good tool. So, basically, when should I use OOP?
Agreed with others, arrays and OOP are two different and overlapping concepts. It's like saying, "How should I get to work today? On time, or in a car?" You can do both/either/neither, they are two different things. Assuming you have one person (your friend) in the program with a set of scores, and you add all the scores up to find a grade, then just use an "array" (list, sequence, vector, etc) C++: vector<float> myScores; myScores.push_back(100.0); myScores.push_back(50.5); myScores.push_back(10.0); float calcGrade(vector<float> scores) { float grade = 0; for (unsigned int i=0; i<scores.size(); i++) { grade += scores[i]; } return grade / scores.size(); } calcGrade(myScores) Python: scores = [] scores.append(100.0) scores.append(50.5) scores.append(10.0) def calcGrade(scores): grade = 0 for i in scores: grade += i return grade / len(scores) calcGrade(scores) However, if you have multiple people in your program with multiple scores, then you should consider using a better structure to hold data. You could do a more OOP approach class Person { vector<float> scores; float calcGrade(); } or just take it simple with multi-dimensional arrays. But at that point, you probably need some "OOP" in your program.
1,547,066
1,547,080
How do we iterate through all elements of a set while inserting new elements to it?
consider this: // set_iterator.cpp : Defines the entry point for the console application. #include "stdafx.h" #include <iostream> #include <set> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { set<int> a1; set<int> a2; a1.insert(3); a1.insert(4); a1.insert(5); a2.insert(1); a2.insert(2); a2.insert(6); set<int>::iterator iter; int x = 0; for (iter = a1.begin(); iter != a1.end(); ++iter) { if (x == 0) { x = 1; a1.insert(a2.begin(), a2.end()); } cout << *iter << endl; } system("pause"); return 0; } goal is to visit each element of the set exactly once. i think the iterator is not valid after we insert elements into a1. output is 3 4 5 6 1,2 are not printed. how do we code such a situation.
Actually, the iterator is still valid. A set is a node-based container. The problem is that in a set the elements are always sorted. Before insertion, your set looks like this: 3 4 5 ^ iter After insertion, your set looks like this: 1 2 3 4 5 6 ^ iter You'll have to use a different container if you want to be able to do what you're doing.
1,547,092
1,547,098
Stream Insertion Overloading C++
Im trying to call the function: friend ostream& operator<<(ostream& out, stack::myItem& theItem); that is public to my stack object: class stack { public: stack(int capacity); ~stack(void); void method1(); ... private: struct myItem { int item; }; ... public: friend ostream& operator<<(ostream& out, stack& s); friend ostream& operator<<(ostream& out, stack::myItem& theItem); }; What I know is that this function below: ostream& operator<<(ostream& out, stack& s) { if ( s.count == 0 ) // then no elements have been counted. out << "\nstack: empty\n\n"; else { out << "\nstack: "; for ( int i = 0; i < s.count; i++ ) { if ( i < s.count-1 ) out << s.myItem[i].item << ", "; else out << s.myItem[i].item; } out << "\n\n"; } return out; } given the statement: stack s = stack(7); the function above is called whenever i use: cout << s; How do I call the function below? ostream& operator<<(ostream& out, stack::myItem& theItem) out << theItem.item; return out; } Because when I try to do the following: ostream& operator<<(ostream& out, stack& s) { if ( s.count == 0 ) // then no elements have been counted. out << "\nstack: empty\n\n"; else { out << s; } return out; } It results in a crash, because the statement out << s; will be endless.. While debugging the code will never go to the next statement...
If you are looking to call it on the myItem struct, then: for ( int i = 0; i < s.count; i++ ) { if ( i < s.count-1 ) out << s.myItem[i] << ", "; else out << s.myItem[i]; } would call it on each struct in the stack. In the endlessly recursive one, you are just calling it again on the stack, and in the first version, you are calling it on the "item" int within the myItem struct. (and as a matter of taste, I prefer to keep end condition loops out of for statements like this:) for ( int i(0), end(s.count-1); i < end; ++i ) { out << s.myItem[i] << ", "; } out << s.myItem[s.count];
1,547,211
1,547,251
How to create minidump for my process when it crashes?
I am not able to create minidump form my process by changing system setting. So my Question is : Will the system create a minidump for a user process when it crashes If yes, which setting do I need to configure Or do I have to create minidump programmatically. How effective are minidumps while investigating a crash I'm using Windows XP, C++, VC6
You need to programatically create a minidump (with one exception, see next link). CodeProject has a nice article on MiniDumps. Basically, you want to use dbghelp.dll, and use the function MiniDumpWriteDump() (see MSDN on MiniDumpWriteDump). How effective such dumps are depends very much on the application. Sometimes, for optimized binaries, they are practically useless. Also, without experience, heap/stack corruption bugs will lead you astray. However, if the optimizer was not too hard on you, there is a large class of errors where the dumps do help, namely all the bugs where having a stack-trace + values of the locally used variables is useful, i.e. many pure-virtual-function call things (i.e. wrong destruction order), access violations (uninitialized accessed or missing NULL checks), etc. BTW, if your maintenance policy somehow allows it, port your application from VC6 to something acceptable, like VC8 or 9. You'll do yourself a big favor.
1,547,342
1,557,354
C++ run time error with protected members
I am trying to do a homework assignment where we insert a string into a string at a specified point using a linked stack, hence the struct and typedef. Anyway, when I try to access stringLength in the StringModifier class inside the InsertAfter method, I get a run time error and I cannot figure out what the problem is. I should be able to access and modify the variable because it's protected and the derived class is inherited publicly. struct StringRec { char theCh; StringRec* nextCh; }; typedef StringRec* StringPointer; class String { public: String(); ~String(); void SetString(); void OutputString(); int GetLength() const; protected: StringPointer head; int stringLength; }; class StringModifier : public String { public: StringModifier(); ~StringModifier(); void InsertAfter( StringModifier& subString, int insertAt ); }; void StringModifier::InsertAfter( StringModifier& subString, int insertAt ) { // RUN TIME ERROR HERE stringLength += subString.stringLength; } in MAIN StringModifier test; StringModifier test2; cout << "First string" << endl; test.SetString(); test.OutputString(); cout << endl << test.GetLength(); cout << endl << "Second string" << endl; test2.SetString(); test2.OutputString(); cout << endl << test2.GetLength(); cout << endl << "Add Second to First" << endl; test.InsertAfter( test2, 2 ); test.OutputString(); cout << endl << test.GetLength(); //String Class String::String() { head = NULL; stringLength = 0; } String::~String() { // Add this later } void String::SetString() { StringPointer p; char tempCh; int i = 0; cout << "Enter a string: "; cin.get( tempCh ); // Gets input and sets it to a stack while( tempCh != '\n' ) { i++; p = new StringRec; p->theCh = tempCh; p->nextCh = head; head = p; cin.get( tempCh ); } stringLength = i; } void String::OutputString() { int i = stringLength; int chCounter; StringPointer temp; // Outputs the string bottom to top, instead of top to bottom so it makes sense when read while( head != NULL && i > 0 ) { temp = head; chCounter = 0; while( temp != NULL && chCounter < (i-1) ) { temp = temp->nextCh; chCounter++; } cout << temp->theCh; i--; } } int String::GetLength() const { return stringLength; } The StringModifier class has empty constructors and destructors.
Thanks for everyone's help. It turns out I was adding things to the list wrong to begin with. Instead of making it a stack I made it a Queue and all is working great! I took advice you guys gave and looked elsewhere for the problem. Thank You! void String::SetString() { StringPointer p, last; char tempCh; last = head; int i = 0; cout << "Enter a string: "; cin.get( tempCh ); while( tempCh != '\n' ) { i++; if( i == 1 ) { p = new StringRec; p->theCh = tempCh; head = p; last = p; } else { p = new StringRec; p->theCh = tempCh; p->nextCh = last; last->nextCh = p; last = p; } cin.get( tempCh ); } last->nextCh = NULL; stringLength = i; }
1,547,621
1,547,656
General printing raster and/or vector images
I'm looking for some API for printing. Basically what I want to achieve is to print set of pixels(monochromatic bitmap which I store in memory) onto the generic paper format (A4,A5..etc.). What I think that would be minimum API is: printer devices list printer buffer where I could send my in-memory pixmap (ex. like winXP printer tasks folder) some API which would translate SI dimensions onto printer resolution, or according to previous - in memory pixmap (ex. 450x250) onto paper in appropriate resolution. What I was considering is postScript, but I've some old LPT drived laserjet which probably doesn't support *PS. Currently I'm trying to find something interesting in Qt - QGraphicsView. http://doc.trolltech.com/4.2/qgraphicsview.html
Well you got close, look at Printing in Qt. There is the QPrinter class that implements some of what you are looking for. It is implmenetent as a QPaintDevice. This means that any widget that can render itself on the screen can be printed. This also mean you don't need to render to a bitmap to print, you can use Qt widgets or drawing functions for printing On a side note, check the version number of the Qt documentation, the last release of Qt is 4.5, 4.6 is in beta.
1,547,632
1,548,638
Programming in gamedev (performance related)
I am just wondering how some things work in gamedev: I know, that the performance is actually crucial so there is still (and I think never will be) no place to use managed languages/platforms as Java/.NET just because of their performance. But... recently I have read somewhere here on SO, that even though people creating games use C++ as a primary language, they actually do not use STL or Boost (or a lot of them). In think it has something in common with performance, right? If I am wrong, could you please tell me what are the reasons to avoid those libraries (that I think make developer's life much easier)? Is it because of licensing (Boost)? And what about EA's version of STL? Do other studios make their own versions too? How "close to metal" game programming really is? Do you go deeper and closer to the machine? Do you sometimes use Assembly for critical inner loops, or C++ is actually the lowest abstraction layer that you use at the moment? I assume that in such products where performance is the most important thing profiling is very, very common task - but are you sometimes forced to use assembly to speed some parts up, or good C++ is "good enough"? Edit: Sorry, It may not have been clear, but I am interested in answers from people having game industry experience. I am not interested in some assumptions given by people who do not have commercial experience in game development. I am also not interested in examples of some niche-games created in C#/Java whatever. However if you know a product that looks better than FarCry2 (just and example, but your favourite modern great looking game name here), and is written entirely in Java/.NET, and has similar performance to FarCry2... do not hesitate to mention this product! Thanks.
It is true that in game development, STL is not used. In spite of what certain people always rush to claim, they also never use Java or C# or other managed languages. I'm not talking about small X-Box Live Arcade downloadable games or web browser games, or such things. I'm talking about high-end development in AAA games. They don't use STL. However, they do use their own custom implementations that look a lot like STL. There will be smart-arrays, there will be hash tables, there will be smart pointers, they just won't be STL. Consoles have some performance characteristics that are very different from PCs. Even game projects that exclusively target PC are usually using codebases that have been used for console projects in the past. A lot of tweaking goes into making the basic template structures work as desired. Most game studios also want code that they can adapt to other platforms. Locking into an implementation from MS/Sony/Nintendo makes for a lot more pain when it comes time to port the game to a new platform. The provided template libraries (which aren't necessarily STL to start with) are often less than stellar. At least they are that way early in the hardware cycle when a studio is ironing out the engine they plan to keep using for the next five years. At the studios I've worked at, I've certainly seen a fair degree of "not-built-here" attitude to dismiss third party code. Sometimes it's justified, sometimes it's not. In the case of basic data structure templates, it typically is. As for your second question, assembler is occasionally used. But only in isolated situations where a large volume of math needs to happen very frequently. An entire engine might contain two or three smallish files of asm blocks.
1,547,746
1,548,429
C++ Passing two dimensional arrays as parameters to classes
I've got a Car class and a Track class. The Car class constructor takes a road parameter which is supposed to be a 32x32 boolean array. Then I've got a Track class which creates a Car class and is supposed to pass the 32x32 array to it's constructor. Note that I've simplified the code somewhat by removing irrelevant bits and pieces. class Car : public WorldObject { private: bool _road[32][32]; public: Car(bool road[32][32]) { _road = road; } }; class Track : public WorldObject { public: bool _road[32][32]; Track() { Car* _car = new Car(this->_road); _car->Position.X = 50; _car->Position.Y = 50; ChildObjects.push_back(_car); } }; This won't compile ... I get an error: Error 1 error C2440: '=' : cannot convert from 'bool [][32]' to 'bool [32][32]' in the the _road = road; line in the Car constructor. What am I doing wrong?
You can't copy arrays like that. Others have already discussed this in more detail, including alternative for-loop individual assignment and memcpy solutions. Another solution is to wrap your array inside a struct. Struct's can be copied like that. E.g.: struct RoadStruct { bool road[32][32]; }; class Car : public WorldObject { private: RoadStruct _road; public: Car(const RoadStruct & road ) { _road = road; } }; Though it would be more efficient to copy like this: public: Car(const RoadStruct & road ) : _road ( road ) {} (Of course that creates 2 RoadStruct data sets. If you only wanted one shared array, that could be arranged...)
1,547,790
1,547,807
How to assign a value to a TCHAR array
I have a TCHAR array in my C++ code which I want to assign static strings to it. I set an initial string to it via TCHAR myVariable[260] = TEXT("initial value"); Everything works fine on this. However, when I split it in two lines as in TCHAR myVariable[260]; myVariable = TEXT("initial value"); it bugs and gives a compiler error: error C2440: '=': cannot convert from 'const char [14]' to 'TCHAR [260]' shouldn't the TEXT() function do exactly what I want here? convert the given string to TCHARs? Why does it work, when putting the two lines together? What do I have to change in order to get it working? Some other confusing thing I have encountered: I've searched the internet for it and have seen that there are also _T() and _TEXT() and __T() and __TEXT(). What are they for? Which of them should I use in what environment?
The reason the assignment doesn't work has very little to do with TCHARs and _T. The following won't work either. char var[260]; var = "str"; // fails The reason is that in C and C++ you can't assign arrays directly. Instead, you have to copy the elements one by one (using, for example, strcpy, or in your case _tcscpy). strcpy(var, "str"); Regarding the second part of your question, TEXT, _T and the others are macros, that in Unicode builds turn a string literal to a wide-string literal. In non-Unicode builds they do nothing.
1,547,864
1,547,876
Pointer to class method
I'm trying to have pointer to class methods, so I have something like: class foo { public: static void bar() { } }; void (foo::*bar)() = &foo::bar; That doesn't compile :( I get: > error: cannot convert ‘void (*)()’ to > ‘void (foo::*)()’ in > initialization
A static method, when used by name rather than called, is a pointer. void (*bar)() = foo::bar; // used as a name, it's a function pointer ... bar(); // calls it
1,547,870
1,547,892
Why is my nest class being seen as abstract?
I have an abstract base class which contains a private nested implementation. visual c++ is giving me the following error when I try to instantiate the non-abstract nested implementation: error C2259: 'node::empty_node' : cannot instantiate abstract class (line 32) as far as I can tell, I've overridden all the abstract members of the base class Code follows: using namespace boost; template<typename K, typename V> class node { protected: class empty_node : public node<K,V> { public: bool is_empty(){ return true; } const shared_ptr<K> key() const { throw empty_node_exception; } const shared_ptr<V> value() const { throw empty_node_exception; } const shared_ptr<node<K,V>> left() const { throw empty_node_exception; } const shared_ptr<node<K,V>> right() const { throw empty_node_exception; } const shared_ptr<node<K,V>> add(const shared_ptr<K> &key, const shared_ptr<V> &value) const { return shared_ptr<node<K,V>>(); } const shared_ptr<node<K,V>> remove(const shared_ptr<K> &key) const { throw empty_node_exception; } const shared_ptr<node<K,V>> search(const shared_ptr<K> &key) const { return shared_ptr<node<K,V>>(this); } }; static shared_ptr<node<K,V>> m_empty; public: virtual bool is_empty() = 0; virtual const shared_ptr<K> key() = 0; virtual const shared_ptr<V> value() = 0; virtual const shared_ptr<node<K,V>> left() = 0; virtual const shared_ptr<node<K,V>> right() = 0; virtual const shared_ptr<node<K,V>> add(const shared_ptr<K> &key, const shared_ptr<V> &value) = 0; virtual const shared_ptr<node<K,V>> remove(const shared_ptr<K> &key) = 0; virtual const shared_ptr<node<K,V>> search(const shared_ptr<K> &key) = 0; static shared_ptr<node<K,V>> empty(){ if(NULL == m_empty.get()){ m_empty.reset(new empty_node()); } return m_empty; } };
The function signatures don't match. The pure virtual member functions in the base class 'node' are not const; the functions in the derived class 'empty_node' are const. You either need to make the base class virtual functions const or remove the const qualifier from the member functions in the derived class.
1,547,958
1,547,968
Why am I getting unresolved externals?
I am writing an immutable binary search tree in c++. My terminating nodes are represented by a singleton empty node. My compiler (visual c++) seems to be having trouble resolving the protected static member that holds my singleton. I get the following error: error LNK2001: unresolved external symbol "protected: static class boost::shared_ptr > node::m_empty" (?m_empty@?$node@HH@@1V?$shared_ptr@V?$node@HH@@@boost@@A) I am assuming this means it cant resolve the static m_empty member for the type node. Is this correct? If so how do I fix it? Code follows: using namespace boost; template<typename K, typename V> class node { protected: class empty_node : public node<K,V> { public: bool is_empty(){ return true; } const shared_ptr<K> key() { throw cant_access_key; } const shared_ptr<V> value() { throw cant_access_value; } const shared_ptr<node<K,V>> left() { throw cant_access_child; } const shared_ptr<node<K,V>> right() { throw cant_access_child; } const shared_ptr<node<K,V>> add(const shared_ptr<K> &key, const shared_ptr<V> &value){ return shared_ptr<node<K,V>>(); } const shared_ptr<node<K,V>> remove(const shared_ptr<K> &key) { throw cant_remove; } const shared_ptr<node<K,V>> search(const shared_ptr<K> &key) { return shared_ptr<node<K,V>>(this); } }; static shared_ptr<node<K,V>> m_empty; public: virtual bool is_empty() = 0; virtual const shared_ptr<K> key() = 0; virtual const shared_ptr<V> value() = 0; virtual const shared_ptr<node<K,V>> left() = 0; virtual const shared_ptr<node<K,V>> right() = 0; virtual const shared_ptr<node<K,V>> add(const shared_ptr<K> &key, const shared_ptr<V> &value) = 0; virtual const shared_ptr<node<K,V>> remove(const shared_ptr<K> &key) = 0; virtual const shared_ptr<node<K,V>> search(const shared_ptr<K> &key) = 0; static shared_ptr<node<K,V>> empty() { if(m_empty.get() == NULL){ m_empty.reset(new empty_node()); } return m_empty; } }; the root of my tree is initialized as: shared_ptr<node<int,int>> root = node<int,int>::empty();
m_empty is static and so you'll need to have a source (.cpp) file with something like the following: template <typename K, typename V> shared_ptr<node<K,V> > node<K,V>::m_empty; Note: My original answer was incorrect and did not take into account that this was a template. This is the answer that AndreyT gave in his answer; I've updated this answer with the correct answer because this is the accepted answer and appears at the top of the page. Please upvote AndreyT's answer, not this one.
1,547,991
6,095,469
Invalid Class String Error when creating C++ Project in Visual Studio 2008 with Vista x64
After going through this Problem (connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=329986) that was related with registry permissions, now again, Visual Studio comes with another error. I have the same error as this guy, I have searched all the internet and it seems nobody has resolved it yet. When I create a C++ Windows Forms Application, and want to see the "Design view" of the the default Form1, it just gives me this error: Invalid Class String (Exception from HRESULT: 0x800401F3 (CO_E_CLASSSTRING)) at Microsoft.VisualStudio.Designer.Interfaces.IVSMDCodeDomProvider.get_CodeDomProvider() at Microsoft.VisualStudio.Shell.Design.Serialization.CodeDom.CodeDomDocDataAdapter.get_Provider() at Microsoft.VisualStudio.Shell.Design.Serialization.CodeDom.CodeDomDocDataAdapter.get_CompileUnit() at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager) at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(Int32fReload) I'm sorry if this has nothing to do with programming at all, but if someone has any opinions or comments, I would like to hear it. Image at img12.imageshack.us/img12/8256/dibujowc.jpg Sorry for the links, the system don't allow me to put hyperlinks
Well this hapend to me after i renamed feacp.dll in order to disable intellisense. However, after re-enabling intellisense, all worked ok.
1,548,017
1,553,978
How to include a newline in a C++ macro or how to use C++ templates to do the same?
I saw the following question: How to generate a newline in a cpp macro? Let me give a brief requirement of a need in newline in a C++ preprocessor. Am working on ARM Realview compiler 3.1 on a code which uses embedded assembly code with C++ code. #define DEFINE_FUNCTION(rtype, op, val) \ __asm rtype nt_##op(void*) { \ str lr, [sp, ##val];bl vThunk_##op;ldr lr, [sp,##val];bx lr; \ } \ void vThunk_##op(void*) DEFINE_FUNCTION(void*, mov_lt, #0x04) { // do some operation } The above macro declares a embedded assembly function which forcefully requires newline between each statements in the function body. I think this is because the text in the function body is sent blindly to ARM assembler by ARM compiler. Why C++ preprocessor is still now not supporting multi-line replacements ? and also i cannot use # in the replacement string. for example, for this kind of assembly, str lr, [sp, #0x04] I tried lots of methods and ways, but nothing really worked out. ARM assembler/compiler is so basic that there is no API like asm volatile in GCC. DEFINE_FUNCTION macro is used at lots of places, so cannot ignore it also. So, at final resort thinking about the following solutions: Using m4 preprocessor instead of C++ preprocesser Use C++ templates to somehow achieve this and replace DEFINE_FUNCTION using grep/sed Can anyone give me pointers or ways to do the above things ? I cannot use any compiler other than ARM Realview compiler 3.1. I need some expansion like below with new line for, DEFINE_FUNCTION(void*, mov_lt, #0x04) {}, __asm void* nt_mov_lt(void*) { str lr, [sp, 0x04]; bl vThunk_mov_lt; ldr lr, [sp,0x04]; bx lr; } void vThunk_mov_lt(void*) { // do something }
I solved the above problem using GNU m4 preprocessor successfully. m4_define('DEFINE_FUNCTION',' __asm rtype nt_$2(void*) { str lr, [sp, $3]; bl vThunk_$1; ldr lr, [sp,$3]; bx lr; } void vThunk_$2(void*)') DEFINE_FUNCTION(void*, mov_lt, 0x04) { } Preprocessing the above code using m4 solved my problem of newline requirement in code. Ran m4 -P as a prebuild event so that source file is processed even before C preprocessor and compilation stage comes into picture. Thanks for the help and sorry for confusing a lot. But there is really a scope for good macro pre-processor in latest C++ compilers.
1,548,075
1,548,867
Signing data in C++ compatible with PHP's openssl library
I'm looking for a way to sign some data in C++ code which will then be sent to a PHP script for verification and processing. I want to use the OpenSSL module there, namely the openssl_verify function so I need something compatible with that. The application will be only for Windows so CryptoAPI might be fine but looking at the samples I don't like it and couldn't get it work, some simple lightweight library would be better. I just need to load a private key and generate the signature for some string.
As for the Cripto API this example might help you to import a custom private key. Alternatively, you can look at Crypto++.
1,548,495
1,548,795
Can a program figure out its Oracle resource usage?
My boss would like to find a way for a running executable to ask Oracle, the size of the resources that the program is used. The purpose behind this is so that we can add to the user documentation/capacity planning documentation information on the size of the resources needed for each program. My Google-Fu is weak today, and I really haven't been able to find anything in the docs or online that point toward an API that would help me accomplish this. Does anyone have any experiences they can share? Or suggest leads for me to follow? All on topic answers get +1, as a thank you. Evil.
This query will show you session statistics by their description. select v$statname.name, v$mystat.value from v$mystat, v$statname where v$mystat.statistic# = v$statname.statistic# Descriptions of the various statistics (for 10g) are here: http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/stats002.htm There's other useful information in v$session: select * from v$session where sid = ( select distinct sid from v$mystat )
1,548,658
1,548,666
C++ Error: No Match for Call
I'm trying to compile the following code in C++ string initialDecision () { char decisionReviewUpdate; cout << "Welcome. Type R to review, then press enter." << endl; cin >> decisionReviewUpdate; // Processing code } int main() { string initialDecision; initialDecision=initialDecision(); //ERROR OCCURS HERE // More processing code return 0; } Right where it says "Error occurs here", I get the following error while compiling: "Error: No Match for Call to '(std::string) ()'. How can I resolve this?
Don't give your string and your function the same name, and the error will go away. The compiler has "forgotten" that there is a function with that name, when you declare a local variable with the same name.
1,548,686
1,548,995
functor generation from member function pointer type
I am trying to simplify (via make_fn()) the generation of functors that preprocess parameters (via wrap()) for member functions of arity n. Generating the functors is basically working, but until now only by explicitly specifying the parameter types for the member function. Now i'd like to generate the correct functor from the member function type it handles: struct X {}; template<class C, typename T1, bool (C::*F)(T1)> inline // there are more for T1..TN bool wrap(C* c, X x) { return (c->*F)(process<T1>(x)); } template<class C, typename T1, bool (C::*F)(T1)> inline // there are more for T1..TN boost::function<bool (C*, X)> make_fn(F f) // <- problem here, F is not a type { return boost::bind(&wrap<C, T1, F>, _1, _2); } With this however, vc++ and g++ don't see F as a type for the parameter of make_fn(). I must miss something obvious here and am feeling somewhat blind. The idea was that it should work like this: struct A { bool f1(bool) { return true; } }; void test() { A a; X x; make_fn(&A::f1)(&a, x); } Any ideas on how to make that work? Background: I have a fixed interface which, when simplified, looks like this: bool invoke(C* c, const char* const functionName, int argCount, X* args); X is a variant type which i have to convert to certain backend types (int, std::string, ...). To handle these calls i have a map of functors that are looked up by name and map these calls to member functions of some instance. The intention of the wrapping is to avoid manual conversions and instead generate functors which do the conversion for me or throw. I have this working with a macro based solution, but that solution requires to specify the types and the parameter count explicitly. Via function overload resolution i hope to generate the correct converting functor implicitly from the member function signature.
It appears to me that you are attempting to turn a pointer passed to a function into a non-type template argument, which I'm afraid is not going to work (see comments to your question). What you could do, is to store the function pointer in a function object. The following appears to compile: #include <boost/bind.hpp> #include <boost/function.hpp> struct X {}; template <class T> bool process(X) { return true; } template <class C, class T1, class Func> struct wrap1 { typedef bool result_type; Func f; wrap1(Func f): f(f) {} bool operator()(C* c, X x) { return (c->*f)(process<T1>(x)); } }; template<class C, typename T1> inline // there are more for T1..TN boost::function<bool (C*, X)> make_fn(bool (C::*f)(T1)) { return boost::bind(wrap1<C, T1, bool (C::*)(T1)>(f), _1, _2); } struct A { bool f1(bool) { return true; } }; void test() { A a; X x; make_fn(&A::f1)(&a, x); } However, I'm not sure if that is any good and how you would create the rest of the wrappers. For the latter you might just get a compiler that supports variadic templates. :)
1,548,741
1,548,789
Check if mouse is over a rotated sprite? C++
I'm making a game in c++. It is a card game. I have made 13 cards that rotate about a point to arc out to make your hand. I need a way to figure out which card the user clicks on. My cards are basically rectangles rotated about a point that is in the center of the cards. I was thinking of maybe getting the mouse point and rotating it about my central point but i'm not sure how to rotate a point about a point. Thanks.
Rotating a around p The trick is to reduce rotating around a point to rotating around the origin by doing translations. Subtract p from a (move to the origin) Rotate by angle Add p to resulting point (move again) Formula for rotating (x, y) aroung the origin:
1,548,947
1,548,967
Passing one va_list as a parameter to another
I'm creating an application using the fastcgi library, and their method of printing is a little verbose. I'm trying to wrap their fprintf function in my own method: I would like to turn FCGX_FPrintF(out, char* fmt, ...); into write(char* strFormat, ...); I've found the magic of va_list but can't find an easy way to pass va_list values into their fprintf function. Is there a way to do this? I know vsprintf and vprintf exist so it must be harder than I imagine it is. If all else fails, I'll just overload a write function
You would have to find the analogue of vfprintf() in the Fast CGI library. It is at least moderately plausible that there is one; the easy way to implement FCGX_FPrintF() is: void FCGX_FPrintF(FILE *out, char *fmt, ...) { va_list args; va_start(args, fmt); FCGX_VFPrintF(out, fmt, args); va_end(args); } So it is highly probable that the function exists; you will need to check whether it is exposed officially or not. A quick visit to the Fast CGI web site reveals that the FCGX prefix is used by functions declared in the fgciapp.h header, and that in turn contains: /* *---------------------------------------------------------------------- * * FCGX_FPrintF, FCGX_VFPrintF -- * * Performs printf-style output formatting and writes the results * to the output stream. * * Results: * number of bytes written for normal return, * EOF (-1) if an error occurred. * *---------------------------------------------------------------------- */ DLLAPI int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...); DLLAPI int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg); So, there's the function with the interface completed.
1,548,986
1,549,007
Array Manipulation in C++
Help me understand this piece of code - After the first iteration the value of PlcCode becomes A1*. How come? Shouldn't it be A*? Code = "A1"; char Wild = '*'; TDataString PlcCode(Code); for (int i = (Code.Len() - 1); i >= 0; i--) { PlcCode[i] = Wild; }
Another possibility TDataString is storing non-null terminated data, and has a templated operator= accepting byte arrays. This way, you could think of the code as TDataString Code(3); Code[0] = 'A'; Code[1] = '1'; Code[2] = '\0'; char Wild = '*'; TDataString PlcCode(Code); for (int i = 2; i >= 0; i--) { PlcCode[i] = Wild; } Imagine the following implementation of TDataString struct TDataString { typedef unsigned char TElement; public: TDataString(std::size_t n):data(n) { } template<typename T, std::size_t N> TDataString(T const (&d)[N]):data(d, d+N) { } TElement &operator[](std::size_t i) { return data[i]; } std::size_t Len() const { return data.size(); } private: std::vector<TElement> data; }; Using that class, we can assign "A1" to Code, and it will give it a length of 3, and then executing the loop's first iteration will get us to A1*.
1,549,093
1,549,141
LNK2019 && LNK1120 errors when splitting my code in multiple files
My code is stored in a main.cpp file which contains the void main() function, and a class MyClass which I now want to split to another file. IDE is Microsoft Visual Studio 2008 Professional. myclass.h #include <tchar.h> class MyClass { public: static bool MyFunction (TCHAR* someStringArgument); }; myclass.cpp #include <tchar.h> class MyClass { private: static bool someProperty; static void doSomeOneTimeCode () { if (!someProperty) { /* do something */ someProperty = true; } } public: static bool MyFunction (TCHAR* someStringArgument) { doSomeOneTimeCode(); /* do something */ return true; } }; bool MyClass::someProperty = false; main.cpp #include <windows.h> #include <stdio.h> #include <tchar.h> #include "myclass.h" void main () { if (MyClass::MyFunction(TEXT("myString"))) { _tprintf(TEXT("Yay\n")); } } However, when I try to run it, I get two linker errors. LNK2019: unresolved external symbol ... (mentions MyClass::MyFunction) LNK1120: 1 unresolved externals What can I do to prevent these linker errors?
You declared two classes here. One of them is in myclass.h and the other is in myclass.cpp. Try the following instead: myclass.h #ifndef myclass_h_included #define myclass_h_included #include <tchar.h> class MyClass { private: static bool someProperty; static void doSomeOneTimeCode (); public: static bool MyFunction (TCHAR* someStringArgument); }; #endif //!myclass_h_included myclass.cpp #include "myclass.h" /*static*/ bool MyClass::someProperty = false; void MyClass::doSomeOneTimeCode() { //... } bool MyClass::MyFunction(TCHAR* someStringArgument) { //... } Your main.cpp can stay the same. I would pay attention to UncleBens reply as well. One time initialization code should be hidden if at all possible.
1,549,129
1,671,618
Debugging image rendering in Visual C++, any helpful add-ins?
I often write code that renders images by writing pixels directly into buffers and I often find it hard to get a good overview of what's really going on. The Memory window in Visual Studio's debugger is somewhat a help, but I'd really love to see the images graphically. So my question is, does anyone know of a debugging extension that can read a chunk of memory as a picture in a specified pixel format and display it graphically?
Such a thing exists: A utility for simple printf-style debugging of images in Win32 C/C++ applications. http://billbaxter.com/projects/imdebug/ My coworker raves about it. --chris
1,549,130
1,549,138
Accessing a member/method of a virtual derived class
The example here doesn't make sense, but this is basically how I wrote my program in Python, and I'm now rewriting it in C++. I'm still trying to grasp multiple inheritance in C++, and what I need to do here is access A::a_print from main through the instance of C. Below you'll see what I'm talking about. Is this possible? #include <iostream> using namespace std; class A { public: void a_print(const char *str) { cout << str << endl; } }; class B: virtual A { public: void b_print() { a_print("B"); } }; class C: virtual A, public B { public: void c_print() { a_print("C"); } }; int main() { C c; c.a_print("A"); // Doesn't work c.b_print(); c.c_print(); } Here's the compile error. test.cpp: In function ‘int main()’: test.cpp:6: error: ‘void A::a_print(const char*)’ is inaccessible test.cpp:21: error: within this context test.cpp:21: error: ‘A’ is not an accessible base of ‘C’
Make either B or C inherit from A using "public virtual" instead of just "virtual". Otherwise it's assumed to be privately inherited and your main() won't see A's methods.
1,549,176
1,549,190
C++ - Using std::count() with abstract data types?
My code is using std::count() on a list of an abstract data type that i have defined. (Sommet or Edge in english). But it doesn't work, although i've overloaded the < and == operators like this : bool operator< (const Sommet &left, const Sommet &right) { if(left.m_id_sommet < right.m_id_sommet) return true; return false; } bool operator== (const Sommet &left, const Sommet &right) { if(left.m_id_sommet == right.m_id_sommet) return true; return false; } Just notice that this worked using std::sort() and std::unique(). The errors are: /usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h: In function 'typename std::iterator_traits<_Iterator>::difference_type std::count(_InputIterator, _InputIterator, const _Tp&) [with _InputIterator = __gnu_cxx::__normal_iterator<Sommet*, std::vector<Sommet, std::allocator<Sommet> > >, _Tp = __gnu_cxx::__normal_iterator<Sommet*, std::vector<Sommet, std::allocator<Sommet> > >]': Graphe.cpp:43: instantiated from here /usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h:422: error: no match for 'operator==' in '__first.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = Sommet*, _Container = std::vector<Sommet, std::allocator<Sommet> >]() == __value' Sommet.h:7: note: candidates are: bool operator==(const Sommet&, const Sommet&) Thanks ! EDIT This is how i used std::count() : for(vector<Sommet>::iterator iter = m_sommets.begin(); iter != s_iter_end; iter++) { iter->SetNbSuccesseurs(count(m_sommets.begin(), m_sommets.end(), iter)); }
It looks like you are passing in an iterator as the last parameter to std::count whereas you need to pass in a value (by const reference). Post edit: it looks like I was correct, you are passing iter which is an iterator. You need to dereference it first. Try passing *iter instead.
1,549,184
1,549,199
Something like print END << END; in C++?
Is there anyway to do something like PHP's print << END yadayadayada END; in C++? (multi-line, unescaped, easy-to-cut-and-paste stream insertion)
This answer is now out of date for modern C++ - see sbi's answer for the modern way. This is the best you can do: std::cout << "This is a\n" "multiline\n" "string.\n"; Not as convenient as a proper heredoc, but not terrible.
1,549,447
1,549,460
Why is MSVC throwing a tantrum compiling a macro while G++ is all about zen?
Under MSVC 9.0, this fails. Under g++ this compiles. If we take out the macro then the non-macro version 76-79 compiles. Any ideas? 03: #include <iostream> 04: #include <sstream> 67: #define MAKESTRING(msg, v) \ 68: do { \ 69: std::ostringstream s; \ 70: s << msg; \ 71: v = s.str(); \ 72: } while(false) 73: 74: int main(void) 75: { 76: std::ostringstream oss; 77: std::string str; 78: oss << "foo" << "bar"; 79: str = oss.str(); 80: 81: MAKESTRING("foo" << "bar", str); 82: } testenv.cpp(71) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int testenv.cpp(71) : error C2065: 's' : undeclared identifier testenv.cpp(71) : error C2228: left of '.str' must have class/struct/union 1> type is ''unknown-type'' testenv.cpp(72) : error C2059: syntax error : '}' testenv.cpp(72) : error C2143: syntax error : missing ';' before '}' testenv.cpp(72) : error C2059: syntax error : '}' testenv.cpp(75) : error C2143: syntax error : missing ';' before '{' testenv.cpp(75) : error C2447: '{' : missing function header (old-style formal list?) testenv.cpp(81) : error C2017: illegal escape sequence testenv.cpp(126) : fatal error C1004: unexpected end-of-file found
I would make sure that you don't have any trailing whitespace after the backslashes that you use to separate the lines of your macro. Since the compiler is reporting line numbers that are within your macro definition, it means the preprocessor hasn't quite done what you expect. Also try running this with the MSVC /E compile option to see what the preprocessed source looks like. Actually, even in the source code you pasted into your question, there is a trailing space on line 70. :)
1,549,634
1,550,136
Qt: QImage always saves transparent color as black
How do I save a file with transparency to a JPEG file without Qt making the transparent color black? I know JPEG doesn't support alpha, and the black is probably just a default "0" value for alpha, but black is a horrible default color. It seems like this should be a simple operation, but all of the mask and alpha functions I've tried are ignored when saving as JPEG. For example: image->load("someFile.png"); // Has transparent background or alpha channel image->save("somefile.jpg", "JPG"); // Transparent color is black I've tried filling the image with white before saving as a JPEG, converting the image to ARGB32 (with 8-bit alpha channel) before saving, and even tried ridiculously slow stuff like: QImage image2 = image1->convertToFormat(QImage::Format_ARGB32); image2.setAlphaChannel(image1->alphaChannel()); image2.save(fileURI, "JPG", this->jpgQuality; // Still black! See: http://67.207.149.83/qt_black_transparent.png for a visual.
I'd try something like this (i.e., load the image, create another image of the same size, paint the background, paint the image): QImage image1("someFile.png"); QImage image2(image1.size()); image2.fill(QColor(Qt::white).rgb()); QPainter painter(&image2); painter.drawImage(0, 0, image1); image2.save("somefile.jpg", "JPG");
1,549,843
1,549,902
c/c++ XML library question
I know that a lot of c/c++ XML library questions have been asked already (I tried to read through all of them before getting to this). Here are the things I'm going to need in my own project: Excellent performance SAX2 Validation Open source Cross platform I was going to use Xerces-C, but I see that a simple SAX2 setup with nothing going on in the filter is taking 5 seconds to run. (Perhaps I'm doing something wrong here?) I would like to use libxml++, but as I tried to get it set up on my MacBook, there were some crazy dependencies that took me all the way back to gtk-doc, at which point I sort of tabled the idea. So now I'm at libxml2. Is this the way to go? Have I missed an important option, bearing in mind the five requirements above? I don't mind using a (good) c-library like libxml2, but a c++ interface would be nice. (I don't like Xerces-C's API very much.) I am willing to bend on the SAX2 requirement if comparable functionality is available.
Having spent a goodly amount of time on this same problem, it was my conclusion that libxml2 is the best option available under your guidelines. The C interface is not too difficult to use and it's very fast. There are some other good options for commercial libraries, but most of the other comparable open-source options are either painfully slow or are mired in a deep, annoying vat of dependency soup.
1,549,869
1,549,876
What does const mean following a function/method signature?
According to MSDN: "When following a member function's parameter list, the const keyword specifies that the function does not modify the object for which it is invoked." Could someone clarify this a bit? Does it mean that the function cannot modify any of the object's members? bool AnalogClockPlugin::isInitialized() const { return initialized; }
It means that the method do not modify member variables (except for the members declared as mutable), so it can be called on constant instances of the class. class A { public: int foo() { return 42; } int bar() const { return 42; } }; void test(const A& a) { // Will fail a.foo(); // Will work a.bar(); }
1,549,930
1,549,937
C++ equivalent of Java's toString?
I'd like to control what is written to a stream, i.e. cout, for an object of a custom class. Is that possible in C++? In Java you could override the toString() method for similar purpose.
In C++ you can overload operator<< for ostream and your custom class: class A { public: int i; }; std::ostream& operator<<(std::ostream &strm, const A &a) { return strm << "A(" << a.i << ")"; } This way you can output instances of your class on streams: A x = ...; std::cout << x << std::endl; In case your operator<< wants to print out internals of class A and really needs access to its private and protected members you could also declare it as a friend function: class A { private: friend std::ostream& operator<<(std::ostream&, const A&); int j; }; std::ostream& operator<<(std::ostream &strm, const A &a) { return strm << "A(" << a.j << ")"; }
1,549,941
1,549,960
Perfect square and perfect cube
Is there any predefined function in c++ to check whether the number is square of any number and same for the cube..
No, but it's easy to write one: bool is_perfect_square(int n) { if (n < 0) return false; int root(round(sqrt(n))); return n == root * root; } bool is_perfect_cube(int n) { int root(round(cbrt(n))); return n == root * root * root; }
1,549,949
1,549,962
Segmentation fault only when I redirect stdout to /dev/null?
I've got a C++ unit test that produces useful output to stderr, and mostly noise (unless I'm debugging) to stdout, so I'd like to redirect the stdout to /dev/null. Curiously enough, doing this seems to cause a segmentation fault. Is there any reason why code might seg fault with "> /dev/null" and run fine otherwise? The output is produced entirely by printfs, if that has any bearing. It is difficult for me to post the offending code because it is research being submitted for publication. I'm hoping there is an "obvious" possible cause based on this description. post mortem The segfault was being caused by code like this: ArrayElt* array = AllocateArrayOfSize(array_size); int index = GetIndex(..) % array_size; ArrayElt elt = array[index]; For the umpteenth time, I forgot that x % y remains negative when x is negative in C/C++. Ok, so why was it only happening when I redirected to /dev/null? My guess is that the invalid memory address I was accessing was in an output buffer for stdout - and this buffer isn't allocated when it isn't needed. Thanks for the good answers!
There is no 'normal' reason for I/O to stdout to trigger a core dump when standard output is redirected to /dev/null. You most probably have a stray pointer or a buffer overflow that triggers the core dump when sent to /dev/null and not when sent to standard output - but it will be hard to spot the problem without the code. It is conventional to put the useful information on standard output and the noise on standard error.
1,549,990
1,550,034
in which area is c++ mostly used?
I've been asked many times by my juniors about the areas in which C++ is widely used. I usually answer Operating Systems. Are there any other areas where its extensively used?
A quite large and probably quite definitive list of software written in C++ can be found at Bjarne Stroustrup's homepage.
1,550,070
1,550,085
changing part of a file in C++
Consider i have a file, 'emp.txt' whose content is, EmpNo. Name Phone No. Salary 1 ABC 123 321 2 CBA 456 543 Now i want to change the phone no. 1st Employee alone. When i tried using ios:ate, all the contents of the file got deleted and the new phone no. got inserted. How can i solve this?
If you open a file for just output, the library usually truncates the existing file. To change the existing contents of a file, the easiest way is to open it in 'read/write' mode so that you can seek to the correct position and partially overwrite its contents. Try something like: std::fstream filestream( "emp.txt", std::ios_base::in | std::ios_base::out ); or if you're using C streams: FILE* f = fopen( "emp.txt", "r+" );
1,550,091
1,550,106
How to compare two pointers to object by their most derived type?
I have a following class hierarchy: class Base{ .... virtual bool equal(Base *); } class Derived1: public Base{ .... virtual bool equal(Base *); } class Derived2: public Derived1{ } class Derived3: public Derived1{ } class Derived4: public Base{ } How I should write Base::equal(Base *) function such that compares Derived4 and similar classed? They don't have data fields, so check only that actual objects are of same derived class. And how to write Derived1::equal(Base) - the Derived2 and Derived3 are similar they don't have any data field and the should be compared by data fields in Derived1 and check that objects are from the same derived class? Update: I want this because I don't want to write identical functions to each Derived class such as: bool Derived::equal(Base *b){ Derived *d = dynamic_cast<Derived*>(b); return d; }
I think you can use typeid operator here. You can do something like: typeid(*pointerBase) == typeid(*this); But why do you want to do something like this? It looks very suspicious, I suggest to take a relook at the design.
1,550,292
1,550,300
C++: Element types in a tuple
std::pair has the nested typedefs first_type and second_type which give the type of the first and second element respectively. But is there any way to statically determine the type of the Nth element in a boost::tuple (or std::tuple in C++0x)? I know I could create my own template with N as a parameter, and use it to recursively traverse the cons list of the tuple, but is there a standard way of doing this?
http://www.boost.org/doc/libs/1_40_0/libs/tuple/doc/tuple_advanced_interface.html In C++0x it will work similarly. But I think it has been renamed to tuple_element<I,T>::type
1,550,315
1,550,357
How to catch exception from CloseHandle()
As of the MSDN spec, CloseHandle throws an Exception if an invalid handle is passed to it when it runs under a debugger. Since I want to have clean code, I've inserted some code to catch it. However, it doesn't work, the exception gets uncaught. #include <windows.h> #include <tchar.h> #include <exception> /* omitted code */ CloseHandle(myHandle); // close the handle, the handle is now invalid try { success = CloseHandle(myHandle); } catch (std::exception& e) { _tprintf(TEXT("%s\n"), e.what()); } catch (...) { _tprintf(TEXT("UNKNOWN\n")); } I get the following two errors from the debugger: First-chance exception: 0xC0000008: An invalid handle was specified. Uncaught exception: 0xC0000008: An invalid handle was specified. I think that the first-chance exception is normal, since it gets fired before the catch statement should get it. However, the uncaught exception makes me wondering what's actually wrong here.
You have two options: Option 1: Use SEH, you need to write something like this: __try { // closeHandle } __except(EXCEPTION_EXECUTE_HANDLER) { // print } Option 2: Use the compiler switch /EHa, which will instruct the compiler to emmit code which will allow you to handle SEH exception via C++ style exception handling: try { // close handle } catch (...) { // print } Edit: Note that CloseHandle() only raises an exception if a debugger is attached to your process. From the documentation: If the application is running under a debugger, the function will throw an exception if it receives either a handle value that is not valid or a pseudo-handle value.
1,550,329
1,550,334
How can I indent cout output?
I'm trying to print binary tree void print_tree(Node * root,int level ) { if (root!=NULL) { cout<< root->value << endl; } //... } How can I indent output in order to indent each value with level '-' chars.
You can construct a string to contain a number of repitions of a character: std::cout << std::string(level, '-') << root->value << std::endl;
1,550,354
1,550,405
Visual C++ studio, recompiling only the modified files
I have two dll files made by around 1500 cpp files. When I need to edit one, I usually then recompile all the 1500 files from the start. But I heard there is a way to make Visual Studio recompile the modifies only, taking a lot less time... How do I do this?
VS is actually pretty good in doing the dependency checks so that only necessary stuff is re-compiled. I can see a couple of (more or less likely) reasons for what you're seeing: You modify a header and that's been included everywhere. You're hitting "rebuild" instead of "build". You have included a cpp file. Something's fishy with your projects, your disk, or your date. That's in what I consider decreasing probability order.
1,550,370
1,550,459
C++: Polymorphic class template
Consider a class Calendar that stores a bunch of Date objects. The calendar is designed to hold a collection of any type of objects that inherit from Date. I thought the best way to do it is to have a class template such as template<typename D> class Calendar{ ... } But it struck me that D can now in fact be any class. My question is now, how can I make sure that D is a subclass of the date object? I know how to do this is Java, but I'm still unfamiliar with the C++ syntax. The problem is very much similar to how some collections can only take a template variables that implement Comparable. The header would then look something like public class Calendar<D extends Date>{ ... } --------------------EDIT: ------------------------------------------ The template argument defines which actual day the calendar refers to. Different date types refer to the same day in different formats. For instance, if I make a Calendar<Gregorian> it will be able to take dates in another Date format, say the Julian calendar, or any other date format and present them in Gregorian format. This enables for conversion between calendars in different date formats. So, if I have a Calendar<Gregorian> I can easily convert it into a Calendar<Julian>. Then the following is possible: Calendar<Gregorian> cal; std::cout << "These events are entered as dates in the Gregorian calendar" << std::endl; cal.add_event("Christmas", 12, 25); cal.add_event("Gregorian new year", 1, 1); std::cout << cal << std::endl; std::cout << "----" << std::endl; std::cout << "And printed out as Julian dates" << std::endl; Calendar<Julian>(cal); std::cout << cal<< std::endl; and outputs: These events are entered as dates in the Gregorian calendar 2009-12-25 Christmas 2010-01-01 Gregorian new year ---- And printed out as Julian dates 2009-12-13 Christmas 2009-12-19 Gregorian new year ------------- New edit: ---------------------- The last edit now makes more sense. I had a slight disagreement with the formatting. Thanks for all the answers. I'm a Computer Science student on my third year, and I'd say I'm fairly familiar with OO and related concepts like Polymorphism etc. The purpose of this post was to find out whether or not there was a way in C++ to express a condition for a template argument the same way that it is in Java and solve the problem in a concise, elegant and intuitive way.
I know how to do this is Java, but I'm still unfamiliar with the C++ syntax. The problem is very much similar to how some collections can only take a template variables that implement Comparable. The header would then look something like public class Calendar<D extends Date>{ ... } True, it is the same problem, and in C++, it is usually solved by ignoring it. Why do we need to enforce that the object must implement IComparable? In Java, it's necessary because of its anemic type system. Without this constraint, we'd be unable to compare objects. In C++, the rules are different. Containers simply try to compare the objects they store, and if the type doesn't support it, you get a compile error. No interfaces or inheritance is required. And you'd typically do the same in your Calendar class. Simply don't enforce the "must subclass form Date constraint. Instead, specify the members the type must expose, and what, if any, semantics should be expected from them. For example, if your Calendar attempts to do the following operations, for date objects d0 and d1: d0.getDay(); d0.getTime(); Time t = d0 - d1; Then those are the operations that should be supported. Any class which supports these operations is a valid Date class, even if it doesn't subclass anything.
1,550,561
1,550,570
Prepending a string to another string
Currently, I have this code to prepend a "tag" to an exception message which gives me a very light version of a stack trace: try { doSomething(); } catch (std::exception& e) { int size = 8 + _tcslen(e.what()); TCHAR* error = new TCHAR[size]; _sntprintf(error, size, TEXT("myTag: %s"), e.what()); std::exception x = std::exception(error); delete []error; throw x; } It just looks horrible and I'm sure that there has to be an easy way to accomplish this. Could you please help me with this?
what about something like this: throw std::exception(std::string("myTag: ").append(e.what()).c_str()); Added a call to c_str() and tested it in Visual Studio and it works (side note: this doesn't compile in gcc, there's only a default constructor in the implementation).
1,550,648
1,550,675
template which enforces interface
Is it possible to create a template accepting types which implement certain interface? For example, I want to say to template user: you can store anything in my container as long as it implements Init() and Destroy() methods. Thanks
A limited subset of the (intended, but unfortunately cut) C++0x functionality of concepts is provided by the Boost Concept Check library. You can harness it by creating a concept check class for your required interface.
1,550,686
1,550,696
Are c styled strings safe?
In c/c++ some people use c-styled strings like: char *str = "This is a c-styled string"; My question is is this safe? The way I see it is they created a char pointer that points to the first letter of a const array of chars, but can't some other thing eg another variable overwrite a portion of the char array in the memory? Thus causing str to be logically invalid?
These days string constants are placed in read-only sections of your binary. If you attempt to write to an address in a read-only section the CPU's memory management unit will cause a fault and your application will get an access violation or segmentation fault or some other operating system dependent behavior. Also, compilers warn if you declare the type of the string constant to be non const.
1,550,721
1,551,253
python struct.pack equivalent in c++
I want a fixed length string from a number just like struct.pack present in python but in c++. I thought of itoa (i,buffer,2) but problem can be that its length will depend on platform. Is there any way to make it independent of platform ?
If you're looking for a complete solution similar to Python's struct package, you might check out Google's Protocol Buffers Library. Using that will take care of a lot of issues (e.g. endian-ness, language-portability, cross-version compatibility) for you.
1,550,770
1,550,786
How to check for division by 7 for big number in C++?
I have to check, if given number is divisible by 7, which is usualy done just by doing something like n % 7 == 0, but the problem is, that given number can have up to 100000000, which doesn't fit even in long long. Another constrain is, that I have only few kilobytes of memory available, so I can't use an array. I'm expecting the number to be on stdin and output to be 1/0. This is an example 34123461273648125348912534981264376128345812354821354127346821354982135418235489162345891724592183459321864592158 0 It should be possible to do using only about 7 integer variables and cin.get(). It should be also done using only standard libraries.
Think about how you do division on paper. You look at the first digit or two, and write down the nearest multiple of seven, carry down the remainder, and so on. You can do that on any abritrary length number because you don't have to load the whole number into memory.
1,550,844
1,550,863
How to use string indexes in c++ arrays (like php)?
How can I use a string index in a c++ array (like in php)?
You could use std::map to get an associative container in which you can lookup values by a string index. A map like std::map<std::string, int> would associate integer values with std::string lookup keys.
1,550,904
1,553,597
Stuck building a game engine
I'm trying to build a (simple) game engine using c++, SDL and OpenGL but I can't seem to figure out the next step. This is what I have so far... An engine object which controls the main game loop A scene renderer which will render the scene A stack of game states that can be pushed and popped Each state has a collection of actors and each actor has a collection of triangles. The scene renderer successfully sets up the view projection matrix I'm not sure if the problem I am having relates to how to store an actors position or how to create a rendering queue. I have read that it is efficient to create a rendering queue that will draw opaque polygons front to back and then draw transparent polygons from back to front. Because of this my actors make calls to the "queueTriangle" method of the scene renderer object. The scene renderer object then stores a pointer to each of the actors triangles, then sorts them based on their position and then renders them. The problem I am facing is that for this to happen the triangle needs to know its position in world coordinates, but if I'm using glTranslatef and glRotatef I don't know these coordinates! Could someone please, please, please offer me a solution or perhaps link me to a (simple) guide on how to solve this. Thankyou!
A 'queueTriangle' call sounds to me to be very inefficient. Modern engines often work with many thousands of triangles at a time so you'd normally hardly ever be working with anything on the level of a single triangle. And if you were changing textures a lot to accomplish this ordering then that is even worse. I'd recommend a simpler approach - draw your opaque polygons in a much less rigorous order by sorting the actor positions in world space rather than the positions of individual triangles and render the actors from front to back, an actor at a time. Your transparent/translucent polygons still require the back-to-front approach (providing you're not using premultiplied alpha) but everything else should be simpler and faster.
1,550,910
1,550,926
C++ and Java performance
this question is just speculative. I have the following implementation in C++: using namespace std; void testvector(int x) { vector<string> v; char aux[20]; int a = x * 2000; int z = a + 2000; string s("X-"); for (int i = a; i < z; i++) { sprintf(aux, "%d", i); v.push_back(s + aux); } } int main() { for (int i = 0; i < 10000; i++) { if (i % 1000 == 0) cout << i << endl; testvector(i); } } In my box, this program gets executed in approx. 12 seconds; amazingly, I have a similar implementation in Java [using String and ArrayList] and it runs lot faster than my C++ application (approx. 2 seconds). I know the Java HotSpot performs a lot of optimizations when translating to native, but I think if such performance can be done in Java, it could be implemented in C++ too... So, what do you think that should be modified in the program above or, I dunno, in the libraries used or in the memory allocator to reach similar performances in this stuff? (writing actual code of these things can be very long, so, discussing about it would be great)... Thank you.
You have to be careful with performance tests because it's very easy to deceive yourself or not compare like with like. However, I've seen similar results comparing C# with C++, and there are a number of well-known blog posts about the astonishment of native coders when confronted with this kind of evidence. Basically a good modern generational compacting GC is very much more optimised for lots of small allocations. In C++'s default allocator, every block is treated the same, and so are averagely expensive to allocate and free. In a generational GC, all blocks are very, very cheap to allocate (nearly as cheap as stack allocation) and if they turn out to be short-lived then they are also very cheap to clean up. This is why the "fast performance" of C++ compared with more modern languages is - for the most part - mythical. You have to hand tune your C++ program out of all recognition before it can compete with the performance of an equivalent naively written C# or Java program.
1,550,997
1,551,248
CreateProcessWithLoginW - Redirecting STDOUT
What I would like is to have the process start but have the input and output all be in the same console. if(CreateProcessWithLogonW(user,domain, pass, LOGON_WITH_PROFILE, NULL, cmd, 0, 0, 0, &sa, &pe)) { printf("[~] Process spawned with PID %X\n", pe.dwProcessId); } else { printf("[!] Failed to create process. Error Code: %X\n", GetLastError()); } When I use this code it creates a whole new window instead of having it in the same window. Is there a way to unset the "CREATE_NEW_CONSOLE" flag because even when I set it to 0 it still creates a new console.
According to help on this method: The CREATE_DEFAULT_ERROR_MODE, CREATE_NEW_CONSOLE, and CREATE_NEW_PROCESS_GROUP flags are enabled by default— even if you do not set the flag, the system functions as if it were set. It looks like Windows API doesn't allow these flags not to be set.
1,551,085
1,551,116
Standard practice for implementing threads in C++?
I'm looking forward to an interview in C++ in the coming weeks. (yay) So I have been relearning C++ and studying up. Unfortunately I have realized that I've never implemented threads in C++, and am somewhat concerned about a quiz on concurrency. As far as I can tell, C++ uses pthreads in Linux and some other device in Windows. Is this correct? Is there another industry standard, more OO way to handle threads in C++ that I should be expected to know? And are there any good web resources that you can point me to for practicing and learning threads in C++? Thanks!
Currently C++ is entirely unaware that threads exist. Different OSes provide threading libraries to make them available. The next version of C++, so called C++0x, is going to make a thread library standard. If I were to start a multithreaded app today I would go with either boost threads or the threads that were a part of any package I might be using i.e. QT or WxWidgets.
1,551,106
1,551,119
How to use string and string pointers in C++
I am very confused about when to use string (char) and when to use string pointers (char pointers) in C++. Here are two questions I'm having. which one of the following two is correct? string subString; subString = anotherString.sub(9); string *subString; subString = &anotherString.sub(9); which one of the following two is correct? char doubleQuote = aString[9]; if (doubleQuote == "\"") {...} char *doubleQuote = &aString[9]; if (doubleQuote == "\"") {...}
None of them are correct. The member function sub does not exist for string, unless you are using another string class that is not std::string. The second one of the first question subString = &anotherString.sub(9); is not safe, as you're storing the address of a temporary. It is also wrong as anotherString is a pointer to a string object. To call the sub member function, you need to write anotherString->sub(9). And again, member function sub does not exist. The first one of the second question is more correct than the second one; all you need to do is replace "\"" with '\"'. The second one of the second question is wrong, as: doubleQuote does not refer to the 10th character, but the string from the 10th character onwards doubleQuote == "\"" may be type-wise correct, but it doesn't compare equality of the two strings; it checks if they are pointing to the same thing. If you want to check the equality of the two strings, use strcmp.
1,551,333
1,551,426
Data structures for real time applications
We are designing a p2p applications using c++ which transmits voice to other peer using UDP. We are capturing a mic signal in a buffer in the thread which captures voice for one second in the while loop. For every second voice captured in buffer it splits it into packets and sends to the other peer. Now I need a proper data structure at the destination which is copes real time transmission. Same data structure I am going to use for screen capturing. Here are two approaches using queue I thought of Implementing a queue using a linked list which maintains a queue of OneSecVoice objects or Image object in case of image. Implementing a queue using static array of OneSecVoice or Image objects OneSecVoice/Image objects will contain a total number of packets, packets buffer for that particular Image/OneSecVoice. As its a real time one thread will continuously scan for queue and take out latest complete Image/OneSecVoice by popping the Image/OneSecVoice from queue. So which to chose Implementing a queue using a linked list or Implementing a queue using static array. Me and my friend are having fight over this so we decided to post here.
I would use boost::circular_buffer. You will get the cache benefits having a fixed memory area and no unexpected memory allocations. In order to achieve maximum efficiency, the circular_buffer stores its elements in a contiguous region of memory, which then enables: Use of fixed memory and no implicit or unexpected memory allocation. Fast constant-time insertion and removal of elements from the front and back. Fast constant-time random access of elements. Suitability for real-time and performance critical applications. Possible applications of the circular_buffer include: Storage of the most recently received samples, overwriting the oldest as new samples arrive. As an underlying container for a bounded buffer (see the Bounded Buffer Example). A kind of cache storing a specified number of last inserted elements. Efficient fixed capacity FIFO (First In, First Out) or LIFO (Last In, First Out) queue which removes the oldest (inserted as first) elements when full.
1,551,408
1,551,412
Help me debug this - invalid conversion from 'const char*' to 'char*'
I simply don't see why this error's popping up. Widget.cpp: In constructor 'Widget::Widget(Generic, char*, int, int, int, QObject*)': Widget.cpp:13: error: invalid conversion from 'const char*' to 'char*' Nowhere do I have a 'const char*' in terms of Widget's constructor. class Widget: public QObject { Q_OBJECT Q_PROPERTY(char *col READ getCol WRITE setCol) Q_PROPERTY(char *row READ getRow WRITE setRow) Generic visitor; char *_name; char *_widget_base; int _row; int _col; int _type; public: Widget(Generic visitor, char *name, int row, int col, int type, QObject *parent); char* widgetBase() const; QString getCol() const; void setCol(const QString &col); QString getRow() const; void setRow(const QString &row); }; Widget::Widget(Generic v, char *name, int row, int col, int type, QObject *parent = 0 ) { visitor = v; std::string str(name); int pos1 = str.find(":"); int pos2 = str.rfind(":"); _widget_base = str.substr(pos1, pos2-pos1).c_str(); _name = name; _row = row; _col = col; _type = type; }
This is a const char * value str.substr(pos1, pos2-pos1).c_str();
1,551,510
1,551,531
return a list<int> from a function c++
Every time I try to use my add function and return a list from it. I get an undefined symbol error. What am I doing wrong here. this is the error: Undefined first referenced symbol in file add(std::list<int, std::allocator<int> > const&, std::list<int, std::allocator<int> >)/var/tmp//cc78hUrW.o ld: fatal: Symbol referencing errors. No output written to a.out collect2: ld returned 1 exit status #include <iostream> #include <list> #include <math.h> using namespace std; list<int> add(const list<int> &lhs, const list<int> $rhs); list<int> sub(const list<int> &lhs, const list<int> $rhs); list<int> mul(const list<int> &lhs, const list<int> &rhs); int main(int argc, char* argv[]) { /*variables*/ list<int> num1, num2, num3; list<int> ::iterator it1, it2, it3; char temp[1001]; int x = 0, y = 0; it1 = num1.begin(); for(x = 0; x <= 1001; x++) temp[x] = -42; cout << "Number 1: "; cin >> temp; for(x = 0; temp[x] != -42; x++) num1.insert(it1, temp[x] - '0'); for(x = 0; x <= 1001; x++) temp[x] = -42; cout << "Number 2: "; cin >> temp; it2 = num2.begin(); for(x = 0; temp[x] != -42; x++) num2.insert(it2, temp[x] - '0'); it1 = num1.end(); it1--; num1.erase(it1); for(it1 = num1.begin(); it1 != num1.end(); it1++) cout << *it1; cout << endl; it2 = num2.end(); it2--; num2.erase(it2); for(it2 = num2.begin(); it2 != num2.end(); it2++) cout << *it2; cout << endl; num3 = add(num1, num2); for(it3 = num3.begin(); it3 != num3.end(); it3++) cout << *it3; cout << endl; return 0; } list<int> add(const list<int> &lhs,const list<int> &rhs) { /*Variables*/ list<int> left = lhs; list<int> right = rhs; list<int> answer; list<int>::iterator itl, itr, ans; int cary = 0; int sum = 0; int lfint = 0, rtint = 0; int lsize=0, rsize=0; lsize = (int)left.size(); rsize = (int)right.size(); while(lsize < rsize) { itl = left.end(); left.insert(itl, 0); lsize = (int)left.size(); } while(rsize < lsize) { itr = right.end(); right.insert(itr, 0); rsize = (int)right.size(); } itl = left.begin(); itr = right.begin(); ans = answer.begin(); while(itl != left.end()) { lfint = *itl; rtint = *itr; sum = lfint + rtint; sum = sum + cary; cary = 0; if(sum >= 10) { sum = sum - 10; cary = 1; } answer.insert(ans, sum); itl++; itr++; } if(cary == 1) { answer.insert(ans, 1); } return answer; }
You used a $ instead of a & when you declared add() here... list<int> add(const list<int> &lhs, const list<int> $rhs);
1,551,539
1,551,555
What is the preferred design of a template function that requires a default parameter value?
I'm currently working on cleaning up an API full of function templates, and had a strong desire to write the following code. template <typename T, typename U, typename V> void doWork(const T& arg1, const U& arg2, V* optionalArg = 0); When I invoke this template, I would like to do so as follows. std::string text("hello"); doWork(100, 20.0, &text); doWork('a', text); // oops! doWork<char, std::string, void>('a', text); // to verbose! Unfortunately, the second invocation doesn't compile since the compiler cannot deduce the type of the optional parameter. This is unfortunate, since I really don't care what the parameter type is, but rather that its value is NULL. Also, I'd like to avoid the route of the third invocation since it hampers readability. This lead me to try to make the template argument V have a default type, which also doesn't work since you cannot apply a default type to a function template argument (at least using VC++ 9.0). template <typename T, typename U, typename V = void> // oops! void doWork(const T& arg1, const U& arg2, V* optionalArg = 0); My only remaining option is to introduce an overload of doWork that knows nothing of the template argument V. template <typename T, typename U> void doWork(const T& arg1, const U& arg2) { doWork(arg1, arg2, 0); } template <typename T, typename U, typename V> void doWork(const T& arg1, const U& arg2, V* optionalArg); Is this the best approach to solving this problem? The only drawback I see is that I could potentially introduce many trivial forwarding functions if a function template contains many parameters that have suitable defaults.
I think that your forwarding function is a perfectly suitable solution, although in your solution, won't you have to explicitly specify the template parameters? (0 is an integer constant that can be coverted to any V* type.) Also doWord vs doWork? As a general rule, try to avoid optional parameters where they don't have a very strong pay-off. It might be easier to force clients of you function to just add a , (void*)0 if appriopriate than add to much extra mechanism to support both a two parameter and a three parameter version of the template. It depends on the expected uses, though.
1,551,544
1,551,585
Reading in image files without specifying name
Are there any facilities in SDL or C++ that allow you to read image files in from a folder without specifying their name, like reading them in sequential order, etc.? If not are there any techniques you use to accomplish something along the same lines? Doing something like this: foo_ani[0] = LoadImage("Animations/foo1.png"); foo_ani[1] = LoadImage("Animations/foo2.png"); foo_ani[2] = LoadImage("Animations/foo3.png"); can become quite tedious, and a loop can't be used because the file name is specific each time. The only way I could really think of is maybe having a string that you modify through each loop iterator and insert the loop number into the specific part of the string assuming that's how your files are labeled, and using that string as the LoadImage parameter. That seems like more work though than just doing the above.
Use boost::filesystem. The tiny program shown here lists all files in the directory files/, matching the pattern fileN.type, where N is from 0 and upwards, unspecified. #include <iostream> #include <sstream> #include <string> #include <boost/filesystem.hpp> using namespace std; namespace fs = boost::filesystem; int main(int argc, char** argv) { fs::path dir ("./files"); string prefix = "file"; string suffix = "type"; int i = 0; fs::path file; do { stringstream ss; ss << prefix << i++ << "." << suffix; file = fs::path(dir / fs::path(ss.str())); if(fs::exists(file)) { cout << file.leaf() << " exists." << endl; } } while(fs::exists(file)); return 0; } Link with -lboost_filesystem. boost::filesystem also provides a simple directory iterator.
1,551,777
1,551,786
Can the attributes of a class be an array?
I'm new to OOP, so please bear with me if this is a simple question. If I create a class, which has attributes "a", "b", and "c", is it possible for the attributes to be an array, such that attribute a[2] has a meaning?
Member variables can ofcourse be arrays. Example: class MyClass { int a[3]; // Array containing three ints int b; int c; };
1,551,829
1,551,852
Can I delete a dynamically allocated class using a function within that class?
I'm writing a state manager for a game. I've got most of the logic down for how I want to do this. I want states, which will be classes, to be handled in a stack in the StateManager class. Each state will have pause functions, and the stack will be an STL stack. When a state is done with what it needs to do (example: from the pause screen, the user clicks "return to game") it needs to be removed from the stack and deleted. My current logic (which I have been unable to test, unfortunately) would be this: State finishes its job. In its update function, when it finds that its done, it will call a function to clean up the state. This function will take care of any immediate loose ends that need to be tied (if there are any), call the pop function from the state manager stack, and delete itself. What I'm asking is: can I delete a class from within itself?
See C++-FAQ-lite: Is it legal (and moral) for a member function to say delete this? As long as you're careful, it's OK for an object to commit suicide (delete this).
1,551,842
1,551,853
Why are most of the biggest open source projects in C?
I'm having a debate with a friend and we're wondering why so many open source projects have decided to go with C instead of C++. Projects such as Apache, GTK, Gnome and more opted for C, but why not C++ since it's almost the same? We're precisely looking for the reasons that would have led those projects (not only those I've listed but all C projects) to go with C instead of C++. Topics can be performance, ease of programming, debugging, testing, conception, etc.
C is very portable, much more than C++ was 10 years ago. Also, C is very entrenched in the Unix tradition. Read more in 'The Art of Unix Programming', about Unix and OO in general, and about specific languages on unix (including C and C++).
1,551,997
1,552,030
How to disable visual C++ memory leak checking for a particular file?
One of my projects is making use of Microsoft's supplied memory leak checker via _CrtSetDbgFlag etc. This is working fine except that I now want to make use of a third-party package which is leaking a small amount of memory. I have no particular need to fix the leaks, but the output is annoying since it will disguise "genuine" leaks that may be introduced. How does one go about disabling this leak checking for a particular file or project, but leave it on for others? My understanding is that it gets enabled via some #define in debug mode - I've had a bit of a fiddle but haven't managed to find something which I can #undef to switch it off.
You can deactive the heap allocation checker in the concerned files by use of _CrtSetDbgFlag() and the macro _CRTDBG_CHECK_DEFAULT_DF (which is equal to 0) before the first new instruction in a file where you don't want to check memory leaks and reactive it just after the new instructions. See MSDN here. Another way only for MFC projects: I personally use the DEBUG_NEW macro to detect memory leaks. In each file of my project I have added the macro. If you don't put the macro in a file, memory leaks will not be found in it but only in the others. The macro is explained here.
1,552,058
1,552,104
How to implement precompiled headers into your project
I understand the purpose and reasoning behind precompiled headers. However, what are the rules when implementing them? From my understanding, it goes something like this: Set your project up to use precompiled headers with the YU directive. Create your stdafx.h file and set that to be your precompiled header. Include this as the top include statement in each of your .h files. It this correct? Should you exclude the including it in the files that are included within your precompiled header? Currently, I get the following compilation error when following my intuition with this: error C2857: '#include' statement specified with the /Ycstdafx.h command-line option was not found in the source file The command-line options are as such: /Od /I "../External/PlatformSDK/Include" /I ".." /I "../External/atlmfc/Include" /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /Gm /EHsc /RTC1 /MDd /Yc"stdafx.h" /Fp"....\Output\LudoCore\Debug\LudoCore.pch" /Fo"....\Output\LudoCore\Debug\" /Fd"....\Output\LudoCore\Debug\vc80.pdb" /W4 /WX /nologo /c /ZI /TP /wd4201 /errorReport:prompt
You stdafx.cpp should include stdafx.h and be built using /Yc"stdafx.h". Your other *.cpp should be include stdafx.h and be built using /Yu"stdafx.h". Note the double-quote characters used in the compiler options! Here's a screenshot of the Visual Studio settings for stdafx.cpp to create a precompiled header: Here are the corresponding command-line options (which are read-only but reflect the settings specified on other pages; note that the IDE inserts double-quote characters around the filename, in the compiler option): This is what's in my stdafx.cpp file: // stdafx.cpp : source file that includes just the standard includes // CallWinsock.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
1,552,069
1,552,762
Undefined reference to vtable. Trying to compile a Qt project
I'm using Code::Blocks 8.02 and the mingw 5.1.6 compiler. I'm getting this error when I compile my Qt project: C:\Documents and Settings\The Fuzz\Desktop\GUI\App_interface.cpp|33|undefined reference to `vtable for AddressBook' File AddressBook.h: #ifndef ADDRESSBOOK_H #define ADDRESSBOOK_H #include <QWidget> class QLabel; class QLineEdit; class QTextEdit; class AddressBook : public QWidget { Q_OBJECT public: AddressBook(QWidget *parent = 0); private: QLineEdit *nameLine; QTextEdit *addressText; }; #endif File AddressBook.cpp: #include <QtGui> #include "addressbook.h" AddressBook::AddressBook(QWidget *parent) : QWidget(parent) { QLabel *nameLabel = new QLabel(tr("Name:")); nameLine = new QLineEdit; QLabel *addressLabel = new QLabel(tr("Address:")); addressText = new QTextEdit; QGridLayout *mainLayout = new QGridLayout; mainLayout->addWidget(nameLabel, 0, 0); mainLayout->addWidget(nameLine, 0, 1); mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop); mainLayout->addWidget(addressText, 1, 1); setLayout(mainLayout); setWindowTitle(tr("Simple Address Book")); }
Warning: Do not do this if you already have a .pro file - you'll lose it! In order to automatically ensure that all moc cpp files are generated, you can get qmake to automatically generate a .pro file for you instead of writing one yourself. Run qmake -project in the project directory, and qmake will scan your directory for all C++ headers and source files to generate moc cpp files for.
1,552,098
1,552,245
ImpersonateLoggedOnUser doesn't appear to work
After a successful call to both LogonUser and ImpersonateLoggedOnUser it doesn't appear that my process is running as the new user... system("whoami"); prints out: Chris-PC\Chris when it should be: Chris-PC\LimitedGuy Is there a function I'm not calling or something? My code: if(argc == 6) // impersonate { printf("[~] Logging in as %ws\\\\%ws..\n", argv[3], argv[4]); if(!LogonUser(argv[4], argv[3], argv[5], LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &logonToken)) { printf("[!] Failed to login as %ws. Error Code: %X\n", argv[4], GetLastError()); return 1; } if(!ImpersonateLoggedOnUser(logonToken)) { printf("[!] ImpersonateLoggedOnUser failed with error code: %X\n", GetLastError()); return 1; } LoadUserProfile(logonToken, &plinfo); system("whoami"); printf("[~] Login successful!\n"); }
When you use the system call a new process is created to execute the command but in Windows the new process is always created with the token from the parent process not the thread (unless you specifically use one of the CreateProcessAsUser, CreateProcessWithLogonW, etc. calls). So in your case 'whoami' is executed in the context of the original user not the one impersonating. To check the name of the user being impersonated call GetUserName.
1,552,170
1,552,183
Help with error: ISO C++ forbids declaration of 'vector' with no type
As the title states, I'm not sure why I'm getting this error. I've put together a test.cpp that's similar to this structure, and it works fine. Also, other than the vector problem, there's the other problem about 'protected', which isn't even in the code. I think 'protected' is a macro, so no telling what's there. I'm new to QT, so I'm likely "doing it wrong." That's certainly what the compiler's suggesting. In file included from DrvCrystalfontz.cpp:8: LCDText.h:28: error: ISO C++ forbids declaration of 'vector' with no type LCDText.h:28: error: expected ';' before '<' token LCDText.h:30: error: ISO C++ forbids declaration of 'vector' with no type LCDText.h:30: error: expected ',' or '...' before '<' token LCDText.h:46: error: expected ':' before 'protected' LCDText.h: In constructor 'LCDText::LCDText(int, int, int, int, int, int, int, QObject*)': LCDText.h:33: error: expected '{' at end of input scons: *** [DrvCrystalfontz.o] Error 1 scons: building terminated because of errors. Here's the code. I've numbered the lines noted in the error. #ifndef __LCD_TEXT__ #define __LCD_TEXT__ #include <vector> #include <QObject> #include "LCDBase.h" #include "WidgetText.h" #include "WidgetBar.h" #include "WidgetHistogram.h" #include "WidgetIcon.h" #include "WidgetBignums.h" #include "WidgetGif.h" class LCDText: public LCDBase, public virtual QObject { Q_OBJECT protected: char *LayoutFB; char *DisplayFB; int GOTO_COST; int CHARS; int CHAR0; int LROWS; int LCOLS; int DROWS; int DCOLS; vector<vector<char *> > chars; // Line 28 void (*TextRealWrite) (const int row, const int col, const char *data, const int len); void (*TextRealDefchar) (const int ascii, const vector<char *> matrix); // Line 30 public: LCDText(int rows, int cols, int xres, int yres, int _goto, int chars, int char0, QObject *parent) : LCDBase(xres, yres), QObject(parent); // Line 33 ~LCDText(); void TextInit(int rows, int cols); void TextBlit(int row, int col, int height, int width); void TextClear(); void TextClearChars(); void TextGreet(); void TextDraw(WidgetText widget); void TextBarDraw(WidgetBar widget); void TextHistogramDraw(WidgetHistogram widget); void TextIconDraw(WidgetIcon widget); void TextBignumsDraw(WidgetBignums widget); void TextGifDraw(WidgetGif widget); public signals: // Line 46 void SpecialCharChanged(int ch); public slots: void TextSpecialCharChanged(int ch); }; #endif
Vector resides in the std namespace. You have to do one of the following: Prepend the type with the namespace: std::vector<std::vector<char *> > chars; Tell the compiler you are using vector from the std namespace using std::vector; vector<vector<char *> > chars; Or, tell the compiler you are using the std namespace, which will bring in everything (not recommended, see comments) using namespace std;
1,552,354
1,552,365
Problem overloading the < operator in C++
I have a vector of Student objects which I want to sort using #include <algorithm> and sort(list.begin(), list.end()); In order to do this, I understand that I need to overload the "<" operator but after trying (and failing) with several methods suggested online, I am running out of ideas. Here is my latest attempt: In Student.h... ... using namespace std; class Student { friend bool operator <(const Student& first, const Student& second); public: ... private: ... }; And in Student.cpp... ... #include "Student.h" using namespace std; ... bool operator <(const Student& first, const Student& second) { return first.Name() < second.Name(); } where "Name()" is a constant function which returns a string. The program compiles and runs, but my operator function is never called during the sort and when I tried comparing two Student objects like s1 < s2 I got an "error: overloaded operator not found" How can I correctly overload this operator so that my sort will work as I intend?
I wouldn't use a friend here, and I'm not sure it works at all. What I would use is... class Student { public: bool operator< (const Student& second) const; }; bool Student::operator< (const Student& second) const { return (Name() < second.Name()); } Note the trailing const, indicating that within operator<, *this is constant. EDIT I cannot delete this answer because it was accepted, but I would if I could. I also can't replace it with a correct one. See Drew Dormanns comment below, and Ross Smiths answer.
1,552,495
1,552,513
In C++, how do I push an object to a vector while maintaining a pointer to the object?
In my code, I have a vector of Student objects. vector<Student> m_students; I want to: Check to see if the vector contains any Student of a certain name. If no such Student exists, add a new one. Add data to the Student of that name. Consider the following code: // Check to see if the Student already exists. Student* targetStudent = NULL; for each (Student student in m_students) { if (student.Name() == strName) { targetStudent = &student; break; } } // If the Student didn't exist, add it. if (targetStudent == NULL) { targetStudent = new Student(strName); m_students.push_back(*targetStudent); } // Add the course info to the Student. targetStudent->Add(strQuarter, strCourse, strCredits, strGrade); When I make the call to m_students.push_back(*targetStudent); it seems that the vector "m_students" ends up with a copy of the Student object that "targetStudent" points to at that time. The subsequent attempt to add to targetStudent does not change the object contained in the vector. How can I, starting with a pointer to an object, add that object to a vector and then access the object that is in the vector?
STL containers copy the objects they contain. There is no way to work around this. You can, however, have a std::vector<std::shared_ptr<Student> >, which allow you to have a container of smart pointers. For this to work, though, your objects must all be attached to the shared_ptr at the time of construction. So, something like: std::vector<std::shared_ptr<Student> > m_students; std::shared_ptr<Student> targetStudent; for each (std::shared_ptr<Student> student in m_students) { if (student->Name() == strName) { targetStudent = student; break; } } // If the Student didn't exist, add it. if (!targetStudent) { // creates a new Student and attaches it to smart pointer targetStudent.reset(new Student(strName)); m_students.push_back(targetStudent); } std::shared_ptr is defined in the <memory> header in C++11. (In TR1, you can use std::tr1::shared_ptr instead.) If you're using C++98 without TR1, or need to be portable with it, you can use boost::shared_ptr instead; download from Boost.
1,552,728
1,552,774
Why can't the Nodes be linked together?
EDIT: Is it possible to NOT use new? (do not dynamically allocating memory) I think it is push that is wrong, but I don't know where, how, and why. here is the code: struct Node { string fileName; Node *link; }; int size(Node *&flist) { int count = 0; Node *tempPtr = flist; while (tempPtr != 0) { count += 1; tempPtr->link = (tempPtr->link)->link; } return count; } Node* push(Node *&flist, string name) { Node temp; Node *tempPtr = &temp; temp.fileName = name; temp.link = flist; cout << tempPtr->fileName << endl; cout << (tempPtr->link)->fileName << endl; return tempPtr; } int main( int argc, char *argv[] ) { Node aNode; Node *flist = &aNode; flist->fileName = "a"; flist->link = NULL; push(flist, "b"); int s = size(flist); cout << "size: " << s << endl; } the output is b a size: 0 Thank you.
In your size() function you are modifying the list in the loop. You don't want to modify tempPtr->link but rather just change tempPtr as you iterate. Changing tempPtr won't modify anything permanently. You should also avoid passing flist by reference here as there's no need to modify it. So: int size(Node *flist) { int count = 0; Node *tempPtr = flist; while (tempPtr != 0) { count += 1; tempPtr = tempPtr->link; } return count; } As for push(), the biggest problem is that you're allocating the new node as a local variable which means it'll be on the stack and will get destroyed when the function returns. To create a node that is more permanent you need to allocate it on the heap using the new operator. And again the '&' for flist is unnecessary: Node* push(Node *flist, string name) { Node *tempPtr = new Node; tempPtr->fileName = name; tempPtr->link = flist; cout << tempPtr->fileName << endl; cout << tempPtr->link->fileName << endl; return tempPtr; } Note that the counterpart to new is delete. Since the new nodes are allocated on the heap they will not be destroyed automatically so you will need to manually delete them when you are done with the list. Your goal is to have one delete for every new, so if you new 5 nodes your code should delete 5 nodes when it cleans up. If you don't do this your program will run fine but it will have a small memory leak. (Actually, when it exits all allocated memory is automatically freed. But it's a bad habit to allocate memory and never free it, in general, so you should pretend this automatic cleanup doesn't happen.)
1,552,738
3,946,294
Is there a Java equivalent of frexp?
Is there a Java equivalent of the C / C++ function called frexp? If you aren't familiar, frexp is defined by Wikipedia to "break floating-point number down into mantissa and exponent." I am looking for an implementation with both speed and accuracy but I would rather have the accuracy if I could only choose one. This is the code sample from the first reference. It should make the frexp contract a little more clear: /* frexp example */ #include <stdio.h> #include <math.h> int main () { double param, result; int n; param = 8.0; result = frexp (param , &n); printf ("%lf * 2^%d = %f\n", result, n, param); return 0; } /* Will produce: 0.500000 * 2^4 = 8.000000 */
How's this? public static class FRexpResult { public int exponent = 0; public double mantissa = 0.; } public static FRexpResult frexp(double value) { final FRexpResult result = new FRexpResult(); long bits = Double.doubleToLongBits(value); double realMant = 1.; // Test for NaN, infinity, and zero. if (Double.isNaN(value) || value + value == value || Double.isInfinite(value)) { result.exponent = 0; result.mantissa = value; } else { boolean neg = (bits < 0); int exponent = (int)((bits >> 52) & 0x7ffL); long mantissa = bits & 0xfffffffffffffL; if(exponent == 0) { exponent++; } else { mantissa = mantissa | (1L<<52); } // bias the exponent - actually biased by 1023. // we are treating the mantissa as m.0 instead of 0.m // so subtract another 52. exponent -= 1075; realMant = mantissa; // normalize while(realMant > 1.0) { mantissa >>= 1; realMant /= 2.; exponent++; } if(neg) { realMant = realMant * -1; } result.exponent = exponent; result.mantissa = realMant; } return result; } This is "inspired" or actually nearly copied identically from an answer to a similar C# question. It works with the bits and then makes the mantissa a number between 1.0 and 0.0.
1,552,787
1,552,864
compare dates in C++
i have a file, 'date.txt' which has date in it. Like, Mon Oct 13 09:37:08 2009. Now i want to compare this date with system date. How can i compare dates in C++.? I used this code to get the contents from the file 'date.txt' string date; while ( inDateFile >>date) //inDateFile is an ifstream object cout<<date<<endl; And this code to get system date, time_t timer; struct tm *tblock; timer = time(NULL); tblock = localtime(&timer); string str = asctime(tblock); Now how can i compare these two dates.?
Parse values, use std::mktime function to get time_t and now use std::difftime to get the difference.
1,553,382
1,553,407
Is delete[] equal to delete?
IP_ADAPTER_INFO *ptr=new IP_ADAPTER_INFO[100]; if I free using delete ptr; will it lead to memory leak, if not then why ? This is disassembly code generated by VS2005 ; delete ptr; 0041351D mov eax,dword ptr [ptr] 00413520 mov dword ptr [ebp-0ECh],eax 00413526 mov ecx,dword ptr [ebp-0ECh] 0041352C push ecx 0041352D call operator delete (4111DBh) 00413532 add esp,4 ; delete []ptr; 00413535 mov eax,dword ptr [ptr] 00413538 mov dword ptr [ebp-0E0h],eax 0041353E mov ecx,dword ptr [ebp-0E0h] 00413544 push ecx 00413545 call operator delete[] (4111E5h) 0041354A add esp,4
Whether this leads to a memory leak, wipes your hard disk, gets you pregnant, makes nasty Nasal Demons chasing you around your apartment, or lets everything work fine with no apparent problems, is undefined. It might be this way with one compiler, and change with another, change with a new compiler version, with each new compilation, with the moon phases, your mood, or depending on the number of neutrinos that passed through the processor on the last sunny afternoon. Or it might not. All that, and an infinite number of other possibilities are put into one term: Undefined behavior: Just stay away from it.
1,553,435
1,553,529
tcmalloc: how can I get my malloc calls overridden when compiling statically?
When I use LD_PRELOAD=/usr/local/lib/libtcmalloc.so, all my calls to malloc become tcmalloc calls. However, when I link statically against libtcmalloc, I find that straight malloc is getting called unless I still use the LD_PRELOAD setting. So how can I statically compile against tcmalloc in such a way that my mallocs hook into tcmalloc? Notes: I'm using lots of C++ new etc, so just #defining malloc to tcmalloc won't work Possibly I have to use malloc_hook myself, but I would have thought I could get tcmalloc to do it for me, since it clearly is doing it when linking dynamically
Symbols are resolved on a first match basis. You need to make sure that libtcmalloc.a is searched before libc.a by the linker. I assume that you are not explicitly linking libc.a since you do not normally need to do so. The solution is to specify -nostdlibs, and then explicitly link all necessary libraries in the order you want them to be searched. Usually something like: -nostdlibs -llibtcmalloc -llibm -llibc -llibgcc Another solution which may be simpler, is to link the object file(s) needed to resolve tcmalloc rather than the static library, since object files take precedence over libraries in resolving symbols.
1,553,603
1,553,915
How to know if a given DLL is loaded by a given process?
Possible Duplicate: How to programmatically get DLL dependencies On Windows, in a C++ program, I want to know if a given DLL (I know the path) is loaded by a given external process (I know the path of the exe), using win32 functions. It must be possible to list all DLLs loaded by a process, as process explorer does. Fabien
First you have get the ID of the Process you are looking for. Use the EnumProcesses function described here to find your desired process. There is a nice example provided to list all processes and their names, that you can use as a starting point. As the second step you can list all of the modules, that is the DLLs loaded by each process. Use the EnumProcessModules function. This example does mostly what you want, you only need to add some more check code to filter for your process and your module.
1,553,817
1,553,943
C++ Read from shared memory
I want to read status information that an application provides via shared memory. I want to use C++ in order to read the content of that named shared memory and then call it with pinvoke from a C#-class. From the software I know that it has a certain file structure: A struct STATUS_DATA with an array of four structs of SYSTEM_CHARACTERISTICS. I'm not (yet) familiar with C++, so I tried to follow msdn basically. To find the size of the file to be mapped, I added the sizes of the struct members as to be seen in the code below. This results in a ACCESS DENIED, so I figured, that the result based on the structs is too high. When I use sizeof(STATUS_DATA) (I added the struct to my source), it still ends up in an ACCESS DENIED. If I try something lower, like 1024 Bytes, only thing I can see in pbuf is a <, while debugging. This is what I got so far: #include <windows.h> #include <stdio.h> #include <conio.h> #include <tchar.h> #include <iostream> #pragma comment(lib, "user32.lib") using namespace std; signed int BUF_SIZE = 4 * (10368 + 16 + 4 + 16 + 4 + 16 + 4 + 1 + 4); // sizeof(STATUS_DATA); TCHAR szName[]=TEXT("ENGINE_STATUS"); int main() { HANDLE hMapFile; unsigned char* pBuf; hMapFile = OpenFileMapping( FILE_MAP_READ, // read access FALSE, // do not inherit the name szName); // name of mapping object if (hMapFile == NULL) { _tprintf(TEXT("Could not open file mapping object (%d).\n"), GetLastError()); return 1; } pBuf = (unsigned char*) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_READ, // read/write permission 0, 0, BUF_SIZE); // 1024); if (pBuf == NULL) { _tprintf(TEXT("Could not map view of file (%d).\n"), GetLastError()); CloseHandle(hMapFile); return 1; } UnmapViewOfFile(pBuf); CloseHandle(hMapFile); return 0; } I also made sure that this Shared Mem "is there" by following that hint. Can somebody give me a hint, what I'm missing? Thanks!
The last parameter to MapViewOfFile (dwNumberOfBytesToMap) must be less than the maximum size specified when the mapping was created. Since we don't know what that size is, it seems fair to assume that BUF_SIZE is exceeding it and 1024 isn't. Specifying 0 for this parameter is an easy way to map the entire file into a single view. Most (all?) C++ debuggers will assume that a pointer to char is a null-terminated string, so when you try and view the mapped data it will only display up until the first byte that is zero. Depending on what data is in the file mapping, this could well be the second byte, which explains why you aren't seeing much information. You would be better to cast the returned pointer to STATUS_DATA* and viewing the individual members. In short: Specify zero (0) for dwNumberOfBytesToMap Cast the returned pointer to STATUS_DATA* instead of unsigned char*
1,553,854
1,553,875
Template static variable
I can't understand, why if we define static variable of usual (non-template) class in header, we have linker error, but in case of templates all works fine and moreover we will have single instance of static variable among all translation units: It's template header (template.h): // template.h template<typename T> class Templ { public: static int templStatic; }; template<typename T> Templ<T>::templStatic = 0; It's first unit using template (unit1.cpp) // unit1.cpp #include "template.h" int method1() { return Templ<void>::templStatic++; } Second unit here (unit2.cpp): // unit2.cpp #include "template.h" int method2() { return Templ<void>::templStatic++; } And, finally, main.cpp: // main.cpp #include <iostream> int method1(); int method2(); int main(int argc, char** argv) { std::cout << method1() << std::endl; std::cout << method2() << std::endl; } After compilling, linking and executing this code, we will have following output: 0 1 So, why in case of templates all works fine (and as expected) ? How compiler or linker handle this (we can compile each .cpp file in separated calling of compiler, and then link them with caling to linker, so compiler and linker don't "see" all .cpp files at same time) ? PS: My compiler: msvcpp 9 (but checked on mingw too)
It's because the definition of the static data member is itself a template. Allowing this is necessary for the same reason you are allowed to have a function template that's not inline multiple times in a program. You need the template to generate the resulting entity (say, a function, or a static data member). If you wouldn't be allowed to put the definition of a static data member, how would you instantiate the following template<typename T> struct F { static int const value; }; template<typename T> int const F<T>::value = sizeof(T); It's not known what T is - the Standard says the definition outside the class template is a template definition, in which the parameters are inherited from its class template owner. I've made some experiment with GCC. In the following, we have one implicit instantiation of F<float>::value, and one explicit specialization of F<char>::value which has to be defined in a .cpp file to not cause duplicated symbol errors when included multiple times. // Translation Unit 1 template<typename T> struct F { static int value; }; template<typename T> int F<T>::value = sizeof(T); // this would belong into a .cpp file template<> int F<char>::value = 2; // this implicitly instantiates F<float>::value int test = F<float>::value; int main() { } The second translation unit contains just another implicit instantiation of the same static data member template<typename T> struct F { static int value; }; template<typename T> int F<T>::value = sizeof(T); int test1 = F<float>::value; Here is what we get with GCC - it makes each implicit instantiation into a weak symbols and sticks it into its own section here. Weak symbols will not cause errors when there exist multiple of them at link time. Instead, the linker will choose one instance, and discards the other ones assuming all of them are the same objdump -Ct main1.o # => # cut down to the important ones 00000000 l df *ABS* 00000000 main1.cpp 0000000a l F .text 0000001e __static_initialization_and_destruction_0(int, int) 00000000 l d .data._ZN1FIfE5valueE 00000000 .data._ZN1FIfE5valueE 00000028 l F .text 0000001c global constructors keyed to _ZN1FIcE5valueE 00000000 g O .data 00000004 F<char>::value 00000000 g O .bss 00000004 test 00000000 g F .text 0000000a main 00000000 w O .data._ZN1FIfE5valueE 00000004 F<float>::value So as we can see F<float>::value is a weak symbol which means the linker can see multiple of these at link time. test, main and F<char>::value are global (non-weak) symbols. Linking main1.o and main2.o together, we see in the map output (-Wl,-M) the following # (mangled name) .data._ZN1FIfE5valueE 0x080497ac 0x4 main1.o 0x080497ac F<float>::value This indicates that actually it drops all except one instance.
1,553,914
1,553,942
New keywords and new type of pointers in Visual C++ 2005. What is managed C++?
Possible duplicates What is gcnew? What does the caret mean in C++/CLI? Difference between managed c++ and c++ I am a advanced C++ programmer with g++. But currently I am working on Visual C++ 2005 doing Windows Forms Application programming . But I am finding it hard with its new terminology. For e.g. instead of new it has gcnew and String ^ kind of thing. Can someone explain what is ^, similar to pointer? Can I make Visual C++ work in the same way as normal C++ like g++ compiler? I also heard something about managed C++. What is that?
The gcnew and ^ values are managed C++ which is a different language to c++. You can use VS2005 as a normal C++ compiler by not using a project type from the CLR section of the new project window.
1,554,047
1,554,405
Convert a C++ program to a Windows service?
I've written a console program that "does stuff" - mainly using boost. How do I convert it to a Windows Service? What should I know about Windows Services beforehand?
There's a good example on how to set up a minimal service on MSDN. See the parts about writing the main function, entry point and also the example code. Once you've got a windows service built and running, you'll discover the next major gotcha: it's a pain to debug. There's no terminal (and hence no stdout/stderr) and as soon as you try to run the executable it actually launches the service then returns to you. One trick I've found very useful is to add a -foreground option to your app so that if you run with that flag then it bypasses the service starter code and instead runs like a regular console app, which makes it vastly easier to debug. In VS.Net set up the debugging options to invoke with that flag.
1,554,070
1,554,137
How to retrieve FQDN of the current host on Win32?
What's an easiest reliable way to retrieve the fully qualified domain name of the current host in Win32? I've tried calling gethostname(), but it returns a NetBIOS name.
Try getnameinfo, it comes with a sample that worked for me.
1,554,083
1,815,221
QT4 incomplete getting website content
I'm trying to write a small test using QHttp to get an URL and return its content. The program ran fine, but it has some problem. With this link http://www.mediafire.com/download.php?ztyniqhd4lb ( or some random MF link ), my program cannot load all its content. With some workaround, I found that all the SIGNAL before the done(bool) is emitted, including the last dataReadProgress, stateChanged and the last requestFinished. The last SIGNAL requestFinished didn't generate any error. my code looks like this ( it's quite long with some slots, so I only write the main http call here, url is QUrl("http://www.mediafire.com/download.php?ztyniqhd4lb") http.setHost(url.host(), url.port(80)); http.get(url.path()+ QString("?") + url.queryItems ()[0].first, &file); http.close(); the SIGNAL done(bool) never be emitted, any other SIGNAL before it was fine. Thanks for any help
I was about to say that QHttp is deprecated. You should use QNetworkAccessManager.
1,554,276
1,588,619
How can I define operations on a template without caring what type it's instantiated with?
I have inherited a bunch of networking code that defined numerous packet types. I have to write a bunch of conversion functions that take structs of a certain type, and copy the values into other structs that have the same fields, but in a different order (as part of a convoluted partial platform bit order conversion thing -- don't ask). Also, I know that there may be better ways of expressing the conversion, etc. below, but I'm not concerned with those at the moment. Particularly, I cannot make convert take its output variable by reference, because I will be passing in bitfields, and that generates a compiler error. So there are a bunch of structs like this: struct foo { int bar; int baz; }; struct foo_x86 { int baz; int bar; }; And a bunch of functions like this, to convert between the two: foo_x86 convert(const foo& in) { foo_x86 out; out.bar = in.bar; out.baz = in.baz; return out; } This is all no big deal. The problem I have is this: there is also a template struct that looks something like this: template <class T> struct Packet { HeaderType head; T data; }; There are a number of instantiations of this template, using packet types above as the template parameters, for example: struct superfoo { Packet<foo> quux; }; struct superfoo_x86 { Packet<foo_x86> quux; }; Now, assuming that there exists a function foo_x86 convert(const foo&); is there any way to create a template function for handling Packet objects that calls this convert function? For example, I want something that looks sort of like this: template <class type_1, class type_2> Packet<type_2> convert(const Packet<type_1>& in) { Packet<type_2> out; out.head = in.head; out.data = convert(in.data); return out; } That would work in a function like: superfoo_x86 convert(const superfoo& in) { superfoo_x86 out; out.quux = convert(in.quux); return out; } I want to be able to convert Packet objects without caring what type they are instantiated with, and I want to avoid having to declare separate convert functions for every possible Packet instantiation. Is there anyway to do with with templates in C++?
I ended up doing something like what outis suggested in the comment on the original question. First, I created an unspecialized conversion class template, like so: template <class type_1> struct conversion {}; I then threw in a macro for specializing this class (which I believe is like the traits template outis suggested, right?), like so: #define GEN_CON(type_1, type_2) \ template <> struct conversion<type_1> { typedef type_2 type; } Then, for every conversion function from foo to foo_x86, I added the following macro call in the header after the convert function definition:: foo_x86 convert (const foo&); GEN_CON(foo, foo_x86); This instantiates a conversion template for foo and foo_x86, like so: template <> struct conversion<foo> { typedef foo_x86 type; } Now, I can refer to conversion::type to get foo_x86. So, finally, I can create my Packet conversion function, referring to the conversion class, like so: template <class type_1> Packet< typename conversion<type_1>::type > convert(const Packet<type_1>& in) { Packet< typename conversion<type_1>::type > out; out.head = convert(in.head); out.data = convert(in.data); return out; } This allowed the compiler to resolve references to Packet convert(const Packet& in) just fine, without having pass the template parameters into the call (like da_m_n suggested). Thanks for all your suggestions!
1,554,558
1,554,614
Best way to create an Environment object in C++
I want to create an environment class that is accessible from all of my classes in my program but I dont want to initialize the environment object everytime I want to access its members from my other classes. What is the best way to go around doing this in C++? I want to do this because I have the environment object store all my config values that other classes may use. Those values are read from multiple places, including different files. I dont want to parse the files every time I create a new environment object in my classes.
A Singleton object isn't always the solution. While sometimes it seems like an easy solution, it does have some disadvantages (see this question for example). How many of your classes actually need access to this Environment object? If you literally meant that every class you have do then it sounds like your design is flawed. Quite often a better alternative to a singleton is just to pass the object around to those who actually need it.
1,554,591
1,554,621
How to start a process on a remote machine in C++ under Windows
I'm using Dev-C++ under Windows. My question is how can i start a process on a remote machine? I know that PsExec can do that, but if it's possible, i want to avoid to use it. If someone can give some example code, i would appreciate it :) Thanks in advance! kampi
If this was easy, hackers would be starting up malware on all machines exposed to the internet. PSExec uses the Services Control Manager over a LAN to start a service EXE from 'here', i.e. the machine where you run it. It requires a lot of security privileges - e.g. admin rights. If you don't want to do this, you can look into SSH (there are open source examples) or Remote Command Prompt (in Windows Resource Kit).
1,554,750
1,554,822
C++ const keyword - use liberally?
In the following C++ functions: void MyFunction(int age, House &purchased_house) { ... } void MyFunction(const int age, House &purchased_house) { ... } Which is better? In both, 'age' is passed by value. I am wondering if the 'const' keyword is necessary: It seems redundant to me, but also helpful (as an extra indication the variable will not be changing). Does anyone have any opinion as to which (if any) of the above are better?
This, IMHO, is overusing. When you say 'const int age,...' what you actually say is "you can't change even the local copy inside your function". What you do is actually make the programmer code less readable by forcing him to use another local copy when he wants to change age/pass it by non-const reference. Any programmer should be familiar with the difference between pass by reference and pass by value just as any programmer should understand 'const'.
1,554,774
1,554,796
Create new C++ object at specific memory address?
Is it possible in C++ to create a new object at a specific memory location? I have a block of shared memory in which I would like to create an object. Is this possible?
You want placement new(). It basically calls the constructor using a block of existing memory instead of allocating new memory from the heap. Edit: make sure that you understand the note about being responsible for calling the destructor explicitly for objects created using placement new() before you use it!
1,554,878
1,589,326
Why does Windows not allow WinSock to be started while impersonating another user
Using my own program or others I can't get winsock to run when calling if the process is created with CreateProcessWithLogonW or CreateProcessAsUserW. It returns this error when I create the socket: WSAEPROVIDERFAILEDINIT 10106 Service provider failed to initialize. The requested service provider could not be loaded or initialized. This error is returned if either a service provider's DLL could not be loaded (LoadLibrary failed) or the provider's WSPStartup or NSPStartup function failed . However, WSAStartup seems to go w/o an error. Just creating the socket with WSASocket returns this. UPDATE: Errors: LoadUserProfile: Error Code 2. Can't find file specified AdjustTokenPrivs: Error Code 5. Access Denied
You have to have the Act As Operating Priv
1,554,910
1,555,046
D.R.Y vs "avoid macros"
I am creating my own implementation of XUL in C++ using the Windows API. The fact that the elements are constructed by the XML parser requires that they have identical interfaces, so that we don't need to write custom code for each element constructor. The result is that most of my elements look like this: class Button : public Element { public: static const char * Type() { return "button"; } private: friend class Element; Button(Element * inParent, const AttributesMapping & inAttributesMapping); }; class Label : public Element { public: static const char * Type() { return "label"; } private: friend class Element; Label(Element * inParent, const AttributesMapping & inAttributesMapping); }; class Description : public Element { public: static const char * Type() { return "description"; } virtual bool init(); private: friend class Element; Description(Element * inParent, const AttributesMapping & inAttributesMapping); }; So there is a lot of code duplication here. I wonder if it would be a good idea to replace them with macro calls like this: #define DECLARE_ELEMENT(ElementType, XULName) \ class ElementType : public Element \ { \ public: \ static const char * Type() { return XULName; } \ \ private: \ friend class Element; \ ElementType( \ Element * inParent, \ const AttributesMapping & inAttributesMapping); \ }; \ DECLARE_ELEMENT(Window, "window") DECLARE_ELEMENT(Button, "button") DECLARE_ELEMENT(Label, "label") I haven't completely worked out the concept yet, so a few things are missing here, like the class definitions, and (maybe) the ability to add methods per element. But I'd like to know your opinion of using macros in this situation. Feel free to share your thoughts. EDIT I am now using a small ruby script that generates the source and header files from a set of templates. I enhanced the scripts so that the files are also automatically marked for addition on SVN, and the Visual Studio project file is modified to include the files. This saves me a lot of manual labor. I'm quite happy with this solution. FYI this is what the templates look like now: #ifndef {{ELEMENT_NAME_UPPER}}_H_INCLUDED #define {{ELEMENT_NAME_UPPER}}_H_INCLUDED #include "XULWin/Element.h" namespace XULWin { class {{ELEMENT_NAME}} : public Element { public: static ElementPtr Create(Element * inParent, const AttributesMapping & inAttr) { return Element::Create<{{ELEMENT_NAME}}>(inParent, inAttr); } static const char * Type() { return "{{ELEMENT_TYPE}}"; } virtual bool init(); private: friend class Element; {{ELEMENT_NAME}}(Element * inParent, const AttributesMapping & inAttributesMapping); }; } // namespace XULWin #endif // {{ELEMENT_NAME_UPPER}}_H_INCLUDED CPP document: #include "XULWin/{{ELEMENT_NAME}}.h" #include "XULWin/{{ELEMENT_NAME}}Impl.h" #include "XULWin/AttributeController.h" #include "XULWin/Decorator.h" namespace XULWin { {{ELEMENT_NAME}}::{{ELEMENT_NAME}}(Element * inParent, const AttributesMapping & inAttributesMapping) : Element({{ELEMENT_NAME}}::Type(), inParent, new {{ELEMENT_NAME}}Impl(inParent->impl(), inAttributesMapping)) { } bool {{ELEMENT_NAME}}::init() { return Element::init(); } } // namespace XULWin
I would not use a macro here. The clue is in your class "Description", which has an extra member function init, which the others don't. So you wouldn't be able to use the macro to define it, but you'd instead expand the macro manually and add the extra line. To me, this is a bigger violation of DRY than just writing out all the class definitions. Almost not repeating yourself, but doing it just for one case, often ends up harder to maintain that repeating yourself consistently. DRY is about finding good abstractions, not just cutting down on boilerplate. I might replace those constructors, though, with a SetAttributes function in class Element. That might cut the amount of boilerplate actually required in each derived class, since constructors are the one thing that can't be inherited from the base. But it depends how similar the implementations are of the constructor of each class.
1,554,984
1,562,458
C++: LINK : debug\XXXXX.exe not found or not built by the last incremental link; performing full link
Using visual studio 2008 SP1, This line: LINK : debug\XXXXX.exe not found or not built by the last incremental link; performing full link appears every single time I compile the project, no matter how small a change I make. What could be the reasons for that?
So it turns out that the problem fixes it self if I add /INCREMENTAL to the linker command line. This in spite the fact that the default behavior according to the docs is to enable incremental linking. Strange.
1,555,368
1,555,404
C++ char** -> vector<string> -> string -> char** parsing problem
Lets say that I'm trying to solve a parsing problem of string to char ** For some reason the below code generates a lot of trash, can anyone have a look at it please? Here's what it's supposed to do : Dump all argv into a string_array container Dump everything in the string_array container into a std::string and separate with spaces Break the string down into string tokens using boost/algorithm/string create a new char ** and dump all tokens into it, print out the new char **, clean up What have I done wrong ? #include <string> #include <vector> #include <iostream> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost; typedef vector<string> string_array; int main(int argc, char ** argv) { string_array args; string_array tokens; cout << "Real arguments :" << endl; for(int i = 0; i < argc; i++) { cout << argv[i] << endl;} string arg = ""; for(int i = 1; i < argc; i++) { args.push_back(argv[i]); } for(int i = 0; i < (int)args.size(); i++) { arg += args[i]; if(i != (int)args.size() - 1) arg += " "; } split(tokens, arg, is_any_of(" ")); char ** new_args = NULL; new_args = new char*[(int)tokens.size()]; for(int i = 0; i < (int)tokens.size(); i++) { new_args[i] = new char[(int)tokens[i].size()]; for(int j = 0; j < (int)tokens[i].size(); j++) { new_args[i][j] = tokens[i][j]; } } for(int i = 0; i < (int)tokens.size(); i++) { std::cout << new_args[i] << std::endl; } delete [] new_args; }
C-style strings (char*) are meant to be zero-terminated. So instead of new char[tokens[i].size()], you need to add 1 to the allocation: new char[token[i].size() + 1]. Also, you need to set new_args[i][tokens[i].size()] = 0 to zero-terminate the string. Without the zero-terminator, programs would not know when to stop printing, as char* does not hold a string length, unlike std::string.
1,555,545
1,555,621
Const Correctness Question in C++
I have a random question about const correctness. Lets say i have a class that is a singleton. class Foo : public Singleton<Foo> { friend class Singleton<Foo>; public: std::wstring GetOrSet(const int id) const; private: Foo(); ~Foo(); void LoadStringIntoMap(const int id, const std::wstring &msg); std::map<int, std::wstring> strMap; }; The functions are defined as such std::wstring Foo::GetOrSet(const int stringId) const { if ( strMap.find(stringId) == strMap.end() ) { Foo::GetInstance()->LoadStringIntoMap(stringId, std::wstring(L"HELLO WORLD222")); } std::map<int, std::wstring>::const_iterator retStr = strMap.find(stringId); return retStr->second; } void Foo::LoadStringIntoMap(const int stringId, const std::wstring &msg) { strMap.insert(std::pair<int, std::wstring>(stringId, msg)); } If i directly get call LoadStringIntoMap i get an error that it cannot convert this pointer from const Foo to Foo &. Which makes sense since your calling a non const function from within a const function. But why is this not an issue when calling the singleton, and doing modification through that. Is this just really unsafe? This is what singleton is defined as: template <typename T> class Singleton { protected: Singleton () {}; ~Singleton () {}; public: static T *GetInstance() { return (static_cast<T*> (m_This)); } static void Destroy() { if(m_This != NULL) delete m_This; } static void CreateInstance() { m_This = GetInstance(); if (m_This == NULL) { m_This = new T; } } private: // Unique instance static T *m_This; }; template <typename T> T *Singleton<T>::m_This = NULL;
GetInstance() returns a non-const pointer. As the function GetInstance() is not bound to the object itself, but class-wide, it may be called from a const function. Essentially, you have tricked yourself out of the const environment; but then, you could do that from any context/state of your program (privateness of members is not bound to specific objects, only classes). In this scenario, you have to care for a safe usage of the singleton accessors on your own.
1,555,548
1,555,670
VB6 GUI not working in multithreaded COM environment
I have a VB6 COM client that makes calls to an inprocess STA ATL/COM server. One of the Server methods, X, can take a while to finish so I need to be able to cancel it. What I tried was to run the method code in a new thread and include another method, Y, that does a timed WaitForSinleObject. So the client first calls X then goes into a loop calling VB6 DoEvents and then Y until Y indicates that X has finished. This works fine, however, the fly in the ointment is that the X thread also triggers events back to the client via the IConnectionPoint interface. The events get through ok but any GUI calls don't work because, as far as I can glean, the GUI can only work on one thread, ie the main thread. Is there an obvious way round this using my existing code? Alternatively, please can you suggest other ways I could accomplish this.
You should always marshal your connection-point calls. When you don't do that, you can call VB code, but it fails in random ways (non-marshaled-objects), or just doesn't work (GUI). To use marshaling, you have to implement several interfaces (see below). The other possibility is to convert the asynchronous calls to VB into synchronous 'fetch' calls. So your code goes from (in C Pseudo code ...) : while( !wait( X ) ) { doevents(); } to : while( !wait( X ) ) { doevents(); fetch_async_data(); } 1) Add a marshaller to your class by adding it to the COM_AGGRGATE table : CComPtr<IUnknown> m_pUnkMarshaler; BEGIN_COM_MAP(..) ... COM_INTERFACE_ENTRY_AGGREGATE(IID_IMarshal, m_pUnkMarshaler.p) END_COM_MAP() 2) Create the marshaller in FinalConstruct() FinalConstruct() { HRESULT rval = CoCreateFreeThreadedMarshaler( GetControllingUnknown(), &m_pUnkMarshaler.p ); ... } FinalRelease() { ...; m_pUnkMarshaler = 0; } 3) Derive your connection point from IConnectionPointImplMT and lock the calls internally when you can fire more then one at the same time. 4) Do not wait indefinitely in the methods of your object, because you can run in deadlocks. 5) Repeat this for every exposed object and connection point. (This should work, but I haven't tried this in a long time ...)
1,555,640
1,555,710
Which is latest C++ Standard Release , From where i can download it
Possible Duplicate: Where do I find the current {X} standard? I have a simple Question ! I am looking for soft copy of latest C++ Standard release. I have ISO/IEC 14882 First Edition ,1998-09-01, But i have doubt if it is latest. I visited http://www.open-std.org/jtc1/sc22/wg21/, There are many drafts. Please guide me which one is latest and i should refer.
If you don't want to pay money, you can always use the final draft. It is basically the same with only minor edits. And it is free. You can find a PDF here. Otherwise just search for 14882 final draft. edit: Updated link to the document instead of the index
1,555,661
1,555,728
Initializing an array in C++
I am trying to initialize an array of objects: SinglyLinkedList offeredClasses[22] = {SinglyLinkedList("CSCE101"),SinglyLinkedList("CSCE101L"),SinglyLinkedList("CSCE150E"),SinglyLinkedList("CSCE150EL"),SinglyLinkedList("CSCE150EM"),SinglyLinkedList("CSCE150EML"),SinglyLinkedList("CSCE155"),SinglyLinkedList("CSCE155H"),SinglyLinkedList("CSCE156"),SinglyLinkedList("CSCE230"),SinglyLinkedList("CSCE230L"),SinglyLinkedList("CSCE235"),SinglyLinkedList("CSCE251"),SinglyLinkedList("CSCE310"),SinglyLinkedList("CSCE322"),SinglyLinkedList("CSCE361"),SinglyLinkedList("CSCE351"),SinglyLinkedList("CSCE451"),SinglyLinkedList("CSCE423"),SinglyLinkedList("CSCE428"),SinglyLinkedList("CSCE486"),SinglyLinkedList("CSCE487")}; but when I try to do this it keeps trying to call my copy constructor instead of an overloaded constructor. Any ideas to fix this? the 2 constructors in question are: SinglyLinkedList(string course); //Constructor SinglyLinkedList(SinglyLinkedList & otherObj); //Copy Constructor I need the copy constructor for other things so I can't remove it. Thanks for your help!
It appears theat your compiler is seriously broken. Your copy-constructor is declared with a non-const reference parameter. Such a copy-constructor cannot be invoked with temporary object as an argument, since a non-const reference cannot be bound to a temporary object. Your initializers are temporary objects, meaning that there's absolutely no way a copy-constructor can be called here. If your compiler does it, it means that it is either broken or that you are using some set of settings that make it behave in a weird non-compliant way. Which compiler are you using? That's the first part of the answer. The second part is that brace-enclosed initializer lists are interpreted as copy-initialization in C++. In other words, the copy-constructor must be called in this case. There's no way around it (the call can be later optimized away, but the constructor must be available in any case). In this regard, your compiler is behaving "correctly", i.e. it makes an attempt to call the copy-constructor, as it should. Except that, as I said above, in your case it should issue an error (since the copy-constructor is not callable) instead of quetly calling it. And, finally, the third part of the answer. You are saying that the copy-constructor is called instead of the conversion constructor. In reality, both are called. If you look carefully, you'll see it. Firstly, the conversion constructor is called in order to create an intermediate temporary object of 'SinglyLinkedList' type from the string you supplied (that involves constructing a temporary 'std::string' object as well), and then the copy-constructor is called in order to initialize the array element from the temporary (this happens for each element in the array). This is how it should be in C++, assuming your copy-constrcutor is declared properly, i.e. with a const reference parameter. But with non-const reference parameter, the copy-constructor is not callable and the code is ill-formed.
1,555,719
1,555,725
C++ c_str doesn't return entire string
I've tried the following code with both normal ifstreams and the current boost:iostream I'm using, both have the same result. It is intended to load a file from physfs into memory then pass it to a handler to process (eg Image, audio or data). Currently when c_str is called it only returns a small part of the file. PhysFS::FileStream file("Resources/test.png" , PhysFS::OM_READ); if(file.is_open()) { String* theFile; theFile = new String((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); String::iterator it; for ( it=theFile->begin() ; it < theFile->end(); it++ ) { std::cout << *it; } // Outputs the entire file std::cout << theFile->c_str(); // Outputs only the first few lines } The iterator loop outputs the entire png file as expected, but the c_str call only returns the first few characters (\211PNG). I've been trying variations of this code for quite some time with no success. Any ideas?
I imagine that the next character is a null (ASCII 0) byte. c_str() simply gives you a *char, therefore your write to stdout is interpreted as a class C string which ends at the first null byte. If you really need a C-like interface to this string, the main thing is that theFile->c_str() points to your data and theFile.length gives you the number of characters in the string. So you might want to do something like this: char *c_value = theFile->c_str() for (int i = 0; i < theFile.length; i++) { cout << c_value[i]; } The real solution depends on why you are converting to a char * in the first place. If you are calling a legacy function that only accepts char *, there is likely also a length argument to that legacy function.
1,555,825
1,555,987
I'm an experienced C# developer, what things should I know to code effectively in c/c++?
I have a little bit of experience in c/c++ from college but have not worked in it for years. What sorts of things do I need to know to even be considered for a c/c++ job position?
I have to disagree with a lot of the advice you've received. You should not concentrate on manual memory management. Manual memory management was/is difficult to avoid in C. Most C++ code, however, has little need to use manual memory management at all. Manual memory management is heavily overused in a great deal of code, leading to many problems that would have been easy to avoid. The first and most important thing to study is the standard library. It's substantially different from .NET (to put it mildly). My immediate advice would be to pick up a copy of Accelerated C++, and work through it. It's designed for people in exactly your position (i.e. learning C++, but already have experience with at least one other language), and for that situation I'm pretty sure there's no better book available. Edit: (mostly in respond to Kenny's comment) -- it's true that especially if you're maintaining existing code, there's a pretty good chance that you'll be stuck with learning about all manner of unpleasantness any sane person would probably rather avoid. Likewise, depending on the team you join, you might be stuck with ugliness even in new code. Unfortunately, without a fair amount of background and experience with the language, it might not be at all apparent what to look for.
1,556,014
1,556,024
Memory usage isn't decreasing when using free?
Somehow this call to free() is not working. I ran this application on Windows and followed the memory using in Task Manager, but saw no reduction in memory usage after the call to free(). int main(int argc, char *argv[]) { int i=0; int *ptr; ptr = (int*) malloc(sizeof(int) * 1000); for (i=0; i < 1000; i++) { ptr[i] = 0; } free(ptr); // After this call, the program memory usage doesn't decrease system("PAUSE"); return 0; }
Typical C implementations do not return free:d memory to the operating system. It is available for use by the same program, but not to others.
1,556,054
1,738,280
Problem between a QTcpServer and a TCPClientSocket (Cayuga)
I try to communicate via TCP Socket between a QT4-Application (MyApp) and Cayuga (written in C++). The connection part works fine, i.e. Cayuga connects to MyApp. Now, MyApp is sending some data to Cayuga, but nothing is received. void MyApp::init() QTcpServer *m_server; QTcpSocket *clientConnection; //Open socket for transmission m_server = new QTcpServer(this); if (!m_server->listen(QHostAddress::Any, m_port)) { //Error handling return; } connect(m_server, SIGNAL(newConnection()), this, SLOT(startSend())); void MyApp::startSend() { clientConnection = m_server->nextPendingConnection(); } The writting is done here: QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << (quint16)0; out << s; out.device()->seek(0); out << (quint16)(block.size() - sizeof(quint16)); clientConnection->write(block); clientConnection->flush(); My tutor suggested to use an external library (cudb) if I cannot get it to work with QTcpSockets. That does not feel right and that's why I hope you have a better answer to my problem.
This is my guess of what's happening: QDataStream implements a serializing protocol (Hence having to specify a version (Qt_4_0) for it). You need something on the other end that understands that protocol (to wit, another Qt_4_0 DataStream). Particularly, QDataStream makes sure you get the right data regardless of the endianness of the sending and receiving ends. Instead of serializing to a block and then writing the block, you can try something like: QDataStream out(clientConnection, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out.writeRawData(data, length); clienConnection->flush(); writeRawData() does not marshall your data...
1,556,150
1,556,338
deleting char ** correctly?
I've created a 2d array of c-strings using : char ** my_array = new char*[N]; and then I initialized each row using : my_array[i] = new char[M]; // where M is a varying number. assign values to my_array[i] later So I pretty much got a jagged 2d array. I wanted to proceed and delete the whole thing like this : for(int i = 0; i < N; i++) { delete [] my_array[i]; } followed by a : delete [] my_array; the for loop gave me HEAP CORRUPTION ERROR - why? ************** UPDATE - full code ********************* #define BOOST_TEST_MODULE ARGS #define BOOST_LIB_DIAGNOSTIC #include <string> #include <vector> #include <iostream> #include <boost/test/unit_test.hpp> #include <boost/algorithm/string.hpp> #include <boost/assign.hpp> #include <boost/assign/list_of.hpp> #include <boost/assign/std/vector.hpp> using namespace std; using namespace boost; using namespace boost::assign; typedef vector<string> string_array; BOOST_AUTO_TEST_CASE(test1) { string_array args = list_of ("aaa")("bbbb")("ccccccc")("dd")("eeeeeeeee")("ff")("g")("hhh"); string_array tokens; string arg = ""; for(int i = 0; i < (int)args.size(); i++) { arg += args[i]; if(i != (int)args.size() - 1) arg += " "; } split(tokens, arg, is_any_of(" ")); char ** new_args = NULL; new_args = new char*[(int)tokens.size() + 1]; new_args[(int)tokens.size()] = 0; for(int i = 0; i < (int)tokens.size(); i++) { new_args[i] = new char[(int)tokens[i].size()]; for(int j = 0; j <= (int)tokens[i].size(); j++) { if(j == (int)tokens[i].size()) new_args[i][j] = '\0'; else new_args[i][j] = tokens[i][j]; } } for(int i = 0; i < (int)tokens.size(); i++) { std::cout << new_args[i] << std::endl; } for(int i = (int)tokens.size() - 1; i >= 0; i--) delete new_args[i]; delete [] new_args; } If you don't have boost installed : convert the BOOST_AUTO_TEST_CASE to main() and voil'a. What the above thing does : converts a vector into char **
In your array initialization code you allocate 'tokens[i].size()' characters for each 'tokens[i]' element, and then you initialize elements from 0 to 'tokens[i].size()'. This is obvious memory overrun. If you want to have elements from 0 to 'tokens[i].size()', you need to allocate an array of size 'tokens[i].size() + 1'.