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
2,264,819
2,264,847
Ambiguity while including std class libraries
I have Visual studio 2005 . One of my header file has a enum like typedef enum { scalar, array, set } increment; When I try to include the header file I get an ambiguity error for "set". I am using the std::set in this cpp file . The issue is the compiler is unable to differentiate between the std::set and the set in the enum . Any suggestions to resolve this ambiguity without declaring any new namespace
Don't import the std namespace into the global namespace. The STL set is in the std namespace so if you don't have the line using namespace std in your headers you shouldn't get a conflict. Beyond that, refactor your enum.
2,265,022
2,265,161
Alternative for templates in C++
I wrote code that looked like the following: template<typename CocoaWidget> class Widget : boost::noncopyable { private: CocoaWidget* mCocoaWidget; public: Widget() { mCocoaWidget = [[CocoaWidget alloc] init]; } // ... }; class Button : Widget<NSButton> { // ... }; But that doesn't work, because Mac Dev Center says: Objective-C classes, protocols, and categories cannot be declared inside a C++ template So what shall I do now best?
Are you sure you can't do this (have you tried)? The quote from Mac Dev Center says you can't declare an Objective-C class inside a template. What you're doing, however, is merely declaring a pointer to an Objective-C object inside a template -- quite a different thing, and I don't see a reason why it shouldn't be allowed (though I have never tried).
2,265,027
2,265,065
problem mixing c and c++
i need to build a c++ project that exports functions to c project this is my c++ class : ** MyCppClass.h ** class MyCppClass { public: static void MyCppMethod() } ** MyCppClass.cpp ** void MyCppClass::MyCppMethod(){} *now i need to create an interface for the Method MyCppMethod (static). i did that : ** MyExport.h** #define Export __declspec(dllexport) extern "C" void Export MyCppMethodWrapper(); ** MtExport.cpp** #include "MyCppClass.h" #include "MyExport.h" void MyCppMethodWrapper() { MyCppClass::MyCppMethod();} thats it ! now the C part (different project) i linked the project with MyExport.lib ** program.c** #include "MyExport.h" ->does not compile because of the extern "C" int main() { MyCppMethodWrapper(); } if i do not add the line : #include "MyExport.h" at program.c the program compiles and work fine but i need to provide an header for the exports (the client needs the header) and i want to make the program use that header. how can i resolve that ??? thanks for your answers
you can easily conditionally define the extern if that is what you want to do as such: #ifdef __cplusplus #define EXTERN_C extern "C" #else #define EXTERN_C #endif And then: EXTERN_C Export MyCppMethodWrapper();
2,265,187
2,265,222
start/stop thread in ctor/dtor or better use start()/stop()?
I've a class that internally uses a worker thread. Currently the ctor starts the thread and the dtor stops (and waits for) it. Is this considered good code? I think it would be better to have separate start() / stop() functions for this purpose. One of the problems is that stopping and waiting for the thread may throw exceptions, which is bad in a dtor. What would you advice me: leave the code as it is and just catch and log exceptions in the dtor use start() / stop(), let the client handle exceptions and just delete the thread in the dtor (and issue a warning on unclean shutdown or something)
I would probably not start the thread in the constructor, but rather have a start function. If the worker thread is basically invisible to the user then it might make little difference, and starting in the constructor might be better. But if the user interacts with the worker thread in any way (e.g. their code is run in it), then eventually someone will need to set up some state after the object is created, but before the thread runs. Murphy's Law guarantees it ;-) I would stop it in the destructor, and catch and log the exception. If the user is likely to need to know the result of stopping (for instance if failure means that the worker thread might not have done its work), then also have a stop function which they can optionally call in order to get that information. Btw, there are also some technical concerns to do with starting a thread in a constructor at all. The new thread will potentially run before the constructor returns in the old thread. If it accesses its owner object (for example to report the result), it can therefore access an incompletely-constructed object. That's usually easy to work around, right up to the point where you inherit from your original class. Now the thread is started before the derived class constructor runs, which could cause all kinds of trouble. So if you do start a thread in a constructor, and the thread can access the object directly or indirectly, take care and leave lots of warnings.
2,265,192
2,265,212
Sound capture in CPP and Qt
I would like to capture some sound from the microphone in cpp, in order to use it in a Qt application. So I'm looking for a multi platform library easily integrable in a Qt4 project.
OpenAL is a good, cross-platform C++ library for capturing audio.
2,265,381
2,265,406
How do I check my template class is of a specific classtype?
In my template-ized function, I'm trying to check the type T is of a specific type. How would I do that? p/s I knew the template specification way but I don't want to do that. template<class T> int foo(T a) { // check if T of type, say, String? } Thanks!
I suppose you could use the std::type_info returned by the typeid operator
2,265,518
2,265,540
returning two created arrays in c++
Hi I have a text file containing two arrays and one value(all integers) like this 3 90 22 5 60 33 24 Where the first number stands for how many integers to read in. I can read in all this in one function. Do I need several functions to be able to use the different matrices and the first variable? ifstream in(SOMEFILE.dat); if (!in) { cerr << "Cannot open file.\n"; return -1;} in >> VAR; A=new int[VAR]; B=new int[VAR]; for(int i=0 ;i<VAR;i++){ in >>A[i]; } for(int i=0 ;i<VAR;i++){ in >>B[i]; } in.close(); Above is the code I have so far and this would work in the main function. Do I have to write three functions to read this info in so I can use it in my program or is there any way I could for example send in three pointers to a function? I would like A to be 90 22 5 B to be 60 33 24 And VAR to be 3 Thanks
Whenever you want to group together data items, use a class or a structure. For example, to pass three integers as x, y and z coordinates,: struct Coord { int x, y, z; }; and then pass the structure to the function: void f( Coord & c ) { } The same goes for arrays, but in your case you would make the structure contain pointers. Your question actually opens up huge areas of C++ programming that it seems you are not aware of. Some things you should read up on before you go any further: the concept of structures, as outlined above constructors and destructors for structures when and when not to use dynamic memory allocation use of C++ standard library containers like std::vector This may seem a lot, but once you have a clear grip on these, you will find C++ programming much, much easier and safer.
2,265,650
2,718,770
How can I send messages to/from a Websphere Message Broker from an embedded C client (no JVM)?
What are my options for pubsubing (or point to point but pubsub is better) messages to and from an IBM message broker from an embedded headless C/C++ linux client that doesn't have a JVM? Ideally we want large file transfer (2GB once per day off of the client) encryption (SSL) reliable ('assured' delivery / QoS2, maybe QoS1 would do) The client in question currently only has exes and some bash scripts, I've been playing with MQTTv3 and RSMB, but for that I'd have to chomp the large files up (and reassemble back home) and I don't want to get into that if there's a transport that will do this for me? I've looked at MQTTv5 (but our client's got no JVM); JMS (no JVM) and XMS? which again looks like it gives me a C API but then needs the JVM to be installed on the client (or am I wrong?) Any clues or hints would be appreciated.
Why not just use the WMQ C/C++ API? The WMQ Client install is downloadable as SupportPac MQC7: WebSphere MQ V7.0 Clients. Once you have that, just use the C API and compile as usual. This is all native WMQ base product functionality. Note that the WMQ V7 QMgr with the WMQ v7 client provides much better interop with JMS, WMQ Broker and so forth, because all message attributes are now message properties and pub/sub is natively supported in WMQ v7 QMgrs. Also, v6 is end-of-life as of Sept 2011 so do as much new development on v7 components as possible to avoid migration later.
2,265,664
2,265,674
How to dynamically allocate an array of pointers in C++?
I have the following class class Node { int key; Node**Nptr; public: Node(int maxsize,int k); }; Node::Node(int maxsize,int k) { //here i want to dynamically allocate the array of pointers of maxsize key=k; } Please tell me how I can dynamically allocate an array of pointers in the constructor -- the size of this array would be maxsize.
Node::Node(int maxsize,int k) { NPtr = new Node*[maxsize]; } But as usual, you are probably better off using a std::vector of pointers.
2,265,671
2,265,953
How to force QDateTime::fromString to read UTC time
I have some input containing UTC time formatted according to iso8601. I try to parse it using QDateTime: const char* s = "2009-11-05T03:54:00"; d.setTimeSpec(Qt::UTC); d = QDateTime::fromString(s, Qt::ISODate); Qt::TimeSpec ts = d.timeSpec(); When this fragment ends, ts is set to localTime and d contains 3 hours 54 minutes. Does anyone know how to read the date properly?
What about setting the time spec after the fromString method. const char* s = "2009-11-05T03:54:00"; d = QDateTime::fromString(s, Qt::ISODate); d.setTimeSpec(Qt::UTC); Qt::TimeSpec ts = d.timeSpec();
2,265,967
2,265,981
Writing a LinkedList destructor?
Is this a valid LinkedList destructor? I'm still sort of confused by them. I want to make sure I'm understanding this correctly. LinkedList::~LinkedList() { ListNode *ptr; for (ptr = head; head; ptr = head) { head = head->next delete ptr; } } So at the beginning of the loop, pointer ptr is set to hold the address of head, the first node in the list. head is then set to the next item, which will become the beginning of the list once this first deletion takes place. ptr is deleted, and so is the first node. With the first iteration of the loop, pointer is set to head again. The thing that concerns me is reaching the very last node. The condition "head;" should check that it is not null, but I'm not sure if it will work. Any help appreciated.
Why not do it much much simpler - with an elegant while-loop instead of trying to carefully analyze whether that overcompilcated for-loop is correct? ListNode* current = head; while( current != 0 ) { ListNode* next = current->next; delete current; current = next; } head = 0;
2,266,179
2,266,192
C++ STL map I don't want it to sort!
This is my code map<string,int> persons; persons["B"] = 123; persons["A"] = 321; for(map<string,int>::iterator i = persons.begin(); i!=persons.end(); ++i) { cout<< (*i).first << ":"<<(*i).second<<endl; } Expected output: B:123 A:321 But output it gives is: A:321 B:123 I want it to maintain the order in which keys and values were inserted in the map<string,int>. Is it possible? Or should I use some other STL data structure? Which one?
There is no standard container that does directly what you want. The obvious container to use if you want to maintain insertion order is a vector. If you also need look up by string, use a vector AND a map. The map would in general be of string to vector index, but as your data is already integers you might just want to duplicate it, depending on your use case.
2,266,203
2,266,773
Using boost.assign on collection of shared_ptr
Consider the following snippet: class Foo { public: Foo( int Value ); // other stuff }; std::list< boost::shared_ptr< Foo > > ListOfFoo = list_of( 1 )( 2 )( 3 )( 4 )( 5 ); This does not work out of the box. What is the simplest way to make this work, or is there any method to assign values to ListOfFoo as simple as that?
boost::assign::ptr_list_of lets you construct a Boost pointer container with a very simple syntax. You can extend it through private inheritance so that it lets you create containers of shared_ptr: template< class T > struct shared_ptr_list : boost::assign_detail::generic_ptr_list<T> { typedef boost::assign_detail::generic_ptr_list<T> Base; template< class Seq > operator Seq() const { Seq result; for(typename Base::impl_type::iterator it = Base::values_.begin(), e = Base::values_.end(); it != e; ++it) result.push_back(typename Seq::value_type(&*it)); Base::values_.release().release(); return result; } template< class U > shared_ptr_list& operator()( const U& u ) { return (shared_ptr_list&)boost::assign_detail ::generic_ptr_list<T>::operator()(u); } }; template< class T, class U > shared_ptr_list<T> shared_ptr_list_of( const U& t ) { return shared_ptr_list<T>()(t); } It looks a bit ugly but then it's really convenient to use: int main() { using boost::shared_ptr; std::deque<shared_ptr<Foo> > deq = shared_ptr_list_of<Foo>(1)(2)(3); }
2,266,218
2,266,242
Memory / heap management across DLLs
Although it seems to be a very common issue, I did not harvest much information: How can I create a safe interface between DLL boundaries regarding memory alloction? It is quite well-known that // in DLL a DLLEXPORT MyObject* getObject() { return new MyObject(); } // in DLL b MyObject *o = getObject(); delete o; might certainly lead to crashes. But since interactions like the one above are - as I dare say - not uncommon, there has to be a way to ensure safe memory allocation. Of course, one could provide // in DLL a DLLEXPORT void deleteObject(MyObject* o) { delete o; } but maybe there are better ways (e.g. smart_ptr?). I read about using custom allocators when dealing with STL containers as well. So my inquiry is more about general pointers to articles and/or literature dealing with this topic. Are there special fallacies to look out for (exception handling?) and is this problem limited to only DLLs or are UNIX shared objects "inflicted" too?
As you suggested, you can use a boost::shared_ptr to handle that problem. In the constructor you can pass a custom cleanup function, which could be the deleteObject-Method of the dll that created the pointer. Example: boost::shared_ptr< MyObject > Instance( getObject( ), deleteObject ); If you do not need a C-Interface for your dll, you can have getObject return a shared_ptr.
2,266,290
2,266,527
Link a static library to a DLL
I am using Visual Studio 5.0 I have DLL and a static library . My intention is to use a static function that is defined in the static library . I have included the header file in the intended source cpp and also given the path in the project dependencies . Still it gives me linker errors . Following is the linker error error LNK2019: unresolved external symbol "public: static bool __cdecl gph::IsA(class PtOnDemand &,wchar_t const *)" (?IsA@gph@@SA_NAAVPtOnDemand@@PB_W@Z) referenced in function "private: int __thiscall PtXMLP::HandleObjectBegin(char const *,char const * *)" (?HandleObjectBegin@PtXMLP@@AAEHPBDPAPBD@Z) 1>.\ReleaseU/epptxml.dll : fatal error LNK1120: 1 unresolved externals Any suggestions
It could be that the linker is not finding your function because it is compiled with different settings. Like release vs debug, unicode vs non-unicode, differences in calling conventions. That may cause the name to be mangled differently. If the .h file is written in c, not c++, you might need to disable name mangling altogether by wrapping the prototypes in extern "C" { // function prototypes go here. }
2,266,317
2,266,384
Question on Call-By-Reference?
main() calls Call_By_Test() function with argument parameter First Node. I have freed the First Node in Call_By_Test() but First node address not freed in main(), why ?. typedef struct LinkList{ int data; struct LinkList *next; }mynode; void Call_By_Test(mynode * first) { free(first->next); first->next = (mynode *)NULL; free(first); first = (mynode *)NULL; } int main() { mynode *first; first = (mynode *)malloc(sizeof(mynode)); first->data = 10; first->next = (mynode *)NULL; cout<<"\n first pointer value before free"<<first<<endl; Call_By_Test(first); // we freed first pointer in Call_By_Test(), it should be NULL if(first != NULL) cout<< " I have freed first NODE in Call-By-Test(), but why first node pointer has the value "<<first<<endl; } Output: first pointer value 0x804b008 I have freed first NODE in Call-By-Test(), but why first node pointer has the value 0x804b008
Since the question is tagged c++, I would refactor to: void Call_By_Test( mynode *& first ) // rest of code remains the same That conveys the pass-by-reference without extra dereferences. All the solutions that propose passing a pointer to the pointer (void Call_By_Test( mynode ** first )) are using pass-by-value semantics in a pointer to the pointer variable. While you can do this in C++, pass-by-reference is clearer.
2,266,417
2,269,330
Delphi: Calling a function from a vc++ dll that exports a interface / class
i have some trouble accessing a dll written in vc++ that exports an interface. First i tried to use classes, but after some google-search i came to the solution, that this i not possible. I just want to make sure, that the plugin interface can accessed, by using other languages like c++. Delphi Interface IPlugIn = interface function GetName: WideString; stdcall; end; Delphi Plugin call procedure TForm1.Button5Click(Sender: TObject); var hLib: Cardinal; MLoadPlugIn: TLoadPlugIn; PlugIn: IPlugIn; begin hLib := LoadLibrary('PluginB.dll'); try if not(hLib = 0) then begin @MLoadPlugIn := GetProcAddress(hLib, 'LoadPlugIn'); if not(@MLoadPlugIn = nil) then begin if MLoadPlugIn(PlugIn) then try ShowMessage(PlugIn.GetName); // here i get the access-violation using the vc++ plugin finally // i get the return value but the instance is not created PlugIn := nil; end; end else raise Exception.Create(''); end; finally FreeLibrary(hLib); end; end; Delphi plugin dll TMyPlugin = class(TInterfacedObject, IPlugIn) public function GetName: WideString; stdcall; end; function TMyPlugin.GetName; begin result := 'TMyPlugin'; end; function LoadPlugIn(var PlugIn: IPlugIn): Boolean; stdcall; begin try PlugIn := TMyPlugin.Create; result := True; except result := False; end; end; exports LoadPlugIn; vc++ plugin dll // IPlugIn __interface //__declspec(uuid("E44BB34F-D13F-42D7-9479-4C79AF5C0D1B")) IPlugIn : public IUnknown { void _stdcall GetName(BSTR* result); }; // TMyPlugIn header class TMyPlugIn : public IPlugIn { public: // Constructor TMyPlugIn() : m_cRef(1) {} // Destructor ~TMyPlugIn() {} // Needed to implement IUnknown used by COM to acces your component HRESULT _stdcall QueryInterface(const IID& iid, void** ppv); ULONG _stdcall AddRef(); ULONG _stdcall Release(); void _stdcall GetName(BSTR* result); private: long m_cRef ; }; // TMyPlugIn cpp HRESULT _stdcall TMyPlugIn::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown) { *ppv = static_cast<IPlugIn*>(this) ; } else if (iid == IID_IPlugIn) { *ppv = static_cast<IPlugIn*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG _stdcall TMyPlugIn::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG _stdcall TMyPlugIn::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } void _stdcall TMyPlugIn::GetName(BSTR* result) { string s1 = "PluginName"; *result = A2WBSTR(s1.c_str()); } // the export function from the cpp plugin extern "C" bool __declspec(dllexport) __stdcall LoadPlugIn(IPlugIn* PlugIn); bool __declspec(dllexport) __stdcall LoadPlugIn(IPlugIn* PlugIn) { PlugIn = new TMyPlugIn; return TRUE; }
You get the access violation because this code extern "C" bool __declspec(dllexport) __stdcall LoadPlugIn(IPlugIn* PlugIn); bool __declspec(dllexport) __stdcall LoadPlugIn(IPlugIn* PlugIn) { PlugIn = new TMyPlugIn; return TRUE; } creates an instance of your plugin class and writes the address to the stack, where it quickly will be forgotten. Back in the Delphi program the original plugin interface variable is still nil, so calling a method on it crashes. You need to mimic what QueryInterface() does, like so: extern "C" bool __declspec(dllexport) __stdcall LoadPlugIn(IPlugIn** PlugIn); bool __declspec(dllexport) __stdcall LoadPlugIn(IPlugIn** PlugIn) { *PlugIn = new TMyPlugIn; return TRUE; } This passes the address of the interface variable, and the address of the plugin instance will be written to the variable.
2,266,452
2,270,723
How to programmatically clear the Kerberos ticket cache
Does anyone know how to clear out the Kerberos ticket cache on the local computer - using managed \ unmanaegd code? Thanks in advance!
I believe you need to do a call to LsaCallAuthenticationPackage using KERB_PURGE_TKT_CACHE_REQUEST after using either LsaConnectUntrusted or LsaRegisterLogonProcess. Sorry no specifics, but I don't have my code for this around...
2,266,735
2,268,489
Make an executable at runtime
Ok, so I was wondering how one would go about creating a program, that creates a second program(Like how most compression programs can create self extracting self excutables, but that's not what I need). Say I have 2 programs. Each one containing a class. The one program I would use to modify and fill the class with data. The second file would be a program that also had the class, but empty, and it's only purpose is to access this data in a specific way. I don't know, I'm thinking if the specific class were serialized and then "injected" into the second file. But how would one be able to do that? I've found modifying files that were already compiled fascinating, though I've never been able to make changes that didn't cause errors. That's just a thought. I don't know what the solution would be, that's just something that crossed my mind. I'd prefer some information in say c or c++ that's cross-platform. The only other language I'd accept is c#. also I'm not looking for 3-rd party library's, or things such as Boost. If anything a shove in the right direction could be all I need. ++also I don't want to be using a compiler. Jalf actually read what I wrote That's exactly what I would like to know how to do. I think that's fairly obvious by what I asked above. I said nothing about compiling the files, or scripting. QUOTE "I've found modifying files that were already compiled fascinating" Please read and understand the question first before posting. thanks.
Building an executable from scratch is hard. First, you'd need to generate machine code for what the program would do, and then you need to encapsulate such code in an executable file. That's overkill unless you want to write a compiler for a language. These utilities that generate a self-extracting executable don't really make the executable from scratch. They have the executable pre-generated, and the data file is just appended to the end of it. Since the Windows executable format allows you to put data at the end of the file, caring only for the "real executable" part (the exe header tells how big it is - the rest is ignored). For instance, try to generate two self-extracting zip, and do a binary diff on them. You'll see their first X KBytes are exactly the same, what changes is the rest, which is not an executable at all, it's just data. When the file is executed, it looks what is found at the end of the file (the data) and unzips it. Take a look at the wikipedia entry, go to the external links section to dig deeper: http://en.wikipedia.org/wiki/Portable_Executable I only mentioned Windows here but the same principles apply to Linux. But don't expect to have cross-platform results, you'll have to re-implement it to each platform. I couldn't imagine something that's more platform-dependent than the executable file. Even if you use C# you'll have to generate the native stub, which is different if you're running on Windows (under .net) or Linux (under Mono).
2,266,975
2,267,189
Can I measure the necessary buffer for sprintf in Microsoft C++?
I'm writing a small proof-of-concept console program with Visual Studio 2008 and I wanted it to output colored text for readability. For ease of coding I also wanted to make a quick printf-replacement, something where I could write like this: MyPrintf(L"Some text \1[bright red]goes here\1[default]. %d", 21); This will be useful because I also build and pass strings around in some places so my strings will be able to contain formatting info. However I hit a wall against wsprintf because I can't find a function that would allow me to find out the required buffer size before passing it to the function. I could, of course, allocate 1MB just-to-be-sure, but that wouldn't be pretty and I'd rather leave that as a backup solution if I can't find a better way. Also, alternatively I'm considering using std::wstring (I'm actually more of a C guy with little C++ experience so I find plain-old-char-arrays easier for now), but that doesn't have anything like wsprintf where you could build a string with values replaced in them. So... what should I do?
You want _snwprintf. That function takes a buffer size, and if the buffer isn't big enough, just double the size of the buffer and try again. To keep from having to do multiple _snwprintf calls each time, keep track of what the buffer size was that you ended up using last time, and always start there. You'll make a few excess calls here and there, and you'll waste a bit of ram now and then, but it works great, and can't over-run anything.
2,267,026
2,267,633
Crypto++ Version 5.6.0
anyone used the latest version of cryptopp. i think its 5.6.0. I have a solution working in unix. but in windows I am stuck. Anyone here already using cryptopp 5.6 in vs2008 could you please give very specific instructions on how you compiled this? i have also posted in the cryptopp user groups for an answer. There are some instructions but for vs 6.0 and not the version i am using. So, I am not sure how to proceed. The errors are as follows: error: lnk2005 already defined in cryptlib(iterhash.obj) (cryptlib.obj)
All I did was open the cryptest.sln file and tell it to build. EDIT: Visual Studio did have to convert from VS2005 format but it compiles and runs just fine.
2,267,253
2,267,492
rotation, translation in opengl through header file?
I've a header file called base.h which has all initial display and stuff like, my main aim is to simulate a robot with degree of freedom. class center_rods { public: center_rods() { } void draw_center_rod() { glPushMatrix(); glTranslatef(0,1,0); glRotatef(90.0,1.0,0.0,0.0); glScalef(0.3,5,0.3); glColor3f(0,0,1); glutSolidCube(1.0); glPopMatrix(); } /* design and implementation of clamp holder of center rod, needs to be done */ }; class base_of_robot: public base1 { public: base_of_robot() { } in main program called robo.cpp, I want to achieve these things, can I pass arguements from main program to header file? because I use a glutkeyBoardFunc(), so I need my robot arm to translate and rotate based upon keys, like this: case 'a': to_arm = 0, fro_arm = 0; glutTimerFunc(100, myTimerFunc, 3); break; How do I pass parameters to header file, since all re-display is controlled from the header file.
You should put some state to represent the transformations inside one of the classes (probably the robot). You can represent the orientation as Euler angles, a matrix or quaternion, but Euler angles are probably the simplest to start out with. The glutkeyBoardFunc function should then modify this state through member functions defined on the enclosing class, like RotateX(float amountInRadians). Your draw functions should be based on the state in the classes. This way, you are passing data into an instance of the class defined in the header file. Taking a step back, you should search for a basic tutorial on using glut which will show you how you might structure your program (e.g http://nehe.gamedev.net/). Many of these are written in C (or are largely procedural), so they often don't illustrate the object oriented design you hinted at.
2,267,262
2,267,363
Storing data effectively
maybe i'm having stupid question as always, but somehow i can't google out how should I store variables so it's effective. Our teacher on c++ just by the way droped something about how could size of the stored data type affect the speed of storing it (like searching for closest sufficient continuous block of memory) and I would like to find out more about it. Could you please give me some directions?
In general for numeric variables (such as loop counters) you should use "int" and let the compiler choose the most efficient size for the task. If you have a particular need for a specific size (eg uint16 for a 16-bit part of a packet header being received off a network, or similar) then use a typedef that gives that specific size on your specific platform; otherwise, just use int. That said, it sounds like your teacher may have been talking about dynamic memory allocators (i.e. the code behind "malloc" and "free"). If you request to allocate 64 bytes, say, the allocator is responsible for providing you with a block of at least that size, and keeping track of it so it can be returned to available storage when it is freed. There's a lot of info about these, for example on Wikipedia here: http://en.wikipedia.org/wiki/Dynamic_memory_allocation
2,268,339
2,268,647
Change version of documented code in doxygen (without using macros)
Is there any way to change the version in a comment block? For e.g. const char VER[] = "1.2.3.4"; /** * \version (VER) */ I know how to do this with preprocessing and I was wondering if there were any other way? On a related note, how do you guys handle changing version numbers in documentation, the application, etc. without changing different version numbers all over the place? Right now I have a VER-like variable in a namespace accessible by all (essentially global without namespace pollution).
Most developers use a source control tool which usually provides a mechanism for obtaining the current revision, stringizing it, and inserting into the source. Something along the lines of const char *VER = "$Rev$";
2,268,478
2,268,538
unable to start "program.exe" the system cannot find the file specified vs2008
I am able to successfully build solution. but i keep getting this when i try to start debugging or executing it. any suggestions why this might be the case? update: i fixed the issue. I just recreated the proj with empty files and then just rebuild and it worked. one question: when i start the program (its a console app) how do i stop it from disappearing when i try to enter any input from within vs2008? thanks
Make sure the debug command (Properties > Configuration Properties > Debugging > Command) is pointing to the output file built by your selected configuration. (Properties > Configuration Properties > General > Output Directory), (Properties > Configuration Properties > Linker > General > Output File)
2,268,562
2,268,587
What are intrinsics?
Can anyone explain what they are and why I would need them? What kind of applications am I building if I need to use intrinsics?
Normally, "intrinsics" refers to functions that are built-in -- i.e. most standard library functions that the compiler can/will generate inline instead of calling an actual function in the library. For example, a call like: memset(array1, 10, 0) could be compiled for an x86 as something like: mov ecx, 10 xor eax, eax mov edi, offset FLAT:array1 rep stosb Intrinsics like this are purely an optimization. "Needing" intrinsics would most likely be a situation where the compiler supports intrinsics that let you generate code that the compiler can't (or usually won't) generate directly. For an obvious example, quite a few compilers for x86 have "MMX Intrinsics" that let you use "functions" that are really just direct representations of MMX instructions.
2,268,749
2,268,783
Defining global constant in C++
I want to define a constant in C++ to be visible in several source files. I can imagine the following ways to define it in a header file: #define GLOBAL_CONST_VAR 0xFF int GLOBAL_CONST_VAR = 0xFF; Some function returing the value (e.g. int get_GLOBAL_CONST_VAR()) enum { GLOBAL_CONST_VAR = 0xFF; } const int GLOBAL_CONST_VAR = 0xFF; extern const int GLOBAL_CONST_VAR; and in one source file const int GLOBAL_CONST_VAR = 0xFF; Option (1) - is definitely not the option you would like to use Option (2) - defining instance of the variable in each object file using the header file Option (3) - IMO is over killing in most cases Option (4) - in many cases maybe not good since enum has no concrete type (C++0X will add possibility to define the type) So in most cases I need to choose between (5) and (6). My questions: What do you prefer (5) or (6)? Why (5) is ok, while (2) is not?
(5) says exactly what you want to say. Plus it lets the compiler optimize it away most of the time. (6) on the other hand won't let the compiler ever optimize it away because the compiler doesn't know if you'll change it eventually or not.
2,268,762
3,086,422
How to add statusbar correctly?
Currently it is floating on top of my rendered window, i dont think thats good for few reasons: 1) i waste rendering time for rendering stuff that isnt visible. 2) it must be rendered every frame again when i wouldnt be updating the whole statusbar every frame anyways. So how i could create a window where it leaves space for my statusbar and none of my OpenGL stuff could be rendered in that area? At this moment i just adjust my viewports in a way that creates empty space for statusbar, but it causes some problems in my current way of doing things. i would have to make my code look much more messier to make it work.
http://www.gamedev.net/community/forums/topic.asp?topic_id=291682 Edit: Its not a simple question to answer. If you don't know what a child window is under Win32 then you may be in a much better position. However asking someone to give you a full explanation of the windows windowing system is no mean feat. Here is an overview: Basically you need to create a child window which can be done using CreateWindow to create a window with the WS_CHILD style and with its hWndParent parameter set to the window handle you want the new window to be a child of. When you created the window you will have, necessarily, create a window procedure When you call DispatchMessage from your message pump (The Loop that does a Get/PeekMessage and then dispatches the messages is the message pump). Inside the window procedure you can then switch on the message type and handle each message sent to your window. From here you can handle things like setup. Your initial window will have either a WM_CREATE or a WM_INITDIALOG (Depending on what type of window you create). It is from there that you need to create the child windows (Don't forget to call ShowWindow to make them visible!!). From this point you can then set up the DirectX device to be attached to the child window handle (HWND). Furthermore if you want to be able to re-size the window then you ALSO need to take into account the WM_SIZE mesage. However I'd strongly recommend trying to get the rest working before even beginning to look into this as it gets very complicated as you will need to destroy and re-create your DirectX device so that it is the right size. Anyway thats just a simple overview. I hope it helps!
2,268,768
2,268,802
anyone know how to add command line args in vs2008
i have a program that runs like so: a.out 23421232 now if i use a.out it will tell me check params and gives an example and closes. I am curious if there is a way to add command line args when executing my code in vs2008?
VS doesn't normally produce an executable named a.out like most Unix compilers do. Instead, given an input XXX.cpp, it'll produce an executable named XXX.exe. Adding command line arguments is done by bringing up the project properties (Alt+F7), selecting "Debugging" and then entering the argument(s) in the "Command Arguments" control. There, you'll add JUST the argument "23421232" (or whatever).
2,268,790
2,269,256
How to debug application when third-party library provides no debug build?
I have an application I'm working on that uses two third party libraries, each with pre-compiled libs and dlls, one of which provides necessary .lib files for both debug and release builds (A[d].lib) and the other which provides only .lib files for release builds (B.lib). Compiling in Release mode (using MSVC9) works fine, however attempting to compile in debug mode fails because third party A requires LIBCMTD.lib (or MSVCRTD.lib) while third party B requires LIBCMT.lib (or MSVCRT.lib). Can I work around this or am I stuck debugging in release mode?
Do you want full debug mode, or do you just want to be able to debug? If the later is the case, just go to the linker options, and turn on the generation of symbolic information (.pdb). This way you can use the debugger in your own code, step through the lines, and look at variables. If you get annoyed by the changes in control flow that the optimizers create, you can go to the compiler options, and turn off optimizations. This way you get to use the debugger AND build in release mode. Once you're happy with your code, you just change the settings back to creating optimized code.
2,269,003
2,270,101
C++ - What libraries or command line programs will I need to create a program that takes an AVI file and burns it to a DVD?
My goal is to create a program that will take an AVI file as input and then do whatever is necessary to burn it to a DVD. Currently, I use three separate programs to accomplish this. The first tool requires me to convert it from an AVI file to an MPEG. The second tool takes that MPEG and creates DVD files (a VIDEO_TS folder, with a few files inside of it). The third tool burns the folder to the DVD. I would like to combine these three tools into one, and if possible skip the AVI to MPEG conversion and just create the DVD files and burn them. The target platform is Windows 7 and the language I'm going to use is C++. What libraries or command line programs will help me on my quest for glory? EDIT: To clarify, I want to create a video DVD to play movies on a DVD player. (Thanks Jerry) EDIT 2: I ended up using Python on Linux to automate everything. Here is the script in case anyone needs it. (Note: this is my first python script so it probably isn't very good) import sys import os import shutil from subprocess import call # step 1: call ffmpeg and convert the input avi to an mpeg-2 def avi_to_mpeg(input, output): return call(["ffmpeg", "-i", input, "-target", "ntsc-dvd", "-threads", "4", output]) # step 2: create the xml file needed for dvdauthor def create_xml_file(mpg_source, xml_file): with open(xml_file, "w") as file: file.write("<dvdauthor>\n") file.write("\t<vmgm />\n") file.write("\t<titleset>\n") file.write("\t\t<titles>\n") file.write("\t\t\t<pgc>\n") file.write("\t\t\t\t<vob file=\"" + mpg_source + "\" />\n") file.write("\t\t\t</pgc>\n") file.write("\t\t</titles>\n") file.write("\t</titleset>\n") file.write("</dvdauthor>\n") return os.path.isfile(xml_file) # step 3: invoke dvdauthor def author_dvd(mpg_source): return call(["dvdauthor", "-o", "mkdvd_temp", "-x", xml_file]) # step 4: finally, burn the files to the dvd def burn_dvd(dvd_target): return call(["growisofs", "-Z", dvd_target, "-dvd-video", "mkdvd_temp"]) # step 5: clean up the mess def clean_up(mpg_source, xml_file): shutil.rmtree("mkdvd_temp") os.remove(mpg_source) os.remove(xml_file) def eject(dvd_target): return call(["eject", dvd_target]) def print_usage(): print "mkdvd by kitchen" print "usage: mkdvd -s file.avi -t /dev/disc" print " -s : Input .AVI file" print " -t : Target disc, /dev/dvd for example" def get_arg(sentinel): last_arg = "" for arg in sys.argv: if last_arg == sentinel: return arg last_arg = arg return None # program start avi_source = get_arg("-s") # input .avi file dvd_target = get_arg("-t") # the disc to burn it to (/dev/dvd for example) if avi_source == None or dvd_target == None: print_usage() sys.exit("Not enough parameters.") if os.path.isfile(avi_source) == False: sys.exit("File does not exists (" + avi_source + ")") mpg_source = avi_source + ".mpg" if avi_to_mpeg(avi_source, mpg_source) != 0: sys.exit("Failed to convert the AVI to an MPG") xml_file = mpg_source + ".xml" if create_xml_file(mpg_source, xml_file) == False: sys.exit("Failed to create the XML file required by dvdauthor") if author_dvd(mpg_source) != 0: sys.exit("Failed to create the DVD files") if burn_dvd(dvd_target) != 0: sys.exit("Failed to burn the files to the disc") print "mkdvd has finished burning " + avi_source + " to " + dvd_target print "Cleaning up" clean_up(mpg_source, xml_file) eject(dvd_target)
I know you are using Windows, but here are the steps I take to create a DVD from multiple AVIs on linux. The main three programs are ffmpeg to do the transcoding, dvdauthor to build the DVD filesystem, and growisofs to make a DVD image out of the DVD filesystem. I think you can find windows binaries for each of them through Google (I was just able to rather quickly, but I don't want to paste all of the links). Transcode each avi: ffmpeg -i <infile.avi> -target ntsc-dvd -threads 2 <outfile.mpg> Create xml file for DVD author: Example: <dvdauthor dest="dvd"> <vmgm> </vmgm> <titleset> <titles> <pgc> <vob file="<file1.mpg>" chapters="0,5:00,10:00,15:00,20:00,25:00,30:00,35:00,40:00" /> </pgc> <pgc> <vob file="<file2.mpg>" chapters="0,5:00,10:00,15:00,20:00,25:00,30:00,35:00,40:00" /> </pgc> </titles> </titleset> </dvdauthor> Create DVD file structure (will create it at the dest shown above): dvdauthor -x <xmlfile.xml> Roll filesystem into an iso and burn it. growisofs -Z /dev/dvd -dvd-video dvd/ where dvd/ is where the DVD filesystem was created. This process could be automated fairly easily by just calling the correct command line programs and creating the dvdauthor xml file. You'll want to read the documentation for dvdauthor to find out all the details about the xml file that defines your DVD. You'll also probably have to replace /dev/dvd/ in the growisofs command to the windows DVD burner drive letter. About your hope that you could skip the transcode from avi to mpeg-2: there is no way to do this and still make it compatible with the DVD standard which strictly requires MPEG-2 video in an MPEG-PS (Program Stream) container.
2,269,546
2,269,613
How to construct a std::list iterator in loop with increment
I'm trying to do a double-loop over a std::list to operate on each pair of elements. However, I'm having some trouble initialising the second iterator. The code I'd like to write is: for(std::list<int>::iterator i = l.begin(); i != l.end(); ++i) { for(std::list<int>::iterator j = i+1; j != l.end(); ++j) { ... } } That doesn't work because list iterators aren't random-access, so you can't do +1. But I'm having some trouble finding a neat alternative; the compiler doesn't seem to be very happy with std::list<int>::iterator j(i)++; which I had some hope for. Achieving what I want seems like I'm going to have to have some awkward extra increment which won't fit the structure of the for loop nicely. There are obvious alternatives (using a vector, for example!) but it seems to me that there should be some reasonably neat way of doing this which I'm just not seeing at the moment. Thanks in advance for any help :)
How about: for (std::list<int>::iterator i = l.begin(); i != l.end(); ++i) { for (std::list<int>::iterator j = i; ++j != l.end(); ) { // ... } }
2,269,865
2,269,876
How to create a Taskbar on multiple monitors?
I have three monitors and I want too create a taskbar on all three of them in C++ ?
There are various solutions already available to do this; in the past I've used UltraMon but recently I have switched to DisplayFusion as it does a better job replicating the Windows 7 Taskbar.
2,269,918
2,269,979
C++ Win32, easiest way to show a window with a bitmap
It's only for 'debugging' purposes, so I don't want to spend a lot of time with this, nor it is very important. The program exports the data as a png, jpg, svg, etc... -so it's not a big deal, though it could be good to see the image while it is being generated. Also, the program is going to be used in a Linux server; but I'll limit this 'feature' to the Win version. I also don't want to use a library, except if it is very, very lightweight (I used CImg for a while, but I wasn't very happy with its speed, so I ended up writing the important functions myself and just using libjpeg and libpng directly). I have the image in an ARGB format (32bpp), though converting the format won't be a problem at all. I would like to use Win32, creating a window from a function deep inside the code (no known hInstance, etc), and writing the bitmap. Fast and easy, hopefully. But I don't know the win32api enough. I've seen that the only option to draw (GDI) is trough a HBITMAP object... Any code snippet or example I can rely on? Any consideration I might not overlook? Or maybe -considering my time constrains- should I just forget it? Thanks!
The biggest piece of work here is actually registering the window class and writing a minimal window procedure. But if this is debug only code, you can actually skip that part. (I'll come back to that later). If you have an HBITMAP, then you would use BitBlt or StretchBlt to draw it, but if you don't already have the image as an HBITMAP, then StretchDIBits is probably a better choice since you can use it if you only have a pointer to the bitmap data. You have to pass it a source and destination rectangle, a BITMAPINFOHEADER and a pointer to the raw bitmap data. Something like this SIZE sBmp = { 100, 200 }; LPBITMAPINFOHEADER pbi; // the bitmap header from the file, etc. LPVOID pvBits; // the raw bitmap bits StretchDIBits (hdc, 0, 0, sBmp.cx, sBmp.cy, 0, 0, sBmp.cx, sBmp.cy, pvBits, pbi, DIB_RGB_COLORS, SRCCOPY); So the next part is how do I get a HDC to draw in? Well for Debug code, I often draw directly to the screen. HDC hdc = GetDC(NULL) will get a DC that can draw to the screen, but there are security issues and it doesnt' work the same with Aero in Windows Vista, so the other way is to draw onto a window. If you have a window that you can just draw over, then HDC hdc = GetDC(hwnd) will work. The advantage of doing it this way is that you don't have to create and show a window, so it's less disruptive of code flow, It's helpful for debugging a specific problem, but not the sort of thing you can leave turned on all of the time. For a longer term solution, You could create a dialog box and put your bitmap drawing call in the WM_PAINT or WM_ERASEBKGND message handler for the dialog box. But I don't recommend that you show a dialog box from deep inside code that isn't supposed to be doing UI. Showing a window, especially a dialog window will interfere with normal message flow in your application. If you want to use a dialog box for this bitmap viewer, then you want that dialog window to be something that the User shows, and that you just draw onto if it's there. If you don't have access to an HINSTANCE, it's still possible to show a dialog box, it's just more work. That's sort of a different question.
2,270,047
2,270,061
How do I use errorno and _get_errno?
Calling system() to run an external .exe and checking error code upon errors: #include <errno.h> #include <stdlib.h> function() { errno_t err; if( system(tailCmd) == -1) //if there is an error get errno { //Error calling tail.exe _get_errno( &err ); } } First two compile errors: error C2065: 'err' : undeclared identifier error C2065: 'errno_t' : undeclared identifier Not sure why as I am including the required and optional header files? Any help is appreciated. Thank You.
A typical usage is like: if (somecall() == -1) { int errsv = errno; printf("somecall() failed\n"); if (errsv == ...) { ... } } which is taken from here.
2,270,073
2,271,649
How do I troubleshoot boost library/header inclusion via autoconf/automake?
I'm new to autom4te, and I'm trying to use autoconf/automake to build and link a C++ program on multiple architectures. Complicating the linking is the fact that the project requires boost (filesystem, system, program_options). I'm using boost.m4 (from http://github.com/tsuna/boost.m4/tree/), and it seems to locate all the libraries and headers successfully. Unfortunately, linking still fails, leaving me confused. These are the relevant lines of configure.ac: AC_CONFIG_MACRO_DIR([m4]) # ... AC_PROG_CXX AC_PROG_LIBTOOL # ... BOOST_REQUIRE([1.41.0]) BOOST_FILESYSTEM BOOST_SYSTEM BOOST_PROGRAM_OPTIONS # ... And in src/Makefile.am: bin_PROGRAMS = phenomatrix phenomatrix_CXXFLAGS = $(BOOST_CPPFLAGS) phenomatrix_LDFLAGS = $(BOOST_LDFLAGS) $(BOOST_SYSTEM_LDFLAGS) $(BOOST_FILESYSTEM_LDFLAGS) $(BOOST_PROGRAM_OPTIONS_LDFLAGS) # $(BOOST_SYSTEM_LIB) $(BOOST_PROGRAM_OPTIONS_LIB) $(BOOST_FILESYSTEM_LIB) phenomatrix_LIBS = $(BOOST_SYSTEM_LIBS) $(BOOST_FILESYSTEM_LIBS) $(BOOST_PROGRAM_OPTIONS_LIBS) phenomatrix_SOURCES = adjacency_list.cpp distance.cpp genephene.cpp knearest.cpp marshall.cpp oracle.cpp type_shield.cpp avgmindist.cpp euclidean.cpp hypergeometric.cpp main.cpp mindist.cpp partialbayes.cpp utilities.cpp These give no errors, and it even manages to find the libraries and headers: checking for Boost headers version >= 104100... yes checking for Boost's header version... 1_41 checking for the toolset name used by Boost for g++... gcc44 -gcc checking boost/system/error_code.hpp usability... yes checking boost/system/error_code.hpp presence... yes checking for boost/system/error_code.hpp... yes checking for the Boost system library... yes checking boost/filesystem/path.hpp usability... yes checking boost/filesystem/path.hpp presence... yes checking for boost/filesystem/path.hpp... yes checking for the Boost filesystem library... yes checking for boost/system/error_code.hpp... (cached) yes checking for the Boost system library... (cached) yes checking boost/program_options.hpp usability... yes checking boost/program_options.hpp presence... yes checking for boost/program_options.hpp... yes checking for the Boost program_options library... yes But then, when I run make, I get errors: libtool: link: g++ -g -O2 -o phenomatrix phenomatrix-adjacency_list.o phenomatrix-distance.o phenomatrix-genephene.o phenomatrix-knearest.o phenomatrix-marshall.o phenomatrix-oracle.o phenomatrix-type_shield.o phenomatrix-avgmindist.o phenomatrix-euclidean.o phenomatrix-hypergeometric.o phenomatrix-main.o phenomatrix-mindist.o phenomatrix-partialbayes.o phenomatrix-utilities.o -L/usr/local/lib -Wl,-rpath -Wl,/usr/local/lib phenomatrix-adjacency_list.o: In function `__static_initialization_and_destruction_0': /usr/local/include/boost/system/error_code.hpp:208: undefined reference to `boost::system::get_system_category()' /usr/local/include/boost/system/error_code.hpp:209: undefined reference to `boost::system::get_generic_category()' /usr/local/include/boost/system/error_code.hpp:214: undefined reference to `boost::system::get_generic_category()' /usr/local/include/boost/system/error_code.hpp:215: undefined reference to `boost::system::get_generic_category()' /usr/local/include/boost/system/error_code.hpp:216: undefined reference to `boost::system::get_system_category()' which repeat ad nauseum. I'm not even sure how to go about testing to see if it's including the right directories. Yes, I understand that there's a -t flag on g++, but I don't exactly know how to pass that (from within autom4te). I gather this has something to do with multiple versions of the boost libs and headers on the same machine, and there's not much I can do about that.
It does not compile because it the library are not properly set... The script does not configure correctly the -lboost_libraryname option. $(BOOST_PROGRAM_OPTIONS_LIB) -> $(BOOST_PROGRAM_OPTIONS_LIBS) in tyour makefil.am your_program_LDFLAGS The ax_boost_***.m4 script in the the following repository worked fine with me: Script listing (http://www.nongnu.org/autoconf-archive/The-Macros.html#The-Macros)
2,270,110
2,270,371
How to rotate Bitmap in windows GDI?
How would I go about rotating a Bitmap in Windows GDI,C++?
You can do it with GDI+ (#include <gdiplus.h>). The Graphics class has the RotateTransform method. That allows arbitrary rotations. Use Image::RotateFlip() if you only need to rotate by 90 degree increments, that's a lot more efficient.
2,270,138
2,270,210
Does passing an empty range (identical iterators) to an STL algorithm result in defined behavior?
Consider the following: std::vector<int> vec(1); // vector has one element std::fill(vec.begin(), vec.begin(), 42); std::fill(vec.begin()+1, vec.end(), 43); std::fill(vec.end(), vec.end(), 44); Will all of the std::fill usages above result in defined behavior? Am I guaranteed that vec will remain unmodified? I'm inclined to think "yes", but I want to make sure the standard allows such usage.
No, if doesn't cause undefined behavior. The standard defines empty iterator range in 24.1/7 and nowhere it says that supplying an empty range to std::fill algorithm causes undefined behavior. This is actually what one would expect from a well-thought through implementation. With algorithms that handle emtpy range naturally, imposing the requirement to check for empty range on the caller would be a serious design error.
2,270,166
2,270,198
boost::filesystem::create_directories(); adding folders to strange locations
I'm using boost to create a directory to place some temp files in. int main( int argc, char* argv[] ) { std::cout << "Current Dir: " << argv[0] << std::endl; boost::filesystem::create_directories( "TempFolder" ); return 0; } Now if double click the exe, the folder "TempFolder" is created in the same directory as the exe, which I expect. However if I now drag a file onto the exe the folder is created in "C:\Documents and Settings\0xC0DEFACE" which i certainly was not expecting. Seeing my app hasnt changed, and the dir being printed out hasnt changed, and my app is currently ignoring passed strings, why is the folder now being created in a new directory? im running windows XP, with VS9 and am using boost 1.39.
I think it's because of the way you 'execute' your binary. In the first case you double click it and it will run in 'current' directory. In the second case you drop file on it which causes different action by Windows to execute your binary. In the second case the binary runs in your 'home' directory I believe. It's the difference between how Windows executes your application. I've had similar issues when dropping files on my executable.
2,270,472
2,270,490
How to parse HTML in C++?
How would I go about parsing HTML in C++ on my Webserver Application?
libxml2 has a HTML parser. libxml++ is a wrapper for libxml2, but I'm not sure if it exposes the HTMLparser functionality.
2,270,527
2,283,599
How to code a new Windows Shell?
How would I go about coding a new Windows Vista Shell?
Everything you need to do as shell has never been documented, so there are some issues with file change notifications etc. The basics are: SystemParametersInfo(SPI_SETMINIMIZEDMETRICS,...MINIMIZEDMETRICS) with (undocumented?) flag 8 Register as the shell (SetShellWindow,SetProgmanWindow,ShellDDEInit,RegisterShellHook etc) Hide welcome screen by setting a signal ("msgina: ShellReadyEvent" and "ShellDesktopSwitchEvent") Start registry run key, start menu\startup and ShellServiceObjects Set registry Explorer\SessionInfo The good thing is, you are not the first to write a new shell, if you look around, you can find some obscure required info. Here is a list to get you started: https://web.archive.org/web/2019/http://www.lsdev.org/doku.php http://bb4win.cvs.sourceforge.net/bb4win/blackbox/Blackbox.cpp?revision=1.49&view=markup http://xoblite.net/source/Blackbox.cpp.html http://svn.reactos.org/svn/reactos/trunk/reactos/base/shell/ http://www.geoffchappell.com/viewer.htm?doc=studies/windows/shell/explorer/index.htm&tx=36
2,270,552
2,270,584
What is a packet UDP/TCP?
Im getting into Winsocks and is there any reference to tell me what a packet is. Like UDP/TCP Packets?
A good starting point for TCP/IP is here: http://en.wikipedia.org/wiki/Internet_Protocol_Suite, and for UDP here: http://en.wikipedia.org/wiki/User_Datagram_Protocol In addition, this looks like a pretty good introduction to Winsock in C++: http://www.madwizard.org/programming/tutorials/netcpp/
2,270,598
2,270,636
C++ template black magic
This needs only work in g++. I want a function template<typename T> std::string magic(); such that: Class Foo{}; magic<Foo>(); // returns "Foo"; Class Bar{}; magic<Bar>(); // returns "Bar"; I don't want this to be done via specialization (i.e. having to define magic for each type. I'm hoping to pull some macro/template black magic here. Anyone know how?) Thanks!
Try typeid(Foo).name() for a start. Parse as you see fit; will be implementation-dependent (but simply getting a string back is portable).
2,270,622
2,270,743
Program crash in x64, works fine in Win32
I'm working on an application which builds and runs fine in Win32. However, in x64, it builds but crashes on run. Looking at the code and narrowing down the problem, if I comment out the call to the below function, it runs with no problem. void vec3_copy (double* v1, const double* v2) { v1[0] = v2[0]; v1[1] = v2[1]; v1[2] = v2[2]; } I'm building in Visual Studio 2008 with the C/C++ compiler. All updates have been installed. Any ideas? EDIT 1 (to answer comments): The pointers should be valid, as in Win32, it runs fine. No code is change and a different path is not taken, unless the pointer are somewhat modified because its x64 (will look into this). Unfortunately, there is no information about the crash. In Windows 7, it simply saying that it is looking for a solution to the problem, finds nothing, and returns in the command prompt. In the event viewer, I was able to find the following information: Faulting application name: DRR_C.exe, version: 0.0.0.0, time stamp: 0x4b7a1ee1 Faulting module name: DRR_C.exe, version: 0.0.0.0, time stamp: 0x4b7a1ee1 Exception code: 0xc0000005 Fault offset: 0x0000000000003950 Faulting process id: 0x16a4 Faulting application start time: 0x01caaec078a9c84a Faulting application path: D:\Development\gpu\dev\DRR_C\x64\Debug\DRR_C.exe Faulting module path: D:\Development\gpu\dev\DRR_C\x64\Debug\DRR_C.exe EDIT 2 (to answer more comments): Modified the line to, memcpy(v1, v2, 3 * sizeof(double)); New error info has the same exception code and fault offset.
The fact that it still crashes with memcpy confirms that the source of the bad pointer is elsewhere, as expected. How big is the application? It looks like somewhere along the line, a pointer was truncated to 32 bits or otherwise corrupted. Most likely you will need to spend some quality time with the debugger to track down the exact location.
2,270,726
2,270,745
How to determine the size of an array of strings in C++?
I'm trying to simply print out the values contained in an array. I have an array of strings called 'result'. I don't know exactly how big it is because it was automatically generated. From what I've read, you can determine the size of an array by doing this: sizeof(result)/sizeof(result[0]) Is this correct? Because for my program, sizeof(result) = 16 and sizeof(result[0]) = 16 so that code would tell me that my array is of size 1. However that doesn't appear correct, because if I manually print out the array values like this: std::cout << result[0] << "\n"; std::cout << result[1] << "\n"; std::cout << result[2] << "\n"; std::cout << result[3] << "\n"; etc... ...then I see the resulting values I'm looking for. The array is upwards of 100+ values in length/size. It seems like it should be very simple to determine the size/length of an array... so hopefully I'm just missing something here. I'm a bit of a C++ newb so any help would be appreciated.
You cannot determine the size of an array dynamically in C++. You must pass the size around as a parameter. As a side note, using a Standard Library container (e.g., vector) allieviates this. In your sizeof example, sizeof(result) is asking for the size of a pointer (to presumably a std::string). This is because the actual array type "decays" to a pointer-to-element type when passed to a function (even if the function is declared to take an array type). The sizeof(result[0]) returns the size of the first element in your array, which coincidentally is also 16 bytes. It appears that pointers are 16 bytes (128-bit) on your platform. Remember that sizeof is always evaluated at compile-time in C++, never at run-time.
2,270,942
2,270,959
Problem referring to the exe path in _wsystem() in Windows XP
I am having problem referring to the file path in Windows XP (SP2). Actually I want to run an exe file from a specified path say "C:\users\rakesh\Documents and settings\myexe.exe" in my program...I am using the function _wsystem("C:\users\rakesh\Documents and settings\myexe.exe") to run the file.. The problem is that it is not recognizing the space, so I went through some articles and I found an solution for that. I tried using the solution below ..it worked great: C:\\users\\rakesh\\Docume~1\\myexe.exe in the above after the first 6 chars I used "~1" to accomplish the rest...but it's not working when exe name is with space like below: C:\\users\\rakesh\\Docume~1\\my exe.exe and also I can't replace them with "~1"(not working for exe name). How do you execute programs when there are spaces in the path or executable file name?
Just like on the command line, the spaces need to be inside double quotes: _wsystem ("\"C:/users/rakesh/Documents and settings/myexe.exe\""); Note that forward slashes work just fine for path delimiters.
2,270,995
2,271,004
Exiting from C++ Console Program
I currently have a program which has the following basic structure main function -- displays menu options to user -- validates user input by passing it to a second function (input_validator) -- if user selects option 1, run function 1, etc function1,2,3,etc -- input is requested from user and then validated by input_validator -- if input_validator returns true, we know input is good Here is my problem. I want to allow the user to quit at any point within the program by typing '0'. I planned on doing this with some basic code in input_validator (if input = 0, etc). This would appear to be simple, but I have been told that using quit() will result in some resources never been released / etc. I cannot simply do a 'break' either -- it will result in my program simply returning to the main function. Any ideas?
One possibility would be to do it by throwing an exception that you catch in main, and when you catch it, you exit the program. The good point of throwing an exception is that it lets destructors run to clean up objects that have been created, which won't happen if you exit directly from elsewhere (e.g., by using exit()).
2,271,016
2,271,162
Equivalent to toString() in Eclipse for GDB debugging
In Eclipse I can override the toString() method of an Object to pretty print it. This is especially useful because during a debug sessions as I can click on a variable and see the object in a human readable form. Is there any kind of equivalent for C++ during a gdb session. I'm also open to any IDEs that can emulate this behavior.
In gdb, print command prints the contents of the variable. If you are using any IDE for C++, eg. Netbeans, Eclipse, VC++ then pointing on the variable shows the content. EDIT: See if the below code is what you are looking for. #include <string> using std::string; #define magic_string(a) #a template<typename T> class Object_C { private: virtual string toString_Impl() { return magic_string(T); } public: Object_C(void) { } virtual ~Object_C(void) { } string toString() { return toString_Impl(); } }; class Base_C : public Object_C<Base_C> { private: string toString_Impl() { char str[80] = ""; sprintf_s(str, 79, "Base.x:%d\n", x_); return string(str); } private: int x_; public: Base_C(int x = 0) : x_(x) { } ~Base_C(void); }; void ToStringDemo() { Base_C base; cout << base.toString() << endl; }
2,271,046
2,271,055
If changing a const object is undefined behavior then how do constructors and destructors operate with write access?
C++ standard says that modifying an object originally declared const is undefined behavior. But then how do constructors and destructors operate? class Class { public: Class() { Change(); } ~Class() { Change(); } void Change() { data = 0; } private: int data; }; //later: const Class object; //object.Change(); - won't compile const_cast<Class&>( object ).Change();// compiles, but it's undefined behavior I mean here the constructor and destructor do exactly the same thing as the calling code, but they are allowed to change the object and the caller is not allowed - he runs into undefined behavior. How is it supposed to work under an implementation and according to the standard?
The standard explicitly allows constructors and destructors to deal with const objects. from 12.1/4 "Constructors": A constructor can be invoked for a const, volatile or const volatile object. ... const and volatile semantics (7.1.5.1) are not applied on an object under construction. Such semantics only come into effect once the constructor for the most derived object (1.8) ends. And 12.4/2 "Destructors": A destructor can be invoked for a const, volatile or const volatile object. ... const and volatile semantics (7.1.5.1) are not applied on an object under destruction. Such semantics stop being into effect once the destructor for the most derived object (1.8) starts. As background, Stroustrup says in "Design and Evolution of C++" (13.3.2 Refinement of the Defintion of const): To ensure that some, but not all, const objects could be placed read-only memory (ROM), I adopted the rule that any object that has a constructor (that is, required runtime initialization) can't be place in ROM, but other const objects can. ... An object declared const is considered immutable from the completion of the constructor until the start of its destructor. The result of a write to the object between those points is deemed undefined. When originally designing const, I remember arguing that the ideal const would be an object that is writable until the constructor had run, then becomes read-only by some hardware magic, and finally upon the entry into the destructor becomes writable again. One could imagine a tagged architecture that actually worked this way. Such an implementation would cause a run-time error if someone could write to an object defined const. On the other hand, someone could write to an object not defined const that had been passed as a const reference or pointer. In both cases, the user would have to cast away const first. The implication of this view is that casting away const for an object that was originally defined const and then writing to it is at best undefined, whereas doing the same to an object that wasn't originally defined const is legal and well defined. Note that with this refinement of the rules, the meaning of const doesn't depend on whether a type has a constructor or not; in principle, they all do. Any object declared const now may be placed in ROM, be placed in code segments, be protected by access control, etc., to ensure that it doesn't mutate after receiving its initial value. Such protection is not required, however, because current systems cannot in general protect every const from every form of corruption.
2,271,376
2,272,424
Find a window using c++ and modifying controls
I would like to use c++ without mfc(and not clr) in order to modify textbox's and activate a button on a form outside of my project. I don't know where to start. I've done a lot of searching but can only find information for VB. A starting point would help. Thanks. I tried this and it doesn't seem to work. HWND fWindow = FindWindow(NULL ,(LPCWSTR)"title"); and I also tried this HWND fWindow = FindWindow(NULL ,LPCWSTR("title")); I ALSO tried using LPTSTR instead of LPCWSTR, incase it was a unicode deal. Maybe I don't understand this microsoft LPCWSTR and LPTSTR crap. I also tried HWND fWindow = FindWindow(NULL,TEXT("title")); and that didn't work. I guess the windows api must just be broken. I tried the function on other programs...I'm using xp and I tried catching the calculator, and an explorer window, and something else. But I got nothing. Heres some of the exact code I'm using to try and figure this out. HWND face = NULL; face = FindWindow(NULL,TEXT("My Computer")); LPSTR title = TEXT(""); GetWindowText(face,title,250); if(face != NULL) { MessageBox(NULL,title,TEXT("WOOP"),1); } face = nothing. title = "" Bear in mind, I'm not actually trying to hook explorer, I just want to figure out how to get it to work.
Use spy++ or winspector to see the actual "text" of the window. (Strictly speaking, the caption of the window need not match it's window text. Especially true of "fancy" windows which paint their own caption.) The following works fine for me (using Calc.exe to test). HWND hwnd = NULL; hwnd = FindWindow(NULL,_T("Calculator")); TCHAR title[251]; if(hwnd != NULL) { GetWindowText(hwnd,title,250); MessageBox(NULL,title,_T("WOOP"),MB_OK); } else MessageBox(NULL,_T("No such window."),_T("OOPS"),MB_OK); Edit: You should have used _TEXT instead of TEXT.
2,271,385
2,271,404
Don't understand the const method declaration
Too much C# and too little C++ makes my mind dizzy... Could anyone remind me what this c++ declaration means? Specifically, the ending "const". Many thanks. protected: virtual ostream & print(ostream & os) const
A const method will simply receive a const this pointer. In this case the this pointer will be of the const ThisClass* const type instead of the usual ThisClass* const type. This means that member variables cannot be modified from inside a const method. Not even non-const methods can be called from such a method. However a member variable may be declared as mutable, in which case this restriction will not apply to it. Therefore when you have a const object, the only methods that the compiler will let you call are those marked safe by the const keyword.
2,271,390
2,271,402
Expected constructor, destructor, or type conversion before '*' token
I honestly have no idea why this is happening. I checked, double-checked, and triple-checked curly braces, semicolons, moved constructors around, etc. and it still gives me this error. Relevant code follows. BinTree.h #ifndef _BINTREE_H #define _BINTREE_H class BinTree { private: struct Node { float data; Node *n[2]; }; Node *r; Node* make( float ); public: BinTree(); BinTree( float ); ~BinTree(); void add( float ); void remove( float ); bool has( float ); Node* find( float ); }; #endif And BinTree.cpp #include "BinTree.h" BinTree::BinTree() { r = make( -1 ); } Node* BinTree::make( float d ) { Node* t = new Node; t->data = d; t->n[0] = NULL; t->n[1] = NULL; return t; }
Because on the line: Node* BinTree::make( float d ) the type Node is a member of class BinTree. Make it: BinTree::Node* BinTree::make( float d )
2,271,907
2,271,925
Correct BOOST_FOREACH usage?
When using BOOST_FOREACH, is the following code safe? BOOST_FOREACH (const std::string& str, getStrings()) { ... } ... std::vector<std::string> getStrings() { std::vector<std::string> strings; strings.push_back("Foo"); ... return strings; } Or should I grab a copy of the container before calling BOOST_FOREACH, e.g.: const std::vector<std::string> strings = getString(); BOOST_FOREACH (const std::string& str, strings) { ... } In the first example is there any danger that BOOST_FOREACH could end up calling getStrings() multiple times?
And although BOOST_FOREACH is a macro, it is a remarkably well-behaved one. It evaluates its arguments exactly once, leading to no nasty surprises
2,271,980
2,271,985
Recursive functions in C/C++
If we consider recursive function in C/C++, are they useful in any way? Where exactly they are used mostly? Are there any advantages in terms of memory by using recursive functions? Edit: is the recursion better or using a while loop?
Recursive functions are primarily used for ease of designing algorithms. For example you need to traverse a directory tree recursively - its depth it limited, so you're quite likely to never face anything like too deep recursion and consequent stack overflow, but writing a tree traversal recursively is soo much easier, then doing the same in iterative manner. In most cases recursive functions don't save memory compared to iterative solutions. Even worse they consume stack memory which is relatively scarse.
2,271,997
2,272,025
Is it possible to find out if a VNC connection is active
My application is running on windows XP, a VNC server is also running on the PC. I'd like to find out if someone is currently connected to the VNC server (e.g. to use simpler icons). I'm using UltraVNC. Is there a simple (preferably documented) way to to this? EDIT: Apparently someone voted to close because he/she thought this belonged on superuser, so I think I should clarify the question: I need a programmatic solution, preferably in .NET or C++. (This is problem is trivial for a user: just look at the VNC icon in the tray.)
check the status of port 5900
2,272,109
2,272,155
safe reading from a stream in a for loop using getline
I want to read from a stream using std::getline inside a for loop. The stream I mean is a class inherited from the std::basic_iostream. std::string line; for(;;){ try{ std::getline( myStreamObj, line ); if( line != "" ){ std::cout << line << std::endl; } } catch( std::ios_base::failure& ex ){ std::cout << ex.what() << std::endl; } } I want also to check against other error conditions like eofbit failbit badbit But I am bit confused about it. If some of the conditions settings these 3 flags is met is any exception thrown like std::ios_base::failure? How to handlse these 3 cases? Do I have to do checkings other ways? Thanks AFG
If you want to capture the errors via exceptions you need to set it using ios::exception. Otherwise an exception will not be thrown. You can check out the documentation here: http://www.cplusplus.com/reference/iostream/ios/exceptions/. You can also explicitly call ios::fail(), ios::bad() or ios::eof(). Docs here: http://www.cplusplus.com/reference/iostream/ios/
2,272,200
2,272,291
undefined referance to LibSerial
So i'm writing a serial transmision program, and have just changed over to using C++, it been a while since I used C++ (I've been working with C recently, and before that java) Now I need to use LibSerial, (it seems much simpler to use than C's termios) my code is: //gen1.cpp #include "string2num.h" // a custom header #include <iostream> #include <SerialStream.h> using namespace LibSerial; //using namespace std; int main(int argc, char*argv[]) { if (argc<2) { std::cout<<argv[0]<<"requires the device name eg \"dev/tty0\" as a parameter\nterminating.\n"; return 1; } SerialStream theSerialStream(argv[1]); //open the device return 0; } When I compile the output: g++ -Wall -o gen1 gen1.cpp string2num.o /tmp/cchPBWgx.o: In function `main': gen1.cpp:(.text+0x121): undefined reference to `LibSerial::SerialStream::SerialStream(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::_Ios_Openmode)' /tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x24): undefined reference to `LibSerial::SerialStreamBuf::showmanyc()' /tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x28): undefined reference to `LibSerial::SerialStreamBuf::xsgetn(char*, int)' /tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x2c): undefined reference to `LibSerial::SerialStreamBuf::underflow()' /tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x34): undefined reference to `LibSerial::SerialStreamBuf::pbackfail(int)' /tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x38): undefined reference to `LibSerial::SerialStreamBuf::xsputn(char const*, int)' /tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x3c): undefined reference to `LibSerial::SerialStreamBuf::overflow(int)' collect2: ld returned 1 exit status make: *** [gen1] Error 1
This is the linker complaining that it cannot find the functions referenced by the libserial header file. If I look on my Linux system to see how the shared library is called: $ dpkg -L libserial0 ... /usr/lib/libserial.so.0.0.0 /usr/lib/libserial.so.0 On my system this implies I would add -lserial as a g++ option (aka link with libserial.so) this would turn your compilation command into g++ -Wall -lserial -o gen1 gen1.cpp string2num.o
2,272,316
2,272,467
how to capture mouse cursor in screen grab?
I'm using OpenGL to grab the contents of the Mac OSX screen - thsi works very well, except it does not grab the mouse cursor graphic. I need to somewhow get that cursor graphic, either as part of my screen capture routine, or separately. My question is either: How can I ensure that the mouse cursor image is included with the OpenGL screen grab? or How can I get the current mouse cursor image as a simple RGBA bitmap? I'm developing under Mac OSX 10.6, using C++ / Carbon. Cheers,
You can use I/O Kit to read the pixels for the current cursor. See IOFramebufferShared.h and IOGraphicsLib.h for some of the relevant API.
2,272,735
2,272,772
Private/public header example?
Can someone please give me an example of how public and private headers work? I have done some reading on the net but I can't seem to find much useful information with sample codes. I was advised that I should use private headers to separate the public and private parts of my code for creating a static library. After some reading I have a general idea of how it works, but would really appreciate a good example to get me started. Specifically, what I don't quite understand is how to put the interface functions in my public header, and the private variables/functions in my private header? Thanks! EDIT: Maybe I'm not wording my question right, but what I meant is, for example, I have myMath.h and myMath.cpp, and myMath.h has: class myMath{ public: void initialise(double _a, double _b); double add(); double subtract(); private: double a; double b; }; And myMath.cpp has the implementations of the functions. How can I make it so that myMath.h only has the three public functions, and the private variables are defined in another file (e.g. myMath_i.h), and these three files are in such a way that after I create a static library, only myMath.h is needed by users. This also means myMath.h cannot #include myMath_i.h. So something like: myMath.h: class myMath{ public: void initialise(double _a, double _b); double add(); double subtract(); } and myMath_i.h: class myMath{ private: double a; double b; } Of course that's not possible because then I'll be redefining the class myMath...
You have two header files MyClass.h and MyClass_p.h and one source file: MyClass.cpp. Lets take a look at what's inside them: MyClass_p.h: // Header Guard Here class MyClassPrivate { public: int a; bool b; //more data members; } MyClass.h: // Header Guard Here class MyClassPrivate; class MyClass { public: MyClass(); ~MyClass(); void method1(); int method2(); private: MyClassPrivate* mData; } MyClass.cpp: #include "MyClass.h" #include "MyClass_p.h" MyClass::MyClass() { mData = new MyClassPrivate(); } MyClass::~MyClass() { delete mData; } void MyClass::method1() { //do stuff } int MyClass::method2() { return stuff; } Keep your data in MyClassPrivate and distribute MyClass.h.
2,272,922
2,276,166
vim omnicomplete vs. vim intellisense
Are Vim OmniComplete and Vim Intellisense mutually exclusive or complementary? I'm a bit confused by conflicting terminology and implementations, such as these C++ OmniComplete and C++ Intellisence plugins.
Vim Omnicomplete is a feature of Vim version 7, on all platforms. Vim Intellisense is a plugin for vim 6.1 and 6.2 on Windows only.
2,272,955
2,277,414
How to detect if HPET is available
how can I detect (using C++) wether my system has a HPET or not? Thx for your help, Tobias HPET = High Precision Event Timer
If your system has a HPET, then it should be listed in the device manager and therefore somewhere in the registry. I would see if there is a key in there somewhere that denotes a HPET. I'm not in win32 right now, but msdn mentions HKEY_LOCAL_MACHINE\Drivers\Active. http://msdn.microsoft.com/en-us/library/aa447470.aspx
2,273,091
2,273,105
C++ Is private really private?
I was trying out the validity of private access specifier in C++. Here goes: Interface: // class_A.h class A { public: void printX(); private: void actualPrintX(); int x; }; Implementation: // class_A.cpp void A::printX() { actualPrintX(); } void A::actualPrintX() { std::cout << x: } I built this in to a static library (.a/.lib). We now have a class_A.h and classA.a (or classA.lib) pair. I edited class_A.h and removed the private: from it. Now in another classTester.cpp: #include "class_A.h" // the newly edited header int main() { A a; a.x = 12; // both G++ and VC++ allowed this! a.printX(); // allowed, as expected a.actualPrintX(); // allowed by G++, VC++ gave a unresolved linker error return 0; } I know that after tampering a library's header all bets are off (I mean, system integrity, etc.) Albeit the method being hacky, is this really allowed? Is there a way to block this? Or am I doing something wrong here?
private is not a security mechanism. It's a way of communicating intents and hiding information that other parts of your program do not need to know about, thus reducing overall complexity. Having two different header files is not standards compliant, so technically you're entering undefined behaviour territory, but practically, as you've found, most compilers won't care.
2,273,146
2,273,199
Compile for x64 with Visual Studio?
Question: Assume a C++ hello world program, non .NET. With Visual Studio 2005/2008/2010, how can I compile a 64-Bit application ? I have a 64 Bit Windows, but by default, VS seems to compile 32 bit executables... On Linux with g++, I can use -m32 and -m64, but how can I compile a 64 bit solution with Windows ? Is it even possible with 2005 ? Or does one need 2008 or even 2010 Beta, or even some x64 SDK ?
There is a step-by-step instructions by Microsoft: http://msdn.microsoft.com/en-us/library/9yb4317s.aspx
2,273,187
2,273,360
Why is the delete operator required to be static?
I found this one question asking the same thing, however only the 'new' part was answered, so here goes again. Why is the delete operator required to be static? Somehow it doesn't make sense. The new operator makes perfect sense, just like the constructor can't be virtual, neither can the new operator. However, the destructor can (and should) be virtual when you use inheritance, in order to allow destruction of objects being used (by way of polymorphism) as a base class. I understand that, when the delete operator is called, the object has already been destroyed, so no 'this' exists. Yet it still makes sense, using the same reasoning as with virtual destructor, to have the delete operator match the new operator which created the object. This is what I mean class A { public: virtual ~A() {} }; class B : public A { public: void* operator new (size_t sz); void operator delete (void* ptr, size_t sz); }; now if we do A *ptr = new B(); delete ptr; // <-- fail A's delete operator (default) should've been called, since it's static and it's not known (for anything but the trivial case here) at compile time which delete-operator is the correct one. However, I made a small test program with the code above (just malloc/free in the new/delete operators, and print statement in delete), and compiled it using g++. Running it quite unexpectedly produced the output in B's delete operator. My (real) question is this: Is there some implicit 'virtualness' to the delete operator? Is it only static in the no-this-pointer sense? Or is this just a g++ feature? I started looking through the C++ specification, but I must admit, I was bit overwhelmed by it, so any help appreciated.
The answer in the language rules is really in 12.5 [class.free]. If you are deleting via a pointer to a base class then the destructor must be virtual or you get undefined behaviour. Otherwise, the implementation has to determine the dynamic type of the object being deleted. 12.5/4 says that when the delete isn't prefixed by :: then the deallocation function is determined by looking up delete in the context of the dynamic type's virtual destructor. This ensures virtual-like lookup, even though operator delete is always a static member function. Raw allocation and deallocation happen conceptually outside of the object's lifetime so by the time the deallocation function is to be called, there is no longer an object to provide a virtual lookup mechanism but the lookup rules ensure that operator delete has a dynamic (virtual-lite!) lookup mechanism. This means that operator delete can sensibly be static without losing touch with the original object's dynamic type.
2,273,264
2,273,281
Extracting 'parts' of a hexadecimal number
I want to write a function getColor() that allows me to extract parts of a hexadecimal number entered as a long The details are as follows: //prototype and declarations enum Color { Red, Blue, Green }; int getColor(const long hexvalue, enum Color); //definition (pseudocode) int getColor(const long hexvalue, enum Color) { switch (Color) { case Red: ; //return the LEFTmost value (i.e. return int value of xAB if input was 'xABCDEF') break; case Green: ; //return the 'middle' value (i.e. return int value of xCD if input was 'xABCDEF') break; default: //assume Blue ; //return the RIGHTmost value (i.e. return int value of xEF if input was 'xABCDEF') break; } } My 'bit twiddling' isn't what it used to be. I would appreciate some help on this. [Edit] I changed the ordering of the color constants in the switch statements - no doubt any designers, CSS enthusiasts out there would have noticed that colors are defined (in the RGB scale) as RGB ;)
Generally: Shift first Mask last So, for instance: case Red: return (hexvalue >> 16) & 0xff; case Green: return (hexvalue >> 8) & 0xff; default: //assume Blue return hexvalue & 0xff; The ordering of the operations help cut down on the size of the literal constants needed for the masks, which generally leads to smaller code. I took DNNX's comment to heart, and switched the names of the components since the order is typically RGB (not RBG). Furthermore, please note that these operations have nothing to do with the number being "hexadecimal", when you're doing operations on an integer type. Hexadecimal is a notation, a way of representing numbers, in textual form. The number itself is not stored in hex, it's binary like everything else in your computer.
2,273,285
2,273,298
pass by reference c++
My teacher in c++ told me that call by reference should only be used if I'm not going to change anything on the arrays inside the function. I have some really big vectors that I'm passing around in my program. All the vectors will be modified inside the functions. My matrices are of sizes about [256*256][256][50]... Is there some particular reason not to use call-by reference here? AFAIK call by reference should be way faster and consume less memory?
My teacher in c++ told me that call by reference should only be used if I'm not going to change anything on the arrays inside the function. It should be used when you are not changing something inside the function or you change things and want the changes to be reflected to the original array or don't care about the changes to be reflected in the original array. It shouldn't be used if you don't want your function to change your original array (you need to preserve the original values after the call) and the callee function changes the values of the passed argument.
2,273,330
2,273,352
Restore the state of std::cout after manipulating it
Suppose I have a code like this: void printHex(std::ostream& x){ x<<std::hex<<123; } .. int main(){ std::cout<<100; // prints 100 base 10 printHex(std::cout); //prints 123 in hex std::cout<<73; //problem! prints 73 in hex.. } My question is if there is any way to 'restore' the state of cout to its original one after returning from the function? (Somewhat like std::boolalpha and std::noboolalpha..) ? Thanks.
you need to #include <iostream> or #include <ios> then when required: std::ios_base::fmtflags f( cout.flags() ); //Your code here... cout.flags( f ); You can put these at the beginning and end of your function, or check out this answer on how to use this with RAII.
2,273,380
2,273,448
How to create a C-style array without calling default constructors?
I am writing a memory-managing template class in which I want to create a C-style array of fixed size, to serve as a heap. I keep the objects stored in an array like this: T v[SIZE]; As this only serves the role as a heap that can hold T objects, I don't want the T default constructor to get automatically called for every object in the array. I thought about the solution to define the heap like this: char v[SIZE * sizeof(T)]; ...but this will give me alignment problems. Is there any better way to achieve this? ADD: As I have special run time requirements, it is essential that this class doesn't do any allocations on the global heap. ADD 2: SIZE is a template argument and known at compile-time.
The standard containers use allocators to seperate allocation/deallocation from construction/destruction. The standard library supplies a single allocator which allocates on the heap. This code declares an array big enough to hold SIZE elements of type T with the correct allignment: typedef typename std::tr1::aligned_storage<sizeof(T),std::tr1::alignment_of<T>::value>::type aligned_storage; aligned_storage array[SIZE]; The solution using std::allocator can't be used to declare an array on the stack, and as the standard containers require that custom allocators hold no state, a custom allocator can't be portably used to allocate on the stack either. If your compiler doesn't support std::tr1::alignment_of you can use boost::alignment_of instead.
2,273,475
2,274,301
Magic COLORREF/RGB value to determine when to use light/dark text
Years ago, in my long lost copy of Charles Petzold's Windows 3.0 Programming book, there was a magic COLORREF or RGB value documented that you could use to check whether you should draw text in a light colour or a dark colour. E.g. if the background colour was below this value, then use black text, if it was higher, use white text. Does anyone know/remember what this magic value is?
I can't tell about COLORREF but I've got good results using the luminance as threshold: Y= 0.3 * R + 0.59 * G + 0.11 * B with colours expressed as a decimal value between 0.0 and 1.0. If Y>=0.5 I considered the background "light" (and used dark text), if Y<0.5 I did the opposite. I remember I also used other formulas including the simple mean: L = (R+G+B)/3 but I didn't like the result. It seems logical to me that Green contributes to lightness more than Red and Red more than Blue.
2,273,488
2,273,983
Graphics primitive generators
I'm looking for something that can generate primitives (e.g. rounded rectangles for dialog boxes etc) so I can load them into a DirectX textured Sprite. Functionality is like SPriG.
Its pretty easy and there are 2 ways : 1) If you are using DirectX10+ use Direct2D. 2) Use GDI+ to draw them onto a texture. Both are integrated with the system and do not need for any external library. Just pick and use. As far as Direct2D, I don't know all the details, but I can assure you can do whatever you want with GDI+. (You generate them once, so you don't care about speed)
2,273,777
2,273,792
Is <value optimized out> in gdb a problem?
I have an application that only crashes in -O2 optimization (compiled with gcc 4.2.4). When I step through the code and get to the spot that crashes and try to inspect the value, I get a "value optimized out" in gdb. I read on the internet that this means that the value is stored in the register. I was wondering if my crash could be related to the fact that some information is placed in registers? Is there a way to print what is in the registers to see if it has been corrupted? Is there a way to keep optimizations but not use registers? Thanks!
It's 99% likely to be a bug in your code and 1% likely to be a compiler code generation bug. So spend a proportionate amount of time looking for latent bugs in your code but be aware that you just may have found a code generation bug (in which case you'll need to study the compiler generated code carefully to see what the problem is).
2,273,811
2,273,842
C++: returning by reference and copy constructors
References in C++ are baffling me. :) The basic idea is that I'm trying to return an object from a function. I'd like to do it without returning a pointer (because then I'd have to manually delete it), and without calling the copy-constructor, if possible (for efficiency, naturally added: and also because I wonder if I can't avoid writing a copy constructor). So, all in all, here are the options for doing this that I have found: The function return type can be either the class itself (MyClass fun() { ... }) or a reference to the class (MyClass& fun() { ... }). The function can either construct the variable at the line of return (return MyClass(a,b,c);) or return an existing variable (MyClass x(a,b,c); return x;). The code that receives the variable can also have a variable of either type: (MyClass x = fun(); or MyClass& x = fun();) The code which receives the variable can either create a new variable on the fly (MyClass x = fun();) or assign it to an existing variable (MyClass x; x = fun();) And some thoughts on that: It seems to be a bad idea to have the return type MyClass& because that always results in the variable being destroyed before it gets returned. The copy constructor only seems to get involved when I return an existing variable. When returning a variable constructed in the line of return, it never gets called. When I assign the result to an existing variable, the destructor also always kicks in before the value is returned. Also, no copy constructor gets called, yet target variable does receive the member values of the object returned from the function. These results are so inconsistent that I feel totally confused. So, what EXACTLY is happening here? How should I properly construct and return an object from a function?
The best way to understand copying in C++ is often NOT to try to produce an artificial example and instrument it - the compiler is allowed to both remove and add copy constructor calls, more or less as it sees fit. Bottom line - if you need to return a value, return a value and don't worry about any "expense".
2,273,863
2,273,879
How do I use Xerces w/ in a Windows environment?
I have downloaded the source for Xerces and am trying to use it in a Greenhills project. I get the following error: could not open source file "xercesc/util/Xerces_autoconf_config.hpp" The code where the error hit is commented as: // If the next line generates an error then you haven't run ./configure #include <xercesc/util/Xerces_autoconf_config.hpp> How do I run "./configure" in a windows environment?
you can't you will have to install some unix like environment like Cygwin.
2,273,865
2,279,490
Update system environment variable from c++
I am currently writing an unmanaged C++ program which works with a system environment variable. I am getting the value with GetEnvironmentVariable(...). Now I have an C# program which may change this variable at any time, e.g. like this: Environment.SetEnvironmentVariable("CalledPath", System.Windows.Forms.Application.ExecutablePath, EnvironmentVariableTarget.Machine); The problem is that the C++ program does not update this variable (or its environment block in general) automatically so that I am still working with the old value unless I restart the program which is not really good. Is there a way to update the environment block or preferably another way to read system environment variables? Thanks in advance, Russo
Thank you guys but I finally figured it out myself. Since the values I receive with GetEnvironmentVariable are not the current ones I read the values directly from the registry. The machine environment variables are stored in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment I read them via the RegOpenKeyEx(...) and RegQueryValueEx(...) functions which works perfectly well.
2,273,934
4,302,176
OpenGL Calls Lock/Freeze
I am using some dell workstations(running WinXP Pro SP 2 & DeepFreeze) for development, but something was recenlty loaded onto these machines that prevents any opengl call(the call locks) from completing(and I know the code works as I have tested it on 'clean' machines, I also tested with simple opengl apps generated by dev-cpp, which will also lock on the dell machines). I have tried to debug my own apps to see where exactly the gl calls freeze, but there is some global system hook on ZwQueryInformationProcess that messes up calls to ZwQueryInformationThread(used by ExitThread), preventing me from debugging at all(it causes the debugger, OllyDBG, to go into an access violation reporting loop or the program to crash if the exception is passed along). the hook: ntdll.ZwQueryInformationProcess 7C90D7E0 B8 9A000000 MOV EAX,9A 7C90D7E5 BA 0003FE7F MOV EDX,7FFE0300 7C90D7EA FF12 CALL DWORD PTR DS:[EDX] 7C90D7EC - E9 0F28448D JMP 09D50000 7C90D7F1 9B WAIT 7C90D7F2 0000 ADD BYTE PTR DS:[EAX],AL 7C90D7F4 00BA 0003FE7F ADD BYTE PTR DS:[EDX+7FFE0300],BH 7C90D7FA FF12 CALL DWORD PTR DS:[EDX] 7C90D7FC C2 1400 RETN 14 7C90D7FF 90 NOP ntdll.ZwQueryInformationToken 7C90D800 B8 9C000000 MOV EAX,9C the messed up function + call: ntdll.ZwQueryInformationThread 7C90D7F0 8D9B 000000BA LEA EBX,DWORD PTR DS:[EBX+BA000000] 7C90D7F6 0003 ADD BYTE PTR DS:[EBX],AL 7C90D7F8 FE ??? ; Unknown command 7C90D7F9 7F FF JG SHORT ntdll.7C90D7FA 7C90D7FB 12C2 ADC AL,DL 7C90D7FD 14 00 ADC AL,0 7C90D7FF 90 NOP ntdll.ZwQueryInformationToken 7C90D800 B8 9C000000 MOV EAX,9C So firstly, anyone know what if anything would lead to OpenGL calls cause an infinite lock,and if there are any ways around it? and what would be creating such a hook in kernal memory ? Update: After some more fiddling, I have discovered a few more kernal hooks, a lot of them are used to nullify data returned by system information calls(such as the remote debugging port), I also managed to find out the what ever is doing this is using madchook.dll(by madshi) to do this, this dll is also injected into every running process(these seem to be some anti debugging code). Also, on the OpenGL side, it seems Direct X is fine/unaffected(I ran one of the DX 9 demo's without problems), so could one of these kernal hooks somehow affect OpenGL?
After some research, it seems that there is something actively blocking user->kernel mode calls for OGL, probably an option of DeepFreeze. DirectX works flawlessly though, so I've switched over to that.
2,274,181
2,279,930
Send custom information through Windows FileSystem Attributes
Before getting into the point, I'll give you an overview of what I want to do. Because I don't know if using Windows Filesystem attributes is the right option to do that. I have two components in the system. One of them is a ShellExtension that put an OverlayIcon when some condition is satisfied, and the other component is a Filesystem driver which provide information to Windows ( and therefore to the ShellExtension ) The FileSystem, using the name of the file make a network request to a remote server and depending on the result of this request, the overlay icon should appear or not. The straightforward solution is to repeat the request from the OverlayIcon side, but this is not desirable. In the FileSystem side I have the request result, but I need to send it to the Overlay. The first solution that came to my mind was use the Windows FileSystem attributes. I mean, in the Filesystem driver I will put a aparently-not-used attrubute ( for example 0x1000000 that appears not to be used according to MSDN ), and recover this information in the OverlayIcon, given that the explorer sends to the Shell Extension the file attribute as a parameter of "IsMemberOf". That is, use the Windows File Attributes to codify information from the FileSystem side to the ShellExtension one. This solution doesn't work, it seems that in some part of the flow, this attribute is removed. It makes sense because this attribute appears not to be valid. If I replace the attribute value to one like HIDDEN, it works perfectly. The obvious solution ( but it has more work to do ) is to use some IPC Mechanism. But as I am on the both sides of the game It would be better if I could use the Windows Filesystem information. What do you suggest? Thank you!
Why so complex? There's a proper interface for this. Call GetFileInformationByHandleEx(FileRemoteProtocolInfo) to get a FILE_REMOTE_PROTOCOL_INFO. Put your protocol-specific data in ProtocolSpecificReserved. That's 64 bytes big. The closest alternative to your current idea which might work would be to use FILE_ATTRIBUTE_REPARSE_POINT. If you use this, you can put a tag in WIN32_FIND_DATA::dwReserved0. This won't clash with other tags, as these tags are Microsoft-allocated. http://msdn.microsoft.com/en-us/library/aa365511(VS.85).aspx There are more places to squirrel your data away. You might consider using the lowest bit of the creation filetime. Do you really need 100 ns resolution, or is 200 ns good enough? Could you store it in BY_HANDLE_FILE_INFORMATION::nFileIndexHigh somehow?
2,274,188
2,274,252
fatal error LNK1104: cannot open file 'libboost_regex-vc90-mt-gd-1_42.lib'
i'm trying to use boost regex within my program the problem is i get this error... the only installation step i did was to add: "C:\Program Files\boost\boost_1_42" into the Additional Include Directories... i'm using VS2008... trying to implement this: #include <iostream> #include <string> #include <boost/regex.hpp> using namespace std; int main( ) { std::string s, sre; boost::regex re; boost::cmatch matches; while(true) { cout << "Expression: "; cin >> sre; if (sre == "quit") { break; } cout << "String: "; cin >> s; try { // Assignment and construction initialize the FSM used // for regexp parsing re = sre; } catch (boost::regex_error& e) { cout << sre << " is not a valid regular expression: \"" << e.what() << "\"" << endl; continue; } // if (boost::regex_match(s.begin(), s.end(), re)) if (boost::regex_match(s.c_str(), matches, re)) { // matches[0] contains the original string. matches[n] // contains a sub_match object for each matching // subexpression for (int i = 1; i < matches.size(); i++) { // sub_match::first and sub_match::second are iterators that // refer to the first and one past the last chars of the // matching subexpression string match(matches[i].first, matches[i].second); cout << "\tmatches[" << i << "] = " << match << endl; } } else { cout << "The regexp \"" << re << "\" does not match \"" << s << "\"" << endl; } } } what seems to be the problem ? any additional settings should be made ?
Some Boost libraries have to be built; this is one of them. Here's how you can build them: Make a new file called boost_build.bat, and inside put: bjam toolset=msvc-9.0 variant=release threading=multi link=static define=_SECURE_SCL=0 define=_HAS_ITERATOR_DEBUGGING=0 bjam toolset=msvc-9.0 variant=debug threading=multi link=static Note 9.0 refers to VS 2008. (10.0 for 2010, 8.0 for 2005, 7.1 for 2003, 6.0 for, well, 6.0). Once you've done this: Extract build_boost.bat to <boost_root> Go to: <boost_root>\tools\jam And run build_dist.bat Copy <boost_root>\tools\jam\stage\bin.ntx86\bjam.exe to <boost_root> Run boost_build.bat Libraries are located in <boost_root>\stage\lib Note, this is my own method. I would love if someone chimed in an easier way, or some link from Boost; it seems it's difficult to find proper build instructions from Boost. Once it's built, make sure you let the compiler know where the libraries are in your VC Directories (the Library Paths); add "<boost_root>\stage\lib". In the bjam defines, I have _SECURE_SCL=0 _HAS_ITERATOR_DEBUGGING=0 for Release. This disables all iterator checking in Release builds, for a speed improvement.
2,274,356
2,274,399
What are the default return values for operator< and operator[] in C++ (Visual Studio 6)?
I've inherited a large Visual Studio 6 C++ project that needs to be translated for VS2005. Some of the classes defined operator< and operator[], but don't specify return types in the declarations. VS6 allows this, but not VS2005. I am aware that the C standard specifies that the default return type for normal functions is int, and I assumed VS6 might have been following that, but would this apply to C++ operators as well? Or could VS6 figure out the return type on its own? For example, the code defines a custom string class like this: class String { char arr[16]; public: operator<(const String& other) { return something1 < something2; } operator[](int index) { return arr[index]; } }; Would VS6 have simply put the return types for both as int, or would it have been smart enough to figure out that operator[] should return a char and operator< should return a bool (and not convert both results to int all the time)? Of course I have to add return types to make this code VS2005 C++ compliant, but I want to make sure to specify the same type as before, as to not immediately change program behavior (we're going for compatibility at the moment; we'll standardize things later).
operator< returns a bool by default. operator[] returns int by default (I think), but it should almost certainly be changed to return whatever the collection contains. For the String example you gave above, that would be a char or wchar_t.
2,274,428
2,274,457
How to determine how many bytes an integer needs?
I'm looking for the most efficient way to calculate the minimum number of bytes needed to store an integer without losing precision. e.g. int: 10 = 1 byte int: 257 = 2 bytes; int: 18446744073709551615 (UINT64_MAX) = 8 bytes; Thanks P.S. This is for a hash functions which will be called many millions of times Also the byte sizes don't have to be a power of two The fastest solution seems to one based on tronics answer: int bytes; if (hash <= UINT32_MAX) { if (hash < 16777216U) { if (hash <= UINT16_MAX) { if (hash <= UINT8_MAX) bytes = 1; else bytes = 2; } else bytes = 3; } else bytes = 4; } else if (hash <= UINT64_MAX) { if (hash < 72057594000000000ULL) { if (hash < 281474976710656ULL) { if (hash < 1099511627776ULL) bytes = 5; else bytes = 6; } else bytes = 7; } else bytes = 8; } The speed difference using mostly 56 bit vals was minimal (but measurable) compared to Thomas Pornin answer. Also i didn't test the solution using __builtin_clzl which could be comparable.
You need just two simple ifs if you are interested on the common sizes only. Consider this (assuming that you actually have unsigned values): if (val < 0x10000) { if (val < 0x100) // 8 bit else // 16 bit } else { if (val < 0x100000000L) // 32 bit else // 64 bit } Should you need to test for other sizes, choosing a middle point and then doing nested tests will keep the number of tests very low in any case. However, in that case making the testing a recursive function might be a better option, to keep the code simple. A decent compiler will optimize away the recursive calls so that the resulting code is still just as fast.
2,274,661
2,274,831
Throwing non-const temporaries by reference
Is there any problem with throwing an object constructed on the stack in a try-block by non-const reference, catching it and modifying it, then throwing it by reference to another catch block? Below is a short example of what I'm refering to. struct EC { EC(string msg) { what = msg; } string where; string what; void app(string& t) { where += t; } string get() { return what; } }; try { try { try { EC error("Test"); throw error; } catch (EC& e) { e.app("1"); throw e; } } catch (EC& e) { e.app("2"); throw e; } } catch (EC& e) { e.app("3"); cout << e.where << endl; cout << e.get() << endl; } Is it possible that this could cause e.what to contain junk, but e.where to remain intact? For example: e.where is "123" e.get() returns a lot of garbage data, until it happens to hit a null byte.
There's no such thing as "throwing by reference". It is simply impossible. There's no syntax for that. Every time you try to "throw a reference", a copy of the referenced object is actually thrown. Needless to say, there are no attempts to throw by reference in your code. It is possible to catch a previously thrown exception by reference (even by a non-const one) and modify the temporary exception object through it. It will work. In fact, you can re-throw the now-modified existing exception object instead of creating a new one. I.e. you can just do throw; instead of throw e; in your catch clauses and still get the correctly behaving code, i.e. the original object (with modifications) will continue its flight throgh the handler hierarchy. However, your code is ill-formed at the e.app("1"); call (and other calls to app) since the parameter is non-const reference. Change the app declaration to either void app(const string& t) { where += t; } // <- either this void app(string t) { where += t; } // <- or this for it to compile. Otherwise, you code should work fine. You are not supposed to get any garbage from get(). If you do, it must be either a problem with your compiler or with your code that you don't show.
2,274,686
2,299,215
C++ for Wireless Sensor Networks
Similar to: Why are RTOS only coded in C, but: Besides the numerous myths about C++, why is it not used as much as C/nesC (TinyOS) for WSN? Knowing C++ can be used for Simulating Wireless Sensor Networks with OMNeT++ it is hard not to think that it can also be used in real-time embedded systems as C is to accomplish event handling. I do NOT want to start a C++ is better than C flame war, but enough evidence suggests that the whole C is faster and more versatile than C++ is a total myth. Take a look at: C vs. C++ paper where the following points were highlighted: - C++ is slower than C: Wrong! Many C programs are valid C++ programs as well - and such a C program should run at identical speed when translated with either the C and with the C++ compiler. - C++ specific features give overhead: Wrong! The so-called overhead introduced by certain C++ specific features (such as virtual function calls or exceptions), is comparable to the overhead you yourself would introduce should you choose to go thru the pain it would be to implement a similar feature in C. - C++ is object oriented: Wrong! The C++ language contains some language extentions over C, that make object oriented programming and generic programming more convenient. C++ does not force object oriented design anywhere - it merely allows for it if the programmer deems OO feasible. C allows for object oriented programming as well, C++ only makes it simpler and less error prone. Why are you still using C
I believe the answers to the following question apply here. Is there any reason to use C instead of C++ for embedded development?
2,274,769
2,274,815
C++ pointers to class instances
I have an (for C++ programmers better than me) simple problem with classes and pointers. I thought about posting example code describing my problem but I found it easier to just explain it in words. Assuming I have three classes: Class A: The main class - it contains an instance of both B and C. Class B: This class contains a method that outputs some string, call it Greet(). Class C: This one has a method too, but that method has to call Greet() in the instance of B that is located in class A. Let's name it DoSomethingWithB() So the program starts, in the main function I create an instance of A. A, again, creates instances of B and C. Then, A calls C.DoSomethingWithB();. And there my problem begins: I can't access B from inside C. Obviously, I will need to pass a pointer to B to the DoSomethingWithB() function so that I can call B.Greet() from inside C Long explanation, short question: How do I do this? Example code incoming: #include <iostream> using namespace std; class B { public: void Greet( ) { cout<<"Hello Pointer!"<<endl; } }; class C { public: void DoSomethingWithB( ) { // ... b.Greet( ); Won't work obviously } }; class A { public: B b; // Not caring about visibility or bad class/variable names here C c; void StartTest( ) { c.DoSomethingWithB( ); } }; int main( ) { A mainInstance; mainInstance.StartTest(); }
Wouldn't you simply pass a pointer or reference to he B object? class C { public: void DoSomethingWithB( B& b) { b.Greet( ); // will work fine } }; class A { public: B b; // Not caring about visibility or bad class/variable names here C c; void StartTest( ) { c.DoSomethingWithB( b); } }; If the DoSomethingWithB() function won't modify the passed in B instance, you should mark the reference const so it can be called with a const B object (for example if the owning A object happens to be const): void DoSomethingWithB( B const& b); You have a few options for how to pass the B object to the function: as a reference (void DoSomethingWithB( B& b)) which will let the function modify the passed in object. Changes will be refelected in the object that's passed in. as a const reference (void DoSomethingWithB( B const& b)) which won't let the function modify the passed in object (unless the constness is cast away - something which can lead to undefined behavior if done on an object the is truely const) as a pointer or const pointer to a B object (void DoSomethingWithB( B* b) or void DoSomethingWithB( B const* pb) ). These have similar performance to passing by reference, but the function could be passed a NULL pointer which needs to be dealt with properly (by not dereferencing it in that case). Also, the call of the function would need to change slightly to pass the address of the B object: c.DoSomethingWithB( &b); as a pass-by-value parameter (void DoSomethingWithB( B b)). This has difference that the function can do whatever it likes with theo bject passed in and it won't affect the originally passed object since the function is dealing with a copy. The disadvantage is that passing the parameter causes a copy to be made which might be expensive. You could also pass in a const value, but there's little to recommend that over passing a const reference. Note that when chosing the parameter passing method, you should first chose based on the sematics of what you need the function to do (or not do). Worry about efficiency later. Always first design and code for correctness - worry about efficiency only after you have the design and code correct.
2,274,854
2,274,894
What are the possible reasons the system() function can not find the executable?
if( system("tail -500 log.txt") == -1) { //Error calling tail.exe on log //errno is a system macro that expands int returning //the last error. strerror() converts the error to it's //corresponding error message. printf("Error calling tail.exe with system(): %s",strerror( errno )); } System() is calling Tail.exe with log.txt All are in the same directory as the executable calling it. Getting the error ENOENT- No such file or directory Also, specified paths to everything, same error. Any advice is appreciated, thank you.
From the docs on system() that you linked: ENOENT Command interpreter cannot be found. So the problem isn't that it can't find tail.exe, the problem is that it can't find the command interpreter. This suggests that something larger is going wrong. We'll need more information to diagnose the real problem. Also from the same page: The system function passes command to the command interpreter, which executes the string as an operating-system command. system refers to the COMSPEC and PATH environment variables that locate the command-interpreter file (the file named CMD.EXE in Windows NT and later). If command is NULL, the function simply checks to see whether the command interpreter exists. This suggests a couple of avenues for investigation: What does system(NULL) return? And what are the values for the COMSPEC and PATH environment variables when your program runs?
2,275,076
2,275,095
Is std::vector copying the objects with a push_back?
After a lot of investigations with valgrind, I've made the conclusion that std::vector makes a copy of an object you want to push_back. Is that really true ? A vector cannot keep a reference or a pointer of an object without a copy ?! Thanks
Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a std::vector<whatever*> instead of std::vector<whatever>. However, you need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them (smart pointers utilizing the RAII idiom solve the problem).
2,275,132
2,275,164
opengl problem with QT
I'm using QT with opengl to make a chart in order to use it in different simulated physical experiments, but I'm facing the following problem. I can't see my chart line unless I minimized my form window and then maximized it, and I should do that all the time as long as my line chart is being drawn in order to get the full result!! What can I do, this is urgent and I need this chart working properly without minimizing and maximizing.??
It looks like you aren't doing a repaint until minimize/maximize. I suggest using a timer to get the job done. Posting your code will help!!
2,275,184
2,275,237
What is the best tutorial for learning MPI for C++?
I plan to use MPI for my C++ code. I have installed MPICH2 on my computers. But I do not know much about MPI and hope to find some materials to read. I hope you experts can recommend some good materails to me. Any advice will be appreciated.
I'm assuming you already know how to program C++ pretty well and have a basic understanding of parallel programming (or at least know how you want to parallelize your code). I would check out the book Using MPI first. Using MPI 2 is the follow on book that discusses using the new bits in MPi-2. Both books were written by the guys who wrote the MPI library and headed up the standardization effort. One nice thing about Using MPI is that it's available online so you can check it out w/o spending money :-)
2,275,225
2,275,245
Find boundaries of an array of objects with only the boundaries of the objects
New Programmer here. Trying space invaders. I have a 2 dimensional array of objects stored in a one dimensional array (using modulo to determine rows and columns). Each object will return its boundaries in graphical space. I need to determine the boundaries (top, bottom, left, right) of the whole array for collision detection. I feel like I'm missing something super simple. All my tests seem to only get the position of the last one. Also, some of the objects disappear, possibly changing the dimensions.
The overall boundary box is overall_top = min(all of top) overall_bottom = max(all of bottom) overall_left = min(all of left) overall_right = max(all of right)
2,275,251
2,311,973
Debugged Program Window Won't Close
I'm using VS 2008 on a 64-bit XP machine. I'm debugging a 32-bit C++ DLL via a console program. The DLL and EXE projects are contained in the same SLN so that I can modify the DLL as I test. What happens is that every once in a while I kill the program with Debug | Stop Debugging (Shift-F5). VS stops the program, but the console window stays open! If I'm sitting at a breakpoint and hit Shift-F5, it will terminate properly, but if the program is running full-tilt when I stop it, I often see this instead. The big problem is that I can't close these zombie windows. Using End Task in Task Manager does nothing (no message, no nothing). When I shut down the machine, it is unable to due to the orphans and I have to resort to actually turning off the power. I think this is connected to having the DLL and EXE project in the same SLN, as for months I worked on this project in 2 VS instances, one for the DLL and the other for the EXE. I would continually jump back and forth between the windows as I worked. This problem never happened until I put the two projects into a single SLN. The single SLN works a lot better, but this anomaly is very irritating. Any ideas anyone? UPDATE After a bit of searching (here), I found that it appears to have to do with one of the updates from last Tuesday (KB977165 or KB978037). Thank you Microsoft for your excellent pre-release testing.
It's KB978037. Uninstalling it resolves the issue. More info here
2,275,373
2,275,454
Disjoint Set ADT Implementation in C++
I have problem in implementing a disjoint set ADT in C++ due to the fact that our teacher only explained the union and find operations. I fully understand the concepts of union and find but I am still confused about how to implement them. Could someone please give me an idea of the implementation and also explain what the interface of this data structure should look like?
You have way too many requirements, we're not here to do your homework for you. Have a look at http://en.wikipedia.org/wiki/Disjoint-set_data_structure
2,275,520
2,275,932
Creating a prefixed sequence in one line
Given the initialized variables unsigned a, unsigned b with b > a and std::vector<std::string> strings of size b-a. How can I fill strings with the elements e.g. "x3" "x4" "x5" "x6" (in case a=3 and b=7) for arbitrary a and b with one C++ command (meaning one semicolon at all :))?
Not too challenging... std::transform( boost::make_counting_iterator(a), boost::make_counting_iterator(b), strings.begin(), "x" + boost::lambda::bind(boost::lexical_cast<std::string, unsigned int>, boost::lambda::_1));
2,275,601
2,366,234
Documenting namespaces with Doxygen
I'm having issues with Doxygen recognizing namespaces and modules. I believe the issue surrounds whether to place the \addtogroup within the namespace or outside the namespace. Example 1, outside the namespace: /*! * \addtogroup Records * @{ */ //! Generic record interfaces and implementations namespace Records { //! Describes the record interface class Interface; } // End namespace Records /*! @} End of Doxygen Groups*/ Example 2 - within namespace //! Generic record interfaces and implementations namespace Records { /*! * \addtogroup Records * @{ */ //! Describes the record interface class Interface; /*! @} End of Doxygen Groups*/ } // End namespace Records I would like the namespace Records to appear under the Doxygen Namespaces tab and indirectly under the Modules tab. Clicking on the item in the Namespaces page should produce a page containing Records::Interface. Clicking on the item in the Modules tab should also produce a page containing Records::Interface. In my Doxygen documentation, I have items missing from Namespaces tab that are in Modules and vice-versa, due to my inconsistency resulting from this dilemma. So which is the proper method, Example 1 or Example 2? {The Doxygen manual is not clear on this topic.} Doxygen: \addtogroup Doxygen: documenting namespaces
I have performed an experiment using Doxygen and the two examples and here are the results. The class names in the examples have been renamed to avoid confusion with Doxygen. Example 1, Outside Namespace /*! * \addtogroup Records * @{ */ //! Generic record interfaces and implementations namespace Records { //! Describes the record interface class Interface; } // End namespace Records /*! @} End of Doxygen Groups*/ Doxygen Results: Click on Modules button (in the main bar). Click on "Records" module in the window. Example 2: Within Namespace (class renamed to Fields) //! Generic record interfaces and implementations namespace Fields { /*! * \addtogroup Fields * @{ */ //! Describes the record interface class Interface; /*! @} End of Doxygen Groups*/ } // End namespace Fields Doxygen Results: Click on Modules button (in the main bar). Click on "Records" module in the window. Summary The location of Doxygen \addtogroup command has different results depending on whether it is located within a namespace definition or outside. When declared outside of a namespace, the Doxygen Modules tab will show the namespace, as shown in Example 1 above. When the \addtogroup command is placed inside a namespace, the Doxygen Modules tab will not display the namespaces as shown in Example 2 above. If you want your namespace to be listed in the Doxygen Modules tab, locate the \addtogroup command outside of the namespace.
2,275,653
2,275,700
Object construction/Forward function declaration ambiguity
Observation: the codes pasted below were tested only with GCC 4.4.1, and I'm only interested in them working with GCC. Hello, It wasn't for just a few times that I stumbled into an object construction statement that I didn't understand, and it was only today that I noticed what ambiguity was being introduced by it. I'll explain how to reproduce it and would like to know if there's a way to fix it (C++0x allowed). Here it goes. Suppose there is a class whose constructor takes only one argument, and this one argument's type is another class with a default constructor. E.g.: struct ArgType {}; class Class { public: Class(ArgType arg); }; If I try to construct an object of type Class on the stack, I get an ambiguity: Class c(ArgType()); // is this an object construction or a forward declaration // of a function "c" returning `Class` and taking a pointer // to a function returning `ArgType` and taking no arguments // as argument? (oh yeh, loli haets awkward syntax in teh // saucecode) I say it's an object construction, but the compiler insists it's a forward declaration inside the function body. For you who still doesn't get it, here is a fully working example: #include <iostream> struct ArgType {}; struct Class {}; ArgType func() { std::cout << "func()\n"; return ArgType(); } int main() { Class c(ArgType()); c(func); // prints "func()\n" } Class c(ArgType funcPtr()) // Class c(ArgType (*funcPtr)()) also works { funcPtr(); return Class(); } So well, enough examples. Anyone can help me get around this without making anything too anti-idiomatic (I'm a library developer, and people like idiomatic libraries)? -- edit Never mind. This is a dupe of Most vexing parse: why doesn't A a(()); work?. Thanks, sbi.
This is known as "C++'s most vexing parse". See here and here.
2,275,829
2,640,961
scons setting CXXFLAGS in one module affects another one
in dirA/SConscript I have: Import('env') probeenv = env.Clone() probeenv['CXXFLAGS'] += ['-fno-rtti','-Wnon-virtual-dtor'] ... stuff that uses probeenv in dirB/SConscript I have Import('env') sipenv = env.Clone() ... stuff that uses sipenv Now, c++ files in dirB that gets compiled, gets the CXXFLAGS from dirA - how come ? This does not happen with CCFLAGS. Nor does it happen if I use probeenv['CXXFLAGS'] = ['-fno-rtti','-Wnon-virtual-dtor'] in dirA
This seems to be a scons bug if CXXFLAGS is not set in "main" SConstruct. The workaround is to simply set it to an empty list there. SConscript: env['CXXFLAGS'] = []
2,275,905
2,275,933
Move C++ app with Boost from Linux to Windows with Visual Studio 6
I made a small program with Boost in Linux 2 yrs ago. Now I want to make it work in Windows. I found there are few .a files in my libs folder. I am wondering how to make it works in Windows? do I need to build Boost in Windows to get library or I can download somewhere? I am using Visual Studio 6.
Yes, you'll need to recompile for different platforms. Coincidentally, I posted instructions on this not long ago. I hugely recommend you do not use Visual Studio 6. It's very dated, and terribly non-conforming. You can get the newer versions for free, as Express. You won't be missing anything.
2,276,007
2,276,048
Which IDE for C++ software can I use for targeting Windows, Linux and OSX?
I was reading today question on IDEs fo C++, and there are very good ones like Netbeans. My question is about creating a software in C++ on Windows Environment, but let users install and run my software also on Linux and OSX. Does netbeans has a compiler to do the job, or is there any good IDE which has a compiler for targeting my c++ code to these other environments? thank you
QtCreator. It's awesome, slick and everything. While it is not as feature rich as some competitors, it does many things just right that others don't. I would say it is the one truly cross-platform IDE that is competitive to single-platform solutions. And it comes with tight integration of a very powerful and clean cross-platform toolkit. Something that you need for most cross-platform applications by itself.
2,276,325
2,276,452
Prevent memory fragmentation
Can anyone point me to a source or outline how the algorithm for the low-fragmentation heap works?
First decide which 'multiples' you want to use for the allocated memory chunks. I typically use 8 bytes. At startup of the application, make a vector where each element in the vector points to a 'pool' of memory chunks. The first index in the vector will be for memory allocations of 8 bytes or less. The second index in the vector will be for memory allocations from 9-16 bytes, and so on. Within every pool, allocate memory in bigger chunks. E.g. in the pool for allocations of 8 bytes (or less), don't allocate 8 bytes, but allocate N times 8 bytes. Within the pool remember which parts are really allocated in the application and which parts are just waiting to be allocated. When freeing memory, don't free it immediately, but keep some chunks ready for the next allocation of that size. Only if you have a lot of subsequent free chunks, return the free memory to the operating system. That's the basic idea. The rest is implementing the pools (typically linked lists of chunks). The difficult part is integrating the heap implementation into the application. If you are still using malloc/free, use #define's to redefine malloc and free If you use new/delete, define global new and delete operators Also take a look at How to solve Memory Fragmentation, and my comment at Memory management in memory intensive application
2,276,329
2,276,409
Why can one specify the size of an array in a function parameter?
I don't understand why the following example compiles and works: void printValues(int nums[3], int length) { for(int i = 0; i < length; i++) std::cout << nums[i] << " "; std::cout << '\n'; } It seems that the size of 3 is completely ignored but putting an invalid size results in a compile error. What is going on here?
In C++ (as well as in C), parameters declared with array type always immediately decay to pointer type. The following three declarations are equivalent void printValues(int nums[3], int length); void printValues(int nums[], int length); void printValues(int *nums, int length); I.e. the size does not matter. Yet, it still does not mean that you can use an invalid array declaration there, i.e. it is illegal to specify a negative or zero size, for example. (BTW, the same applies to parameters of function type - it immediately decays to pointer-to-function type.) If you want to enforce array size matching between arguments and parameters, use pointer- or reference-to-array types in parameter declarations void printValues(int (&nums)[3]); void printValues(int (*nums)[3]); Of course, in this case the size will become a compile-time constant and there's no point of passing length anymore.
2,276,481
2,276,514
Error loading type library/DLL
When I use the following code I get an compilation error #import <dwmapi.lib> #include <dwmapi.h> I get the following error: fatal error C1083: Cannot open type library file: 'c:\program files\microsoft sdks\windows\v7.0a\lib\dwmapi.lib': Error loading type library/DLL. Intellisense says: 2 IntelliSense: cannot open source file "c:/users/####/documents/visual studio 2010/Projects/modlauch/modlauch/Debug/dwmapi.tlh": Bad file descriptor c:\users\####\documents\visual studio 2010\projects\modlauch\modlauch\modlauchdlg.cpp 7 1 modlauch Does anyone know how to solve it? I'm sure that my 'dwmapi' library is fine and there is nothing wrong with it. I'm using MFC with VS2010 , but I don't think that is related to the problem. (Platform - Win32) If I get rid of "#import" then I get "unresolved external symbol __imp__DwmExtendFrameIntoClientArea@8" error.
dwmapi .lib is a type library? YOu sure its not just a plain old dll. A com lib is either .DLL or .tlb. I think its a plain old dll. So you dont #import it you need instead #pragma comment(lib,"dwmapi.lib")
2,276,725
2,276,988
Reading file with cyrillic
I have to open file with cyrillic symbols. I've encoded file into utf8. Here is example: en: Couldn't your family afford a costume for you   ru: Не ваша семья позволить себе костюм для вас How do I open file: ifstream readFile(fileData.c_str()); while (!readFile.eof()) { std::getline(readFile, buffer); ... } The first trouble, there is some symbol before text 'en' (I saw this in debugger): "en: least" And another trouble is cyrillic symbols: " ru: наименьший" What's wrong?
there is some symbol before text 'en' That's a faux-BOM, the result of encoding a U+FEFF BYTE ORDER MARK character into UTF-8. Since UTF-8 is an encoding that does not have a byte order, the faux-BOM shouldn't ever be used, but unfortunately quite a bit of existing software (especially in the MS world) does nonetheless. Load the messages file into a text editor and save it back out again as UTF-8, using a “UTF-8 without BOM” encoding if one is especially listed. ru: наименьший That's what you get when you've got a UTF-8 byte string (representing наименьший) and you print it as if it were a Code Page 1252 (Windows Western European) byte string. It's not an input problem; you have read in the string OK and have a UTF-8 byte string. But then, in code you haven't quoted, it gets output as cp1252. If you're just printing it to the console, this is to be expected, as the console always uses the system default code page (1252 on a Western Windows install), and not UTF-8. If you need to send Unicode to the console you'll have to convert the bytes to native-Unicode wchar​s and write them from there. I don't know what the final destination for your strings is though... if you're just going to write them to another file or something you could just keep them as bytes and not care about what encoding they're in.
2,276,797
2,336,704
gdb Input/Output error remote debugging to Android
I'm trying to debug an android app that call native code to do some GL rendering. The native code is existing code that I'm trying to port (and that I don't really know that well). I've got the existing code compiling, linking, and installing correctly, and I've got some native functions that call in to that code that are being correctly called from my Java code. I'm getting a segfault that I'm trying to track down, and having some problems getting gdb to set a breakpoint in the program. This is on windows XP with Cygwin - and I should probably mention I'm still learning gdb. I started with the directions at http://honeypod.blogspot.com/2008/01/debug-native-application-for-android.html; here's what I'm currently doing. Start the app in the emulator. In a cmd prompt: > adb forward tcp:1234 tcp:1234 > adb shell # gdbserver localhost:1234 --attach 2120 gdbserver localhost:1234 --attach 2120 Attached; pid = 2120 Listening on port 1234 In a cygwin shell: arm-eabi-4.2.1/bin/arm-eabi-gdb.exe out/apps/app-android/libDM.so GNU gdb 6.6 Copyright (C) 2006 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "--host=i686-pc-cygwin --target=arm-elf-linux"... (gdb) target remote localhost:1234 Remote debugging using localhost:1234 warning: shared library handler failed to enable breakpoint 0xafe0da04 in AppRefCounted::unref () at ../../stlport/stl/_iosfwd.h:39 39 class basic_ostream; Current language: auto; currently c++ (gdb) b Java_com_app_AppRenderer_onCreate Breakpoint 1 at 0xafff1b1a: file apps/app-android/../../../app-Android/jni/DMJNI/DMInterface.cpp, line 75. (gdb) c Continuing. Warning: Cannot insert breakpoint 1. Error accessing memory address 0xafff1b1a: Input/Output error. So it looks like the breakpoint gets set ok, and that the symbols are ok, but maybe the address is wrong when it tries to insert the breakpoint. I've tried several variations of different commands from the webpage referenced above, but so far, no luck. Any ideas what's going on? Thanks
Essentially, at this point with NDK 1.6, I've found that there just isn't support for this kind of debugging strictly with the NDK. However, if you use the PDK (platform development kit), you can do this kind of debugging with native code. We haven't tried the PDK, because generating a map file worked well enough for us (see this SO question), but if you do go that route, check the NDK google group for more details.