question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,089,545
2,089,572
Fine to have variables in a namespace?
I have a set of functions that work on a file. Originally I made it into a class, with the only private member being a static const std::string which was the name of the file. The user used these functions by creating an object and calling functions from it. However, I think I'm going to switch to using a namespace, since it's just a set of functions and makes more sense. The only problem is that I still would like to keep that constant string. Would doing something along these lines be fine? namespace FileHandler { // Functions to do stuff with file const std::string FILE_NAME; } I have a separate implementation file for the namespace, but I'm wondering if the loss of encapsulation from having the file name be a private member in a class is worth using the namespace instead.
You can do similar things but they will have different semantics. In a class, a static variable is a declaration, not a definition, it still requires a definition outside of the class; a variable declaration in a namespace is a definition unless you mark in as extern and don't provide an initializer. In your case it doesn't make too much difference as const variables have internal linkage by default so you can have multiple definitions in a program (one per translation unit) without problems. E.g. class Test { static const std::string FILE_NAME; }; is (in some ways) equivalent to: namespace Test { extern const std::string FILE_NAME; } If you did this, you would be declaring FILE_NAME as an empty string. You couldn't redeclare it elsewhere in the same translation unit. namespace Test { const std::string FILE_NAME; } You could, though, do this. namespace Test { const std::string FILE_NAME = "myfile.txt"; } Each translation unit would have its own version of Test::FILE_NAME but they would all be consistent.
2,089,619
2,089,900
How do you create a freestanding C++ program?
I'm just wondering how you create a freestanding program in C++? Edit: By freestanding I mean a program that doesn't run in a hosted envrioment (eg. OS). I want my program to be the first program the computer loads, instead of the OS.
Have a look at this article: http://www.codeproject.com/KB/tips/boot-loader.aspx You would need a little assembly start-up code to get you as far as main() but then you could write the rest in C++. You'd have to write your own heap manager (new/delete) if you wanted to create objects at runtime and your own scheduler if you wanted more than one thread.
2,090,021
2,090,198
Interview test for applied scientific computing job
Do you know a good and objective question/test to examine applicants for a scientific computing job? (In fact, this test comes after the candidate passed an interview.) 1st) They need to be intelligent. (Edit, thanks for the words from Trent) 2nd) They would have to deal mostly with programming (C++ and Python, using scientific libraries), numerics and mathematics, but also with engineering and physics topics. Also, C-like or Fortran-like style is not desired... usage of O.O. concepts would be good. The applicant may have access to compilers, tools, libraries and internet. The duration of the test should be no more than 4 hours.
Well, an easy problem is to ask someone to solve a simple ODE system using whatever libraries they wish to use. None of the libraries that I know of are straightforward enough that they can be learnt during the test. For example, solve this system for x=1:10: dx/dt = -k (x^2/x). A tougher one is to ask someone to solve a stiff ODE system. Here, the choice of algorithm becomes important and a 'guess' probably won't work. For example, most Michaelis-Menten equations are stiff. dS/dt = - vmax * S/(Ks + S) where dS is the rate of substrate depletion and vmax and Ks are constants (that you can give the candidate). Choosing the wrong solver here leads to rather disastrous results, as I have found out first hand. Neither problem is any good on its own, since pretty much anyone could solve either one by trial and error given 4 hours to solve it. But as part of a larger test, they might be useful. EDIT: What does it prove? Well, ODEs are everywhere in scientific computing. If you haven't at least dealt with them cursorily at some point, it's a big hole in your knowledge. I've only tried to answer the question as asked. "What are specific questions to ask an applicant to a scientific computing job?". To solve the problem the applicant is going to have to know 1) Basic calculus. 2) Some sort of a scientific computing library (MATLAB, SciPy, GSL). 3) If the question is asked appropriately (for example, if they were asked to compute a rate of acceleration), domain knowledge (physics in this case) is also tested. I think this checks all the boxes :)
2,090,392
2,090,407
Are Constants Really Appropriate Here, Or Is There Another Approach? - C++
I'm a programming student in my 2nd OOP course, which is taught in C++. I know that it is generally bad practice to use magic numbers in code, so here's my question: In the next program I have to write for this class, there is over 120 numbers given to us in tax tables, and we need to use them to compute tax and other relevant info. With such a large amount of numbers, do I define a constant for each number? Or is there something else I can do?
Constants would be more appropriate than magic numbers - However, with that many "constants", and something that changes over time (tax tables), I personally would load these via a configuration file, and use some type of dictionary lookup for the individual values. This would make it much easier to adjust to new tax tables without recompilation.
2,090,393
2,090,409
Storage of a high score table, what kind of container?
Say I have a high score table structured like name score name score .... I need to do some file operations and manipulate certain areas of the file, and I thought the best way to do this would be to store it in a container that preserved the order of the file, do the data manipulation with the container, then output back to the file. I considered using a map< std::string, int >, but a map wouldn't preserve the order of the file. Would a vector< pair< std::string, int >> be better, or is there some kind of ordered map I can use? I also need the container to repeat a name if necessary. I think a multimap keeps one key, but allows multiple values for that key, which isn't what I want since it wouldn't preserve order.
Use the std::vector< std::pair< std::string, int > > solution. Or even better, do a HighScoreEntry class, and have a std::vector< HighScoreEntry > -- then you'll be able to add additional data to it later, and embed score handling code in the class. To add an entry, push the entry to the end of the vector, and run std::sort on it, just remember to write a comparison operator for HighScoreEntry. class HighScoreEntry { public: std::string name; uint32 score; bool operator<(const HighScoreEntry& other) const { // code that determines ordering goes here return score < other.score } }; Highscore table: std::vector< HighScoreEntry > highscores; Sorting: std::sort( highscores.begin(), highscores.end() ); To preserve sort order for highscores that have the same score, use a timestamp, and add it to the comparator.
2,090,442
2,090,698
Producer/Consumer For Talking to Devices Serially
Here is my problem: I have to be able to send and receive to a device over serial. This has to be done in a multi-threaded fashion. The flow is as follows: Wait for device to send me something - or if idle, then query status to see if online with device If device sends me something, then process message, acknowledge, and tell device to perform other commands as necessary Right now, I have a receive thread and transmit thread. The receive thread has a while loop that keeps checking the serial port via ReadFile(...) for one byte. If I have a byte, then I begin building my buffer and then parse the data to determine what was sent to me. The send thread takes the next command defined by the read thread and sends it via WriteFile to the same COM port. The key is that there is a receive/send relationship between myself and the device. My question is, do I have a nested Producer/Consumer model here? If my receive thread is consuming from the device and the send thread is producing to the device, the threads need to inherently talk so they are synchronized-right? What is the best way to synchronize my efforts in efficiently and quickly talk to the device? Note: I am using C++ Builder 5 which has TThreads and can use critical sections and mutexes. Edit: I am also using polling so I am open to using WaitCommEvent as well if this will work better!
What resources are you sharing that you think you need to synchronize? If you have something like a queue in between the two threads then that is a pretty classic producer/consumer model. E.G. If you just have one thread reading and then putting commands in a queue while another thread extracts from the queue, processes the command and writes to the device then you need to synchronize access to the queue with a mutex or semaphore. Perhaps I'm missing something but this should only get complicated if you have multiple threads reading from the queue and the commands which need to be transmitted need to stay in order. So try to keep it simple.
2,090,619
2,090,796
Dual purpose code commenting(users & maintainers)...HOW?
I am writing a C++ static library and I have been commenting with doxygen comments in the implementation files. I have never really had to care very much about documentation but I am working on something now that needs to be documented well for the users and also I am trying to replace my previous bad habit of just wanting to code and not document with better software engineering practices. Anyway, I realized the other day that I need a couple different types of documentation, one type for users of the library(doxygen manual) and then comments for myself or a future maintainer that deal more with implementation details. One of my solutions is to put the doxygen comments for file, class, and methods at the bottom of the implementation file. There they would be out of the way and I could include normal comments in/around the method definitions to benefit a programmer. I know it's more work but it seems like the best way for me to achieve the two separate types of commenting/documentation. Do you agree or have any solutions/principles that might be helpful. I looked around the site but couldn't really find any threads that dealt with this. Also, I don't really want to litter the interface file with comments because I feel like it's better to let the interface speak for itself. I would rather the manual be the place a user can look if they need a deeper understanding of the library interface. Am I on the right track here? Any thoughts or comments are much appreciated. edit: Thanks everyone for your comments. I have learned alot from hearing them. I think I have a better uderstanding of how to go about separating my user manual from the code comments that will be useful to a maintainer. I like the idea that @jalf has about having a "prose" style manual that helps explain how to use the library. I really think this is better than just a reference manual. That being said...I also feel like the reference manual might really come in handy. I think I will combine his advice with the thoughts of others and try to create a hybrid.(A prose manual(using the doxygen tags like page, section, subsection) that links to the reference manual.) Another suggestion I liked from @jalf was the idea of the code not having a whole manual interleaved into it. I can avoid this by placing all of my doxygen comments at the bottom of the implementation file. That leaves the headers clean and the implementation clean to place comments useful for someone maintaining the implementation. We will see if this works out in reality. These are just my thoughts on what I have learned so far. I am not positive my approach is going to work well or even be practical. Only time will tell.
I generally believe that comments for users should not be inline in the code, as doxygen comments or anything like that. It should be a separate document, in prose form. As a user of the library, I don't need to, or want to, know what each parameter for a function means. Hopefully, that's obvious. I need to know what the function does. And I need to know why it does it and when to call it. And I need to know what pre- and postconditions apply. What assumptions does the function make when I call it, and what guarantees does it provide when it returns? Library users don't need comments, they need documentation. Describe how the library is structured and how it works and how to use it, and do so outside the code, in an actual text document. Of course, the code may still contain comments directed at maintainers, explaining why the implementation looks the way it does, or how it works if it's not obvious. But the documentation that the library user needs should not be in the code.
2,090,651
2,093,010
DLL EXE Hybrid C++ Windows
I am currently working with DLL injection and need to have a single hybrid binary that could act as both an executable and a DLL. I thought of maybe writing a DllMain and WinMain function and then compiling it as an executable but I don't know what would happen if I did that. I know that it is posssible to combine a dll and exe by using something like thinstall or extracting the dll to a temporary location then going from there but I don't want to mess with any of that stuff. So basically, is it possible to define a WinMain and Dll Main and then use the resulting executable as both, and if not, is this even possible? Thanks in advance!
No. Both a DLL and an EXE have a PE (Portable Executable) header. That header has a field IMAGE_FILE_HEADER::Characteristics. Bit 14 of that field is either 0 (for an EXE) or 1 (for a DLL).
2,090,661
2,090,700
protected inheritance
Why protected and private inheritance are defined and proposed? I understand some cases private inheritance could be used but it is not recommended. How about protected inheritance? Can anyone offer me an situation in which protected inheritance is a choice? I rarely see this. Thanks so much!
Private inheritance is usually used for mixins---where people inherit to get functionality from the base class, rather than because of "is-a" inheritance. Protected inheritance can also be used for mixins, where the mixed-in functionality is to be available to downstream classes too.
2,090,754
2,090,935
What datatype to use for image data to avoid std:bad_alloc?
I'm developping an imaging library and I'm struggling with the image data datatype Since images can have variable datatypes (8 bits per pixel, 16 bits per pixel) I thought of implementing my image data pointer to void* pimage_data; however void* leads to all kind of nastiness including ugly pointer arithmetics such as pimage_data = &((unsigned char*)pimage_parent->m_pdata)[offset_y * pimage_parent->m_pitch + offset_x]; I suspect that something is wrong with this since when I pass it to another method CImage* roi = CImage::create_image(size_x, size_y, pimage_parent->m_data_type, pimage_data); CImage* CImage::create_image(int size_x, int size_y, E_DATA_TYPE data_type, void* pimage) { assert(size_x > 0); assert(size_y > 0); CImage* image = new CImage(size_x, size_y, data_type); image->m_pdata = pimage; return image; } the new returns std::bad_alloc Now I must agree that void* does not directly lead to bad_alloc but I'm pretty sure something is wrong with it here. Any hints? EDIT: CImage does close to nothing CImage::CImage(int size_x, int size_y, E_DATA_TYPE data_type) { assert(size_x > 0); assert(size_y > 0); // Copy of the parameter to the class members this->m_size_x = size_x; this->m_size_y = size_y; this->m_data_type = data_type; this->m_pitch = size_x; // The ctor simply create a standalone image for now this->m_pimage_child = NULL; this->m_pimage_parent = NULL; } sizes are x:746, y:325
bad_alloc can mean you are out of free memory (since you say sizeof(CImage) == 28, you would most likely be doing it in a tight or infinite loop). It can also mean you have corrupted the freestore though previous naughty memory behavior and it just caught it on the next allocation/release cycle. A good debugging session can help tell the difference.
2,090,974
2,091,186
How to separate CUDA code into multiple files
I am trying separate a CUDA program into two separate .cu files in effort to edge closer to writing a real app in C++. I have a simple little program that: Allocates a memory on the host and the device. Initializes the host array to a series of numbers. Copies the host array to a device array Finds the square of all the elements in the array using a device kernel Copies the device array back to the host array Prints the results This works great if I put it all in one .cu file and run it. When I split it into two separate files I start getting linking errors. Like all my recent questions, I know this is something small, but what is it? KernelSupport.cu #ifndef _KERNEL_SUPPORT_ #define _KERNEL_SUPPORT_ #include <iostream> #include <MyKernel.cu> int main( int argc, char** argv) { int* hostArray; int* deviceArray; const int arrayLength = 16; const unsigned int memSize = sizeof(int) * arrayLength; hostArray = (int*)malloc(memSize); cudaMalloc((void**) &deviceArray, memSize); std::cout << "Before device\n"; for(int i=0;i<arrayLength;i++) { hostArray[i] = i+1; std::cout << hostArray[i] << "\n"; } std::cout << "\n"; cudaMemcpy(deviceArray, hostArray, memSize, cudaMemcpyHostToDevice); TestDevice <<< 4, 4 >>> (deviceArray); cudaMemcpy(hostArray, deviceArray, memSize, cudaMemcpyDeviceToHost); std::cout << "After device\n"; for(int i=0;i<arrayLength;i++) { std::cout << hostArray[i] << "\n"; } cudaFree(deviceArray); free(hostArray); std::cout << "Done\n"; } #endif MyKernel.cu #ifndef _MY_KERNEL_ #define _MY_KERNEL_ __global__ void TestDevice(int *deviceArray) { int idx = blockIdx.x*blockDim.x + threadIdx.x; deviceArray[idx] = deviceArray[idx]*deviceArray[idx]; } #endif Build Log: 1>------ Build started: Project: CUDASandbox, Configuration: Debug x64 ------ 1>Compiling with CUDA Build Rule... 1>"C:\CUDA\bin64\nvcc.exe" -arch sm_10 -ccbin "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin" -Xcompiler "/EHsc /W3 /nologo /O2 /Zi /MT " -maxrregcount=32 --compile -o "x64\Debug\KernelSupport.cu.obj" "d:\Stuff\Programming\Visual Studio 2008\Projects\CUDASandbox\CUDASandbox\KernelSupport.cu" 1>KernelSupport.cu 1>tmpxft_000016f4_00000000-3_KernelSupport.cudafe1.gpu 1>tmpxft_000016f4_00000000-8_KernelSupport.cudafe2.gpu 1>tmpxft_000016f4_00000000-3_KernelSupport.cudafe1.cpp 1>tmpxft_000016f4_00000000-12_KernelSupport.ii 1>Linking... 1>KernelSupport.cu.obj : error LNK2005: __device_stub__Z10TestDevicePi already defined in MyKernel.cu.obj 1>KernelSupport.cu.obj : error LNK2005: "void __cdecl TestDevice__entry(int *)" (?TestDevice__entry@@YAXPEAH@Z) already defined in MyKernel.cu.obj 1>D:\Stuff\Programming\Visual Studio 2008\Projects\CUDASandbox\x64\Debug\CUDASandbox.exe : fatal error LNK1169: one or more multiply defined symbols found 1>Build log was saved at "file://d:\Stuff\Programming\Visual Studio 2008\Projects\CUDASandbox\CUDASandbox\x64\Debug\BuildLog.htm" 1>CUDASandbox - 3 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== I am running Visual Studio 2008 on Windows 7 64bit. Edit: I think I need to elaborate on this a little bit. The end result I am looking for here is to have a normal C++ application with something like Main.cpp with the int main() event and have things run from there. At certains point in my .cpp code I want to be able to reference CUDA bits. So my thinking (and correct me if there a more standard convention here) is that I will put the CUDA Kernel code into their on .cu files, and then have a supporting .cu file that will take care of talking to the device and calling kernel functions and what not.
You are including mykernel.cu in kernelsupport.cu, when you try to link the compiler sees mykernel.cu twice. You'll have to create a header defining TestDevice and include that instead. re comment: Something like this should work // MyKernel.h #ifndef mykernel_h #define mykernel_h __global__ void TestDevice(int* devicearray); #endif and then change the including file to //KernelSupport.cu #ifndef _KERNEL_SUPPORT_ #define _KERNEL_SUPPORT_ #include <iostream> #include <MyKernel.h> // ... re your edit As long as the header you use in c++ code doesn't have any cuda specific stuff (__kernel__,__global__, etc) you should be fine linking c++ and cuda code.
2,091,136
2,092,136
Unhandled exception: 0x80000001: Not implemented. (VC++)
I am using MS Visual Studio 2005 (C++).. Could anyone tell me what could cause a runtime exception like so..? Unhandled exception at 0x07ed0027 (xxx.dll) in yyy.exe: 0x80000001: Not implemented. xxx.dll is a dll i am working on and yyy.exe is an exe that is calling that dll.. When the undhandled exception comes up while debugging, it takes me to a function but I can't see anything wrong with the function (it doesn't raise the exception everytime this function is called). Anyway, I checked all the values in the function and they seem ok.. If I click continue instead of break, or press F5 after the break, then it goes on like nothing happened.. Please let me know if I haven't supplied enough information.. Thanks.
Like the more familiar 0xC0000005, 0x80000001 is the code of an exception that's being raised. You can look them up in winnt.h. In this case, I've found #define STATUS_GUARD_PAGE_VIOLATION ((DWORD )0x80000001L) Guard pages are used for stack growth. The first page after the top of the stack is marked as a guard page. When you write to that - typically by pushing more data on the stack - a guard page exception is taken. The OS allocates an extra page or RAM (or perhaps 2 - details left to the OS) and moves the guard page up.
2,091,426
2,091,633
Why can't we create objects for an abstract class in C++?
I know it is not allowed in C++, but why? What if it was allowed, what would the problems be?
Judging by your other question, it seems you don't understand how classes operate. Classes are a collection of functions which operate on data. Functions themselves contain no memory in a class. The following class: struct dumb_class { void foo(){} void bar(){} void baz(){} // .. for all eternity int i; }; Has a size of int. No matter how many functions you have ever, this class will only take up the space it takes to operate on an int. When you call a function in this class, the compiler will pass you a pointer to the place where the data in the class is stored; this is the this pointer. So, the function lie in memory somewhere, loaded once at the beginning of your program, and wait to be called with data to operate on. Virtual functions are different. The C++ standard does not mandate how the behavior of the virtual functions should go about, only what that behavior should be. Typically, implementations use what's called a virtual table, or vtable for short. A vtable is a table of function pointers, which like normal functions, only get allocated once. Take this class, and assume our implementor uses vtables: struct base { virtual void foo(void); }; struct derived { virtual void foo(void); }; The compiler will need to make two vtables, one for base and one for derived. They will look something like this: typedef /* some generic function pointer type */ func_ptr; func_ptr __baseTable[] = {&base::foo}; func_ptr __derivedTable[] = {&derived::foo}; How does it use this table? When you create an instance of a class above, the compiler slips in a hidden pointer, which will point to the correct vtable. So when you say: derived d; base* b = &d; b->foo(); Upon executing the last line, it goes to the correct table (__derivedTable in this case), goes to the correct index (0 in this case), and calls that function. As you can see, that will end up calling derived::foo, which is exactly what should happen. Note, for later, this is the same as doing derived::foo(b), passing b as the this pointer. So, when virtual methods are present, the class of the size will increase by one pointer (the pointer to the vtable.) Multiple inheritance changes this a bit, but it's mostly the same. You can get more details at C++-FAQ. Now, to your question. I have: struct base { virtual void foo(void) = 0; }; // notice the = 0 struct derived { virtual void foo(void); }; and base::foo has no implementation. This makes base::foo a pure abstract function. So, if I were to call it, like above: derived d; base* b = &d; base::foo(b); What behavior should we expect? Being a pure virtual method, base::foo doesn't even exist. The above code is undefined behavior, and could do anything from nothing to crashing, with anything in between. (Or worse.) Think about what a pure abstract function represents. Remember, functions take no data, they only describe how to manipulate data. A pure abstract function says: "I want to call this method and have my data be manipulated. How you do this is up to you." So when you say, "Well, let's call an abstract method", you're replying to the above with: "Up to me? No, you do it." to which it will reply "@#^@#^". It simply doesn't make sense to tell someone who's saying "do this", "no." To answer your question directly: "why we cannot create an object for an abstract class?" Hopefully you see now, abstract classes only define the functionality the concrete class should be able to do. The abstract class itself is only a blue-print; you don't live in blue-prints, you live in houses that implement the blue-prints.
2,091,495
2,091,503
Does new() allocate memory for the functions of a class also?
class Animal { public: int a; double d; int f(){ return 25;} }; Suppose for the code above, I try to initialize an object, by saying new Animal(), does this new() also allocate memory for the function f()? In other words, what is the difference in memory allocation terms if I had this class instead and did a new Animal() ? : class Animal { public: int a; double d; };
No. Functions exist in the text page and so no space is allocated for them.
2,091,499
2,091,505
Why are global and static variables initialized to their default values?
In C/C++, why are globals and static variables initialized to default values? Why not leave it with just garbage values? Are there any special reasons for this?
Security: leaving memory alone would leak information from other processes or the kernel. Efficiency: the values are useless until initialized to something, and it's more efficient to zero them in a block with unrolled loops. The OS can even zero freelist pages when the system is otherwise idle, rather than when some client or user is waiting for the program to start. Reproducibility: leaving the values alone would make program behavior non-repeatable, making bugs really hard to find. Elegance: it's cleaner if programs can start from 0 without having to clutter the code with default initializers. One might then wonder why the auto storage class does start as garbage. The answer is two-fold: It doesn't, in a sense. The very first stack frame page at each level (i.e., every new page added to the stack) does receive zero values. The "garbage", or "uninitialized" values that subsequent function instances at the same stack level see are really the previous values left by other method instances of your own program and its library. There might be a quadratic (or whatever) runtime performance penalty associated with initializing auto (function locals) to anything. A function might not use any or all of a large array, say, on any given call, and it could be invoked thousands or millions of times. The initialization of statics and globals, OTOH, only needs to happen once.
2,091,500
2,091,581
Maintaining a std::set<boost::shared_ptr>
I'm writing a game and an accompanying engine in C++. The engine relies heavily on automation using a simple embedded scripting language. Scripts can create object classes, define event listeners on them, and produce instances from them. At present, an instance must be bound to a script-global identifier in order to preserve its existence. The obvious result of this is that there can be no anonymous objects, which will be by far the most common. At present, instances are managed using a std::set<Instance*, spatial_sort>, where spatial_sort is a functor that sorts instances by position, for rendering and collision detection. Instances are removed and re-inserted each frame using their current position as a hint, under the assumption that they're not likely to move a whole lot in a fiftieth of a second. If a dead flag is set in the instance, it is erased from the set. The Instance constructors and destructor invoke insert(this) and erase(this), respectively. In order to allow anonymous instances, I want to change the set to a std::set<boost::shared_ptr<Instance>, spatial_sort>, which would allow Instance to share ownership of instances and preserve their existence until they destroy themselves. Unfortunately, because the calls to insert() need to be placed in the constructor, shared_from_this() won't work for obtaining a shared_ptr to the Instance. It doesn't matter at all that Instance happens to already inherit from boost::enable_shared_from_this<> via its base class. Can anyone recommend a suitable workaround? Edit: I did what I should have been doing in the first place, and split the behaviour of the Instance class into two classes: Instance and Reference. The expression new SomeClass in a script then returns a Reference to a new Instance. The Instance objects themselves are never managed using a shared_ptr, so they are responsible for committing suicide in response to a suitable event, e.g., end of animation, end of level, etc. Thanks for the help! Refactoring is as good a solution as any if it Just Works.
You could add a static method to Instance that you then use to create new objects and that also does the administrative stuff like adding it to the set: static Instance* create(int something) { boost::shared_ptr<Instance> sptr(new Instance(something)); instanceset.insert(sptr); return sptr.get(); } If you want to make this the only way to construct an object of this class you could also make the normal constructor private or protected. For more on this see also the C++ FAQ Lite entry about "Dynamic binding during initialization", which is not directly related but uses the same technique to work around the restrictions on the use of virtual functions in constructors.
2,091,717
2,092,936
Basic C++ program crashes VS 2008
I'm following this tutorial on wrapping a .lib in a C++ DLL. Right after I use the VS wizard to generate a Win32 DLL project, everything compiles just fine. Then, following the tutorial, I substitute this VS-generated code: DEMODLL_API int fnDemoDll(void) { return 42; } for this code: DEMODLL_API int fnDemoDll(int a,int b) { return a+b; } When I then build, the VS 2008 SP1 IDE crashes. Google turned up several hits for this type of crash, but nothing that seems to apply. There is an entry in the event viewer related to the crash: Faulting application devenv.exe, version 9.0.30729.1, time stamp 0x488f2b50, faulting module VCProjectEngine.dll, version 9.0.30729.1, time stamp 0x488f2e94, exception code 0xc0000005, fault offset 0x0003dd11, process id 0x1f80, application start time 0x01ca98d27f9c8b85. UPDATE: I recreated the project, compiled it was fine, changed return 42; to return 43; and VS crashed again.
The exact code is probably irrelevant. It's the IDE, not the compiler that crashes. Can you start the build in another way?
2,091,788
2,091,811
How to make a PInvoke friendly native-API?
How to make a native API to be PInvoke friendly? there are some tips on how to modify native-programs to be used with P/Invoke here. But before I even write a native programs, what are the things I should look out to make my programs/library PInvoke friendly? using C or C++ are fine. update: if I write a C API, what are the things I have to do so that It is P/Invoke-able using C# syntax like the following: [DLLimport("MyDLL.dll")] is it possible to do the same with native C++ code/library? Summary/Rephrase of Some Tips to make a P/Invoke friendly native-API: + the parameters should be of native types (int, char*, float, ...) + less parameters is better + if dynamic memory is allocated and passed to managed code, make sure to create a "cleaner" function which is also p/invoked + provide samples and/or unit tests that illustrate how to call the API from .NET + provide C++/CLI wrapper
By definition every native function can be p/invoked from managed code. But in order to be p/invoke friendly a function should have as few parameters as possible which should be of native types (int, char*, float, ...). Also if a function allocates memory on some pointer that is returned to managed code, make sure you write its counter part that will free the pointer as managed code cannot free memory allocated from unmanaged code.
2,091,813
2,102,976
Embedded Assembly Files in Visual Studio
I'll make this short and to the point. The _asm block has been completely stripped when creating 64 bit code in Visual Studio. My question is, where can I find some information on how to use assembly in some code that I can call from my project. Like an assembly file I suppose that has some "optimized" function in which I can call directly in my C++ source.
One approach is to write a C template for your assembler function, then use /FAs to generate assembler source for that function template. You should then be able to use the generated assembler source in place of the C template source and build from there. That way you take care of all the messy error-prone ABI stuff automagically.
2,091,824
2,092,679
C++ syntax to call templated inner class static member function?
I have some template code which compiles fine in VC9 (Microsoft Visual C++ 2008) but won't compile in GCC 4.2 (on Mac). I'm wondering if there's some syntactical magic that I'm missing. Below I have a stripped-down example which demonstrates my error. Sorry if this example seems meaningless, I removed as much as I could to isolate this error. In particular I have a template class S which has an inner class R which is also a template class. From a top-level template function foo, I am trying to call R::append which is a static member function of R: template< typename C > struct S { template< typename T > S<C> & append( const T & ) { return *this; } template< int B > struct R { template< typename N > static S<C> & append( S<C> & s, const N ) { return s.append( 42 ); } }; }; template< typename C > S<C> & foo( S<C> & s, const int n ) { S<C>::R<16>::append( s, n ); // error: '::append' has not been declared return s; } Anyone out there know what I'm doing wrong?
Having use both Visual Studio and gcc, it's a known issue :) And I used VS2003 and gcc 3.4.2 so it's been like that for a while. If I remember correctly, the problem is due to the way templates are parsed on these compilers. gcc behaves as stated by the standard, and performs 2 parses: the first when encountering the template, without any information on the types, at this point it necessitates some typename and template magic to help understand what's going on a second when actually instantiating the template with a given type on the other hand, VS only does one parse, at instantiation, and therefore can fully resolve the symbols without typename and template here and there. You have the same thing for methods: template <class Item> struct Test { template <class Predicate> void apply(Predicate pred); void doSomething { this->apply(MyPredicate()); } // Visual Studio void doSomething { this->template apply(MyPredicate()); } // gcc }; // struct Test On the same topic, if you do something like: template <class Item> struct Test { static const std::string Name; }; You need to actually define this static attribute for each instantiation of the template, or you'll have an undefined symbol. VS accepts this syntax: const std::string Test<MyType>::Name = "MyType"; But gcc asks for a little keyword: template <> const std::string Test<MyType>::Name = "MyType"; You may think of VS as better since it asks less of you, but on the other hand gcc may warn you of mistakes in your template methods / classes as soon as it parses them the first time (ie without any actual instantiation) and personally, the sooner the better. Obviously, the good news is that if compiles on gcc (for these issues), it will also compile fine on Visual Studio. Since I am not a standardista though, I am not sure whether or not the standard actually demands or advises the 2-parses scheme.
2,091,833
2,091,877
C++: making shallow copy of an object a) syntax b) do i need to delete it
I have a class MyClassA. In its constructur, I am passing the pointer to instance of class B. I have some very basic questions related to this. (1) First thing , is the following code correct? ( the code that makes a shallow copy and the code in methodA()) MyClassA::MyClassA(B *b){ this.b = b; } void MyClassA::methodA(){ int i; i = b.getFooValue(); // Should I rather be using the arrow operator here?? // i = b->getFooValue() } (2) I am guessing I don't need to worry about deleting memory for MyClassA.b in the destructor ~MyClassA() as it is not allocated. Am I right? thanks Update: Thank you all for your answers! MyclassA is only interested in accessing the methods of class B. It is not taking ownership of B.
1) this.b = b; Here you pass a pointer to an instance of B. As Mac notes, this should be: this->b = b; b.getFooValue(); This should be b->getFooValue(), because MyClassA::b is a pointer to B. 2) This depends of how you define what MyClassA::b is. If you specify (in code comments) that MyClassA takes over ownership over the B instance passed in MyClassA's constructor, then you'll need to delete b in MyClassA's destructor. If you specify that it only keeps a reference to b, without taking over the ownership, then you don't have to. PS. Regrettably, in your example there is no way to make ownership explicit other than in code documentation.
2,092,045
2,092,686
Creating Java object with boost::posix_time::ptime serialized XML representation
I have following XML generated by serializing a boost::posix_time::ptime structure. I want to create a Java Date object with this XML. <timeStamp class_id="0" tracking_level="0" version="0"> <ptime_date class_id="1" tracking_level="0" version="0"> <date>20100119</date> </ptime_date> <ptime_time_duration class_id="2" tracking_level="0" version="0"> <time_duration_hours>11</time_duration_hours> <time_duration_minutes>53</time_duration_minutes> <time_duration_seconds>33</time_duration_seconds> <time_duration_fractional_seconds>0</time_duration_fractional_seconds> </ptime_time_duration> </timeStamp> Below is the Java code that is supposed to construct Date object by de-serializing this XML. Problem that I am facing is how to break the <date> tag into year/month/day sequence. Integer date = timeStamp.getPtimeDate().getDate(); Integer hrs = timeStamp.getPtimeTimeDuration().getTimeDurationHours(); Integer mins = timeStamp.getPtimeTimeDuration().getTimeDurationMinutes(); Integer secs = timeStamp.getPtimeTimeDuration().getTimeDurationSeconds(); Calendar cal = Calendar.getInstance(); //TODO //cal.set(year, month, day, hrs, mins, secs); Date date = cal.getTime(); Any hints? EDIT: I am looking for some elegant solution that doesn't require converting date to a string and then splitting it. That would be my last resort. Thanks
As you don't want to use a String (though I urge you to reconsider, after all that's what it is and easier to parse too), I guess you can do regular old division to extract parts. i.e. int tmp = date; // unboxing int year = tmp / 10000; int month = (tmp % 10000) / 100; int day = tmp % 100; That's not very elegant either. The best way to handle this would be to instruct whatever you're using to deserialize to give you back a String for date instead of an Integer. Then you can just take the first four characters for your, next two for month and last two for day. SimpleDateFormat can do the heavy lifting here.
2,092,141
2,092,224
PDB file from different versions of Visual Studio
I have an old DLL file which was built with VC++ 6. Now I need to investigate the dump file but I don't have its PDB available. The stacktrace reported by WinDbg is also inaccurate. Is it possible to rebuild the project with later versions of Visual Studio i.e. 2003, 2005, 2008, have the PDB generated, and use this to map addresses to symbols in the old DLL? Is there something like VC 6.0 compatible mode for building project? Obtaining VC++ 6 is one option, but it looks like VS6.0 has already vanished from MSDN subscriber download page :( Thanks!
I'm afraid I think the answer is no: you'll need to try and rebuild it with the same tool-chain exactly as the binary that generated the dump file you have. VS is really fussy about how it matches dump files to pdb files in my experience: the only luck I've ever had in these situations is with WinDbg (but you've tried that)/
2,092,244
2,092,293
g++ and file read, weird behaviour with Xcode/Snow Leopard
I am writing a program that reads a file, whose first two lines are: Field of space: 0.4 226981 20 Then I want to pass 226981 and 20 to integer variables. So I do: ifstream vfile(file_name, ios::in); vfile.getline(header,FILENAME); // Read the header-line vfile >> nTot >> file_size; If I compile the program with g++; I get for nTot and file_size the right values, 226981 and 20, but If do it for Mac OS X Snow Leopard with the last Xcode, I get 0 and 1634000000 respectively. Has anyone experienced this kind of error?
This might be the _GLIBCXX_DEBUG issue - make sure you have the latest Xcode installed, that _GLIBCXX_DEBUG is set the same for all your code and libraries, and you might also want to check the xcode-users mailing list.
2,092,283
2,092,419
How functions are resolved by compiler?
How it is determined whether the below call is bound at compile time or at runtime? object.member_fn;//object is either base class or derived class object p->member_fn;//p is either base class or derived class pointer EDITED: #include <iostream> using namespace std; class Base { public: Base(){ cout<<"Constructor: Base"<<endl;} ~Base(){ cout<<"Destructor : Base"<<endl;} }; class Derived: public Base { //Doing a lot of jobs by extending the functionality public: Derived(){ cout<<"Constructor: Derived"<<endl;} ~Derived(){ cout<<"Destructor : Derived"<<endl;} }; void foo() { Base & Var = Derived(); Base*pVar = new Derived; delete pVar; } void main() { foo(); std::cin.get(); } out put: Constructor: Base Constructor: Derived Constructor: Base Constructor: Derived Destructor : Base // the Derived is not called, // the PVal is of type Base* and the fn is not virtual //so compile time binding Destructor : Derived Destructor : Base
If the method is not virtual, both calls will be resolved at compile time. If the method is virtual then the first call in your question (obj.method()) will be resolved at compile time for an object, but at runtime for a reference. The second call (objp->method()) will be resolved at runtime. You can also force at compile time to call the non-derived version of a method. struct base { void f(); virtual void v(); }; struct derived : public base { void f(); void v(); // intentionally left virtual out, it does not really matter }; int main() { derived d; base & b = d; base * bp = &d; // compile time: d.f(); // derived::f d.v(); // derived::v b.f(); // base::f -- non-virtual bp->f(); // base::f -- non-virtual // runtime: b.v(); // derived::v bp->v(); // derived::v // compile time (user forced): b.base::v(); // base::v bp->base::v(); // base::v }
2,092,378
2,164,689
MacOSX: How to collect dependencies into a local bundle?
I am creating a plugin application (dylib) that depends on several other libraries. These other libraries are installed on my system, but are not guaranteed to be installed on any user's system. So I need to find a way bundle the dependencies along with my application. I found that I can use otool to list or change the paths to other dylibs. This would allow to create a folder that bundles my plugin application and all needed dependencies. However, doing this manually seems like a time-consuming and dumb task. Are there utilities available to automate it? Or perhaps I'm doing it wrong and there is a better and more obvious approach for this problem? Edit I created a script that automates most the task.
Use relative paths in your dylib using install_name_tool. That way you can set them once, and install that directory anywhere without needing to modify your libraries at install time. You should place all of your dylib dependencies into one folder, then use install_name_tool to set the relative location of the other dylibs you depend on. Suppose your library libmyfoo.dylib depends on libbar.dylib: install_name_tool -change "/Whatever/full/path/libbar.dylib" "@loader_path/libbar.dylib" libmyfoo.dylib This way, your library will always look for libbar.dylib in the same directory where libmyfoo.dylib is located. You might also need to run install_name_tool on some of the other dylibs, if they depend on one another. Beware, the documentation for install_name_tool points out that "For this tool to work when the install names or rpaths are larger the binary should be built with the ld(1) -headerpad_max_install_names option.", so be sure to include the -headerpad_max_install_names command line option when building your library. @loader_path is relative to the binary used to load the dylib, in this case your libmyfoo.dylib. Use @executable_path if you want to find the libraries relative to executable that started the library loading sequence.
2,092,640
2,092,670
What's the difference between ON_NOTIFY, ON_CONTROL, ON_CONTROL_REFLECT?
I always struggle to keep all these macros straight in my head. Is there an easy way to remember them, and which to use in a given scenario? Specifically, does one of these allow a dialog to intercept/detect messages to child control windows? e.g Can the dialog register an interest when IDC_MY_CONTROL gets a WM_PAINT message?
ON_NOTIFY handles WM_NOTIFY messages. ON_CONTROL handles WM_COMMAND messages from controls. ON_CONTROL_REFLECT is for handling messages sent to a parent from the child class.
2,092,728
2,092,755
Find address of variables in main?
Recently while surfing some C++ blogs, I came across a small C teaser program in one of them. #include<stdio.h> int find_addr() { /*fill your code here*/ } int main() { int i,j; clrscr(); find_addr(); return 0; } The question is to find the address of variables i & j without touching the main function. I haven't been able to figure it out yet. Feels awful that I couldn't even solve this minor question :((. EDIT: The above program had lot of non-standard statements like the use of inclusion of conio.h anbd other non standard headers and its functions , getch() and other statements, I edited it in a hurry and forgot to omit void from void main(), apologies for that. EDIT2: I have given my one vote to close this thread since I perceive through the responses posted here that there are non-standard issues related to the question.
I think I found where you read the puzzles. Most of the programs use typeless main(), or worse, void main(). They assume a lot of system- and/or compiler-specific things. The programs on the page are not very good quality, and make for a bad tutorial. Please stay away from it. For example, this is the first program: what is the output? Definitely the output is not what you think! so think more.. main() { int i = 300; char *ptr = &i; *++ptr = 2; printf("%d",i); getch(); } Third program: what is the output of the following code if array name starts with 65486? void main() { int num[] = {10,11,12,13}; printf("%u %u",num,&num); } I could go on, but there is no need really. As I said, stay away from this page!
2,093,039
2,093,097
Math question in regards to functions in the form (1) / ( b ^ c )
I've found functions which follow the pattern of 1 / bc produce nice curves which can be coupled with interpolation functions really nicely. The way I use the function is by treating 'c' as the changing value, i.e. the interpolation value between 0 and 1, while varying b for 'sharpness'. I use it to work out an interpolation value between 0 and 1, so generelly the function I use is as such: float interpolationvalue = 1 - 1/pow(100,c); linearinterpolate( val1, val2, interpolationvalue); Up to this point I've been using a hacked approach to make it 'work' since when interpolation value = 1 the value is very close to but not quite 0. So I was wondering, is there a function in the form of or one which can reproduce similar curves to the ones produced by 1 / bc where at c = 0 result = 1 and c = 1 result = 0. Or even C = 0, result = 0 and C = 1 result = 1. Thanks for any help!
For interpolation the approach offering the most flexibility is using splines, in your case quadratic splines would seem sufficient. The wikipedia page is math heavy, but you can find adapted desciptions on google.
2,093,057
2,093,065
Using wmemset in c++
While using wmemset api (http://msdn.microsoft.com/en-us/library/1fdeehz6(VS.80).aspx) for the count parameter should I have to multiply the length of the target string by 2 and provide or will wmemset will itself take care of the conversion?
The answer is no. They have an example on the page you linked to: #include <wchar.h> #include <stdio.h> int main( void ) { wchar_t buffer[] = L"This is a test of the wmemset function"; wprintf( L"Before: %s\n", buffer ); wmemset( buffer, '*', 4 ); wprintf( L"After: %s\n", buffer ); } Output: Before: This is a test of the wmemset function After: **** is a test of the wmemset function Of course, the destination must have enough space (sizeof(wchar_t) times the number of characters being written to).
2,093,175
2,093,225
Using a STL container to store Treeview data
i'm looking for a C++ STL container class to keep the treeview parent/child node strings but when a node is deleted from tree control, do i have iterate through all the container class elements to find that selected one and then delete it? what's the best to keep the data updated in container?
use STL set, which is efficient in operations like insert and delete in O(log n) time. e.g. set<TreeNode> a; a.insert(aTreeNode); // insert a.erase(aTreeNode); // delete
2,093,212
2,093,265
Using templates to make items of varying length stay on stack?
The situation is that I have an array of items, and the items have an array inside. However, I want to make the array inside of variable length at declaration time, yet resizable at compile time. So I would want something like: class2<16>[] = new class2<16>[2048*1024]; Or whatever. Hopefully you get the idea. Obviously making it have fixed array inside is easy, but the problem is the array can be HUGE so I don't want to have 2048*1024 calls to new, so I definitely don't want class2 to call any new or delete methods. Is this even possible?
You can create a template parameter for your internal array-size. For example:- template<int siz> class Item{ int arr[siz]; }; int main() { Item<15> items[10]; return 0; }
2,093,409
2,096,440
How to insert data into a TdxMemData in Borland Builder
I'm struggling to insert data into a TdxMemData which is linked to a grid by a TDataSourse. The MemData -called PurchaseData- has 3 columns: Date (date), Place (string) and Value (currency). I have a button that does the following: PurchaseData->Insert(); PurchaseData->FieldByName("Date")->Value = TDateTime::CurrentDate().DateString(); PurchaseData->FieldByName("Place")->Value = ""; PurchaseData->FieldByName("Value")->Value = 0.0f; PurchaseData->Post(); Clicked once, it inserts a row normally and the data appears in a new row of the grid, but when clicking the button again I get a popup on the Insert() saying "Could not convert variant of type (Null) into type (String)". I'm worried about the fact that the property "KeyFields" of the columns shows in its combo the field "RecId" besides the other 3 fields. I don't remember creating any column called RecId and if I did, I removed it. I can't figure out what it is and could not find help neither.
I had mapped the event OnSelectionChanged of the grid and read the data in the newly selected row. Unfortunately when PurchaseData->Insert() is called, the SelectionChanged event is fired right away. before the new row's data is set by the next lines. I got Null from the data read and did Bad Things with it like setting an edit->Text with it, thus the message in the popup.
2,093,467
2,097,548
Treeview selected item index
is there anyway to get the index of selected tree view node or do they even have one?
Since you're asking for "index" only to be able to find data associated with this item you should know that tree control can hold your data. Every item (TVITEM struct) has a lParam member that you can use for this. If you really need a container do as avakar suggested. Use HTREEITEM as key.
2,093,672
2,093,706
Can I prevent object assignment?
I want to ensure that the following type of call is illegal: MyClass me; MyClass you; me = you; // how to make this illegal? Is it possible?
Declare the assignment operator private: class A { private: void operator=(const A&); ... }; but don't provide an implementation - you will get a compile or link-time error if you try to perform an assignment to A. I prefer to use a macro to do this. This also prevents copying, by making the copy constructor private too: #define CANNOT_COPY( class ) \ private: \ class(const class&); \ void operator=(const class &) \ I can then say things like: class A { CANNOT_COPY( A ); ... }; which is easy to read and easy to search for.
2,093,740
2,093,815
My wxFrame has a small thin 1 px border around it even though I asked for no border. Why?
Using wxwidgets. I want a window without a border. I pass the follwoing flags to the frame wxFRAME_NO_TASKBAR | wxSTAY_ON_TOP but it still draws a black outline 1 px wide around the window. Is this a bug or something?
You must also set wxBORDER_NONE.
2,094,032
2,100,744
Configure .NET-Based Components for Registration-Free Activation
I've been trying to get a registration-free .NET based COM DLL to work, but without success. In Visual Studio 2008 I added a new C# class library. I enabled the 'make assembly COM-visible' and 'register for COM interop' options. I added a public interface and class with some functions. I added a manifest dependency to my C++ client application: #pragma comment(linker,"/manifestdependency ... But when I start my application I get 'the application has failed to start because the application configuration is incorrect'. I've used Microsoft's mt tool to extract the manifest files of both the C++ client application and the C# COM DLL and the information in both is the same (the dependentAssembly in the C++ manifest file contains the same name and version as the assemblyIdentity in the COM manifest file). I've also tried the approach described on http://msdn.microsoft.com/en-us/library/eew13bza.aspx but with similar results. Similarly I tried to add a reference to my COM project in 'Framework and References' of my C++ client application. The information on that property page looked promising (it shows options like 'copy local', 'copy dependencies', etc and properties like the 'assemblyIdentity'), but Visual Studio neither copies the DLLs nor adds a dependency to the manifest file automatically. Note that the 'registered variant' works fine. Anyone have any ideas of what I'm doing wrong? Update: When I create a simple C++ DLL and embed a manifest with the same name and version of my .NET COM DLL (same assemblyIdentity) my application starts up fine. So the problem lies with the manifest file of my .NET COM DLL. I can successfully extract the manifest from the DLL with mt -managedassemblyname:... and then embed the same manifest with mt -outputresource:..., but this also doesn't cause Windows to successfully resolve the dependency.
I found the steps needed to get registration-free .NET COM interop working myself :-) Run: mt -managedassemblyname:"myDll.dll" -out:"myDll.manifest" Clean manifest (see format at http://msdn.microsoft.com/en-us/library/eew13bza.aspx). Mainly I needed to remove all tags except for assemblyIdentity, clrClass and file (and specifically remove the runtime, mvid and dependency tags). Run mt -outputresource:"myDll.dll" -manifest "myDll.manifest". Basically this adds the modified manifest as a resource to the DLL. Note that this is apparently not the same manifest (location)! If I reextract the manifest with the managedassemblyname option I still get the 'old' manifest. If I extract it with the inputresource option I get the new one. I pretty much found this all thanks to Windows Vista. Unlike my Windows XP it contains a tool called sxstrace that gives rather detailed information about the problems with side-by-side execution.
2,094,072
2,094,214
Nested unnamed namespace?
When using an unnamed namespace are there any issues if it is nested within another namespace? For example, is there any real difference between Foo1.cpp and Foo2.cpp in the following code: // Foo.h namespace Foo { void fooFunc(); } // Foo1.cpp namespace Foo { namespace { void privateFunction() { ... } } void fooFunc() { privateFunction(); } } // Foo2.cpp namespace { void privateFunction() { ... } } namespace Foo { void fooFunc() { privateFunction(); } }
Unnamed namespace could be considered as a normal namespace with unique name which you do not know. According to C++ Standard 7.3.1.1: An unnamed-namespace-definition behaves as if it were replaced by namespace unique { /* empty body */ } using namespace unique; namespace unique { namespace-body } where all occurrences of unique in a translation unit are replaced by the same identifier and this identifier differs from all other identifiers in the entire program. There are no additional issues.
2,094,154
2,094,300
referenced argument to a function with default value in C++
Possible Duplicate: Default value to a parameter while passing by reference in C++ Is it possible to do something like this: // definition bool MyFun(int nMyInt, char* szMyChar, double& nMyReferencedDouble = 0.0); Then the function can be called either like this: MyFun(nMyInt, szMyChar, nMyReferencedDouble); or like this: MyFun(nMyInt, szMyChar); My compiler (VS 98) complains. Is there a way to do this?
You could overload the function instead. // Definition bool MyFun(int nMyInt, char* szMyChar, double& nMyReferencedDouble); // Overload bool MyFun(int nMyInt, char* szMyChar) { double nMyReferencedDouble = 0.0; MyFun( nMyInt, szMyChar, nMyReferencedDouble ); } This is how you get around the current limitations of no default values in C# and works equally well for semantic limitations in C++.
2,094,253
2,102,708
Editing PDF with XPDF (or with something else)
I would like to ask if it is possible to edit PDF files using the xpdf library and if yes how? I guess this is possible but i could not find any tutorial nor documentation for xpdf so i have realy no idea :( . I'm also open for using another library if any other has support for pdf editing. My only requirement for such library is that it has to be a C++ library or at least a C one and has to be cross-platform (Windows and Linux) I Only need basic editing of a pdf file for example: "this is a text in a pdf document" would be changed to "this is a text in pdf" with a different text color as well. Thanks for all your replies!
Just so you understand the scope of what you're getting into, "basic editing" of PDF content is nearly always non-trivial. Page content in PDF is represented by short RPN programs that paint on the page. It's a small language similar to PostScript in semantics, but without looping structures or function definitions (so there is no halting problem). In a sane world, your text on the page is going to be represented by something like this: BT /F1 12 Tf 72 720 Td (this is a text in a pdf document) Tj ET which when translated into something more familiar, is this: BeginText(); SetFont(F1, 12.0); // Font 1, 12.0 pt TextMoveTo(72, 720); ShowText("this is a text in a pdf document"); EndText(); So in this case, you have to transform this into something like this: BeginText(); SetFont(F1, 12.0); // Font 1, 12.0 pt TextMoveTo(72, 720); ShowText("this is a "); SetFont(F2, 12); ShowText("text"); SetFont(F1, 12); ShowText(" in a pdf document"); EndText(); which would become: BT /F1 12 Tf 72 720 Td (this is a ) Tj /F2 12 Tf (text) Tj /F1 12 Tf ( in a pdf document) Tj ET in the equivalent PDF. The problem is many-fold: You have to extract out the page and all its resources (non-trivial) You have to generate a new page, inserting new resources (you're adding a new font), embedding the font if allowable Alter the content stream of the page to include your changed content. And 3 is where you're going to get hung up, because there are an infinite number of ways to generate a page that has the content you describe and even with a decent library, you're going to have a hard time getting maybe 70% of them. Let me briefly describe why this is as bad as it sounds. There are PDF generation programs (I'm looking at you, troff) that lay all the plain text on a page first, then lay all the italic text, then all the bold text. I swear, I'm not making this up. Some programs want to lay text down very precisely, so if you're lucky, they'll use the TJ operator which lays out text with specific kerning. If you're not lucky (which is most of the time), they're instead lay out the text with a set of moves before every single glyph on the page. And what if your text is laid our on a curve or an unusual orientation (maps, ads)? What about the cases where someone subtly changes the font size for a greater distinction between upper and lower case or simulates small caps? This is why, when I wrote the find text tool for Acrobat 1.0, it took me two months of sweat to handle as many of the edge cases. This is not editing text - it's just trying to find a single word or phrase. I'm not going to recommend a library for you - sorry - I gave xpdf a brief look over and it's not clear whether or not it has PDF generation capabilities or if it is simply a consumer of PDF. PdfLib, which is a commercial product, appears to be to generate PDF, although it's not clear if it can consume it, but you could certainly get both sides by gluing them together. If it were me, I would use tools that I've developed and I'd still be a little shy of this task. My library is being used by Atalasoft, the company I work for, to generate PDFs from whole cloth and to do editing within a very limited domain (annotations, document metadata). The hardest part is that we do our very best to hide the complexity of PDF from our customers. In general, our customers want us to understand the spec instead of them and make the rest easy - but tasks like this (redaction is another one), are really hard to do without understanding the depth of the PDF specification. If you start entering the library world of PDF manipulation, you should start with reading the spec, especially chapter 8 (Graphics) and chapter 9 (Text), and you'll get a better understanding of what you're going to have to do with the library.
2,094,366
2,094,412
C++: Printing ASCII Heart and Diamonds With Platform Independent
I'm developing a card playing game and would like to print out the symbol for hearts, diamonds, spades and clubs. My target platform will be Linux. In Windows, I know how to print out these symbols. For example, to print out a heart (in ASCII) I wrote... // in Windows, print a ASCII Heart #include <iostream> using std::cout; using std::endl; int main() { char foo = '\3'; cout << heart << endl; system ( "PAUSE" ); return 0; } However, as I alluded to, a heart symbol won't be printed in Linux. Is there a standard library that can be used to print out a symbol for hearts, diamonds, spades and clubs in both Linux and Windows? What I have been researching so far is looking at Unicode since it is my understanding this is universal.
If you want a portable way, then you should use the Unicode code points (which have defined glyphs associated to them): ♠ U+2660 Black Spade Suit ♡ U+2661 White Heart Suit ♢ U+2662 White Diamond Suit ♣ U+2663 Black Club Suit ♤ U+2664 White Spade Suit ♥ U+2665 Black Heart Suit ♦ U+2666 Black Diamond Suit ♧ U+2667 White Club Suit Remember that everything below character 32 in ASCII is a control character. They have a meaning associated with them and you don't have a guarantee of getting a glyph or a behavior there (even though most control characters to have glyphs, although they were never intended to be printable). Still, it's not a safe bet. However, using Unicode needs proper font and encoding support which may or may not be a problem on UNIX-likes. On Windows at least some of the above code points map to the ASCII control character glyphs you're outputting if the console is set to raster fonts (and therefore not supporting Unicode or anything else than the currently set OEM code page). This only applies to the black variants since the white ones have no equivalent.
2,094,427
2,095,209
DLL : export as a C/C++ function?
I generated a DLL in Visual from a C++ code. Dependency Walker sees 3 functions exported as C functions. I made an SCons project to do the generate the DLL, and 2 of the 3 functions are not seen as C functions. What makes a function seen as a or C++ function, without modifying the code ? It must be in the compilation/linking options, but I didn't find any relevant thing. The function are prefixed by a macro : AM_LIB_EXPORT In the .h, I have : #ifdef _WIN32 #define AM_LIB_EXPORT __declspec(dllexport) #else #define AM_LIB_EXPORT #endif // _WIN32 Thanks.
What makes a function seen as a or C++ function, without modifying the code ? A function compiled by a C++ compiler is automatically a 'C++-function' and name-mangling occurs to resolve C++ features such as namespaces and overloading. In order to get 'C' export names, one must use the aforementioned extern "C" qualifier in the function declaration. Alternatively a huge extern "C" { .. } block around the header containing the prototypes. If this does not solve your issue, its maybe related to dllimport/dllexport. If you #define AM_LIB_EXPORT __declspec(dllexport) in your DLL build, you'll typically also need to make it dllimport for apps linking against your DLL in order for the linker to know where to fetch the symbols from.
2,094,717
2,094,743
Do these two classes violate encapsulation?
class X { protected: void protectedFunction() { cout << "I am protected" ; } }; class Y : public X { public: using X::protectedFunction; }; int main() { Y y1; y1.protectedFunction(); } This way I am able to expose one of the functions of the base class. Doesn't this violate the encapsulation principle? Is there a specific reason as to why this is in standard? Is there any uses of this, or is it going to be changed in the new standard? Are there any open issues related to this in the standard?
Yes it does and that's why protected has received a fair share of criticism. Bjarne Stroustrup, the creator of C++, regrets this in his excellent book The Design and Evolution of C++: One of my concerns about protected is exactly that it makes it too easy to use a common base the way one might sloppily have used global data....In retrospect, I think that protected is a case where "good arguments" and fashion overcame my better judgement and my rules of thumb for accepting new features.
2,094,776
2,094,791
Is It Possible To Do The Following In A Switch Statement - C++?
I am a programming student in my second OOP class, and I have a simple question that I have not been able to find the answer to on the internet, if it's out there, I apologize. My question is this: Is it possible have Boolean conditions in switch statements? Example: switch(userInputtedInt) { case >= someNum && <= someOtherNum break; // Is this possible? }
No this is not possible in C++. Switch statements only support integers and characters (they will be replaced by their ASCII values) for matches. If you need a complex boolean condition then you should use an if / else block
2,095,223
2,095,401
Better C++ syntax for template base class typedefs and functions?
I have code that compiles fine with VC9 (Microsoft Visual C++ 2008 SP1) but not with GCC 4.2 (on Mac, if that matters). If I pile on enough qualifiers and keywords I can force it to work in GCC but this doesn't seem right. Here's a minimal code sample exhibiting my problems: template< typename N > struct B { typedef N n_type; // can derived class access typedef? void foo() {} // can derived class access function? }; template< typename N > struct D : public B<N> { typedef B<N> b_type; typedef typename b_type::n_type bn_type; void f1( n_type ) {} // ERROR: 'n_type' has not been // declared void f2( typename B<N>::n_type ) {} // OK, verbose void f3( b_type::n_type ) {} // ERROR: 'struct B<N>::n_type' is // not a type void f4( typename b_type::n_type ) {} // OK, verbose void f5( bn_type ) {} // OK, verbose typedefs void f6() { foo(); } // ERROR: there are no arguments to // 'foo' that depend on a template // parameter, so a declaration of // 'foo' must be available void f7() { b_type::foo(); } // OK, verbose }; Am I wrong to expect a template class derived from another template class to be able to use inherited typedefs and functions directly? Is there a better way to do this than what I've come up with so far?
Am I wrong to expect a template class derived from another template class to be able to use inherited typedefs and functions directly? Yes, this will not generally work as you expect it. The C++ name lookup rules specify that a name is only searched in a templated base classes if it depends on a template parameter (if it is a "dependent name"). If a name does not depend on a template parameter it isn't searched there. (Also see this C++ FAQ Lite entry) To call functions from a dependent base class the most easy way is to use this->, since this is always implicitly a dependent name: void f6() { this->foo(); }
2,095,277
2,095,368
Difference between C++ and Java compilation process
Possible Duplicate: Why does C++ compilation take so long? Hi, I searched in google for the differences between C++ and Java compilation process, but C++ and Java language features and their differences are returned. I am proficient in Java, but not in C++. But I fixed few bugs in C++. From my experience, I noticed that C++ always took more time to build compared to Java for minor changes. Regards Bala
There are a few high-level differences that come to my mind. Some of those are generalizations and should be prefixed with "Often ..." or "Some compilers ...", but for the sake of readability I'll leave that out. C/C++ compilation doesn't read any information from binary files, but reads method/type definitions only from header files that need to be parsed in full (exception: precompiled headers) C/C++ compilation includes a pre-processor step that can do a wide array of text-replacement (which makes header pre-compilation harder to do) The C++ syntax is a lot more complex than the Java syntax The C++ type system is a lot more complex than the Java type system C++ compilation usually produces native assembler code, which is a lot more complex to produce than the relatively simple byte code C++ compilers need to do optimizations because there isn't any other thing that will do them. The Java compiler pretty much does a simple 1:1 translation of Java source code to Java byte code, no optimizations are done at that step (that's left for the JVM to do). C++ has a template language that's Turing complete! (so strictly speaking C++ code needs to be run to produce executable code and a C++ compiler would need to solve the halting problem to tell you if arbitrary C++ code is compilable).
2,095,363
2,095,820
C++ application - should I use static or dynamic linking for the libraries?
I am going to start a new C++ project that will rely on a series of libraries, including part of the Boost libraries, the log4cxx or the google logging library - and as the project evolves other ones as well (which I can not yet anticipate). It will have to run on both 32 and 64 bit systems, most probably in a quite diverse Linux environment where I do not expect to have all the required libraries available nor su privileges. My question is, should I build my application by dynamically or statically linking to all these libraries? Notes: (1) I am aware the static linking might be a pain during development (longer compile times, cross-compiling for both 32 and 64 bit, going down dependency chains to include all libraries, etc), but it's a lot easier during testing - just move the file and run. (2) On the other hand, dynamic linking seams easier during development phase - short compile times, (don't really know how to handle dynamic linking to 64 bit libraries from my 32 bit dev environment), no hustle with dependency chains. Deployment of new versions on the other hand can be ugly - especially when new libraries are required (see condition above of not having su rights on the targeted machines, nor these libraries available). (3) I've read the related questions regarding this topic but couldn't really figure out which approach would best fit my scenario. Conclusions: Thank you all for your input! I will probably go with static linking because: Easier deployment Predictable performance and more consistent results during perf. testing (look at this paper: http://www.inf.usi.ch/faculty/hauswirth/publications/CU-CS-1042-08.pdf) As pointed out, the size and duration of compilation of static vs. dynamic does not seem to be such a huge difference Easier and faster test cycles I can keep all the dev. cycle on my dev. machine
Static linking has a bad rap. We have huge hard drives these days, and extraordinarily fat pipes. Many of the old arguments in favor of dynamic linking are way less important now. Plus, there is one really good reason to prefer static linking on Linux: The plethora of platform configurations out there make it almost impossible to guarantee your executable will work across even a small fraction of them without static linking. I suspect this will not be a popular opinion. Fine. But I have 11 years experience deploying applications on Linux, and until something like LSB really takes off and really extends it's reach, Linux will continue to be much more difficult to deploy applications on. Until then, statically link your application, if you have to run across a wide range of platforms.
2,095,398
2,095,433
C++ passing arrays to a method problem
Hey there I have this function: void vdCleanTheArray(int (*Gen_Clean)[25]) { } I wanted to know what kind of array does it accepts and clear it. Sorry, I have a little knowledge in c++, someone just asked me. Thanks!
It accepts an array declared as int array[25]; which should be passed "by pointer", i.e. by applying the & operator to the array vdCleanTheArray(&array); As for how to clean it... As I understand, it is the above function that should clean it and you are supposed to write it, right? Well, inside the function you access the array by using the dereference operator * as in (*Gen_Clean)[i] and you just "clear" it as you would clear any other array. Depends on what you mean by "clear". Fill with zeros? If so, then just write a cycle from 0 to 24 (or to sizeof *Gen_Clean / sizeof **Gen_Clean) that would set each element to zero.
2,095,465
2,095,603
Calling managed c++ directly from C# failed
Having A.dll which is a managed c++ project (no other dependencies) From B.dll which is a C# project where A.dll is referenced having a Nunit method foo(). If calling the managed c++ code from foo() I got FileNotFoundException:The specified module could not be found. (Exception from HRESULT: 0x8007007E). I tried to change B.dll to console application and the same exception occurs. If I'm wrapping the managed c++ code in some other c# class in B.dll and then calling the wrapper from foo() everything works just fine. The managed C++ is a static class where all of the functions arguments are managed types. Ideas? Thanks, Guy
This is not a managed DLL loading error, you can't see it in Fuslogvw.exe. I'd guess at an unmanaged DLL dependency for C++/CLI assembly that cannot be located. You'll be able to see Windows searching for the DLL with SysInternals' ProcMon utility.
2,095,759
2,095,782
C++: Constructor versus initializer list in struct/class
An object of a struct/class (that has no constructor) can be created using an initializer list. Why is this not allowed on struct/class with constructor? struct r { int a; }; struct s { int a; s() : a(0) {} }; r = { 1 }; // works s = { 1 }; // does not work
No, an object with a constructor is no longer considered a POD (plain old data). Objects must only contain other POD types as non-static members (including basic types). A POD can have static functions and static complex data members. Note that the upcoming C++ standard will allow you to define initializer lists, which will allow non-POD objects to be initialized with braces.
2,095,977
2,095,994
To Mutex or Not To Mutex?
Do I need a mutex if I have only one reader and one writer? The reader takes the next command (food.front()) from the queue and executes a task based on the command. After the command is executed, it pops off the command. The writer to the queue pushes commands onto the queue (food.push()). Do I need a mutex? My reader (consumer) only executes if food.size() > 0. I am using a reader thread and send thread.
A mutex is used in multi-threaded environments. I don't see mention of threads in your question, so I don't see a need for a mutex. However, if we assume by reader and writer you mean you have two threads, you need to protect mutual data with a mutex (or other multi-threaded protection scheme.) What happens when the queue has items, and the reader thread pops something off while the writer thread puts something on? Disaster! With a mutex, you'll be sure only one thread is operating on the queue at a time. Another method is a lock-free thread-safe queue. It would use atomic operations to ensure the data isn't manipulated incorrectly.
2,096,084
2,096,128
Designing Thread Class
I have a design question. Is it better to define separate classes for SENDING and RECEIVING. Or, is it better to define a single Thread class? I like the idea of a single Thread class because it is easier to share a queue which can be locked by mutex. Design Option #1 (Separate): mySendThread = new SendThread(); // Have thread properties and separate members myRcvThread = new RcvThread(); // Have thread properties and separate members Design Option #2 (Master): Master thread - Execute() { if (threadType == RCV_THREAD) { globalVar = new MasterThread(serialPortHandle); } while (!Terminated) { if (threadType == RCV_THREAD) { if(globalVar) { // do work } } if (threadType == SND_THREAD) { tCountSnd = GetTickCount() / SND_THREAD_DELAY; if (tCountSnd != tCountSnd2) { tCountSnd2 = tCountSnd; if (globalVar) { // do sending work } } } } }
I've designed a thread for communicating on the serial port (in Python, not C++, but it doesn't matter much) as follows: There's a single thread and two queues - one for sent and one for received messages. The thread always listens (asynchronously) on both the serial port (for received data) and the sending queue (to send stuff the application asks to send). If data arrived on the serial port, it's placed in the receive queue for the application's use If the application placed data into the send queue, the thread sends it down the serial port This design makes more sense to me because the single resource (the serial port) is held by a single thread, and not shared by two. Breaking it to several classes sounds like an overkill to me, since reading/writing from queues and reading/writing from the serial port is a trivial operation (naturally the serial port is wrapped in a convenient class - by the way I really recommend this class by Ramon De Klein) Oh, and it works very well.
2,096,381
2,096,403
invalid conversion from 'int' to 'int*'
I was looking for solving a LCS problem (Longest common subsequence) and I tried to make my own code in c++ by referring to the explanation and the pascal code given at wikipedia. My final result was this: #include <iostream> #include <algorithm> using namespace std; int LCS(int a[100], int b[100], int m, int n); int main() { int n, m, i, k, x[100], y[100]; cout << "n i m: " << endl; cin >> n >> m; cout << "n array: " << endl; for(i=1;i<=n;i++) cin >> x[i]; cout << "m array: " << endl; for(i=1;i<=m;i++) cin >> y[i]; k = LCS(x[100], y[100], m, n); cout << k << endl; return 0; } int LCS(int a[100], int b[100], int m, int n) { int c[m][n], i, j; for(i=0;i<=m;i++) c[i][0] = 0; for(i=0;i<=n;i++) c[0][i] = 0; for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { if(a[i] == b[j]) { c[i][j] = c[i-1][j-1]+1; } else c[i][j] = max(c[i][j-1], c[i-1][j]); } } return c[m][n]; } I tried to compile it via g++ and i got an error: 3.cpp: In function 'int main()': 3.cpp:19: error: invalid conversion from 'int' to 'int*' 3.cpp:19: error: initializing argument 1 of 'int LCS(int*, int*, int, int)' 3.cpp:19: error: invalid conversion from 'int' to 'int*' 3.cpp:19: error: initializing argument 2 of 'int LCS(int*, int*, int, int)' I'm not really into c/c++ programming, and i want to know where is my mistake, why it happens and how to fix it. Thank you.
Just pass the array name. This LCS(x, y, m, n); not this LCS(x[100], y[100], m, n);
2,096,450
2,096,531
Putting a string or int back on the front of cin
I have a problem where I get an int as input at the wrong time in my c++ program, so I need to "put it back" on cin later. However the closest thing I can find to do this is the pushback function for istreams. This sadly is only for characters and using multiple characters seems to separate them. Is there a good way to put a piece of input back on the front of cin? Thanks. edit The reason for this is that I am using a graph class that uses the >> operator for input, but the first piece of input has to be the number of edges. I was hoping to leave the graph class alone and just give cin the number of edges myself. So basically the only piece of input that is out of order is the first int that gets sent from cin.
If you are using a seekable input (such as a file), you can use seekg. Unfortunately, this won't work for non-seekable streams (such as a pipe or human input).
2,096,596
2,096,697
MFC dialog buttons show up as black boxes
I have an old MFC utility written with VS2008 project. We have used this utility for a few years now and I have never experienced this problem personalty but it is showing up more and more often on customers computers. Sub dialogs launched from my main dialog will have their buttons blackened out. I have included a screenshot from one of my customers computers. (source: chipkin.com) The customer is using Microsoft Windows XP Professional Version 2002 Service Pack 3. I have tested this problem with this version of Windows in our lab with out being able to reproduce it. This problem has happened on lots of different peoples computers. Do you know what causes it? and how to resolve it?
I've seen this when the machine was out of memory. It didn't have enough RAM left to load the button images.
2,096,668
2,097,348
What was the most useful time you used a pointer-to-pointer and/or reference-to-pointer in a c/c++ project?
Pointers-to-pointers and references-to-pointers seem overly complicated at first, especially for newbies. What is the best and most useful reason you used one in a c/c++ project you worked on? This can help people better understand pointers and how to use them effectively. Edited: Included C as well as C++
Since no one has mentioned this yet, they may be useful as iterators. Assume you have a list of objects of some sort. And you need to traverse some of them in some specific order. So you create an array holding pointers to the objects you need to traverse, and then you sort that array. An iterator into that array is a pointer to a pointer. Sorting it with std::sort requires a pair of iterators, which means that it requires a pair of pointers to pointers. And then traversing it with std::for_each also requires a pair of iterators. That's the context in which I last used pointers to pointers. (I actually had one final layer of abstraction so I ended up with pointers to pointers to pointers, but that's probably more unusual)
2,096,709
2,097,305
What's the best way to insert version and arch info into C++ sources?
I want my C++ program to include a "--version" option which causes it to print out: Architecture it's compiled for Version of the source (e.g., v0.1.0) Name of the application I'm also using autoconf/automake for the first time, and I notice that configure.ac has both the binary and the version. It doesn't currently have architecture information in it, and I don't want to add such info, since I'll be compiling under multiple arches. Is there an easy way to automate the insertion of the version/arch/appname information in a header or source file? How do most C++ coders do this?
autoconf gives you a config.h, which provides string macros such as PACKAGE, PACKAGE_NAME, PACKAGE_STRING, PACKAGE_VERSION, and VERSION. (When I use the Argp argument parser, I simply use #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <argp.h> const char *argp_program_version = PACKAGE_STRING; const char *argp_program_bug_address = PACKAGE_BUGREPORT; /* et cetera */ int main(int argc, char **argv) { error_t argp_result = argp_parse(&argp, argc, argv, 0, 0, NULL); if (argp_result) return argp_result; /* et cetera */ } and then --help, --version, etc. just automatically work.) You could also add AC_CANONICAL_HOST AC_DEFINE_UNQUOTED([CHOST], ["$host"], [Canonical host]) AC_CANONICAL_BUILD AC_DEFINE_UNQUOTED([CBUILD], ["$build"], [Canonical build]) AC_CANONICAL_TARGET AC_DEFINE_UNQUOTED([CTARGET], ["$target"], [Canonical target]) to your configure.ac, if you want to have those string macros in your config.h too. These are typically strings of the form $arch-$vendor-$kernel-$libc, where CHOST is the platform that will run the software after it is built, CBUILD is the platform that is currently building the software, and CTARGET is the platform the software will act on. (These are all the same unless you are cross-compiling or building a cross-compile toolchain.)
2,096,762
2,096,822
What exactly is a PWSTR and why use this naming compared to char*, std::string, or CString in C++?
In various c++ code you often see different usage of strings: PWSTR, char*, std::string, CString, etc ... When is the best time to use PWSTR as compared to any other string type?
a PWSTR would be a wchar_t string pointer. That is a UNICODE (usually UCS2) string with each character taking 16 bits. a char* would be a pointer 8 bits per character. this could be ASCII, ANSI, UTF8, or one of many hundreds of other encodings. Although you only need to worry about encodings if you need the string to hold languages other than English or special symbols. In general, The Windows API is all UNICODE internally so most Windows programmers use wchar strings. But std::string and CString can both be UNICODE if the right symbols are #defined, so your choice between PWSTR, std::string and CString will be a matter of preference or the convention of the codebase you work with.
2,096,897
2,099,694
Can Win32 "move" heap-allocated memory?
I have a .NET/native C++ application. Currently, the C++ code allocates memory on the default heap which persists for the life of the application. Basically, functions/commands are executed in the C++ which results in allocation/modification of the current persistent memory. I am investigating an approach for cancelling one of these functions/commands mid-execution. We have hundreds of these commands, and many are very complicated (legacy) code. The brute-force approach that I am trying to avoid is modifying each and every command/function to check for the cancellation and do all the appropriate clean-up (freeing heap memory). I am investigating a multi-threaded approach in which an additional thread receives the cancellation request and terminates the command-execution thread. I would want all dynamic memory to be allocated on a "private heap" using HeapCreate() (Win32). This way, the private heap could be destroyed by the thread handling the cancellation request. However, if the command runs to completion, I need the dynamic memory to persist. In this case, I would like to do the logical equivalent of "moving" the private heap memory to the default/process heap without incurring the cost of an actual copy. Is this in any way possible? Does this even make sense? Alternatively, I recognize that I could just have a new private heap for every command/function execution (each will be a new thread). The private heap could be destroyed if the command is cancelled, or it would survive if the command completes. Is there any problem with the number of heaps growing indefinitely? I know there is some overhead involved with each heap. What limitations might I run into? I am running on Windows 7 64-bit with 8GB RAM (consider this the target platform). The application I am working with is about 1 million SLOC (half C++, half C#). I am looking for any experience/suggestions with private heap management, or just alternatives to my solution.
Heap is a sort of big chunk of memory. It is a user-level memory manager. A heap is created by lower-level system memory calls (e.g., sbrk in Linux and VirtualAlloc in Windows). In a a heap, then you can request or return a small chunk of memory by malloc/new/free/delete. By default, a process has a single heap (unlike stack, all threads share a heap). But, you can have many heaps. Is it possible to combine two heaps w/o copying? A heap is essentially a data structure that maintains a list of used and freed memory chunks. So, a heap should have a sort of bookkeeping data called meta data. Of course, this meta data is per heap. AFAIK, no heap manager supports a merge operation of two heaps. I had reviewed entire source code of malloc implementation in Linux glibc (Doug Lea's implementation), but no such operation. Windows Heap* functions are also implemented in a similar way. So, it is currently impossible to move or merge two separate heaps. Is it possible to have many heaps? I don't think there should be a big problem to have many heaps. As I said before, a heap is just a data structure that keeps used/freed memory chunks. So, there should be some amount of overhead. But, it's not that severe. When you look at one of malloc implementation, there is malloc_state, which is a basic data structure for each heap. For example, you can create another heap by create_mspace (in Windows, it is HeapCreate), then you will get a new malloc state. It's not that big. So, if this tread-off (some heap overhead vs. implementation easiness) is fine, then you may go on. If I were you, I'll try the way you describe. It makes sense to me. Having a lot of heap objects would not make a big overhead. Also, it should be noted that technically moving memory regions is impossible. Pointers that pointed the moved memory region will result in dangling pointers. p.s. Your problem seems like a transaction, especially Software Transactional Memory. A typical implementation of STM buffers pending memory writes, and then commits to the real system memory it the transaction had no conflict.
2,097,418
2,097,448
Pointers and Functions in C++
From the lectures notes of a course at university, on "call-by-value": void fun(int *ip) { *ip =100; } called by int n=2; int *np; np = &n; fun(np); would change the value of n to 100. When we say "int *ip", what exactly do we mean? A pointer of type integer? If so, when we call fun() with np as its argument, shouldn't there be an error as np has the address of n, which is not an integer? And then, we change the value of ip to 100, so doesn't that mean that n now has the value that's in the "memory slot" with the address 100? I am sure I am missing something. :)
A pointer of type integer? No, a pointer to an integer. when we call fun() with np as its argument, shouldn't there be an error as np has the address of n, which is not an integer? n is an integer so there’s no problem. &n, np and ip all have the same type in your code: int*. And then, we change the value of ip to 100 No … we change the value of *ip, not of ip. That is, we change the value that ip points to (which is also sometimes called the pointee).
2,097,705
2,097,734
inside c++ thread, initializing reference
I've came across the following code, ok, not exactly but close. The point of interest is the second line in the (heavily abbreviated code). Why does one have to intialize someReference 'someReference' ? Other then be able to use . operator instead of -> ? ptrThis is just as good, no? (it's inside the thread method, if that makes any difference) // this line, why? SomeClass & someReference(*ptrThis); unsigned SomeClass::someThread(void *ptr) { SomeClass *ptrThis = reinterpret_cast<SomeClass*>(ptr); SomeClass & someReference(*ptrThis); // some other code }
References always need to be initialized when they're declared (unless they're external). They remain bound to one object during their whole lifetime. This ensures that a reference, unlike a normal pointer, can (theoretically) never be NULL because it must refer to somebody. Assigning to a reference assigns to the referencee.
2,097,738
2,097,778
how to pass a non static-member function as a callback?
io_iterator_t enumerator; kern_return_t result; result = IOServiceAddMatchingNotification( mNotifyPort, kIOMatchedNotification, IOServiceMatching( "IOFireWireLocalNode" ), serviceMatchingCallback, (void *)0x1234, & enumerator ); serviceMatchingCallback((void *)0x1234, enumerator); if i declare serviceMatchinCallback as static then it works, but i do not want it to be static. Is there a way to pass it a non-static callback function? Thank you
You could keep it static, but use the userdata to store the this pointer in addition to whatever other userdata you want (by packing them into a structure, for example) and then call an object-specific callback from the static version by calling this->someCallback (where this is the pointer stored in the userdata, of course).
2,097,811
2,114,807
C++ syntax for explicit specialization of a template function in a template class?
I have code which works in VC9 (Microsoft Visual C++ 2008 SP1) but not in GCC 4.2 (on Mac): struct tag {}; template< typename T > struct C { template< typename Tag > void f( T ); // declaration only template<> inline void f< tag >( T ) {} // ERROR: explicit specialization in }; // non-namespace scope 'structC<T>' I understand that GCC would like me to move my explicit specialization outside the class but I can't figure out the syntax. Any ideas? // the following is not correct syntax, what is? template< typename T > template<> inline void C< T >::f< tag >( T ) {}
You can't specialize a member function without explicitly specializing the containing class. What you can do however is forward calls to a member function of a partially specialized type: template<class T, class Tag> struct helper { static void f(T); }; template<class T> struct helper<T, tag1> { static void f(T) {} }; template<class T> struct C { // ... template<class Tag> void foo(T t) { helper<T, Tag>::f(t); } };
2,098,149
2,098,444
What platforms have something other than 8-bit char?
Every now and then, someone on SO points out that char (aka 'byte') isn't necessarily 8 bits. It seems that 8-bit char is almost universal. I would have thought that for mainstream platforms, it is necessary to have an 8-bit char to ensure its viability in the marketplace. Both now and historically, what platforms use a char that is not 8 bits, and why would they differ from the "normal" 8 bits? When writing code, and thinking about cross-platform support (e.g. for general-use libraries), what sort of consideration is it worth giving to platforms with non-8-bit char? In the past I've come across some Analog Devices DSPs for which char is 16 bits. DSPs are a bit of a niche architecture I suppose. (Then again, at the time hand-coded assembler easily beat what the available C compilers could do, so I didn't really get much experience with C on that platform.)
char is also 16 bit on the Texas Instruments C54x DSPs, which turned up for example in OMAP2. There are other DSPs out there with 16 and 32 bit char. I think I even heard about a 24-bit DSP, but I can't remember what, so maybe I imagined it. Another consideration is that POSIX mandates CHAR_BIT == 8. So if you're using POSIX you can assume it. If someone later needs to port your code to a near-implementation of POSIX, that just so happens to have the functions you use but a different size char, that's their bad luck. In general, though, I think it's almost always easier to work around the issue than to think about it. Just type CHAR_BIT. If you want an exact 8 bit type, use int8_t. Your code will noisily fail to compile on implementations which don't provide one, instead of silently using a size you didn't expect. At the very least, if I hit a case where I had a good reason to assume it, then I'd assert it.
2,098,300
2,215,693
A terminal-like window for wxWidgets?
I'm looking to add an element to my wxWidgets GUI that behaves like a terminal emulator. Not in terms of a shell which executes commands, but just the input-output setup of an application running in a terminal. Basically, the requirements are: Streaming input/output: When you enter a character, it is added to an input stream, and when something is piped to the terminal, it prints out immediately. No editing: Once you type in a character, it's permanently there, since it's probably been consumed by the application running in the terminal. Some sort of scrolling (even if it just shows a few lines or something). It would be nice if there is something that already does this, but suggestions on how to implement this with already existing controls such as wxTextCtrl would also be welcome.
I know this is a couple weeks late, but hopefully it's still useful. I've got a project called Chameleon that uses a wxWidgets-based VT100 terminal widget, which was itself based off of a project called taTelnet. The Chameleon source is available from my website (download page here). Not sure if it's exactly what you're looking for, but it might give you some ideas. Feel free to let me know if you have any questions about it.
2,098,319
2,098,416
Calculating large factorials in C++
I understand this is a classic programming problem and therefore I want to be clear I'm not looking for code as a solution, but would appreciate a push in the right direction. I'm learning C++ and as part of the learning process I'm attempting some programming problems. I'm attempting to write a program which deals with numbers up to factorial of 1billion. Obviously these are going to be enormous numbers and way too big to be dealing with using normal arithmetic operations. Any indication as to what direction I should go in trying to solve this type of problem would be appreciated. I'd rather try to solve this without using additional libraries if possible Thanks PS - the problem is here http://www.codechef.com/problems/FCTRL Here's the method I used to solve the problem, this was achieved by reading the comments below: Solution -- The number 5 is a prime factor of any number ending in zero. Therefore, dividing the factorial number by 5, recursively, and adding the quotients, you get the number of trailing zeros in the factorial result E.G. - Number of trailing zeros in 126! = 31 126/5 = 25 remainder 1 25/5 = 5 remainder 0 5/5 = 1 remainder 0 25 + 5 + 1 = 31 This works for any value, just keep dividing until the quotient is less than 5
Skimmed this question, not sure if I really got it right but here's a deductive guess: First question - how do you get a zero on the end of the number? By multiplying by 10. How do you multiply by 10? either by multiplying by either a 10 or by 2 x 5... So, for X! how many 10s and 2x5s do you have...? (luckily 2 & 5 are prime numbers) edit: Here's another hint - I don't think you need to do any multiplication. Let me know if you need another hint.
2,098,370
2,101,558
How to launch short codes on mobile device?
Nokia has a long list of short codes on Symbian that can be applied to on-device data, such as *#0000# - to check the phones software revision type, *#7780# - to restore factory settings, etc (the list is long) If given a short code, how can I launch it? The program should not be aware of the functionality of the short code, it should just execute it. I am particularly interested in device short codes (not operator USSD codes). How does the native dialer do that? Can you please provide a code example in C++ for S60 3rd or 5th edition? Thank you.
I don't think there is a generic way to do this. From a pure Platform Security perspective, I expect only the phone manufacturer or operator to be able to give your application the capability to restore the handset factory settings. As for the other short codes, your best bet is to find a single Symbian OS C++ API that matches one single code. For example, firmware version can be obtained via SysUtil::GetSWVersion
2,098,484
2,098,537
Which of these statements about objects is true?
Given this: struct { int x; } ix; struct A { A() {}; int x; }; A ia; Which of these is true? a. ix is an object b. ia is an object c. both are objects d. both are not objects.
Many of these answers have ignored the C++ tag. In C++, "an object is a region of storage. [Note: a function is not an object, regardless of whether or not it occupies storage in the same way that objects do.]" (The C++ Standard, 1.8/1). If the homework question is about C++, then no other definition of object is applicable, not even "anything that is visible or tangible and is relatively stable in form" (dictionary.reference.com). It's not asking for your opinion about OOP principles, it's in effect asking whether ix and ia are variables. Since it's homework I'll not tell you the answer, but do note that struct { int x; } ix; is not the same thing as struct ix { int x; };. On the other hand, if the homework assignment is about OOP principles, then knock yourself out with whatever definition your lecturer has given you of "object". Since I don't know what that is, I can't tell you what answer he'll consider correct...
2,098,685
2,103,731
How does C++ builder stack up against other RAD IDEs?
It has been a few years since I did any development for PCs (I usually do embedded software). At that time I was highly proficient with (Borland, now CodeGear) C++ Builder. Time has moved on, C++ Builder has become extremely expensive and there are alternatives (MSVC studio, NetBeans, QtCreator, maybe even Eclipse with the right plugins). Others? Three things concern me (in no particular order), ease of use, additional GUI components and cross-platformness. Ease of use - I want an IDE which helps, not hinders me. Good debugger, refactoring, jump to variable declaration, usage, that sort of thing .. GUI components - when using C++ Builder I was impressed by how easy it was to develop additional VCL components and how many were available, often for free. Thus if I wanted a standard string grid where the cells also could contain pictures, checkboxes, etc, I could probably find one, or roll my own. I am not sure what the current state of play is with respect to add-on components. Do other systems have anything like http://www.tmssoftware.com/site/ ? Cross-platform - I personally use Linux for everything, but realistically, the majority of my users have Windows installations. So, cross-platform is "nice to have", "all other things being equal". Now I have to pick a solution and stick with it for the next few years. Which one, given my points above (cost plays a role, but is not make/break)? Thanks in advance for your help.
I never used C++ Builder but used to be a big fan/user of delphi. I normally work on server apps in c++, with some java. Reciently I started writing some small productivity apps for myself originally I used java, but then moved to Qt. Now I love it. The library feels well designed just like vcl did in delphi. The signals/slots mechanism is great, I am still surprised how often I don't have to write code to wire up a dialog box. Using qt is easy and the code you write is very easy to read and create. I haven't yet had to write my own widgets, I think qt's model/view architecture splits the roles very well making the stock widgets very powerful. For example when using a QTableView most display and editing functions can be provided by the ItemModel, more powerful control is provided by an ItemDelegate. I have found these easier to reuse than writing custom widgets although it seems easy enough from looking at the documentation. Qt creator is basic but does 95% of what I require, integrated project, gui designer, code, debug and help. Has support for CMake as well as qmake. It doesn't have advanced features like refactoring, but the intelli sense better than VS2005. However the next version of KDevelop looks very promising and will include these. You could also use eclipse if you wanted these features, or move between eclipse and qt creator as required. But I am very happy with qt creator. On the cross platform issue, I develop my apps on Linux at home and tend to use them on windows in work. So far everything that works on linux works just work windows and looks like it was written for it too.
2,098,820
2,098,906
reference to the pointed object
Dereferencing pointers can make the code very hard to read. What I usually do is putting a reference to the pointed object and working with the reference. Example: shared_ptr<std::vector<int> > sp = get_sp_to_vector(); std::vector<int>& vec = *sp; ... vec.push_back(5); I wonder if it's a good practice. Does it have any drawback? Update: To complete the example, I'd define get_sp_to_vector() the following way: shared_ptr<std::vector<int> > get_sp_to_vector() { // create a vector and send back a shared pointer pointing at it shared_ptr<std::vector<int> > sp(new std::vector<int>); sp->push_back(1); sp->push_back(3); return sp; }
Using local references is common, especially inside loop bodies, but there is one requirement: only do it when the reference will obviously live as long as the target object. This usually isn't hard to guarantee, but here are some bad examples: shared_ptr<X> p = get_p(); X& r = *p; p.reset(); // might result in destroying r use(r); // oops // or: shared_ptr<X> p = get_p(); X& r = *p; p = get_some_other_p(); // might result in destroying r use(r); // oops
2,098,832
2,098,845
Should I use "int" or "bool" as a return value in C++?
If I have a function that performs some procedure and then needs to return the truth value of something is there a compelling reason to use either a boolean variable, or an int variable, as the return type? bool Foo() { ... ... return truthValue; } int Foo() { ... ... return truthValue; } Is there an appreciable difference between these two functions? What are some potential pitfalls and advantages to both of them? thanks, nmr
If it's a genuine truth value, then you should use a bool as it makes it very clear to the caller what will be returned. When returning an int, it could be seen as a code/enum type value. Code should be as clear and explicit as possible whether it be function names, parameter names and types, as well as the types of the return codes. This provides more self-documenting code, code that is easier to maintain, and a lower probability that someone will misinterpret what you "meant".
2,098,901
2,098,984
My version of C++ non-member getline(), that takes a FILE* (created by _wfopen()) instead of a stream, is too slow
In C++, you can use non-member getline() with a stream in a loop like this: #include <string> #include <fstream> #include <cstdlib> using namespace std; int main() { ifstream in("file.txt"); if (!in) { return EXIT_FAILURE; } for (string line; getline(in, line); ) { // Do stuff with each line } } However, I want to do that with a FILE* created by _wfopen("file.txt", "r") instead, so I created one: #include <cstdio> #include <string> #include <cstdlib> #include <cwchar> using namespace std; bool getline(FILE* const in, string& s) { int c = fgetc(in); if (c == EOF) { return false; } s.clear(); while (c != EOF && c != 10 && c != 13) { s += c; c = fgetc(in); } return true; } int main() { FILE* const in = _wfopen(L"file.txt", L"r"); if (!in) { return EXIT_FAILURE; } for (string line; getline(in, line); ) { // Do stuff with the line } if (in) { fclose(in); } } It handles newlines like I want and works in a loop like I want. It's just too slow because I'm reading one char at a time and inserting one char in the string at a time. For example, it takes 6 seconds to process a 12MB file while the original getline does it virtually instantly. That's not that big of a deal for a small file, but for a 2GB file for example, it'd be a problem. I'd like it to be as fast as C++'s getline(), but I don't think I can make it any faster without redesigning it. So, how should I redesign it so it's more efficient? I know I should fread in chunks into a buffer (a vector for example and resize when needed) till I find() a newline or newline pair in it and append the range to the string. However, I'm not really picturing how to make it work like my char-by-char version, especially if I read in too much and have to put data after the newline or newline pair back into the stream so it can be consumed on the next iteration. Now, VC++ has a wifstream that takes a FILE* and STLPort might have one too. But, I'm using just Mingw 4.4.1. (I don't want to use STLPort because it's a pain in the ass to build with Mingw.) The reason I need to use a FILE* is because that's what _wfopen() returns. I need to use _wfopen() because it supports wchar_t* paths that I will be getting from the wchar_t** array returned by windows function CommandLineToArgvW(CommandLineW(), &argc). ifstream doesn't take a wide path. Thanks
You should be using C++ I/O facilities if you're programming in C++. Having said that... First, you are checking for newline by checking for 10 and 13. You should open your file in text mode, and check for '\n' instead. This method is portable, and works with different line-end conventions, as well as on non-ASCII systems. Assuming you have to use native C FILE *, I would do it this way: #include <cstdio> #include <cstring> #include <string> bool cgetline(FILE* const in, std::string &s) { char buf[BUFSIZ+1] = {0}; s.clear(); while (fgets(buf, sizeof buf, in) != NULL) { char *end = strchr(buf, '\n'); if (end == NULL) { /* We didn't see a newline at the end of the line, if we hit the end of file, then the last line wasn't terminated with a newline character. Return it anyway. */ if (feof(in)) { s.append(buf, strlen(buf)); return true; } else { s.append(buf, sizeof buf - 1); } } else { s.append(buf, end - buf); return true; } } return false; } The complication is from making sure the program does the right thing when the last line of a file doesn't end with a newline character. Reading from a file character-by-character and appending to a string is probably why your version is slow.
2,099,120
2,099,148
Why doesn't C++ implement construction + calling functions in same line?
I'm wondering why C++ (and possibly other languages, I'm not sure) doesn't allow statements like this. MyObject foo.DoBar(); You would think that the language could understand to construct the object, then call the function. The only reason I can think of this not working is that if the construction of the object failed, the statement would still try to call the function. What are the reasons why those who help develop and integrate new features into C++ (and possibly other languages) don't allow this?
You can construct an object and immediately call a function on it, you just can't assign the object to a variable if you do so: MyObject().DoBar(); A practical reason for this restriction is that the constructor creates the object and the function you're calling could also have a return value, so that you would end up with two values produced by the same statement. Then you would need some special syntax to assign both of these values to variables, something that doesn't happen anywhere else. And the little convenience that might be gained by directly calling the method isn't that big of an advantage that it would be worth introducing new syntax for it.
2,099,436
2,099,518
A few sorting questions
I have found a way that improves (as far as I have tested) upon the quicksort algorithm beyond what has already been done. I am working on testing it and then I want to get the word out about it. However, I would appreciate some help with some things. So here are my questions. All of my code is in C++ by the way. One of the sorts I have been comparing to my quicksort is the std::sort from the C++ Standard Library. However, it appears to be extremely slow. I am only sorting arrays of ints and longs, but it appears to be around 8-10 times slower than both my quicksort and a standard quicksort by Bentley and McIlroy (and maybe Sedgewick). Does anyone have any ideas as to why it is so slow? The code I use for the sort is just std::sort(a,a+numelem); where a is the array of longs or ints and numelem is the number of elements in the array. The numbers are very random, and I have tried different sizes as well as different amounts of repeated elements. I also tried qsort, but it is even worse as I expected. Edit: Ignore this first question - it's been resolved. I would like to find more good quicksort implementations to compare with my quicksort. So far I have a Bentley-McIlroy one and I have also compared with the first published version of Vladimir Yaroslavskiy's dual-pivot quicksort. In addition, I plan on porting timsort (which is a merge sort I believe) and the optimized dual-pivot quicksort from the jdk 7 source. What other good quicksorts implementations do you know about? If they aren't in C or C++ that might be okay because I am pretty good at porting, but I would prefer C or C++ ones if you know of them. How would you recommend getting out the word about my additions to the quicksort? So far my quicksort seems to be significantly faster than all other quicksorts that I've tested it against. The main source of its speed is that it handles repeated elements much more efficiently than other methods that I've found. It almost completely eradicates worst case behavior without adding much time in checking for repeated elements. I posted about it on the Java forums, but got no response. I also tried writing to Jon Bentley because he was working with Vladimir on his dual-pivot quicksort and got no response (though I wasn't terribly surprised by this). Should I write a paper about it and put it on arxiv.org? Should I post in some forums? Are there some mailing lists to which I should post? I have been working on this for some time now and my method is legit. I do have some experience with publishing research because I am a PhD candidate in computational physics. Should I try approaching someone in the Computer Science department of my university? By the way, I have also developed a different dual-pivot quicksort, but it isn't better than my single-pivot quicksort (though it is better than Vladimir's dual-pivot quicksort with some datasets). I really appreciate your help. I just want to add what I can to the computing world. I'm not interested in patenting this or any absurd thing like that.
If you have confidence in your work, definitely try to discuss it with someone knowledgeable at your university as soon as possible. It's not enough to show that your code runs faster than another procedure on your machine. You have to mathematically prove whatever performance gain you claim to have achieved through analysis of your algorithm. I'd say the first thing to do is make sure both algorithms you are comparing are implemented and compiled optimally - you may just be fooling yourself here. The likelihood of an individual achieving such a marked improvement upon such an important sorting method without already having thorough knowledge of its accepted variants just seems minuscule. However, don't let me discourage you. It should be interesting anyway. Would you be willing to post the code here? ...Also, since quicksort is especially vulnerable to worst-case scenarios, the tests you choose to run may have a huge effect, as will the choice of pivots. In general, I would say that any data set with a large number of equivalent elements or one that is already highly sorted is never a good choice for quicksort - and there are already well-known ways of combating that situation, and better alternative sorting methods.
2,099,442
2,102,487
Algorithm for allocating memory pages and page tables
I want to design an algorithm for allocating and freeing memory pages and page tables. What data structures would allow best performance and simplest implementation?
Even though OS normally implement page tables, the simpler solution could be something like this. Have a large contiguous memory as an array. When you allocate some memory, maintain that information in a linked list storing the index of the array and the length in the data part. When you are building the linked list, make sure that it is sorted on the index. When you want to allocate memory, scan the linked list and this will take O(N). where N is the allocations already done. Deletion will be scanning the array for the particular index and removing the node in linked list. Once the node is removed, have a separate linked list containing these free allocations. Insertion will look like this. 1. Check in free list if there is an element in the list of size requested. 2. If not, allocate memory after the last element of linked list Deletion will work like this, 1. Move the node to the free list. Make sure free list and linked list are sorted on the index. This approach doesn't address the fragmentation issue in memory allocators.One easy approach is to use compaction. Regularly, scan the free node linked list and for each element move the elements in the array and update the index of the node in linked list appropriately.
2,099,540
2,099,590
Defining custom hash function and equality function for unordered_map
I am trying to define a type of unordered_map that has a custom hash function and equality comparison function. The function prototypes of these functions are as follows: //set<Vertex3DXT*> is the type of the key; Cell3DXT* is the type of the value size_t VertexSetHashFunction(set<Vertex3DXT*> vertexSet); //hash function bool SetEqual(set<Vertex3DXT*> a, set<Vertex3DXT*> b); //equality I have these function prototypes declared and then I try to declare the type as follows: typedef std::tr1::unordered_map<set<Vertex3DXT*>, Cell3DXT*, VertexSetHashFunction, SetEqual> CellDatabaseMapType; But it says that the VertexSetHashFunction and SetEqual are not valid template type arguments. The documentation is confusing because it doesn't say exactly what type the template arguments are supposed to be - am I just supposed to give it the function as I did here, or is there some other kind of object that encapsulates the function (because the documentation does talk about the "hash function object type")?
Those functions should be declared as an operator () in a class, unfortunately. Like this: class VertexSetHashFunction { public: ::std::size_t operator ()(const ::std::set<Vertex3DXT*> &vertexSet) const; }; class SetEqual { public: bool operator ()(const ::std::set<Vertex3DXT*> &a, const ::std::set<Vertex3DXT*> &b) const; }; You do not have to modify the arguments to be const references, but I would highly recommend it. Making a copy of a ::std::set is relatively expensive and you shouldn't do it unless you absolutely have to. The trailing const is just because the operator doesn't actually modify the class state at all, mostly because there isn't any. It's just nice to say so explicitly. Alternately, you could define your own specialization of the ::std::hash template. I would actually recommend this if there is one standard way you want that particular set hashed because this template is used by default if you do not supply a hash function to unordered_map or unordered_set and anything else that needs a hash function.
2,099,731
2,099,898
Which one to use const char[] or const std::string?
Which is better for string literals, standard string or character array? I mean to say for constant strings, say const char name[] = "so"; //or to use const string name = "so";
For string literals, and only for string constants that come from literals, I would use const char[]. The main advantage of std::string is that it has memory management for free, but that is not an issue with string literals. It is the actual type of the literal anyway, and it can be directly used in any API that requires either the old C style null terminated strings or the C++ strings (implicit conversion kicks in). You also get a compile time size implementation by using the array instead of the pointer. Now, when defining function interfaces, and even if constants are intented to be passed in, I would prefer std::string rather than const char*, as in the latter case size is lost, and will possibly need to be recalculated. Out of my own experience. I grew old of writting .c_str() on each and every call to the logging library (that used variable arguments) for literal strings with info/error messages.
2,099,743
2,110,613
NPAPI plugin in QtWebKit
I know its possible to integrate NPAPI plugins with QtWebKit as its been supported since the release of Qt 4.5. My question is, should I go and design my plugin according to the Mozilla/Gecko documentaion -Which is probably the only available/reliable documentation for NPAPI beside some really old book called "Programming Netscape Plug-ins"- or does Qt handle NPAPI plugins in a different way?
Going with Mozillas and other documentation like colonelpanics tutorial will be fine. You might also want to take a look at FireBreaths source because we already solved some common issues there. QtWebKit actually wraps WebKit and i don't recall there being any real differences between Mozilla and WebKit. Of course you should handle possible differences in supported browser-properties etc., but you should do that in any NPAPI plugin anyway. The added benefit is that you won't have too much problems using the same plugin in other enviroments then QtWebKit.
2,099,804
2,099,902
porting from 32 bit to 64 bit
I have windows application build using Visual C++. Its being build and run on 32 bit windows env. Now I need to make sure it works on windows vista / 7 64 bit env. What all things I need to consider for this porting process ??
That's not porting from 32bit to 64, that's just running your 32bit code on a 64bit machine to make sure it still works. The way to do that is to just test all the functionality on the 64-bit machine, just as you do every time you release a new version, right? :-) If you really want to port it (i.e., compile it to a 64bit executable), the first step is to just try it. You may find it works as-is. I'd only be worried about porting problems if you try it and then problems appear. Then, and only then, would I go looking for the causes. Otherwise it's potentially wasted effort.
2,099,830
2,099,873
Unsigned keyword in C++
Does the unsigned keyword default to a specific data type in C++? I am trying to write a function for a class for the prototype: unsigned Rotate(unsigned object, int count) But I don't really get what unsigned means. Shouldn't it be like unsigned int or something?
From the link above: Several of these types can be modified using the keywords signed, unsigned, short, and long. When one of these type modifiers is used by itself, a data type of int is assumed This means that you can assume the author is using ints.
2,099,882
2,099,901
Checking for a null object in C++
I've mostly only worked with C and am running into some unfamiliar issues in C++. Let's say that I have some function like this in C, which would be very typical: int some_c_function(const char* var) { if (var == NULL) { /* Exit early so we don't dereference a null pointer */ } /* The rest of the code */ } And let's say that I'm trying to write a similar function in C++: int some_cpp_function(const some_object& str) { if (str == NULL) // This doesn't compile, probably because some_object doesn't overload the == operator if (&str == NULL) // This compiles, but it doesn't work, and does this even mean anything? } Basically, all I'm trying to do is to prevent the program from crashing when some_cpp_function() is called with NULL. What is the most typical/common way of doing this with an object C++ (that doesn't involve overloading the == operator)? Is this even the right approach? That is, should I not write functions that take an object as an argument, but rather, write member functions? (but even if so, please answer the original question) Between a function that takes a reference to an object, or a function that takes a C-style pointer to an object, are there reasons to choose one over the other?
Basically, all I'm trying to do is to prevent the program from crashing when some_cpp_function() is called with NULL. It is not possible to call the function with NULL. One of the purpose of having the reference, it will point to some object always as you have to initialize it when defining it. Do not think reference as a fancy pointer, think of it as an alias name for the object itself. Then this type of confusion will not arise.
2,100,012
2,100,107
Object creation wrapper for a template class
Given a template class as such: template <typename TYPE> class SomeClass { public: typedef boost::intrusive_ptr<SomeClass<TYPE> > Client_t; inline Client_t GetClient() { return Client_t(this); } }; SomeClass is intended only to be used via pointer references returned by SomeClass::GetClient(). Which makes it natural to write a wrapper function around creation like this: template <typename TYPE> SomeClass<TYPE>::Client_t New_SomeClass() { return (new SomeClass<TYPE>)->GetClient(); } Compiling the above code under GCC 4.4: SomeClass<int>::Client_t some_class = New_SomeClass(); Gives the error "‘New_SomeClass’ was not declared in this scope" Now I'm no template wizard, so there could be details here I'm not aware of, but I'm guessing I can't use a construct of this sort at all due to the fact that C++ doesn't allow overloading on return type. I guess a...shiver... macro would solve it: #define NEW_SOMECLASS(TYPE) ((new SomeClass<TYPE>)->GetClient()) auto some_class = NEW_SOMECLASS(int); But there has to be a sensible way to expose object creation of a template class without resorting to macros or other cumbersome constructs?
SomeClass<int>::Client_t some_class = New_SomeClass<int>(); Because template parameters for New_SomeClass don't depend on a function parameter, you must specify them. The error message you reported is a little strange for this problem, however, so you might have something else going on. Or, my preference instead of New_SomeClass function: template<class T> struct SomeClass { typedef boost::intrusive_ptr<SomeClass> Client; inline Client client() { return Client_t(this); } static Client create() { return (new SomeClass())->client(); } private: SomeClass(); // can be public too, if you really need it accessible }; //... SomeClass<int>::Client some_class = SomeClass<int>::create(); Even though it essentially just moves the function "into" the class, I find it generally cleaner. In any case, if your compiler supports 0x's 'auto' then you can use it: auto some_class = SomeClass<int>::create();
2,100,239
2,100,295
C++ STL container and in-place construction
Please consider the following: class CMyClass { public: CMyClass() { printf( "Constructor\n" ); } CMyClass( const CMyClass& ) { printf( "Copy constructor\n" ); } }; int main() { std::list<CMyClass> listMyClass; listMyClass.resize( 1 ); return 0; } It produces the following output: Constructor Copy constructor Now my question is: How do I avoid the copy constructor? Or to put it in another way: How can I create objects inside an STL container without the unnecessary copy operation. Is there some way to do an "in-place" construction using the default constructor? Update - answers so far: It can't be done Use pointers or smart pointers instead. Smart pointers are an overkill for my application. But I really wonder why this can't be done. It seems like such an obvious thing to want to do. Any other ideas? I will even accept a nasty hack if it works... Solution I think I just found a solution for my problem from all the comments and answers posed here. The solution is to construct an empty object and to keep it around for the sole purpose of using it later for making clean copies of. Then you can use one of the methods that take a reference (like push_back or insert). This still calls the copy constructor for every new object inserted, but at least it is not both the default constructor AND copy constructor: int main() { CMyClass Empty; std::list<CMyClass> listMyClass; for ( int c=0; c<10; ++c ) { listMyClass.push_back( Empty ); } return 0; }
By design, all the C++ Standard Library containers store copies. Therefore the call to the copy constructor cannot be avoided if you wish to store values in the container - the only way out is to store pointers instead. If you want to mitigate the overhead of copying, investigate the use of reference counting.
2,100,458
2,100,546
Multiple writes in boost::asio to a single socket
I couldn't find any thing about what happens if you try to do a second write to a boost::asio socket before a previous one completed. This seems like something that could potentially happen in many asynchronous programs (since after doing the first write, the program will then continue before waiting for it to finish, potentially causing a second message to be sent and so on). I've thought of a few possible things that could happen (this is assuming that in all cases the message is sent with a single call to async_write). void handleWrite(const boost::system::error_code&error) { if(error)throw NetError(error); } vodi sendStuff() { const char msg1 = "Red, Green, Blue"; const char msg2 = "One, Two, Three"; asio::async_write(socket,asio::buffer(msg1,sizeof(msg1)),boost::bind(&handleWrite,_1)); //assume msg1 has still not been sent by the time we get here asio::async_write(socket,asio::buffer(msg2,sizeof(msg2)),boost::bind(&handleWrite,_1)); } So assuming that the first send doesn't cause an error: Asio sends msg1, then msg2, in order, possible even in a single TCP packet The second async_write call blocks until msg1 is done The result is undefined If an error occurs in msg1s, i'm assuming the exception will cause msg2 to abort as well? Also is this effected by if the associated io_service has a thread pool, or just a single thread? If it's not safe, then has any one written some kind of simple wrapper that maintains a queue of messages to send, sending them one by one and aborting if any write handler throws an exception?
So, with normal non-blocking sockets, you can write some implementation-dependant amount of stuff to the socket, then eventually a write will return -EWOULDBLOCK and not do the write so you can retry later. Poking around in the source tells me that Boost wraps that, so that everything you write should get there eventually (or raise an error, not including would_block or try_again).
2,100,486
2,100,576
Advantages/disadvantages of auto pointers
What are the advantages and disadvantages of using auto pointers (auto_ptr), compared to ordinary pointers? I've heard it does automatic releasing of memory but how come it is not used often?
The main drawback of std::auto_ptr is that it has the transfer-of-ownership semantic. That makes it impossible to store std::auto_ptr in STL containers because the containers use the copy constructor when you store or get an element. Also, another important aspect that i have noticed about the std::auto_ptr is that they cannot serve in the use of PIMPL idiom. This is because, they require the complete definition of the wrapped class's destructor. See this thread on c.l.c++.m for more detailed discussion. Update: Transfer of ownership class Test {}; std::auto_ptr<Test> ap_test_1(new Test); std::auto_ptr<Test> ap_test_2(new Test); ap_test_2 = ap_test_1; // here ap_test_1's ownership is transferred i.e. ap_test_2 is the // new owner and ap_test_1 is NULL. See this thread on Herb Sutter's site for more details on what this means when used in a STL container used by STL algorithms.
2,100,644
2,100,685
Will using delete with a base class pointer cause a memory leak?
Given two classes have only primitive data type and no custom destructor/deallocator. Does C++ spec guarantee it will deallocate with correct size? struct A { int foo; }; struct B: public A { int bar[100000]; }; A *a = (A*)new B; delete a; I want to know do I need to write an empty virtual dtor? I have tried g++ and vc++2008 and they won't cause a leak. But I would like to know what is correct in C++ standard.
Unless the base class destructor is virtual, it's undefined behaviour. See 5.3.5/4: If the static type of the operand [of the delete operator] is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behaviour is undefined.
2,100,776
2,100,990
C++ app: modules design
My app contains several modules (big classes) like network io, data storage, controls, etc. Some of them can cooperate. What would be a good way of declaring and binding the modules? I see several possibilities: 1) All modules declared as global, so we have in main.cpp #include ... ModuleA a; ModuleB b; ModuleC c; and if a wants to talk to module c for example, we will have in a.cpp the following: #include "c.hpp" extern ModuleC c; and so on; 2) All modules declared in main(), so they are local. The bindings are made in constructors: int main() { ModuleC c; ModuleA a(c); ModuleB b; } but in this way would be hard to bind objects which want each other ( a(c), c(a) ) 3) First phase: declare locally, second phase: bind with pointers: int main() { ModuleA a; ModuleB b; ModuleC c; a.Connect(&b); b.Connect(&a); c.Connect(&a, &b); } Is there a better way? I'd like it to be in cpp style. Third way keeps pointers which is a bit confusing (though there won't be problems with validness of pointers though modules lives all the time, but still) and has two-phase initialization, which doesn't guarantee that we won't forget to init some module, and oops -- an invalid pointer. The second way (as i think) may crash all the idea if some objects would need cross-binding. The first way seems to be natural (since modules represent the app itself), but isn't it a bad style? I saw some projects where the modules were declared in some universe class and they cooperate via this universe just like it woule be if all of them are global. What do you think? Thanks.
From a computer science point of view, you ideally want to decrease the coupling as much as possible. From a general development point of view, you want to reduce the amount of code that is compiled when you make a change somewhere. So, to address this, you'll want to use interfaces and the 'universe' class. main () { Universe my_app; ModuleA a (my_app); ModuleB b (my_app); ModuleC c (my_app); } class ModuleA : public ModuleAInterface { public: ModuleA (Universe &my_app) : m_my_app (my_app) { m_my_app.Register (this); } private: Universe &m_my_app; } // etc... class Universe { public: template <class T> void Register (T *module) { m_modules [T::ModuleID] = module; } template <class T> T *Module () { return reinterpret_cast <T *> (m_modules [T::ModuleID]); } private: std::map <int, void *> m_modules; }; Note that this means that Module constructors can't call functions in other modules as the order of construction is effectively undefined. To use the above, ModuleA might have a function like: void ModuleA::SomeFunction () { ModuleBInterface *b = m_my_app.Module <ModuleBInterface> (); } So, putting it all together, here's a sample program that compiles and runs using DevStudio 2005 (create a default, empty console application): #include <map> #include <iostream> class Universe { public: template <class T> void Register (T *module) { m_modules [T::ModuleID] = module; } template <class T> T *Module () { return reinterpret_cast <T *> (m_modules [T::ModuleID]); } private: std::map <int, void *> m_modules; }; class ModuleAInterface { public: static const unsigned ModuleID = 1; virtual ~ModuleAInterface () {}; }; class ModuleBInterface { public: static const unsigned ModuleID = 2; virtual ~ModuleBInterface () {}; virtual void OutputString (char *string) = 0; }; class ModuleCInterface { public: static const unsigned ModuleID = 3; virtual ~ModuleCInterface () {}; }; class ModuleA : public ModuleAInterface { public: ModuleA (Universe &my_app) : m_my_app (my_app) { m_my_app.Register (this); } void DoSomething () { ModuleBInterface *b = m_my_app.Module <ModuleBInterface> (); b->OutputString ("Hello"); } private: Universe &m_my_app; }; class ModuleB : public ModuleBInterface { public: ModuleB (Universe &my_app) : m_my_app (my_app) { m_my_app.Register (this); } private: virtual void OutputString (char *string) { std::cout << string; } Universe &m_my_app; }; class ModuleC : public ModuleCInterface { public: ModuleC (Universe &my_app) : m_my_app (my_app) { m_my_app.Register (this); } private: Universe &m_my_app; }; int main () { Universe my_app; ModuleA a (my_app); ModuleB b (my_app); ModuleC c (my_app); a.DoSomething (); } Once the code has been split up, only changes to the interfaces will cause large recompilation, changing the implementation of the interfaces will only recompile the changed module, nothing else will need to be recompiled.
2,101,041
2,105,624
Capturing network status change event
I am trying to get events when the internet connection is reestablished after it is lost. It is for a data transfer software that I am developing. If I lose the network during data transfer, I would like to be notified when it is back and continue the transfer automatically. I can of course create a separate thread and check the network once in a while with a timer, but maybe there is a better option out there. I am developing for windows mainly, in C++ (not .net). I can also use wxwidgets (I use it for GUI) but I doubt it offers any related functionality.
You might want to check out the System Event Notification Server (SENS) API http://msdn.microsoft.com/en-us/library/cc185680(VS.85).aspx I have not actually used it, but it seems like it supplies the events your looking for. EDIT: WMI appears to have all the information you need about various network connectivity and state changes. It also has an asynchronous event model that can be used to get notifications. The trick is, i suppose, generating the proper WMI query to get the information you want. This blog looks like the right type of query, and this MSDN explains how to handle the events asynchronously.
2,101,078
2,101,135
Redefine Virtual Functions between header files in C++
I have one header file which uses a virtual function. This is declared and defined: #ifndef HeaderH #define HeaderH class Base { <some code> public:virtual int checkVal(int& val) { return val;} }; #endif I have another header file which declares some functions, and inherits from this base header. Finally, I have the implementation of this header file in another .cpp file: I want to override the virtual function checkVal in my implementation here, but I keep getting a redefinition error. int Base::checkVal(int& value) { if(value == 0) value = 10; return value; } Is there something I should include in my header file which will override the Base virtual function?
You have already provided the definition of checkval() inside your base class, so why are you redefining it? You can define it only once.If you want to give the implementation inside the .cpp file, just declare checkval() inside the base class, no need to define it there. Your implementation of checkval() fails if you call it like the following: Base b; //some code b.checkval(10);//Error because temporaries cannot be bound to non-constant references Is there something I should include in my header file which will override the Base virtual function? Create a derived class inside the header file and override checkval() then by declaring the function inside the derived class and defining it inside .cpp file.
2,101,103
2,116,932
Assembler task - min and max values of the array
I've encountered problems with assembler code. I'm a newbie to assembler, so it seems difficult for me to solve it myself. The task is: "To find minimal and maximal elements of the array." All I've already done is searching for maximal element. I can't find out, how to make check for the minimal element and where I should put such verification. Or, probably, I should loop through elements second time after finding maximal element? Code: #include <conio.h> #include <stdio.h> #include <iostream.h> void main() { int N = 10, i; clrscr(); // on this platform, int is 16-bit int a[] = { 1, 4, -6, 12, -25, 10, 3, -4, 15, 7}, MAX, MIN, RESULT; __asm{ mov cx, N lea si, a lodsw mov bx, ax mov dx, ax dec cx } m: __asm{ lodsw cmp dx, ax jge m1 mov dx, ax } m1: __asm{ loop m mov MAX, dx } cout << "Max = " << MAX; //cout << "Min = " << MIN; getch(); }
If it's interesting to someone, here is the solution for my question(I found out it today with help of my tutor): #include <conio.h> #include <stdio.h> #include <iostream.h> void main() { int N = 10, i; clrscr(); int a[] = { 1, 4, -6, 12, -25, 10, 3, -4, 15, 7}, MAX, MIN, RESULT; __asm{ mov cx, N lea si, a lodsw mov MIN, ax mov MAX, ax dec cx } m: __asm{ lodsw cmp MIN, ax jle m1 mov MIN, ax jmp m2 } m1: __asm{ cmp MAX, ax jge m2 mov MAX, ax } m2: __asm{ loop m; } cout << "Max = " << MAX << "\n"; cout << "Min = " << MIN; getch(); } Algorithm: if cmp MIN, ax has negative result, it means ax is greater, than MIN. So script jumps to m1 label to compare ax value with MAX. When cmp MIN, ax returns positive value, scripts assigns value of ax register to MIN variable and after that jumps to the m2 label to decrement loop counter. Algorithm of finding maximal value works similarly(label m1).
2,101,362
2,101,592
Why is QMutex unknown?
I've included the QMutex header and using it as seen below. But I get the following error: error C2146: syntax error : missing > ';' before identifier > '_RecorderParamsMutex' error C4430: missing type specifier - int assumed. > Note: C++ does not support default-int error C4430: missing type specifier -> int assumed. Note: C++ does not > support default-int #ifndef RECORDERinterface_h #define RECORDERinterface_h #include "qstring.h" #include "ccc.h" #include "ddd.h" #include <qmutex.h> #include "eee.h" using namespace Common; //for aaaaa class RecorderInterface{ //the implemented recorders are my friends, the may access all my private stuff :) friend class A; friend class B; public: RecorderInterface(); bool setParam(RecorderPrintParam *up); private: QMutex _RecorderParamsMutex; }; #endif
Looking at the header file, the class declarations are wrapped by an #ifdef. Try it like this: #define QT_THREAD_SUPPORT #include <qmutex.h> This probably ought to be a project-level #define so other threading definitions are available as well.
2,101,390
2,101,464
Will C++ exceptions safely propagate through C code?
I have a C++ application that calls SQLite's (SQLite is in C) sqlite3_exec() which in turn can call my callback function implemented in C++. SQLite is compiled into a static library. If an exception escapes my callback will it propagate safely through the C code of SQLite to the C++ code calling sqlite3_exec()?
My guess is that this is compiler dependent. However, throwing an exception in the callback would be a very bad idea. Either it will flat-out not work, or the C code in the SQLite library will be unable to handle it. Consider if this is some code in SQLite: { char * p = malloc( 1000 ); ... call_the_callback(); // might throw an exception ... free( p ); } If the exception "works", the C code has no possible way of catching it, and p will never be freed. The same goes for any other resources the library may have allocated, of course.
2,101,449
2,133,159
Experience with IBPP interface for Firebird database
I'd like to the ask guys with experience in Firebird and IBPP (especially the latter). I found a lot of positive posts about Firebird but I'm having a problem to decide about IBPP. The interface itself is clean and simple but it seems that the project does not have much of activity going on (maybe because it's very stable). Would you recommend IBPP for production environment? Is it thread-safe? Any known bugs? Thanks.
In addition to the points Milan mentioned: There is currently no way to use more than one client library when connecting to different databases, or even to specify which client library will be used. There is a certain hard-coded sequence of client library locations that are probed, and the first one that is found will be used for all connections. An IBPP version changing this has been hinted at for a very long time, but hasn't arrived yet. SVN trunk contains some code to deal with this, but I'd say that's alpha quality at most. And all of this holds true for Windows only, as on all other platforms the Firebird client library isn't loaded at runtime anyway. The library isn't thread-safe. That doesn't matter for the most part, as you should let each thread have its own connection, transaction and other assorted objects anyway. But IBPP uses its own smart pointer implementation, which is neither completely exception-safe nor thread-safe. Still, as long as you initialize the library from the main thread (before any other thread is created) and create and destroy IBPP objects in the same thread (so absolutely no sharing of objects with other threads!) using IBPP in multiple threads should work fine. If you can live with the points above (they may not matter to you, at all) it is certainly ready for production use. You can always change things you run into, as we did for FlameRobin too.
2,101,789
2,137,875
Implementation of a work stealing queue in C/C++?
I'm looking for a proper implementation of a work stealing queue in C/CPP. I've looked around Google but haven't found anything useful. Perhaps someone is familiar with a good open-source implementation? (I prefer not to implement the pseudo-code taken from the original academic papers).
No free lunch. Please take a look the original work stealing paper. This paper is hard to understand. I know that paper contains theoretical proof rather than pseudo code. However, there is simply no such much more simple version than TBB. If any, it won't give optimal performance. Work stealing itself incurs some amount of overhead, so optimizations and tricks are quite important. Especially, dequeues are must be thread-safe. Implementing highly scalable and low-overhead synchronizations are challenging. I'm really wondering why you need it. I think that proper implementation means something like TBB and Cilk. Again, work stealing is hard to implement.
2,102,056
2,102,070
Why can't for_each modify its functor argument?
http://www.cplusplus.com/reference/algorithm/for_each/ Unary function taking an element in the range as argument. This can either be a pointer to a function or an object whose class overloads operator(). Its return value, if any, is ignored. According to this article, I expected that for_each actually modifies the object given as its third argument, but it seems like for_each operates on a temporary object, and doesn't even modify the object given to it. So, why is it implemented in that way? It seems much less useful. Or did I misunderstand something and my code below contains errors? #include <iostream> #include <vector> #include <algorithm> template <class T> struct Multiplicator{ T mresult; public: const T& result() const{return mresult;} Multiplicator(T init_result = 1){ mresult = init_result; } void operator()(T element){ mresult *= element; std::cout << element << " "; // debug print } }; int main() { std::vector<double> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); Multiplicator<double> multiply; std::for_each(vec.begin(),vec.end(),multiply); std::cout << "\nResult: " << multiply.result() << std::endl; return 0; } Expected output: 1 2 3 Result: 6 But got following output: 1 2 3 Result: 1
The function object is taken by value. for_each returns the function object, so if you change it to: multiply = std::for_each(vec.begin(),vec.end(),multiply); you get the expected output.
2,102,151
2,104,955
How to write a Cocoa OpenGL app in C++?
I'm writing an application that needs to use OpenGL, on the Mac, in C++. Is there anyway I can get Cocoa to just give me an OpenGL context and let me do my work in C++? (I want my app to run on both Mac OS X and iPHone; but all the GUI is in OpenGL, I just need a OpenGL context). Thanks!
You cannot escape a minimal amount of objective-C code. However, if you rename the objective C files to .mm files, the objective C code will be able to call c++ class methods. This means you can hook the -drawRect (and other relevent NSOpenGLView messages) to your c++ OpenGL implementation. The NSOpenGLView has a -makeCurrent method that you can call outside of drawRect to ensure that the correct OpenGL context is active. Your c++ code can then simply call gl functions as needed.
2,102,187
2,102,257
Can a functor retain values when passed to std::for_each?
According to the first answer to this question, the functor below should be able to retain a value after being passed to foreach ( I couldn't get the struct Accumulator in the example to compile, so built a class). class Accumulator { public: Accumulator(): counter(0){} int counter; void operator()(const Card & c) { counter += i; } }; Example usage ( as per the example ) // Using a functor Accumulator acc; std::for_each(_cards.begin(), _cards.end(), acc); // according to the example - acc.counter contains the sum of all // elements of the deque std::cout << acc.counter << std::endl; _cards is implemented as a std::deque<Card>. No matter how long _cards gets, acc.counter is zero after the for_each completes. As I step through in the debugger I can see counter incrementing, however, so is it something to do with acc being passed by value?
This was just asked here. The reason is that (as you guessed) std::for_each copies its functor, and calls on it. However, it also returns it, so as outlined in the answer linked to above, use the return value for for_each. That said, you just need to use std::accumulate: int counter = std::accumulate(_cards.begin(), _cards.end(), 0); A functor and for_each isn't correct here. For your usage (counting some, ignoring others), you'll probably need to supply your own functor and use count_if: // unary_function lives in <functional> struct is_face_up : std::unary_function<const Card&, const bool> { const bool operator()(const card& pC) const { return pC.isFaceUp(); // obviously I'm guessing } }; int faceUp = std::count_if(_cards.begin(), _cards.end(), is_face_up()); int faceDown = 52 - faceUp; And with C++0x lambda's for fun (just because): int faceUp = std::count_if(_cards.begin(), _cards.end(), [](const Card& pC){ return pC.isFaceUp(); }); Much nicer.
2,102,401
2,102,511
Determine if O/S is Windows 7
Working on a project and need to be able to determine whether the O/S is Windows 7, Vista or default to XP. I understand I could run into Win2K and earlier versions but let's just say that's not a concern as other code will catch that before it gets to this point. My application will be in C++ for the time being using VS2005. I've found articles and sample code alike but they seem way bloated for my uses. Just looking for a quick and dirty return. http://msdn.microsoft.com/en-us/library/ms724358%28VS.85%29.aspx
List of Windows Version, using GetVersionEx: Version Number Description 6.1 Windows 7 / Windows 2008 R2 6.0 Windows Vista / Windows 2008 5.2 Windows 2003 5.1 Windows XP 5.0 Windows 2000
2,102,582
2,102,615
(How) can I count the items in an enum?
This question came to my mind, when I had something like enum Folders {FA, FB, FC}; and wanted to create an array of containers for each folder: ContainerClass*m_containers[3]; .... m_containers[FA] = ...; // etc. (Using maps it's much more elegant to use: std::map<Folders, ContainerClass*> m_containers;) But to come back to my original question: What if I do not want to hard-code the array size, is there a way to figure out how many items are in Folders? (Without relying on e.g. FC being the last item in the list which would allow something like ContainerClass*m_containers[FC+1] if I'm not mistaken.)
There's not really a good way to do this, usually you see an extra item in the enum, i.e. enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS}; So then you can do: int fuz[FOOBAR_NR_ITEMS]; Still not very nice though. But of course you do realize that just the number of items in an enum is not safe, given e.g. enum foobar {foo, bar = 5, baz, quz = 20}; the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options. edit: as requested, made the special entry stick out more.
2,102,907
2,102,943
Which side (left or right) of && (and) operator evaluated in C++
Which order is the and && operator evaluated For example the following code if (float alpha = value1-value2 && alpha > 0.001) //do something threw an exception that alpha is being used without being initiated. I thought the expression left of the && would always initiate the value of alpha first, but it seems I may be wrong Any idea? Thanks
This gets parsed as: if (int alpha = (value1-value2 && (alpha > 0.001))) ... because && has a higher "parsing precedence" than = -- which is probably not what you want. Try: int alpha = value1-value2; if (alpha && (alpha > 0.001))