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,846,138
2,846,148
Microsoft #include header file (.h) for "_HFILE"
I'm trying to compile some Microsoft SAPI example code in a non-Microsoft C++ Compiler, and am getting an error at this line: _HFILE m_hfilePrev; Presumably because it doesn't recognize the _HFILE #define. Does anybody know what .h file I should include for that?
It is defined in crtdbg.h typedef void *_HFILE; /* file handle pointer */
2,846,310
2,846,320
Are .dll files loaded once for every program or once for all programs?
I have a simple small question which someone who knows will be able to answer easily, I searched google but couldn't find the answer. There are many programs running at once on a computer, and my question is: when a program loads a DLL, does it actually load the DLL file or does it find the memory in which the DLL is already loaded? For example, is ws2_32.dll (winsock 2) loaded for every program that uses winsock, or is it loaded once and all programs that use it use the same memory addresses to call the functions?
It's loaded once and all programs share the same in-memory copy of code. It's kind of complicated, but for the read-only sections of the DLL (that is, code) the operating system loader uses a technique called "memory mapping" to map the DLL into the process's address space. The pages are only loaded into physical memory once for all processes, even though they may have the page mapped to different address in their virtual address space. However, each process has a separate data section (so that global variables are not shared - unless you explicitly ask them to be) and they obviously also have a separate heap so that dynamically-allocated memory is not shared.
2,846,501
2,846,514
atol(), atof(), atoi() function behaviours, is there a stable way to convert from/to string/integer?
In these days I'm playing with the C functions of atol(), atof() and atoi(), from a blog post I find a tutorial and applied: Here are my results: void main() { char a[10],b[10]; puts("Enter the value of a"); gets(a); puts("Enter the value of b"); gets(b); printf("%s+%s=%ld and %s-%s=%ld",a,b,(atol(a)+atol(b)),a,b,(atol(a)-atol(b))); getch(); } There is atof() which returns the float value of the string and atoi() which returns integer value. Now to see the difference between the 3 I checked this code: main() { char a[]={"2545.965"}; printf("atol=%ld\t atof=%f\t atoi=%d\t\n",atol(a),atof(a),atoi(a)); } The output will be atol=2545 atof=2545.965000 atoi=2545 char a[]={“heyyou”}; Now when you run the program the following will be the output (why?, is there any solution to convert pure strings to integer?) atol=0 atof=0 atoi=0 The string should contain the numeric value. Now modify this program as char a[]={“007hey”}; The output in this case (tested in Red Hat Linux) will be atol=7 atof=7.000000 atoi=7 so the functions have taken 007 only, not the remaining part (why?). Now consider this char a[]={“hey007?}; The output of the program will be atol=0 atof=0.000000 atoi=0 So I just want to convert my strings to numbers and then again to the same text. I played with these functions, and, as you see, I'm getting really interesting results. Why is that? Are there any other functions to convert from/to string/integer and vice versa? EDIT: So as an input, if I take some names, or whatever, I will convert them to integers/floats... then apply some other functions. Also I'm curious about if I will take the same output with the same inputs when I use any of your suggestions?
The high-end solution to this problem, given that you also added a C++ tag, is to use Boost lexical_cast.
2,846,502
2,846,535
Build System with Recursive Dependency Aggregation
I recently began setting up my own library and projects using a cross platform build system (generates make files, visual studio solutions/projects etc on demand) and I have run into a problem that has likely been solved already. The issue that I have run into is this: When an application has a dependency that also has dependencies then the application being linked must link the dependency and also all of its sub-dependencies. This proceeds in a recursive fashion e.g. (For arguments sake lets assume that we are dealing exclusively with static libraries.) TopLevelApp.exe dependency_A dependency_A-1 dependency_A-2 dependency_B dependency_B-1 dependency_B-2 So in this example TopLevelApp will need to link dependency_A, dependency_A-1, dependency_A-2 etc and the same for B. I think the responsibility of remembering all of these manually in the target application is pretty sub optimal. There is also the issue of ensuring the same version of the dependency is used across all targets (assuming that some targets depend on the same things, e.g. boost). Now linking all of the libraries is required and there is no way of getting around it. What I am looking for is a build system that manages this for you. So all you have to do is specify that you depend on something and the appropriate dependencies of that library will be pulled in automatically. The build system I have been looking at is premake premake4 which doesn't handle this (as far as I can determine). Does anyone know of a build system that does handle this? and if there isn't then why not?
The typical way that this is handled is by having the library on which you depend tell you what it, in turn, requires and what versions it has linked against. One way of doing this is via pkg-config. For example, if you invoke pkg-config name_of_package --cflags, it will print out the necessary flags that should include flags needed to add headers of indirect dependencies. Similarly, pkg-config name_of_package --ldflags would print the necessary linker flags that include that particular library as well as its dependencies. As for build system, my recommendation would be to use CMake. In CMake, dependencies are found via an invocation of FIND_PACKAGE(name_of_package), which in turn defines the variable name_of_package_FOUND as 1 if the package was found, and also -- if it was found -- defines name_of_package_LIBRARIES and name_of_package_INCLUDE_DIRS to the libraries and header paths for that package as well as to the libraries and headers of its dependencies. That said, the FIND_PACKAGE mechanism works via pluggable modules written by third parties, and so while the system is supposed to set the _LIBRARIES and _INCLUDE_DIRS variables such that dependencies of dependencies are included recursively, not all of the modules do this correctly last I checked.
2,846,546
2,846,579
number of elements in a static array of a predefined size
I have an array like this: int a[100]; I am filling only the first 4 elements in this array: a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; When I do sizeof(a)/sizeof(a[0]) it returns 100. Is there a way I can get number of elements to which I have assinged a value and thus filtering out the remaining 96 unassigned elements? thanks
All elements must be assigned to something, thus the array always has 100 elements. If you can ensure all the elements are initialized to a special value which means "unassigned" to you (e.g. -1), you can work it out like this: // fill the array with a special value which means "uninitialized" const int special_uninitialized = -1; std::fill(&a[0], &a[100], special_uninitialized); // set up your values a[0] = 1; // count std::size_t uninitialized_count = std::count(&a[0], &a[100], special_uninitialized); std::size_t initialized_count = 100 - uninitialized_count; If you just want to know how many elements are in an array, you have these options: Don't use an array, use std::vector, which has a size() function, and is generally a better choice than a basic array Keep track of the element count yourself, in a separate variable Use the special "unassigned" value as described above, and use std::find to find the first one, and work out how many are there by subtracting the address of the zeroth element from that. This is a pretty ugly solution. For a beginner, std::vector is a much better choice. You can use it like this: std::vector<int> vec; vec.push_back(17); vec.push_back(23); vec.push_back(5); int x = vec[0]; // x will be 17 vec[0] = 40; // set element 0 size_t s = vec.size(); // s will be 3
2,846,611
2,846,776
Visual Studio 2008 compiler macro reference or tutorial?
Does anyone know the location of a good list or tutorial showing all the compiler macros (_T etc) in use in Visual Studio 2008?
See here: a starting point for C++ specific: http://msdn.microsoft.com/en-us/library/503x3e3s(v=VS.80).aspx a general list: http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx a starting point for MFC: http://msdn.microsoft.com/en-us/library/f2dch7fb(v=VS.100).aspx
2,846,622
2,846,661
Creating a menustrip in WinAPI?
Is there a way to get a menustrip instead of an HMENU when using the WinAPI? Like menus that .Net applications use? Because the HMENU just doesn't fit my color scheme, I need a darker menu. Thanks
If you don't like the system defaults, you can owner-draw the menu. If you only need to support Windows Vista and higher, you can follow this article. Otherwise you need to call ModifyMenu() on your menu items and set MF_OWNERDRAW and everything that comes with that.
2,846,644
2,846,650
C++ Type error with Object versus Object reference
I have the following function (which worked in Visual Studio): bool Plane::contains(Vector& point){ return normalVector.dotProduct(point - position) < -doubleResolution; } When I compile it using g++ version 4.1.2 , I get the following error: Plane.cpp: In member function âvirtual bool Plane::contains(Vector&)â: Plane.cpp:36: error: no matching function for call to âVector::dotProduct(Vector)â Vector.h:19: note: candidates are: double Vector::dotProduct(Vector&) So as you can see, the compiler thinks (point-position) is a Vector but it's expecting Vector&. What's the best way to fix this? I verified that this works: Vector temp = point-position; return normalVector.dotProduct(temp) < -doubleResolution; But I was hoping for something a little bit cleaner. I heard a suggestion that adding a copy constructor might help. So I added a copy constructor to Vector (see below), but it didn't help. Vector.h: Vector(const Vector& other); Vector.cpp: Vector::Vector(const Vector& other) :x(other.x), y(other.y), z(other.z), homogenous(other.homogenous) { }
Your problem is that the result of point - position is a temporary object, which cannot be bound to a non-const reference. If a function does not modify an argument taken by reference, then it should take a const reference. Ergo, your dot product function should be declared as: double Vector::dotProduct(const Vector&);
2,846,844
2,854,818
Wii MotionPlus support
I am developing a PC application that interacts with the Wiimote. So far I have been using the wiiuse library, which has worked great. However, wiiuse does not support the MotionPlus extension. I have heard of extensions to implement this by Dolphin and libogc but have not managed to locate this code. Do you know of code that implements support for MotionPlus with wiiuse, or another C based libary?
I found that fWIIne has a modded version with MotionPlus support, though only in the release zip file and not the repository.
2,846,872
2,846,893
Thread-safe get (accessor method)
I'm currently using the following code for thread-safe access of a variable. int gnVariable; void getVariableValue(int *pnValue) { acquireLock(); //Acquires the protection mechanism *pnValue = gnVariable; releaseLock(); //Releasing the protection mechanism } I would like to change my API signature to a more user-friendly int getVariableValue(void); How should I rewrite the function - such that the users of the API don't have to bother about the locking/unlocking details?
Since you gave C++ as an option, you can wrap the mutex lock/unlock. You can then return the value directly: class lock_wrapper { public: lock_wrapper() { acquireLock(); } ~lock_wrapper() { releaseLock(); } }; int getVariableValue() { lock_wrapper lw; return gnVariable; } This will also come in handy if you ever need to do a lock/unlock around code that can throw an exception.
2,846,939
2,846,950
List<MyClass*> & array question
Assuming a definition like this, void CConfigTest::OnSelchangedTree(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; TVITEM item = pNMTreeView->itemNew; // find the session of the selected item if(item.hItem != NULL) { HTREEITEM root, parent, node; node = item.hItem; parent = m_treeSM.GetParentItem(item.hItem); root = m_treeSM.GetRootItem(); while(parent != root && parent != NULL) { node = parent; parent = m_treeSM.GetParentItem(parent); } MyCommand* pCmd = (MyCommand*)(m_treeSM.GetItemData(node)); .... .... I tried these statements below, but failed. pCmd->subList[2] (pCmd->subList)[2] How can I get the array member values(such as subList[2]). I want to replace the value of subList[2] with other same type value. Thank you.
Lists do not support random access. You need to switch to another container type which does, or iterate over the list until you reach the element you want.
2,847,019
2,847,073
Flexible string handling in Visual Studio 2008 C++
I'm slowly starting to get the hang of the _T stuff in Visual Studio 2008 c++, but a few things still elude me. I can see the benefit of the flexibility, but if I can't get the basics soon, I think I'll go back to the standard way of doing this - much less confusing. The idea with the code below is that it scans the parameters for -d and then stores the text that follows that in the string variable fileDir. It also ignores any other parameters. Any help is appreciated. //Console application Parameters::Parameters(int argc, _TCHAR* argv[]) { _Tstring fileDir; // Is there some kind of _t variable to use here for a string? for (int i = 0; i < argc; i = i + 1) { if (_tccmp(argv[i], _T("-d")) == 0) // this appeared to accept anything starting with - { i = i + 1; fileDir = argv[i] } } _tprintf("Parameter value found: %s\n", fileDir); }
You can use _tstring to represent and std::string with a TCHAR parameter. Also, the name of the function is _tcscmp, not _tccmp so I don't see how that code snippet could even compile? To be honest, I wouldn't bother with any of that, though. The whole TCHAR stuff was useful back when people were writing code that was to be portable between Windows 9X (which was Ansi internally) and Windows NT (which was/is Unicode internally). These days, there's very little benefit to using the macros. If you want to do anything, you can switch to wchar_t entirely. That means prefixing string literals with "L", as in L"Some wide-char string" and using the 'w' versions of functions (e.g. std::wstring, wcscmp, etc). But even that might be considered overkill for many scenarios.
2,847,153
2,847,417
How to draw a web page into a memory DC?
I would like to trick Chrome in to rendering its tabs in some memory device context of mine. Is this possible at all ? Thank you !
There's a method in chrome.tabs called captureVisibleTab. What you get back is either a PNG or JPEG. http://code.google.com/chrome/extensions/tabs.html That API is available to Chrome extensions - but you can't call it from ordinary JavaScript in an unextended browser. I presume this is the technique used by "Aviary Screen Capture". If you have a C++ program running in its own process, and you want to "poke into" Chrome - there are a lot of dodgy ways to do window hooks and capturing. But why not save yourself the trouble? Chrome is based on WebKit - just use WebKit directly. Qt makes it super easy, for instance: http://doc.qt.nokia.com/4.6/examples-webkit.html
2,847,310
2,847,350
C++ smart pointer for a non-object type?
I'm trying to use smart pointers such as auto_ptr, shared_ptr. However, I don't know how to use it in this situation. CvMemStorage *storage = cvCreateMemStorage(); ... use the pointer ... cvReleaseMemStorage(&storage); I'm not sure, but I think that the storage variable is just a malloc'ed memory, not a C++ class object. Is there a way to use the smart pointers for the storage variable? Thank you.
shared_ptr allows you do specify a custom deallocator. However, looking at the documentation cvReleaseMemStorage() doesn't have the right form (void f(T*)) and you need a wrapper: void myCvReleaseMemStorage(CvMemStorage* p) { cvReleaseMemStorage(&p); } shared_ptr<CvMemStorage> sp(cvCreateMemStorage(), &myCvReleaseMemStorage);
2,847,334
2,847,362
Constructor initialization list: code from the C++ Primer, chapter 16
Toward the end of Chapter 16 of the "C++ Primer" I encountered the following code (I've removed a bunch of lines): class Sales_item { public: // default constructor: unbound handle Sales_item(): h() { } private: Handle<Item_base> h; // use-counted handle }; My problem is with the Sales_item(): h() { } line. For the sake of completeness, let me also quote the parts of the Handle class template that I think are relevant to my question (I think I don't need to show the Item_base class): template <class T> class Handle { public: // unbound handle Handle(T *p = 0): ptr(p), use(new size_t(1)) { } private: T* ptr; // shared object size_t *use; // count of how many Handles point to *ptr }; I would have expected something like either: a) Sales_item(): h(0) { } which is a convention the authors have used repeatedly in earlier chapters, or b) Handle<Item_base>() if the intention was to invoke the default constructor of the Handle class. Instead, what the book has is Sales_item(): h() { }. My gut reaction is that this is a typo, since h() looks suspiciously similar to a function declaration. On the other hand, I just tried compiling under g++ and running the example code that uses this class and it seems to be working correctly. Any thoughts? EDIT: All good answers, thanks! I have in the intervening 30 minutes tracked down a relevant quote from chapter 12 of the same book: "When we initialize a member of class type, we are specifying arguments to be passed to one of the constructors of that member's type. We can use any of that type's constructors." And as you all pointed out, in this case we are passing zero arguments.
What you have with Sales_item(): h() { } is a constructor with a data member initialization. I would have expected something like either: a) Sales_item(): h(0) { } which is a convention the authors have used repeatedly in earlier chapters, or This isn't necessary because the constructor of Handle<Item_base>() can be invoked without an argument. (Its one argument has a default value, so it can be omitted.) b) Handle<Item_base>() if the intention was to invoke the default constructor of the Handle class. This is simply incorrect syntax. That syntax is used for base classes and there it is fine, since any class can inherit only once from Handle<Item_base>(). However, it can have many data elements of that type, so in order to initialize the right data member, its name is used rather than its type. That's a very good book you're learning from, BTW. Once you're through it, you might want to look at The Definitive C++ Guide and List for more good input.
2,847,410
2,848,961
Goal of C's "auto" keyword
What is the goal of the "auto" keyword in C? With C++ 0x it got new meaning but does it mean that my code will break if I port C code over to a C++ 0x compiler?
Bjarne Stroustrup mentions in his C++0x FAQ about auto: "The old meaning of auto ("this is a local variable") is redundant and unused. Several committee members trawled through millions of lines of code finding only a handful of uses -- and most of those were in test suites or appeared to be bugs." So I assume, that compilers wil not be forced by the standard to implement the old meaning of auto.
2,847,488
2,847,529
Is RegSetValueEx thread safe?
I suspect that RegSetValueEx is thread safe, but would like some confirmation from the community. If called from multiple threads, will there be any side effects? The RegSetValueEx MSDN documentation doesn't mention thread safety at all.
related Q: Is the Win32 Registry ‘thread safe’?
2,847,729
2,847,747
What's the main difference between stdlib.h and cstdlib in C++?
I'm using EXIT_FAILURE macro, so I need to include stdlib.h or cstdlib. But I don't know what the difference is. Should I use cXXX style header file rather than XXX.h? Thank you.
As EXIT_FAILURE is a macro, it makes no difference which you include. The cstdlib version will put the names of all the functions into the std namespace, so you can say things like: std::exit(0); but as macros don't respect namespaces, you can't say: std::EXIT_FAILURE
2,847,734
2,847,768
Is `auto int i` valid C++0x?
In answering this question the question arose as to whether the traditional C meaning of the keyword auto (automatic storage) is still valid in C++0x now that it means type deduction. I remember that the old meaning of auto should remain where relevant but others disagreed. auto char c = 42; // either compilation error or c = '*' Looking at compilers I see the current division. Old meaning of auto is no longer allowed VS10 g++ Old meaning of auto is used where relevant Comeau Do you know which is the correct behaviour?
No, it is not. In fact, §7.1.6.​4/3 gives the following example: auto x = 5; // OK: x has type int const auto *v = &x, u = 6; // OK: v has type const int*, u has type const int static auto y = 0.0; // OK: y has type double auto int r; // error: auto is not a storage-class-specifier As you can see, it results in an error. §7.1.6.​5 pretty much seals the deal with: A program that uses auto in a context not explicitly allowed in this section is ill-formed.
2,847,787
2,847,835
Constructor or Assignment Operator
Can you help me is there definition in C++ standard that describes which one will be called constructor or assignment operator in this case: #include <iostream> using namespace std; class CTest { public: CTest() : m_nTest(0) { cout << "Default constructor" << endl; } CTest(int a) : m_nTest(a) { cout << "Int constructor" << endl; } CTest(const CTest& obj) { m_nTest = obj.m_nTest; cout << "Copy constructor" << endl; } CTest& operator=(int rhs) { m_nTest = rhs; cout << "Assignment" << endl; return *this; } protected: int m_nTest; }; int _tmain(int argc, _TCHAR* argv[]) { CTest b = 5; return 0; } Or is it just a matter of compiler optimization?
What is happening here depends a bit on your compiler. It could create a temporary object using the int constructor and then copy construct b from that temporary. It will most likely elide the copy constructor call however. In neither case will the assignment operator be used.
2,847,872
2,848,255
GUI system architecture?
I'm designing GUI (graphical user interface) system for a game engine (C++). Idea is to create a heirarchy of GUI controllers like Focusable, Hoverable, Dragable etc. Every GUI component can attach multiple controllers, they modify component's behaviour. I think it gives flexible system and protects from code duplication. Different instances of the same GUI class can have different complex behaviours (may be, even change it dynamically), so this approach looks practical. The other choice is to add focused, hovered, dragged etc. flags in the base GUI component class. It looks like overhead and not that flexible. Another solution is to use Decorator pattern and wrap objects with FocusDecorator, HoverDecorator etc. Maintaining such system looks a bit harder. Question: What are pitfalls in my solution? May be you have seen a better approaches in GUI systems? What are the best ways of implementing such flexible complex system?
Your solution is quite good, to be honest, I think it is exactly what the Decorator design pattern is about, however in C++ you have better implementation techniques at hand. You can easily use policy based design to create GUI component template class and add component behaviour trait classes as its arguments and then inherit from the arguments.
2,848,068
2,848,183
boost::regex_replace() replaces only first occurrence, why?
My code: #include <string> #include <boost/algorithm/string/regex.hpp> std::cout << boost::algorithm::replace_regex_copy( "{x}{y}", // source string boost::regex("\\{.*?\\}"), // what to find std::string("{...}") // what to replace to ); This is what I see: {…}{y} Thus, only the first occurrence replaced. Why? How to solve it?
You might want to use replace_all_regex_copy() instead of replace_regex_copy()
2,848,087
2,848,109
How to clear stringstream?
stringstream parser; parser << 5; short top = 0; parser >> top; parser.str(""); //HERE I'M RESETTING parser parser << 6; //DOESN'T PUT 6 INTO parser short bottom = 0; parser >> bottom; Why doesn't it work?
Typically to 'reset' a stringstream you need to both reset the underlying sequence to an empty string with str and to clear any fail and eof flags with clear. parser.str( std::string() ); parser.clear(); Typically what happens is that the first >> reaches the end of the string and sets the eof bit, although it successfully parses the first short. Operations on the stream after this immediately fail because the stream's eof bit is still set.
2,848,347
2,848,571
How can I access all matches of a repeated capture group, not just the last one?
My code is: #include <boost/regex.hpp> boost::cmatch matches; boost::regex_match("alpha beta", matches, boost::regex("([a-z])+")); cout << "found: " << matches.size() << endl; And it shows found: 2 which means that only ONE occurrence is found… How to instruct it to find THREE occurrences? Thanks!
This is what I've found so far: text = "alpha beta"; string::const_iterator begin = text.begin(); string::const_iterator end = text.end(); boost::match_results<string::const_iterator> what; while (regex_search(begin, end, what, boost::regex("([a-z]+)"))) { cout << string(what[1].first, what[2].second-1); begin = what[0].second; } And it works as expected. Maybe someone knows a better solution?
2,848,585
2,848,628
cpp/Qt : per class debugging
I'm developing a Qt application. For each class, I'm trying to mimic the framework, such as error() and errorString() method, use of Private implementation. But I would like to add a per class debugging: Set a macro to the desired level of debug, have a macro or a function that knows the level of debug, and use qDebug() or qWarning() which is class independant, and will know the current class's name (for some pretty prints) Anyone have a good idea to implement this ?
You may write a class, for example CDebug with all needed debug methods, and use it in other classes, like: class CMyDialog : public QDialog, public CDebug {...};
2,848,809
2,848,884
Set size of scroll thumb?
I'v looked on MSDN and can't find how to do this. It lets me set the range and position but not the thumb that the user clicks and drags. Thanks
You want to set the scroll page size, so it calculates the proportional size of the bar given the range and page size. Look at SetScrollInfo and related functions.
2,848,928
2,849,024
Strange C++ thread function invocation
I have the following: class DThread { virtual void run()=0; _beginthreadex(NULL,0,tfunc,this,0,&m_UIThreadID); // class itself being passed as param to thread function... static unsigned int __stdcall tfunc(void* thisptr) { static_cast<DThread*>(thisptr)->run(); return 0; } //other stuff } The run function is implemented in a derived class. Why is the function that's being called in the thread being called through a cast this pointer? Is this good practise? Can't it just be called directly? The actual function needing to run is in the derived class. My question is
Most platform-level thread APIs are bare-bones C and take a plain pointer to function to run in new thread. This means in C++ that function has to be either a free function or a static member. Neither of these give access to any class instance. The workaround for building statefull thread classes is to exploit additional "pass-through" argument of the thread creation call (that's usually a pointer that is later passed to the function executed in the new thread) and give it a pointer to the class itself, i.e. this. The static function could then call a [virtual] member, say run() or something like that.
2,849,795
2,849,818
Is there a standard C++ grammar?
Does the standard specify the official C++ grammar? I searched, but did not find it anywhere. Also, I wish to read a bit about C++ grammar in detail, like which category of grammars it falls in, etc. Any links pointing me in the right direction would be helpful. By category, I mean taken from here.
Yes, it does. The grammar is described in detail throughout the standard and is summarized in Appendix A: Grammar Summary (it's Appendix A in both the C++03 standard and the C++0x final committee draft). You can purchase the C++03 standard or you can download the C++0x FCD (it's document n3092 on that page). To answer the "what category is it in?" question, the C++ grammar is not context-free (also see the questions linked in answers to that question; they have additional examples of issues related to the C++ grammar and parsing C++).
2,849,827
4,539,399
Translations using Qt Linguist?
I am working on Ubuntu 9.10 aka Karmic Kola and latest version of gcc, Qt 4.6.2. I have installed the french fonts and hindi fonts for ubuntu. I changed the language and Keyboard layout accordingly so that I could type in the abovementioned languages. It worked fine. I then made a sample application and added appropriate translations in Hindi and French. The linguist tool worked fine then. I was able to type in Hindi in Linguist. This was around a week back. Today I was making a different application with Hindi translations, with the steps that I did earlier using Qt Linguist. But now when I type in Hindi in Qt Linguist it gives only one character(for any keypress) which is like "=" with more space between the two horizontal bars in "equal to" sign. In the .ts file generated by lrelease the translations are displayed perfectly but on execution again characters in the form of squares appear as the translated text. I have tried umpteen times, even changing the codecrtr in .pro file but to no effect. Can somebody point out why Qt Linguist is interpreting hindi characters as "=" but when typed in other applications like openoffice writer and browsers its perfect hindi fonts? I have torn my hair the whole day on this seemingly annoying problem. Didn't try for french though :). Thanks
After banging my head many times on this problem, I decided to try translations on a newer version of Qt and VOILA it did the trick. Probably there is a bug in Qt translations module in the version I was using. Notified Qt guys about the same. Hope others will find this information valuable. Cheers!!!
2,849,901
2,849,982
empty struct definitions illegal in C but not C++?
struct t_empty { }; This appears to compile properly in C++ but not C. (at least with the TI 28xx DSP compiler, where it emits the error "expected a declaration") Is this mentioned somewhere in the C standards, or is my compiler broken?
Empty struct is a syntax error in C. The grammar of C language is written so that it prohibits empty structs. I.e. you won't find it stated in the standard explicitly, it just follows from the grammar. In C++ empty classes are indeed legal. P.S. Note, that often you might see the quote from the C standard that says "If the struct-declaration-list contains no named members, the behavior is undefined.", which is presented as the portion of the document that prohibits empty structs. In reality, empty structs are, again, prohibited by the grammar. So a literally empty struct (as in your question) is a syntax error, not undefined behavior. The above quote from the standard applies to a different situation: a struct with no named members. A struct can end up non-empty, but at the same time with no named members if all members are unnamed bitfields struct S { int : 5; }; In the above case the behavior is undefined. This is what the above quote is talking about.
2,850,142
2,850,239
How can I use boost::thread::id as key to an unordered_map?
According to the documentation, a boost::thread::id can be considered unique for each running thread and can be used in containers such as std::set and std::map (because the < operator is overridden for thread::id). My problem is that I'd like to use thread::id as a key to an boost::unordered_map, however it requires that the key is "hashable" (ie. supports hashing to a size_t). Since all implementation detail for thread::id is hidden I don't think have anything I can use. So my question is - is it possible to use thread::id as a key to an unordered_map?
You can use the streaming ability: struct Hasher { size_t operator()(const boost::thread::id& id) { std::ostringstream os; os << id; return hash(os.str()); } }; Little excerpt of the class, so that others may see what's possible: class thread::id { public: id(); bool operator==(const id& y) const; bool operator!=(const id& y) const; bool operator<(const id& y) const; bool operator>(const id& y) const; bool operator<=(const id& y) const; bool operator>=(const id& y) const; template<class charT, class traits> friend std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const id& x); };
2,850,157
2,866,408
How to delete ProgIDs from other user accounts when uninstalling from Windows?
I've been investigating "how should a modern windows c++ application register its file types" with Windows (see C++: How do I correctly register and unregister file type associations for our application (programatically)). And having combed through the various MSDN articles on the subject, the summary appears to be as follows: The installer (elevated) should register the global ProgID HKLM\Software\Classes\my-app.my-doc[.version] (e.g. HKLM\Software\Classes\TextPad.text) The installer also configures default associations for its document types (e.g. .myext) and points this to the aforementioned global ProgID in HKLM. NOTE: a user interface should be provided here to allow the user to either accept all default associations, or to customize which associations should be set. The application, running standard (unelevated), should provide a UI for allowing the current user to set their personal associations as is available in the installer, except that these associations are stored in HKCU\Software\Classes (per user, not per machine). The UN-installer is then responsible for deleting all registered ProgIDs (but should leave the actual file associations alone, as Windows is smart enough to handle associations pointing to missing ProgIDs, and this is the specified desired behavior by MSDN). So that schema sounds reasonable to me, except when I consider #4: How does an uninstaller, running elevated for a given user account, delete any per-user ProgIDs created in step #3 for other users? As I understand things, even in elevated mode, an uninstaller cannot go into another user's registry hive and delete items? Or can it? Does it have to load each given user hive first? What are the rules here? Thanks for any insight you might have to offer! EDIT: See below for the solution (My question was founded in confusion)
I just realized: What MS wants us to do is to have per-user override the file mapping itself - i.e. .foo -> what? NOT create any progIDs, which should only be created by the installer, which are deleted by their uninstaller, so no "dangling ProgIDs" - only "dangling file mappings" which map to a missing ProgID, which MS explicitly states is OK. Before install: HKCR\.txt -> HKCR\txtfile (global) After install: HKCR\.txt -> HKCR\MyEditor.text.1 (global) A user decides they want to map .txt files to TextPad instead: HKCU\Software\Classes\.txt -> HKCR\TextPad.txt (this user only, globally still .txt->MyEditor.text.1) After uninstall: HKCR\.txt x-> HKCR\MyEditor.text.1 (global, but the key HKCR\MyEditor.txt.1 has been deleted) And the one user who overrode their value is still okay because wherever their individual copy of .txt points is either valid or not, either way, Microsoft handles it. I hope that helps others...
2,850,312
2,850,354
Use of for_each on map elements
I have a map where I'd like to perform a call on every data type object member function. I yet know how to do this on any sequence but, is it possible to do it on an associative container? The closest answer I could find was this: Boost.Bind to access std::map elements in std::for_each. But I cannot use boost in my project so, is there an STL alternative that I'm missing to boost::bind? If not possible, I thought on creating a temporary sequence for pointers to the data objects and then, call for_each on it, something like this: class MyClass { public: void Method() const; } std::map<int, MyClass> Map; //... std::vector<MyClass*> Vector; std::transform(Map.begin(), Map.end(), std::back_inserter(Vector), std::mem_fun_ref(&std::map<int, MyClass>::value_type::second)); std::for_each(Vector.begin(), Vector.end(), std::mem_fun(&MyClass::Method)); It looks too obfuscated and I don't really like it. Any suggestions?
You can iterate through a std::map object. Each iterator will point to a std::pair<const T,S> where T and S are the same types you specified on your map. Here this would be: for (std::map<int, MyClass>::iterator it = Map.begin(); it != Map.end(); ++it) { it->second.Method(); } If you still want to use std::for_each, pass a function that takes a std::pair<const int, MyClass>& as an argument instead. Example: void CallMyMethod(std::pair<const int, MyClass>& pair) // could be a class static method as well { pair.second.Method(); } And pass it to std::for_each: std::for_each(Map.begin(), Map.end(), CallMyMethod);
2,850,433
2,851,443
Using a class callback for a custom control?
I'm creating a custom control class and since I want complete control of it, I register the class and want to use the class's LRESULT CALLBACK OGLTOOLBAR::ToolProc(HWND, UINT, WPARAM, LPARAM) but it's not letting me. I'm doing: HWND OGLTOOLBAR::create(HWND parent,HINSTANCE hInst, int *toolWidthPtr) { if (toolhWnd != NULL) { return toolhWnd; } toolWidth = toolWidthPtr; ZeroMemory(&rwc,sizeof(rwc)); rwc.lpszClassName = TEXT("OGLTool"); rwc.hbrBackground = GetSysColorBrush(COLOR_BTNSHADOW); rwc.lpfnWndProc = (WNDPROC)ToolProc; rwc.hCursor = LoadCursor(0, IDC_ARROW); RegisterClass(&rwc); toolhWnd = CreateWindowEx(NULL, rwc.lpszClassName,NULL, WS_CHILD | WS_VISIBLE, 0, 0, *toolWidth, 900, parent, 0, NULL, 0); return toolhWnd; } what is the correct way of doing this? Thanks compiler says: Error 1 error C2440: 'type cast' : cannot convert from 'overloaded-function' to 'WNDPROC'
If ToolProc isn't a static member, you can't pass a member function pointer as a callback like that, assuming you want ToolProc to be a non-static function, you can create a static member function, and use the GetWindowLong/SetWindowLong and the GWL_USERDATA area, to store a pointer to the current object(this), and have a static callback call the individual objects callback function, that can utilize the individual objects data members. Assuming that ToolProc is not a static member of your OGLTOOLBAR class, you have to tie the this pointer of the object to the window handle, you can do this like so: void OGLTOOLBAR::SetObjectToHWnd( HWND hWnd, LPARAM lParam ) { LPCREATESTRUCT cs = reinterpret_cast<LPCREATESTRUCT>(lParam); OGLTOOLBAR *pWnd = reinterpret_cast<OGLTOOLBAR*>(cs->lpCreateParams); SetLastError( 0 ); if( !SetWindowLong( hWnd, GWL_USERDATA, reinterpret_cast<long>(pWnd) ) && GetLastError() ) //Do something about the error } OGLTOOLBAR *OGLTOOLBAR::GetObjectFromHWnd( HWND hWnd ) { return reinterpret_cast<OGLTOOLBAR*>(GetWindowLong(hWnd,GWL_USERDATA)); } And then you have a static WndProc(Or ToolProc) member function like this: LRESULT OGLTOOLBAR::StaticToolProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { if( uMsg == WM_NCCREATE ) SetObjectToHwnd( hWnd, lParam ); Window *pWnd = GetObjectFromWnd( hWnd ); if( pWnd ) return pWnd->ToolProc( hWnd, uMsg, wParam, lParam ); else return DefWindowProc( hWnd, uMsg, wParam, lParam ); } And then when you call the CreateWindow function in OGLTOOLBAR::create, pass reinterpret_cast<void*>(this) as the lpParam argument(The last one). And each OGLTOOLBAR object will then have it's own ToolProc called for each instance, through the StaticToolProc function. Or at least I believe this should work.
2,850,613
2,850,729
Reading lines from a file using std:: istream_iterator. Who?
Possible Duplicate: How do I iterate over cin line by line in C++? I need to read all lines from a file: std::ifstream file("..."); std::vector<std::string> svec( (std::istream_iterator<std::string>(file)), (std::istream_iterator<std::string>()), ); but it is read as words.
I believe the issue is that the input methods for std::string will read until a space character is found, then terminate. Have you tried using std::getline inside a loop? Check out the C++ FAQ.
2,850,646
2,860,583
Fill container with template parameters
I want to fill the template parameters passed to a variadic template into an array with fixed length. For that purpose I wrote the following helper function templates template<typename ForwardIterator, typename T> void fill(ForwardIterator i) { } template<typename ForwardIterator, typename T, T head, T... tail> void fill(ForwardIterator i) { *i = head; fill<ForwardIterator, T, tail...>(++i); } the following class template template<typename T, T... args> struct params_to_array; template<typename T, T last> struct params_to_array<T, last> { static const std::size_t SIZE = 1; typedef std::array<T, SIZE> array_type; static const array_type params; private: void init_params() { array_type result; fill<typename array_type::iterator, T, head, tail...>(result.begin()); return result; } }; template<typename T, T head, T... tail> struct params_to_array<T, head, tail...> { static const std::size_t SIZE = params_to_array<T, tail...>::SIZE + 1; typedef std::array<T, SIZE> array_type; static const array_type params; private: void init_params() { array_type result; fill<typename array_type::iterator, T, last>(result.begin()); return result; } }; and initialized the static constants via template<typename T, T last> const typename param_to_array<T, last>::array_type param_to_array<T, last>::params = param_to_array<T, last>::init_params(); and template<typename T, T head, T... tail> const typename param_to_array<T, head, tail...>::array_type param_to_array<T, head, tail...>::params = param_to_array<T, head, tail...>::init_params(); Now the array param_to_array<int, 1, 3, 4>::params is a std::array<int, 3> and contains the values 1, 3 and 4. I think there must be a simpler way to achieve this behavior. Any suggestions? Edit: As Noah Roberts suggested in his answer I modified my program like the following: I wrote a new struct counting the elements in a parameter list: template<typename T, T... args> struct count; template<typename T, T head, T... tail> struct count<T, head, tail...> { static const std::size_t value = count<T, tail...>::value + 1; }; template<typename T, T last> stuct count<T, last> { static const std::size_t value = 1; }; and wrote the following function template<typename T, T... args> std::array<T, count<T, args...>::value> params_to_array() { std::array<T, count<T, args...>::value> result; fill<typename std::array<T, count<T, args...>::value>::iterator, T, args...>(result.begin()); return result; } Now I get with params_to_array<int, 10, 20, 30>() a std::array<int, 3> with the content 10, 20 and 30. Any further suggestions?
There is no need to count the number of types in a parameter pack manually, thats what the sizeof... operator is for. Additionally i'd make the iterator type for fill() deducible, there is no need to specify it explicitly: template<typename T, typename FwdIt> void fill(FwdIt it) { } template<typename T, T head, T... tail, typename FwdIt> void fill(FwdIt it) { *it = head; fill<T, tail...>(++it); } template<class T, T... args> std::array<T, sizeof...(args)> params_to_array() { std::array<T, sizeof...(args)> a; fill<T, args...>(a.begin()); return a; }; Parameter packs however are also expandable in initializer-list contexts, which makes fill() redundant: template<class T, T... args> std::array<T, sizeof...(args)> params_to_array() { std::array<T, sizeof...(args)> a = {{args...}}; return a; };
2,850,815
2,851,586
What is the inet_addr function equivalent in C#
i need to know how to use an IP address like inet_addr("192.168.0.2"); in C++ where this returns DWORD. My wrapper in C# treats this field as an Int? Can anyone help on this misunderstanding?
You should use the IPAddress class. It will hassle you a bit because it tries to prevent you from taking a dependency on IP4 addresses. The Address member is declared obsolete. Here is the workaround: using System; using System.Net; class Program { static void Main(string[] args) { var addr = IPAddress.Parse("192.168.0.2"); int ip4 = BitConverter.ToInt32((addr.GetAddressBytes()), 0); Console.WriteLine("{0:X8}", ip4); Console.ReadLine(); } } Output: 0200A8C0 Note that the address is in proper network order (big endian).
2,851,100
2,851,191
Why do I get errors when using unsigned integers in an expression with C++?
Given the following piece of (pseudo-C++) code: float x=100, a=0.1; unsigned int height = 63, width = 63; unsigned int hw=31; for (int row=0; row < height; ++row) { for (int col=0; col < width; ++col) { float foo = x + col - hw + a * (col - hw); cout << foo << " "; } cout << endl; } The values of foo are screwed up for half of the array, in places where (col - hw) is negative. I figured because col is int and comes first, that this part of the expression is converted to int and becomes negative. Unfortunately, apparently it doesn't, I get an overflow of an unsigned value and I've no idea why. How should I resolve this problem? Use casts for the whole or part of the expression? What type of casts (C-style or static_cast<...>)? Is there any overhead to using casts (I need this to work fast!)? EDIT: I changed all my unsigned ints to regular ones, but I'm still wondering why I got that overflow in this situation.
Unsigned integers implement unsigned arithmetic. Unsigned arithmetic is modulo arithmetics. All values are adjusted modulo 2^N, where N is the number of bits in the value representation of unsigned type. In simple words, unsigned arithmetic always produces non-negative values. Every time the expression should result in negative value, the value actually "wraps around" 2^N and becomes positive. When you mix a signed and an unsigned integer in a [sub-]expression, the unsigned arithmetic "wins", i.e. the calculations are performed in unsigned domain. For example, when you do col - hw, it is interpreted as (unsigned) col - hw. This means that for col == 0 and hs == 31 you will not get -31 as the result. Instead you wil get UINT_MAX - 31 + 1, which is normally a huge positive value. Having said that, I have to note that in my opinion it is always a good idea to use unsigned types to represent inherently non-negative values. In fact, in practice most (or at least half) of integer variables in C/C++ the program should have unsigned types. Your attempt to use unsigned types in your example is well justified (if understand the intent correctly). Moreover, I'd use unsigned for col and row as well. However, you have to keep in mind the way unsigned arithmetic works (as described above) and write your expressions accordingly. Most of the time, an expression can be rewritten so that it doesn't cross the bounds of unsigned range, i.e. most of the time there's no need to explicitly cast anything to signed type. Otherwise, if you do need to work with negative values eventually, a well-placed cast to signed type should solve the problem.
2,851,202
2,851,312
callback for each for loop iteration
a bit of a naive question, but nonetheless. I am trying to break up a for loop in which a 2d Matrix is being read. I would like to write a callback function to consume row-wise/col-wise chunks per row/col iteration. Any hints on how to tie up the callback function with iteration? bool ReadMatrix(const int** array) { ..... int columns;// array col int rows; //array rows for(int col=0; col<columns; ++col) { for(int row=0; row<rows; ++row) { ReadValue(row, col); //arbitrary function... which i would like to tie up with iterations } } .... }
My first take would be for your callback to take the array, a row index, a row span, and column index and a column span. class functor { public: void operator()(int data[][], size_t row_idx, size_t row_span, size_t col_idx, size_t col_span); }; I'd write the iterator function as a template so it can easily take a functor, free function or class static function: template <class CB_T> void iterate(int data[][], size_t rows, size_t columns, CB_T cb);
2,851,217
2,851,489
Basic C++ class how to implement with Objective C
I have some problems with implementing class which written in C++, because I not familiar with c++ .. if someone could help with implementing it in Objective C #ifndef ENTITY_H #define ENTITY_H class BaseGameEntity { private: int m_ID; static int m_iNextValidID; void SetID(int val); public: BaseGameEntity(int id) { SetID(id); } virtual ~BaseGameEntity(){} virtual void Update()=0; int ID()const{return m_ID;} }; #endif #include "BaseGameEntity.h" #include <cassert> int BaseGameEntity::m_iNextValidID = 0; void BaseGameEntity::SetID(int val) { assert ( (val >= m_iNextValidID) && "<BaseGameEntity::SetID>: invalid ID"); m_ID = val; m_iNextValidID = m_ID + 1; }
This is rougly equivalent to that C++ class: // In BaseGameEntity.h #import <Cocoa/Cocoa.h> @interface BaseGameEntity : NSObject { NSInteger m_ID; } - (id)initWithID:(NSInteger)ID; - (void)update; // must be defined by subclasses - (NSInteger)ID; @end // In BaseGameEntity.m #import "BaseGameEntity.m" @implementation BaseGameEntity static NSInteger m_iNextValidID; - (id)initWithID:(NSInteger)ID { self = [super init]; if (!self) return nil; NSAssert2(ID >= m_iNextValidID, @"%s invalid id: %d", __PRETTY_FUNCTION__, ID); m_ID = ID; m_iNextValidID = m_ID + 1; return self; } - (NSInteger)ID { return m_ID; } - (void)setID:(NSInteger)newID { NSAssert2(newID >= m_iNextValidID, @"%s invalid id: %d", __PRETTY_FUNCTION__, newID); m_ID = newID; m_iNextValidID = m_ID + 1; } @end A few differences to note: All methods are virtual in Objective-C, so there's no need to declare them as such Objective-C doesn't have pure virtual functions Objective-C doesn't have class-static variables — it only has function-static and file-static variables like C does — so we declare the static int in the implementation file I included the setID: method for equivalence, but it's considered bad form to use setters in Objective-C initializers, so it's never actually called — I just copied the body of the method into the init method
2,851,326
2,891,403
Getting QT to respond to power-events (sleep/hibernate)
I'm trying to develop software that is intelligent wrt sleep events (cleanly closing network connections, making sure data restart locations are set properly, etc). Are there mechanisms in QT (4.6) currently that facilitate me responding to system power events?
I dont think there's a native to qt and multi platform way for these but there are propably some ways and api's to do things you are looking for. Posix signals might provide something to notify your app about ongoing system events. Also you might want to look QDbus stuff, some cases dbus will broadcast system events.. But how to do the stuff you are really looking for is very os dependant and without knowning your target os, its rather hard to point out a optimal solution.
2,851,384
2,851,407
stl priority queue based on lower value first
I have a problem with stl priority queue.I want to have the priority queue in the increasing order,which is decreasing by default.Is there any way to do this in priority queue. And what is the complexity of building stl priority queue.If i use quick sort in an array which takes O(nlgn) is its complexity is similar to using priority queue??? Plz someone ans.Advanced thanx.
Use a different comparator as the 3rd template argument of std::priority_queue. priority_queue is a container adaptor that works on any sequence you define. The performance of insertion is equal to the std::push_heap operation and takes logarithmic time. So the complexity to sorting after all insertions are done isn't equal. If you insert a fixed amount and work the queue afterwards a vector and a single sort could be more efficient.
2,851,517
2,851,552
Naming a typedef for a boost::shared_ptr<const Foo>
Silly question, but say you have class Foo: class Foo { public: typedef boost::shared_ptr<Foo> RcPtr; void non_const_method() {} void const_method() const {} }; Having a const Foo::RcPtr doesn't prevent non-const methods from being invoked on the class, the following will compile: #include <boost/shared_ptr.hpp> int main() { const Foo::RcPtr const_foo_ptr(new Foo); const_foo_ptr->non_const_method(); const_foo_ptr->const_method(); return 0; } But naming a typedef ConstRcPtr implies, to me, that the typedef would be typedef const boost::shared_ptr<Foo> ConstRcPtr; which is not what I'm interested in. An odder name, but maybe more accurate, is RcPtrConst: typedef boost::shared_ptr<const Foo> RcPtrConst; However, Googling for RcPtrConst gets zero hits, so people don't use this as a typedef name :) Does anyone have any other suggestions?
The name of a typedef does not represent the syntactical construct used to define its type. The typedef name should convey some of its desired meaning. For example, the Standard defines the names of iterators over const T as const_iterator, even though the iterator itself is not const (you can still increment it). In fact, the whole purpose of an iterator is to change it, in order to iterate over a sequence :) typedef T const* const_iterator; For pointers, i personally see little reason to generally typedef them as constant. So the Const in front of the trailing parts could convey the same meaning as the iterators do, and will go with existing practice. So i think it is perfectly fine for you to go and say typedef boost::shared_ptr<Foo const> ConstRcPtr; In fact, this is how std::allocator<>::const_pointer is worded too.
2,851,616
2,851,688
Template meta-programming with member function pointers?
Is it possible to use member function pointers with template meta-programming? Such as: class Connection{ public: string getName() const; string getAlias() const; //more stuff }; typedef string (Connection::*Con_Func)() const; template<Con_Func _Name> class Foo{ Connection m_Connect; public: Foo(){ cout << (m_Connect.*_Name)(); } }; typedef Foo<&Connection::getName> NamedFoo; typedef Foo<&Connection::getAlias> AliasFoo; Granted, this is rather contrived but is it possible? (yes, there are probably much better ways but humor me.)
Check out this discussion on the subject of pointers-to-nonstatic-members as template parameters. It looks like there are issues with the VC++ implementation.
2,851,868
2,852,641
Multiset container appears to stop sorting
I would appreciate help debugging some strange behavior by a multiset container. Occasionally, the container appears to stop sorting. This is an infrequent error, apparent in only some simulations after a long time, and I'm short on ideas. (I'm an amateur programmer--suggestions of all kinds are welcome.) My container is a std::multiset that holds Event structs: typedef std::multiset< Event, std::less< Event > > EventPQ; with the Event structs sorted by their double time members: struct Event { public: explicit Event(double t) : time(t), eventID(), hostID(), s() {} Event(double t, int eid, int hid, int stype) : time(t), eventID( eid ), hostID( hid ), s(stype) {} bool operator < ( const Event & rhs ) const { return ( time < rhs.time ); } double time; ... }; The program iterates through periods of adding events with unordered times to EventPQ currentEvents and then pulling off events in order. Rarely, after some events have been added (with perfectly 'legal' times), events start getting executed out of order. What could make the events ever not get ordered properly? (Or what could mess up the iterator?) I have checked that all the added event times are legitimate (i.e., all exceed the current simulation time), and I have also confirmed that the error does not occur because two events happen to get scheduled for the same time. I'd love suggestions on how to work through this. The code for executing and adding events is below for the curious: double t = 0.0; double nextTimeStep = t + EPID_DELTA_T; EventPQ::iterator eventIter = currentEvents.begin(); while ( t < EPID_SIM_LENGTH ) { // Add some events to currentEvents while ( ( *eventIter ).time < nextTimeStep ) { Event thisEvent = *eventIter; t = thisEvent.time; executeEvent( thisEvent ); eventCtr++; currentEvents.erase( eventIter ); eventIter = currentEvents.begin(); } t = nextTimeStep; nextTimeStep += EPID_DELTA_T; } void Simulation::addEvent( double et, int eid, int hid, int s ) { assert( currentEvents.find( Event(et) ) == currentEvents.end() ); Event thisEvent( et, eid, hid, s ); currentEvents.insert( thisEvent ); } I should add that occasionally an event, when executed, will delete other events from currentEvents. This is done with double oldRecTime = 10.0; // gets defined legitimately in simulation EventPQ::iterator epqItr = currentEvents.find( Event(oldRecTime) ); assert( currentEvents.count( Event(oldRecTime) ) == 1 ); currentEvents.erase( epqItr ); Even if this code looks okay, I'd like to know other ways I can examine what's going on--I'm currently using a lot of asserts() and cout << checks.
In the simulation, where I have commented // Add some events to currentEvents events were being added to currentEvents. (Hope that was clear.) If an event was added that happened to belong at the top of the queue, I believe it messed up the iterator pointing to currentEvents.begin(). I reset the iterator immediately before the inner while loop, and things appear to work. I will update this question if this turns out not to be the solution, or if there are other problems in what I have here. Thanks to all those who commented; it helps me learn how I should be approaching these problems.
2,851,991
2,852,234
(static initialization/template instantiation) problems with factory pattern
Why does following code raise an exception (in createObjects call to map::at) alternativly the code (and its output) can be viewed here intererestingly the code works as expected if the commented lines are uncommented with both microsoft and gcc compiler (see here), this even works with initMap as ordinary static variable instead of static getter. The only reason for this i can think of is that the order of initialization of the static registerHelper_ object (factory_helper_)and the std::map object (initMap) are wrong, however i cant see how that could happen, because the map object is constructed on first usage and thats in factory_helper_ constructor, so everything should be alright shouldnt it ? I am even more suprised that those doNothing() lines fix the issue, because that call to doNothing() would happen after the critical section (which currently fails) is passed anyway. EDIT: debugging showed, that without the call to factory_helper_.doNothing(), the constructor of factory_helper_ is never called. #include <iostream> #include <string> #include <map> #define FACTORY_CLASS(classtype) \ extern const char classtype##_name_[] = #classtype; \ class classtype : FactoryBase<classtype,classtype##_name_> namespace detail_ { class registerHelperBase { public: registerHelperBase(){} protected: static std::map<std::string, void * (*)(void)>& getInitMap() { static std::map<std::string, void * (*)(void)>* initMap = 0; if(!initMap) initMap= new std::map<std::string, void * (*)(void)>(); return *initMap; } }; template<class TParent, const char* ClassName> class registerHelper_ : registerHelperBase { static registerHelper_ help_; public: //void doNothing(){} registerHelper_(){ getInitMap()[std::string(ClassName)]=&TParent::factory_init_; } }; template<class TParent, const char* ClassName> registerHelper_<TParent,ClassName> registerHelper_<TParent,ClassName>::help_; } class Factory : detail_::registerHelperBase { private: Factory(); public: static void* createObject(const std::string& objclassname) { return getInitMap().at(objclassname)(); } }; template <class TClass, const char* ClassName> class FactoryBase { private: static detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName> factory_helper_; static void* factory_init_(){ return new TClass();} public: friend class detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName>; FactoryBase(){ //factory_helper_.doNothing(); } virtual ~FactoryBase(){}; }; template <class TClass, const char* ClassName> detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName> FactoryBase<TClass,ClassName>::factory_helper_; FACTORY_CLASS(Test) { public: Test(){} }; int main(int argc, char** argv) { try { Test* test = (Test*) Factory::createObject("Test"); } catch(const std::exception& ex) { std::cerr << "caught std::exception: "<< ex.what() << std::endl; } #ifdef _MSC_VER system("pause"); #endif return 0; }
The problem is not related to initialization order, but rather to template instantiation. Templated code is instantiated on demand, that is, the compiler will not instantiate any templated code that is not used in your program. In particular, in your case the static class member FactoryBase<>::factory_helper_ is not being instantiated and thus it does not exist in the final binary, it does not register itself... (you can check this with 'nm' from the gnu toolchain, that will show the list of symbols present in your executable) Try changing the FactoryBase constructor to this: template <class TClass, const char* ClassName> class FactoryBase { //... FactoryBase(){ factory_helper_; } //... }; This will force the compiler into actually instantiating the static member in the binary and you should be set. There is no need to create an empty method and calling it. EDIT: As an answer to the comment, towards the end of paragraph §14.7.1[temp.inst]/1 in the current standard: Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.
2,852,140
2,852,183
priority queue clear method
How do I delete all elements from a priority queue? That means how do I destroy a priority queue? advanced thanks for your answer. Is there any clear- or erase-like method?
The priority_queue interface doesn't have a clear() method (for no good reason I've ever been able to discern). A simple way to clear it is just to assign a new, empty queue: priority_queue <int> q; // use it q = priority_queue <int>(); // reset it
2,852,348
2,852,368
Loop through hex variable in C
I have the following code in a project that write's the ascii representation of packet to a unix tty: int written = 0; int start_of_data = 3; //write data to fifo while (length) { if ((written = write(fifo_fd, &packet[start_of_data], length)) == -1) { printf("Error writing to FIFO\n"); } else { length -= written; } } I just want to take the data that would have been written to the socket and put it in a variable. to debug, I have just been trying to printf the first letter/digit. I have tried numerous ways to get it to print out, but I keep getting hex forms (I think). The expected output is: 13176 and the hex value is: 31 33 31 37 36 0D 0A (if that is even hex) Obviously my C skills are not the sharpest tools in the shed. Any help would be appreciated. update: I am using hexdump() to get the output
These are the ASCII codes of characters: 31 is '1', 33 is '3' etc. 0D and 0A are the terminating new line characters, also known as '\r' and '\n', respectively. So if you convert the values to characters, you can print them out directly, e.g. with printf using the %c or %s format codes. As you can check from the table linked, the values you posted do represent "13176" :-)
2,852,390
2,852,419
Reading long int using scanf
To read an int using scanf we use: scanf("%d", &i); What if i is a long not int?? Note: when using %d with long it gives me an irritating warning..
Just use long l; scanf("%ld", &l); it gives me an irritating warning.. That warning is quite right. This is begging for stack corruption.
2,852,400
3,737,644
Using an initializer_list on a map of vectors
I've been trying to initialize a map of <ints, vector<ints> > using the new 0X standard, but I cannot seem to get the syntax correct. I'd like to make a map with a single entry with key:value = 1:<3,4> #include <initializer_list> #include <map> #include <vector> using namespace std; map<int, vector<int> > A = {1,{3,4}}; .... It dies with the following error using gcc 4.4.3: error: no matching function for call to std::map<int,std::vector<int,std::allocator<int> >,std::less<int>,std::allocator<std::pair<const int,std::vector<int,std::allocator<int> > > > >::map(<brace-enclosed initializer list>) Edit Following the suggestion by Cogwheel and adding the extra brace it now compiles with a warning that can be gotten rid of using the -fno-deduce-init-list flag. Is there any danger in doing so?
As the comment above has mentioned, {1,{3,4}} is a single element in the map, where the key is 1 and the value is {3,4}. So, what you would need is { {1,{3,4}} }. Simplifying the error: error: no matching function for call to map<int,vector<int>>::map(<brace-enclosed initializer list>) Not a precise error, but somewhat helpful nonetheless.
2,852,557
2,855,188
Protecting Content Files
I want a simple layer of protection for my content (resource) files in my application. For example, I have various sound and image files used in my application. I think, I can wrap them in a SFX archive (Probably packed with WinRAR), then in my application, start the SFX exe with some parameters, like, -silent. But this may not be the best way to do this, so if you can give me some suggestions, that would be great. P.S. I know it does not sound unbreachable (like there is one, anyways), but this is needed for some reasons. P.S. I could use some help for a method to hide the files after the SFX (or some other package) complete extraction. Thank you.
Don't use a SFX archive. Well a lot depends on how you use your resources. If you have a lot of library code that requires file names then the files have to be persisted on hard drive for a while. If you can, you want to find out if your sound and media libraries can be passed pointer - then you load the files up yourself, decrypt them, and pass the pointers to the decrypted buffers to the media api's. As to the actual encryption. Either use an archive file format, something like zlib. This gives you the ability to store all your data files in a single encrypted archive and expand them into memory. Or roll your own per-file encryption. A rolled at home XOR encryption has the advantage of being very fast. Almost all file encryption comes down to: Start with a "key". A short string. Use the key to initialize a random number generator. XOR the bytes from the rng with the data to be encrypted to encrypt it. Later, to decrypt the data: start with the same key, initialize the rng Which will generate the same stream of bytes, XOR them with the encrypted data to decrypt it. The problem is (obviously) that the key needs to exist in the client so any determined hacker can get it. So theres no real point in being too fancy here. Just generate 256 bytes of "random" data and use it to encrypt and decrypt your files as you load them into memory - or write them to a temporary folder. If you need to write out ttemp files, you might be able to use FILE_FLAG_DELETE_ON_CLOSE to get the temp folder to clean itself up safely without leaving unencrypted resources persisted on disk.
2,852,637
2,853,402
C++ program runs slow in VS2008
I have a program written in C++, that opens a binary file(test.bin), reads it object by object, and puts each object into a new file (it opens the new file, writes into it(append), and closes it). I use fopen/fclose, fread and fwrite. test.bin contains 20,000 objects. This program runs under linux with g++ in 1 sec but in VS2008 in debug/release mode in 1min! There are reasons why I don't do them in batches or don't keep them in memory or any other kind of optimizations. I just wonder why it is that much slow under windows. Thanks,
Unfortunately file access on Windows isn't renowned for its brilliant speed, particularly if you're opening lots of files and only reading and writing small amounts of data. For better results, the (not particularly helpful) solution would be to read large amounts of data from a small number of files. (Or switch to Linux entirely for this program?!) Other random suggestions to try: turn off the virus checker if you have one (I've got Kaspersky on my PC, and writing 20,000 files quickly drove it bananas) use an NTFS disk if you have one (FAT32 will be even worse) make sure you're not accidentally using text mode with fopen (easily done) use setvbuf to increase the buffer size for each FILE try CreateFile/ReadFile/etc. instead of fopen and friends, which won't solve your problem but may shave a few seconds off the running time (since the stdio functions do a bit of extra work that you probably don't need)
2,852,772
2,852,840
Wrong reading file in UNICODE (fread) on C++
I'm trying to load into string the content of file saved on the dics. The file is .CS code, created in VisualStudio so I suppose it's saved in UTF-8 coding. I'm doing this: FILE *fConnect = _wfopen(connectFilePath, _T("r,ccs=UTF-8")); if (!fConnect) return; fseek(fConnect, 0, SEEK_END); lSize = ftell(fConnect); rewind(fConnect); LPTSTR lpContent = (LPTSTR)malloc(sizeof(TCHAR) * lSize + 1); fread(lpContent, sizeof(TCHAR), lSize, fConnect); But result is so strange - the first part (half of the string is content of .CS file), then strange symbols like 췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍 appear. So I think I read the content in a wrong way. But how to do that properly? Thank you so much and I'm looking to hear!
ftell(), fseek(), and fread() all operate on bytes, not on characters. In a Unicode environment, TCHAR is at least 2 bytes, so you are allocating and reading twice as much memory as you should be. I have never seen fopen() or _wfopen() support a "ccs" attribute. You should use "rb" as the reading mode, read the raw bytes into memory, and then decode them once you have them all available, ie: FILE *fConnect = _wfopen(connectFilePath, _T("rb")); if (!fConnect) return; fseek(fConnect, 0, SEEK_END); lSize = ftell(fConnect); rewind(fConnect); LPBYTE lpContent = (LPBYTE) malloc(lSize); fread(lpContent, 1, lSize, fConnect); fclose(lpContent); .. decode lpContent as needed ... free(lpContent);
2,852,775
2,888,489
boost lambda versus phoenix
I recently started looking at boost phoenix, as replacement for lambda. Is phoenix a full replacement for lambda, or is there some lambda functionality which is not provided by phoenix? is phoenix mature? Are there any gotcha I should know about? my primary interest are operator composition, control statements and casts are less so Thanks
This post answers all your questions. Phoenix is very mature. Phoenix and lambda will be merged. It will be the base for future lambda implementations.
2,852,878
2,852,881
Is this a memory leak?
char *pointer1; char *pointer2; pointer1 = new char[256]; pointer2 = pointer1; delete [] pointer1; In other words, do I have to do delete [] pointer2 as well? Thanks!
Nope, that code is fine and won't leak memory. You only have to use delete[] once because you've only used one new to allocate an area for memory, even though there are two pointers to that same memory.
2,852,895
2,856,241
C++ iterate or split UTF-8 string into array of symbols?
Searching for a platform- and 3rd-party-library- independent way of iterating UTF-8 string or splitting it into array of UTF-8 symbols. Please post a code snippet. Solved: C++ iterate or split UTF-8 string into array of symbols?
Solved using tiny platform-independent UTF8 CPP library: char* str = (char*)text.c_str(); // utf-8 string char* str_i = str; // string iterator char* end = str+strlen(str)+1; // end iterator do { uint32_t code = utf8::next(str_i, end); // get 32 bit code of a utf-8 symbol if (code == 0) continue; unsigned char[5] symbol = {0}; utf8::append(code, symbol); // copy code to symbol // ... do something with symbol } while ( str_i < end );
2,852,907
2,853,127
problem finding a header with a c++ makefile
I've started working with my first makefile. I'm writing a roguelike in C++ using the libtcod library, and have the following hello world program to test if my environment's up and running: #include "libtcod.hpp" int main() { TCODConsole::initRoot(80, 50, "PartyHack"); TCODConsole::root->printCenter(40, 25, TCOD_BKGND_NONE, "Hello World"); TCODConsole::flush(); TCODConsole::waitForKeypress(true); } My project directory structure looks like this: /CppPartyHack ----/libtcod-1.5.1 # this is the libtcod root folder --------/include ------------libtcod.hpp ----/PartyHack --------makefile --------partyhack.cpp # the above code (while we're here, how do I do proper indentation? Using those dashes is silly.) and here's my makefile: SRCDIR = . INCDIR = ../libtcod-1.5.1/include CFLAGS = $(FLAGS) -I$(INCDIR) -I$(SRCDIR) -Wall CC = gcc CPP = g++ .SUFFIXES: .o .h .c .hpp .cpp $(TEMP)/%.o : $(SRCDIR)/%.cpp $(CPP) $(CFLAGS) -o $@ -c $< $(TEMP)/%.o : $(SRCDIR)/%.c $(CC) $(CFLAGS) -o $@ -c $< CPP_OBJS = $(TEMP)partyhack.o all : partyhack partyhack : $(CPP_OBJS) $(CPP) $(CPP_OBJS) -o $@ -L../libtcod-1.5.1 -ltcod -ltcod++ -Wl,-rpath,. clean : \rm -f $(CPP_OBJS) partyhack I'm using Ubuntu, and my terminal gives me the following errors: max@max-desktop:~/Desktop/Development/CppPartyhack/PartyHack$ make g++ -c -o partyhack.o partyhack.cpp partyhack.cpp:1:23: error: libtcod.hpp: No such file or directory partyhack.cpp: In function ‘int main()’: partyhack.cpp:5: error: ‘TCODConsole’ has not been declared partyhack.cpp:6: error: ‘TCODConsole’ has not been declared partyhack.cpp:6: error: ‘TCOD_BKGND_NONE’ was not declared in this scope partyhack.cpp:7: error: ‘TCODConsole’ has not been declared partyhack.cpp:8: error: ‘TCODConsole’ has not been declared make: *** [partyhack.o] Error 1 So obviously, the makefile can't find libtcod.hpp. I've double checked and I'm sure the relative path to libtcod.hpp in INCDIR is correct, but as I'm just starting out with makefiles, I'm uncertain what else could be wrong. My makefile is based off a template that the libtcod designers provided along with the library itself, and while I've looked at a few online makefile tutorials, the code in this makefile is a good bit more complicated than any of the examples the tutorials showed, so I'm assuming I screwed up something basic in the conversion. Thanks for any help.
What happens here, is that 1) make evaluates the target all, which resolves to partyhack. 2) make evaluates the target partyhack, which resolves to $(CPP_OBJS) 3) make evaluates the target $(CPP_OBJS), which resolves to $(TMP)partyhack.o 4) make evaluates the target $(TMP)partyhack.o which resolves to partyhack.o This is because TMP is not defined. Also note that the slash is missing after $(TMP). 5) make evaluates the target partyhack.o, and applies the implicit rule g++ -c -o partyhack.o partyhack.cpp It does not apply the rule you specified, namely $(TEMP)/%.o : $(SRCDIR)/%.cpp because TEMP is not defined, so this evaluates to /partyhack.o : ./partyhack.cpp, and we are not building /partyhack.o because we are not in the root directory. 6) g++ does not find the include file, because the include directories were not passed to it, because your rule was not applied. To fix this: First, you need to define TEMP (see Nick Meyers answer). TEMP = . Second, you need to change the definition of CPP_OBJS (as Paul R suggested). CPP_OBJS = %(TEMP)/partyhack.o This will work if you invoke make inside the directory CppPartyHack/PartyHack.
2,852,952
2,853,010
Purpose of boost::checked_delete
I don't understand the purpose of boost::checked_delete. The documentation says: The C++ Standard allows, in 5.3.5/5, pointers to incomplete class types to be deleted with a delete-expression. When the class has a non-trivial destructor, or a class-specific operator delete, the behavior is undefined. Some compilers issue a warning when an incomplete type is deleted, but unfortunately, not all do, and programmers sometimes ignore or disable warnings. The supplied function and class templates can be used to prevent these problems, as they require a complete type, and cause a compilation error otherwise. So the C++ standard allows you to delete incomplete types, which causes undefined behavior if the type has a non-trivial destructor. What? How can an incomplete type have any destructor at all? Isn't an incomplete type just a prototype?
The most common example of an incomplete type is one that has only been declared: // this file does not include the definition of foo class foo; void bad(foo *f) { delete f; // undefined behavior if there exists foo::~foo } In reality, the definition of foo may look like this: class foo { public: ~foo() { ... }; }; But if the top code has not 'seen' the class definition and just sees the class declaration, the code will compile.
2,852,984
2,853,067
C++ Set Erase Entry Question
I encountered a problem here. I'm using C++ multiset. This is the test file. Score: 3-1 Ben Steven Score: 1-0 Ben Score: 0-0 Score: 1-1 Cole Score: 1-2 Ben I'm using while loop and ifstream (fin1) to read in from the test file above. multiset<string, less<string> > myset; while(!fin1.eof()) { fin1 >> scoreName; if(scoreName == "Score:") { //calculates number of matches played } else { goalCheck = scoreName.substr(1,1); if(goalCheck == "-") { string lGoal, rGoal; lGoal = scoreName.substr(0,1); rGoal = scoreName.substr(2,1); int leftGoal, rightGoal; leftGoal = atoi(lGoal.c_str()); rightGoal = atoi(rGoal.c_str()); if(leftGoal > rightGoal) //if team wins { //some computations } else if(leftGoal < rightGoal) //if team loses { //computations } else if(leftGoal == rightGoal) //if team draws { //computations } else { myset.insert(myset.begin(), scoreName); } } } I'm inserting all names into myset (regardless of wins/loses/draws) in my last else statement. But I only require the names of those matches who won/draw. Those names whose matches lost will not be included in myset. In the test file above, there's only one match that lost (1-2) and I wanted to remove "Ben". How can I do that? I tried to use myset.erase(), but I'm not sure how to get it point to Ben and remove it from myset. Any help is much appreciated. Thanks.
If I understand what you're trying to do, I think it would be easier to remember whether the team had won, drawn or lost when you read the "Score" line and only insert the following lines (ie. "Ben") if the team hasn't lost. Inserting everyone and then erasing ones you didn't want seems overcomplicated to me :) For reference: If you do need to erase, you would use the find() member to locate an entry matching a given key, and then erase() on the returned iterator to delete it (after checking that find() didn't return an iterator equal to end(), which means the item wasn't found). Also, you shouldn't pass begin() to insert(). The iterator is a hint as to where the map might insert the item; in practice that's rarely useful. There is an overload of that function which takes only one argument, the item to insert.
2,853,029
2,853,053
C/C++ usage of special CPU features
I am curious, do new compilers use some extra features built into new CPUs such as MMX SSE,3DNow! and so? I mean, in original 8086 there was even no FPU, so compiler that old cannot even use it, but new compilers can, since FPU is part of every new CPU. So, does new compilers use new features of CPU? Or, it should be more right to ask, does new C/C++ standart library functions use new features? Thanks for answer. EDIT: OK, so, if I get all of you right,even some standart operations, especially with float numbers can be done using SSE faster. In order to use it, I must enable this feature in my compiler, if it supports it. If it does, I must be sure that targeted platform supports that features. In case of some system libraries that require top performance, such as OpenGL, DirectX and so, this support may be supported in system. By default, for compatibility reasons, compiler doesen´t support it, but you can add this support using special C functions delivered by, for example Intel. This should be the best way, since you can directly control wheather and when you use special features of desired platform, to write multi-CPU-support applications.
gcc will support newer instructions via command line arguments. See here for more info. To quote: GCC can take advantage of the additional instructions in the MMX, SSE, SSE2, SSE3 and 3dnow extensions of recent Intel and AMD processors. The options -mmmx, -msse, -msse2, -msse3 and -m3dnow enable the use of these extra instructions, allowing multiple words of data to be processed in parallel. The resulting executables will only run on processors supporting the appropriate extensions--on other systems they will crash with an Illegal instruction error (or similar)
2,853,100
2,855,633
Problem passing a reference as a named parameter to a variadic function
I'm having problems in Visual Studio 2003 with the following: void foo(const char*& str, ...) { va_list args; va_start(args, str); const char* foo; while((foo = va_arg(args, const char*)) != NULL) { printf("%s\n", foo); } } When I call it: const char* one = "one"; foo(one, "two", "three", NULL); I get: Access violation reading location 0xcccccccc on the printf() line -- va_arg() returned 0xcccccccc. I finally discovered it's the first parameter being a reference that breaks it -- if I make it a normal char* everything is fine. It doesn't seem to matter what the type is; being a reference causes it to fail at runtime. Is this a known problem with VS2003, or is there some way in which that's legal behavior? It doesn't happen in GCC; I haven't tested with newer Visual Studios to see if the behavior goes away
VS2005 also crashes on it. The problem is that va_start uses the address of the argument given to it, and since str is a reference, its address is the address of the "one" variable defined int the caller, not the address on the stack. I see no way of getting the address of the stack-variable (the argument that actually contains the address of "one" that is being passed), but there are some work arounds: Instead of "const char * &str", use "const char *str" or "const char **str" Add the next argument also to the "fixed" argument list This code illustrates the second alternative: void foo(const char* &str, const char *arg1, ...) { if (arg1) { va_list args; va_start(args, arg1); printf ("%s\n", arg1); const char* foo; while((foo = va_arg(args, const char*)) != NULL) { printf("%s\n", foo); } } }
2,853,133
2,853,168
What am I not getting about this abstract class implementation?
PREFACE: I'm relatively inexperienced in C++ so this very well could be a Day 1 n00b question. I'm working on something whose long term goal is to be portable across multiple operating systems. I have the following files: Utilities.h #include <string> class Utilities { public: Utilities() { }; virtual ~Utilities() { }; virtual std::string ParseString(std::string const& RawString) = 0; }; UtilitiesWin.h (for the Windows class/implementation) #include <string> #include "Utilities.h" class UtilitiesWin : public Utilities { public: UtilitiesWin() { }; virtual ~UtilitiesWin() { }; virtual std::string ParseString(std::string const& RawString); }; UtilitiesWin.cpp #include <string> #include "UtilitiesWin.h" std::string UtilitiesWin::ParseString(std::string const& RawString) { // Magic happens here! // I'll put in a line of code to make it seem valid return ""; } So then elsewhere in my code I have this #include <string> #include "Utilities.h" void SomeProgram::SomeMethod() { Utilities *u = new Utilities(); StringData = u->ParseString(StringData); // StringData defined elsewhere } The compiler (Visual Studio 2008) is dying on the instance declaration c:\somepath\somecode.cpp(3) : error C2259: 'Utilities' : cannot instantiate abstract class due to following members: 'std::string Utilities::ParseString(const std::string &)' : is abstract c:\somepath\utilities.h(9) : see declaration of 'Utilities::ParseString' So in this case what I'm wanting to do is use the abstract class (Utilities) like an interface and have it know to go to the implemented version (UtilitiesWin). Obviously I'm doing something wrong but I'm not sure what. It occurs to me as I'm writing this that there's probably a crucial connection between the UtilitiesWin implementation of the Utilities abstract class that I've missed, but I'm not sure where. I mean, the following works #include <string> #include "UtilitiesWin.h" void SomeProgram::SomeMethod() { Utilities *u = new UtilitiesWin(); StringData = u->ParseString(StringData); // StringData defined elsewhere } but it means I'd have to conditionally go through the different versions later (i.e., UtilitiesMac(), UtilitiesLinux(), etc.) What have I missed here?
Utilities *u = new Utilities(); tells the compiler to make a new instance of the Utilities class; the fact that UtilitiesWin extends it isn't necessarily known and doesn't affect it. There could be lots of classes extending Utilities, but you told the compiler to make a new instance of Utilities, not those subclasses. It sounds like you want to use the factory pattern, which is to make a static method in Utilities that returns a Utilities* that points to a particular instance: static Utilities* Utilities::make(void) {return new UtilitiesWin();} At some point you're going to have to instantiate a non-abstract subclass; there's no way around specifying UtilitiesWin at that point
2,853,275
2,853,561
What new Unicode functions are there in C++0x?
It has been mentioned in several sources that C++0x will include better language-level support for Unicode(including types and literals). If the language is going to add these new features, it's only natural to assume that the standard library will as well. However, I am currently unable to find any references to the new standard library. I expected to find out the answer for these answers: Does the new library provide standard methods to convert UTF-8 to UTF-16, etc.? Does the new library allowing writing UTF-8 to files, to the console (or from files, from the console). If so, can we use cout or will we need something else? Does the new library include "basic" functionality such as: discovering the byte count and length of a UTF-8 string, converting to upper-case/lower-case(does this consider the influence of locales?) Finally, are any of these functions are available in any popular compilers such as GCC or Visual Studio? I have tried to look for information, but I can't seem to find anything. I am actually starting to think that maybe these things aren't even decided yet(I am aware that C++0x is a work in progress).
Does the new library provide standard methods to convert UTF-8 to UTF-16, etc.? No. The new library does provide std::codecvt facets which do the conversion for you when dealing with iostream, however. ISO/IEC TR 19769:2004, the C Unicode Technical Report, is included almost verbatim in the new standard. Does the new library allowing writing UTF-8 to files, to the console (or from files, from the console). If so, can we use cout or will we need something else? Yes, you'd just imbue cout with the correct codecvt facet. Note however that the console is not required to display those characters correctly Does the new library include "basic" functionality such as: discovering the byte count and length of a UTF-8 string, converting to upper-case/lower-case(does this consider the influence of locales?) AFAIK that functionality exists with the existing C++03 standard. std::toupper and std::towupper of course function just as in previous versions of the standard. There aren't any new functions which specifically operate on unicode for this. If you need these kinds of things, you're still going to have to rely on an external library -- the <iostream> is the primary piece that was retrofitted. What, specifically, is added for unicode in the new standard? Unicode literals, via u8"", u"", and U"" std::char_traits classes for UTF-8, UTF-16, and UTF-32 mbrtoc16, c16rtomb, mbrtoc32, and c32rtomb from ISO/IEC TR 19769:2004 std::codecvt facets for the locale library The std::wstring_convert class template (which uses the codecvt mechanism for code set conversions) The std::wbuffer_convert, which does the same as wstring_convert except for raw arrays, not strings.
2,853,431
2,853,450
C++ - Need to learn some basics in a short while
For reasons I will spare you, I have two weeks to learn some C++. I can learn alone just fine, but I need a good source. I don't think I have time to go through an entire book, and so I need some cliff notes, or possibly specific chapters/specialized resources I need to look up. I know my Asm/C/C# well, and so anything inherited from C, or any OOP is not needed. What I do need is some sources on the following subjects(I have a page that specifies what is needed, this is basically it, but I trimmed what I know): new/delete in C++ (as opposed to C#). Overloading cin/cout. Constructor, Destructor and MIL. Embedded Objects. References. Templates. If you feel some basic C++ concept that is not shared with C/C# is not included on this list, feel free to enter those as well. But the above subjects are the ones I'm supposed to roughly know in two week's time. Any help would be appreciated, thanks. Edit: I want to clarify - I don't expect to study for two weeks and then go and write Quake. I need to get to a level where given some code and a while to think about it, I can understand it. nuances like ++X vs X++ don't matter as much as knowing what the main keywords are, etc.
I know you said you didn't want to read a book but "Accelerated C++" is probably what you want. It was actually was used in like a 2 week crash course at Stanford from what I remember to get people up to speed on C++.
2,853,438
2,853,451
C++ Vector of pointers
For my latest CS homework, I am required to create a class called Movie which holds title, director, year, rating, actors etc. Then, I am required to read a file which contains a list of this info and store it in a vector of pointers to Movies. I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects? Do I just make two vectors - one of pointers and one of Movies and make a one-to-one mapping of the two vectors?
It means something like this: std::vector<Movie *> movies; Then you add to the vector as you read lines: movies.push_back(new Movie(...)); Remember to delete all of the Movie* objects once you are done with the vector.
2,853,615
2,853,622
get length of `wchar_t*` in c++
Please, how can I find out the length of a variable of type wchar_t* in c++? code example below: wchar_t* dimObjPrefix = L"retro_"; I would like to find out how many characters dimObjPrefix contains
If you want to know the size of a wchar_t string (wchar_t *), you want to use wcslen(3): size_t wcslen (const wchar_t *ws);
2,853,703
2,853,854
Modify an object without using it as parameter
I have a global object "X" and a class "A". I need a function F in A which have the ability to modify the content of X. For some reason, X cannot be a data member of A (but A can contain some member Y as reference of X), and also, F cannot have any parameter, so I cannot pass X as an parameter into F. (Here A is an dialog and F is a slot without any parameter, such as accept() ) How can I modify X within F if I cannot pass X into it? Is there any way to let A know that "X" is the object it need to modify?? I try to add something such as SetItem to specify X in A, but failed.
If you don't want F to reference X globally, then you could 'set' it on the object before calling the "worker" method. E.g. class A { public: A() : member_x(NULL) { } void SetX(X* an_x) { member_x = an_x; } void F(); { member_x->Manipulate(); } private: X* member_x; }; X global_x; A global_a; void DoStuff() { global_a.SetX(&global_x); global_a.F(); }
2,853,901
19,693,285
boost::serialization with mutable members
Using boost::serialization, what's the "best" way to serialize an object that contains cached, derived values in mutable members? class Example { public: Example(float n) : num(n), sqrt_num(-1.0) {} // compute and cache sqrt on first read float get_sqrt() const { if(sqrt_num < 0) sqrt_num = sqrt(num); return sqrt_num; } template <class Archive> void serialize(Archive& ar, unsigned int version) { ... } private: float num; mutable float sqrt_num; }; I'd like to avoid splitting serialize() into separate save() and load() methods, for maintenance reasons. One suboptimal implementation of serialize: template <class Archive> void serialize(Archive& ar, unsigned int version) { ar & num; sqrt_num = -1.0; } This handles the deserialization case, but in the serialization case, the cached value is killed and must be recomputed. What is the best practice in this case?
You can check the Archive::is_loading field, and load cached values if it's true. template <class Archive> void serialize(Archive& ar, unsigned int version) { ar & num; if(Archive::is_loading::value == true) sqrt_num = -1.0; }
2,854,156
2,860,124
Partial specialization with reference template parameter fails to compile in VS2005
I have code that boils down to the following: template <typename T> struct Foo {}; template <typename T, const Foo<T>& I> struct FooBar {}; //////// template <typename T> struct Baz {}; template <typename T, const Foo<T>& I> struct Baz< FooBar<T,I> > { static void func(FooBar<T,I>& value); }; //////// struct MyStruct { static const Foo<float> s_floatFoo; }; // Elsewhere: const Foo<float> MyStruct::s_floatFoo; void callBaz() { typedef FooBar<float, MyStruct::s_floatFoo> FloatFooBar; FloatFooBar myFloatFooBar; Baz<FloatFooBar>::func(myFloatFooBar); } This compiles successfully under GCC, however, under VS2005, I get: error C2039: 'func' : is not a member of 'Baz<T>' with [ T=FloatFooBar ] error C3861: 'func': identifier not found However, if I change const Foo<T>& I to const Foo<T>* I (passing I by pointer rather than by reference), and defining FloatFooBar as: typedef FooBar<float, &MyStruct::s_floatFoo> FloatFooBar; Both GCC and VS2005 are happy. What's going on? Is this some kind of subtle template substitution failure that VS2005 is handling differently to GCC, or a compiler bug? (The strangest thing: I thought I had the above code working in VS2005 earlier this morning. But that was before my morning coffee. I'm now not entirely certain I wasn't under some sort of caffeine-craving-induced delirium...)
For me it looks like VS2005 uses the first template specification of Baz template <typename T> struct Baz {}; This struct does indeed not contain a member named func. Looks like VS2005 doesn't deduce the template parameters correctly.
2,854,178
2,855,041
How to access webbrowser object on this code? C++
I found this example http://www.mvps.org/user32/webhost.cab that host an Internet Explorer WebBrowser object, and it uses this code to access the object void webhostwnd::CreateEmbeddedWebControl(void) { OleCreate(CLSID_WebBrowser,IID_IOleObject,OLERENDER_DRAW,0,&site,&storage,(void**)&mpWebObject); mpWebObject->SetHostNames(L"Web Host",L"Web View"); // I have no idea why this is necessary. remark it out and everything works perfectly. OleSetContainedObject(mpWebObject,TRUE); RECT rect; GetClientRect(hwnd,&rect); mpWebObject->DoVerb(OLEIVERB_SHOW,NULL,&site,-1,hwnd,&rect); IWebBrowser2* iBrowser; mpWebObject->QueryInterface(IID_IWebBrowser2,(void**)&iBrowser); VARIANT vURL; vURL.vt = VT_BSTR; vURL.bstrVal = SysAllocString(L"http://google.com"); VARIANT ve1, ve2, ve3, ve4; ve1.vt = VT_EMPTY; ve2.vt = VT_EMPTY; ve3.vt = VT_EMPTY; ve4.vt = VT_EMPTY; iBrowser->put_Left(0); iBrowser->put_Top(0); iBrowser->put_Width(rect.right); iBrowser->put_Height(rect.bottom); iBrowser->Navigate2(&vURL, &ve1, &ve2, &ve3, &ve4); VariantClear(&vURL); iBrowser->Release(); } I don't have much experience with cpp, I want to know how to access that same ie object (to use Navigate2 for example) from a button or something like that. How could I achieve this?
mpWebObject is a member of the class webhostwnd. You can use the code, IWebBrowser2* iBrowser; mpWebObject->QueryInterface(IID_IWebBrowser2,(void**)&iBrowser); anywhere in the class to access the browser interface( once the mpWebObject is created). If you are not hell bent on using the same code, here is a better example that could serve your purpose.
2,854,301
2,854,316
Is there a better way to check if a value is bigger than of type double?
double x; cin>>x; if( x > 1.7976931348623157e+308 || x < -1.7976931348623157e+308 ) { cout<<"value not in range"<<endl; exit(1); } Is there like a DOUBLE_MAX or DOUBLE_MIN and would I need to include any header files?
There are constants for the largest and smallest double types, but since x is of type double, x cannot be larger or smaller than these values! If you wish to compare an inputted value to these limits you'll need to parse the string yourself and check for overflow.
2,854,554
2,854,574
What speech libraries are available in Linux?
When it comes to TTS (text-to-speech) libraries in Linux, what choices do developers have? What libraries ship with the majority of distros? Are there minimal libraries? What functionality does each library offer? I'm approaching this primarily from a C++ point of view, although Python would suit me too.
Use Flite as your speech library, and then use voices from festival or festvox.
2,854,563
2,857,118
Lua/SWIG wrap userdata from within Lua
I am using swig-lua. I have a function in Lua which I call and it returns me a pointer (userdata). right now I know what this pointer is, but how can I tell Lua from within Lua?
From the Lua Reference Manual: setmetatable (table, metatable) Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from C.) You cannot "tell Lua" what a userdata is within Lua. It must be given a metatable or manipulated through bound function calls using the C API. See chapter 28.1 of Programming in Lua (Pil) for more information.
2,855,121
4,493,621
What is the purpose of using -pedantic in the GCC/G++ compiler?
This note says: -ansi: tells the compiler to implement the ANSI language option. This turns off certain "features" of GCC which are incompatible with the ANSI standard. -pedantic: used in conjunction with -ansi, this tells the compiler to be adhere strictly to the ANSI standard, rejecting any code which is not compliant. First things first: What is the purpose of the -pedantic and -ansi options of the GCC/G++ compiler (I couldn't understand the above description)? What are the right circumstances for using these two options? When should I use them? Are they important?
GCC compilers always try to compile your program if this is at all possible. However, in some cases, the C and C++ standards specify that certain extensions are forbidden. Conforming compilers such as GCC or g++ must issue a diagnostic when these extensions are encountered. For example, the GCC compiler’s -pedantic option causes GCC to issue warnings in such cases. Using the stricter -pedantic-errors option converts such diagnostic warnings into errors that will cause compilation to fail at such points. Only those non-ISO constructs that are required to be flagged by a conforming compiler will generate warnings or errors.
2,855,214
2,855,267
How can I assign pointer member with long string?
When I did the practice below to erase my pointer member and assign new value to it. (*pMyPointer).member.erase(); (*pMyPointer).member.assign("Hello"); // Successfully Than I tried more... (*pMyPointer).member.erase(); (*pMyPointer).member.assign("Long Multi Lines Format String"); // How to? If the long multi lines string can't quote by double quoter, how to handle it. Thank you.
I really have no clue what you are trying to ask. Maybe this: (*pMyPointer).member.assign("Long Multi Lines Format String" "more lines that will be" "concatenated by the compiler"); Or did you mean line breaks like this: (*pMyPointer).member.assign("Long Multi Lines Format String\n" "more lines that will be\n" "concatenated by the compiler");
2,855,504
2,856,225
What is the best practice when coding math class/functions?
I'm currently implementing some algorithms into an existing program. Long story short, I created a new class, "Adder". An Adder is a member of another class representing the physical object actually doing the calculus , which calls adder.calc() with its parameters (merely a list of objects to do the maths on). To do these maths, I need some parameters, which do not exist outside of the class (but can be set, see below). They're neither config parameters nor members of other classes. These parameters are D1 and D2, distances, and three arrays of fixed size: alpha, beta, delta. I know some of you are more comfortable reading code than reading text so here you go: class Adder { public: Adder(); virtual Adder::~Adder(); void set( float d1, float d2 ); void set( float d1, float d2, int alpha[N_MAX], int beta[N_MAX], int delta[N_MAX] ); // Snipped prototypes float calc( List& ... ); // ... inline float get_d1() { return d1_ ;}; inline float get_d2() { return d2_ ;}; private: float d1_; float d2_; int alpha_[N_MAX]; // A #define N_MAX is done elsewhere int beta_[N_MAX]; int delta_[N_MAX]; }; Since this object is used as a member of another class, it is declared in a *.h: private: Adder adder_; By doing that, I couldn't initialize the arrays (alpha/beta/delta) directly in the constructor ( int T[3] = { 1, 2, 3 }; ), without having to iterate throughout the three arrays. I thought of putting them in static const, but I don't think that's the proper way of solving such problems. My second guess was to use the constructor to initialize the arrays: Adder::Adder() { int alpha[N_MAX] = { 0, -60, -120, 180, 120, 60 }; int beta[N_MAX] = { 0, 0, 0, 0, 0, 0 }; int delta[N_MAX] = { 0, 0, 180, 180, 180, 0 }; set( 2.5, 0, alpha, beta, delta ); } void Adder::set( float d1, float d2 ) { if (d1 > 0) d1_ = d1; if (d2 > 0) d2_ = d2; } void Adder::set( float d1, float d2, int alpha[N_MAX], int beta[N_MAX], int delta[N_MAX] ) { set( d1, d2 ); for (int i = 0; i < N_MAX; ++i) { alpha_[i] = alpha[i]; beta_[i] = beta[i]; delta_[i] = delta[i]; } } Would it be better to use another function (init()) which would initialize the arrays? Or is there a better way of doing that? Did you see some mistakes or bad practice along the way?
You have chosen a very wide subject, so here is a broader answer. Be aware of your surroundings Too often I have seen code doing the same thing as elsewhere in the codebase. Make sure that the problem you are trying to solve has not already been solved by your team-mates or predecessors. Try not to reinvent the wheel An extension of my previous point. While everyone should probably write a linked-list or a string class as an exercise, there is no need to write one for production code. You will have access to MFC, OWL, STL, Boost, whatever. If the wheel has already been invented, use it and get on with coding a solution to the real problem! Think about how you are going to test your code Test Driven Development (TDD) is one way (but not the only way) to ensure that your code is both testable and tested. If you think about testing your code from the beginning, it will be very easy to test. Then test it! Write SOLID code The Wikipedia page explains this far better than I could. Ensure your code is readable Meaningful identifiers are just the beginning. Unnecessary comments can also detract from readability as can long functions, functions with long argument lists (such as your second setter), etcetera. If you have coding standards, stick to them. Use const more My major gripe with C++ is that things aren't const by default! In your example, your getters should be declared const and your setters should have their arguments passed in as const (and const-reference for the arrays). Ensure your code is maintainable Unit tests (as mentioned above) will ensure that the next person to change your code doesn't break your implementation. Ensure your library is usable If you follow Principle of least astonishment and document your library with unit-tests, programmers using it will have fewer issues. Refactor mercilessly An extension of the previous point. Do everything you can to reduce code duplication. Today I witnessed a bug-fix that had to be executed in fifteen separate places (and was only executed in thirteen of these).
2,855,750
2,855,813
Showing a progress bar while SFX archive is extracting
I'm writing a program with C++ and by native Win32 API. I'm creating a process from a SFX archive EXE in silent mode that no GUI is shown to user. But I want to show a progress bar in my application, while the SFX archive extracting. How can I do that? Thanks.
If the process you create produces some textual output to the standard output then you can probably parse that output somehow and show the progress. To know if it does, activate it in a command line windows and watch what you get from it. win32's CreateProcess() allows you to redirect the standard output of the process to a pipe. This way you can receive the output as soon as it is produced. If the process you're creating doesn't report its progress somehow then there's really not much you can do. You can try to come up with function between the size of the file and the average time it takes to extract it and then fake a progress bar. That will serve the purpose of setting the user's mind at ease but nothing more. --Edit The call to CreateProcess() returns as soon as the process is created. CreateProcess() fills up the struct PROCESS_INFORMATION with the handles of the process it creates. it contains the handle of the main thread of the process. If you want to wait for the process to finish you can WaitForSingleEvent() on that thread handle which gets signaled when the thread terminates. Don't forget to CloseHandle() those handles when you're done with them.
2,855,874
2,856,229
How to cast a pointer of memory block to std stream
I have programed an application on windows XP and in Visual Studio with c++ language. In that app I used LoadResource() API to load a resource for giving a file in the resource memory. It returned a pointer of memory block and I wanna cast the pointer to the std stream to use for compatibility. Could anyone help me?
Why would you need this? Casting raw data pointers to streams means byte-by-byte copying of your resource and, therefore, lacks in performance (and, also to mention, I don't see any benefit in this approach). If you want to work with raw memory, work with it. Casting here (compatibility?) seems to be a very strange approach. Still, if you want to do it, you could create some stream from your memory block, that treats it as a sequence of bytes. In this case, it means using std::stringstream (istringstream). After you lock your resource by LockResource, create a string from received void* pointer and pass it to your stringstream instance. void* memory = LockResource(...); // You would probably want to use SizeofResource() here size_t memory_size = ... ; std::string casted_memory(static_cast<char*>(memory), memory_size); std::istringstream stream(casted_memory);
2,855,884
2,860,753
Use the right tool for the job: embedded programming
I'm interested in programming languages well suited for embedded programming. In particular: Is it possible to program embedded systems in C++? Or is it better to use pure C? Or is C++ OK only if some features of the language (e.g. RTTI, exceptions and templates) are excluded? What about Java in this domain? Thanks.
Is it possible to program embedded systems in C++? Yes, of course, even on 8bit systems. C++ only has a slightly different run-time initialisation requirements than C, that being that before main() is invoked constructors for any static objects must be called. The overhead (not including the constructors themselves which is within your control) for that is tiny, though you do have to be careful since the order of construction is not defined. With C++ you only pay for what you use (and much that is useful may be free). That is to say for example, a piece of C code that is also C++ compilable will generally require no more memory and execute no slower when compiled as C++ than when compiled as C. There are some elements of C++ that you may need to be careful with, but much of the most useful features come at little or no cost, and great benefit. Or is it better to use pure C? Possibly, in some cases. Some smaller 8 and even 16 bit targets have no C++ compiler (or at least not one of any repute), using C code will give greater portability should that be an issue. Moreover on severely resource constrained targets with small applications, the benefits that C++ can bring over C are minimal. The extra features in C++ (primarily those that enable OOP) make it suited to relatively large and complex software construction. Or is C++ OK only if some features of the language (e.g. RTTI, exceptions and templates) are excluded? The language features that may be acceptable depend entirely on the target and the application. If you are memory constrained, you might avoid expensive features or libraries, and even then it may depend on whether it is code or data space you are short of (on targets where these are separate). If the application is hard real-time, you would avoid those features and library classes that are non-deterministic. In general, I suggest that if your target will be 32bit, always use C++ in preference to C, then cut your C++ to suit the memory and performance constraints. For smaller parts be a little more circumspect when choosing C++, though do not discount it altogether; it can make life easier. If you do choose to use C++, make sure you have decent debugger hardware/software that is C++ aware. The relative ease with which complex software can be constructed in C++, make a decent debugger even more valuable. Not all tools in the embedded arena are C++ aware or capable. I always recommend digging in the archives at Embedded.com on any embedded subject, it has a wealth of articles, including a number of just this question, including: Poor reasons for rejecting C++ Real men program in C Dive in to C++ and survive Guidelines for using C++ as an alternative to C in embedded designs Why C++ is a viable alternative to C in embedded systems design Better even at the lowest levels Regarding Java, I am no expert, but it has significant run-time requirements that make it unsuited to resource constrained systems. You will probably constrain yourself to relatively expensive hardware using Java. Its primary benefit is platform independence, but that portability does not extend to platforms that cannot support Java (of which there are many), so it is arguably less portable than a well designed C or C++ implementation with an abstracted hardware interface. [edit] Concidentally I just received this in the TechOnline newsletter: Using C++ Efficiently in Embedded Applications
2,855,968
2,856,052
How do I toggle 'always on top' for a QMainWindow in Qt without causing a flicker or a flash?
void MainWindow::on_actionAlways_on_Top_triggered(bool checked) { Qt::WindowFlags flags = this->windowFlags(); if (checked) { this->setWindowFlags(flags | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint); this->show(); } else { this->setWindowFlags(flags ^ (Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint)); this->show(); } } The above solution works but because setWindowFlags hides the window, it needs to be re-shown and of course that doesn't look very elegant. So how do I toggle "always on top" for a QMainWindow without that "flashing" side effect?
Nokia says no: It is not possible to make changes to the window flags once the window has been created without causing flicker. Flicker is unavoidable since the window needs to be recreated. But sometimes if you're stuck with a flashing effect that's kind of ugly like this, you can intentionally drag it out to make it seem like something "cool" just happened. Maybe pop up a little progress bar that's not in the window, say "Adjusting Window Properties!"...fade the window out of existence and then back in, and close the progress bar popup.
2,856,156
2,856,186
Constructors for C++ objects
I have class Person as following : class Person { char* name; int age; }; Now I need to add two contructors. One taking no arguments, that inserts field values to dynamically allocated resources. Second taking (char*, int) arguments initialized by initialization list. Last part is to define a destructor showing information about destroying objects and deallocating dynamically allocated resources. How to perform this task ? That's what I already have : class Person { char* name; int age; public: Person(){ this->name = new *char; this->age = new int; } Person(char* c, int i){ } };
In the default constructor, allocation of the char array should include its desired size, e.g. this->name = new char[32]; Note that this size includes the terminating 0 character, so the effective length of names you can store in this array is 31. In the parameterized constructor, you can simply assign the given parameters to your class members. In the destructor, you need to deallocate dynamically allocated resources - make sure to use delete[] when, and only when, deallocating memory allocated with new[]: ~Person(){ std::cout << "Destroying resources" << std::endl; delete[] name; delete age; } Update: I missed this one: if you want to allocate age dynamically, you should declare it as int* age. I assume that the point of this exercise is to practice dynamic allocation/deallocation; in this context, it is fine. However, in general, it is not good practice to dynamically allocate ints, and instead of char* you should almost always use std::string, which handles memory allocation for you automatically and safely.
2,856,176
2,871,808
How to make windows media player go to previous song in playlist?
I am writing a simple Windows app in c++, that will be able to send commands to windows media player. My problem is that I want my app to move to the previous song in the playlist. IWMPControls::previous() seems to do the job, but its behavior differs from what is written in msdn. In fact this function rewinds current media to the beginning and then (if current position is less than 2-3 seconds) it switches to the previous song. I would like to implement two different buttons (please, don't ask me why :)) - one for rewinding to the beginning, and one - to moving to previous song. Is there any easy way to do this through IWMPControls (or any other WMP-related COM interface)? p.s. I could handle this if I could get the position (index) of the current song in the list. But as far as I read MSDN, it seems to me that there is no easy way to get the current item index from playlist...
Well, I think I figured it out. You can force the previous song by 1) first calling IWMPControls::put_currentPosition(0.0), 2) then calling IWMPControls::previous(). There can be some problems, as it seems that some time must pass between 1) and 2). The obvious solution is to use ::PostMessage() inside your program (NOT ::PostMessage to WMP), so you make step 1), then PostMessage and, while processing your message, make step 2).
2,856,334
2,856,579
EXE stops working if containing folder is renamed. MSVCP90.dll
This popup comes up as soon as the app is started: The program can't start because MSVCP90.dll is missing from your computer. Before anyone says "install the VC++ runtimes", wait! If I rename the folder containing my .EXE then the app runs. If I rename it back, it breaks. The app has been running for weeks without any changes to my system/VS installation (2008 SP1), we suddenly spotted this error a few days ago. Lost as to why the name of the dir is causing issues... again this has not changed in months and all our resource paths are relative anyway, e.g "../someOtherDir/...." It doesn't just do this on my PC, we have the /bin dir (the one containing EXE) in SVN and suddenly everyone started seeing the same issue, even though the binaries themselves seem just fine. Is it possible some additional data got put into SVN and that's the cause? Since it's not just one PC, there must be something either in SVN or the EXE itself... Note this popup comes before our code even gets to run.
It seems that there is a .exe.manifest file lying around, specifying some other version of MSVCP90.dll. Removing this file should do the trick (In theory the manifest is the solution against dll hell, but in reality it is just a new PITA).
2,856,721
2,856,747
Linkage Error with Inherited Class
I have static library and another program which uses it. In the static library If I define header without inheretence it works fine. class TcpCommunication On the other hand If I use inheretence with a QT class, class TcpCommunication:public QTcpServer I'm getting linkage error when I compiling code which uses this static library. >MStoDKAPId.lib(TcpCommunication.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: virtual __thiscall QTcpServer::~QTcpServer(void)" (__imp_??1QTcpServer@@UAE@XZ) referenced in function "public: virtual __thiscall TcpCommunication::~TcpCommunication(void)" (??1TcpCommunication@@UAE@XZ) What can be the problem? Thanks.
The application using your static library also needs to link to QT
2,857,157
2,857,809
stdout and stderr character encoding
i working on a c++ string library that have main 4 classes that deals with ASCII, UTF8, UTF16, UTF32 strings, every class has Print function that format an input string and print the result to stdout or stderr. my problem is i don't know what is the default character encoding for those streams. for now my classes work in windows, later i'll add support for mac and linux so if you know anything about those stream encoding i'll appreciate it. so my question is: what is the default encoding for stdout and stderr and can i change that encoding later and if so what would happens to data stored there? thank you.
stdout and stderr use "C" locale. "C" locale is netural, and in most system translated into the current user's locale. You can force the program to use a specific locale using setlocale function: // Set all categories and return "English_USA.1252" setlocale( LC_ALL, "English" ); // Set only the LC_MONETARY category and return "French_France.1252" setlocale( LC_MONETARY, "French" ); setlocale( LC_ALL, NULL ); The locale strings supported are system and compiler specific. Only "C" and "" are required to be supported. http://www.cplusplus.com/reference/clibrary/clocale/
2,857,272
2,857,379
Can't compile std::map sorting, why?
This is my code: map<string, int> errs; struct Compare { bool operator() (map<string, int>::const_iterator l, map<string, int>::const_iterator r) { return ((*l).second < (*r).second); } } comp; sort(errs.begin(), errs.end(), comp); Can't compile. This is what I'm getting: no matching function for call to ‘sort(..’ Why so? Can anyone help? Thanks!
Maps are, by definition, sorted by their keys, so you can't resort a map by its values. You can provide an alternate comparison function as the third template parameter to a map, if you want to sort the keys by a non-default order. If you're trying to sort a map by its values, then perhaps you could try using Boost.MultiIndex to make a bidirectional map instead?
2,857,526
2,858,556
Genetic programming in c++, library suggestions?
I'm looking to add some genetic algorithms to an Operations research project I have been involved in. Currently we have a program that aids in optimizing some scheduling and we want to add in some heuristics in the form of genetic algorithms. Are there any good libraries for generic genetic programming/algorithms in c++? Or would you recommend I just code my own? I should add that while I am not new to c++ I am fairly new to doing this sort of mathematical optimization work in c++ as the group I worked with previously had tended to use a proprietary optimization package. We have a fitness function that is fairly computationally intensive to evaluate and we have a cluster to run this on so parallelized code is highly desirable. So is c++ a good language for this? If not please recommend some other ones as I am willing to learn another language if it makes life easier. thanks!
I would recommend rolling your own. 90% of the work in a GP is coding the genotype, how it gets operated on, and the fitness calculation. These are parts that change for every different problem/project. The actual evolutionary algorithm part is usually quite simple. There are several GP libraries out there ( http://en.wikipedia.org/wiki/Symbolic_Regression#Implementations ). I would use these as examples and references though. C++ is a good choice for GP because they tend to be very computationally intensive. Usually, the fitness function is the bottleneck, so it's worthwhile to at least make this part compiled/optimized.
2,857,589
2,857,637
Can I avoid a circular dependency in my Matrix class's iterators?
We have two classes: template<typename T, typename Size, typename Stack, typename Sparse> class Matrix and template<typename T, typename Size> class Iterator Matrix should be able to return begin and end iterators and Iterator will keep a referrence to the Matrix to access the elements via it's interface. We don't want Iterator to depend on the internal storage of the Matrix to prevent coupling. How can we solve this cyclic dependency problem? (The internal Storage class has the same template parameters as the Matrix class and the same access procedures as the Matrix itself)
In order to iterate, iterators typically do need to know about the internal storage they iterate over - this coupling can usually not be avoided. Take a map iterator for example - it is going to have to know about the internal tree structure of the map in order for it to do its job.
2,857,864
2,857,959
QTextEdit with different text colors (Qt / C++)
I have a QTextEdit box that displays text, and I'd like to be able to set the text color for different lines of text in the same QTextEdit box. (i.e. line 1 might be red, line 2 might be black, etc.) Is this possible in a QTextEdit box? If not, what's the easiest way to get this behavior? Thanks.
Use text formated as HTML, for example: textEdit->setHtml(text); where text, is a HTML formated text, contains with colored lines and etc.
2,858,127
2,858,291
"multiset" & "multimap" - What's the point?
As the question states ... I don't get the point about multisets / multimaps. So, what's the purpose?
Some use cases: multimap With ZIP code as a key, all people which have that ZIP code With account ID as key, all open orders of that person/account A dictionary, with per keyword various explanations multiset is in essence a map with a key and a integer count. The inventory of a shop, all products have their key and the amount still available is the value accumulated sales data of a shop, every time a product is sold the product id get's added to the multiset thereby increasing the amount sold
2,858,134
2,858,157
Windows message when mouse leave a control?
I have created a control and the mosemove for that control makes it change color, but I want to change it back to default when my mouse moves out of that control. I would have thought WM_MOUSELEAVE would do it but it didn't. Thanks
That would be the correct message. Are you calling TrackMouseEvent?
2,858,136
2,858,639
Can I detect (and warn on) redundancies at compile time?
Is there any way I can catch and warn about redundancies at compile time? Such as if (abc && abc) or if (def || def) Ok, this isn't actually from an optimisation point of view - I'm thinking more along the lines of a mistake in code - so when the coder intended to write if (abc && abc) when actually they meant to write if (abc && def) The compiler is going to silently optimise away the mistake, whereas I actually want to know if I can get the compiler to warn me if that has happened, in case it's in there by mistake!
If you're looking for a tool that statically checks for dubious-looking code, you most likely need some form of lint. Industrial-strength lint implementations check for many, many things--I don't know if it will check for the kind of redundancy you gave as an example, but it's worth a try.
2,858,217
2,858,236
How do I extend mouse space in OpenGL windowed mode
How do I extend the distance the mouse can move in an OpenGL window? What I wish to achieve is an fps like interface where the cursor is hidden and camera rotations are not limited by the mouse having to remain inside the window boundaries.
This is often implemented by "warping" the mouse back to the center of the screen, in Linux. Here is a forum thread on this, using the popular SDL library to do the actual mouse reading. In Windows, look into using lower-level input API:s, such as XInput.
2,858,398
2,858,471
Gradients for polygons in OpenGL
what is the best way to create a gradient for a 2D polygon in OpenGL, (Linear, and Radial)? Thanks How can you generate textures for radial gradients on the fly?
Linear is very easy - you just set different colors to different points like red ---- red | | | | | | blue ---- blue for radial texture might be better option to generate it on fly create empty texture then fill it with function sqrt((MAXX - x)^2 + (MAXY - y)^2), then add color to it.
2,858,483
2,860,396
How can I compare the performance of log() and fp division in C++?
I’m using a log-based class in C++ to store very small floating-point values (as the values otherwise go beyond the scope of double). As I’m performing a large number of multiplications, this has the added benefit of converting the multiplications to sums. However, at a certain point in my algorithm, I need to divide a standard double value by an integer value and than do a *= to a log-based value. I have overloaded the *= operator for my log-based class and the right-hand side value is first converted to a log-based value by running log() and than added to the left-hand side value. Thus the operations actually performed are floating-point division, log() and floating-point summation. My question whether it would be faster to first convert the denominator to a log-based value, which would replace the floating-point division with floating-point subtraction, yielding the following chain of operations: twice log(), floating-point subtraction, floating-point summation. In the end, this boils down to whether floating-point division is faster or slower than log(). I suspect that a common answer would be that this is compiler and architecture dependent, so I’ll say that I use gcc 4.2 from Apple on darwin 10.3.0. Still, I hope to get an answer with a general remark on the speed of these two operators and/or an idea on how to measure the difference myself, as there might be more going on here, e.g. executing the constructors that do the type conversion etc. Cheers!
Do you divide by the same integer multiple times? If so you can instead multiply by 1./yourInteger, and only do the divide once. That would be faster than either if possible. As to your actual question, it's not only compiler and architecture dependent, but also micro-architecture and data dependent. On your particular platform (darwin/x86), for current hardware i5/i7: ~24 cycles for divide(1), ~35 cycles for log( )(2). However, because divide only uses a single instruction dispatch slot, the hardware's reorder engine can do other useful computation while the divide is in flight; log( ) is implemented in software, by contrast, and so there is less opportunity for the processor to hoist other computations into the latency of the logarithm. This means that in practice, divide will often be a good bit faster. 1) From the Intel Optimization Manual 2) Measured by calling log( ) in a tight loop and using mach_absolute_time( ) to get wall time.
2,858,724
2,859,280
Link one shared library static to my shared library
I am struggeling a little bit with some options for linking on a project I am currently working on: I am trying to create a shared library which is linked against 2 other libraries. (Lets call them libfoo.so and libbar.so) My output library has to be a shared library and I want to static link libfoo.so to the resulting library, but libbar.so should linked as a dynamic library. (libbar.so should be available on every machine, where libfoo.so is not available and I do not want the user install it / ship it with my binaries.) How could I archive this? My current build instruction look like this: c++ -Wall -shared -c -o src/lib.o src/lib.cpp c++ -Wall -shared -o lib.ndll src/lib.o -lfoo -lbar I my defense: I am not a c/c++ expert, so sorry if this question seems to be stupid.
There are two Linux C/C++ library types. Static libraries (*.a) are archives of object code which are linked with and becomes part of the application. They are created with and can be manipulated using the ar(1) command (i.e. ar -t libfoo.a will list the files in the library/archive). Dynamically linked shared object libraries (*.so) can be used in two ways. The shared object libraries can be dynamically linked at run time but statically aware. The libraries must be available during compile/link phase. The shared objects are not included into the binary executable but are tied to the execution. The shared object libraries can be dynamically loaded/unloaded and linked during execution using the dynamic linking loader system functions. In order to statically link libfoo.so into your binary, you will need a corresponding static library which is typically called libfoo.a. You can use a static library by invoking it as part of the compilation and linking process when creating a program executable. The result would be changing your build commands to something like the following: g++ -Wall -fPIC -c -o src/lib.o src/lib.cpp g++ -shared -Wl,-soname,mylib.so.1 -o mylib.so.1 src/lib.o -L/path/to/library-directory -lbar libfoo.a
2,858,979
2,859,608
CComPtr CoCreateInstance returns 0x80070582 (Class already exists.)
I have a StartComObjects function called when the user presses the Login button and a StopComObjects function called when the user presses the Cancel button. The StartComObjects function uses CComPtr.CoCreateInstance to create the COM object and sets up some connection points using AfxConnectionAdvise. When the user presses the Cancel button the connection points are disconnected using AfxConnectionUnadvise and the COM object is stopped before calling Release on the CComPtr. When I press the login button a second time the CComPtr.CoCreateInstance returns 0x80070582 (Class already exists). This prevents the COM object from being created on the second call to StartComObjects. I am not sure why this isn't working. Shouldn't CComPtr::Release free the COM object and allow me to create a new one after the old one was stopped? Is there any way to get around this?
It is a Windows error (facility 7, error code 1410), caused by RegisterClass(Ex). This sample code reproduces it: #include "stdafx.h" #include <windows.h> #include <assert.h> int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR, int) { WNDCLASSEX wcex = { sizeof(WNDCLASSEX) }; wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.hInstance = hInstance; wcex.lpszClassName = L"Example"; ATOM at1 = RegisterClassEx(&wcex); assert(at1 != 0); // Register again, should fail with error 1410 ATOM at2 = RegisterClassEx(&wcex); assert(at2 == 0); int err = GetLastError(); assert(err == ERROR_CLASS_ALREADY_EXISTS); return 0; } Look through your code for places where the coclass uses RegisterClass(Ex). It must use UnregisterClass when the instance is destroyed. Or avoid registering the window class again. Or ignore the specific error code.
2,859,062
2,859,136
Can a constructor return a NULL value?
I know constructors don't "return" anything but for instance if I call CMyClass *object = new CMyClass() is there any way to make object to be NULL if the constructor fails? In my case I have some images that have to be loaded and if the file reading fails I'd like it to return null. Is there any way to do that? Thanks in advance.
I agree with everyone else that you should use exceptions, but if you do really need to use NULL for some reason, make the constructor private and use a factory method: static CMyClass* CMyClass::create(); This means you can't construct instances normally though, and you can't allocate them on the stack anymore, which is a pretty big downside.
2,859,435
2,860,759
Suggestions on error handling of Win32 C++ code: AtlThrow vs. STL exceptions
In writing Win32 C++ code, I'd appreciate some hints on how to handle errors of Win32 APIs. In particular, in case of a failure of a Win32 function call (e.g. MapViewOfFile), is it better to: use AtlThrowLastWin32 define a Win32Exception class derived from std::exception, with an added HRESULT data member to store the HRESULT corresponding to value returned by GetLastError? In this latter case, I could use the what() method to return a detailed error string (e.g. "MapViewOfFile call failed in MyClass::DoSomething() method."). What are the pros and cons of 1 vs. 2? Is there any other better option that I am missing? As a side note, if I'd like to localize the component I'm developing, how could I localize the exception what() string? I was thinking of building a table mapping the original English string returned by what() into a Unicode localized error string. Could anyone suggest a better approach? Thanks much for your insights and suggestions.
AtlThrow isn't terribly useful, it throws CAtlException which merely wraps an error code. Having a MapViewOfFile fail is a truly exceptional problem with a low-level error code that doesn't tell you or your user much at all what actually went wrong. Handling the error is almost always impossible, it isn't likely that you can shrug it off and just not use a MMF. You'll have to log the error and terminate your program with a very generic error. Getting very detailed in your error message is usually wasted effort. "MapViewOfFile call failed in MyClass::DoSomething() method" just doesn't mean anything at all to your user or her support staff. Great for you though, something to trace the error to. But you can easily automate this, without localization trouble, by using the __FILE__ and __LINE__ macros. All that you really need to match the error to the source code. Keep the error message short and snappy. For Windows errors, you'll want to use FormatMessage() to let Windows generate the message. It will automatically be localized, the message text is standardized and googles well. Deriving from std::exception is okay. Use string resource IDs for custom messages so you can easily localize them. Solves the what() problem too.
2,859,761
2,859,891
adding virtual function to the end of the class declaration avoids binary incompatibility?
Could someone explain to me why adding a virtual function to the end of a class declaration avoids binary incompatibility? If I have: class A { public: virtual ~A(); virtual void someFuncA() = 0; virtual void someFuncB() = 0; virtual void other1() = 0; private: int someVal; }; And later modify this class declaration to: class A { public: virtual ~A(); virtual void someFuncA() = 0; virtual void someFuncB() = 0; virtual void someFuncC() = 0; virtual void other1() = 0; private: int someVal; }; I get a coredump from another .so compiled against the previous declaration. But if I put someFuncC() at the end of the class declaration (after "int someVal"): class A { public: virtual ~A(); virtual void someFuncA() = 0; virtual void someFuncB() = 0; virtual void other1() = 0; private: int someVal; public: virtual void someFuncC() = 0; }; I don't see coredump anymore. Could someone tell me why this is? And does this trick always work? PS. compiler is gcc, does this work with other compilers?
I'm a bit surprised that this particular rearrangement helps at all. It's certainly not guaranteed to work. The class you give above will normally be translated to something on this order: typedef void (*vfunc)(void); struct __A__impl { vfunc __vtable_ptr; int someVal; }; __A__impl__init(__A__impl *object) { static vfunc virtual_functions[] = { __A__dtor, __A__someFuncA, __A__someFuncB}; object->__vtable__ptr = virtual_functions; } When/if you add someFuncC, you should normally get another entry added to the class' virtual functions table. If the compiler arranges that before any of the other functions, you'll run into a problem where attempting to invoke one function actually invokes another. As long as its address is at the end of the virtual function table, things should still work. C++ doesn't guarantee anything about how vtables are arranged though (or even that there is a vtable). With respect to normal data, (non-static) members are required to be arranged in ascending order as long as there isn't an intervening access specificer (public:, protected: or private:). If the compiler followed the same rules when mapping virtual function declarations to vtable positions, your first attempt should work, but your second could break. Obviously enough, there's no guarantee of that though -- as long as it works consistently, the compiler can arrange the vtable about any way it wants to.