question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,149,286
3,149,739
Architectural tips on building a shared resource for different processess
In the company I work at we're dealing with a huge problem: we have a system that consists in several units of processing. We made it this way so each module has specific functionality. The integration between these modules is done using a queue system (which is not fast but we're working on it) and replicating messages between these modules. The problem is that this is generating a great deal of overhead as four of these systems are requiring the same kind of data, and maintaining consistency for these modules is bad. Another requirement for the system is redundancy, so I was thinking to kill these two problems in one shot. So I was thinking of using some kind of shared resource. I've looked at shared memories (which are great but could lead to locking inconsistencies if the module crashes leading to inconsistencies in the program), and maybe do some "raw copy" from the segment to another computer to do redundancy. So I've began to search for alternatives, ideas and something like that. I've found one that is noSQL, but I don't know if the speed that I'm requiring would suffice this. I need something (ideally): Memory-like fast That could provide me redundancy (active-passive is ok, active active is good)
I also think that shared-memory is the way to go. To provide redundancy, let every process copy the data that is going to be changed to local/non-shared memory. Only after the module has done its work, copy it back to shared memory. Make sure the 'copy-to-shared-memory' part is as small as possible and nothing can go wrong while doing the copy. Some tricks you could use are: Prepare all data in local memory and use one memcpy operation to copy it to shared memory Use a single value to indicate that the written data is valid. This could be a boolean or something like a version number that indicates the 'version' of the data written in shared memory.
3,149,371
3,149,404
PHP-Based intranet application Call center
As in title, I am making a PHP-Based intranet application Call center, I've finished the DB design/UI. But now I need to automatically intercept calls and send the caller ID to the PHP webserver so the request is routed to the next free agent while his webpage refreshes with the caller's card(and previous questions maybe). Now, How can i route a call inside LAN?, My setup will be a switch where multiple telephone lines is connected this switch is connected with the server where there's a module(Maybe C++ that can intercept calls,route it to free agent,record the call and open the caller's card in the screen of the agent). So, Can any one give me a starting point for this call routing and call intercepting problem? Thanks
Have you looked at TrixBox? This should be able to handle incoming calls, and from memory I believe it has methods to send data elsewhere eg to your webserver. From there it should be able to route the call over an IP-based network to your next free agent. This obviously depends on the flexibility of your hardware and whether you could integrate this or not...! :-)
3,149,395
3,151,047
How to compile and build this BHO for IE?
http://www.adp-gmbh.ch/win/com/bho.html When I compile, I get lots of errors: error C2236: unexpected 'class' 'adpbho'. Did you forget a ';'? error C3381: 'adpbho' : assembly access specifiers are only available in code compiled with a /clr option ..\adpbho.cpp(15) : error C3861: 'MB1': identifier not found ..\adpbho.cpp(24) : error C3861: 'MB1': identifier not found ..\adpbho.cpp(34) : error C3861: 'MB1': identifier not found ..\adpbho.cpp(85) : error C3861: 'MB1': identifier not found ..\adpbho.cpp(95) : error C2014: preprocessor command must start as first nonwhite space ..\adpbho.cpp(96) : error C2039: 'MB1' : is not a member of 'adpbho'
Well, assuming you turned off your brain and just cut and pasted the garbage on that site, the first error is that this is not a valid way to declare a C++ class: class BHO class adpbho : public IObjectWithSite, public IDispatch { There are two class statements. That's not allowed. It's probably supposed to be: class adpbho : public IObjectWithSite, public IDispatch { The rest of the code is pretty horrible too. You're going to have to go line-by-line and clean it up, or find a better sample. EDIT: The more I look at it the more bugs and errors I see. I highly recommend that you not use this code and instead find a better sample somewhere. This has nothing to do specifically with BHO's or IE plugins and everything to do with basic C++ win32 programming, so I'll fix your tags.
3,149,407
3,149,686
Call a member function with bare function pointer
What's the best way to call a member function if you have an object and a bare function pointer pointing to the member? Essentially I want to call the function pointer with thiscall calling convention. Background: I'm looking up symbols in a shared library dynamically, obtaining a factory function pointer and a pointer to a certain member function I want to call. The member function itself is not virtual. I have no control over the shared library, I just have the binary. Example: typedef void * (*GenericFptr)(); GenericFptr lookup(const char *); class CFoo; GenericFptr factoryfn(lookup("CFoo factory function")); CFoo *foo = reinterpret_cast<CFoo *>(factoryfn()); GenericFptr memberfn(lookup("CFoo member function")); // now invoke memberfn on foo Currently I'm using an union to convert the function pointer to a pointer to member function. It's ugly and creates dependencies to compiler implementation details: class CFoo { public: void *dummy() { return 0; } }; typedef void * (CFoo::*FooMemberPtr)(); union { struct { // compiler-specific layout for pointer-to-member void *x, *y; GenericFptr ptr; } fnptr; FooMemberPtr memberfn; } f; f.memberfn = &CFoo::dummy; // init pointer-to-member f.fnptr.ptr = memberfn; // rewrite pointer void *result = (foo->*f.memberfn)();
Unfortunately a member function pointer has more information than a standard function pointer, and when you get the standard function pointer, converting it to a member function pointer would effectively be trying to generate extra data out of thin air. I don't think there's any portable way to do what you're attempting, although if the union appears to work you could probably get away with that. Again, you would need to know the representation and calling convention for these methods for each compiler you wish to use to build the bode. If you know the member function's name, why can't you just do foo->dummy() for example? Otherwise either the lookup function needs to provide a full member function pointer or the library would have to provided a C wrapper interface with normal functions to which a this pointer can be passed.
3,149,543
3,149,575
Method return being assigned to variable
I have a method that is returning a CString and placing it into a variable, however this variable is a parameter in the method. Is there a better way to assign the return of the method into the variable? Example: CString foo = "foo"; foo = MakeBar(foo);
Pass foo by reference into the function. In that way it's understood that it will be an input/output parameter. void MakeBar(CString &foo) { if(foo == "foo") foo = "bar"; } //... CString foo = "foo"; MakeBar(foo);
3,149,611
3,149,742
Sort a vector on a value calculated on each element, without performing the calculation multiple times per element
can anyone recommend a nice and tidy way to achieve this: float CalculateGoodness(const Thing& thing); void SortThings(std::vector<Thing>& things) { // sort 'things' on value returned from CalculateGoodness, without calling CalculateGoodness more than 'things.size()' times } Clearly I could use std::sort with a comparison function that calls CalculateGoodness, but then that will get called several times per Thing as it is compared to other elements, which is no good if CalculateGoodness is expensive. I could create another std::vector just to store the ratings and std::sort that, and rearrange things in the same way, but I can't see a tidy way of doing that. Any ideas? Edit: Apologies, I should have said without modifying Thing, else it's a fairly easy problem to solve :)
I can think of a simple transformation (well two) to get what you want. You could use std::transform with suitable predicates. std::vector<Thing> to std::vector< std::pair<Result,Thing> > sort the second vector (works because a pair is sorted by it first member) reverse transformation Tadaam :) EDIT: Minimizing the number of copies std::vector<Thing> to std::vector< std::pair<Result,Thing*> > sort the second vector transform back into a secondary vector (local) swap the original and local vectors This way you would only copy each Thing once. Notably remember that sort perform copies so it could be worth using. And because I am feeling grant: typedef std::pair<float, Thing*> cached_type; typedef std::vector<cached_type> cached_vector; struct Compute: std::unary_function< Thing, cached_type > { cached_type operator()(Thing& t) const { return cached_type(CalculateGoodness(t), &t); } }; struct Back: std::unary_function< cached_type, Thing > { Thing operator()(cached_type t) const { return *t.second; } }; void SortThings(std::vector<Thing>& things) { // Reserve to only allocate once cached_vector cache; cache.reserve(things.size()); // Compute Goodness once and for all std::transform(things.begin(), things.end(), std::back_inserter(cache), Compute()); // Sort std::sort(cache.begin(), cache.end()); // We have references inside `things` so we can't modify it // while dereferencing... std::vector<Thing> local; local.reserve(things.size()); // Back transformation std::transform(cache.begin(), cache.end(), std::back_inserter(local), Back()); // Put result in `things` swap(things, local); } Provided with the usual caveat emptor: off the top of my head, may kill kittens...
3,149,816
3,149,912
MFC: Save from CImage to database as selected file-type
We have a requirement that a user can load any standard image into a dialog, the image is displayed, and the image saved as a specific format (JPG) in a database. It seems CImage is the class to be using since it can load and save BMP/GIF/JPG/PNG. But is there an easy way to save the JPG as a BLOB in the database without calling CImage::Save and then loading the file to memory - we don't want to save the file even temporarily. Any ideas?
CImage::Save has two overloads. You could use HRESULT Save( IStream* pStream, REFGUID guidFileType ) const throw(); to save the image to an IStream. You could write your own simple IStream implementation or could try to use the CreateStreamOnHGlobal function, which creates an IStream object on an HGLOBAL.
3,149,859
3,149,881
std::map::const_iterator template compilation error
I have a template class that contains a std::map that stores pointers to T which refuses to compile: template <class T> class Foo { public: // The following line won't compile std::map<int, T*>::const_iterator begin() const { return items.begin(); } private: std::map<int, T*> items; }; gcc gives me the following error: error: type 'std::map<int, T*, std::less<int>, std::allocator<std::pair<const int, T*> > >' is not derived from type 'Foo<T>' Similarly, the following also refuses to compile: typedef std::map<int, T*>::const_iterator ItemIterator; However, using a map that doesn't contain the template type works OK, e.g.: template <class T> class Foo { public: // This is OK std::map<int, std::string>::const_iterator begin() const { return items.begin(); } private: std::map<int, std::string> items; }; I assume this is related to templates and begs the question - how can I return a const_iterator to my map?
Use typename: typename std::map<int, T*>::const_iterator begin() const ... When this is first passed by the compiler, it doesn't know what T is. Thus, it also doesn't know wether const_iterator is actually a type or not. Such dependent names (dependent on a template parameter) are assumed to not be types unless prefixed by typename not to be templates unless directly prefixed by template.
3,149,974
3,152,171
Is C++ OTL SQL database library using parameterized queries under the hood, or string concat?
I've been looking at the OTL (Oracle, Odbc and DB2-CLI Template Library) for C++ database access. I'm unsure of whether the query I pass in is converted to a parameterized query for the underlying database, or if it's basically just concatenating all the arguments into one big string and passing the query to the database that way. I see that the query you pass in to it can include type information for the arguments, but what happens between then and the query hitting the database, I can't tell.
OTL author's response to my e-mail: OTL passes queries with placeholders into the DB API layers. The naming conventions for actual bind variables are different for different DB types. Say, for Oracle, SELECT * FROM staff WHERE fname=:f_name<char[20]> will be translated into: SELECT * FROM staff WHERE fname=:f_name plus a bunch of host variable bind calls. For MS SQL Server, or DB2, the same SELECT would look like this: SELECT * FROM staff WHERE fname=? It's described in the manual that you can't have a placeholder with the same name more than once for MS SQL, DB2. SQL statements with placeholder / bind variables are relatively expensive to create, so if you instantiate an parameterized SQL via an otl_stream, it makes sense to reuse the stream as much as you can. If you have more questions, or suggestions on how I can improve the OTL manual, feel free to email me. Cheers, Sergei pheadbaq wrote: Hi, I've been evaluating C++ DB libraries recently to use as a base for an ORM library I wish to build, and have been gravitating more and more towards the OTL. It looks very nice by the way, and seems like it would meet most of the needs I have. I just have one lingering question that I can't seem to clarify by reading the docs. Does OTL pass a parameterized query on to the underlying DBMS, or is it concatenating the arguments and query I pass to the OTL stream into a single string and hand that to the DBMS? In other words, if I hand OTL this MSSQL query, along with with the string "Bob" as the bind variable: SELECT * FROM staff WHERE fname = :f_name<char[20]> Does the OTL parser produce this: SELECT * FROM staff WHERE fname = 'Bob' Or this: SELECT * FROM staff WHERE fname = @f_name along with my string as a parameter I've posted this same question to StackOverflow.com if you care to respond there: Is C++ OTL SQL database library using parameterized queries under the hood, or string concat? Thank you for your time
3,150,108
3,150,262
Listview flickers on Win32 dialog when removing and re-adding all items and all columns
Consider a plain Win32 dialog with listview control (in report mode) written in C++. Upon a certain event all items and all columns are deleted and new columns and items are created. Basically, as content changes, columns are automatically generated based on content. When old items/columns are removed and new ones added, listview flickers like hell. I have tried WM_SETREDRAW and LockWindowUpdate() with no change to visual experience. I have even set extended listview style LVS_EX_DOUBLEBUFFER and that didn't help at all. The parent dialog has WS_CLIPCHILDREN set. Any suggestions how to make this work with as little flicker as possible? I am thinking of using two listviews, alternating visibility, using the hidden one as a back buffer but this sounds like an overkill. There must be an easy way.
The default list control painting is pretty flawed. But there is a simple trick to implement your own double-buffering technique: CMyListCtrl::OnPaint() { CRect rcClient; GetClientRect(rcClient); CPaintDC dc(this); CDC dcMem; dcMem.CreateCompatibleDC(&dc); CBitmap bmMem; bmMem.CreateCompatibleBitmap(&dc, rcClient.Width(), rcClient.Height()); CBitmap* pbmOld = dcMem.SelectObject(&bmMem); dcMem.FillSolidRect(rcClient, ::GetSysColor(COLOR_WINDOW)); this->DefWindowProc(WM_PAINT, (WPARAM)dcMem.m_hDC, (LPARAM)0); dc.BitBlt(0,0,rcClient.Width(), rcClient.Height(), &dcMem, 0, 0, SRCCOPY); dcMem.SelectObject(pbmOld); CHeaderCtrl* pCtrl = this->GetHeaderCtrl(); if (::IsWindow(pCtrl->GetSafeHWnd()) { CRect aHeaderRect; pCtrl->GetClientRect(&aHeaderRect); pCtrl->RedrawWindow(&aHeaderRect); } } This will create a bitmap and then call the default window procedure to paint the list control into the bitmap and then blitting the contents of the bitmap into the paint DC. You should also add a handler for WM_ERASEBKGND: BOOL CMyListCtrl::OnEraseBkgnd(CDC* pDC) { return TRUE; } This will stop the control from always erasing the background before a redraw. You can optimize the OnPaint further if you add a member variable for the bitmap and only (re)create it when the size of the window changed (because always creating a bitmap may be costly depending on the size of the window). This should work pretty well.
3,150,268
3,150,326
Creating `char ***data`?
I have to create a 3-Dimensional array, wich gets allocated at object creation. I've done such stuff before with normal arrays. typedef unsigned char byte; // =| byte ***data;
If you're using C++, I strongly advise you using std::vector instead of raw arrays. Something like: std::vector<std::vector<std::vector<char> > > data(3, std::vector<std::vector<char> >(3, std::vector<char>(3, 0))); Will create a 3x3x3 array of chars, all initialized to 0. You can then access the items the same way you would with a char***: data[0][0][0] = 1; Depending on your needs you might also use only one std::vector and inline your three-dimensional space into it. This would fasten both computation and copy operations, as the values would then be in a contiguous block of memory. The way you could inline the values depending on your needs, but here is an example: For a 3 dimensional array like this: a----b |\ |\ | d----c e-|--f | \| \| h----g You might store values like this in memory: a, b, c, d, e, f, g, h This require some maths, but if you encapsulate this, you can even achieve the same level of usability of a vector of vector of vector, with much higher performances.
3,150,310
3,150,330
C++ virtual override functions with same name
I have something like that (simplified) class A { public: virtual void Function () = 0; }; class B { public: virtual void Function () = 0; }; class Impl : public A , public B { public: ???? }; How can I implement the Function () for A and the Function() for B ? Visual C++ lets you only define the specific function inline (i.e. not in the cpp file), but I suppose it's an extension. GCC complains about this. Is there a standard C++ way to tell the compiler which function I want to override? (visual c++ 2008) class Impl : public A , public B { public: void A::Function () { cout << "A::Function" << endl; } void B::Function () { cout << "B::Function" << endl; } }; Thank you!
You cannot use qualified names there. I you write void Function() { ... } you are overriding both functions. Herb Sutter shows how it can be solved. Another option is to rename those functions, because apparently they do something different (otherwise i don't see the problem of overriding both with identical behavior).
3,150,477
3,150,521
C++ and C# interoperability : P/Invoke vs C++/CLI
In the course of finding a way to interoperate between C# and C++ I found this article that explains about P/Invoke. And I read a lot of articles claiming that C++/CLI is not exact C++ and requires some effort to modify from original C++ code. I want to ask what would be the optimal way when I have some C++ objects (code/data) that I want to use from C# objects. It looks like that in order to use P/Invoke, I should provide C style API. Is it true? I mean, is there a way to export C++ object to C# like SWIG with P/Invoke? Or, do I have to use SWIG for this purpose? How hard is it to change C++ to C++/CLI? Is it worth trying compared to rewrite the C++ to C#? The C++ is well designed, so implementing it to C# is not great deal. (Off the topic question) Is there the other way round? I mean, if I want to use C# code from C++, is there any way to do so?
I would not recommend rewritng your C++ library into C++/CLI. Instead, I would write a C++/CLI wrapper that you can call from C#. This would consist of some public ref class classes, each of which probably just manages an instance of the native class. Your C++/CLI wrapper just "include the header, link to the lib" to use the native library. Because you have written public ref class classes, your C# code just adds a .NET reference. And all you do inside each public ref class is use C++ Interop (aka It Just Works interop) to call the native code. You can apply a facade while you're at it if you like.
3,150,563
3,159,074
adding a document to a Lucene index causes crash
i'm trying to index an mp3 file with only one ID3 frame. using CLucene and TagLib. the following code works fine: ... TagLib::MPEG::File file("/home/user/Depeche Mode - Personal Jesus.mp3"); if (file.ID3v2Tag()) { TagLib::ID3v2::FrameList frameList = file.ID3v2Tag()->frameList(); lucene::document::Document *document = new lucene::document::Document; TagLib::ID3v2::FrameList::ConstIterator frame = frameList.begin(); std::wstring field_name((*frame)->frameID().begin(), (*frame)->frameID().end()); const wchar_t *fieldName = field_name.c_str(); const wchar_t *fieldValue = (*frame)->toString().toWString().c_str(); lucene::document::Field field(fieldName, fieldValue, true, true, true, false); document->add(field); writer->addDocument(document); } ... but this one makes the application crash: ... TagLib::MPEG::File file("/home/user/Depeche Mode - Personal Jesus.mp3"); if (file.ID3v2Tag()) { TagLib::ID3v2::FrameList frameList = file.ID3v2Tag()->frameList(); lucene::document::Document *document = new lucene::document::Document; for (TagLib::ID3v2::FrameList::ConstIterator frame = frameList.begin(); frame != frameList.end(); frame++) { std::wstring field_name((*frame)->frameID().begin(), (*frame)->frameID().end()); const wchar_t *fieldName = field_name.c_str(); const wchar_t *fieldValue = (*frame)->toString().toWString().c_str(); lucene::document::Field field(fieldName, fieldValue, true, true, true, false); document->add(field); } writer->addDocument(document); } ... why is that?!
This is a scope issue - by the time you call writer->addDocument, the fields you added to it are freed. Use this code instead: document->add(* new lucene::document::Field(fieldName, fieldValue, true, true, true, false)); You may want to look at cl_demo and cl_test to see some code samples.
3,150,581
3,151,794
UnicodeString to char* (UTF-8)
I am using the ICU library in C++ on OS X. All of my strings are UnicodeStrings, but I need to use system calls like fopen, fread and so forth. These functions take const char* or char* as arguments. I have read that OS X supports UTF-8 internally, so that all I need to do is convert my UnicodeString to UTF-8, but I don't know how to do that. UnicodeString has a toUTF8() member function, but it returns a ByteSink. I've also found these examples: http://source.icu-project.org/repos/icu/icu/trunk/source/samples/ucnv/convsamp.cpp and read about using a converter, but I'm still confused. Any help would be much appreciated.
call UnicodeString::extract(...) to extract into a char*, pass NULL for the converter to get the default converter (which is in the charset which your OS will be using).
3,150,700
3,151,243
Need meta-programming magic to define a mother lode of bit fields in an error-free way
The goal is to control which types of users are allowed to perform which operations at the UI level. This code has been in place for a while; I just want to improve it a bit. The file which I am trying to improve should probably be auto-generated, but that would be too big of a change, so I seek a simpler solution. A file which we shall call PermissionBits.h has a bunch of these: // Here names are mangled; for example XYZ_OP_A is: // permission to operation A in category/context XYZ // SCU64 = static const unsigned __int64 // Some namespaces utilize all 64 bits // The actual values (as long as they are proper bit fields) // do not matter - they are always used by name namespace XYZPermissionBits { SCU64 XYZ_OP_A = 1UI64 << 0; // 1 = 0x0000000000000001 SCU64 XYZ_OP_B = 1UI64 << 1; // 2 = 0x0000000000000002 SCU64 XYZ_OP_C = 1UI64 << 2; // 4 = 0x0000000000000004 SCU64 XYZ_OP_C = 1UI64 << 3; // 8 = 0x0000000000000008 SCU64 XYZ_OP_D = 1UI64 << 4; // 16 = 0x0000000000000010 SCU64 XYZ_OP_E = 1UI64 << 5; // 32 = 0x0000000000000020 SCU64 XYZ_OP_F = 1UI64 << 6; // 64 = 0x0000000000000040 SCU64 XYZ_OP_G = 1UI64 << 7; // 128 = 0x0000000000000080 SCU64 XYZ_OP_H = 1UI64 << 8; // 256 = 0x0000000000000100 SCU64 XYZ_OP_I = 1UI64 << 9; // 512 = 0x0000000000000200 SCU64 XYZ_OP_J = 1UI64 << 10; // 1024 = 0x0000000000000400 SCU64 XYZ_OP_K = 1UI64 << 11; // 2048 = 0x0000000000000800 SCU64 XYZ_OP_L = 1UI64 << 12; // 4096 = 0x0000000000001000 } Even with the help of 1UI64 << <numBits>; shortcut there are still problems, as coders create flags with duplicate values, make typos, etc. Ideally I would like a macro which can be nicely formatted and look like: BITFIELDS_FOR_NAMESPACE( //*************** <<== I want to make the namespace name more vivid XYZPermissionBits, //*************** <<== somehow if that is possible. It is not a must-have. XYZ_OP_A, // Being able to add a comment here would be nice, but not critical XYZ_OP_B, XYZ_OP_C, XYZ_OP_D, XYZ_OP_E, XYZ_OP_F, XYZ_OP_G, XYZ_OP_H, XYZ_OP_I, XYZ_OP_J, XYZ_OP_K, XYZ_OP_L ) I would like this macro be flexible and prevent me from entering less than 2 or more than 65 arguments - namespace name + 64 flags. Is it possible to do what I want or close to it, or should I resort to generated code? What other advice do you have?
Tested example using Boost.PreProcessor: #include <boost/preprocessor/seq/for_each_i.hpp> #include <boost/preprocessor/comparison/greater.hpp> #include <boost/preprocessor/comparison/less.hpp> #include <boost/preprocessor/debug/assert.hpp> #include <boost/preprocessor/seq/size.hpp> #define CHECK_SIZE(size) \ BOOST_PP_ASSERT_MSG(BOOST_PP_GREATER(size, 1), "< 2 :(") \ BOOST_PP_ASSERT_MSG(BOOST_PP_LESS(size, 65), "> 64 :(") \ #define DO_MAKE_BITFIELDS(a, b, i, elem) \ SCU64 elem = 1UI64 << i; #define BITFIELDS_FOR_NAMESPACE(name, seq) \ CHECK_SIZE(BOOST_PP_SEQ_SIZE(seq)) \ namespace name { \ BOOST_PP_SEQ_FOR_EACH_I(DO_MAKE_BITFIELDS, _, seq) \ } Usage: BITFIELDS_FOR_NAMESPACE( XYZPermissionBits, (XYZ_OP_A) (XYZ_OP_B) // ... );
3,150,844
3,150,925
strange object serialization problem in file parsing
I have a strange problem with object serialization. in the file documentation it states as following The lead in starts with a 4-byte tag that identifies a TDMS segment ("TDSm"). The next four bytes are used as a bit mask in order to indicate what kind of data the segment contains. This bit mask is referred to as ToC (Table of Contents). Any combination of the following flags can be encoded in the ToC: The next four bytes contain a version number (32-bit unsigned integer), which specifies the oldest TDMS revision a segment complies with. At the time of this writing, the version number is 4713. The only previous version of TDMS has number 4712. The next eight bytes (64-bit unsigned integer) describe the length of the remaining segment (overall length of the segment minus length of the lead in). If further segments are appended to the file, this number can be used to locate the starting point of the following segment. If an application encountered a severe problem while writing to a TDMS file (crash, power outage), all bytes of this integer can be 0xFF. This can only happen to the last segment in a file. The last eight bytes (64-bit unsigned integer) describe the overall length of the meta information in the segment. This information is used for random access to the raw data. If the segment contains no meta data at all (properties, index information, object list), this value will be 0. so i implemented as class TDMsLEADIN { public: char Signature[4]; //TDSm __int32 Toc; unsigned __int32 vernum; unsigned __int64 nextSegmentOff; unsigned __int64 rawDataOff; }; fread(&leadin,sizeof(TDMsLEADIN),1,f); then i got signature="TDsm", TOc=6, vernum=4712 as expected. nextSegmentOff=833223655424, rawDataOff=8589934592 but expected both of nextSegmentOff and rawDataOff=194 then i break the class into two parts, and read two two parts seperately class TDMsLEADIN { public: char Signature[4]; //TDSm __int32 Toc; unsigned __int32 vernum; }; class TDMsLeadINend{ public: unsigned __int64 nextSegmentOff; unsigned __int64 rawDataOff; }; fread(&leadin,sizeof(TDMsLEADIN),1,f); fread(&leadin2,sizeof(TDMsLeadINend),1,f); then i got nextSegmentOff ,rawDataOff as expected=194. my question is what is wrong with the original code? why it works when i break it into two parts? i tried unsigned long long instead of unsigned __int64, but still the same result. it is quite strange. Thanks
You seem to be just reading and writing the binary data in the struct directly. Generally the compiler will align structure data for performance, so when it's a single struct there's a hidden 32-bit pad between vernum and nextSegmentOff to align nextSegmentOff. When it's split into two structures there's no such extra padding and you're reading four bytes of padding and four bytes of real data into nextSegmentOff. You can test this by comparing the sizeof(TDMsLEADIN [second version]) + sizeof(TDMsLeadINend) to sizeof(TDMsLEADIN [first version]) The standard way to serialize data is to serialize each underlying piece individually rather than relying on the layout of a class or structure as that can change by compiler without notice.
3,150,942
3,150,965
Is "delete this" allowed in C++?
Is it allowed to delete this; if the delete-statement is the last statement that will be executed on that instance of the class? Of course I'm sure that the object represented by the this-pointer is newly-created. I'm thinking about something like this: void SomeModule::doStuff() { // in the controller, "this" object of SomeModule is the "current module" // now, if I want to switch over to a new Module, eg: controller->setWorkingModule(new OtherModule()); // since the new "OtherModule" object will take the lead, // I want to get rid of this "SomeModule" object: delete this; } Can I do this?
The C++ FAQ Lite has a entry specifically for this https://isocpp.org/wiki/faq/freestore-mgmt#delete-this I think this quote sums it up nicely As long as you're careful, it's OK for an object to commit suicide (delete this).
3,150,961
3,151,137
Yet another Dynamic Array vs. std::vector, but
...well, I got strange results! I was curious about the performance of std::vector vs. that of a dynamic array. Seeing as there are many questions on this subject already, I wouldn't have mentioned it if I didn't constantly get these 'contradictory' results: vector<int> is somehow faster than a new int[]! I always thought that if there was any performance difference, it would always favor the dynamic array. How is this result possible? The code is below: int numElements = 10000000; long j = 0; long k = 0; vector<int> intVector(numElements); int* intArray = new int[numElements]; clock_t start, finish; start = clock(); for (int i = 0; i < numElements; ++i) intVector[i] = i; for (int i = 0; i < numElements; ++i) j += intVector[i]; finish = clock(); cout << "j: " << j << endl; cout << "Total duration: " << (double) finish - start << " ms." << endl; // Test Control. start = clock(); for (int i = 0; i < numElements; ++i) intArray[i] = i; for (int i = 0; i < numElements; ++i) k += intArray[i]; finish = clock(); cout << "k: " << k << endl; cout << "Total duration: " << (double) finish - start << " ms." << endl; Optimizations were on, and I separated the for loops within each start/finish block so that I could separately time the initializations of the array/vector (in that case, std::vector<int> and new int[] appear to perform identically). However, with the above code I constantly get std::vector<int> winning at 26-30 ms versus 36-45 ms for the new int[]. Anyone care to explain why the vector is performing better than the dynamic array? Both were declared before the timing loops so I expected performance to be about the same. Furthermore, I tried the same idea instead using std::vector<int*> and new int*[] and got similar results, with the vector class outperforming the dynamic array, so the same holds for pointers to pointers. Thanks for the help. Addendum: Without optimization, std::vector loses out big time to a dynamic array (~1,400 ms vs. ~80 ms), to give the expected performance difference, but doesn't this imply that the vector class can somehow be optimized to give better performance than a standard dynamic array?
My wild guess is that the OS isn't allocating physical memory until it's first accessed. The vector constructor will initialise all the elements, so the memory will be allocated by the time you've started timing. The array memory is uninitialised (and possibly unallocated), so the time for that might include the allocation. Try changing the array initialisation to int* intArray = new int[numElements](); to value-initialise its elements, and see if that changes the results.
3,151,002
3,151,175
Detect DVD Burners in Windows
Is there anyway to dectect available DVD burners in a windows system using c++? I know how to detect all available drives but I would like to be able to detect which ones have the ability to burn DVD media.
What you want is the Image Mastering API (IMAPI). To list the available devices you can use IDiscMaster::EnumDiscRecorders.
3,151,114
3,151,266
Text Editing Question
I'm traversing a text file line by line adjusting the text so that the file eventually will match the syntax required to be run on a MIPS simulator (MARS). My issue is that whenever I see a line with the string "blezl" in it, I want to do several things. First I need to insert some lines of text following the line containing this word. That's easy enough using insert. I then have to insert some lines of text after the line that originally followed the found line. The problem is, I need to then search the entire document for a string that was at the end of the found string and then insert a few lines before any lines that contain the 2nd string found. So.. #1 blezl v0,#10 #2 addu s1,s0,s5 #3 lw v1,0(s8) ... #10 addu s1,s0,s5 i need to find "blezl", and then I insert some lines between "#1" and "#2". Then I insert some lines between "#2" and "#3", and then I need to search the entire document for "#10" and when I find any, I insert some lines before it. The problem is that the last step requires that I search the entire document (in the middle of traversing line by line until blezl was found). This is because "#10" could occur anywhere before or after "#1". This is going to take forever (there are 80k lines in my file and probably about 2% of them have "blezl" in them.) How can I do this without the massive redundant step?
80k lines isn't large enough that you can't load it into RAM. Searches are fairly fast once you have data in ram. If you are concerned about performance, you could make a b-tree to store lines based on label. This would give you log(n) search time for each line you need to find.
3,151,276
3,151,289
Cyclical Linked List Algorithm
I have been asked recently in a job interview to develop an algorithm that can determine whether a linked list is cyclical. As it's a linked list, we don't know its size. It's a doubly-linked list with each node having 'next' and 'previous' pointers. A node can be connected to any other node or it can be connected to itself. The only solution that I came up at that time was to pick a node and check it with all the nodes of the linked list. The interviewer obviously didn't like the idea as it is not an optimal solution. What would be a better approach?
The general solution is to have 2 pointers moving at different rates. They will eventually be equal if some portion of the list is circular. Something along the lines of this: function boolean hasLoop(Node startNode){ Node slowNode = startNode; Node fastNode1 = startNode; Node fastNode2 = startNode; while (slowNode && fastNode1 = fastNode2.next() && fastNode2 = fastNode1.next()){ if (slowNode == fastNode1 || slowNode == fastNode2) return true; slowNode = slowNode.next(); } return false; } Blatantly stolen from here: http://ostermiller.org/find_loop_singly_linked_list.html
3,151,320
3,151,364
can not count array elements after passing as argument
I am having issues counting the array elements after passing it into an arguement void GXDX::LoadMesh(GXVector vertices[], UINT indices[] = NULL) { D3D10_BUFFER_DESC bufferDesc; UINT numVerts = sizeof(vertices)/sizeof(GXVector); bufferDesc.Usage = D3D10_USAGE_DEFAULT; bufferDesc.ByteWidth = sizeof(GXVector) * numVerts; bufferDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; bufferDesc.MiscFlags = 0; bufferDesc.CPUAccessFlags = 0; code.............. } In the following line above UINT numVerts = sizeof(vertices)/sizeof(GXVector); I am trying to count the number of elements in the array varible vertices. But I am not getting an accurate count, if not one at all. When I did a step through, I notice that I am not able to see all the values in the array, only the first value of the array. So I am not sure if I am passing the array correctly as an arguement. In another application, I did the same thing and i was able to see all the values in the step through. I pass the array like this. GXVector vertices[] = { {D3DXVECTOR3(0.5f, 0.5f, 0.5f)}, {D3DXVECTOR3(0.5f, -0.5f, 0.5f)}, {D3DXVECTOR3(-0.5f, -0.5f, 0.5f)}, {D3DXVECTOR3(-0.5f, -0.5f, 0.5f)}, {D3DXVECTOR3(-0.5f, 0.5f, 0.5f)}, {D3DXVECTOR3(0.5f, 0.5f, 0.5f)}, }; UINT indices[] = {0,1,2,3,4}; GXRenderManager::Device()->LoadMesh(vertices, indices); So in a nutshell, Am I passing the array right as an arguement, what am I doing wrong where I can not get the correct element count of the array.
Yes, you are passing the array correctly; however, in C (and C++), arrays don't contain their size. So you need to pass the size of the array as a separate parameter. Arrays effectively decay into pointers when passed as a parameter into a function, so sizeof(vertices) will give you the size of the pointer type, not the size of the array. You can walk through the array though, either with pointer arithmetic or indexing - but you need to know its exact size, otherwise you can get out of bounds. This is one main reason why in C++ std::vector is recommended to use instead of raw arrays.
3,151,393
3,151,405
Unclear about `delete` and pointers
Say we have a piece of code: //... class A //... A* myA = new A(); A* myPointerToMyA = myA; delete myA; delete myPointerToMyA; // this is wrong, no? //... The last line does the exact same thing as the one above it, correct? So I would now be deleteing an invalid/NULL pointer? I understand this may be a stupid question, but still, I need some reassurance.
You are correct. So I would now be deleteing an invalid/NULL pointer? Well, technically it's only invalid, because nothing was set to NULL. It's ok to delete a NULL pointer.
3,151,440
3,151,520
OpenMP, C++ and Iterators
To loop over elements of a container, I would typically use an iterator, like so: container<type> myContainer; // fill up the container container<type>::iterator it; for(it=myContainer.begin(); it!=myContainer.end(); ++it) { //do stuff to the elements of the container } Now, if I want to parallelize the loop using OpenMP, I might try something like: container<type> myContainer; // fill up the container container<type>::iterator it, it_begin=myContainer.begin(), it_end=myContainer.end(); #pragma omp parallel for default(none) private(it) shared(it_begin, it_end) for(it=it_begin; it!=it_end; ++it) { //do stuff to the elements of the container } However, when I run said code, the changes are not made to the container. If, however, I use a typical indexing on the container, the parallel code works fine. What I am wondering is if it is possible to use iterators in the context of OpenMP, or if I need to convert the iterated loop to an indexed loop?
Parallelization for STL iterators is allowed only in OpenMP 3.0. Which version of OpenMP does your compiler supports?
3,151,464
3,151,498
Why is the code printing the last std::cout?
using namespace std; template<typename T> int f(vector<T> &v){ return v.size(); } template<typename T> class B{ public: int size(){ return v.size(); }; private: vector<T> v; }; int main(int argc, char** argv) { B<string> b; vector<string> v; for(int i=0; i<f<string>(v)-1; i++) std::cout << "using fn template" << endl; for(int i=0; i<b.size()-1; i++) std::cout << "using class B" << endl; for(int i=0; i<v.size()-1; i++) std::cout << "done" << endl; //Why is this printing??? return (EXIT_SUCCESS); }
vector's size() function returns a value of type size_t which is unsigned. So, if size() returns 0 and you subtract 1 from it, you're going to get a very large number rather than -1. That very large number will be greater than 0 and the condition i < v.size() - 1 will therefore be be true since i is 0. EDIT: I should probably add that normally when iterating over an array or a vector, you iterate as long as your index is less than the size of the array or vector rather than size - 1. for(int i = 0; i < v.size(); ++i) std::cout << "done" << endl; would likely be what you really want to do. Even if you used (int)v.size() - 1 to get rid of the signed vs unsigned issue, the loop would stil be wrong because you'd miss the last element in cases where you actually had elements in the vector.
3,151,495
3,151,574
Why doesn't auto_ptr<T> have operator!() defined?
The Title pretty much sums up my question. Why can't the following be done to check for a null pointer? auto_ptr<char> p( some_expression ); // ... if ( !p ) // error This must be done instead: if ( !p.get() ) // OK Why doesn't auto_ptr<T> simply have operator!() defined?
Seems to be there was an error in its design. This will be fixed in C++0x. unique_ptr (replacement for auto_ptr) contains explicit operator bool() const; Quote from new C++ Standard: The class template auto_ptr is deprecated. [Note: The class template unique_ptr (20.9.10) provides a better solution. —end note ] Some clarification: Q: What's wrong with a.get() == 0? A: Nothing is wrong with a.get()==0, but smart pointers lets you work with them as they were real pointers. Additional operator bool() gives you such a choice. I think, that the real reason for making auto_ptr deprecated is that is has has not intuitive design. But operator bool for unique_ptr in the new Standard means that there are no reasons not to have it.
3,151,649
3,151,787
Processing command line argument
I've been working with OpenCV, and some of the example code I've seen uses the following to read in a filename. I understand that argc is the number of command line arguments that were passes, and argv is a vector of argument strings, but can someone clarify what each part of the following line does? I've tried searching this but haven't found many results. Thanks. const char* imagename = argc > 1 ? argv[1] : "lena.jpg"; Thanks.
The example shows the use of the ternary operator. const char* imagename = argc > 1 : argv[1] : "lana.jpg" By ternary you can say that this expression has three members. First member is a condition expression Second member is the value that could be assigned to imagename if conditional expression is true. Third member is the value that could be assigned to imagename if conditional expression is false. This example can be translated to: const char* imagename; if(argc > 1) imagename = argv[1]; else imagename = "lana.jpg";
3,151,728
3,205,136
Unresolved external symbols in compiling 32 bit application in Windows 64
So I am trying to compile legacy app from 32 bit to 64 bit.. I re-compiled all of the libs it used and made it look into WIN SDK6.0A x64 bit for libs.. I am using: Visual Studio Professional Edition 2008 Visual C++ dotNet Framework 3.5 SP1 Windows Server 2008R2 Windows SDK is 6.0A Everythings finally coming up but I am getting these weird undefined symbol errors: error LNK2019: unresolved external symbol InterlockedDecrement referenced in function ... error LNK2019: unresolved external symbol InterlockedIncrement referenced in function ... error LNK2019: unresolved external symbol GetModuleBaseName referenced in ... error LNK2019: unresolved external symbol EnumProcessModules referenced in ... error LNK2019: unresolved external symbol EnumProcesses referenced in ... error LNK2019: unresolved external symbol GetProcessMemoryInfo referenced The problem is these are all win stuff from SDK. InterlockedDec and InterlockedInc are coming from kernel32.lib GetModuleBaseName, EnumProcessModules, EnumProcesses,GetProcessMemoryInfo are in psapi.h but also kernel32.lib or psapi.lib I checked C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib\x64 and both libs kernel32.lib and psapi.lib are there. It definitely looks up the libs at right spot. I turned on /VERBOSE:LIB and it points to the correct folder. So I am really confused why isnt it finding them. Any ideas??? Thanks
So I finally figured it out, kinda... It wasnt finding psapi.lib In Project->Linker->Additional dependencies instead of just saying psapi.lib I gave full path to it and it worked... not really sure why it failed to find it before but oh well...
3,151,729
3,152,802
boost program_options multiple values problem
So I'm working off one of the examples for Boost program_options library, and I wanted to try setting a default value for one of the multiple-values/ vector-values, but it doesn't seem to work. As I think is suggested here to work. What I've modified is on about line 40: po::options_description config("Configuration"); config.add_options() ("optimization", po::value<int>(&opt)->default_value(10), "optimization level") ("include-path,I", o::value< vector<string> >()->default_value(vector<string>(),"SOMETHING")->composing(), "include path") ; When I compile this small change, I expect that when no -I option is passed that the "SOMETHING" is added to the include-path argument list. Does anyone have any idea why this is not the case? Here is the complete source code: #include <boost/program_options.hpp> namespace po = boost::program_options; #include <iostream> #include <fstream> #include <iterator> using namespace std; // A helper function to simplify the main part. template<class T> ostream& operator<<(ostream& os, const vector<T>& v) { copy(v.begin(), v.end(), ostream_iterator<T>(cout, " ")); return os; } int main(int ac, char* av[]) { try { int opt; // Declare a group of options that will be // allowed only on command line po::options_description generic("Generic options"); generic.add_options() ("version,v", "print version string") ("help", "produce help message") ; // Declare a group of options that will be // allowed both on command line and in // config file po::options_description config("Configuration"); config.add_options() ("optimization", po::value<int>(&opt)->default_value(10), "optimization level") ("include-path,I", po::value< vector<string> >()->default_value(vector<string>(),"SOMETHING")->composing(), "include path") ; // Hidden options, will be allowed both on command line and // in config file, but will not be shown to the user. po::options_description hidden("Hidden options"); hidden.add_options() ("input-file", po::value< vector<string> >(), "input file") ; po::options_description cmdline_options; cmdline_options.add(generic).add(config).add(hidden); po::options_description config_file_options; config_file_options.add(config).add(hidden); po::options_description visible("Allowed options"); visible.add(generic).add(config); po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; store(po::command_line_parser(ac, av). options(cmdline_options).positional(p).run(), vm); ifstream ifs("multiple_sources.cfg"); store(parse_config_file(ifs, config_file_options), vm); notify(vm); if (vm.count("help")) { cout << visible << "\n"; return 0; } if (vm.count("version")) { cout << "Multiple sources example, version 1.0\n"; return 0; } if (vm.count("include-path")) { cout << "Include paths are: " << vm["include-path"].as< vector<string> >() << "\n"; } if (vm.count("input-file")) { cout << "Input files are: " << vm["input-file"].as< vector<string> >() << "\n"; } cout << "Optimization level is " << opt << "\n"; } catch(exception& e) { cout << e.what() << "\n"; return 1; } return 0; }
For the "default_value" method, the first parameter is the real value that you wish your option to be, the second value being only the textual representation (for display in --help) when boost cannot infer it. So, the solution to your problem is to write: po::value< vector<string> >()->default_value( vector<string>(1, "SOMETHING"), "SOMETHING")->composing(), This way, you are saying that the default value is a vector with a single element "SOMETHING", and that you want to display "SOMETHING" in the help, such as: Configuration: --optimization arg (=10) optimization level -I [ --include-path ] arg (=SOMETHING) include path
3,151,790
3,151,825
Why isn't the dropdown arrow drawn for an CMFCMenuButton?
I ran into this issue when trying to add a CMFCMenuButton to an existing MFC application. It worked properly, and even resized the button to accommodate the dropdown arrow. But it didn't draw the dropdown arrow, and when I hovered over the button, I saw the following debug output: > Can't load bitmap: 42b8.GetLastError() = 716 > CMenuImages. Can't load menu images 3f01 It turns out that even with Visual Studio 2010 RTM, when you create a brand new MFC Dialog based application, the CMFCMenuButton doesn't draw the arrow and shows the same errors. Initially I assumed that I didn't have something installed or registered correctly. However, the NewControls example from the MFC Feature Pack showed the dropdown arrow perfectly. What is missing?
The reason I posted this question is because I couldn't find any answers via Google. The closest I came when researching it was a couple hacks that didn't seem to be the real solution. After pouring over the NewControls example, I finally found the culprit. At the bottom of the default .rc file for a project, there is the following code: #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE 9, 1 #include "res\YOUR_PROJECT_NAME.rc2" // non-Microsoft Visual C++ edited resources #include "afxres.rc" // Standard components #endif The NewControls example's .rc file looks like this: #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE 9, 1 #include "res\NewControls.rc2" // non-Microsoft Visual C++ edited resources #include "afxres.rc" // Standard components #ifndef _AFXDLL #include "afxribbon.rc" // Ribbon and control bars #endif #endif Adding the afxribbon.rc enables the bitmap resources needed for the controls in the MFC Feature pack update. Now you can't just simply add the missing code to the bottom of the .rc file. If you do that, every time you edit the resource file using the visual designer, your added code will be removed. The solution to the problem is to add this to the bottom of the YOUR_PROJECT_NAME.rc2 file: #ifndef _AFXDLL #include "afxribbon.rc" // Ribbon and control bars #endif Make sure you have an empty line at the bottom of the file, or the resource compiler will complain. I'm not sure what setting needs to be adjusted in order for the visual designer to automatically include afxribbon.rc like it does in the NewControls example project. But adding it to the .rc2 seems to fix the problem. Update Keep in mind that you can use the IDE to modify your RC file: Right-Click the RC file and select Resource Includes...: Paste the new code into the Compile-time directives area:
3,151,801
3,151,824
Compare 2 elements of two arrays in C++
I have two arrays each array has some values for instance: int a[] = {1, 2, 3, 4}; int b[] = {0, 1, 5, 6}; now I need to compare the elements of the array (a) with elements in array (b).. if is there any match the program should return an error or print "error there is a duplicate value" etc.. in the above situation, it should return an error coz a[0] = b[1] because both are have same values. How can I do this??
If the arrays are this small, I would just do a brute force approach, and loop through both arrays: for (int i=0;i<4;++i) { for (int j=0;j<4;++j) { if (a[i] == b[j]) { // Return an error, or print "error there is a duplicate value" etc } } } If you're going to be dealing with large arrays, you may want to consider a better algorithm, however, as this is O(n^2). If, for example, one of your arrays is sorted, you could check for matches much more quickly, especially as the length of the array(s) gets larger. I wouldn't bother with anything more elaborate, though, if your arrays are always going to always be a few elements in length.
3,151,851
3,151,897
C++ template instantiation restrictions
I have a method foo in class C which either calls foo_1 or foo_2. This method foo() has to be defined in C because foo() is pure virtual in BaseClass and I actually have to make objects of type C. Code below: template <class T> class C:public BaseClass{ void foo() { if (something()) foo_1; else foo_2; } void foo_1() { .... } void foo_2() { .... T t; t.bar(); // requires class T to provide a method bar() .... } }; Now for most types T foo_1 will suffice but for some types foo_2 will be called (depending on something()). However the compiler insists on instantiating both foo_1 and foo_2 because either may be called. This places a burden on T that it has to provide a bar method. How do I tell the compiler the following: if T does not have bar(), still allow it as an instantiating type?
you could use boost.enable_if. something like this: #include <boost/utility/enable_if.hpp> #include <iostream> struct T1 { static const bool has_bar = true; void bar() { std::cout << "bar" << std::endl; } }; struct T2 { static const bool has_bar = false; }; struct BaseClass {}; template <class T> class C: public BaseClass { public: void foo() { do_foo<T>(); } void foo_1() { // .... } template <class U> void foo_2(typename boost::enable_if_c<U::has_bar>::type* = 0) { // .... T t; t.bar(); // requires class T to provide a method bar() // .... } private: bool something() const { return false; } template <class U> void do_foo(typename boost::enable_if_c<U::has_bar>::type* = 0) { if (something()) foo_1(); else foo_2<U>(); } template <class U> void do_foo(typename boost::disable_if_c<U::has_bar>::type* = 0) { if (something()) foo_1(); // I dunno what you want to happen if there is no T::bar() } }; int main() { C<T1> c; c.foo(); }
3,151,963
3,152,140
Static check const char* contains spaces
Is there a way to check (assert) at compile time wether a const char* contains spaces or not? Something like: const char* cstr1 = "ok"; const char* cstr2 = "very bad"; check( cstr1 ); //OK check( cstr2 ); //Fail to compile The type is the same, but it may be possible to define some tricky template metaprogramming tecnique to do it. Point is, all the info required is fixed at compile time. This problem should be related to the "From const char variable to type" problem, which I think can be solved by compile-time hashing via metaprogramming tecniques. Thank you in advance for your help.
You can't use ordinary strings since their characters cannot be accessed by templates, but you can use MPL strings: #include <boost/mpl/char.hpp> #include <boost/mpl/string.hpp> #include <boost/mpl/contains.hpp> #include <boost/utility/enable_if.hpp> typedef boost::mpl::char_<' '> space; typedef boost::mpl::string<'o', 'k'> cstr1; typedef boost::mpl::string<'v', 'e', 'r', 'y', ' ', 'b', 'a', 'd'> cstr2; boost::disable_if< boost::mpl::contains<cstr1, space> >::type check(); // boost::disable_if< boost::mpl::contains<cstr2, space> >::type check(); The second line fails to compile.
3,152,035
3,152,202
Why are heaps in c++ implemented as algorithms instead of containers?
I was wondering why the heap concept is implemented as algorithms (make_heap, pop_heap, push_heap, sort_heap) instead of a container. I am especially interested is some one's solution can also explain why set and map are containers instead of similar collections of algorithms (make_set add_set rm_set etc).
STL does provide a heap in the form of a std::priority_queue. The make_heap, etc., functions are there because they have uses outside the realm of the data structure itself (e.g. sorting), and to allow heaps to be built on top of custom structures (like stack arrays for a "keep the top 10" container). By analogy, you can use a std::set to store a sorted list, or you can use std::sort on a vector with std::adjacent_find; std::sort is the more general-purpose and makes few assumptions about the underlying data structure. (As a note, the std::priority_queue implementation does not actually provide for its own storage; by default it creates a std::vector as its backing store.)
3,152,241
3,152,296
Case insensitive std::string.find()
I am using std::string's find() method to test if a string is a substring of another. Now I need case insensitive version of the same thing. For string comparison I can always turn to stricmp() but there doesn't seem to be a stristr(). I have found various answers and most suggest using Boost which is not an option in my case. Additionally, I need to support std::wstring/wchar_t. Any ideas?
You could use std::search with a custom predicate. #include <locale> #include <iostream> #include <algorithm> using namespace std; // templated version of my_equal so it could work with both char and wchar_t template<typename charT> struct my_equal { my_equal( const std::locale& loc ) : loc_(loc) {} bool operator()(charT ch1, charT ch2) { return std::toupper(ch1, loc_) == std::toupper(ch2, loc_); } private: const std::locale& loc_; }; // find substring (case insensitive) template<typename T> int ci_find_substr( const T& str1, const T& str2, const std::locale& loc = std::locale() ) { typename T::const_iterator it = std::search( str1.begin(), str1.end(), str2.begin(), str2.end(), my_equal<typename T::value_type>(loc) ); if ( it != str1.end() ) return it - str1.begin(); else return -1; // not found } int main(int arc, char *argv[]) { // string test std::string str1 = "FIRST HELLO"; std::string str2 = "hello"; int f1 = ci_find_substr( str1, str2 ); // wstring test std::wstring wstr1 = L"ОПЯТЬ ПРИВЕТ"; std::wstring wstr2 = L"привет"; int f2 = ci_find_substr( wstr1, wstr2 ); return 0; }
3,152,265
3,152,425
Why isn't this thread reading all data from the pipe consistently?
Anything wrong with this in general? CallingFunction() { CreatePipe() CreateMutex() CreateThread( ThreadFunction ) while(there is data left to send) { WriteFile(send data in 256 byte chunks) } WaitForSingleobject() //don't return until ReadThread is done return 0; } ThreadFunction() { WaitForSinglObject() while(bytesRead != totalBytestoReadFileSize) { ReadfromPipe(in chunks) update bytesRead++ } ReleaseMutex() return 0; } Before the calling function ends - FileSize: 232016 BytesWrittenToPipe: 232016 BytesReadFromPipe: 231946 or 232012 or 231840 -> Why not consistent?
Expecting us to debug such an issue from pseudo code is not realistic. Use FlushFileBuffers to ensure all data in the pipe is written.
3,152,326
3,250,880
Google Test: Parameterized tests which use an existing test fixture class?
I have a test fixture class which is currently used by many tests. #include <gtest/gtest.h> class MyFixtureTest : public ::testing::Test { void SetUp() { ... } }; I would like to create a parameterized test which also uses all that MyFixtureTest has to offer, without needing to change all my existing tests. How do I do that? I have found similar discussions on the web, but have not fully understood their answers.
The problem is that for regular tests your fixture has to be derived from testing::Test and for parameterized tests, it has to be derived from testing::TestWithParam<>. In order to accommodate that, you'll have to modify your fixture class in order to work with your parameter type template <class T> class MyFixtureBase : public T { void SetUp() { ... }; // Put the rest of your original MyFixtureTest here. }; // This will work with your non-parameterized tests. class MyFixtureTest : public MyFixtureBase<testing::Test> {}; // This will be the fixture for all your parameterized tests. // Just substitute the actual type of your parameters for MyParameterType. class MyParamFixtureTest : public MyFixtureBase< testing::TestWithParam<MyParameterType> > {}; This way you can keep all your existing tests intact while creating parameterized tests using TEST_P(MyParamFixtureTest, MyTestName) { ... }
3,152,330
3,152,342
Ambiguous pow() function
I am trying to make a simple call to the pow() function from math.h someihing similar to.. #include<math.h> int main() { float v,w; w=3.0; v=pow(w,0.5);//i think this is 'float pow(float,float)' return 0; } but visual studio says it's an error 1>c:\users\user\documents\visual studio 2008\projects\deo\deo\main.cpp(7) : error C2666: 'pow' : 6 overloads have similar conversions 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(575): could be 'long double pow(long double,int)' 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(573): or 'long double pow(long double,long double)' 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(527): or 'float pow(float,int)' 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(525): or 'float pow(float,float)' 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(489): or 'double pow(double,int)' 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(123): or 'double pow(double,double)' 1> while trying to match the argument list '(float, double)' I thought I had the format float pow(float, float).
In the line: v=pow(w,0.5); w is a float and 0.5 is a double. You can use 0.5f instead.
3,152,372
3,158,286
Boost : Error : 2 overloads have similar conversions
I'm basically brand new to using Boost. I'm trying to use a ptr_vector to handle some objects that I created. Specifically I have defined a class Location which defines a particular node on a map (simple 2D game layout). I defined a ptr_vector to hold a set of Locations that have value to the calling function (nodes with units on them). In code : boost::ptr_vector<Location> find_targets(int b_hash) { boost::ptr_vector<Location> targets; //find a node with variables row and col defining its position targets.push_back(new Location(row,col)); //find and push more targets return targets; } When I attempt to compile this, even without calling that function, I get the following error : error C2666: 'boost::scoped_array::operator []' : 2 overloads have similar conversions boost\ptr_container\detail\scoped_deleter.hpp 81 Anyone have any ideas? I couldn't find any relevant help online, but I'll keep looking in the mean-time. EDIT : More details I'm using Boost 1.43.0 on Visual Studio 2005. This is the simplest test I could make that would give this error. #include "Location.h" #include <boost\ptr_container\ptr_vector.hpp> boost::ptr_vector<Location> find_targets() { boost::ptr_vector<Location> targets; targets.push_back(new Location(1,1)); targets.push_back(new Location(2,1)); return targets; } int main(int argc, char **argv) { boost::ptr_vector<Location> t = find_targets(); } And the Location class class Location { // variables // private : int _row; int _col; public : // functions // private : public : Location() {_row = 0;_col = 0;} Location(int r, int c) { _row = r; _col = c;} ~Location(){}; int get_row() {return _row;} int get_col() {return _col;} }; The error occurs with any ptr_vector for any type T that I use. It only happens when I attempt to return a ptr_vector. It works if I return a ptr_vector*, so I'm experimenting with a wrapper class to see if that solves the issue.
That's not reproducible when using Boost 1.43 and VC2005. In order to try it out I added a dummy class Location (you didn't provide it with your code): struct Location { Location(int, int) {} }; That makes me believe it's an issue with your class Location. Could you provide its definition?
3,152,567
3,152,602
In C++ how can you create class instance w call to either a struct or nothing?
I'm creating a Class. This class stores user preferences in a Struct. When creating an instance of the class, I want the client to have the option of creating an instance with no preferences passed in or with a preferences struct passed in. I can do this with pointers, but I wanted to know how I could do it by passing the preferences struct into the class by reference. Either way, once the class receives the preferences it makes a copy for its own use. Here's what it looks like with pointers struct preferences {}; class Useful { public: Useful(preferences const * = NULL); ... } ... int main() { preferences * testPrefs; ... Useful testClass(testPrefs); // or if no prefs: Useful testClass; ... } So how would you pass the preferences struct in by reference when creating an instance of the class with a default value of no struct passed in? This is the line I'm stuck on, since neither NULL nor *NULL will work: class Useful { public: Useful(preferences & = ???????);
You point out the advantage of pointers over references, and how well pointers fit your situation, then announce you don't want to use them. You can still get what you want. Write two overloads for your constructor. One takes a reference, the other takes no parameters and does what the other constructor did when it got a null pointer.
3,152,577
3,152,864
A form that writes to excel
I was wondering what the easiest way to write a simple form program or web page that will output to a text file that can be opened in excel easily. I know how to write in C++ but I dont know any GUI and I wanted a simple form. I was thinking I could just write an HTML/PHP page but it has to be able to run without the internet, but I dont know if you can have a web page append to a file in a folder. Can anyone point me into a direction to do this?
If you want a Windows based application, and you can code in C++, then possibly the simplest route is to get hold of Visual Studio (you can get the Express versions for free), and write something using your language of choice. Basic GUI stuff in Visual Studio is simple enough. You can then write your output either to a delimited text file (like a CSV), or use the Excel Object Model if you want to create an actual Excel spreadsheet - although that might be overkill if the data are simple. You might find this question useful too (it's about Word documents, but some of the concepts and pitfalls are the same): Programmatically generating editable Word docs from ASP.NET? Installing PHP and creating an HTML page is perfectly possible, but it seems like a lot of effort. You should search Stackoverflow for PHP Excel, as you may find some other useful stuff here. In what environment will the form/application be run?
3,152,664
3,152,705
C++ cast to array of a smaller size
Here's an interesting question about the various quirks of the C++ language. I have a pair of functions, which are supposed to fill an array of points with the corners of a rectangle. There are two overloads for it: one takes a Point[5], the other takes a Point[4]. The 5-point version refers to a closed polygon, whereas the 4-point version is when you just want the 4 corners, period. Obviously there's some duplication of work here, so I'd like to be able to use the 4-point version to populate the first 4 points of the 5-point version, so I'm not duplicating that code. (Not that it's much to duplicate, but I have terrible allergic reactions whenever I copy and paste code, and I'd like to avoid that.) The thing is, C++ doesn't seem to care for the idea of converting a T[m] to a T[n] where n < m. static_cast seems to think the types are incompatible for some reason. reinterpret_cast handles it fine, of course, but is a dangerous animal that, as a general rule, is better to avoid if at all possible. So my question is: is there a type-safe way of casting an array of one size to an array of a smaller size where the array type is the same? [Edit] Code, yes. I should have mentioned that the parameter is actually a reference to an array, not simply a pointer, so the compiler is aware of the type difference. void RectToPointArray(const degRect& rect, degPoint(&points)[4]) { points[0].lat = rect.nw.lat; points[0].lon = rect.nw.lon; points[1].lat = rect.nw.lat; points[1].lon = rect.se.lon; points[2].lat = rect.se.lat; points[2].lon = rect.se.lon; points[3].lat = rect.se.lat; points[3].lon = rect.nw.lon; } void RectToPointArray(const degRect& rect, degPoint(&points)[5]) { // I would like to use a more type-safe check here if possible: RectToPointArray(rect, reinterpret_cast<degPoint(&)[4]> (points)); points[4].lat = rect.nw.lat; points[4].lon = rect.nw.lon; } [Edit2] The point of passing an array-by-reference is so that we can be at least vaguely sure that the caller is passing in a correct "out parameter".
I don't think it's a good idea to do this by overloading. The name of the function doesn't tell the caller whether it's going to fill an open array or not. And what if the caller has only a pointer and wants to fill coordinates (let's say he wants to fill multiple rectangles to be part of a bigger array at different offsets)? I would do this by two functions, and let them take pointers. The size isn't part of the pointer's type void fillOpenRect(degRect const& rect, degPoint *p) { ... } void fillClosedRect(degRect const& rect, degPoint *p) { fillOpenRect(rect, p); p[4] = p[0]; } I don't see what's wrong with this. Your reinterpret-cast should work fine in practice (i don't see what could go wrong - both alignment and representation will be correct, so the merely formal undefinedness won't carry out to reality here, i think), but as i said above i think there's no good reason to make these functions take the arrays by reference. If you want to do it generically, you can write it by output iterators template<typename OutputIterator> OutputIterator fillOpenRect(degRect const& rect, OutputIterator out) { typedef typename iterator_traits<OutputIterator>::value_type value_type; value_type pt[] = { { rect.nw.lat, rect.nw.lon }, { rect.nw.lat, rect.se.lon }, { rect.se.lat, rect.se.lon }, { rect.se.lat, rect.nw.lon } }; for(int i = 0; i < 4; i++) *out++ = pt[i]; return out; } template<typename OutputIterator> OutputIterator fillClosedRect(degRect const& rect, OutputIterator out) { typedef typename iterator_traits<OutputIterator>::value_type value_type; out = fillOpenRect(rect, out); value_type p1 = { rect.nw.lat, rect.nw.lon }; *out++ = p1; return out; } You can then use it with vectors and also with arrays, whatever you prefer most. std::vector<degPoint> points; fillClosedRect(someRect, std::back_inserter(points)); degPoint points[5]; fillClosedRect(someRect, points); If you want to write safer code, you can use the vector way with back-inserters, and if you work with lower level code, you can use a pointer as output iterator.
3,152,734
3,153,041
Problem either adding to or traversing a linked list
I have a problem either adding to or traversing a linked list. The main item class is used by another class but I can add the correct number of these but it looks like when I add more data to the list the app no longer works. I am not sure exactly where the error is. I know that when I try to traverse the list the application crashes. Any ideas or any improvements would be appreciated. I can make the crash not happen by changing the AddOccurence method to not do the while loop. Do void Item::AddOccurence(int Item,int placeInLine){ ItemOccurence* ocr=myHead; if(ocr) { } instead of void Item::AddOccurence(int Item,int placeInLine){ ItemOccurence* ocr=myHead; while(ocr) { } Basically hitting the first node but no more. I have an object that contains a list. Here is the .h file #include using namespace std; class ItemOccurence{ public: ItemOccurence(int line,int placeInLine,ItemOccurence* link=NULL) :myLine(line),myPlaceInLine(placeInLine),myLink(link){} int myLine; int myPlaceInLine; ItemOccurence* myLink; }; class Item { public: Item(); Item(string Item,int line,int placeInLine); virtual ~Item(); void deallocate(ItemOccurence* p); void AddOccurence(int Item,int placeInLine); string myItem; ItemOccurence* myHead; private: bool isEmpty(); }; And the .cpp file #include "Item.h" #include <string> #include<iostream> using namespace std; Item::Item(string Item,int line,int placeInLine):myHead(NULL){ myItem=Item; myHead= new ItemOccurence(line,placeInLine,NULL); } Item::Item():myHead(NULL){ myHead=0; } Item::~Item() { deallocate(myHead); myHead=0; } void Item::deallocate(ItemOccurence* p){ ItemOccurence* tmp; while(p){ tmp=p; p=p->myLink; delete tmp; } } void Item::AddOccurence(int Item,int placeInLine){ ItemOccurence* ocr=myHead; while(ocr) { cout<<"orrucence head while adding " << myHead->myLine << " " << myHead->myPlaceInLine <<"\n"; ocr=ocr->myLink; } myHead = new ItemOccurence(Item,placeInLine,myHead); return; } bool Item::isEmpty(){ if(myHead) return false; else return true; } EDIT: I updated AddOccurence to be. void Item::AddOccurence(int line,int placeInLine){ ItemOccurence* prev = myHead; ItemOccurence* curr = myHead->myLink; while(curr){ prev=curr; curr=curr->myLink; } // insert new ItemOccurence cout<<"adding " <<line<< " and " << placeInLine <<"\n"; prev->myLink = new ItemOccurence(line,placeInLine); return; } But I am still crashing. I am trying to debug but not sure what to look for.
It's very hard to tell what your code is trying to do. Unfortunately, the hard truth is, it's pretty far away from "working". Here's a few hints: Reconsider your classes. What is Item and ItemOccurrence? A linked list is a list. It has items. You should probably name it List and Item. If you want, you can do this in a single class representing Item (the List is only a special case of the front Item). Each Item needs a string (the node data) and a next (the pointer to the next node). If you use List, it will need to have a pointer to head (the first Item). You don't need to store placeInLine. placeInLine should only be used when searching for the place to insert a new Item. It's unclear what ItemOccurrence::myLine is supposed to represent. When you initialize myHead(NULL), you don't need to set it to 0. isEmpty() is not usually a private method. The algorithm for adding a node is: Loop until you find the place before it needs to be inserted. It looks like you need to check for two things: "end of list" and "placeInLine" Set new_node->next = current->next->next node. Set current->next = new_node node. Be aware of the special case where current->next is NULL. Instead of if (x) return true; else return false;, it's common to return x;
3,152,927
3,152,959
What's the most interesting wrong view people have on the difference between structure and class in C++?
What's the most interesting wrong view people have on the difference between structure and class in C++?
For those who are interested in what the actual difference is, the default access specified for structs is public, and for classes it is private. There is no other difference. See this related answer. Member of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default. In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class. I can imagine a lot of people thinking that there will be a performance difference but there is not.
3,153,001
3,153,100
question about std::vector::end()
I recently finished fixing a bug in the following function, and the answer surprised me. I have the following function (written as it was before I found the bug): void Level::getItemsAt(vector<item::Item>& vect, const Point& pt) { vector<itemPtr>::iterator it; // itemPtr is a typedef for a std::tr1::shared_ptr<item::Item> for(it=items.begin(); it!=items.end(); ++it) { if((*it)->getPosition() == pt) { item::Item item(**it); items.erase(it); vect.push_back(item); } } } This function finds all Item objects in the 'items' vector that has a certain position, removes them from 'items', and puts them in 'vect'. Later, a function named putItemsAt does the opposite, and adds items to 'items'. The first time through, getItemsAt works fine. After putItemsAt is called, though, the for loop in getItemsAt will run off the end of 'items'. 'it' will point at an invalid Item pointer, and getPosition() segfaults. On a hunch, I changed it!=items.end() to it<items.end(), and it worked. Can anyone tell me why? Looking around SO suggests it might involve erase invalidating the iterator, but it still doesn't make sense why it would work the first time through. I'm also curious because I plan to change 'items' from a vector to a list, since list's erase is more efficient. I know I'd have to use != for a list, as it doesn't have a < operator. Would I run into the same problem using a list?
When you call erase(), that iterator becomes invalidated. Since that is your loop iterator, calling the '++' operator on it after invalidating it is undefined behavor. erase() returns a new valid iterator that points to the next item in the vector. You need to use that new iterator from that point onwards in your loop, ie: void Level::getItemsAt(vector<item::Item>& vect, const Point& pt) { vector<itemPtr>::iterator it = items.begin(); while( it != items.end() ) { if( (*it)->getPosition() == pt ) { item::Item item(**it); it = items.erase(it); vect.push_back(item); } else ++it; } }
3,153,012
3,153,044
String handling in C++
How do I write a function in C++ that takes a string s and an integer n as input and gives at output a string that has spaces placed every n characters in s? For example, if the input is s = "abcdefgh" and n = 3 then the output should be "abc def gh" EDIT: I could have used loops for this but I am looking for concise and an idiomatic C++ solution (i.e. the one that uses algorithms from STL). EDIT: Here's how I would I do it in Scala (which happens to be my primary language): def drofotize(s: String, n: Int) = s.grouped(n).toSeq.flatMap(_ + " ").mkString Is this level of conciseness possible with C++? Or do I have to use explicit loops after all?
Copy each character in a loop and when i>0 && i%(n+1)==0 add extra space in the destination string. As for Standard Library you could write your own std::back_inserter which will add extra spaces and then you could use it as follows: std::copy( str1.begin(), str1.end(), my_back_inserter(str2, n) ); but I could say that writing such a functor is just a wasting of your time. It is much simpler to write a function copy_with_spaces with an old good for-loop in it.
3,153,098
3,153,129
C++ control order of static member's deallocation
I have a C++ program with a reference-counting smart pointer class. This class works by mapping pointers to reference counts in a static map: map<ValueIntern*,unsigned int>& ValueRetainMapGetter(){ static map<ValueIntern*,unsigned int> m; return m; } The issue that I've been having is that some static variables which I have are being deallocated after the reference map has been deallocated. My question is: how can I control the order in which the static variables are deallocated so that the map is deallocated after all of the references.
I'd recommend using boost::shared_ptr (or std::tr1::shared_ptr if it's in your tool chain) instead of rolling your own.
3,153,114
3,153,183
How do I install and build against OpenSSL 1.0.0 on Ubuntu?
You can consider this a follow-up question to How do I install the OpenSSL C++ library on Ubuntu? I'm trying to build some code on Ubuntu 10.04 LTS that requires OpenSSL 1.0.0. Ubuntu 10.04 LTS comes with OpenSSL 0.9.8k: $ openssl version OpenSSL 0.9.8k 25 Mar 2009 So after running sudo apt-get install libssl-dev and building, running ldd confirms I've linked in 0.9.8: $ ldd foo ... libssl.so.0.9.8 => /lib/i686/cmov/libssl.so.0.9.8 (0x00110000) ... libcrypto.so.0.9.8 => /lib/i686/cmov/libcrypto.so.0.9.8 (0x002b0000) ... How do I install OpenSSL 1.0.0 and the 1.0.0 development package? Update: I'm writing this update after reading SB's answer (but before trying it), because it's clear I need to explain that the obvious solution of downloading and installing OpenSSL 1.0.0 doesn't work: After successfully doing the following (recommended in the INSTALL file): $ ./config $ make $ make test $ make install ...I still get: OpenSSL 0.9.8k 25 Mar 2009 ...and: $ sudo apt-get install libssl-dev Reading package lists... Done Building dependency tree Reading state information... Done libssl-dev is already the newest version. The following packages were automatically installed and are no longer required: linux-headers-2.6.32-21 linux-headers-2.6.32-21-generic Use 'apt-get autoremove' to remove them. 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. ...and (just to make sure) after rebuilding my code, ldd still returns the same thing. Update #2: I added the "-I/usr/local/ssl/include" and "-L/usr/local/ssl/lib" options (suggested by SB) to my makefile, but I'm now getting a bunch of undefine reference compile errors, for example: /home/dspitzer/foo/foo.cpp:86: undefined reference to `BIO_f_base64' /home/dspitzer/foo/foo.cpp:86: undefined reference to `BIO_new' /usr/local/ssl/include/ contains only an openssl directory (which contains numerous .h files), so I also tried "-I/usr/local/ssl/include/openssl" but got the same errors. Update #3: I tried changing the OpenSSL includes from (for example): #include <openssl/bio.h> ...to: #include "openssl/bio.h" ...in the .cpp source file but still get the same undefined reference errors. Update #4: I now realize those undefined reference errors are linker errors. If I remove the "-L/usr/local/ssl/lib" from my Makefile, I don't get the errors (but it links to OpenSSL 0.9.8). The contents of /usr/local/ssl/lib/ are: $ ls /usr/local/ssl/lib/ engines libcrypto.a libssl.a pkgconfig I added -lcrypto, and the errors went away.
Get the 1.0.0a source from here. # tar -xf openssl-1.0.0a.tar.gz # cd openssl-1.0.0a # ./config # sudo make install Note: if you have man pages build errors on modern systems, use make install_sw instead of make install. This puts it in /usr/local/ssl by default When you build, you need to tell gcc to look for the headers in /usr/local/ssl/include and link with libs in /usr/local/ssl/lib. You can specify this by doing something like: gcc test.c -o test -I/usr/local/ssl/include -L/usr/local/ssl/lib -lssl -lcrypto EDIT DO NOT overwrite any system libraries. It's best to keep new libs in /usr/local. Overwriting Ubuntu defaults can be hazardous to your health and break your system. Additionally, I was wrong about the paths as I just tried this in Ubuntu 10.04 VM. Fixed. Note, there is no need to change LD_LIBRARY_PATH since the openssl libs you link against by default are static libs (at least by default - there might be a way to configure them as dynamic libs in the ./config step) You may need to link against libcrypto because you are using some calls that are built and defined in the libcrypto package. Openssl 1.0.0 actually builds two libraries, libcrypto and libssl. EDIT 2 Added -lcrypto to gcc line.
3,153,141
3,153,309
Defining a byte in C++
In http://www.parashift.com/c++-faq-lite/intrinsic-types.html#faq-26.6, it is wriiten that "Another valid approach would be to define a "byte" as 9 bits, and simulate a char* by two words of memory: the first could point to the 36-bit word, the second could be a bit-offset within that word. In that case, the C++ compiler would need to add extra instructions when compiling code using char* pointers." I couldn't understand what it meant by "simulating char* by two words" and further quote. Could somebody please explain it by giving an example ?
I think this is what they were describing: The PDP-10 referenced in the second paragraph had 36-bit words and was unable to address anything inside of those words. The following text is a description of one way that this problem could have been solved while fitting within the restrictions of the C++ language spec (that are included in the first paragraph). Let's assume that you want to make 9-bit-long bytes (for some reason). By the spec, a char* must be able to address individual bytes. The PDP-10 can't do this, because it can't address anything smaller than a 36-bit word. One way around the PDP-10's limitations would be to simulate a char* using two words of memory. The first word would be a pointer to the 36-bit word containing the char (this is normally as precise as the PDP-10's pointers allow). The second word would indicate an offset (in bits) within that word. Now, the char* can access any byte in the system and complies with the C++ spec's limitations. ASCII-art visual aid: | Byte 1 | Byte 2 | Byte 3 | Byte 4 | Byte 5 | Byte 6 | Byte 7 | Byte 8 | ------------------------------------------------------------------------- | Word 1 | Word 2 | | (Address) | (Offset) | ------------------------------------------------------------------------- Say you had a char* with word1 = 0x0100 and word2 = 0x12. This would point to the 18th bit (the start of the third byte) of the 256th word of memory. If this technique was really used to generate a conforming C++ implementation on the PDP-10, then the C++ compiler would have to do some extra work with juggling the extra bits required by this rather funky internal format. The whole point of that article is to illustrate that a char isn't always 8 bits. It is at least 8 bits, but there is no defined maximum. The internal representation of data types is dependent on the platform architecture and may be different than what you expect.
3,153,155
3,155,944
When setting the WA_DeleteOnClose attribute on a Qt MainWindow, the program crashes when deleting the ui pointer
I have set the WA_DeleteOnClose widget attribute in a MainWindow. setAttribute(Qt::WA_DeleteOnClose); However, whenever I close that main window, I get a segfault in its destructor, which only has delete ui; In a nutshell, created a Qt4 GUI Application in Creator, added the setAttribute(Qt::WA_DeleteOnClose); to constructor, program now crashes on exit.
Are you getting a segfault in its destructor the first time, or the second time? Remember that your main window destructor should run only once. That is to say that it should run either because of a stack unwind, or because of WA_DeleteOnClose, not both. IIRC, Creator will put the main window on the stack of main(). Therefore, when main() returns the main window is destroyed.
3,153,169
3,153,197
C++: new, memory understanding question
why doesn't this work: Snippet 1: int *a = new int[6]; (*a)[0]=1; while this is working Snippet 2: int myint = 0; int *ptr = &myint; *ptr=1; I know that if i use a[0]=1 in snippet 1 it will work. But for me that makes no sense, cos for me it looks that a[0]=1 means: put value 1 to adress a[0]. In other words I put the value as the memory. Instead it makes more sense to use (*a)[0]=1 which means to me: put value 1 to the value field which a[0] points to. Could anyone describe this discrepance?
You should just be using *a not (*a)[0]. Remember 'a' is a pointer. A pointer is an address. *a = a[0] or the first integer *(a + 1) = a[1] or the second integer 'a' is not a pointer to an array. It is a pointer to an integer. So, *a does not hand an array back to you for the [ ] to operate on. What is confusing you is that the address of an integer array is also the address of the first integer in that array. Remember to always keep in mind the type of what you are assigning on the left hand side. Consider the following: int x = 10; This snippet declares an integer x and assigns it the value 10. Now consider this: int *y = &x; This snippet declares that y is a pointer to an integer and it assigns the address of x to y. You could write it this way: int x = 10; int *y; y = &x; By the way, when you assign something to 'y' above it will simply take the data at that address and turn it into an integer. So, if you send it a to an array of char (8 bits or 1 byte each) and an integer is 32 bits (4 bytes) long on your system then it will just take the first four characters of the char array and convert the resulting 32 bit number into an int. Tread carefully with pointers, there be dragons here.
3,153,385
3,160,259
Controlling the work of worker threads via the main thread
Hey I am not sure if this has already been asked that way. (I didn´t find anwsers to this specific questions, at least). But: I have a program, which - at startup - creates an Login-window in a new UI-Thread. In this window the user can enter data which has to be verified by an server. Because the window shall still be responsive to the users actions, it (ofc it´s only a UI-thread) shall not handle the transmission and evaluation in it´s own thread. I want the UI-thread to delegate this work back to the main thread. In addition: The main thread (My "client" thread) shall manage all actions that go on, like logging in, handle received messages from the server etc... (not window messages) But I am not sure of how to do this: 1.) Shall I let the UI-Thread Queue an APC to the main thread (but then the main thread does not know about the stuff going on. 2.) May I better use event objects to be waited on and queues to transmit the data from one thread to another?... Or are there way better options? For example: I start the client: 1. The client loads data from a file and does some intialization The client creates a window in a new thread which handles login data input from the user. The Window Thread shall notifiy and handle the , that has been entered by the user, over to the client. The Client shall now pack the data and delegate the sending work to another object (e.g. CSingleConnection) which handles sending the data over a network (of course this does not require a new thread, because it can be handle with Overlapped I/O... One special receiver thread receives the data from the server and handles it back to the client, which - in turn - evaluates the data. If the data was correct and some special stuff was received from the server, the main thread shall signal the UI thread to close the window and terminate... The client then creates a new window, which will handle the chatting-UI The chatting UI thread and the Client thread shall communicate to handle messages to be sent and received... (Hope this helps to get what I am trying)...
I don´t know wether this is good style or not (anwsering Your own question): But I think I go with Event Objects and two queues (one for the connection between Client and Connection, and one to communicate Client and UI)...
3,153,426
3,153,488
OpenGL pausing problems
I have the following function that is used as the glutKeyboardFunc function parameter: void handleKeypress(unsigned char key, //The key that was pressed int x, int y) { //The current mouse coordinates switch (key) { case 27: //Escape key exit(0); //Exit the program } if (key == 'a') { moveCircleLeft(0); } if (key == 'w') { moveCircleUp(0); } if (key == 's') { moveCircleDown(0); } if (key == 'd') { moveCircleRight(0); } } Now I will show you moveCircleLeft as an example of how the moveCircle functions are written: void moveCircleLeft(int x) { characterX = characterX - 0.1; glutPostRedisplay(); x++; if (x < 10) { glutTimerFunc(10, moveCircleLeft, x); } } The other moveCircle functions work similar and the only differences between the four functions is whether its plus of minus 0.1 or if it is characterY as opposed to characterX. Now, here is the problem: All the directions are moving in the right direction but, there is a delay/pause in movement of the character when I try to press keys. So, if I press just the d key (moveCircleRight) it moves right a little, stops a for a small amount of time, then moves across the screen in that direction at a constant speed with no pauses. Then if I change to a different key it pause for a little bit before changing directions then moves at a constant speed in that direction. Any suggestion around this would be appreciated!
Create a boolean variable for each key (preferably an array). Then use KeyDown/KeyUp instead of KeyPress (i believe in GLUT its something like KeyboardUpFunc and KeyboardFunc, but cant remember now). On KeyDown, set the appropriate variable to true, on KeyUp, set it to false. Now you probably have an Idle function or something like that. Call there your "move" functions based on the boolean variables. There should be no pauses now. Beware though that you might need to keep track of the time elapsed between frames and scale the distance moved appropriately.
3,153,548
3,153,588
C++: Struct initialization and maps
This works fine: #include <iostream> #include <map> using namespace std; struct Bar { int i; int f; }; int main() { map<int, Bar> m; Bar b; b.i = 1; b.f = 2; m[0] = b; } But if I want to make it a little more concise, I get errors: int main() { map<int, Bar> m; m[0] = {1, 2}; } Is there any way to make that struct initialization syntax work? Am I doing it wrong, or is it prohibited for maps?
You can add a constructor: In this situation I would say it is better than the fancy new initializer as it actually lets the maintainer see what type is being put in the map without having to go and look for it. struct Bar { Bar(int anI,int aJ) :i(anI), j(aJ) {} int i; int j; } ..... m[0] = Bar(1,2);
3,153,725
3,153,802
typedef struct : Default Initialization
typedef struct foo { bool my_bool; int my_int; } foo; In the example above I understand that my_bool will be initialized randomly to either true or false but what about my_int? I assumed that my_int would be default initialized to 0 but that seems not to be the case. Defining structs in this way appears to be incompatible with initialization lists so what is the best way to initialize my_bool and my_int to false and 0 respectively?
Types don't get "initialized". Only objects of some type get initialized. How and when they get initialized depends on how and where the corresponding object is defined. You provided no definition of any object in your question, so your question by itself doesn't really make much sense - it lacks necessary context. For example, if you define a static object of type foo static foo foo_object; // zeros it will be automatically zero-initialized because all objects with static duration are always automatically zero-initialized. If you define an automatic object of type foo without an initializer, it will remain uninitialized void func() { foo foo_object; // garbage } If you define an automatic object of type foo with an aggregate initializer, it will be initialized in accordance with that initializer void func() { foo foo_object1 = { 1, 2 }; // initialized foo foo_object2 = {}; // initialized with zeros } If you allocate your object with new and provide no initializer, it will remain uninitialized foo *p = new foo; // garbage in `*p` But if you use the () initializer, it will be zero-initialzed foo *p = new foo(); // zeros in `*p` If you create a temporary object of type foo using the foo() expression, the result of that expression will be zero-initialized bool b = foo().my_bool; // zero int i = foo().my_int; // zero So, once again, in your specific case the initialization details depend on now you create the object of your type, not on your type itself. Your type itself has no inherent initialization facilities and doesn't interfere with the initialization in any way.
3,153,939
3,154,143
Properly writing to a nonblocking socket in C++
I'm having a strange problem while attempting to transform a blocking socket server into a nonblocking one. Though the message was only received once when being sent with blocking sockets, using nonblocking sockets the message seems to be received an infinite number of times. Here is the code that was changed: return ::write(client, message, size); to // Nonblocking socket code int total_sent = 0, result = -1; while( total_sent < size ) { // Create a temporary set of flags for use with the select function fd_set working_set; memcpy(&working_set, &master_set, sizeof(master_set)); // Check if data is available for the socket - wait 1 second for timeout timeout.tv_sec = 1; timeout.tv_usec = 0; result = select(client + 1, NULL, &working_set, NULL, &timeout); // We are able to write - do so result = ::write(client, &message[total_sent], (size - total_sent)); if (result == -1) { std::cerr << "An error has occured while writing to the server." << std::endl; return result; } total_sent += result; } return 0; EDIT: The initialization of the master set looks like this: // Private member variables in header file fd_set master_set; int sock; ... // Creation of socket in class constructor sock = ::socket(PF_INET, socket_type, 0); // Makes the socket nonblocking fcntl(sock,F_GETFL,0); FD_ZERO(&master_set); FD_SET(sock, &master_set); ... // And then when accept is called on the socket result = ::accept(sock, NULL, NULL); if (result > 0) { // A connection was made with a client - change the master file // descriptor to note that FD_SET(result, &master_set); } I have confirmed that in both cases, the code is only being called once for the offending message. Also, the client side code hasn't changed at all - does anyone have any recommendations?
I do not believe that this code is really called only once in the "non blocking" version (quotes because it is not really non-blocking yet as Maister pointed out, look here), check again. If the blocking and non blocking versions are consistent, the non blocking version should return total_sent (or size). With return 0 instead caller is likely to believe nothing was sent. Which would cause infinite sending... is it not what's happening ? Also your "non blocking" code is quite strange. You seem to use select to make it blocking anyway... Ok, with a timeout of 1s, but why don't you make it really non blocking ? ie: remove all the select stuff and test for error case in write() with errno being EWOULDBLOCK. select or poll are for multiplexing. Also you should check errors for select and use FD_ISSET to check if socket is really ready. What if the 1 s timeout really happen ? Or if select is stopped by some interruption ? And if an error occurs in write, you should also write which error, that is much more useful than your generic message. But I guess this part of code is still far from finished. As far as I understand your code it should probably look somewhat like that (if the code is running in an unique thread or threaded, or forking when accepting a connection would change details): // Creation of socket in class constructor sock = ::socket(PF_INET, socket_type, 0); fcntl(sock, F_SETFL, O_NONBLOCK); // And then when accept is called on the socket result = ::accept(sock, NULL, NULL); if (result > 0) { // A connection was made with a client client = result; fcntl(client, F_SETFL, O_NONBLOCK); } // Nonblocking socket code result = ::write(client, &message[total_sent], (size - total_sent)); if (result == -1) { if (errno == EWOULDBLOCK){ return 0; } std::cerr << "An error has occured while writing to the server." << std::endl; return result; } return size;
3,154,095
3,154,178
Techniques to prevent overdraw (OpenGL)
I'm drawing lots of semi transparent polygons. My scene is 2D and uses 2f verticies. I can't use the depth buffer since it wont help because of alpha blending. What are some other techniques to reduce overdraw since this is what is crippling my application, not polygon counts since I use VBO's.
First off, how have you determined that overdraw is your problem? Without more information about what exactly you are drawing, it is quite hard to guess how to draw it faster. Speaking generally, the key to avoiding over draw is to avoid drawing anything that isn't required. So, if you have a 2D side scroller game with several layers of background image scrolling independently for parallax purposes -- sky, clouds, mountains, forest far, and forest near -- you would want to avoid drawing the sky wherever any of the other layers is visible. So, if you know that the mountains are guaranteed to cover a certain part of the sky, change the shape of your sky poly to only draw in the areas where you expect the sky to be visible. Potentially, make a fairly high resolution grid for the sky which follows the shape of the mountains, if you still have a problem. Likewise, if the ground plane of the forest layers is guaranteed to cover a certain height span, then don't have the mountains being drawn in that area. OTOH, on modern video hardware, a few layers of overdraw in a 2D scene is usually not that big of a deal, so I'm still interested to know exactly how you determined this, and if there might be some sort of bias in your instrumentation and profiling which could be leading you astray.
3,154,170
3,154,256
Combine two constant strings (or arrays) into one constant string (or array) at compile time
In C# and Java, it's possible to create constant strings using one or more other constant strings. I'm trying to achieve the same result in C++ (actually, in C++0x, to be specific), but have no idea what syntax I would use to achieve it, if such a thing is possible in C++. Here's an example illustrating what I want to do: #include <stdio.h> const char array1[] = "Hello "; const char array2[] = "world!\n"; const char array3[] = array1 + array2; // C++ doesn't like it when I try this int main() { printf(array3); return 0; } Any pointers? (No pun intended.) EDIT: I need to be able to apply this to integer arrays as well - not just char arrays. However, in both cases, the to-be-combined arrays will be fixed-size and be compile-time constants.
In C++0x you can do the following: template<class Container> Container add(Container const & v1, Container const & v2){ Container retval; std::copy(v1.begin(),v1.end(),std::back_inserter(retval)); std::copy(v2.begin(),v2.end(),std::back_inserter(retval)); return retval; } const std::vector<int> v1 = {1,2,3}; const std::vector<int> v2 = {4,5,6}; const std::vector<int> v3 = add(v1,v2); I don't think there's any way to do this for STL containers in C++98 (the addition part for v3 you can do, but you can't use the initializer lists for v1 and v2 in C++98), and I don't think there's any way to do this for raw arrays in C++0x or C++98.
3,154,506
3,154,912
Best way to make a QToolBar of "checkable" QToolButtons where only one of the buttons can be checked at a time?
I'm looking to make a QToolBar with a few actions in it, each of which is "checkable" (that is, I call setCheckable(true) on each action after creating it, which leaves the button in the down state after clicking it). The only way I can think of "unchecking" the other buttons is to hook into each button's triggered signal and uncheck the other buttons when a given button is checked. Is there a better way?
Create a QActionGroup and let it be the parent of your actions. This QActionGroup will maintain the states of its children. QActionGroup *anActionGroup = new QActionGroup(yourParentWidget); QAction* action1 = new QAction("Action 1", anActionGroup); QAction* action2 = new QAction("Action 2", anActionGroup); QAction* actionN = new QAction("Action N", anActionGroup); action1->setCheckable(true); action2->setCheckable(true); actionN->setCheckable(true); // Add these action to the tool bar
3,154,620
3,154,707
How to find out DC's dimensions?
Let's say I have a handle to device context (naturally, in Windows environment): HDC hdc; How can I get the width and height of it?
A device context (DC) is a structure that defines a set of graphic objects and their associated attributes, and the graphic modes that affect output. By width and height I'm guessing you are referring to the bitmap painted ? If so then i guess you can try the following : BITMAP structBitmapHeader; memset( &structBitmapHeader, 0, sizeof(BITMAP) ); HGDIOBJ hBitmap = GetCurrentObject(hDC, OBJ_BITMAP); GetObject(hBitmap, sizeof(BITMAP), &structBitmapHeader); //structBitmapHeader.bmWidth //structBitmapHeader.bmHeight
3,154,636
3,155,449
Zooming into the mouse position with a translation?
To zoom into the mouse position I was using: glTranslatef(current.ScalePoint.x,current.ScalePoint.y,0); glScalef(current.ScaleFactor,current.ScaleFactor,current.ScaleFactor); glTranslatef(-current.ScalePoint.x,-current.ScalePoint.y,0); so basically I translate to the new origin (the mouse position) then scale by the current scale factor, then translate back. This kind of works generally well, but it can be a bit buggy. My issue is really that now I'v introduced a camera offset so I tried something like this: glTranslatef(controls.MainGlFrame.GetCameraX(), controls.MainGlFrame.GetCameraY(),0); glTranslatef(current.ScalePoint.x,current.ScalePoint.y,0); glScalef(current.ScaleFactor,current.ScaleFactor,current.ScaleFactor); glTranslatef(-current.ScalePoint.x,-current.ScalePoint.y,0); But this did not work as I intended. How could I properly do this knowing that: The matrix's origin is the top left corner (0,0) 1 unit == 1 pixel My scale factor My camera's position relative to how far it is from (0,0) (the origin) and the mouse position (screen to client). Thanks
It is more safe (and also for code reuse) to un-project the mouse coordinate point (from window coordinates to model coordinates) first even though you know how projection is done. You can use the following function: void unProject(int ix, int iy, int &ox, int &oy) { // First, ensure that your OpenGL context is the selected one GLint viewport[4]; GLdouble projection[16]; GLdouble modelview[16]; glGetIntegerv(GL_VIEWPORT, viewport); glGetDoublev(GL_PROJECTION_MATRIX, projection); glGetDoublev(GL_MODELVIEW_MATRIX, modelview); int xx = ix; int yy = viewport[3] - iy; GLdouble x, y, z; gluUnProject(xx, yy, 0 /*check*/, modelview, projection, viewport, &x, &y, &z); ox = (int) x; oy = (int) y; } The output then is the correct point on the model coordinates for your zooming
3,154,672
3,154,766
How to get parent node of element using tinyxml
Is there a way to get a parent node from a TiXmlElement? For example... TiXmlElement *parent = child->ParentElement( "someName" ); If you can't do this in tinyxml, are there any other xml parsers that allow this?
TinyXML's TiXmlElement is derived from TiXMLNode which contains a method called Parent().
3,154,730
3,154,886
How does char *blah = "hello" work?
When you make a string out of char pointers how does this work? char *name = "ben"; Is this 'hidden' pointer arithmetic?
There isn't any hidden pointer arithmetic, but I suspect you want a more detailed answer than that. If you have a function: void foo() { char * bar = "Hello World"; } There are actually two chunks of memory that come in to play: The first is where the 12 bytes are used to store "Hello World" (1 byte for each letter plus a NULL byte at the end). The compiler will put this in the Data segment. This memory (location and values) is set at compile time and cannot be modified at run time (if you try it will segfault). The second location is the pointer to the data, this is the bar variable. When your program calls foo(), it allocates enough stack space (4 bytes on 32 bit) to house this memory location and it gets initialized to the location of the actual data. This happens every time you fun foo(). Further more, if you execute a statement like this later in the function: bar = "Good bye"; You aren't changing the data "Hello World" to "Good bye". You actually just end up with a 3rd chunk of memory in the data segment with "Good bye" in it (still allocated at compile time), then the pointer (bar) gets set to that location when that line executes. Another method to create "strings" (character arrays) is: void foo() { char bar[] = "Hello World"; } This is not the same as the first (close, though). In this method, you still have two variables, except the actual data you're concerned about ("Hello World" + null byte) is allocated and initialized on the program stack. You can see the difference in the compiled assembly by running gcc -S test.c and then reading test.s. At some point you will want to look at C's string functions. They key thing to remember when using these functions is that they don't know how long your character arrays are at all, they figure that out based on where the first null character is (a sentinel value).
3,154,759
3,155,531
Getting the points from wglUseFontOutlines?
I'm making a vector application for Windows. Right now i'm using wglUseFontOutlines to generate display lists which wrks well, except I would like to be able to let the user remodel the font. I would also like to use VBO's instead of DL's for this. Does Microsoft provide a way to get the points for this, or atleast the outlines, I could then use my tesselator to do the rest. Thanks
You may use the Win32 API GetPath , it works really nice and it returns lines and bezier pieces.
3,155,021
3,155,035
Consistenty header file names between C++ libraries
In my project I use two libraries, v8 and boost. Boost uses the .hpp extension for its headers, while v8 uses the .h extension for its headers. In the end of day, my source code starts like that: #include "v8.h" #include "boost/filesystem.hpp" ... In other question I asked about this subject, the general answer was that it is okay, but I just should be consistent between names. This code compiles well, but, coding styles/standards - is it okay? Is there any solution for this problem (like changing all .hpp to .h automatically somehow?) Thanks. And sorry for those stupid questions.
Don't worry about the inconsistency, it doesn't matter. Too much time is often spent obsessing about such details, and everyone is guilty of it. Just be consistent with your own coding standards. You'll eventually use some 3rd party library or several that use different conventions than you. There's nothing you can do about it, and often 2 of those libraries you use will be conflicting with your standards and with each other. That's not only for include extensions, but also for naming convetions like function_that_does_something vs FunctionThatDoesSomthing .It's fine. I would definitely strongly advice against trying to change someone else's library to fit into your coding standard. I.e. for example renaming boost .hpp to .h. This is a bad idea and when you want to upgrade to newer versions of the library it will be a nightmare. Spend your time solving the problem you're solving in a more elegant way rather than worrying about details like this.
3,155,044
3,155,068
sorting strings in a file
I need a solution for sorting of unix pwd file using C++ based on the last name. The format of the file is username, password, uid, gid, name, homedir, shell. All are seperated by colon delimiters. The name field contains first name follwed by last name both seperated by space I am able to sort the values using map and i am posting my code. Can some one suggest me improvements that I can do to my code please. Also I am unable to see the sorted lines in my file. string line,item; fstream myfile("pwd.txt"); vector<string> lines; map<string,int> lastNames; map<string,int>::iterator it; if(myfile.is_open()) { char delim =':'; int count =0; while(!myfile.eof()) { count++; vector<string> tokens; getline(myfile,line); istringstream iss(line); lines.push_back(line); while(getline(iss,item,delim)) { tokens.push_back(item); } cout<<tokens.size()<<endl;; size_t i =tokens[4].find(" "); string temp = tokens[4].substr(i,(tokens[4].size()-i)); cout<<temp<<endl; lastNames.insert(pair<string,int>(temp,count)); tokens.clear(); } myfile.seekg(0,ios::beg); for(it=lastNames.begin();it!=lastNames.end();it++) { cout << (*it).first << " => " << (*it).second << endl; int value=lastNames[(*it).first ]; myfile<<lines[value-1]<<endl; cout<<lines[value-1]<<endl; cout<<value<<endl; } } Also I am having problem writing to the file I am unable to see the sorted results. my problem: Can someone please explain me why I am unable to see the written results in the file! Thanks & Regards, Mousey.
Since the format of the file is fixed username, password, uid, gid, first name(space)lastname, homedir, shell Maintain a std::map with key value as string (which will contain last name, and value as line number Start reading the file line by line, extract the last name (Split the line by "," and then split fifth extracted part on space). Store the name along with line number in map When complete file has been read, just output the line numbers as mentioned in map. (Map contains lat names in sorted order) For splitting a string Refer to Split a string in C++?
3,155,054
3,155,085
C++ User Input When Initializing Values
I'm a student in an introductory C++ course. For one of our past assignments we have had to create a simple program to add fractions. Each new lab is just an application of new skills learned to making the same program. Now I need to make one using objects from a class definition. After tooling with a multiplying example my professor gave us, I finally got the code to add fractions properly. #include <iostream> using namespace std; class Fraction { private: float numer; float denom; public: void Init(float n, float d); void Multi(Fraction *, Fraction *); void Print(); Fraction() { numer = 0.0; denom = 0.0; } void setNumer( float n ) { numer = n; } void setDenom( float d ) { denom = d; } float getNumer() { return numer; } float getDenom() { return denom; } }; main() { Fraction x; Fraction y; Fraction f; x.Init( 1.0, 4.0 ); y.Init( 3.0, 4.0 ); f.Init( 0.0, 0.0 ); f.Multi( &x, &y ); x.Print(); y.Print(); f.Print(); } void Fraction::Init(float n, float d) { numer = n; denom = d; } void Fraction::Multi(Fraction *x, Fraction *y) { numer = ( x->numer*y->denom) + (x->denom*y->numer); denom = ( x->denom*y->denom); } void Fraction::Print() { cout << "Fraction:" << endl; cout << " Numerator: " << numer << endl; cout << " Denominator: " << denom << endl; } Stackoverflow cut off my code. :/ (Not too sure why. I'm kinda new to the site) Anyways, what I'd really like to do is set this program up so it could take user input for what the x and y fractions would be. In my past assignments I've just used cin and cout commands, but now have no idea what to do. Once I get that I know I can make it reduce the fractions properly and display properly, but I have no idea how make it take input. Does anyone have any suggestions? (Or even better if you can direct me to a site that has more information like cplusplus.com I would be very grateful!)
Renaming your Multi method Add would avoid a lot of potential confusion and is highly recommended. As for input, what's wrong with (e.g.) std::cin >> numer >> denom (with numer and denom declared as integers) for example? Then of course you can pass them to the Init method, etc. (You'll probably also want to do prompting on std::cout before reading the user input, naturally).
3,155,133
3,155,206
Application crashing in WInXp and WIn2k3 but not in Vista or Win7 after applying KB981793 hot Fix from Microsoft
I have an existing application developed in VC++ 6.0 which has been installed in many customer sites throughout the world. This application was working fine until sometime back when the Microsoft KB981793 hot fix was applied. This hotfix has changes related to Timezones and was crashing a crash due to an array overflow in our application code. When this patch was removed the application no longer crashed. But the interesting thing is this crash was observed only in WinXP and Win2k3 machines and not in Vista or Win7 machines. Any reason why this works this way.
For XP and 2K3, Microsoft specifies minimum service pack levels as prerequisites. For Vista and 7 they don't require prerequisites even though service packs exist for Vista.
3,155,224
3,155,308
C++ Can I print the content of 1 or 2 dim array using Visual Studio's Command window?
C++ Can I print the content of 1 or 2 dim array using Visual Studio's Command window? I guess it comes down to whether a "command window" support some kind of loop and print (?) syntax or not.
The visual studio command window is used to enter commands to the development environment, not for code execution. For example you could type 'open' so that VS shows the Open Dialog.
3,155,257
3,155,357
GDB - What is the mysterious Assembly code?
Dump of assembler code for function main: 0x0804833e <+0>: push %ebp 0x0804833f <+1>: mov %esp,%ebp 0x08048341 <+3>: sub $0x8,%esp 0x08048344 <+6>: and $0xfffffff0,%esp 0x08048347 <+9>: mov $0x0,%eax 0x0804834c <+14>: add $0xf,%eax 0x0804834f <+17>: add $0xf,%eax 0x08048352 <+20>: shr $0x4,%eax 0x08048355 <+23>: shl $0x4,%eax 0x08048358 <+26>: sub %eax,%esp => 0x0804835a <+28>: movl $0x10,-0x4(%ebp) 0x08048361 <+35>: movl $0x0,-0x8(%ebp) 0x08048368 <+42>: pushl -0x4(%ebp) 0x0804836b <+45>: call 0x8048334 <myfunc1 at test.c:4> 0x08048370 <+50>: add $0x4,%esp 0x08048373 <+53>: pushl -0x8(%ebp) 0x08048376 <+56>: call 0x8048339 <myfunc2 at test.c:8> 0x0804837b <+61>: add $0x4,%esp 0x0804837e <+64>: mov $0x0,%eax 0x08048383 <+69>: leave 0x08048384 <+70>: ret End of assembler dump. (gdb) info line Line 16 of "test.c" starts at address 0x804835a <main+28 at test.c:16> and ends at 0x8048361 <main+35 at test.c:17>.------------------------------------(1) (gdb) shell cat test.c #include<stdio.h> void myfunc1(int recv_arg1) { /* does nothing */ } void myfunc2(int recv_arg1) { /* does nothing */ } int main(int argc,char **argv) { int var1; int var2; var1 = 16; var2 = 0; myfunc1(var1); myfunc2(var2); return 0; } Note in (1) that the asm code for main is within that range !! and the asm code before this range is for something else ? What ? surely something mysterious !!
Allow me to comment this for you. 0x0804833e <+0>: push %ebp ; Establish standard 0x0804833f <+1>: mov %esp,%ebp ; stack frame record 0x08048341 <+3>: sub $0x8,%esp ; Make room for locals 0x08048344 <+6>: and $0xfffffff0,%esp ; Align esp to 16-byte memory 0x08048347 <+9>: mov $0x0,%eax ; eax=0 0x0804834c <+14>: add $0xf,%eax ; eax=f 0x0804834f <+17>: add $0xf,%eax ; eax= (eax + 0xf) 0x08048352 <+20>: shr $0x4,%eax ; ( >> 4) 0x08048355 <+23>: shl $0x4,%eax ; ( << 4) ;The above math rounds up eax as set by 0x0804834c to the next 16-byte boundary ;In this case, eax will be 0x10, rounded up from 0x0f. You compiled without ;optimizations? This could be a "probe" checking whether the upcoming call ;will fail? 0x08048358 <+26>: sub %eax,%esp ; Make room for "0x10 more mystery bytes" 0x0804835a <+28>: movl $0x10,-0x4(%ebp) ; var1 = 16 0x08048361 <+35>: movl $0x0,-0x8(%ebp) ; var2 = 0 0x08048368 <+42>: pushl -0x4(%ebp) ; push var1 0x0804836b <+45>: call 0x8048334 <myfunc1 at test.c:4> ;myfunc1( ); 0x08048370 <+50>: add $0x4,%esp ; pop (var1) 0x08048373 <+53>: pushl -0x8(%ebp) ; push var2 0x08048376 <+56>: call 0x8048339 <myfunc2 at test.c:8> ;myfunc2( ); 0x0804837b <+61>: add $0x4,%esp ; pop (var2) 0x0804837e <+64>: mov $0x0,%eax ; return 0; 0x08048383 <+69>: leave ; undo standard stack frame 0x08048384 <+70>: ret ; actual return I think it is a good question, why finally execute 0x08048358 which allocates seemingly useless space. I suspect this is a check for esp out of range exception before performing the call. If you specify the processor you are using, I wonder if this will "go away" -- it smells like it might be for a specific chip's errata.
3,155,277
3,155,287
Cannot dynamic_cast void* to templated class
The exact error I'm getting is: Cannot dynamic_cast 'object' (of type 'void*') to type 'class udDator(int)*' (source is not a pointer to a class) This is happening inside an overridden operator delete. I'm attempting to create a templated memory management class that can inherit into any other class, managing memory through references. This would be in place of something like a smart shared_ptr, in an attempt to make memory management even more invisible, and without extra typing ( shared_ptr< someClass > shared( new someClass() ) is kinda long... ). Anyway, here is the relevant code. If I have forgotten to mention any details, or do not have some code that you need to see, just let me know. Overridden operator: template< class T > class udSharedMemory { public: void operator delete( void *object ) { T *temp = dynamic_cast< T* >( object ); //<------ ERROR! assert( temp && "Something went wrong during casting" ); temp->release(); } } Templated class: template< class T > class udDator : public udMemoryManaged, public udSharedMemory< udDator< T > > { // stuff }; Usage of the templated class: udDator< int > *test = new udDator< int >( "5" );
Dynamic cast requires polymorphic behavior, which void does not have. Use a static_cast instead.
3,155,377
3,155,385
Equivalent asm code for C/C++ codes
Possible Duplicate: How do you get assembler output from C/C++ source in gcc? Hello out there! I have a C and C++ source code that I wanted to see in assembly code. How can I produce an equivalent asm codes for those? What tools should I use? Or is it already possible in using tools such as the gcc compiler? Then what commands should I execute? I prefer tools on top of Linux particularly Ubuntu. Thanks in advance!
gcc -S x.c This should produce the assembly that gcc thinks is equivalent to your code. Beware though, the optimizer can do some very tricky things which may be hard to see are functionally equivalent to your code. Especially in c++ where the optimizer is so dependent on inlining and stuff like that. From the gcc man page: -S Stop after the stage of compilation proper; do not assemble. The output is in the form of an assembler code file for each non-assembler input file specified. By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s. Input files that don't require compilation are ignored.
3,155,448
3,155,607
Eclipse plugin for generating UML diagram from c++ code
Is there any eclipse plugin that can generate UML/Class Diagram from C++ source code?
From the list of UML tools, I only see commercial UML editors (with C++ as one of the language reverse engineered), like: Enterprise Architect Magic Draw Modelio In other word, I don't know of a open-source project offering C++ reverse engineered UML diagrams. nrs mentions in the comments, from the Modelio Wikipedia entry: The core Modelio software was released under the GPLv3 on October 5, 2011. Key APIs are licensed under the more permissive Apache License 2.0. Note: it is a standalone app (based on Eclipse RCP), which cannot be added directly in your IDE Eclipse. Eclipse as a plugin.
3,155,680
3,155,706
Is there a way to free only a part of the dynamically allocated array in C\C++ (shrink existing array)?
In a program I allocate a huge multidimensional array, do some number-crunching, then only the first part of that array is of further interest and I'd like to free just a part of the array and continue to work with the data in the first part. I tried using realloc, but I am not sure whether this is the correct way, given I must preserve the data in the array and preferably avoid copying of that chunk in memory. #include <cstring> #include <cassert> #include <iostream> using namespace std; void FillArrayThenTruncate(char* my_array, const int old_size, int* new_size); int main() { const int initial_size = 1024*1024*1024; char* my_array = static_cast<char*>(malloc(initial_size)); assert(my_array); int new_size; FillArrayThenTruncate(my_array, initial_size, &new_size); for(int i = 0; i < new_size; ++i) cout << static_cast<int>(my_array[i]) << endl; } void FillArrayThenTruncate(char* my_array, const int old_size, int* new_size) { //do something with my_array: memset(my_array, 0, old_size); for(int i = 0; i < 10; ++i) my_array[i] = i % 3; //cut the initial array *new_size = 10; void* new_array = realloc(my_array, *new_size); cout << "Old array pointer: " << static_cast<void*>(my_array) << endl; cout << "New array pointer: " << new_array << endl; my_array = static_cast<char*>(new_array); assert(my_array != NULL); } UPDATE: * Please do not bother to suggest to use STL. The question is about C array. * Thanks to "R Samuel Klatchko" for pointing out the bug in the code above.
Yes, if you allocate with malloc, you can resize with realloc. That said, realloc is allowed to move your memory so you should be prepared for that: // Only valid when shrinking memory my_array = realloc(my_array, *new_size); Note that if you are growing memory, the above snippet is dangerous as realloc can fail and return NULL in which case you will have lost your original pointer to my_array. But for shrinking memory it should always work.
3,155,743
3,155,980
Good IMAP library for a Mac application
I am looking for a nice library that can talk to GMail from a Mac application. Really, I am thinking about writing a GMail application for the Mac. Thunderbird and Mail.app just don't cut it for me. Anyway, the library should be written in C, C++ or Obj-C or at least have interfaces for those languages. Of course, anything free and/or open source would be greatly appreciated.
I think vmime should work for this.
3,155,782
3,155,879
What is the difference between WM_QUIT, WM_CLOSE, and WM_DESTROY in a windows program?
I was wondering what the difference between the WM_QUIT, WM_CLOSE, and WM_DESTROY messages in a windows program, essentially: when are they sent, and do they have any automatic effects besides what's defined by the program?
They are totally different. WM_CLOSE is sent to the window when it is being closed - when its "X" button is clicked, or "Close" is chosen from the window's menu, or Alt-F4 is pressed while the window has focus, etc. If you catch this message, this is your decision how to treat it - ignore it, or really close the window. By default, WM_CLOSE passed to DefWindowProc() causes the window to be destroyed. WM_DESTROY is sent to the window when it starts to be destroyed. In this stage, in opposition to WM_CLOSE, you cannot stop the process, you can only make any necessary cleanup. When you catch WM_DESTROY, none of its child windows have been destroyed yet. WM_NCDESTROY is sent to the window when it is finishing being destroyed. All of its child windows have been destroyed by this time. WM_QUIT is not related to any window (the hwnd got from GetMessage() is NULL, and no window procedure is called). This message indicates that the message loop should be stopped and the application should exit. When GetMessage() reads WM_QUIT, it returns 0 to indicate that. Take a look at a typical message loop snippet - the loop is continued while GetMessage() returns non-zero. WM_QUIT can be sent by the PostQuitMessage() function. This function is usually called when the main window receives WM_DESTROY (see a typical window procedure snippet).
3,156,125
3,163,833
Is there any reliable API to Get Windows Folder in Windows?
Is there any reliable API to Get Windows Folder in Windows in C++? I am using the following way, however it failed. BOOL CQUserInfoHelper::GetWindowsPath(CString& strWindowsPath) { TCHAR windowsPathTemp[MAX_PATH]; int nSize = MAX_PATH; ::GetWindowsDirectory( windowsPathTemp, nSize); strWindowsPath = windowsPathTemp; return TRUE; }
Try This - const DWORD dwBufferLength = 65537; CStringW strBuffer; if (!::GetCurrentDirectory( dwBufferLength , strBuffer.GetBuffer(dwBufferLength)) ) return L""; ... strBuffer.ReleaseBuffer();
3,156,455
3,156,529
Difference in memory allocation in WIn 7/Vista compared to WinXP/Win2k3 in following code
I have the following piece of code. This is written for getting the list of timezones from registry and populating into an array. This piece of code works fine in Win7 and Vista OS but not in WinXp and Win2k3. The reason is because of the size of array getting overflown. I have defined only 100 elements. However there are more than 100 elements in the registry. Now my question is why this does not fail in Vista or Win7 machines. Is there any difference in allocation of memory between Xp and Vista OS. It crashes in the line while getting 100the element from registry while( RegEnumKeyEx( Key, nTimezones, tzKeyNames[nTimezones].GetBuffer( size ), &size, NULL, NULL, NULL, NULL ) != ERROR_NO_MORE_ITEMS ) Full code CString sRegKey; HKEY Key; HKEY subKey; int nTimezones = 0; CArray< CString, CString > tzKeyNames; tzOffset.SetSize( 100, 10 ); tzKeyNames.SetSize( 100, 10 ); tzDisplayNames.SetSize( 100, 10 ); OSVERSIONINFO osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); GetVersionEx(&osvi); if( osvi.dwPlatformId == VER_PLATFORM_WIN32_NT ) { sRegKey = _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones"); } else { sRegKey = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Time Zones"); } if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, sRegKey, 0, KEY_READ , &Key ) == ERROR_SUCCESS ) { DWORD size; DWORD type = REG_SZ; TZINFO tz; _TCHAR name[ 128 ]; BYTE data[ 128 ]; size = 128; while( RegEnumKeyEx( Key, nTimezones, tzKeyNames[nTimezones].GetBuffer( size ), &size, NULL, NULL, NULL, NULL ) != ERROR_NO_MORE_ITEMS ) { tzKeyNames[nTimezones].ReleaseBuffer(); if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, sRegKey + _T("\\") + (LPCTSTR)tzKeyNames[nTimezones], 0, KEY_READ , &subKey ) == ERROR_SUCCESS ) { size = 128; if( RegQueryValueEx( subKey, _T("Display"), NULL, &type, (unsigned char*)name, &size ) == ERROR_SUCCESS ) { tzDisplayNames[nTimezones] = name; } size = 128; if( RegQueryValueEx( subKey, _T("TZI"), NULL, &type, data, &size ) == ERROR_SUCCESS ) { memcpy( &tz, data, size ); tzOffset[ nTimezones ] = (int)(( tz.Bias / -60.0 ) * 2.0 ) + 24; } RegCloseKey( subKey ); } nTimezones++; } RegCloseKey( Key ); }
Exception is raised when application tries to read/write a piece of memory that is not in it's address space. In one case after the array there was addressed memory, in other there wasn't. This is random. And yes, various allocation algorithm will lead to various results but this is only one element causing randomness. The results are also dependent on how many bytes are allocated and where they are allocated by your application, other applications and the OS itself. // EDIT tzKeyNames[nTimezones].ReleaseBuffer(); Probably the problem is not in reading after the array's end (it's usually within addressed space) but that some garbage was read. This garbage is used as a pointer, when dereferenced causes exception.
3,156,501
3,156,535
Make any class reference counted with inheritance?
In my new project I wish to (mostly for to see how it will work out) completely ban raw pointers from my code. My first approach was to let all classes inherit from this simple class: template class Base { public: typedef std::shared_ptr ptr; }; And simple use class::ptr wherever I need a pointer. This approach seemed suitable until I realized sometimes my objects wish to pass the 'this' pointer to other objects. Letting my objects just wrap it inside a shared_ptr won't do since then there could be two owners for the same pointer. I assume this is bad. My next idea was to change the 'Base' class to implement reference counting itself, thus every instance of classes that inherits from 'Base' can only have one count. Is this a good solution, are there any better and can boost and/or stl already solve this problem for me?
You may want to take a look at enable_shared_from_this. On another note, when using shared_ptr, you need to be aware of the possibility of circular references. To avoid this, you can use weak_ptr. This means you will need some way to distinguish between the two of them, so simply having a typedef class::ptr may not suffice.
3,156,597
3,156,660
Override or remove an inherited constructor
Here is some C++ code: #include <iostream> using namespace std; class m { public: m() { cout << "mother" << endl; } }; class n : m { public: n() { cout << "daughter" << endl; } }; int main() { m M; n N; } Here is the output: mother mother daughter My problem is that I don't want the m's constructor to be called when I create N. What should I do ?
AFAIK, you cannot remove inherited constructor. The problem in your example comes from incorrect class design. Constructor is normally used for allocating class resources, setting default values, and so on. It is not exactly suitable to be used for outputting something. You should put n() { cout << "daughter" << endl; } Into virtual function. In general - if you have a need to remove inherited constructor, then you probably need to rethink/redesign your class hierarchy.
3,156,623
3,156,695
Software product pricing/cost estimation
I always had trouble with estimating cost/price of finished software (or programming work), so here are two questions about it. question 1: You're asked to write a piece of code for cash (all rights to the code belongs to buyer once you're done). You know approximate number of hours it will take (+-25%), and approximate complexity (i.e. whether you can write it in your sleep or will suffer severe mental burnout once you're done). Product is written in compiled language (C, C++, etc.). How do you(would you) pick price for the job? question 2: Let's say you spend a few months writing something, this thing is now finished, and now want to (try to) sell it. Product will be extremely "Niche", and it won't be possible to sell it for large numbers of people (it is SDK, game engine, library, or something like that, not a text editor - number of people that would want it will be small). "opensourcing" it is out of the question. You know approximate number of hours you spent, total size of files, LoC, and you have a repository with entire development history. The result can be sold with or without source code access, for commercial or non-commercial use, or you can (try to) sell software rights. How do you determine price for: Rights for that piece of software? Commercial use with source code access? Commercial use without source code access? Non-commercial use?
You can find some interesting insights gathered in a (free) book of Neil Davidson: http://www.neildavidson.com/dontjustrollthedice.html
3,156,778
3,156,822
No matching function for call to operator new
I'm trying to wrap a class from a library I'm using in Lua. Specifially, I'm trying to wrap the color class from SFML. The full source for the color class can be seen here and here. This is the function that's that I'm failing in. int SFColor_new(lua_State* L) { // omitting part where I set r, g, b, and a new (lua_newuserdata(L, sizeof(Color))) Color(r, g, b, a); // Line 47 luaL_getmetatable(L, LuaInfo<Color>::myMetaTableName); lua_setmetatable(L, -2); return 1; } And this is the error LuaSFMLColor.cpp: In function ‘int ag::SFColor_new(lua_State*)’: LuaSFMLColor.cpp:47: error: no matching function for call to ‘operator new(unsigned int, void*)’ <built-in>:0: note: candidates are: void* operator new(unsigned int) make: *** [game] Error 1 I do similar things in a few other places without running into this error, so I'm not sure what would be causing it. Looking at the Color's source code I don't see anything weird or out of the ordinary, and I've run out of ideas. I've also tried using the default constructor (i.e. no arguments) and then just setting the value afterward, but that didn't do any good either.
To use the standard placement form of new you have to #include <new>. The form of new that you are using requires a declaration of void* operator new(std::size_t, void*) throw();. You don't have to #include <new> to use non-placement new.
3,156,841
3,158,112
boost::filesystem::rename: Cannot create a file when that file already exists
I'm renaming a file using boost::filesystem, and sometimes the target file will exist. According to the boost documentation here: http://www.boost.org/doc/libs/1_42_0/libs/filesystem/doc/reference.html#Non-member-functions template void rename(const Path1& from_p, const Path2& to_p); Requires: Path1::external_string_type and Path2::external_string_type are the same type. Effects: Renames from_p to to_p, as if by POSIX rename(). Postconditions: !exists(from_p) && exists(to_p), and the contents and attributes of the file originally named from_p are otherwise unchanged. [Note: If from_p and to_p resolve to the same file, no action is taken. Otherwise, if to_p resolves to an existing file, it is removed. A symbolic link is itself renamed, rather than the file it resolves to being renamed. -- end note] (my emphasis) When testing this code compiled via MS Visual Studio 2008 on XP SP3, the rename throws boost::filesystem::filesystem_error with the message: Cannot create a file when that file already exists I note this has been raised in a bug report: https://svn.boost.org/trac/boost/ticket/2866 ... but claims to be closed in Boost 1.41.0 and I'm using Boost 1.42.0. Am I doing something wrong here or should I just revert to std::rename? I haven't tested this on Linux yet so don't know if the problem exists there too.
Looks like it was fixed, but only in the sandbox "V3" version of Boost.Filesystem, which is not in the mainline Boost releases yet. I tested on Boost 1.43.0 on Linux with the same results - in fact the bug report points out the offending code, which explicitly checks for existence on POSIX and throws the exception. It's possible this was done originally because MoveFile on Windows exhibits the same behavior? In the sandbox V3 version, rename will call MoveFileEx on Windows and std::rename on POSIX, and allows overwriting an existing file. I suppose you could work around it by calling boost::filesystem::remove on the target before calling boost::filesystem::rename, depending upon whether your program needs the operation to be atomic or not.
3,156,852
3,156,884
Why would I want to start a thread "suspended"?
The Windows and Solaris thread APIs both allow a thread to be created in a "suspended" state. The thread only actually starts when it is later "resumed". I'm used to POSIX threads which don't have this concept, and I'm struggling to understand the motivation for it. Can anyone suggest why it would be useful to create a "suspended" thread? Here's a simple illustrative example. WinAPI allows me to do this: t = CreateThread(NULL,0,func,NULL,CREATE_SUSPENDED,NULL); // A. Thread not running, so do... something here? ResumeThread(t); // B. Thread running, so do something else. The (simpler) POSIX equivalent appears to be: // A. Thread not running, so do... something here? pthread_create(&t,NULL,func,NULL); // B. Thread running, so do something else. Does anyone have any real-world examples where they've been able to do something at point A (between CreateThread & ResumeThread) which would have been difficult on POSIX?
To preallocate resources and later start the thread almost immediately. You have a mechanism that reuses a thread (resumes it), but you don't have actually a thread to reuse and you must create one.
3,157,098
3,157,112
Whats the right approach to return error codes in C++
I'm using error codes for handling errors in my c++ project. The problem is how to return error codes from a function which is supposed to return some variable/object. consider this: long val = myobject.doSomething(); Here, myobject is an object of some class. If doSomething function encounters some error condition then how should it notify the caller (Without using exceptions). Possible solutions: Have a data member (say err_) in the class which can be checked by the caller. But it would be unsafe in a multi-threaded application sharing the same object and calling the same function. Use some global error variable, again same issue in a multi-threaded environment. Now how can I notify the caller about some error condition?
You can pass variable as reference and return error code in it.
3,157,126
3,157,149
The inner depths of PHP
I've been studying Visibility issue in PHP (public, private, protected) and wondered how is this sort of "dom-building" is implemented in PHP? I mean there should be some kind of algorithm that PHP uses to go through all your classes and establish relations between them. Not sure if it is called "dom-building" though, but I think the same algorithms are utilized by the modern IDE's that may use it for auto-completion. Can someone redirect me to a nice resource? Thank you.
PHP does not pass through all your classes and establish relations between them. Only at run-time, when you call a method on another class, PHP checks whether that method is accessible (i.e. public or in some cases protected).
3,157,212
25,965,304
WH_JOURNALRECORD hook in Windows (C++) - Callback never called.
The following code has been giving me some troubles for the past few hours. I'm trying to write a small program (based on some tutorials from the web), that uses a WH_JOURNALRECORD windows hook to log keystrokes. Main code: #include "StdAfx.h" #include <tchar.h> #include <iostream> #include <windows.h> using std::cout; using std::endl; int _tmain(int argc, _TCHAR* argv[]) { HINSTANCE hinst = LoadLibrary(_T("testdll3.dll")); typedef void (*Install)(); typedef void (*Uninstall)(); Install install = (Install) GetProcAddress(hinst, "install"); Uninstall uninstall = (Uninstall) GetProcAddress(hinst, "uninstall"); install(); int foo; std::cin >> foo; cout << "Uninstalling" << endl; uninstall(); return 0; } Code of the DLL: #include <windows.h> #include <stdio.h> #include <tchar.h> HHOOK hhk; HHOOK hhk2; LRESULT CALLBACK journalRecordProc(int code, WPARAM wParam, LPARAM lParam) { FILE * fileLog = fopen("journal.txt", "a+"); fprintf(fileLog,"loggedJournal\n"); fclose(fileLog); CallNextHookEx(hhk,code,wParam,lParam); return 0; } LRESULT CALLBACK wireKeyboardProc(int code,WPARAM wParam,LPARAM lParam) { FILE * fileLog = fopen("keyboard.txt", "a+"); fprintf(fileLog,"loggedKeyboard\n"); fclose(fileLog); CallNextHookEx(hhk,code,wParam,lParam); return 0; } extern "C" __declspec(dllexport) void install() { HINSTANCE thisDllInstance = LoadLibrary(_T("testdll3.dll")); hhk = SetWindowsHookEx(WH_JOURNALRECORD, journalRecordProc, thisDllInstance, NULL); hhk2 = SetWindowsHookEx(WH_KEYBOARD, wireKeyboardProc, thisDllInstance, NULL); } extern "C" __declspec(dllexport) void uninstall() { UnhookWindowsHookEx(hhk); UnhookWindowsHookEx(hhk2); } BOOL WINAPI DllMain( __in HINSTANCE hinstDLL, __in DWORD fdwReason, __in LPVOID lpvReserved) { return TRUE; } For some reason, the keyboard hook (SetWindowsHookEx(WH_KEYBOARD, wireKeyboardProc,..)) works (the 'keyboard.txt' file is created), but the journaling hook (SetWindowsHookEx(WH_JOURNALRECORD, journalRecordProc,...)) doesn't. That is, the callback for the journaling hook is never called (journal.txt file is never created). I think this might have something to do with Windows' UAC (which I discovered while searching the web), but disabling UAC and running the program with administrative rights didn't help. I'm not sure what to do now. Can anyone help me? Thanks Joris Additional Info: I'm using Windows 7 + Visual Studio 2010 Edit: It turned out that this was indeed related to access rights. That is, in since Windows Vista, the journal hooks (WH_JOURNALRECORD) are disabled for security reasons (see also this website). In the end, we used a totally different approach to provide similar functionality in our application (which I won't go into detail here, as I'm editing this question 1.5 years after I asked this question and I don't recall all the details of our solution).
The answer, as per the link in the edited question: http://www.wintellect.com/CS/blogs/jrobbins/archive/2008/08/30/so-you-want-to-set-a-windows-journal-recording-hook-on-vista-it-s-not-nearly-as-easy-as-you-think.aspx The application needs to run with administrative privileges. The application must be run from (a subdir of) c:\program files To disable the UAC dialog the app must be digitally signed. Note that with UAC active Windows (Vista and above) will not allow the exe to be debugged. Or... You can disable UAC (useful when debugging). Here's the settings dialog for Visual Studio, will check to see if I can get the manifest file in XML format
3,157,323
3,157,377
How can I simplify this binary-tree traversal function?
template<typename T> void traverse_binary_tree(BinaryTreeNode<T>* root,int order = 0)// 0:pre, 1:in , 2:post { if( root == NULL ) return; if(order == 0) cout << root->data << " "; traverse_binary_tree(root->left,order); if(order == 1) cout << root->data << " "; traverse_binary_tree(root->right,order); if(order == 2) cout << root->data << " "; } Is there a better way to write this function?
No. Kidding. I think it looks pretty efficient. I would enum the order values, for readability. ... enum TOrder {ORDER_PRE, ORDER_IN, ORDER_POST}; template<typename T> void traverse_binary_tree(BinaryTreeNode<T>* root,TOrder order = ORDER_PRE) { ...
3,157,347
3,157,664
Visual Studio solutions in Qt Creator
I am using Qt 4.5 and having Qt Creator as the IDE. I am quite comfortable with it. I know we can open the .pro files (from the Qt Creator) in the Visual Studio IDE. But how about the reverse? i.e How can I open a visual studio Qt solution (.sln) in Qt Creator? Is it possible or I have to create a pro file again for the project? There are other Qt projects which are created by others in Visual Studio IDE. So if I am supposed to use those, can I migrate those Visual Studio solutions to a Qt Creator compatible way so that I can continue to use Qt Creator? I am using Windows XP. Any pointers regarding this are welcome.
You can install Visual Studio Add-in of Qt, then in Visual Studio, Qt menu will appear.There is an export option to create .pro files. Edit: Detailed Information
3,157,454
3,157,541
C++: Fill array according to template parameter
Essentially, the situation is as follows: I have a class template (using one template parameter length of type int) and want to introduce a static array. This array should be of length length and contain the elements 1 to length. The code looks as follows up to now: template<int length> class myClass{ static int array[length]; }; Then I wanted to write a line for initalizing the array // of course, the line below does not work as intended. template<int length> int myClass<length>::array[length]={1,2, ..., length}; (How) can this be achieved?
Use "static constructor" idiom. // EDIT 2 #include <iostream> template<int length> class myClass { public: typedef int ArrayType[length]; static struct StaticData { ArrayType array; StaticData() { for (int i = 0; i < length; i++) array[i] = i; } } static_data; static ArrayType &array; }; template<int length> typename myClass<length>::StaticData myClass<length>::static_data; template<int length> typename myClass<length>::ArrayType &myClass<length>::array = myClass<length>::static_data.array; int main(int argc, char** argv) { const int LEN = 5; for (int i = 0; i < LEN; i++) { std::cout << myClass<LEN>::array[i]; } }
3,157,684
3,157,761
C++ char * pointer passing to a function and deleting
I have a the following code: #include <iostream> using namespace std; void func(char * aString) { char * tmpStr= new char[100]; cin.getline(tmpStr,100); delete [] aString; aString = tmpStr; } int main() { char * str= new char[100]; cin.getline(str,100); cout<< str <<endl; func(str); cout<< str <<endl; return 0; } Why the second cout does not print the second input string? How can I change this code to work it?
Because the second cout will print what is pointed by str. And str, the pointer, in your main function will have the same value before and after the call to func. Indeed, in the func function, you are changing the value of the aString variable. But this is another variable than str in main. If you want the value of str to be changed, you have to pass it to func by reference or by pointer. (Note that what you write, is to pass the characters by pointer. I mean you have to pass the pointer by pointer: void func(char **str_ptr), or by reference void func(char *&str_ref)) If you're really doing C++, you should use std::string instead of the old C strings. An example of passing the pointer by pointer: func(char ** aString) { char * tmpStr= new char[100]; cin.getline(tmpStr,100); delete [] *aString; *aString = tmpStr; } Plus you should call it like this: func(&str);
3,157,786
3,158,607
QGraphicsView/QGraphicsScene rendering question
I am using QGraphicsScene/QGraphicsView pair in my application. I had subclassed them for my purpose. The code snippet that generate the pair is below: itsScene = new QGraphicsScene; itsView = new QGraphicsView; itsView->setParent(itsCanvas); itsView->setGeometry(20,20,1700,720); itsView->setBackgroundBrush(Qt::black); itsView->setAlignment(Qt::AlignTop); itsView->setScene(itsScene); After adding some widgets into QGraphicsScene my application final UI snapshot is below: Here my question is why there is some free space above the picture? What may cause this? I am using some negative coordinates for my widgets. Is it related with that?
The negative coordinates may be the cause. QGraphicsScene calculates its bounding rect from combining the bounds of all items in it. If you know your scene bounds, call setSceneRect to fix it down to a known rect. This way graphics items placed out of the bound will not cause the scene to expand beyond what you want.
3,157,938
3,158,027
in gcc how to force symbol resolution at runtime
My first post on this site with huge hope:: I am trying to understand static linking,dynamic linking,shared libraries,static libraries etc, with gcc. Everytime I try to delve into this topic, I have something which I don't quite understand. Some hands-on work: bash$ cat main.c #include "printhello.h" #include "printbye.h" void main() { PrintHello(); PrintBye(); } bash$ cat printhello.h void PrintHello(); bash$ cat printbye.h void PrintBye(); bash$ cat printbye.c #include <stdio.h> void PrintBye() { printf("Bye bye\n"); } bash$ cat printhello.c #include <stdio.h> void PrintHello() { printf("Hello World\n"); } gcc -Wall -fPIC -c *.c -I. gcc -shared -Wl,-soname,libcgreet.so.1 -o libcgreet.so.1.0 *.o ln -sf libcgreet.so.1.0 libcgreet.so ln -sf libcgreet.so.1.0 libcgreet.so.1 So I have created a shared library. Now I want to link this shared library with my main program to create an executable. gcc -Wall -L. main.c -lcgreet -o greet It very well works and if I set the LD_LIBRARY_PATH before running greet( or link it with rpath option) I can make it work. My question is however different: Since I am anyway using shared library, is it not possible to force symbol resolution at runtime (not sure about the terminology but perhaps called dynamic linking as per the book "Linkers and Loaders"). I understand that we may not want to do it because this makes the program run slow and has overhead everytime we want to run the program, but I am trying to understand this to clear my concepts. Does gcc linker provide any option to delay symbol resolution at runtime? (to do it with the library we are actually going to run the program with)(as library available at compile time may be different than the one available at runtime if any changes in the library) I want to be able to do sth like: bash$ gcc main.c -I. (what option needed here?) so that I don't have to give the library name, and just tell it that I want to do symbol resolution at runtime, so headers are good enough for now, actual library names are not needed. Thanks, Learner For Ever.
Any linker (gcc, ld or any other) only resolves links at compile-time. That is because the ELF standard (as most others) do not define 'run-time' linkage as you describe. They either link statically (i.e. lib.a) or at start-up time (lib.so, which must be present when the ELF is loaded). However, if you use a dynamic link, the linker will only put in the ELF the name of the file and the symbols it must find, it does not link the file directly. So, if you want to upgrade the lib to a newer version later, you can do so, as long as system can find the same filename (the path can actually be different) and the same symbol names. The other option, to get symbols at run-time, is to use dlopen, which has nothing to do with gcc or ld. dlopen simply put, opens a dynamic link library, just like fopen might, and returns you a handle, which then you pass to dlsym with the name of the symbol you want, which might be a function name for example. dlsym will then pass you a pointer to that symbol, which you can then use to call the function or use as a variable. This is how plugins are implemented.
3,158,280
3,160,439
Why do I get segfaults when declaring a struct globally or extern?
I have a struct defined in a header as follows: #define LC_ERR_LEN 300 typedef struct dLC_ERRMSG { short nr; short strategy; char tx[LC_ERR_LEN]; } LC_ERRMSG; Which I use in my code as such: LC_ERRMSG err; char *szError; szError = strerror(sStatus); snprintf(err.tx,LC_ERR_LEN," %s - %s",szFilename,szError); /* do something with our error string */ That works. If however, I declare LC_ERRMSG err; globally - i.e. outside the function it is used, or even extern LC_ERRMSG err; (which was my original intention, as I would want to be able to read out the error status in a central location), the code segfaults at the snprintf call. Can you give me any clues why? ddd tells me that the memory is initialized to either all zeroes when declared globally, or at least initialized and readable when declared extern. The values szFilename, szError and LC_ERR_LEN are all correct and meaningful.
Your linker can simply throw away the symbols, which it believes are not used (the GNU linker does so). In this case you can explicitly link the object file with that symbol. With C++ you can not control the order of initialization of global objects defined in other compilation units without any additional efforts (see http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12). Use the "construct on first use" idiom, which simply means to wrap your static object inside a function.
3,158,833
3,158,866
C++: how can I write a program to read integers from a file?
When I use the code recommended in the book, I get an error. I am using NetBeans 6.8 for Mac. Here is the code: #include <iostream> #include <fstream> using namespace std; int main() { ifstream inputFile; int number; inputFile.open("MacintoshHD/Users/moshekwiat/Desktop/random.txt"); inFile >> number; cout<<endl <<number<<endl; inputFile.close(); return (0); } Here is the error: main.cpp:20: error: 'inFile' was not declared in this scope What needs to be done?? Thank You
Replace inFile with inputFile.
3,158,922
3,158,955
Reverse iterator won't compile
I'm trying to compile a reverse iterator but my attempts to do so give a horrid mess. The minimal example of the code is... #include <iostream> #include <vector> #include <algorithm> class frag { public: void print (void) const; private: std::vector<int> a; }; void frag::print (void) const { for (std::vector<int>::reverse_iterator iter = a.begin (); iter != a.end (); ++iter) { std::cout << *iter << std::endl; } } and attempting to compile it produces the following... In file included from /usr/include/c++/4.4/bits/stl_algobase.h:69, from /usr/include/c++/4.4/bits/char_traits.h:41, from /usr/include/c++/4.4/ios:41, from /usr/include/c++/4.4/ostream:40, from /usr/include/c++/4.4/iostream:40, from frag.cpp:1: /usr/include/c++/4.4/bits/stl_iterator.h: In constructor ‘std::reverse_iterator<_Iterator>::reverse_iterator(const std::reverse_iterator<_Iter>&) [with _Iter = __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >, _Iterator = __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >]’: frag.cpp:14: instantiated from here /usr/include/c++/4.4/bits/stl_iterator.h:134: error: no matching function for call to ‘__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >::__normal_iterator(__gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >)’ /usr/include/c++/4.4/bits/stl_iterator.h:686: note: candidates are: __gnu_cxx::__normal_iterator<_Iterator, _Container>::__normal_iterator(const _Iterator&) [with _Iterator = int*, _Container = std::vector<int, std::allocator<int> >] /usr/include/c++/4.4/bits/stl_iterator.h:683: note: __gnu_cxx::__normal_iterator<_Iterator, _Container>::__normal_iterator() [with _Iterator = int*, _Container = std::vector<int, std::allocator<int> >] /usr/include/c++/4.4/bits/stl_iterator.h:669: note: __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >::__normal_iterator(const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&) There was a question on this subject yesterday but I don't think this is the same as it isn't a template. If a vector is declared in a similar way locally it is quite happy. (g++ on Ubuntu 10.4). Anyone know what I should do?
You need to use const_reverse_iterator (print is a const function so a is const) and a.rbegin() and a.rend() rather than begin() and end().
3,159,225
3,159,482
What's the language for Socket Server
What’s the best language and IDE to develope socket server? I want a language I can learn quickly that will work on an enterprise level. Please set me up with some good resources:) Thanks RECOMMENDED LANGUAGES 'I only know Flash and scripting languages' • JAVA • C languages and VB++ • PHP I’m tring to get my Flash animations to connect to an old backend system. The IT director of my company left, and I don’t want the project to get canned. I’m willing to stay up nights learning, as long as I can get a prototype made. WHAT I'M DOING 'Connecting to an archaic back-end system' alt text http://poizenpoprecords.com/myspace/videodnd/umlSocket.jpg No time contraints or limits Is any of the languages already used in your enterprise? C and VB are used How complex should your socket server be? Not complex, but have a good library and foundation to expand later Can you use something already existing? Yes, but it can't cost anything What is your purpose Learning and proof of concept is my purpose. Out of the box solution would be ideal, but sometimes implementing a new framework takes as much time, and could go against what's already in place. I'm likely to go with a language that I can continue use in game development.
What’s the best language and IDE to develope socket server? Any language that supports sockets programming (almost anything). The question is a bit simplistic. I want a language I can learn quickly that will work on an enterprise level. You can learn quickly most languages, but to become proficient in them may take time. More than that, the language doesn't matter as much as the library you use. Here are a few examples of what I mean: Python takes little time to become proficient with, but I'm not sure how "enterprise level" it is (it's used by NASA, Google and a few other major players so it may be enough). It is also very high-level, so I wouldn't be surprised if you can write the code for a simple socket server within ten lines of code (it only takes one line of code for creating a web server in python). Java and C#/C++.cli/VB+ should support the creation of a socket server with relatively few lines of code, as (the same as python) they have already-made libraries supporting most of the functionality. They are more verbose than Python though so you'll write much more code. I don't know much about PHP to say how good it would be for this. C is too low level which means you'll probly write more code than the others mentioned. It's very powerful, but writing the project in C will take you at least a week of writing code and a week (probably many more) in debugging it - especially if you're new with the language. C++ is ... well across the spectrum (it is both high and low level) but it is difficult to use correctly (it has many quirks and the mistakes you make are not obvious until you understand why it's designed as it is). C++ would probably take more than C to learn and use correctly. Please set me up with some good resources:)+ I would but your question is too broad. Here are some questions to narrow it down: what are your time constraints? are there any limits? is any of the languages already used in your enterprise? how complex should your socket server be? can you use something already existing? what is your purpose (do you need socket-server functionality urgently? do you need to learn sockets programming? do you need a socket-server-based solution to a problem you have?) Edit: Considering your answers, I'd recommend going with C++ and boost (boost::asio specifically). Here's my reasoning: I'm likely to go with a language that I can continue use in game development. C++ is the language of choice for game development. It has many pitfalls, but the advantages seem to outweigh that. If you use good C++ practices you will avoid most of the pitfalls and reasonably manage the ones you can't avoid. ( If you want a list of good practices or common C++ pitfalls ask a new question :) ). it can't cost anything Neither C++ nor boost cost anything. For IDEs, you can download Microsoft's Visual Studio 2010 Express (free) for Windows, and use Eclipse+CDT or Code::Blocks for other platforms (I think they're available for Windows also). If possible, also use a distributed source control system (like Git or Mercurial). They save you a lot of headaches and make managing the code much easier. Learning and proof of concept is my purpose. You will learn a lot :D. Here are some resources to get you started: For C++ look at Thinking in C++ (free) and (if you can get your hands on them) Effective C++, More Effective C++ and maybe Effective STL. For boost, the boost documentation (also free) should be enough, once you get started with C++. Specifically, have a look at the boost::asio examples. They offer the complete source code for various servers (HTTP servers, echo servers and so on). boost::asio is an already implemented framework, but learning C++ and the boost libraries on top of it may require a steep learning curve on your side.
3,159,332
3,159,365
Windows Service with GUI monitor?
I have a C++ Win32 application that was written as a Windows GUI project, and now I'm trying to figure out to make it into a Service / GUI hybrid. I understand that a Windows Service cannot / should not have a user interface. But allow me to explain what I have so far and what I'm shooting for. WHAT I HAVE NOW is a windows application. When it is run it places an icon in the system tray that you can double-click on to open up the GUI. The purpose of this application is to process files located in a specified directory on a nightly schedule. The GUI consists of the following: A button to start an unscheduled scan/process manually. A button to open a dialog for modifying settings. A List Box for displaying status messages sent from the processing thread. A custom drawn window for displaying image data (the file processing includes the creation and saving of images). A status bar - while a process is not running, it shows a countdown to the next scheduled scan. During a scan it also provides some status feedback, including a progress bar. WHAT I'M SHOOTING FOR is a service that will run on boot-up and not require a user to login. This would consist of the scheduled file processing. However, when a user logs in I would still like the tray icon to be loaded and allow them to open up a GUI as I described above to monitor the current state of the service, change settings, start a scan manually, and monitor the progress of a scan. I'm sure that I have seen applications like this - that function as a service even when I'm not logged in, but still give me a user interface to work with once I do log in. I'm thinking that instead of having a single multi-threaded application that sends messages to the GUI thread from the processing thread, I need two applications - a Service to perform the processing and a GUI application to provide visual feedback from the Service and also send messages to the Service (for example, to start a scan manually). But I am new to Windows Services and have no idea how this is done. It is also possible that I'm completely off base and a Service is not what I'm looking for at all. Any help / ideas / suggestions would be greatly appreciated! Thank you.
You can't do this as a service. You'll need to make your Windows Service as a normal service application. This will startup on system startup, and run the entire time the system is up. You'd then make a completely separate GUI application, which "talks" to the service. This can be set to run when a user logs in, in the user's account. In order to make them "talk" to each other, you'll need to use some form of IPC. Since these run on the same system (but in different accounts, typically), named pipes or sockets both work quite well.
3,159,357
3,161,706
3rd party header file confliction - need solution
I have to use the windows.h file in my code but it conflicts with other legacy include files on my project that I can not modify. This is in c++. How do I get around this problem, since I can not modify any of the header files in question? I thought about using a namespace but I would think you can not wrap a include in a namespace because once you instantiate you will get the same problem and I would also think it's bad practice? My team leader said to make my header file more stand alone, but eventually I still need to use the windows header in my cpp file where I define my class, so I would think that won't work in the long run. Thanks
Thank you, my solution was to remove the windows.h file from the header and make everything generic, LPSTR, LPWSTR and even the HINSTANCE (made void* and cast back in cpp file). I guess the rest of my problem was just me being an idiot!