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
4,456,919
4,456,950
Declaring 2D vector in constructor
I want my class to contain a 2D vector array in the form: vector<vector<Node> > Grid(20, vector<Node>(20)); When I try and access it from a member function like so: Grid[10][10] I get the error: expression must have pointer-to-object type If I declare the 2D vector inside the member function it works perfectly. Wha...
class X { public: X(); vector<vector<Node> > Grid; }; X::X() :Grid(20, vector<Node>(20)) { }
4,457,013
22,693,504
Makefile Syntax: Static library lib$(library).a($objects)
I'm updating some Makefiles to move from Make 3.81 to 3.82. In multiple places, the original author used something like this to build static libs: all: lib$(library).a($objects) This seems to build each .o file in turn and insert it into the .a using ar: g++ -O2 <snip> -o some_obj.o some_cpp.cpp ar rv libsome_lib.a s...
This is the "archive member" syntax supported in gnu make. It's a bit too intimate with the tools for my tastes, but there it is. The original error may be caused by $(objects) being empty. But I'm really not sure. Here's some documentation: http://www.gnu.org/software/make/manual/make.html#Archive-Members 11.1 Ar...
4,457,171
4,457,745
Why does ReadProcessMemory have `lpNumberOfBytesRead`?
From ReadProcessMemory in MSDN: lpBaseAddress [in]: A pointer to the base address in the specified process from which to read. Before any data transfer occurs, the system verifies that all data in the base address and memory of the specified size is accessible for read access, and if it is not accessible the function f...
From winerror.h: // // MessageId: ERROR_PARTIAL_COPY // // MessageText: // // Only part of a ReadProcessMemory or WriteProcessMemory request was completed. // #define ERROR_PARTIAL_COPY 299L ReadProcessMemory would return FALSE and GetLastError would return ERROR_PARTIAL_COPY when the copy hits a page f...
4,457,221
4,457,264
Basic class templating in C++
I have to two class, class CFoo { public: static CFoo& GetInstance() { static CFoo instance; return instance; } int GetValue(){ return value; } private: CFoo(){ value = 0; ltr = 'a'; } int value; char ltr; }; cl...
Generally, when you want to generalize similar classes like this, you can do so by replacing each of the types with type parameters. So, for example, here you would declare a type parameter for the type of value and a type parameter for the type of ltr. This, obviously, looks something like: template <typename ValueT,...
4,457,234
4,457,600
Using a Console Application as a Screensaver
I have created a simple C++ program that continuously outputs cosine waves made out of 1s and 0s to the console. Is there an easy way to use a console application as a screensaver, or do I have to dabble in the Windows API?
Here's an older tutorial describing how to make your own screensaver in Windows. I haven't tried it myself, but the responses to the original post make it look promising.
4,457,431
4,457,457
Compare with size_t, return int?
I'm writing some code examples from "How to Think Like a Computer Scientist in C++", and this one is about handling playing-card type objects and decks. I'm facing this situation: int Card::find(const std::vector<Card>& deck) const { size_t deckSize = deck.size(); for (size_t i=0; i<deckSize; i++) if (...
Casting from size_t to int will not "crash" your program, but it's a bad bad practice. On the other hand, STL includes nice find algorithm for what you are doing.
4,457,679
4,457,708
STL std::map dynamic ordering
I know this may be a silly question. but stil i have a confusion. W.r.t std::map. i have written a custom predicate for dymanic ordering of map, enum OrderingType { ASCENDING, DESCENDING }; template <class T> class Ordering { OrderingType m_order; public: Ordering(OrderingType order) : m_order(or...
Well setting map2 = map1 is going to in fact copy the whole object, not just the elements. What you probably want to do then is map2.clear(); map2.insert(map1.begin(), map1.end()); I believe off the top of my head that the complexity of the two steps together is going to be O(n log n), but don't quote me on that. Edit...
4,457,795
4,457,825
How is the object std::cout constructed/instantiated
So std::cout is an object. My doubt is how/where is it constructed/instantiated. Thanks.
It's constructed by ios_base::Init. First time that object is created, cout and friends are created. If the last object is destroyed, cout and friends are flushed (calling .flush()). In C++0x it will be guaranteed that if you include <iostream>, and use of cout and friends after the #include will use constructed cout a...
4,457,806
4,457,998
Pointer Arithmetic question
Could someone plz explain to me, what is happening in the following two lines of code ? Assuming that we are working on 32-bit machine p - is pointer (*(long *)((char **)(p) - 1)) (*(int *)((int)(p) - 4)) The only thing I understood, is that *(long *) converts "something" to pointer of type long and then deref. to get...
(*(long *)((char **)(p) - 1)) Start with the pointer p. Cast it to the type (char **). Subtract one from it. Cast the result to the type (long *) and then dereference the result. In other words, shift the pointer by one byte, and get the value of the long stored at that address. This operation may well be broken ...
4,457,967
4,458,634
handling utf-8 string gtk
How can i handle utf-8 string using gtk frame work.
I think you should use the following api: std::string Glib::locale_from_utf8 (const Glib::ustring& utf8_string) Take a look at these pages: glibmm: Character Set Conversion UTF-8 and Glib::ustring
4,457,978
4,458,004
How come the compiler thinks this variable isn't constant?
This is my code: int main() { const int LEN = 5; int x[LEN]; } VS10 says: error C2057: expected constant expression error C2466: cannot allocate an array of constant size 0 error C2133: 'x' : unknown size I even tried the the code in this page and it gives the same problem (I commented the code which gives the...
You might have compiled your code using .c extension. MS Visual C doesn't support C99. In C89 the size of an array must be a constant expression. const qualified variables are not constants in C. They cannot be used at places where a real constant is required. Also read this excellent post by AndreyT. Try saving the f...
4,458,047
4,459,162
Adding Annotation Syntax to C++ Source
I want to create my own custom annotation (just like the Java style annotation) tags in my C++ source. Since standard C++ syntax doesn't allow annotation, I'd like to modify/enhance the compiler for my own needs. But does Visual Studio expose its compiler internals for users to modify (e.g. output of its lexer, abst...
The standard solution to a problem like this, if it's faced in a programming language that is not C++, is to write a custom preprocessor that understands some subset of the language in question and your annotation, rewrites the code with annotations removed, which is then passed to the actual language compiler. This is...
4,458,201
4,459,599
Unable to set the background image in Qt Stylesheet
I'm running my Qt app through command line with a parameter -stylesheet. The styles for the controls work but not when I'm trying to load a background image for the MainWindow. I tried: QMainWindow{ background-image:url(:image_256_8bit_latest_back.png); } Also tried removing the ":" in background, but doesn't make a ...
Where is located the image you are trying to use ? Did you put it as a resource of your application ? If you want to use an image which is part of your resources, you should have a resource file (*.qrc) in your project. This file should contain something like this : <RCC> <qresource prefix="/images"> <file ali...
4,458,460
4,458,680
Send Mail using SMTP in C++ on Linux
Can someone give me an example of how to send a mail using a C++ program? I have come across some programs but they are not that descriptive. I would also like to know what other libraries are there if I need more options.
You might be interested in libcURL. It's a great multi-platform C library which supports a lot of different protocols, including SMTP. The official web page contains samples and tips to get you started. Here is one that might help you. Bindings exists for C++ (but I never used them) if you don't want to use the C inter...
4,458,463
4,458,765
How to make keyword to work instantly with no delay in Qt::4.6 (C++)?
OS:: win xp sp3. Qt:: 4.6 I have class Gameboard in which i have some rectangle.I defined keyPressEvent for that rectangle in order to move him around the screen.Key_A :: rectangle.moveToLeft & Key_D :: rectangle.moveToRight.Problem is that keys work with delay. When i release one key and press another one it takes som...
Put input cursor into any applicable text box and press the 'A' key. What you'll see is once you press the key, letter 'A' will be printed, then there will be a pause, and then first letter 'A' will be quickly followed by many others. That's the way keypress events work. And your program is receiving them exactly like ...
4,458,489
4,459,362
Merging 2 DIFFERENT AVL trees
Assume that I have two AVL trees and that I know their respective sizes. However, I don't know if there are repeated nodes, or any other information. What would be the most efficient way to merge them in a new AVL tree? The original trees can be destroyed.
Convert your trees T1 and T2 to sorted lists L1 and L2 Merge L1 and L2 into a sorted list L Convert L into a tree T again. IIRC all this operations are O(N), so the full merge will also be O(N). If your representation of AVL trees allows to iterate over them efficiently (for instance, using backpointers, continuation...
4,458,715
4,458,833
getting substring from ustring
I have a ustring object sourceString which is πøˆ∑´®. These string i get from an XML file while parsing it.I have used substr method to get these character string as under. Glib::ustring uString = sourceString.substr(5,0); But, i could get only null string, how should i a substring from it.
Not sure about how substr() is implemented in your case, however I'd hazard that the order of your parameters is wrong! std::string::substr() takes position first, and then size. In your case size is 0.
4,459,000
4,459,777
Init a shared_ptr of reference ( std::tr1::shared_ptr<class&> )
I'm using a library which returns a reference to me. I need to use this reference as class-attribute. Not being able to initialize the attribute in constructor directly (the lib needs to be inited before), I thought about using a shared_ptr for lazy initialization: #include <iostream> #include <string> #include <tr1/me...
You need to understand the semantics of references and of memory management. What you probably want is a raw pointer in your class. I assume you can't use a reference because you do not know what object it will refer to until you make the function call so you want to do something like ref=getRef(); You have no way of ...
4,459,194
4,459,302
Pausing a boost::thread for unlimited time
I'm using the boost::thread library (V1.44) to support threads in my C++ project. The user needs to be able to pause the execution of a test loop, that's running in its own thread, for an unlimited amount of time and be able to resume it whenever he pleases. Under Windows I solved it like this bool ContintueLoop(){ if(...
I'm not aware of any way to pause a thread at an arbitrary point using boost::thread, however, the situtation you've described can be implemented using a boolean, mutex and condition variable. bool m_pause; // initialise to false in constructor! boost::mutex m_pause_mutex; boost::condition_variable m_pause_changed; vo...
4,459,218
4,459,305
How to read all the numbers in the string one by one into array (c++)
I have seen a similar question but the answers did not work on my Visual C++ 6. I have a CString (visual C++ String class) with numbers divided by commas: CString szOSEIDs = "5,2,6,345,64,643,25,645"; and I'd like them put one by one into a int array. I tried the stringstream but it gives me only the first int. Can so...
The problem is that stream >> n fails when it hits the , in your string. You can't tokenize the string this way - instead look at a library such as boost which provides a nice tokenizer. However if you can guarantee that your string always looks like this, you can try: int n; while (stream >> n) { // Work wit...
4,459,369
4,459,613
Linker Error LNK2019 traced back to an __stdcall I think I got the right lib - what can I do to resolve this?
I tried to port a LabCVI Project to MSVS 2010 C++ Express. There is a line of code which reads like this: if (InitCVIRTE == 0) return 0; A Linker Error occurs: LNK2019 "_InitCVIRTEEx@12" - all relevant header already feature the cpp statements: #ifdef __cplusplus extern "C" { #endif ... #ifdef __cplusplus } #endif ...
You need to tell the linker what libraries to link in. The search path will only tell the linker where to find those libraries. i.e: Linker Libraries: - a.lib - b.lib Linker Search Dirs: C:\project_a\lib C:\project_b\lib the linker will search both folders for a.lib and b.lib but will not link any libraries it ha...
4,459,378
4,459,427
Visual C++ - Kill process using .net
I want to be kill a process using Visual C++ as easy as the C# way: foreach(Process process in Process.GetProcessesByName("ComponentEnvironmentServer")) { process.Kill(); process.WaitForExit(); } I've seen some examples on the net but they're a lot less simpler than above (cross-platform I guess). I'm very confus...
In managed C++ that would be: foreach (Process* process in Process::GetProcessesByName(S"ComponentEnvironmentServer")) { process->Kill(); process->WaitForExit(); } .NET allows you to use the same libraries whether you write C#, VB.NET or Managed C++. For native C++ the code is different as you...
4,459,423
4,463,418
C# program and C++ DLL compiled for 32-bit system crash on 64-bit system
I have a C# application that makes use of a DLL as I need C++ to access some unmanaged functionalities of the user32 API (I cannot use PInvoke for that). I compile both the application and the DLL for x86 architectures, and everything works fine on Windows 7 32 bits. Now the problem is, on Windows 7 64 bits, the applic...
When interoping with unmanaged code, you need to ensure your .Net app runs on the same subsystem (32-bit or 64-bit). As you've stated the DLL you're loading is for x86, force the .Net to build for only the x86 platform. This setting is found in your project's properties, on the build tab. The default is any CPU, change...
4,459,470
52,712,130
How to make upnp action?
I want to implement port-forwarding using intel-upnp. I got XML data like: Device found at location: http://192.168.10.1:49152/gatedesc.xml service urn:schemas-upnp-org:service:WANIPConnection:1 controlurl /upnp/control/WANIPConn1 eventsuburl : /upnp/control/WANIPConn1 scpdurl : /gateconnSCPD.xml And now, I ...
I know this is an old question, but it can be kept for reference. You can take a look at the sample code in the libupnp library here: https://github.com/mrjimenez/pupnp/blob/master/upnp/sample/common/tv_ctrlpt.c The relevant code is in the function TvCtrlPointSendAction(): int TvCtrlPointSendAction( int service, ...
4,459,650
4,459,757
skipping unknown options without throwing with boost program options
These days I am playing with Boost program options for reading INI files. The code I have throws an exception once in the file there is a line with an unknown option. Do you know whether is possible and how to let the code below read the whole file? I want to skip the unknown options without throwing so that I can read...
Yip: allow_unregistered(), have a look at: http://www.boost.org/doc/libs/1_45_0/doc/html/program_options/howto.html#id2075177
4,459,847
4,460,199
Handling exceptions thrown from a .NET dll in C++/MFC app
I am working with a C++ application which is interacting with a C#.NET component through COM. Due to some exceptions thrown from .NET dll my C++ application is crashing despite all exception handling mechanism in place. Is it possible to catch the exceptions thrown by .NET dll, inside C++ code? How?
I am not an expert in COM/.NET interoperability but I'd expect that the .NET runtime to never let an exception to leak through a COM method call. Instead, I guess the runtime will convert the exception to an object that implements IErrorInfo interface. [edited] I just confirmed my hypothesis. The following code prints ...
4,459,987
4,460,134
Convert float to string without losing precision
I want to store a float value into string without lossing or adding any single precision digits. For example if my float value is 23.345466467 , I want my string to have str = "23.345466467" exact digits. I tried using CString format function with %f. Its giving only first 6 precision. or if i use %10 , if my float val...
1st of all: you can't convert floating to string and back without probably loosing a bit or two. As it is not 1-to-1 conversion as they use different base. For preserving the best accuracy for floating point type: std::string convert(float value) { std::stringstream ss; ss << std::setprecision(std::numeric_limits<f...
4,460,229
4,460,357
Reposition dialog controls when resizing a dialog so that they are consistent between operating systems using mfc C++
Currently I'm repositioning dialog controls when the dialog is resized like this: // Get the list control rect. CRect listRect; list->GetWindowRect(&listRect); ScreenToClient(listRect); // Get the dialog Rect. CRect dialogRect; GetWindowRect(&dialogRect); ScreenToClient(dialogRect); list->MoveWindow(listRect.left, li...
You should use GetClientRect instead of GetWindowRect followed by ScreenToClient -- the former returns the extents of the client part of the window (i.e. without borders), whereas the latter retrieves the extents of the whole window including non-client parts (albeit in client coordinates). // Get the list control rect...
4,460,390
4,538,172
How to rename or relabel a Network Drive label
I am mounting a network drive to windows using WNetAddConnection2 which is working fine but while mounting the drive by default it assigns the name as Server IP and FolderName , NDSTestFolder on 'NAS server (172.24.17.116)'(R:) I need to rename the drive label using SetVolumeLabel but this fails for the network driv...
Translated your script into C++: #include <shldisp.h> void RenameDrive(BSTR strNewName, BSTR strDriveLetter) { IShellDispatch* pShellDispatch = NULL; HRESULT hr = CoCreateInstance(CLSID_Shell, NULL, CLSCTX_INPROC_SERVER, ...
4,460,507
4,461,462
appending to a memory-mapped file
I'm constantly appending to a file of stock quotes (ints, longs, doubles, etc.). I have this file mapped into memory with mmap. What's the most efficient way to make newly appended data available as part of the memory mapping? I understand that I can open the file again (new file descriptor) and then mmap it to get th...
Boost.IOStreams has fixed-size only memory mapped files, so it won't help with your specific problem. Linux has an interface mremap which works as follows: void *new_mapping = mremap(mapping, size, size + GROWTH, MREMAP_MAYMOVE); if (new_mapping == MAP_FAILED) // handle error mapping = new_mapping; This is non-por...
4,460,682
4,460,715
friend classes with pointers to each other
How can I create two classes that have member pointers to each other's class type, with full access to each other's data? In other words, I need two classes like this: class A { protected: B *p; }; class B { protected: A *p; }; I'm having trouble with it because I'm not up to par with C++ conventions, and obvio...
You should use forward class declaration. //in A.h class B; // forward declaration class A { protected: B *p; friend class B; // forward declaration }; //in B.h class A; // forward declaration class B { protected: A *p; friend class A; // forward declaration };
4,460,741
4,460,791
How to convert pointer address to unsigned char array?
I have an address or pointer to an object. How do I convert the address to unsigned char array? I am using it as a reference to transport using sockets. Thanks.
Object * pObject = ...; unsigned char * pSz = reinterpret_cast<unsigned char *>(pObject); // thru pSz you can see your object blindly as a pointer of unsigned char // (the first char is pointed) //and only if you know the size of your object (sizeObject) you can do this: unsigned char pArray[sizeObject] = pSz; Be rea...
4,460,867
4,460,899
Strange error c2660 "function does not take 1 arguments"
My base class has this function LRESULT CBaseClass::OnTestFunction(WPARAM id, LPARAM=0) { ... } When the derived class calls this function OnTestFunction(nId); I get an error C2660 : "function does not take 1 arguments". Why is that ?
You need to put the default value in the class definition in the header file. class CBaseClass { .... LRESULT OnTestFunction(WPARAM id, LPARAM=0); .... };
4,460,904
4,460,993
"The Debugger has exited due to signal 5 (SIGTRAP)", only when NOT debugging
I am developing with Xcode 3.2.5 for the iPhone. When testing my program in the simulator, I get this error immediately when my program starts and crashes The Debugger has exited due to signal 5 (SIGTRAP) But if I activate debugging, even if there are not breakpoints, the program runs perfectly. Do you know where to...
Try restarting Xcode and click "Clean all targets", that might help.
4,461,093
4,461,170
C#-like events in C++, Composition
For the last couple of months I've been using C# a lot and got used to events and delegates. Its is very easy to use composition in your classes, just use events to get messages from the component... Now I'm trying to do something similar in C++ and don't know how to do it. How is composition done in C++? The only way...
Typically, you will use inheritance (either dynamic or static) for this. Alternatively, you would just use a std::function< return(args..) >, which can be bound to a number of alternatives, like function objects, function pointers, lambda functions, etc.
4,461,160
4,461,199
A puzzle while learning Templates in C++
template <class A,class B> class H { public: A a; B b; void fac(); }; template <class B,class A> void H<B,A>::fac() { } What does which follows H exactly mean ? Since I declared template <class B,class A>, <B,A> seemed to be meaningless.... Can anybody help me ?? Thnx!!
There's no language rule preventing you from doing something like template<class B> void H<B, B>::fac() { } and indeed it may be necessary for any explicit or partial specializations. However, since the vast, vast majority of template code is directly inline, it's really of little consequence. For example: template<cl...
4,461,446
4,461,466
STL way to add a constant value to a std::vector
Is there an algorithm in the standard library that can add a value to each element of a std::vector? Something like std::vector<double> myvec(5,0.); std::add_constant(myvec.begin(), myvec.end(), 1.); that adds the value 1.0 to each element? If there isn't a nice (e.g. short, beautiful, easy to read) way to do this in...
Take a look at std::for_each and std::transform. The latter accepts three iterators (the begin and end of a sequence, and the start of the output sequence) and a function object. There are a couple of ways to write this. One way, using nothing but standard stuff, is: transform(myvec.begin(), myvec.end(), myvec.begin...
4,461,535
4,461,676
Singleton class whose ctor requires arguments
I have class Command which is an instance of a class EventManager. Class Command requires two arguments(host, target) in its constructor. class EventManager { public: void Event1(){ cmd->Execute(_eventEnum); } private: Command *cmd; }; class Command { public: Command(Host h, Target t) void Execute(); priva...
I really do not understand your problem, but, just from the title, I can say this: Don't use a singleton. The fact that it requires arguments is a pretty good counter-indicator for the singleton pattern. If you want to make sure that all commands are created with the same parameters, you can provide the client with a C...
4,461,562
4,461,692
How to force closing socket on Linux?
For THIS reason, I want to try something new - close the socket using some system call. The situation in two words - can't set query timeout of the mysql library (the C API, refer to the link for more info), so I want to try closing the socket to see how the library will react. Probably this is not a good idea, but st...
Just a shot in the dark, but make sure you cancel/terminate any running transactions. I'm not familiar with the MySQL C API, but I would imagine there is a way to check if there are any active connections/queries. You may not be able to close the socket simply because there are still things running, and they need to be...
4,461,586
4,461,754
How do I convert boost::posix_time::ptime to time_t?
Is there some "standard" way or the best I can do is to compute it directly by subtracting from gregorian::date(1970,1,1)?
time_t is the type used to hold time in seconds (typically epoch time). I'm guessing you are after epoch time, if so I'm not aware of any way in boost of actually getting epoch time directly, aside from the subtraction you have already. Once you have a time_duration (result of the subtraction), you can call total_secon...
4,461,954
4,462,129
Barrier implementation for inter process in shared memory
I am looking for an inter-processes barrier implementation. Processes are in shared memory (ie. on the same ndoe). Processes are MPI ones. I do not want to use the MPI_Barrier function, because the general policy for all the MPI implementation is active waiting. I want my processes sleeping as long as they wait. The re...
pthread_barrier is the POSIX API for barriers. They may live in process shared memory if you initialize them accordingly.
4,462,027
4,462,098
C/C++ High efficiency sock reverse proxy
i have to write an high efficiency sock reverse proxy in C/C++, so i was wondering, is there any library/framework to easily handle sockets, proxying, etc just to focus on the main part of the project (not the proxy itself :)) ? Something like the ACE framework but possibly i little bit smaller and/or proxy oriented .....
libevent is pretty good. ACE is horrible :)
4,462,128
4,462,183
Lagrange polinom in Visual C++ with OpenGL
How to create and print Lagrange polynomial in Visual C++ with using OpenGL library? Thanks a lot.
There could be different approaches but guess one of the most simple to understand approaches might be something like this: float f(float x) { // calculate y for f(x) here return y; } void draw() { glBegin(); for(float x = 0; x < 10; x += 0.1) glVertex(x, f(x), 0); glEnd(); } Please note t...
4,462,272
4,462,464
How to release a IplImage created by imdecode
I don't know how to free memory in the case of an IplImage created like this: Mat matrixJpeg = cv::imdecode(Mat(jpegBuffer), 1); IplImage fIplImageHeader = matrixJpeg; This won't work: cvReleaseImage(&fIplImageHeader); I will get error: 1 IntelliSense: argument of type "IplImage *" is incompatible with parameter of...
Your example is not dealing with pointers. The memory is on the stack you have nothing to release until the end of scope. The operator IplImage() const from Mat specifies that no data is copied.
4,462,473
4,462,637
Not sure what this code is doing
What is the difference between the two results here? I have seen things like this but don't understand at all. Imagine the following program: int main() { vector<int> v(4); for (int i = 0; i < 4; i++) v[i] = i; cout << v[3] << endl; cout << v[3] - '0'; return 0; } v[3] will return 3 and v[3]-'0' will return -45 ...
Answers are correct, except nobody mentioned the reason, C++ integer promotions require that char type is promoted to int in v[3] - '0' expression, had the types be different (e.g. vector<char> v(4)), the answer would be quite different as well.
4,462,563
4,463,575
C# picturebox drawing speed
I experienced that the I. method is slower then II. My application makes realtime image processing. I know C# is not ideal for this purpose, but I can separate the performance critical things and make it in C++ for example. I'm wondering why slower in C# a simple Bitmap drawing without any computation. My question: is ...
The PixelFormat of the image is critical. The vast majority of machines today run their video adapter in 32bpp mode. That makes the Format32bppPArgb more than 10 times faster than any other ones, including 32bppArgb and 24bppRgb. Do make sure to create the image in that format, convert it if necessary. Also very cru...
4,462,566
4,470,149
Write vorbis comment metadata (tags) to the existing FLAC file using libFLAC++
How to write vorbis comments metadata, i.e. tags (for example "TITLE"), to the existing FLAC file using libFLAC++ (http://flac.sourceforge.net)? For example: const char* fileName = "/path/to/file.flac"; // read tags from the file FLAC::Metadata::VorbisComment vorbisComment; FLAC::Metadata::get_tags(fileName, vorbisCo...
I've analysed metaflac source code (as suggested) and here is a solution to the problem: #include <FLAC++/metadata.h> const char* fileName = "/path/to/file.flac"; // read a file using FLAC::Metadata::Chain class FLAC::Metadata::Chain chain; if (!chain.read(fileName)) { // error handling throw ...; } // now, ...
4,462,716
4,462,782
is there something like C++ const in c#?
Possible Duplicate: Why const parameters are not allowed in C# I am a C++ developer and I had some experience using C#. I have always wondered why there is nothing like this in C#: bool MyFunction(const AnotherClass& x) { //some stuff } I personally think that the constness is one of the best features in C++ (it ...
That functionality is not available in C#. You can pass a copy, you can wrap the object in a read only adapter, or you can pass references to immutable objects/structures.
4,462,819
4,462,895
differences between C++ libraries (namespaces, linking)
I'm just learning C++ and started using different libraries, like Boost and SDL. After first struggling with configuring the paths, now everything seems fine, but I still have some questions about why different libraries work differently. Why is it that while many libraries (like Boost) are separated in their namespac...
SDL was written in C, and the C language doesn't natively support namespaces. Boost is a C++-only library, and took full advantage of C++ namespaces. Boost is a mostly header-only library, so there aren't actual binaries to link most of the time. When there are binaries to link (like Boost.Thread), the headers may tak...
4,463,129
4,463,248
Using a class in a header file without access to its definition?
This is excerpt from google's c++ coding guidelines. How can we use a class Foo in a header file without access to its definition? We can declare data members of type Foo* or Foo&. We can declare (but not define) functions with arguments, and/or return values, of type Foo. (One exception is if an argument Foo ...
Suppose that foo.h knows about Foo declaration only //foo.h class Foo; void f(const Foo &); // It is possible to use the reference. Full definition is in foo.cpp // foo.cpp class CanBeConvertedToFoo; class Foo { Foo (const CanBeConvertedToFoo & x); // implicit constructor } class CanBeConvertedToFoo is implicit...
4,463,234
4,463,909
can't connect QT signal
i am new to QT and was trying to create a custom signal that would tell me a removable disk has been inserted. This is what i did MainWindow.h class MainWindow { QOBJECT .. .. signals: void qm_diskInserted(QString &); public slots: void addItemToList(QString &); ... } MainWindow.cpp...
With connection problems, always make sure that you check the console for messages about connect failures. Since Qt can't tell if a connection makes sense until runtime, it notifies you of failures there. You'd think it would crash, but it just quietly says these things in the console. With Qt, it makes sense to watc...
4,463,315
4,466,130
Forking, Signals and how they interact with global variables in C
I am trying to understand how fork()/Linux Kernel deals with global variables. Given code: #include<signal.h> #include<unistd.h> #include<stdio.h> #include<errno.h> #include <sys/types.h> pid_t pid; int counter = 2; void handler1(int sig) { counter = counter - 1; printf("%d", counter); exit(0); } int main() { s...
After fork(), the entire process, including all global variables, is duplicated. The child is an exact replica of the parent, except that it has a different PID, a different parent, and fork() returned 0. A signal handler in the child will use the child's independent copy of the global variable. The reason you're seei...
4,463,437
4,463,684
How to provide more than one overrides for one virtual function
I have the following classes : class A { }; class B : public A { }; class P { private: std::list<A*> l protected: virtual void DoIt(A* a) = 0; public: void WorkerThread() { for (it=l.begin(); it!=l.end(); it++) DoIt(*it); } }; class Q : public P { protected: void DoIt(A* a) { print("false"); } void DoIt(B*...
Well, nobody's really directly answered your question (well, heavyd tried) so I will. Some other "answers" here are actually more helpful for fixing your problem though. The issue is that void DoIt(B*) is NOT an override of the virtual function DoIt(A*). It's an overload. There's a HUGE difference. When you say that...
4,463,634
4,463,664
Advice on proper handling, is this wise?
I'm doing some funky stuff with pointers and I'm worried I might be leaving myself open to some pointer problems: #include <iostream> class Vector2 { private: double x; double y; public: Vector2(double x, double y) { this->x = x; this->y = y; } Vector2(double coords[2]) { x = coords[0]; y = coords[1];...
There's no leak. In general you cannot leak memory if you don't new any memory. But you're returning the address of a local variable, which leads to undefined behaviour. Solution 1: You could use a static double[2] in operator dPtr(): Solution 2 (Better): Store x and y in a double[2] in your class and return a pointer ...
4,463,676
4,463,962
sockaddr - print all information which sa_data holds - c++
in my c++ application I' using sockaddr. I want to see all the infarmation which sockaddr.sa_data[14] holds. for now I just print the ip from sa_data[2].sa_data[3].sa_data[4].sa_data[5]. I want to print in a way that I can understand (and please explain) all the information in the sa_data 14 bytes. any help? thanks!
One possibility would be to use inet_ntop which should be able to handle IPv4 and IPv6 addresses. It will produce a human-readable string with the address.
4,463,765
4,463,812
Can't include STL header files with Android NDK r5
I've got a very simplistic application: #include <vector> void android_main(struct android_app* state) { } When I build it, I get the following error: test/jni/main.c:14:18: error: vector: No such file or directory How the hell do I include STL header files? I've found stlport, and I can see the header files exi...
test/jni/main.c:14:18: error: vector: No such file or directory You're compiling with a C compiler, probably. Change the extension to *.cpp and check that a C++ compiler is invoked in the tool-chain.
4,463,885
4,463,923
gcc error message repository
I've spent a lot of time using the Microsoft compiler cl and found that the error codes that it gives in compile messages (like C1234, C5432, etc.) can be very useful. When I get a error I'm unfamiliar with I can easily look it up on MSDN and get a more detailed explanation of what it means. Now I'm using gcc almost e...
I find that Googling the exact error message (omitting things that change, such as variable/function names) gives pretty good results. It sometimes helps to enclose all or part(s) of the error message in quotes so that it is treated as a sentence rather than a collection of words. This page explains some of the more ba...
4,464,144
4,464,162
Does C++ virtual function call on derived object go through vtable?
In the following code, it calls a virtual function foo via a pointer to a derived object. Will this call go through the vtable or will it call B::foo directly? If it goes via a vtable, what would be a C++ idiomatic way of making it call B::foo directly? I know that in this case I am always pointing to a B. Class A { ...
Yes, it will use the vtable (only non-virtual methods bypass the vtable). To call B::foo() on b directly, call b->B::foo().
4,464,208
4,464,257
converting an array of null terminated const char* strings to a std::vector< std::string >
I have a Visual Studio 2008 C++ function where I'm given an array of null-terminated strings const char* and a count of the number of strings in that array. I'm looking for a clever way of turning an array of const char* in to a std::vector< std::string > /// @param count - number of strings in the array /// @param ar...
Something like this?: vector< string > ret( array, array + count );
4,464,300
4,464,739
explicit member specialization
g++ 3.4.5 accepts this code: template <typename T> struct A { static const char* const str; }; struct B {}; typedef A<B> C; template<> const char* const C::str = "B"; // Equivalent to following? // template<> const char* const A<B>::str = "B"; But I'm not sure it's actually legal C++03. In particular, [14.7p3...
I think this is strictly ill-formed (at least according to C++ '03). My logic is that although a typedef (7.1.3/1): ... is thus a synonym for another type. The standard still has words to explictily allow for a typedef to be used where a class-name is required (7.1.3/4): A typedef-name that names a class is a class-...
4,464,431
4,469,283
Catching calls from a program in runtime and mapping them to other calls
A program usually depends on several libraries and might sometimes depend on other programs as well. I look at projects like Wine and think how do they figure out what calls a program is making? In a Linux environment, what are the approaches used to know what calls an executable is making in runtime in order to catch...
On Linux you're looking for the LD_PRELOAD environment variable. This will load your libraries before any requested by the program. If you provide a function definition that matches one loaded by the target program then your version will be called instead. You can't really detect what functions a program is calling how...
4,464,723
4,464,731
convert from a `const char*[2]` to pair<string,string>
I have a Visual Studio 2008 C++ application with a const char*[2] parameter that I would like to convert to a std::pair< std::string, std::string >. Is there a simple way to do this? For example: typedef std::pair< std::string, std::string > Group; const char* a[ 2 ] = { "buzz", "foo" }; Group z = a; // ??? // a->firs...
You probably want : Group z(a[0], a[1]);
4,464,996
4,465,338
Free C++ library for windows gui
I just want to write a very simple C++ program for Windows only that uses a GUI. What library for C++ is free and allows me to do this? (This code is not, and will never be, open source).
+1 for Qt. Qt is bloody awesome. Once you've hacked around with QT you will never, ever want to go back to any other UI API. Seriously. It's. That. Good. There's also a free IDE that you can use that makes development even more painless. Oh, and the community is very helpful and generally kicks ass. All Hail Qt!
4,465,049
4,465,145
convert from vector< char > to an array of strings
I have a Visual Studio 2008 C++ application where I'm using a function that accepts an array of pairs of null-terminated strings: /// @brief count - number of pairs /// @brief pairs - pairs of strings void Foo( int count, const char* pairs[][ 2 ] ); I have a std::vector< char > that contains character strings separate...
Function Foo expects an array of pairs of pointers. In your vector you have characters. You need to create an array of pairs of pointers. The easiest is to initialize those pointers to point into your vector's buffer.
4,465,053
4,465,089
How does this code work?
Possible Duplicate: Return value from local scope? #include <stdio.h> int main() { int x = ({int a = 2; a;}); printf("%d\n", x); } Output: 2
It's a non-standard extension to the C/C++ languages provided by GCC called statement expressions. If you attempt to compile with the -pedantic flag, you'll get the warning "ISO C forbids braced-groups within expressions". It is not portable code and should be avoided if possible.
4,465,104
4,467,698
Socket still listening after application crash
I'm having a problem with one of my C++ applications on Windows 2008x64 (same app runs just fine on Windows 2003x64). After a crash or even sometimes after a regular shutdown/restart cycle it has a problem using a socket on port 82 it needs to receive commands. Looking at netstat I see the socket is still in listenin...
If this is only hurting you at debug time, use tcpview from the sysinternals folks to force the socket closed. I am assuming it works on your platform, but I am not sure. If you're doing blocking operations on any sockets, do not use an indefinite timeout. This can cause weird behavior on a multiprocessor machine in m...
4,465,134
4,465,164
Which is more efficient:A Win32 func. or a similar CRT func. in a VC++ app.?
I started win32 programming for fun because I like complex things and I like programming(this is all Charles Petzold's and Jeffrey Richter's fault for writing such beautiful books.) and may be because I have a thing for performance code. Now, the real question:I'll use the example of GetEnvironmentVariable()[a win32 AP...
Stick with the CRT. It maps to the WinAPI, but not necessarily directly. For example, printf() might map to WriteConsole, but with buffering for performance. If GetEnvironmentVariable() doesn't need any code wrapped around it, then getenv() will be the same performance, and if it does (such as buffering), then the CRT ...
4,465,329
4,465,415
C / C++ equivalents to the Python Standard Library
I depend heavily on Python's standard library, both for useful data structures and manipulators (e.g., collections and itertools) and for utilities (e.g., optparse, json, and logging), to skip the boilerplate and just Get Things Done. Looking through documentation on the C++ standard library, it seems entirely about da...
The Poco library is more like other languages' standard libraries. Actually the Poco web site's logo says "C++ now comes with batteries included!", which seems to be precisely what you're asking for. I didn't like it when I tried because I found it too C-like and with too many dependencies between parts (difficult to s...
4,465,639
4,465,756
Call C# dll from unmanaged C++ app without COM
Is there a way to call c# dll from c++ unmanaged application without COM usage?
You can do this using Reverse P/Invoke - example and discussion here.
4,465,661
4,465,789
c++ time manipulation using time_t in Win platform
Well i want to manipulate time with a time_t variable in this way: time1 = get the current time as time_t (say it's 9:30 now) use SYSTEMTIME to see if we passed 10:00 if we didn't pass 10:00 : evaluate what (time_t)time2 would be in 10:00. and set time3 = time2 - time1 in order to get in seconds how much is left till ...
time_t time1; time(&time1); tm time0 = *localtime( &time1); if (time0.tm_hour == 22 && time0.tm_min == 0) ; // it 10PM else { // force time0 to 10PM time0.tm_hour = 22; time0.tm_min = 0; time_t time2 = mktime(&time0); }
4,465,686
4,465,711
How to prevent a method from being overridden in derived class?
How can I enforce that a base class method is not being overridden by a derived class?
If you make the method non-virtual, derived classes cannot override the method. However, in C++03 a class cannot override a method from a base class, and also prevent further derived classes from overriding the same method. Once the method is virtual, it stays virtual.
4,465,872
4,465,907
Why does typeid.name() return weird characters using GCC and how to make it print unmangled names?
How come when I run this main.cpp: #include <iostream> #include <typeinfo> using namespace std; struct Blah {}; int main() { cout << typeid(Blah).name() << endl; return 0; } By compiling it with GCC version 4.4.4: g++ main.cpp I get this: 4Blah On Visual C++ 2008, I would get: struct Blah Is there a way to m...
The return of name is implementation defined : an implementation is not even required to return different strings for different types. What you get from g++ is a decorated name, that you can "demangle" using the c++filt command or __cxa_demangle.
4,466,088
4,466,171
How to get class name?
If I defined a class: class Blah {}; How can I: std::string const className = /* What do I need to do here? */; assert( className == "Blah" ); I dont think typeid().name() is a good idea since it's compiler implementation specific. Is there anything provided by the C++ standard or Boost? Note: If the class were inher...
Like this: class Blah { static std::string const className() { return "Blah"; }}; std::string const name = Blah::className(); assert(name == "Blah"); Or this: class Blah {}; template < typename T > struct name; template < > struct name<Blah> { static std::string value() { return "Blah"; }}; std::string const classn...
4,466,102
4,467,098
Compressing vector with POCO (c++)
The POCO Library requires an istream for input and ostream for output to compress data using its zlib wrapper. I have data in a std::vector(unsigned char) and would like to compress this data into another std::vector(unsigned char). Is there any easy way to do this?
I don't know that this is the most efficient way, but as a start I'd try this: typedef unsigned char uc; typedef vector<uc> v; void Doit(const v& in, v& out) { ostringstream outStream; DeflatingOutputStream compressor(outStream, DeflatingStreamBuf::STREAM_GZIP); copy(in.begin(), in.end(), ostream_iterator<uc>(...
4,466,154
4,466,256
VS2010 Debug Level Mismatch
I noticed while testing my library that VS2010 will throw an error if I try to link to a static library built in Release mode when the project is in Debug mode. Inversely, it appears that the same thing happens if I try to link to a library built in Debug with a project built in Release. error LNK2038: mismatch detect...
It's not a strange behavior, compiler creates different images depending on macro defines, optimization and other flags. It's better not to distribute static libraries, because the users will have to have exactly the same compiler version, standard library version, same compiler flags or you risk incompatibilities: som...
4,466,216
6,526,708
CoreGraphics Alternative?
I'm looking for a 2D rendering library as an alternative to CoreGraphics on iPhone. Everything in my app is pretty dynamic, which makes splitting things up into layers and animations rather hard. I'm quite familiar with OpenGL, and that is how rendering is implemented right now. Everything would be so much easier to ex...
MonkVG is an OpenVG 1.1 like vector graphics API implementation currently using an OpenGL ES backend that should be compatible with any HW that supports OpenGL ES 2.0 which includes most iOS and Android devices. This is an open source BSD licensed project that is in active development. At the time of this writing it is...
4,466,270
4,466,298
Undefined reference to static queue
I'm new with C++ pthreads. What I'm trying to do is use one thread to catch UDP packets and put it into a queue, and another one to process them and send them after. My question is, how can I push/pop elements into/from a container in a separate thread? Here's an example: #include <queue> #include <iostream> #include <...
you need to initialize the static member, add std::queue<int> A::bufferInbound; after the class or move it inside your function.
4,466,302
4,466,366
JNA for a custom library
I am new to the JNA infrastructure but I think that the gist is that I have some library "someLib" and I create a java interface to match it. Then I can 'just' use it right? But the problem is that I am unsure of what I need to mock out, specifically there are some classes that I need the features of. Lets say that ...
JNA will help you access C functions and data. One option is to expose your C++ functionality in a C API. If you want to access many C++ classes, SWIG is a better fit. It can create Java wrappers for your C++ classes. It is very powerful, but there is a learning curve.
4,466,379
4,466,700
Performance profiler: How to use unsigned long to measure time in microseconds?
I am using unsigned long to collect performance data while profiling an application as follows unsigned long time_taken = (unsigned long) ((finish_time_in_nano_sec - start_time_in_nano_sec)/1000); Write time_taken to a file. Do this for every function that gets called in my app. Now after app execution, have a separat...
The problem is in your time measurement code: clock_gettime(CLOCK_REALTIME, &start_time); clock_gettime(CLOCK_REALTIME, &finish_time); unsigned long time_taken = (unsigned long)((finish_time.tv_nsec - start_time.tv_nsec)/1000); If a 1-second clock boundary is crossed between start_time and finish_time, then your subtr...
4,466,430
4,466,642
Changing object members via an iterator?
Been a while since I've used C++. Can I do something like this?: for (vector<Node>::iterator n = active.begin(); n!=active.end(); ++n) { n->ax /= n->m; } where Node is an object with a few floats in it? If written in Java, what I'm trying to accomplish is something similar to: for (Node n : this.active) { n.ax /= ...
Yes. This syntax basically works for almost all STL containers. // this will walk it the container from the beginning to the end. for(container::iterator it = object.begin(); it != object.end(); it++) { } object.begin() - basically gives an iterator the first element of the container. object.end() - the iterator is s...
4,466,433
4,468,520
Is it possible to do the following with auto in C++0x?
Eric Lippert has written an article about Why no var on fields? in C#. I was curious, will we be able to do that in C++0x? ex. struct mystruct_t { auto i = 0, d = 0.0, s = std::string("zero"); }; I couldn't reach an answer through the latest draft, sorry. Thanks,
Sadly you cannot. The spec says at 7.1.6.4/3 and follows Otherwise, the type of the variable is deduced from its initializer. The name of the variable being declared shall not appear in the initializer expression. This use of auto is allowed when declaring variables in a block (6.3), in namespace scope (3.3.6), and in...
4,466,503
4,493,717
how to compile c++ files with cygwin on windows 7
I have installed cygwin. But when I try to compile a c++ file it gives the following error: /usr/lib/gcc/i686-pc-cygwin/4.3.4/cc1plus.exe: error while loading shared libraries: cygmpfr-1.dll: cannot open shared object file: No such file or directory I checked in the lib folder there is no library with the name cygmpfr...
You need to install the gcc4-g++ package via http://cygwin.com/setup.exe You only have gcc4 installed. This will also install your missing dependencies.
4,466,520
4,466,788
Is there a simple way to compute a "smooth" function with the following characteristics in C/C++?
In order to specify some things first: The user should be able to create a graph by specifying 3 to 5 points on a 2D field. The first and the last points are always at the bounds of that field (their position may only be changed in y direction - not x). The derivation of the graph at these positions should be 0. The p...
Do you understand how splines are arrived at? Summary of doing splines You break the range into pieces based on the control points (splitting at the control points or putting the breaks between them), and plop some parameterized function into each sub-range, then constrain the functions by the control points, artifici...
4,466,574
4,468,411
boost::multi_index user-defined key extractor and composite key
To avoid a msvc2010 compiler bug, I'm using a user-defined key extrator in a composite_key like that : enum NodeType { TypeOne = 0, TypeTwo }; struct TypeExtractor { typedef NodeType result_type; const result_type& operator()(const boost::shared_ptr<Node>& p) const { return p->getNodeType(); } ...
Use the following composite key extractor: boost::multi_index::composite_key< boost::shared_ptr<Node>, boost::multi_index::const_mem_fun<Node, const std::string&, &Node::getValue>, TypeExtractor >
4,466,717
4,466,803
Matrix multiplication
I have a question which might be for beginners. I want to multiply a 20x2 matrix by a 2x2 matrix in c++. I tried it with openCV but I get an error which is Bad argument (Unknown array type) in cvarrToMat Here is the code that I used in openCV in order to check the problem if it was with my code or the problem in ...
May be you should post the prototype of the function you are calling, as well as the declaration of your matrices and your call. I don't think everyone is familiar with a openCV.
4,466,733
4,475,910
QtPropertyBrowser and value changed signals
I'm using the Qt Property Browser library as a record editor. When the user has completed their edits of any given field, by removing focus from the edit item or pressing the enter key, I want to be informed of that so that I can take the change, process it, and send it off to the REAL item that's being changed. Unfor...
So, here's the half-ass fix I came up with: I added a "commitItem(QModelIndex)" function to the private thing in the TreePropertyBrowser. Then I call that from the delegate when the setModelData() function is called. This then finds the property, calls a new function I added to the AbstractBrowser to fetch the factory...
4,466,885
4,470,702
What version of the PKCS#1 spec is gcrypt implemented against?
I am trying to determine which version of the PKCS#1 spec that gcrypt is implemented against. Thank you
The gcrypt manual talks about "type 1 padding" (for signatures) and "type 2 padding" (for encryption). This means that it implements the "old-style" PKCS#1 signature and encryption methods, also called "v1.5" because they were the only ones specified in PKCS#1 v1.5. gcrypt does not appear (from what I see in the docume...
4,466,919
4,466,940
Returning a reference to a local/temprorary object without causing a memory leak?
I realize this is wrong (my compiler says so!): Rectangle& Rectangle::Overlap(const Rectangle& rectangle) { Point topLeft(__max(this->GetVerticies()[0]->GetX(), rectangle.GetVerticies()[0]->GetX()) - __min(this->GetVerticies()[0]->GetX() + this->GetWidth(), rectangle.GetVerticies()[0]->GetX() + rectangle.GetWidth(...
Either return by value: Rectangle Rectangle::Overlap(const Rectangle& rectangle); which does not require to change your function body, or add an additional parameter to return the result: void Rectangle::Overlap(const Rectangle& rectangle, Rectangle& out); and assign the result to the out parameter.
4,466,994
4,467,785
Loop reordering across function boundaries in STL Algorithms
For simplicity lets assume that I have a vector of N matrices each of M rows. I am using STL std::accumulate to compute the sum of all the matrices. I pass a binary functor that accepts two matrices (by reference) and returns their sum (by reference). Full disclosure: I am using libstdc++ parallel mode. Inside the func...
class Matrix; class Row; struct SumNRow { int _rowidx; // Row _tempRow; //For return by reference left out for simplicity SumNRow(int iRowIdx): _rowIdx(iRowIdx) {} Row operator(const Matrix & iMarix1, const Matrix iMatrix2) { return iMarix1[_rowIdx] + iMatrix2[_rowIdx]; } }; template<class MatrixIterator>...
4,467,013
4,467,262
Creating C++ project from existing code in VS2005 or VS2010
Could someone please be kind enough to provide details of how one would go about creating a VS c++ project from an existing codebase? In my scenario I am attempting to use the following code http://gears.googlecode.com/svn/trunk/gears/. I have downloaded the entire trunk to a folder on my computer but now wish to open ...
It's not very difficulty to add a new Windows solution for your project. Whether it compiles or not is hard to say, as the project might invoke some unix-specific header files, for example . Anyway, you need to create a new solution. Then add all source files to your project. You don't have to mimic the existing folder...
4,467,038
4,467,064
Is it considered bad form in C++ to put a class declaration containing method definitions in a header file?
I am used to C, where header files usually only contain declarations and not definitions, but C++ seems to encourage the mixing of both, at least with classes. Take this class declaration which could easily be put in a header file. Some of its methods are defined inline, not in the sense of the "inline" keyword, but in...
It may be bad form, depending on the "bigger picture" of the applications using the header. By putting implementation into the header you're requiring modifications to the header when that implementation changes... such modifications trigger/require client object recompilation with many build systems (e.g. make). By ...
4,467,483
4,494,947
Error using std::cout
When I try to print text to the Windows console (in a Console Application) I get Compiler Error C2679 - Binary '<<' : no operator found which takes a right-hand operand of type 'std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion). The code that generates this error is: (where str_var is any var...
OK! problem solved! I reinstalled Visual Studio and now it works. So, it was just a problem with VS, not anything about the code.
4,467,485
4,467,537
vftable performance penalty vs. switch statement
C++ question here. I have a system where I'm going to have hundreds of mini-subclasses of a given superclass. They all will have a "foo" method that does something. Or... I'm going to have one class with an integer called "type" and use a giant switch statement to decide what to do when I foo. Performance is a huge ...
If I have it as a switch statement, I can put the commonly occuring foo's up at the top of the switch statement and the less common ones at the bottom, hopefully shortcutting the comparison. A switch statement is generally compiled to a jump table rather than a block of if-else conditionals as your question implies. ...
4,467,567
4,467,954
g++ 4.1.2 compiler error
I have the following code (stripped down version from actual project to reproduce the issue) that results in a compiler error on RHEL5 (g++ version 4.1.2): ----------- driver (test.cpp)-------------- #include <iostream> #include <classa.hpp> #include <func.hpp> namespace globals { static int kth(const A& a) { ...
Here's what happens. When the function func() is defined, the compiler doesn't know about the function kth(const A&) yet because it is defined later in the code. So when it encounters a reference to kth() inside func(), it assumes that it is a reference to kth(const int&). Now when func() is actually instantiated, it f...
4,467,689
4,467,749
Overriding new but telling unordered_map not to use it
I'm writing a garbage collector for C/C++ as a programming exercise, and part of this involves globally overriding new. However, the garbage collector also uses an unordered_map (to store pointers to allocated blocks), and things will get seriously messed up if the map tries to use the overridden new (it will try to in...
The full declaration of unordered_map, as well as of all STL containers, includes allocator as the last parameter: template<class Key, class Ty, class Hash, class Pred, class Alloc> class unordered_map; That's where a container gets memory for all its internal structures. You probably want to implement your own a...
4,467,871
4,467,900
G++ warning: built for unsupported file format which is not the architecture being linked
Whenever I try to compile my project (with the command line g++ *.hpp *.cpp 2> log.txt), that's what I get: log.txt: ld: warning: in configfile.hpp, file was built for unsupported file format which is not the architecture being linked (x86_64) ld: warning: in erase.hpp, file was built for unsupported file format whic...
You're compiling header files (.hpp) which you shouldn't do yet. Only compile source files (.cpp) Rather than compiling all .cpp files, compile them one at a time and then link them appropriately. g++ -c x.cpp g++ -c y.cpp g++ -c z.cpp g++ -o tst x.o y.o z.o Note that only one of your .cpp files can have a main() fu...
4,468,028
4,468,073
SDL: Delay until keyboard input
Say we have (pseudo) code like this: GetInput() { //insert keyboard stuff here } Update() { //insert rendering stuff here } void game::loop() { game.Update(); player.GetInput(); } How will I go about waiting for the player to give input before updating whats on screen?
Why not switch the order (GetInput first), then block in GetInput and don't return until the user has entered something acceptable?
4,468,243
4,468,630
Qt: I fail to install translator in subclass of QApplication
In my app, I'm subclassing QApplication to do a lot of things, like centralized exception handling, SQLite database connection, initializing default settings (when needed) via QSettings. And, in particular, loading translations. I'm doing it in constructor, and when I do: installTranslator (&translator); qDebug() << "T...
It could be that &translator in installTranslator(&translator) refers to a local variable that is destroyed upon exit from the constructor. If installTranslator() doesn't copy it (docs aren't very clear on this topic), anything could happen including non-working translations or even segfaults. In fact, docs give us a h...
4,468,499
4,469,333
Is there a typical pattern for handling wide character strings in exceptions?
Standard C++'s std::exception::what() returns a narrow character string. Therefore, if I want to put a wide character string message there, I can't. Is there a common way/pattern/library of/for getting around this? EDIT: To be clear, I could just write my own exception class and inherit from it -- but I'm curious if th...
Based on this post Exceptions with Unicode what(), I decided to do something like this: class uexception : public std::exception { public: uexception(LPCTSTR lpszMessage) : std::exception(TCharToUtf8(lpszMessage)) { } }; Everywhere in my code base, I am assuming that .what() will return a string that is en...
4,468,522
4,468,550
Why should C++ permit a variable name and a class name to be the same?
#include <iostream> #include <vector> using namespace std; typedef int UINT4; class Hack {}; Hack& operator <(Hack& a , Hack& b) { std::cerr << "1"; return a; } Hack& operator >(Hack& a, Hack& b) { std::cerr << "2"; return a; } int main() { Hack vector; // It SHOULD be OK!? H...
Ever heard of the following? Please look close at the parameter types :) int stat(const char *path, struct stat *buf); What you have shown in your question really isn't too dramatic. You declare a variable name in a local scope, but the type names in your program are in global scope. I will show you some real pervert ...