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
1,040,504
1,041,141
Any way to get the AtomineerUtils addin to ignore __declspecs?
I'm evaluating the AtomineerUtils addin (which allows Visual Studio to auto-enter doxygen comment blocks). It misfires slightly when I have a class definition that has __declspec (dllexport) in it. That is, instead of the class name appearing in the comment block it adds, it uses the word declspec. Small annoyance, but annoyance nonetheless. Anyone use this tool and have any clues?
Wow.... shot off an email to the Atomineer developer at the same time I posted this. He just got back to me, his new version 5.97 fixes this!
1,040,914
1,040,990
how to Ignore definitions (VS2008)
i have some sourcecode that I want to compile with VS2008 but there are many errors i have to fix. Now there are some Enums like: enum { BACKGROUND = 0x00000001, WEAPON = 0x00000002, TRANSPARENT = 0x00000004 } The problem is that TRANSPARENT is defined as: #define TRANSPARENT 1 in WinGDI.h That will cause a compile error like: error C2143: syntax error : missing '}' before 'constant' Is it possible to fix that error without renaming the field in the enum and without removing the WinGDI.h from the includes (I don't know where it's included..)
You can use #undef TRANSPARENT but that may cause errors elsewhere, if the WinGDI TRANSPARENT is used afterwards. A (messy) workaround could be: #ifdef TRANSPARENT #define _TRANSPARENT TRANSPARENT #undef TRANSPARENT #endif and after your code: #ifdef _TRANSPARENT #define TRANSPARENT _TRANSPARENT #endif
1,040,950
1,040,994
Reference-type conversion operators: asking for trouble?
When I compile the following code using g++ class A {}; void foo(A&) {} int main() { foo(A()); return 0; } I get the following error messages: > g++ test.cpp -o test test.cpp: In function ‘int main()’: test.cpp:10: error: invalid initialization of non-const reference of type ‘A&’ from a temporary of type ‘A’ test.cpp:6: error: in passing argument 1 of ‘void foo(A&)’ After some reflection, these errors make plenty of sense to me. A() is just a temporary value, not an assignable location on the stack, so it wouldn't seem to have an address. If it doesn't have an address, then I can't hold a reference to it. Okay, fine. But wait! If I add the following conversion operator to the class A class A { public: operator A&() { return *this; } }; then all is well! My question is whether this even remotely safe. What exactly does this point to when A() is constructed as a temporary value? I am given some confidence by the fact that void foo(const A&) {} can accept temporary values according to g++ and all other compilers I've used. The const keyword can always be cast away, so it would surprise me if there were any actual semantic differences between a const A& parameter and an A& parameter. So I guess that's another way of asking my question: why is a const reference to a temporary value considered safe by the compiler whereas a non-const reference is not?
It isn't that an address can't be taken (the compiler could always order it shoved on the stack, which it does with ref-to-const), it's a question of programmers intent. With an interface that takes a A&, it is saying "I will modify what is in this parameter so you can read after the function call". If you pass it a temporary, then the thing it "modified" doesn't exist after the function. This is (probably) a programming error, so it is disallowed. For instance, consider: void plus_one(int & x) { ++x; } int main() { int x = 2; float f = 10.0; plus_one(x); plus_one(f); cout << x << endl << f << endl; } This doesn't compile, but if temporaries could bind to a ref-to-non-const, it would compile but have surprising results. In plus_one(f), f would be implicitly converted to an temporary int, plus_one would take the temp and increment it, leaving the underlying float f untouched. When plus_one returned, it would have had no effect. This is almost certainly not what the programmer intended. The rule does occasionally mess up. A common example (described here), is trying to open a file, print something, and close it. You'd want to be able to do: ofstream("bar.t") << "flah"; But you can't because operator<< takes a ref-to-non-const. Your options are break it into two lines, or call a method returning a ref-to-non-const: ofstream("bar.t").flush() << "flah";
1,041,074
1,041,122
throwing exceptions of objects on the stack, mem leak with new?
Is it a bug to do this: if(some_error) throw Cat("Minoo"); Where Cat is a class. Then in some other function that called the method that threw the exception... I would have: catch(const Cat &c) { } If it is invalid, do I use new Cat("Minoo"); Would that cause a memory leak?
1) Invalid? No, that's precisely what you're supposed to do: throw an object. The object in the throw-statement may be on the stack, but it is copied when it is thrown. Compare, for example, the effect of executing return Cat("Minoo"); 2) Will throwing a pointer cause the pointed-to object to be leaked? Yes, if the object was allocated on the heap and unless you arrange to delete it. But you should avoid throwing pointers as a general rule.
1,041,167
1,041,171
Rethrowing from caught
If I throw an exception: throw Cat("Minoo"); Then I catch and rethrow with ... at some lower level in the call stack: catch(...) { throw; } Then at some other lower level in the call stack I try to catch with: catch(const Cat& c) { //Will it enter here, and if so will c be valid data? } catch(...) { }
Yes, this is correct. This is addressed in the very next question of the section of the C++ FAQ that I linked you to on your previous question.
1,041,218
1,041,263
The "Self-Factory" Pattern
I don't know if there is an official name for this, but I have been playing with what I like to call the "self-factory" pattern. Basically, it's when an abstract base class acts as a factory for itself. Let me explain: I have Foo objects and Bar objects in my system, which are used via interfaces FooInterface and BarInterface. I need to give my clients the right type of Foo and Bar. The decision of which concrete Foo object to create is made at compile time. For example, if you compile on win32, you want to only create Win32Foo objects, and if you compile on OSX you want to only create OSXFoo objects and so on. But, the decision of which concrete Bar object to create is made at runtime, based on a key string. Now, my question is about the best way to implement this scheme. One way I come up with uses regular factories: shared_ptr<FooInterface> foo = FooFactory::create(); shared_ptr<BarInterface> happyBar = BarFactory::create("Happy"); shared_ptr<BarInterface> sadBar = BarFactory::create("Sad"); Another way is to use what I call "self-factories": shared_ptr<FooInterface> foo = FooInterface::create(); shared_ptr<BarInterface> happyBar = BarInterface::create("Happy"); shared_ptr<BarInterface> sadBar = BarInterface::create("Sad"); What are the pros and cons of each approach, both from a usability standpoint and from an architectural standpoint?
Factories have two common uses: 1) Decide dynamic polymorphic type at runtime, based on parameters and/or global state (such as configuration). Your pattern does this. 2) Dependency injection: rather than using a static function to create objects, use a factory object, so that the type of object returned can be configured by the caller, by passing in whatever factory they want. Neither of these patterns provides this. Furthermore, your second pattern doesn't even allow static dependency injection (by having template functions that take a factory class as a template parameter), because the interface and the factory are the same. So one con of your pattern (and of your regular factories) is that dependency injection isn't really supported. There is one and only one function to call to get an object that's a FooInterface, and that is FooInterface::create(). I'll not argue why dependency injection is useful, just point out that if you build this way, you can't use it.
1,041,342
1,041,417
Fluent interfaces and inheritance in C++
I'd like to build a base (abstract) class (let's call it type::base) with some common funcionality and a fluent interface, the problem I'm facing is the return type of all those methods class base { public: base(); virtual ~base(); base& with_foo(); base& with_bar(); protected: // whatever... }; Now I could make subtypes, e.g.: class my_type : public base { public: myType(); // more methods... }; The problem comes when using those subtypes like this: my_type build_my_type() { return my_type().with_foo().with_bar(); } This won't compile because we're returning base instead of my_type. I know that I could just: my_type build_my_type() { my_type ret; ret.with_foo().with_bar(); return ret; } But I was thinking how can I implement it, and I've not found any valid ideas, some suggestion?
This problem of "losing the type" can be solved with templates - but it's rather complicated. Eg. class Pizza { string topping; public: virtual double price() const; }; template <class T, class Base> class FluentPizza : public Base { T* withAnchovies() { ... some implementation ... }; }; class RectPizza : public FluentPizza<RectPizza, Pizza> { double price() const { return length*width; :) } }; class SquarePizza : public FluentPizza<SquarePizza, RectPizza> { ... something else ... }; You can then write SquarePizza* p=(new SquarePizza)->withAnchovies(); The pattern is that instead of class T : public B you write class T : public Fluent<T, B> Another approach could be not to use fluent interface on the objects, but on pointers instead: class Pizza { ... }; class RectPizza { ... }; class SquarePizza { ... whatever you might imagine ... }; template <class T> class FluentPizzaPtr { T* pizza; public: FluentPizzaPtr withAnchovies() { pizza->addAnchovies(); // a nonfluent method return *this; } }; Use like this: FluentPizzaPtr<SquarePizza> squarePizzaFactory() { ... } FluentPizzaPtr<SquarePizza> myPizza=squarePizzaFactory().withAnchovies();
1,041,618
1,041,653
Is using *this a good idea?
I'm not sure if return *this is the only way we could return an instance of a class who called a member function? The reason why I asked is because our instructor told us to avoid using pointers if necessary and I'm wondering if this is a case where the only necessary way to do it is by returning the this pointer. I'm working with a fraction class that holds private data members numerator and denominator. The member function I'm talking about is used to add two fractions for example: Fraction C = A.plus(B); plus member function is defined as this: Fraction& plus( const Fraction frac ) The instructor wants us to do C = A += B , so I guess that's why.
Get a new instructor. It looks as if the declaration of plus() is completely wrong. it probably should return a value rather than a reference if it must return a reference, it should return a const reference it should definitely take a const reference as a parameter That is for likely sensible implementations of a member plus() function. Of course, it should probably be a friend.
1,041,620
1,041,939
What's the most efficient way to erase duplicates and sort a vector?
I need to take a C++ vector with potentially a lot of elements, erase duplicates, and sort it. I currently have the below code, but it doesn't work. vec.erase( std::unique(vec.begin(), vec.end()), vec.end()); std::sort(vec.begin(), vec.end()); How can I correctly do this? Additionally, is it faster to erase the duplicates first (similar to coded above) or perform the sort first? If I do perform the sort first, is it guaranteed to remain sorted after std::unique is executed? Or is there another (perhaps more efficient) way to do all this?
I agree with R. Pate and Todd Gardner; a std::set might be a good idea here. Even if you're stuck using vectors, if you have enough duplicates, you might be better off creating a set to do the dirty work. Let's compare three approaches: Just using vector, sort + unique sort( vec.begin(), vec.end() ); vec.erase( unique( vec.begin(), vec.end() ), vec.end() ); Convert to set (manually) set<int> s; unsigned size = vec.size(); for( unsigned i = 0; i < size; ++i ) s.insert( vec[i] ); vec.assign( s.begin(), s.end() ); Convert to set (using a constructor) set<int> s( vec.begin(), vec.end() ); vec.assign( s.begin(), s.end() ); Here's how these perform as the number of duplicates changes: Summary: when the number of duplicates is large enough, it's actually faster to convert to a set and then dump the data back into a vector. And for some reason, doing the set conversion manually seems to be faster than using the set constructor -- at least on the toy random data that I used.
1,041,866
1,041,880
What is the effect of extern "C" in C++?
What exactly does putting extern "C" into C++ code do? For example: extern "C" { void foo(); }
extern "C" makes a function-name in C++ have C linkage (compiler does not mangle the name) so that client C code can link to (use) your function using a C compatible header file that contains just the declaration of your function. Your function definition is contained in a binary format (that was compiled by your C++ compiler) that the client C linker will then link to using the C name. Since C++ has overloading of function names and C does not, the C++ compiler cannot just use the function name as a unique id to link to, so it mangles the name by adding information about the arguments. A C compiler does not need to mangle the name since you can not overload function names in C. When you state that a function has extern "C" linkage in C++, the C++ compiler does not add argument/parameter type information to the name used for linkage. Just so you know, you can specify extern "C" linkage to each individual declaration/definition explicitly or use a block to group a sequence of declarations/definitions to have a certain linkage: extern "C" void foo(int); extern "C" { void g(char); int i; } If you care about the technicalities, they are listed in section 7.5 of the C++03 standard, here is a brief summary (with emphasis on extern "C"): extern "C" is a linkage-specification Every compiler is required to provide "C" linkage A linkage specification shall occur only in namespace scope All function types, function names and variable names have a language linkage See Richard's Comment: Only function names and variable names with external linkage have a language linkage Two function types with distinct language linkages are distinct types even if otherwise identical Linkage specs nest, inner one determines the final linkage extern "C" is ignored for class members At most one function with a particular name can have "C" linkage (regardless of namespace) extern "C" forces a function to have external linkage (cannot make it static) See Richard's comment: static inside extern "C" is valid; an entity so declared has internal linkage, and so does not have a language linkage Linkage from C++ to objects defined in other languages and to objects defined in C++ from other languages is implementation-defined and language-dependent. Only where the object layout strategies of two language implementations are similar enough can such linkage be achieved
1,042,107
1,042,120
Compiler not flagging incorrect return value for HRESULT
I just spent way too long trying to diagnose why, in the following snippet of code, the ProcessEvent() method seemed to be ignoring the false value I passed in for aInvokeEventHandler: HRESULT CEventManager:: Process(Event anEvent) { return (m_pPool->GetFsm()->ProcessEvent(anEvent), false); } // Definition of ProcessEvent() HRESULT ProcessEvent(const Event& anEvent, bool aInvokeEventHandler = true); Whenever I broke in the ProcessEvent() method, aInvokeEventHandler would always be true, regardless of whether I passed in false. It took a workmate to point out to me that the false value should be inside the inner parentheses on the return line, like so: return m_pPool->GetFsm()->ProcessEvent(anEvent, false); // Corrected code As soon as I saw this, I kicked myself. Spotting this was obviously made harder because the original coder used redundant outer parentheses on the return line. My question is, why didn't the compiler pick this up for me? My method is returning a HRESULT, yet in the original code above, I am clearly returning a composite set of values in parentheses, i.e: (HRESULT, bool) Is notation like this acceptable in the C/C++ standards, and if so, what purpose would there be in allowing this? Or is this a bug in the compiler?
You are suffering from the comma operator, which evaluates and discards the value of its left-hand operand, and then evaluates its right-hand operand as the value of the expression. Also, the default value for the argument to ProcessEvent is why your one-argument call was acceptable.
1,042,110
12,762,166
Using scanf() in C++ programs is faster than using cin?
I don't know if this is true, but when I was reading FAQ on one of the problem providing sites, I found something, that poke my attention: Check your input/output methods. In C++, using cin and cout is too slow. Use these, and you will guarantee not being able to solve any problem with a decent amount of input or output. Use printf and scanf instead. Can someone please clarify this? Is really using scanf() in C++ programs faster than using cin >> something ? If yes, that is it a good practice to use it in C++ programs? I thought that it was C specific, though I am just learning C++...
Here's a quick test of a simple case: a program to read a list of numbers from standard input and XOR all of the numbers. iostream version: #include <iostream> int main(int argc, char **argv) { int parity = 0; int x; while (std::cin >> x) parity ^= x; std::cout << parity << std::endl; return 0; } scanf version: #include <stdio.h> int main(int argc, char **argv) { int parity = 0; int x; while (1 == scanf("%d", &x)) parity ^= x; printf("%d\n", parity); return 0; } Results Using a third program, I generated a text file containing 33,280,276 random numbers. The execution times are: iostream version: 24.3 seconds scanf version: 6.4 seconds Changing the compiler's optimization settings didn't seem to change the results much at all. Thus: there really is a speed difference. EDIT: User clyfish points out below that the speed difference is largely due to the iostream I/O functions maintaining synchronization with the C I/O functions. We can turn this off with a call to std::ios::sync_with_stdio(false);: #include <iostream> int main(int argc, char **argv) { int parity = 0; int x; std::ios::sync_with_stdio(false); while (std::cin >> x) parity ^= x; std::cout << parity << std::endl; return 0; } New results: iostream version: 21.9 seconds scanf version: 6.8 seconds iostream with sync_with_stdio(false): 5.5 seconds C++ iostream wins! It turns out that this internal syncing / flushing is what normally slows down iostream i/o. If we're not mixing stdio and iostream, we can turn it off, and then iostream is fastest. The code: https://gist.github.com/3845568
1,042,277
1,044,237
Literate Coding Vs. std::pair, solutions?
As most programmers I admire and try to follow the principles of Literate programming, but in C++ I routinely find myself using std::pair, for a gazillion common tasks. But std::pair is, IMHO, a vile enemy of literate programming... My point is when I come back to code I've written a day or two ago, and I see manipulations of a std::pair (typically as an iterator) I wonder to myself "what did iter->first and iter->second mean???". I'm guessing others have the same doubts when looking at their std::pair code, so I was wondering, has anyone come up with some good solutions to recover literacy when using std::pair?
How about this: struct MyPair : public std::pair < int, std::string > { const int& keyInt() { return first; } void keyInt( const int& keyInt ) { first = keyInt; } const std::string& valueString() { return second; } void valueString( const std::string& valueString ) { second = valueString; } }; It's a bit verbose, however using this in your code might make things a little easier to read, eg: std::vector < MyPair > listPairs; std::vector < MyPair >::iterator iterPair( listPairs.begin() ); if ( iterPair->keyInt() == 123 ) iterPair->valueString( "hello" ); Other than this, I can't see any silver bullet that's going to make things much clearer.
1,042,281
1,042,329
c++ for loop temporary variable use
Which of the following is better and why? (Particular to c++) a. int i(0), iMax(vec.length());//vec is a container, say std::vector for(;i < iMax; ++i) { //loop body } b. for( int i(0);i < vec.length(); ++i) { //loop body } I have seen advice for (a) because of the call to length function. This is bothering me. Doesn't any modern compiler do the optimization of (b) to be similar to (a)?
Example (b) has a different meaning to example (a), and the compiler must interpret it as you write it. If, (for some made-up reason that I can't think of), I wrote code to do this: for( int i(0);i < vec.length(); ++i) { if(i%4 == 0) vec.push_back(Widget()); } I really would not have wanted the compiler to optimise out each call to vec.length(), because I would get different results.
1,042,392
1,042,397
<operator missing when iterating through c++ map
The following code does not want to compile. See the included error message. Code: #include <map> #include <vector> #include <iostream> class MapHolder { public: std::map<std::vector<std::string>,MapHolder> m_map; void walk_through_map() { std::map<std::vector<std::string>,MapHolder>::iterator it; for(it = m_map.begin(); it < m_map.end(); ++it) { it->second.print(); } } void print() { std::cout << "hey" << std::endl; } }; int main(int argc, char *argv[]) { MapHolder m; m.walk_through_map(); } Error: $ g++ test.cc -O test test.cc: In member function 'void MapHolder::walk_through_map()': test.cc:12: error: no match for 'operator<' in 'it < ((MapHolder*)this)->MapHolder::m_map.std::map<_Key, _Tp, _Compare, _Alloc>::end [with _Key = std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, _Tp = MapHolder, _Compare = std::less<std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, _Alloc = std::allocator<std::pair<const std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, MapHolder> >]()' I used this type of map and iterating process multiple times before. What's the problem here? How can it be solved. (The code looks meaningless, but this is a reduced sample which is still supposed to work)
Use != instead of < in iterator comparison.
1,042,415
1,066,246
Windows XP Style: Why do we get dark grey background on static text widgets?
We're writing Windows desktop apps using C++ and Win32. Our dialog boxes have an ugly appearance with "Windows XP style": the background to the static text is grey. Where the dialog box background is also grey, this is not a problem, but inside a tab control, where the background is white, the grey background to the text is very noticeable. In the past we have done a lot of our own drawing of controls, but these days we are trying to use the standard look'n'feel as much as possible, and to avoid overriding standard behaviour as much as possible. We are using the Win32 API, which is getting a bit dated, but I think the problem occurs even with ATL. We are creating a DIALOGTEMPLATE. The text is in a "static" control (0x0082). The only flag we set for the style is "SS_LEFT". The text control is inside a tab control: "SysTabControl32" with only one flag: WS_CLIPSIBLINGS set on it. I've experimented with SS_WHITERECT and WS_EX_TRANSPARENT and other settings, to no avail. All of this gets drawn with the standard Windows dialog box message handler. My main question is "what are we doing wrong?" rather than "how can I work around it?", although I'll settle for the latter if no-one can help me with the first. Any ideas?
We're not overriding the WM_CTLCOLORSTATIC message. There's no occurrence of this string in our source code and nothing like it in our message handlers. We've worked around this problem by overriding the WM_DRAWITEM message for tab controls to paint their contents with the grey background (standard for dialog boxes without tab controls) rather than the white background (standard for the contents of tab controls). brush = CreateSolidBrush(GetSysColor(COLOR_MENU)); FillRect(lpdis->hDC, &lpdis->rcItem, brush); SetBkColor(lpdis->hDC, GetSysColor(COLOR_MENU)); wtext = ToWideStrdup(c->u.tabcontrol.Tabs[lpdis->itemID].name); rect = lpdis->rcItem; rect.top += DlgMarginY - 1; rect.bottom += DlgMarginY; DrawTextW(lpdis->hDC, wtext, -1, &rect, DT_CENTER | DT_VCENTER); free(wtext); DeleteObject(brush); This is obviously a workaround, not a proper answer to my question. Incidentally, we initialise the "common controls", of which I believe the tab control is one, using code like this...I don't suppose this is related to the issue? #pragma comment(linker, "/manifestdependency:\"type='win32' " \ "name='Microsoft.Windows.Common-Controls' " \ "version='6.0.0.0' " \ "processorArchitecture='*' " \ "publicKeyToken='6595b64144ccf1df' " \ "language='*'\"") ... hCommCtrl = GetModuleHandle("comctl32.dll");` if (hCommCtrl) { ptrInit = (TfcInit_fn) GetProcAddress(hCommCtrl, "InitCommonControlsEx"); if (ptrInit) { data.dwSize = sizeof(INITCOMMONCONTROLSEX); data.dwICC = ctrlClass; if (ptrInit(&data) ) gCommCtrlsInitialized |= ICC_TAB_CLASSES | ICC_BAR_CLASSES; } }
1,042,507
1,042,523
Finding smallest value in an array most efficiently
There are N values in the array, and one of them is the smallest value. How can I find the smallest value most efficiently?
If they are unsorted, you can't do much but look at each one, which is O(N), and when you're done you'll know the minimum. Pseudo-code: small = <biggest value> // such as std::numerical_limits<int>::max for each element in array: if (element < small) small = element A better way reminded by Ben to me was to just initialize small with the first element: small = element[0] for each element in array, starting from 1 (not 0): if (element < small) small = element The above is wrapped in the algorithm header as std::min_element. If you can keep your array sorted as items are added, then finding it will be O(1), since you can keep the smallest at front. That's as good as it gets with arrays.
1,042,855
1,448,859
Using Boost to read and write XML files
Is there any good way (and a simple way too) using Boost to read and write XML files? I can't seem to find any simple sample to read XML files using Boost. Can you point me a simple sample that uses Boost for reading and writing XML files? If not Boost, is there any good and simple library to read and write XML files that you can recommend? (it must be a C++ library)
You should Try pugixml Light-weight, simple and fast XML parser for C++ The nicest thing about pugixml is the XPath support, which TinyXML and RapidXML lack. Quoting RapidXML's author "I would like to thank Arseny Kapoulkine for his work on pugixml, which was an inspiration for this project" and "5% - 30% faster than pugixml, the fastest XML parser I know of" He had tested against version 0.3 of pugixml, which has reached recently version 0.42. Here is an excerpt from pugixml documentation: The main features are: low memory consumption and fragmentation (the win over pugxml is ~1.3 times, TinyXML - ~2.5 times, Xerces (DOM) - ~4.3 times 1). Exact numbers can be seen in Comparison with existing parsers section. extremely high parsing speed (the win over pugxml is ~6 times, TinyXML - ~10 times, Xerces-DOM - ~17.6 times 1 extremely high parsing speed (well, I'm repeating myself, but it's so fast, that it outperforms Expat by 2.8 times on test XML) 2 more or less standard-conformant (it will parse any standard-compliant file correctly, with the exception of DTD related issues) pretty much error-ignorant (it will not choke on something like You & Me, like expat will; it will parse files with data in wrong encoding; and so on) clean interface (a heavily refactored pugxml's one) more or less Unicode-aware (actually, it assumes UTF-8 encoding of the input data, though it will readily work with ANSI - no UTF-16 for now (see Future work), with helper conversion functions (UTF-8 <-> UTF-16/32 (whatever is the default for std::wstring & wchar_t)) fully standard compliant C++ code (approved by Comeau strict mode); the library is multiplatform (see reference for platforms list) high flexibility. You can control many aspects of file parsing and DOM tree building via parsing options. Okay, you might ask - what's the catch? Everything is so cute - it's small, fast, robust, clean solution for parsing XML. What is missing? Ok, we are fair developers - so here is a misfeature list: memory consumption. It beats every DOM-based parser that I know of - but when SAX parser comes, there is no chance. You can't process a 2 Gb XML file with less than 4 Gb of memory - and do it fast. Though pugixml behaves better, than all other DOM-based parser, so if you're stuck with DOM, it's not a problem. memory consumption. Ok, I'm repeating myself. Again. When other parsers will allow you to provide XML file in a constant storage (or even as a memory mapped area), pugixml will not. So you'll have to copy the entire data into a non-constant storage. Moreover, it should persist during the parser's lifetime (the reasons for that and more about lifetimes is written below). Again, if you're ok with DOM - it should not be a problem, because the overall memory consumption is less (well, though you'll need a contiguous chunk of memory, which can be a problem). lack of validation, DTD processing, XML namespaces, proper handling of encoding. If you need those - go take MSXML or XercesC or anything like that.
1,042,940
1,043,053
writing directly to std::string internal buffers
I was looking for a way to stuff some data into a string across a DLL boundary. Because we use different compilers, all our dll interfaces are simple char*. Is there a correct way to pass a pointer into the dll function such that it is able to fill the string buffer directly? string stringToFillIn(100, '\0'); FunctionInDLL( stringToFillIn.c_str(), stringToFillIn.size() ); // definitely WRONG! FunctionInDLL( const_cast<char*>(stringToFillIn.data()), stringToFillIn.size() ); // WRONG? FunctionInDLL( &stringToFillIn[0], stringToFillIn.size() ); // WRONG? stringToFillIn.resize( strlen( stringToFillIn.c_str() ) ); The one that looks most promising is &stringToFillIn[0] but is that a correct way to do this, given that you'd think that string::data() == &string[0]? It seems inconsistent. Or is it better to swallow an extra allocation and avoid the question: vector<char> vectorToFillIn(100); FunctionInDLL( &vectorToFillIn[0], vectorToFillIn.size() ); string dllGaveUs( &vectorToFillIn[0] );
I'm not sure the standard guarantees that the data in a std::string is stored as a char*. The most portable way I can think of is to use a std::vector, which is guaranteed to store its data in a continuous chunk of memory: std::vector<char> buffer(100); FunctionInDLL(&buffer[0], buffer.size()); std::string stringToFillIn(&buffer[0]); This will of course require the data to be copied twice, which is a bit inefficient.
1,043,034
1,043,107
What does void mean in C, C++, and C#?
Looking to get the fundamentals on where the term "void" comes from, and why it is called void. The intention of the question is to assist someone who has no C experience, and is suddenly looking at a C-based codebase.
Basically it means "nothing" or "no type" There are 3 basic ways that void is used: Function argument: int myFunc(void) -- the function takes nothing. Function return value: void myFunc(int) -- the function returns nothing Generic data pointer: void* data -- 'data' is a pointer to data of unknown type, and cannot be dereferenced Note: the void in a function argument is optional in C++, so int myFunc() is exactly the same as int myFunc(void), and it is left out completely in C#. It is always required for a return value.
1,043,114
1,043,243
How to buffer output from a .net BackgroundWorker?
I have a stream of data coming in from an external source which I currently collect in a BackgroundWorker. Each time it gets another chunk of data, it presents that data to a GUI using a ReportProgress() call. I get the impression that the ProgressChanged function is just a synchronisation mechanism though so when my worker thread calls that, both threads are locked while the GUI thread processes the change. So I think the problem is that while the background thread is updating the GUI, it can't receive any data which means we lose a few packets. Is that right or is my packet dropping more likely coming frorm elsewhere? If that is the cause, then would adding a second thread to do the GUI updating be a reasonable solution or are there better / more thorough ways of solving these problems which I ought to delve into? Any thoughts and suggestions would be very welcome.
The worker thread just sends an async message to the gui thread, which will result in an event firing in the GUI. It shouldn't halt your background thread.(and that shouldn't matter anyway. Your GUI program could halt for a long time if the user decided to start another program, etc.) You don't talk about what kind of stream you're using. So unless you're receiving UDP datagrams, which are unreliable anyway, there should be no loss of data here. A stream is continuous .
1,043,402
1,043,424
Why does this code crash at the places mentioned?
Can you please elaborate why this code crashes at the places mentioned? I am a bit stumped on this. I guess that it has got something to do with sizeof(int) but I am not so sure. Can anybody explain? class Base { public: virtual void SomeFunction() { printf("test base\n"); } int m_j; }; class Derived : public Base { public: void SomeFunction() { printf("test derive\n"); } private: int m_i; }; void MyWonderfulCode(Base baseArray[]) { baseArray[0].SomeFunction(); //Works fine baseArray[1].SomeFunction(); //Crashes because of invalid vfptr baseArray[2].SomeFunction(); //Crashes because of invalid vfptr baseArray[3].SomeFunction(); //Works fine baseArray[4].SomeFunction(); //Crashes because of invalid vfptr baseArray[5].SomeFunction(); //Crashes because of invalid vfptr baseArray[6].SomeFunction(); //Works fine baseArray[7].SomeFunction(); //Crashes because of invalid vfptr baseArray[8].SomeFunction(); //Crashes because of invalid vfptr baseArray[9].SomeFunction(); //Works fine } int _tmain(int argc, TCHAR* argv[]) { Derived derivedArray[10]; MyWonderfulCode(derivedArray); return 0; }
Quote from this FAQ: Is array of derived same as as array of base? Derived is larger than Base, the pointer arithmetic done with 2nd object baseArray is incorrect: the compiler uses sizeof(Base) when computing the address for 2nd object, yet the array is an array of Derived, which means the address computed (and the subsequent invocation of member function f()) isn’t even at the beginning of any object! It’s smack in the middle of a Derived object.
1,043,670
1,043,788
Do you know which library Firefox 3 uses for the "download completed" info?
It's the window that shows up when you set showAlertOnComplete = true. about:config browser.download.manager.showAlertOnComplete = true I want to add notification messages in my applications and I need to find a good open source library for that task.
There are a few ways of doing notifications. In terms of open source libraries, there are a number of system-wide notification schemes, such as Snarl (Windows), Growl (Mac) or Mumbles (Linux). If you to work only with what is already on the platform, there are some related questions on SO around the Windows API for notifications: Notification Library for Windows Notification API for windows "Speech bubble" notifications
1,043,766
1,043,834
Convert BYTE buffer (0-255) to float buffer (0.0-1.0)
How can I convert a BYTE buffer (from 0 to 255) to a float buffer (from 0.0 to 1.0)? Of course there should be a relation between the two values, eg: 0 in byte buffer will be .0.f in float buffer, 128 in byte buffer will be .5f in float buffer, 255 in byte buffer will be 1.f in float buffer. Actually this is the code that I have: for (int y=0;y<height;y++) { for (int x=0;x<width;x++) { float* floatpixel = floatbuffer + (y * width + x) * 4; BYTE* bytepixel = (bytebuffer + (y * width + x) * 4); floatpixel[0] = bytepixel[0]/255.f; floatpixel[1] = bytepixel[1]/255.f; floatpixel[2] = bytepixel[2]/255.f; floatpixel[3] = 1.0f; // A } } This runs very slow. A friend of mine suggested me to use a conversion table, but I wanted to know if someone else can give me another approach.
Whether you choose to use a lookup table or not, your code is doing a lot of work each loop iteration that it really does not need to - likely enough to overshadow the cost of the convert and multiply. Declare your pointers restrict, and pointers you only read from const. Multiply by 1/255th instead of dividing by 255. Don't calculate the pointers in each iteration of the inner loop, just calculate initial values and increment them. Unroll the inner loop a few times. Use vector SIMD operations if your target supports it. Don't increment and compare with maximum, decrement and compare with zero instead. Something like float* restrict floatpixel = floatbuffer; BYTE const* restrict bytepixel = bytebuffer; for( int size = width*height; size > 0; --size ) { floatpixel[0] = bytepixel[0]*(1.f/255.f); floatpixel[1] = bytepixel[1]*(1.f/255.f); floatpixel[2] = bytepixel[2]*(1.f/255.f); floatpixel[3] = 1.0f; // A floatpixel += 4; bytepixel += 4; } would be a start.
1,043,825
1,044,677
Process name change at runtime (C++)
Is it possible to change the name(the one that apears under 'processes' in Task Manager) of a process at runtime in win32? I want the program to be able to change it's own name, not other program's. Help would be appreciated, preferably in C++. And to dispel any thoughts of viruses, no this isn't a virus, yes I know what I'm doing, it's for my own use.
I know you're asking for Win32, but under most *nixes, this can be accomplished by just changing argv[0]
1,044,088
1,044,133
How to split the strings in vc++?
I have a string "stack+ovrflow*newyork;" i have to split this stack,overflow,newyork any idea??
First and foremost if available, I would always use boost::tokenizer for this kind of task (see and upvote the great answers below) Without access to boost, you have a couple of options: You can use C++ std::strings and parse them using a stringstream and getline (safest way) std::string str = "stack+overflow*newyork;"; std::istringstream stream(str); std::string tok1; std::string tok2; std::string tok3; std::getline(stream, tok1, '+'); std::getline(stream, tok2, '*'); std::getline(stream, tok3, ';'); std::cout << tok1 << "," << tok2 << "," << tok3 << std::endl Or you can use one of the strtok family of functions (see Naveen's answer for the unicode agnostic version; see xtofls comments below for warnings about thread safety), if you are comfortable with char pointers char str[30]; strncpy(str, "stack+overflow*newyork;", 30); // point to the delimeters char* result1 = strtok(str, "+"); char* result2 = strtok(str, "*"); char* result3 = strtok(str, ";"); // replace these with commas if (result1 != NULL) { *result1 = ','; } if (result2 != NULL) { *result2 = ','; } // output the result printf(str);
1,044,103
1,044,296
DebugBreak not breaking
I'm writing a class in C++ that I cannot debug by using F5. The code will run from another "service" that will invoke it. In the past I've used __debugbreak() and when I got a window telling me that an exception was thrown selected to debug it. Recently I've updated to windows 7 and it kept working for a while. Today when I've tried to debug a piece of my code instead of shown the regular dialog that tells me that VSTestHost has stopped working and enable me to to debug the application I got a different dialog suggesting I send the data to microsoft for analysis. Does anyone knows how can I fix this issue so I'll be able to debug my code?
Finally I found the cause of the issue. It's a Vista/Win7 cause: Open The Action center control Goto Action Center settings Goto Problem Reporting Settings Choose "Each time a problem occurs, ask me before checking for solution" Although this is more of IT solution/question I've been plagued with this problem all day and wanted to share the solution with other developers who encounter this problem.
1,044,313
1,124,601
How to use DSP to speed-up a code on OMAP?
I'm working on a video codec for OMAP3430. I already have code written in C++, and I try to modify/port certain parts of it to take advantage of the DSP (the SDK (OMAP ZOOM3430 SDK) I have has an additional DSP). I tried to port a small for loop which is running over a very small amount of data (~250 bytes), but about 2M times on different data. But the overload from the communication between CPU and DSP is much more than the gain (if I have any). I assume this task is much like optimizing a code for the GPU's in normal computers. My question is porting what kind of parts would be beneficial? How do GPU programmers take care of such tasks? edit: GPP application allocates a buffer of size 0x1000 bytes. GPP application invokes DSPProcessor_ReserveMemory to reserve a DSP virtual address space for each allocated buffer using a size that is 4K greater than the allocated buffer to account for automatic page alignment. The total reservation size must also be aligned along a 4K page boundary. GPP application invokes DSPProcessor_Map to map each allocated buffer to the DSP virtual address spaces reserved in the previous step. GPP application prepares a message to notify the DSP execute phase of the base address of virtual address space, which have been mapped to a buffer allocated on the GPP. GPP application uses DSPNode_PutMessage to send the message to the DSP. GPP invokes memcpy to copy the data to be processed into the shared memory. GPP application invokes DSPProcessor_FlushMemory to ensure that the data cache has been flushed. GPP application prepares a message to notify the DSP execute phase that it has finished writing to the buffer and the DSP may now access the buffer. The message also contains the amount of data written to the buffer so that the DSP will know just how much data to copy. The GPP uses DSPNode_PutMessage to send the message to the DSP and then invokes DSPNode_GetMessage to wait to hear a message back from the DSP. After these the execution of DSP program starts, and DSP notifies the GPP with a message when it finishes the processing. Just to try I don't put any processing inside the DSP program. I just send a "processing finished" message back to the GPP. And this still consumes a lot of time. Could that be because of the internal/external memory usage, or is it merely because of the communication overload?
From the measurements I did, one messaging cycle between CPU and DSP takes about 160us. I don't know whether this is because of the kernel I use, or the bridge driver; but this is a very long time for a simple back & forth messaging. It seems that it is only reasonable to port an algorithm to DSP if the total computational load is comparable to the time required for messaging; and if the algorithm is suitable for simultaneous computing on CPU and DSP.
1,044,378
1,044,418
What is a good project / way for an out of practice C++ developer to get back into it?
Like many people here, I started my programming experience with the good ol' green screen BASIC that you get when you booted an Apple II without a disk. I taught myself C++ in my teens, and even took a class on it in college, but as soon as I discovered .NET and C#, I dropped C++ like a bad habit. Now, (many) years later, I'm interested in getting back into C++ development - thank the iPhone for that - and I have to admit, I feel a little daunted. Having to deal with pointers, ATL, macros, etc. seems a bit overwhelming at times when you've been in managed .NET land for a long time. What are some good resources or weekend type projects I could do to ease me back into C++? I'm not interested in debating the relative merits between platforms, stacks, but I would be interested in hearing about objective comparisons between different development platforms, although keep in mind I'm a Windows guy. If anyone wants to change the tags around, feel free - I wasn't quite sure how to tag this. TIA!
Try Euler Project Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.
1,044,448
1,046,317
Why does boost::variant not provide operator !=
Given two identical boost::variant instances a and b, the expression ( a == b ) is permitted. However ( a != b ) seems to be undefined. Why is this?
I think it's just not added to the library. The Boost.Operators won't really help, because either variant would have been derived from boost::operator::equality_comparable. David Pierre is right to say you can use that, but your response is correct too, that the new operator!= won't be found by ADL, so you'll need a using operator. I'd ask this on the boost-users mailing list. Edit from @AFoglia's comment: Seven months later, and I'm studying Boost.Variant, and I stumble over this better explanation of the omission lists. http://boost.org/Archives/boost/2006/06/105895.php operator== calls operator== for the actual class currently in the variant. Likewise calling operator!= should also call operator!= of the class. (Because, theoretically, a class can be defined so a!=b is not the same as !(a==b).) So that would add another requirement that the classes in the variant have an operator!=. (There is a debate over whether you can make this assumption in the mailing list thread.)
1,044,517
1,445,821
Unpacking an executable from within a library in C/C++
I am developing a library that uses one or more helper executable in the course of doing business. My current implementation requires that the user have the helper executable installed on the system in a known location. For the library to function properly the helper app must be in the correct location and be the correct version. I would like to removed the requirement that the system be configured in the above manner. Is there a way to bundle the helper executable in the library such that it could be unpacked at runtime, installed in a temporary directory, and used for the duration of one run? At the end of the run the temporary executable could be removed. I have considered automatically generating an file containing an unsigned char array that contains the text of the executable. This would be done at compile time as part of the build process. At runtime this string would be written to a file thus creating the executable. Would it be possible to do such a task without writing the executable to a disk (perhaps some sort of RAM disk)? I could envision certain virus scanners and other security software objecting to such an operation. Are there other concerns I should be worried about? The library is being developed in C/C++ for cross platform use on Windows and Linux.
You can use xxd to convert a binary file to a C header file. $ echo -en "\001\002\005" > x.binary $ xxd -i x.binary unsigned char x_binary[] = { 0x01, 0x02, 0x05 }; unsigned int x_binary_len = 3; xxd is pretty standard on *nix systems, and it's available on Windows with Cygwin or MinGW, or Vim includes it in the standard installer as well. This is an extremely cross-platform way to include binary data into compiled code. Another approach is to use objcopy to append data on to the end of an executable -- IIRC you can obtain objcopy and use it for PEs on Windows. One approach I like a little better than that is to just append raw data straight onto the end of your executable file. In the executable, you seek to the end of the file, and read in a number, indicating the size of the attached binary data. Then you seek backwards that many bytes, and fread that data and copy it out to the filesystem, where you could treat it as an executable file. This is incidentally the way that many, if not all, self-extracting executables are created. If you append the binary data, it works with both Windows PE files and *nix ELF files -- neither of them read past the "limit" of the executable. Of course, if you need to append multiple files, you can either append a tar/zip file to your exe, or you'll need a slightly more advance data structure to read what's been appended. You'll also probably want to UPX your executables before you append them. You might also be interested in the LZO library, which is reportedly one of the fastest-decompressing compression libraries. They have a MiniLZO library that you can use for a very lightweight decompressor. However, the LZO libraries are GPL licensed, so that might mean you can't include it in your source code unless your code is GPLed as well. On the other hand, there are commercial licenses available.
1,044,665
1,044,683
BSD Socket issue: inet_ntop returning "0.0.0.0"
I'm trying to get the IP of the machine a socket I've bound is listening on. The port number printed works fine, but the address is "0.0.0.0". Here's the relevant code. res has been passed to getaddrinfo and getsockname before getting to this code. char ip[INET_ADDRSTRLEN]; struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr; void* addr = &(ipv4->sin_addr); inet_ntop(res->ai_family, addr, ip, sizeof ip); std::cout << "SERVER_ADDRESS " << ip << std::endl; std::cout << "SERVER_PORT " << ipv4->sin_port << std::endl; What could be wrong?
An address of 0.0.0.0 means that the socket is listening on all addresses. A specific address like 127.0.0.1 would mean that the server is just listening on that address, but not on any other ones.
1,044,703
1,044,732
How do you pass boost::bind objects to a function?
I have a one-dimensional function minimizer. Right now I'm passing it function pointers. However many functions have multiple parameters, some of which are held fixed. I have implemented this using functors like so template <class T> minimize(T &f) { } Functor f(param1, param2); minimize<Functor>(f); However the functor definition has lots of crud. Boost::bind looks cleaner. So that I could do: minimize(boost:bind(f,_1,param1,param2)) However I'm not clear what my minimize declaration should like like using boost::bind. What type of object is boost::bind? Is there an easy pattern for this that avoids the boilerplate of functors but allows multiple parameter binding?
You can just use boost::function. I think boost::bind does have its own return type, but that is compatible with boost::function. Typical use is to make a typedef for the function: typedef boost::function<bool(std::string)> MyTestFunction; and then you can pass any compatible function with boost::bind: bool SomeFunction(int i, std::string s) { return true; } MyTestFunction f = boost::bind(SomeFunction, 42, _1); f("and then call it."); I hope that is what you want. It also works with methods by passing the this pointer for the call as second parameter to boost::bind.
1,044,968
1,052,817
Does Visual C++ 2010 Beta 1 have unique_ptr, and if not, where can I get a C++0x reference implementation?
I do know: It wasn't in the CTP It's slated to be in the final release I can't find it in Beta 1 I want to play with it
It's in the same header as shared_ptr : #include <memory>
1,045,232
1,436,004
Automating RegisterClass in C++ Builder VCL
We use C++ Builder for an application whose forms are kept external to the EXE in a database. Application code is C++ This allows us to modify the forms and form/actions without a re-compile. Here is a snippet of code that gets the job done of loading a form. RegisterClass(__classid(TButton)); RegisterClass(__classid(TEdit)); RegisterClass(__classid(TRadioGroup)); RegisterClass(__classid(TGroupBox)); RegisterClass(__classid(TCheckBox)); RegisterClass(__classid(TRadioButton)); RegisterClass(__classid(TTimer)); RegisterClass(__classid(TListBox)); RegisterClass(__classid(TComboBox)); RegisterClass(__classid(TBitBtn)); RegisterClass(__classid(TSpeedButton)); RegisterClass(__classid(TMaskEdit)); RegisterClass(__classid(TProgressBar)); ms = new TMemoryStream; ms2 = new TMemoryStream; // Loading Module into Memory Stream ms->Position = 0; ms->LoadFromFile(Filename->Text); ms->Position = 0; pModule = new TForm(this); // Reading Module Definition if( !Inputisbin->Checked ) { ms2->Position = 0; ObjectTextToBinary(ms, ms2); ms2->Position = 0; ms2->ReadComponent(pModule); } else ms->ReadComponent(pModule); Log->Lines->Add("Displaying Module"); pModule->Show(); I'm curious to know if there are any built-in functions I can call to register all classes referenced. I suppose it's possible to scan the memory stream or file for all objects myself and call RegisterClass for each but was hoping someone knew of function that already did this. As such, not all forms use all these classes either so it would be nice to only register those that are actually inherited.
The approach you have here is exactly right, in my opinion. I took the same approach years ago using Delphi2, although I had to implement my own class factory and ObjectToText/TextToObject functions as ReadComponent() never featured in the VCL. On your second point of only registering required classes, surely they only need registering once? And the overhead of determining if a class needs to be registered, will outweigh the cost of registering everything. Again, I would leave it as it is.
1,045,530
1,045,567
How to set TCP_NODELAY on BSD socket on Solaris?
I am trying to turn off Nagle's algorithm for a BSD socket using: setsockopt(newSock, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof flag); but the compiler claims TCP_NODELAY hasn't been seen before: error: `TCP_NODELAY' undeclared (first use this function) This is the full list of includes for the file this is in: #include <arpa/inet.h> #include <fcntl.h> #include <iostream> #include <netdb.h> #include <string> #include <sys/socket.h> #include <sys/types.h> using namespace std; I also have the -lnsl and -lsocket linker options, but it just won't compile. Am I missing something? All of this is on a Solaris 8 machine.
Looks like you are missing #include <netinet/tcp.h> - that's where TCP_... defines live.
1,045,675
2,390,777
DirectX post-processing shader
I have a simple application in which I need to let the user select a shader (.fx HLSL or assembly file, possibly with multiple passes, but all and only pixel shader) and preview it. The application runs, the list of shaders comes up, and a button launches the "preview window." From this preview window (which has a DirectX viewport in it), the user selects an image and the shader is run on that image and displayed. Only one frame needs rendered (not real-time). I have a vertex/pixel shader combination set up that takes a quad and renders it to the screen, textured with the chosen image. This works perfectly. I need to then run another effect, purely pixel shader, on the output from the first effect, and display the final image (post-processed) to the screen. This doesn't work at all. I've tried for the past few days to get it working, but for no apparent reason, the identical code blocks used to render each effect only render the first. I can add the second shader file as a second pass in the first shader file and it runs perfectly (although completely defeats my goal of previewing user-created shaders). When I try to use a second effect (which loads and compiles just fine), it does nothing. I've taken the results of the first shader (with GetRenderTargetData) and placed them in a texture & surface (destTex and destSur), then set that texture as the input for the second pass (using dev->SetTexture and later effect->SetTexture("thisframe", destTex)). All calls succeed, effects compile, textures load, quads are drawn, but the effect is not visible. I suspected at first the device (created with software vertex processing) was causing the issue, but that doesn't seem to be the case (I tried with hardware and mixed). Additionally, using both a HAL and REF device (not a problem, since the app isn't realtime anyways), that second shader isn't visible. Everything is written in C++ for Direct3D 9.
Try clearing the depth-stencil buffer after each time you render the quad.
1,045,925
1,114,424
Transparent windows with Linux
I am trying to find a cross linux distribution solution to the problem of making a program have transparent windows. I now there is some methods out there, that take screen shots of the windows underneath and then print them as the background of the image. I would prefer not to uses that method because it likely that i would have video running in the background of the program. But if any one knows of a good way to make this happen i would still be please to here about it. I have tried to implement a method I found at : Changing X11 Windows Properties I couldn't get any change to happen, though I am not sure if Compiz was working correctly. Any help would be greatly appreciated.
You can take a look at the code of the X terminal emulators, KTerm for KDE or Gnome Terminal for gnome (depending of your target platform). I think these are the best examples of apps that implement transparency. I think that you can even find in that code solutions for getting transparency when compiz is not available.
1,045,985
1,046,073
What is the best practice regarding const instance methods?
In light of the accepted answer pointing out that returning a non-const reference to a member from a const instance method won't compile (without a cast or making the member variable mutable), the question has become more a general best-practices discussion of const instance methods. For posterity, here's the original question: If I have an object with a getter that returns a non-const reference, for example: SomeObject& SomeOtherObject::foo(){ return someObjectInstance; } Should this be made const? Obviously the call itself doesn't modify the object, but the caller could then modify someObjectInstance which would mutate my instance of SomeOtherObject. I guess my question really boils down to "what exactly does const on a member method mean?" Is it A) the call itself won't mutate the object or B) no mutation of the object can occur during the call, or as a result of the returned references/pointers (with a caveat for people who do const_casts). As an aside, I'm currently adding this where I need const calls. const SomeObject& SomeOtherObject::constFoo() const{ return someObjectInstance; } to be on the safe side, since I'm reluctant to do SomeObject& SomeOtherObject::foo() const{ return someObjectInstance; } even though it would make my life easier in some places.
const (when applied to a member function) is mainly useful as a means of self documenation. It is a contract with the calling code that this function will not modify the external state (i.e. have no observable side effects). The compilier achieves this by making all members effectively const while inside a const member function It is not uncommon to see code like: const SomeObject& SomeOtherObject::constFoo() const; SomeObject& SomeOtherObject::constFoo(); The following won't compile (MSVC 9 and gcc 3.4.4) SomeObject& SomeOtherObject::constFoo() const{ return someObjectInstance; } You could hack around the above error by casting away the const: SomeObject& SomeOtherObject::constFoo() const{ return (SomeObject&)someObjectInstance; } but this of course breaks the contract with the users of your code that you won't be changing the SomeOtherObject instance. You could also make someObjectInstance mutable to be able to avoid the cast, but in the end it really isn't any better.
1,046,068
1,046,099
Would one have to know the machine architecture to write code?
Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit? IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???
correct for most circumstances The runtime/language/compiler will abstract those details unless you are dealing directly with word sizes or binary at a low level. Even byteorder is abstracted by the NIC/Network stack in the kernel. It is translated for you. When programming sockets in C, you do sometimes have to deal with byte ordering for the network when sending data ... but that doesn't concern 32 or 64 bit differences. When dealing with blobs of binary data, mapping them from one architecture to another (as an overlay to a C struct for example) can cause problems as others have mentioned, but this is why we develop architecture independent protocols based on characters and so on. In-fact things like Java run in a virtual machine that abstracts the machine another step! Knowing a bit about the instruction set of the architecture, and how the syntax is compiled to that can help you understand the platform and write cleaner, tighter code. I know I grimace at some old C code after studying compilers!
1,046,078
1,046,102
Best practices: syncing between threads
Is if almost always required to have thread syncing (i.e. use of mutex, semaphores, critical sections, etc.) when there is cross-thread data accessing, even if it's not required after going through a requirements analysis?
I would always recommended going with the simplest, most straightforward synchronization scheme until analysis shows you should do otherwise - this usually means a few large locks versus many fine-grained locks or lockfree. The issue is that determining if lock-free code is correct is much more difficult than determining if the corresponding code with locks is correct. This creates a large burden on maintainers of your code, and there is a good chance they will get it wrong and introduce bugs. Even if you know that lock-free is safe with how your code is currently used, this could change in the future by people who aren't as aware. Secondly, in many cases, the difference in performance between code with locks and lock-free code is neglible - until you know there is an issue with lock contention, you should not consider lock-free. Even if there are contention problems, lock-free is not necessarily the best solution.
1,046,248
1,055,611
What are some recommended frameworks for manipulating spatial data in C++?
What are some recommended frameworks for manipulating spatial data in C++? I'm looking for a polygon object, point object, and some operations like union, intersection, distance, and area. I need to enter coordinates in WGS84 (lon,lat) and get area in square km. I would prefer a free/open source framework, but am open to suggestions. Edit: Unfortunately I need a non-GPL solution. LGPL is alright.
GEOS is an open source (LGPL) C++ geometry / topology engine. Might suit you? Useful places to look for this stuff are this useful article on the O'Reilly website and also OSGeo which is a collaboration to support open source geospatial stuff.
1,046,322
1,046,403
How do I determine a maximum time needed for TCP socket to die due to intermediate network disconnect?
I have a program in C++, using the standard socket API, running on Ubuntu 7.04, that holds open a socket to a server. My system lives behind a router. I want to figure out how long it could take to get a socket error once my program starts sending AFTER the router is cut off from the net. That is, my program may go idle (waiting for the user). The router is disconnected from the internet, and then my program tries to communicate over that socket. Obviously it's not going to know quickly, because TCP is quite adept at keeping a socket alive under adverse network conditions. This causes TCP to retry a lot of times, a lot of ways, before it finally gives up. I need to establish some kind of 'worst case' time that I can give to the QA group (and the customer), so that they can test that my code goes into a proper offline state. (for reference, my program is part of a pay at pump system for gas stations, and the server is the system that authorizes payment transactions. It's entirely possible for the station to be cut off from the net for a variety of reasons, and the customer just wants to know what to expect). EDIT: I wasn't clear. There's no human being waiting on this thing, this is just for a back office notation of system offline. When the auth doesn't come back in 30 seconds, the transaction is over and the people are going off to do other things. EDIT: I've come to the conclusion that the question isn't really answerable in the general case. The number of factors involved in determining how long a TCP connection takes to error out due to a downstream failure is too dependent on the exact equipment and failure for there to be a simple answer.
You should be able to use: http://linux.die.net/man/2/getsockopt with: SO_RCVTIMEO and SO_SNDTIMEO to determine the timeouts involved. This link: http://linux.die.net/man/7/socket talks about more options that may be of interest to you. In my experience, just picking a time is usually a bad idea. Even when it sounds reasonable, arbitrary timeouts usually misbehave in practice. The general result is that the application becomes unusable when the environment falls outside of the norm. Especially for financial transactions, this should be avoided. Perhaps providing a cancel button and some indication that the transaction is taking longer than expected would be a better solution.
1,046,477
1,046,503
Is there any reason to use the 'auto' keyword in C++03?
Note this question was originally posted in 2009, before C++11 was ratified and before the meaning of the auto keyword was drastically changed. The answers provided pertain only to the C++03 meaning of auto -- that being a storage class specified -- and not the C++11 meaning of auto -- that being automatic type deduction. If you are looking for advice about when to use the C++11 auto, this question is not relevant to that question. For the longest time I thought there was no reason to use the static keyword in C, because variables declared outside of block-scope were implicitly global. Then I discovered that declaring a variable as static within block-scope would give it permanent duration, and declaring it outside of block-scope (in program-scope) would give it file-scope (can only be accessed in that compilation unit). So this leaves me with only one keyword that I (maybe) don't yet fully understand: The auto keyword. Is there some other meaning to it other than 'local variable?' Anything it does that isn't implicitly done for you wherever you may want to use it? How does an auto variable behave in program scope? What of a static auto variable in file-scope? Does this keyword have any purpose other than just existing for completeness?
auto is a storage class specifier, static, register and extern too. You can only use one of these four in a declaration. Local variables (without static) have automatic storage duration, which means they live from the start of their definition until the end of their block. Putting auto in front of them is redundant since that is the default anyway. I don't know of any reason to use it in C++. In old C versions that have the implicit int rule, you could use it to declare a variable, like in: int main(void) { auto i = 1; } To make it valid syntax or disambiguate from an assignment expression in case i is in scope. But this doesn't work in C++ anyway (you have to specify a type). Funny enough, the C++ Standard writes: An object declared without a storage-class-specifier at block scope or declared as a function parameter has automatic storage duration by default. [Note: hence, the auto specifier is almost always redundant and not often used; one use of auto is to distinguish a declaration-statement from an expression-statement (6.8) explicitly. — end note] which refers to the following scenario, which could be either a cast of a to int or the declaration of a variable a of type int having redundant parentheses around a. It is always taken to be a declaration, so auto wouldn't add anything useful here, but would for the human, instead. But then again, the human would be better off removing the redundant parentheses around a, I would say: int(a); With the new meaning of auto arriving with C++0x, I would discourage using it with C++03's meaning in code.
1,046,499
1,046,515
How do I call managed .NET code from my un-managed C++ code in Windows and vice versa?
I have a pure C++ application developed using VC 6.0. I would like this application to make use of a library developed in C#. How do I call the methods in the C# library from my native executable? I do not want to convert my un-managed C++ native application to managed code. Similarly, how do I do the reverse? Is PInvoke the only option? I would appreciate any references or pointers for the same.
To call into managed code from unmanaged C++, use ClrCreateManagedInstance, or export your types in your managed assembly as COM visible, and use COM. To call into unmanaged code from managed, use COM or P/Invoke.
1,046,547
1,046,603
Is there an automatic source code formatter that nicely wraps lines of C/C++?
I use astyle to format my code most of the time, and I love it, but one annoyance is that it can't specify at least a "hint" for max line length. If you have a line of code like: this->mButtonCancel->setLeftClickProc(boost::bind(&FileListDialog::cancelLeftClick, this)); I would like a source code formatter to be able to wrap it even moderately intelligently: this->mButtonCancel->setLeftClickProc( boost::bind(&FileListDialog::cancelLeftClick, this)); ...is probably how I would format that line of code. For long argument lists, I would probably prefer to align on the open parenthesis, but clearly that won't work in this situation. Either way, astyle doesn't support doing anything with long lines that don't contain multiple statements. Does anyone know of a tool that does?
GNU Indent has support for breaking long lines. http://www.gnu.org/software/indent/manual/indent.html#SEC12
1,046,660
1,046,710
How to build a Visual Studio 9.0 solution from Cygwin and get build output?
I am trying to set up an automated build system on Windows using Cygwin. Among other things, it needs to be able to build several Visual C++ solutions. I have a script which sets up the environment variables needed for devenv, and if I type 'devenv' in bash it brings up the Visual Studio IDE. No problems so far. I am also able to build a solution from cygwin's bash prompt by typing $ devenv mysolution.sln /build Debug The problem is that it is not showing me the build output. In fact, it does not even tell me whether or not the build succeeded. The command simply finishes, and I get back the prompt. Then I can go into the output directory, and check whether or not the executable was created, but for a build system I want to be able to grep for errors. What am I doing wrong? I can see the debug output when I run devenv in the windows shell, but not in cygwin. Where is it being sent, and how do I get it back?
Will cygwin find and run .com files? There are 2 devenv executables, one is devenv.com which is a console mode application that handles stdin, stdout and stderr proxying for the other executable, devenv.exe, which is a GUI mode application. If devenv.exe is what cygwin is loading then there will be no stdin/stdout stuff. If devenv.com is being loaded, it should launch devenv.exe while proxying the stdout stuff to the console. Maybe if you explicitly specify that devenv.com should be run?
1,046,714
1,049,643
What is a good random number generator for a game?
What is a good random number generator to use for a game in C++? My considerations are: Lots of random numbers are needed, so speed is good. Players will always complain about random numbers, but I'd like to be able to point them to a reference that explains that I really did my job. Since this is a commercial project which I don't have much time for, it would be nice if the algorithm either a) was relatively easy to implement or b) had a good non-GPL implementation available. I'm already using rand() in quite a lot of places, so any other generator had better be good to justify all the changes it would require. I don't know much about this subject, so the only alternative I could come up with is the Mersenne Twister; does it satisfy all these requirements? Is there anything else that's better? Mersenne Twister seems to be the consensus choice. But what about point #4? Is it really that much better than rand()? Let me be a little clearer on point 2: There is no way for players to cheat by knowing the random numbers. Period. I want it random enough that people (at least those who understand randomness) can't complain about it, but I'm not worried about predictions. That's why I put speed as the top consideration.
George Marsaglia has developed some of the best and fastest RNGs currently available Multiply-with-carry being a notable one for a uniform distribution. === Update 2018-09-12 === For my own work I'm now using Xoshiro256**, which is a sort of evolution/update on Marsaglia's XorShift. === Update 2021-02-23 === In .NET 6 (currently in preview) the implementation of System.Random has been changed to use xoshiro256**, but only for the parameterless constructor. The constructor that takes a seed uses the old PRNG in order to maintain backwards compatibility. For more info see Improve Random (performance, APIs, ...)
1,046,717
1,046,758
Polymorphic member function pointer
I'm trying to write a callback event system in DirectX9. I'm attempting to use method function pointers to trigger events to mouseclicks; but I'm having some problems. My game uses a gamestate manager to manage the rendering. All of my gamestates are derived from a base class AbstractGameState. I have a sprite object with this specific method: m_NewGameSprite->OnClick(this, &MainMenuState::StartGame); MainMenuState is the current gamestate that my game is in, and StartGame is a void method part of this class. I'd like to store the function pointer in a variable within my sprite class so that I can execute it when the user clicks. template <typename T> void OnClick(GameState* LinkedState, void (T::*EventPointer)()) { m_LinkedGameState = LinkedState; m_EventPointer = EventPointer; // <- Doesnt compile } I've tried downcasting the pointer, but that didn't really work. My sprite class also contains these two variables void (GameState::*m_EventPointer)(); GameState* m_LinkedGameState; Any help would be appreciated
I don't really know why your assignment is not working, no doubt litb will be along shortly to explain why. Boost.Function is a beautiful, generic, typesafe and standard function object that can be used as a replacement for function pointers in almost all circumstances. I would do this: typedef boost::function0<void> Event; Event m_Event; Note that the event class now encapsulates the state of the function call, including the object you want to call it on. Normally you also use Boost.Bind to create a closure, but you can easily bind to a free function or some other function object as well. void OnClick(Event &event) { m_Event=event; } Call it like this: OnClick(boost::bind(&MainMenuState::StartGame, this)); With this scheme, you don't really need to store the "linked game state" - this is encapsulated in the event object.
1,046,753
1,046,771
help with explicit template especialization
thank you for looking i got this example from my book but i cant understand why the line S<void,int> sv; // uses Template at (2) but S<void,char> e2; //uses (1) when im thinking it would use (2) especialization as well could anyone explain the behavior? btw all the comments in code below are from book author thank you very much! template<typename T> class Types { public: typedef int I; }; template<typename T, typename U = typename Types<T>::I> class S; // (1) template<> class S<void> { // (2) public: void f(); }; template<> class S<char, char> {}; // (3) template<> class S<char, 0>; // ERROR: 0 cannot substitute U int main() { S<int>* pi; // OK: uses (1), no definition needed S<int> e1; // ERROR: uses (1), but no definition available S<void>* pv; // OK: uses (2) S<void,int> sv; // OK: uses (2), definition available S<void,char> e2; // OK: uses (1), definition available S<char,char> e3; // ERROR: uses (3), but no definition available }
Why should it use (2)? (2) is a specialization of S<void, int>. What you have is S<void, char>. The types are different, so the specialization isn't used. Specializations only apply if they match exactly. It's not good enough that "a char can be implicitly promoted to an int". If no specialization exists for S<void, char>, then it will use the general, nonspecialized version.
1,046,801
1,046,867
Why doesn't this C++0x code call the move constructor?
For some reason, the following code never calls Event::Event(Event&& e) Event a; Event b; Event temp; temp = move(a); a = move(b); b = move(temp); why not? Using std::swap calls it once. class Event { public: Event(): myTime(0.0), myNode(NULL) {} Event(fpreal t, Node* n); Event(Event&& other); Event(Event const& other) = delete; ~Event(); bool operator<(Event const& other) const { return myTime < other.myTime; } bool operator>(Event const& other) const { return myTime > other.myTime; } fpreal getTime() const { return myTime; } void setTime(fpreal time) { myTime = time; } Node* getNode() const { return myNode; } private: fpreal myTime; Node* myNode; };
Your code has two potential locations for where one may expect the move constructor to get called (but it doesn't): 1) calling std::move 2) during assignment. Regarding 1), std::move does a simple cast - it does not create an object from a copy - if it did then the move constructor might get invoked by it, but since it does a simple rvalue cast it doesn't get invoked. The definition of std::move is similar to static_cast<Event&&>(temp). Regarding 2), Initialization and assignment are two entirely different operations (even though some forms of initialization use the '=' symbol). Your code does assignment and therefore uses the default assignment operator which is declared to accept a const lvalue reference. Since you never initialize one event object with another, you won't see your move constructor get invoked. If you declared a move assignment operator: Event& operator=(Event&& other), then your current code would invoke it or if you wrote: Event a; Event tmp = move(a); your move constructor, as written, would get invoked.
1,046,876
1,046,882
When is the planned date for C++0x to be released into the wild?
We've been waiting forever to see if it's going to become a full-fledged language, and yet there doesn't seem to be a release of the formal definition. Just committees and discussions and revising. Does anyone know of a planned deadline for C++0x, or are we going to have to start calling it C++1x?
Well the committee is currently very busy working on the next revision - every meeting is prefaced by many papers, that are a good indicator of the effort that is going into the new standard: http://www.open-std.org/jtc1/sc22/wg21/ What is a little concerning (but reassuring in the sense that they will not rush publishing a standard just to assuage the public, yet do sense the urgency involved) is that Stroustrup just put out a paper saying that we need to take a second look at concepts and make sure that they are as simple as can be - and has proposed a reasonable solution. [Edit] For those who are interested, this paper is available at: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2906.pdf. C++0x will be a huge improvement upon C++ in many regards, and while I do not speak for the committee - my hope is that it will happen by late 2010. [Edit] As underscored by one of the commenters, it is worth appreciating that there is significant concern amongst a few committee members that either the quality of the standard or the schedule (late 2010) will have to suffer if concepts are included: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2893.pdf. But whether these concerns will be substantiated is worth being patient about - we will have more information about this once the committee concludes its meeting in Frankfurt this july (the post-meeting mailing can be expected in late-july, early august). Personally, i sense that it would not be a huge loss to get the standard out without concepts (maintain the late 2010 schedule), and then add them as a TR - versus rushing them through even when there is palpable uneasiness amongst the more seasoned committee members (about concepts) - but I will defer to the committee here - while they have never claimed or been described as perfect, the majority of them are far more qualified to make these decisions than I am and deserve some of our confidence if history is any indicator - I would err on the side of trusting their instincts (over mine) assuming there was some reasonable consensus amongst them. For some perspective, and so that one does not despair about these obstacles too much, compare this to what happened within the ecmascript community - Brendan Eich, the creator, had some very different design goals for the next revision of ecmascript (es5) from some of the other similarly talented wizards in the ecmascript community - they had multiple meetings and after much discussion (some of it heated ;) formulated a very very reasonable compromise followed by a frenzy of activity that has resulted in ecmascript 5 (all in the span of 1-2 years, including the conflict) which will be an excellent and pragmatic, yet much more conservative than Eich had initially proposed, revision of javascript. I have similar hopes for C++ (acknowledging that C++ is a much much much larger language - but then much more effort has been put in ;)
1,046,930
1,046,939
I cannot compile using template in C++
I compiled the following cords with g++ #include <iostream> #include <string> using namespace std; template<class T> class Node<const char*>{ private: string x_; Node* next_; public: Node (const char* k, Node* next):next_(next),x_(k){} string data(){return x_;} Node *get_next(){return next_;} }; $ g++ -c node01.cc node01.cc:5: error: ‘Node’ is not a template What's wrong? I'm begginer for c++
You're mixing up declarations and instantiations. When you declare a template, you don't specify a type immediately after its name. Instead, declare it like this: template<class T> class Node { private: const T x_; Node *next_; public: Node (const T& k, Node *next) : x_(k), next_(next) { } const T& data(){return x_;} Node *get_next(){return next_;} }; Your original declaration also confuses string, const char *, and generic types that should be in terms of T. For a template like this, you probably want to let the user define the type of the member (x_). If you explicitly declare it as const char * or string, you're losing genericity by limiting what the user can use for T. Notice that I changed the types of the instance variables, the parameters of the constructor and the return type of data() to be in terms of T, too. When you actually instantiate a variable of the template type, you can provide a concrete type parameter, e.g.: int main(int argc, const char **argv) { Node<char*> *tail = new Node<char*>("tail", NULL); Node<char*> *node = new Node<char*>("node", tail); // do stuff to mynode and mytail } Whenever you write the template name Node outside the template declaration, it's not complete until you provide a value for the parameter T. If you just say Node, the compiler won't know what kind of node you wanted. The above is a little verbose, so you might also simplify it with a typedef when you actually use it: typedef Node<char*> StringNode; int main(int argc, const char **argv) { StringNode *tail = new StringNode("tail", NULL); StringNode *node = new StringNode("node", tail); // do stuff to mynode and mytail } Now you've built a linked list of two nodes. You can print out all the values in the list with something like this: for (StringNode *n = node; n; n = n->get_next()) { cout << n->data() << endl; } If all goes well, this will print out: node tail
1,047,121
1,048,525
How do I generate GUID under Windows Mobile?
Is there a ready-to-use API (C / C++) in Windows Mobile ecosystem that I could use to generate a GUID? I am looking for simple one-shot API to do this. If there is a need to write a whole algorithm or use some extra 3rd-party modules, I will do away without this. Background. To display notification to the user I use SHNotificationAdd, which requires a GUID for it. Examples in MSDN and other sources show that GUID is hard-coded. However, I want to wrap the SHNotification* within a class that blends well within the overall design of my application. MSDN is very shy on details on what SHNOTIFICATIONDATA->clsid represents. The "class" mentioned raise more questions than it answers.
You don't need to generate a GUID for SHNOTIFICATIONDATA. You only set the clsid if you want WM to notify a COM object that implements IshellNotificationCallback interface. Quote from MSDN: When loading up the SHNOTIFICATIONDATA structure, you can specify either the notification class (clsid), the window to receive command choices (hwndSink), or both. If you specify the clsid, your COM component must implement IshellNotificationCallback. If you specify the clsid and an hwndSink, both COM and Window Message-style callbacks will be generated. I've never personally used the COM callback, I always use the windows message callback. It's a lot easier to setup and use and you don't need to generate a GUID.
1,047,152
1,047,156
MSVC precompiled headers: Which files need to #include "stdafx.h"?
Does every file need to #include "stdafx.h" when using precompiled headers? Or do only source files need to include it. EDIT: Also, my precompiled header file #includes a lot of STL headers. But, in my headers, I sometimes have functions that return std::vector or something like that, so I need to #include <vector> anyway. Is this worse than including stdafx.h? I need to include the definitions for my unit testing framework.
Every source file needs to include it before any non-comment line. Headers do not need to include it, as every source file will include it before any other header.
1,047,200
1,047,226
Extract RGB values from a AVFrame (FFMPEG) in C++
I am currently trying to read in video frames by using FFMPEG. The format is PIX_FMT_RGB24; For each frame, the RGB values are all combined together in frame->data[0] (Where frame is of the type AVFrame). How do I extract the individual R, G and B values for each frame? This is for processing the video. I would think it would work the same way as extracting the RGB values from a bitmap too. Thanks!
My guess: int p=x*3+y*frame->linesize[0]; r=frame->data[0][p]; g=frame->data[0][p+1]; b=frame->data[0][p+2]; I might have r, g, and b backwards. And there's a lot of room for speedup.
1,047,203
1,069,813
Best bignum library to solve Project Euler problems in C++?
I am still a student, and I find project Euler very fun. sometimes the question requires calculations that are bigger than primitive types. I know you can implement it but I am too lazy to do this, So I tried few libraries, MAPM :: very good performance, but it provides only big floats, with the possibility to check if it is an integer. very good to accept input, but nasty to provide output, and compiles like magic with Visual C++ 2008 express. bigint :: a small one, but needs a re engineering in many parts. Very simple to use, but very limited power, and very slow compared to others. only big integers. ttmath :: the most beautiful one I have tried until now!, just some files to include and you have unbelievable power/simplicity. Compiles like magic in Visual C++ 2008 express. It is fast, because it provides fixed-length numbers. It is built using Metaprogramming in C++. The only disadvantage I see, is that numbers are not arbitrary in length at run-time, but you can have 1024K numbers when writing code very easily, ttmath::UInt<1024 * 1024> reallyHugeUnsignedInteger; It provides three types: signed, unsigned and float. I tried to compile gmp under VC2008 express, but I failed! I know it is the best, but no where easy to compile for a beginner under VC2008 express, I appreciate also if you point to a tutorial to compile gmp under VC. EDIT :: If you know how to compile gmp using VC 2008, Please explain to me and get the bounty :) EITD :: It seems that I was not using the right terms, So here is the magical GMP for Windows! works with VC 2008 :) MPIR
Here are a couple of links regarding GMP and Visual Studio 2008: GMP Install Help at CodeGuru GMP Compile Guide at The Edge Of Nowhere (this one looks really thorough)
1,047,406
1,047,508
How to find the global function?
I have a function name called setValue, used in many classes. Also, i have a global function by the same name. When i press C-], it goes to arbitrary setValue function. How do i directly jump to the global setValue function? It is really pain to use tnext every time to find if the function global.
When C-] returns multiple matches you can look up the list with :ts Then enter the number to jump to correct definition or dismiss the list. When ctags does not help ... You can search for occurances of setValue and then jump to the one that looks like definition. :vim /setValue/ * <-- greps for setValue in all files You can search only specific files, if you know that it is in header in subdirectory src or headers: :vim /setValue/ src/*.h headers/*.h once it's done do :cope to open a list, you can navigate up/down to select the definition that looks correct then jump to it with <enter> You can close the list with :clo And later reopen it with :cope It will be there unless you have executed other commands that overwrite the list
1,047,407
1,047,745
How to use 16bit heightmaps with Ogre3d and PhysX
I'm using Ogre3D and PhysX. When I load a terrain from an 8bit height map, it looks normal on Visual Debugger. Look at first image: http://img44.imageshack.us/gal.php?g=44927650.jpg But when I save the height map as a 16bit image, I get what you see on second image. Here's the code, thats works normal with 8bit PNG: mSceneMgr->setWorldGeometry("terrain.cfg" ); mTSM=static_cast<TerrainSceneManager*>(sceneMgr); TerrainOptions mTerrainOptions = mTSM->getOptions(); //load heihgtmap Image mImage; mImage.load("isl_h_ph.png", ResourceGroupManager::getSingleton().getWorldResourceGroupName()); //load image //write image buffer to pOrigSrc const uchar* pOrigSrc = mImage.getData(); const uchar* pSrc; // image size to mPageSize size_t mPageSize = mTerrainOptions.pageSize; NxActorDesc ActorDesc; //set number of segments heightFieldDesc = new NxHeightFieldDesc; heightFieldDesc->nbColumns = mPageSize; heightFieldDesc->nbRows = mPageSize; heightFieldDesc->verticalExtent = -1000; heightFieldDesc->convexEdgeThreshold = 0; heightFieldDesc->samples = new NxU32[mPageSize*mPageSize]; //constructor for every sample? heightFieldDesc->sampleStride = sizeof(NxU32); //some sample step = number of samples pSrc = pOrigSrc; char* currentByte = (char*)heightFieldDesc->samples; //current sample mb? LogManager::getSingletonPtr()->logMessage("+++Heightmap---"); for (NxU32 row = 0; row < mPageSize; row++) { for (NxU32 column = 0; column < mPageSize; column++) //cycle around samples { pSrc = pOrigSrc + column*mPageSize +row; //NxReal s = NxReal(row) / NxReal(mPageSize); //NxReal t = NxReal(column) / NxReal(mPageSize); NxI16 height = (NxI32)(*pSrc++); NxU32 matrixOffset = (row % gMatrixSize) * gMatrixSize + (column % gMatrixSize); //LogManager::getSingletonPtr()->logMessage(Ogre::StringConverter::toString(height)); NxHeightFieldSample* currentSample = (NxHeightFieldSample*)currentByte; currentSample->height = height; currentSample->materialIndex0 = gMatrix[matrixOffset][1]; currentSample->materialIndex1 = gMatrix[matrixOffset][2]; currentSample->tessFlag = gMatrix[matrixOffset][0]; currentByte += heightFieldDesc->sampleStride; } } heightField = mScene->getPhysicsSDK().createHeightField(*heightFieldDesc); NxHeightFieldShapeDesc heightFieldShapeDesc; heightFieldShapeDesc.heightField = heightField; heightFieldShapeDesc.shapeFlags = NX_SF_FEATURE_INDICES | NX_SF_VISUALIZATION; heightFieldShapeDesc.group = 1; heightFieldShapeDesc.heightScale = 18.8f;//1 в Physx = 255 в огре heightFieldShapeDesc.rowScale = mTerrainOptions.scale.x; heightFieldShapeDesc.columnScale = mTerrainOptions.scale.z; heightFieldShapeDesc.meshFlags = NX_MESH_SMOOTH_SPHERE_COLLISIONS; heightFieldShapeDesc.materialIndexHighBits = 0; heightFieldShapeDesc.holeMaterial = 2; ActorDesc.shapes.pushBack(&heightFieldShapeDesc); What should I change to get 16bit or higher image loaded working? P.S.: Sorry for bad English
Your pOrigSrc is a uchar, which is 8 bits, so you're not getting the correct offset when you do this: pSrc = pOrigSrc + column*mPageSize +row; You can fix this by first grabbing the stride of your image before your loops, something like this: int imageStride = mImage.getBPP() / 8; and then multiply your calculated offset by the stride, something like this: pSrc = pOrigSrc + (column*mPageSize +row)*imageStride; That should allow you to use both 8-bit and 16-bit height maps. PhysX only supports 16-bit height maps, so you can't go higher than that.
1,047,513
1,047,523
c++ compilation error
Following code is giving compilation error in visual studio 2009. #include <iterator> #include <vector> template <class T1, class T2 > class A { public: typename std::vector<std::pair<T1,T2> >::iterator iterator; std::pair<iterator, bool > foo(const std::pair<T1 ,T2> &value_in); }; can anyone throw some light on it? Here is the error. error C2327: 'A<T1,T2>::iterator' : is not a type name, static, or enumerator
This declares iterator to be a variable (not a type): typename std::vector<std::pair<T1,T2> >::iterator iterator; Did you mean this? typedef typename std::vector<std::pair<T1,T2> >::iterator iterator; Further information: If you're curious about what typename does, read up about the differences between dependent and non-dependent names. If your type is closely related to a specific container, a typedef of that container can be useful, as the STL pattern uses many nested typedefs you can easily access (V::value_type below). This has the added advantage of requiring less change as your code evolves, e.g. using a different allocator (the second template parameter to vector), requires just one edit. template<class T1, class T2> struct A { private: // you may or may not want to expose these convenience types typedef std::pair<T1, T2> P; typedef std::vector<P> V; public: typedef typename V::value_type value_type; typedef typename V::iterator iterator; std::pair<iterator, bool> foo(value_type const& value_in); };
1,047,663
1,047,694
How do I declare template function outside the class declaration
#include <iterator> #include <map> #include <vector> template <class T1, class T2> class A { public: typedef typename std::vector<std::pair<T1,T2> >::iterator iterator; std::pair<iterator, bool > foo() { iterator aIter; return std::pair<std::vector<std::pair<T1,T2> >::iterator, bool >(aIter ,false); } }; The above code works fine for me. But I want to move the definition of the function outside the the class declaration. I tried this. template <class T1, class T2> class A { public: typedef typename std::vector<std::pair<T1,T2> >::iterator iterator; std::pair<iterator, bool > foo(); }; template <class T1, class T2> std::pair<std::vector<std::pair<T1,T2> >::iterator, bool > A<T1, T2>::foo() { iterator aIter; return std::pair<std::vector<std::pair<T1,T2> >::iterator, bool >(aIter ,false); } But it is not compiling. Any Idea how to do this?
You are again missing the typename in the return value. The function should be: template <class T1, class T2> std::pair<typename std::vector<std::pair<T1,T2> >::iterator, bool > A<T1, T2>::foo() { iterator aIter; return std::pair<std::vector<std::pair<T1,T2> >::iterator, bool >(aIter ,false); }
1,048,218
1,048,352
Select() system call in threads?
I am reading data from multiple serial ports. At present I am using a custom signal handler (by setting sa_handler) to compare and wake threads based on file descriptor information. I was searching for a way out to have individual threads with unique signal handlers, in this regard I found that select system call is to be used. Now I have following questions: If I am using a thread (Qt) then where do I put the select system call to monitor the serial port? Is the select system call thread safe? Is it CPU intensive because there are many things happening in my app including GUI update? Please do not mind, if you find these questions ridiculous. I have never used such a mechanism for serial communication.
The POSIX specification (select) is the place to look for the select definition. I personally recommend poll - it has a better interface and can handle any number of descriptors, rather than a system-defined limit. If I understand correctly you're waking threads based on the state of certain descriptors. A better way would be to have each thread have its own descriptor and call select itself. You see, select does not modify the system state, and as long as you use thread-local variables it'll be safe. However, you will definitely want to ensure you do not close a descriptor that a thread depends on. Using select/poll with a timeout leaves the "waiting" up to the kernel side, which means the thread is usually put to sleep. While the thread is sleeping it is not using any CPU time. A while/for loop on a select call without a timeout on the other hand will give you a higher CPU usage as you're constantly spinning in the loop. Hope this helps. EDIT: Also, select/poll can have unpredictable results when working with the same descriptor in multiple threads. The simple reason for this is that the first thread might be woken up because the descriptor is ready for reading, but the second thread has to wait for the next "available for reading" wakeup. As long as you're not selecting on the same descriptor in multiple threads you should not have a problem.
1,048,749
1,048,789
What is the difference between pointer and array in the following context?
#include <cstring> int main() { char *pName = new char[10]; char dummy[] = "dummy"; strcpy(pName + 0,dummy);//how this is different from -->this works strcpy(pName[0],dummy);//this one...--> error C2664: 'strcpy' : //cannot convert parameter 1 //from 'char' to 'char *' }
pName[0] is the first element in a character array (one character) pName is a shortcut to &pName[0] (a pointer to the first element of your array) The reason you are getting your error is because strcpy expects a pointer to a char (char*), and not a char value (which is what pName[0] is)
1,048,764
1,059,901
validate xml schema using msxml parser
I want to validate an XML file against an XML Schema file. It is a simple xml file, does not include namespace etc. I want to do this in c++, using MSXML 6.0.
You can validate as you load. This is sample code from the Windows/MSXML SDK: IXMLDOMSchemaCollectionPtr pXS; IXMLDOMDocument2Ptr pXD = NULL; IXMLDOMParseErrorPtr pErr = NULL; _bstr_t strResult = ""; HRESULT hr = pXS.CreateInstance(__uuidof(XMLSchemaCache50)); hr = pXS->add("urn:namespace", "myschema.xsd"); // Create a DOMDocument and set its properties. hr = pXD.CreateInstance(__uuidof(DOMDocument50)); // Assign the schema cache to the DOMDocument's // schemas collection. pXD->schemas = pXS.GetInterfacePtr(); // Load books.xml as the DOM document. pXD->async = VARIANT_FALSE; pXD->validateOnParse = VARIANT_TRUE; pXD->resolveExternals = VARIANT_TRUE; hr = pXD->load("TheXmlDocument.xml"); // check hr and pXD->errorCode here You can download the MSXML6 SDK to get this sample and lots of others. Note: It will not install on Vista. If you run Vista, then get the Windows SDK.
1,048,806
1,048,821
Implementing a thread-safe, generic stack in C++ on linux
In a recent interview, I was asked to implement a thread safe generic (i.e.template based) stack in C++, on linux machine. I quickly came up with the following (It may have compilation errors). I got through. The interviewer probably liked something in this implementation. Maybe the design part :) Here are a few problems that this implementation may have:- 1. Incorrect implementation to indicate overflow/underflow. There is no overflow handling since I'm using STL vector as the underlying data structure. Should there be any such handling? Also, underflow (in Pop()) yields false as return value. Should it be done by throwing of an exception? 2. Implementation of PopElem routine. Is the below implementation correct? 3. No real use of top element. 4. Better timing between start of writer and reader thread. Please make any comments/suggestions/improvements. Thanks. //Implementing a thread safe generic stack. #include<pthread.h> #include<iostream> #include<vector> using namespace std; template<typename T> class MyStack { public: //interface bool Push(T elem); bool Pop(T& elem); bool IsEmpty(); //constructor MyStack() { pthread_mutex_init(&lock); top = 0; } //destructor ~MyStack() { pthread_mutex_destroy(&lock); } private: pthread_mutex_t lock; int top; vector<T> stack; bool MyStack::Push(T elem); bool MyStack::PopElem(T& elem); }; //end of MyStack template<typename T> bool MyStack<T>::Push(T elem) { pthread_mutex_lock(&lock); PushElem(elem); pthread_mutex_unlock(&lock); } template<typename T> bool MyStack<T>::Pop(T& elem) { pthread_mutex_lock(&lock); PopElem(elem); pthread_mutex_unlock(&lock); } template<typename T> bool MyStack<T>::PushElem(T elem) { stack.push_back(elem); top = stack.size(); } template<typename T> bool MyStack<T>::PopElem(T& elem) { if(this.IsEmpty()) { return false; } elem = stack.back(); //tricky, returns a reference to the last element stack.pop_back(); // is elem valid after this ?? top = stack.size(); return true; } template<typename T> bool MyStack<T>::IsEmpty() { return stack.empty(); } class MyStackTest { public: void Initialize() { pthread_init(&readerT); pthread_init(&writerT); } void Run() { pthread_create(writerT,0,writer,0); pthread_create(readerT,0,reader,0); pthread_join(&writerT); pthread_join(&readerT); } private: pthread_t readerT; pthread_t writerT; MyStack<int> stack; void reader(void); void writer(void); }; void MyStackTest::writer() { for(int i=0;i<20;i++) { stack.Push(i); cout<<"\n\t Pushed element: "<<i; } //end for } void MyStackTest::reader() { int elem; while(stack.Pop(elem)) { cout<<"\n\t Popped: "<<elem; } } int main() { MyStackTest Test; Test.Run(); }
Some issues: I would implement a Locker class to claim & free the mutex using RAII I would use std::stack I would make the user of std::stack use the Locker to implement the locking policy - having a stack that locks itself is bad design, as the stack can't know how it is to be used
1,048,904
4,623,087
Help for Boost.Statechart bug
Any ideas how to fix this? using 1.39_0 on ubuntu 8.10 w/g++ 4.3.2 In the following statechart, the phrase "BUGGY" is printed three times. One would expect the event would only trigger one "BUGGY". In the case of the project I am working on, I cannot return discard_event() as I need the event to reach multiple states (usually deep in an orthogonal set of states). If there is a workaround that can be applied instead of modifying statechart, I would like to know. $ cat bug.cpp #include <boost/intrusive_ptr.hpp> #include <boost/mpl/list.hpp> #include <boost/statechart/custom_reaction.hpp> #include <boost/statechart/event.hpp> #include <boost/statechart/simple_state.hpp> #include <boost/statechart/state.hpp> #include <boost/statechart/state_machine.hpp> #include <iostream> using namespace std; namespace sc = boost::statechart; namespace mpl = boost::mpl; struct evSay : sc::event<evSay>{ }; struct top; struct c1; struct c2; struct c3; struct sm : public sc::state_machine<sm,top> { }; struct top : sc::simple_state<top,sm,mpl::list<c1,c2,c3> > { typedef sc::custom_reaction<evSay> reactions; sc::result react(const evSay &) { cout<<"BUGGY"<<endl; return forward_event(); } }; struct c1 : sc::simple_state <c1, top::orthogonal<0> > { }; struct c2 : sc::simple_state <c2, top::orthogonal<1> > { }; struct c3 : sc::state <c3, top::orthogonal<2> > { c3( my_context ctx) : my_base(ctx) { post_event( boost::intrusive_ptr< evSay > ( new evSay() ) ); } }; int main() { sm* fsm = new sm(); fsm->initiate(); delete fsm; return 0; } $ g++ bug.cpp && ./a.out BUGGY BUGGY BUGGY EDIT:: This is an example Statemachine that shows my problem that I run into in my much larger one I actually working on. I know that top will forward evSay. Note that c1,c2,c3 do not react to evSay. Here is an example where I need forwarding so that two states may react to evSay. #include <boost/intrusive_ptr.hpp> #include <boost/mpl/list.hpp> #include <boost/statechart/custom_reaction.hpp> #include <boost/statechart/event.hpp> #include <boost/statechart/simple_state.hpp> #include <boost/statechart/state.hpp> #include <boost/statechart/state_machine.hpp> #include <iostream> using namespace std; namespace sc = boost::statechart; namespace mpl = boost::mpl; namespace BUG { struct evSay : sc::event<evSay>{ }; struct top;struct c1;struct c2;struct c3;struct c2_1; struct sm : public sc::state_machine<sm,top> { }; struct top : sc::simple_state<top,sm,mpl::list<c1,c2,c3> > { typedef sc::simple_state<top,sm,mpl::list<c1,c2,c3> > my_type; typedef sc::custom_reaction<evSay> reactions; sc::result react(const evSay &) { cout<<"BUGGY"<<endl; return forward_event(); } }; struct c1 : sc::simple_state <c1, top::orthogonal<0> > { }; struct c2 : sc::simple_state <c2, top::orthogonal<1>, c2_1 > { }; struct c3 : sc::state <c3, top::orthogonal<2> > { c3( my_context ctx) : my_base(ctx) { post_event( boost::intrusive_ptr< evSay > ( new evSay() ) ); } }; struct c2_1 : sc::simple_state<c2_1, c2 > { typedef sc::custom_reaction<evSay> reactions; sc::result react(const evSay &) { cout<<"CHILD REACTION"<<endl; return forward_event(); } }; } int main() { BUG::sm* fsm = new BUG::sm(); fsm->initiate(); delete fsm; return 0; } output: BUGGY CHILD REACTION BUGGY BUGGY
Move the reaction you want down to a child state of the top state. This takes it out of the line of forward_state events. I didn't implement it as a inner-type, but you could. #include <boost/intrusive_ptr.hpp> #include <boost/mpl/list.hpp> #include <boost/statechart/custom_reaction.hpp> #include <boost/statechart/event.hpp> #include <boost/statechart/simple_state.hpp> #include <boost/statechart/state.hpp> #include <boost/statechart/state_machine.hpp> #include <iostream> using namespace std; namespace sc = boost::statechart; namespace mpl = boost::mpl; struct evSay : sc::event<evSay>{ }; struct top;struct c1;struct c2;struct c3;struct c2_1;struct sub_1; struct sm : public sc::state_machine<sm,top> { }; struct top : sc::simple_state<top,sm, mpl::list<c1,c2,c3, sub_1> > { }; struct sub_1 : sc::simple_state<sub_1, top::orthogonal<3> > { typedef sc::custom_reaction<evSay> reactions; sc::result react(const evSay &) { cout<<"PARENT REACTION"<<endl; return forward_event(); } }; struct c1 : sc::simple_state <c1, top::orthogonal<0> > { }; struct c2 : sc::simple_state <c2, top::orthogonal<1>, c2_1 > { }; struct c3 : sc::simple_state <c3, top::orthogonal<2> > { }; struct c2_1 : sc::simple_state<c2_1, c2 > { typedef sc::custom_reaction<evSay> reactions; sc::result react(const evSay &) { cout<<"CHILD REACTION"<<endl; return forward_event(); } }; int main() { sm* fsm = new sm(); fsm->initiate(); fsm->process_event( evSay() ); delete fsm; return 0; } ~$g++ test.cpp -I Downloads/boost_1_45_0 ~$./a.out CHILD REACTION PARENT REACTION
1,048,968
1,049,042
Reading from a file not line-by-line
Assigning a QTextStream to a QFile and reading it line-by-line is easy and works fine, but I wonder if the performance can be inreased by first storing the file in memory and then processing it line-by-line. Using FileMon from sysinternals, I've encountered that the file is read in chunks of 16KB and since the files I've to process are not that big (~2MB, but many!), loading them into memory would be a nice thing to try. Any ideas how can I do so? QFile is inhereted from QIODevice, which allows me to ReadAll() it into QByteArray, but how to proceed then and divide it into lines?
QTextStream has a ReadAll function: http://doc.qt.io/qt-4.8/qtextstream.html#readAll Surely that's all you need? Or you could read all into the QByteArray and QTextStream can take that as an input instead of a QFile.
1,049,212
1,049,232
C++ How to read in objects with a given offset?
Now I have a file with many data in it. And I know the data I need begins at position (long)x and has a given size sizeof(y) How can I get this data?
Use the seek method: ifstream strm; strm.open ( ... ); strm.seekg (x); strm.read (buffer, y);
1,049,637
1,050,938
Register hotkeys in Linux using library for c++
are there any libraries for Linux wrote with C++, that could register global hotkeys for my application? Thanks.
You'll have to provide more information. In Gnome, the global functionality varies by window manager. Metacity has configurable global shortcuts, as do Compiz and Sawfish, and they're all configured differently. Xhotkeys can also be used for the same functionality. However, these are all limited to starting applications only. Within the KDE application framework, KAction can register global shortcuts which perform actions inside your program. These are actually handled by a module in kded (launched on demand), so they work even outside of the KDE desktop environment. If you don't use the KDE framework, but are still using X11, you can use the xlib API to call XGrabKey on the root window. For shortcuts that work outside of X, as long as you are running as root (or permissions are changed permissively) on a 2.6 kernel, you can directly open /dev/input/event*, and poll for the desired key events.
1,049,734
1,050,065
Detecting when an object is passed to a new thread in C++?
I have an object for which I'd like to track the number of threads that reference it. In general, when any method on the object is called I can check a thread local boolean value to determine whether the count has been updated for the current thread. But this doesn't help me if the user say, uses boost::bind to bind my object to a boost::function and uses that to start a boost::thread. The new thread will have a reference to my object, and may hold on to it for an indefinite period of time before calling any of its methods, thus leading to a stale count. I could write my own wrapper around boost::thread to handle this, but that doesn't help if the user boost::bind's an object that contains my object (I can't specialize based on the presence of a member type -- at least I don't know of any way to do that) and uses that to start a boost::thread. Is there any way to do this? The only means I can think of requires too much work from users -- I provide a wrapper around boost::thread that calls a special hook method on the object being passed in provided it exists, and users add the special hook method to any class that contains my object. Edit: For the sake of this question we can assume I control the means to make new threads. So I can wrap boost::thread for example and expect that users will use my wrapped version, and not have to worry about users simultaneously using pthreads, etc. Edit2: One can also assume that I have some means of thread local storage available, through __thread or boost::thread_specific_ptr. It's not in the current standard, but hopefully will be soon.
In general, this is hard. The question of "who has a reference to me?" is not generally solvable in C++. It may be worth looking at the bigger picture of the specific problem(s) you are trying to solve, and seeing if there is a better way. There are a few things I can come up with that can get you partway there, but none of them are quite what you want. You can establish the concept of "the owning thread" for an object, and REJECT operations from any other thread, a la Qt GUI elements. (Note that trying to do things thread-safely from threads other than the owner won't actually give you thread-safety, since if the owner isn't checked it can collide with other threads.) This at least gives your users fail-fast behavior. You can encourage reference counting by having the user-visible objects being lightweight references to the implementation object itself [and by documenting this!]. But determined users can work around this. And you can combine these two-- i.e. you can have the notion of thread ownership for each reference, and then have the object become aware of who owns the references. This could be very powerful, but not really idiot-proof. You can start restricting what users can and cannot do with the object, but I don't think covering more than the obvious sources of unintentional error is worthwhile. Should you be declaring operator& private, so people can't take pointers to your objects? Should you be preventing people from dynamically allocating your object? It depends on your users to some degree, but keep in mind you can't prevent references to objects, so eventually playing whack-a-mole will drive you insane. So, back to my original suggestion: re-analyze the big picture if possible.
1,049,853
1,051,609
Net-SNMP variables using C++
I am having trouble with a few of the variables that the Net-SNMP library provides, specifically the ability to capture in/out Octets. In/OutOctets Issue: I have another check for ASN_INTEGER and I am catching this oid put the output does not seem to be correct. I am using *vars->val.integer and pushing this into a long but I am currently getting negative numbers so I have tried to push this into a double but the output is a completely different value from that of the actual value attached to that oid. Has anyone else had this issues and if so can you provide some insight please? Thanks in advance.
I have partially resolved this issue by using ASN_COUNTER instead of ASN_INTEGER. Although a counter32 is in fact an integer it is a type of ASN_COUNTER. So using a check of ASN_COUNTER with *vars->val.integer is in fact the correct method to catch a counter32.
1,049,909
1,057,277
VC++ doesn't detect newly created env variable using GetEnvironmentVariable
I'm using the Win32 function GetEnvironmentVariable to retrieve the value of a variable that I just created. I'm running Windows XP and VC++ 2005. If I run the program from within Visual Studio, it can't find the new variable. If I run it from a command-prompt, it does. I restarted VC++ but same result. I even restarted all instances of Visual Studio but still the same problem. It might get resolved if I reboot the PC but I'm curious why this is so. Here's the code that I'm using: #define BUFSIZE 4096 #define VARNAME TEXT("MY_ENV_NAME") int _tmain(int argc, _TCHAR* argv[]) { TCHAR chNewEnv[BUFSIZE]; DWORD dwEnv = ::GetEnvironmentVariable(VARNAME, chNewEnv, BUFSIZE); if (dwEnv == 0) { DWORD dwErr = GetLastError(); if(dwErr == ERROR_ENVVAR_NOT_FOUND) { printf("Environment variable does not exist.\n"); return -1; } } else { printf(chNewEnv); } return 0; } If I replace MY_ENV_NAME with something that must exist, such as TEMP, it works as expected. Any ideas? Thanks.
Thanks for all the responses. As I mentioned in my question, I tried restarting everything, short of rebooting the PC. It turns out that because my environment variable was a SYSTEM variable, VS doesn't recognize it without rebooting the PC. When I moved the env variable from SYSTEM to USER and restarted VS, it worked fine.
1,049,976
1,049,999
How could this simple pointer equality test fail?
void FileManager::CloseFile(File * const file) { for (int i = 0; i < MAX_OPEN_FILES; ++i) { if ((_openFiles[i] == file) == true) { _openFiles[i] == NULL; } } ... _openFiles is a private member of FileManager and is just an array of File *'s When the exact same test is performed in the Immediate window i get a result of 1!?! EDIT the == true was added purely as a sanity check!!
You have _openFiles[i] == NULL; should that be _openFiles[i] = NULL; ?
1,050,325
1,111,812
What does the construct keyword do when added to a method?
The code here is X++. I know very little about it, though I am familiar with C#. MS says its similiar to C++ and C# in syntax. Anyway, I assume the code below is a method. It has "Construct" as a keyword. What is a construct/Constructor method? What does the construct keyword change when applied to the function? Also, am I wrong in assuming the code would create some sort of infinite loop? My assumption is that its a method with a return type of "InventMovement". static InventMovement construct(Common buffer, InventMovSubType subType = InventMovSubType::None, Common childBuffer = null) { InventMovement movement = InventMovement::constructNoThrow(buffer,subType,childBuffer); if (!movement) throw error("@SYS20765"); return movement; } Thanks! Kevin
Construct is not a keyword in X++, this is merely a static method called construct that returns an InventMovement class. It is used to allow you to create a derived class of a base class without having to know which derived class to create. This is how AX implements the Factory pattern. You will see this pattern used in AX in many places where there are abstract base classes. InventMovement is an abstract base class for many other classes, such as InventMov_Purch and InventMov_Sales. You can't call new() on an abstract class, so instead of having a switch statement to call either new InventMov_Purch() or new InventMov_Sales() every time you need to create a InventMovement class, you use the InventMovement::construct() method to call the correct new() for you.
1,050,377
1,050,569
Machine ID for Mac OS?
I need to calculate a machine id for computers running MacOS, but I don't know where to retrieve the informations - stuff like HDD serial numbers etc. The main requirement for my particular application is that the user mustn't be able to spoof it. Before you start laughing, I know that's far fetched, but at the very least, the spoofing method must require a reboot. The best solution would be one in C/C++, but I'll take Objective-C if there's no other way. The über-best solution would not need root privileges. Any ideas? Thanks.
Erik's suggestion of system_profiler (and its underlying, but undocumented SystemProfiler.framework) is your best hope. Your underlying requirement is not possible, and any solution without hardware support will be pretty quickly hackable. But you can build a reasonable level of obfuscation using system_profiler and/or SystemProfiler.framework. I'm not sure your actual requirements here, but these posts may be useful: Store an encryption key in Keychain while application installation process (this was related to network authentication, which sounds like your issue) Obfuscating Cocoa (this was more around copy-protection, which may not be your issue) I'll repeat here what I said in the first posting: It is not possible, period, not possible, to securely ensure that only your client can talk to your server. If that is your underlying requirement, it is not a solvable problem. I will expand that by saying it's not possible to construct your program such that people can't take out any check you put in, so if the goal is licensing, that also is not a completely solvable problem. The second post above discusses how to think about that problem, though, from a business rather than engineering point of view. EDIT: Regarding your request to require a reboot, remember that Mac OS X has kernel extensions. By loading a kernel extension, it is always possible to modify how the system sees itself at runtime without a reboot. In principle, this would be a Mac rootkit, which is not fundamentally any more complex than a Linux rootkit. You need to carefully consider who your attacker is, but if your attackers include Mac kernel hackers (which is not an insignificant group), then even a reboot requirement is not plausible. This isn't to say that you can't make spoofing annoying for the majority of users. It's just always possible by a reasonably competent attacker. This is true on all modern OSes; there's nothing special here about Mac.
1,050,431
1,060,283
What is #nomacros (EP003), and is it alive?
The Evolution WG Issues List of 14 February 2004 has ... EP003. #nomacros. See EI001. Note by Stroustrup to be written. In rough (or exact) terms, what is #nomacros, and is it available as an extension anywhere? It would have been a useful diagnostic tool in a recent project involving porting thousands of files of 1995-vintage C++ to a 2005 compiler, compared to the alternative of running the code through the preprocessor and examining the .i files for surprise packages.
It is just a proposal under active consideration for inclusion into C++, but still not available in the current compilers. If you read further down the page, it says: ES042. #nospam. Provide a preprocessor mechanism for limiting macros entering and exiting a scope. For example: #nomacros #in A B … #out A X #endnomacros No macros are expanded between #nomacros and #endnomacros unless explicitly enabled by #in. No macros defined between #nomacros and #endnomacros will be defined after #endnomacros unless explicitly enabled by #out. Suggestion by Bjarne Stroustrup. After discussion in the EWG it was decided to look for a solution that allowed macros used by macros allowed in by “#in” to be used in the expansion of such macros only. #nomacros should nest.
1,050,516
1,063,811
QTabBar icon position
Is there a way to change the alignment of the icon or text of a tab in Qt? Specifically, I would like the text to appear below the icon. By default the icon sits to the left of the text, but that's not appropriate for all situations (especially when you start styling your tabs with stylesheets) It would seem very odd to me that this aspect would be so restricted when I can completely alter the look and feel of the rest of the tab. Thanks for any suggestions!
The only way I can see is to create a subclass of QTabBar that implements your own painting algorithm. Then you'd need to subclass QTabWidget to set your own version of the tab bar. It doesn't look like a lot of fun to me.
1,050,520
1,050,819
What is LogonUser()'s token returned used for?
What can you do with the token LogonUser returns? And what is it used for? BOOL LogonUser( __in LPTSTR lpszUsername, __in_opt LPTSTR lpszDomain, __in LPTSTR lpszPassword, __in DWORD dwLogonType, __in DWORD dwLogonProvider, __out PHANDLE Token ); I just need a more general discription and real world uses of what the token is and how it works. Thanks, -Pete
As MSDN says: "In most cases, the returned handle is a primary token that you can use in calls to the CreateProcessAsUser function". There are no reasons not to believe. Sample: you could write your own runas.exe. Call LogonUser with username&password from command line. Then call CreateProcessAsUser to start program with selected credentials.
1,051,010
1,051,044
How to take a pointer to a template function specialized on a string?
I was trying use a set of filter functions to run the appropriate routine, based on a string input. I tried to create matcher functions for common cases using templates, but I get a "type not equal to type" error when I try to store a pointer to the specialized function (in a structure, in the real application) Distilled example from a Visual C++ 8 'console application' template <const char *C> const char* f(void) { return C; } const char* (*g)(void) = f<"hi">; int _tmain(int argc, _TCHAR* argv[]) { return g(); } This fails with the error Error 1 error C2440: 'initializing' : cannot convert from 'const char *(__cdecl *)(void)' to 'const char *(__cdecl *)(void)' c:\files\pointer.cpp 7 (It also has an error on the main return value, but that doesn't concern me here.) The same example succedes if const char * is replaced with int.
Strings as template-value parameters are prohibited by the ISO standard.
1,051,035
7,739,683
DirectShow stop/resume live stream
I'm using DirectShow to play audio/video files in my application. I use IGraphBuilder::RenderFile() to build the filter graph and the IMediaControl interface to play/pause/stop the media. This works fine for local media files, but causes problems with live mms streams. If I call IMediaControl::Stop() on a live stream, the stream will stop playing as expected. However, if I call IMediaControl::Run() to resume the stream, nothing happens. The graph generates an EC_COMPLETE event, but the video does not play anymore. Calling IMediaControl::Pause() followed by IMediaControl::Run() will resume the stream where it left off, but will eventually stop. It seems to just playback the data that was in the buffer when IMediaControl::Pause() was called, instead of re-syncing with the live stream. Does anybody know how to resume playing a live stream without destroying and rebuilding the filter graph?
The behavior indicates that one of the filters in the graph exhibits buggy behavior. The filter has to be replaced if you want to be able to re-run the feed. Also there is no good source filter to render mms:// streams which are obsolete themselves as protocol. Windows Media Player in Windows 7 is using its private DirectShow filter which is not available to applications. You might end up using custom source filter based on Windows Media Format SDK, or a third party replacement. UPDATE: In Windows XP, mms:// URLs are rednered by Windows Media Splitter filter (wmpasf.dll). It is obviously responsible for the bug in question. So, if you are still going to use it, you might have to remove, re-add a new instance of the filter and re-render its pins in order to restart streaming. As I mentioned, this filter is no longer available in more recent versions of Windows (Windows 7 at the very least).
1,051,089
1,051,209
Managing Implicit Type Conversion in C++
I'm working on code that does nearest-neighbor queries. There are two simple ideas that underlie how a user might query for data in a search: closest N points to a given point in space. all points within a given distance. In my code, Points are put into a PointList, and the PointList is a container has the job of keeping track of the points that have been found in the search. Right now my PointList object has one constructor: PointList( unsigned int maxvals ); // #1 The next two constructors that I'd like to add are these: PointList( float maxdist ); // #2 PointList( unsigned int maxvals, float maxdist ); // #3 My question is: how do I ensure that my users and the C++ compiler will generate the right constructor for the PointList and differentiates between constructors 1 and 2? Should I just implement #3 and provide constants that define arbitrary large values for maxvals and maxdist? Another alternative might be to write another system of lightweight objects that govern the logic for adding Points to the list, but that feels like overkill for such a simple idea. I'm really trying to make this transparent for my users, who are mostly scientists who have learned C++ sometimes without the benefit of formal education. Thanks!
Overload resolution for integer types happen on two categories, which can be very roughly summarized to Promotion: This is a conversion from types smaller than int to int or unsigned int, depending on whether int can store all the values of the source type. Conversion: This is a conversion from any integer type to another integer type. Similar, conversion for floating point types happen on two categories Promotion: This is a conversion from float to double Conversion: This is a conversion from any floating point type to another floating point type And there is a conversion from integer to floating or back. This is ranked as a conversion, rather than a promotion. A promotion is ranked better than a conversion, and where only a promotion is needed, that case will be preferred. Thus, you can use the following constructors PointList( int maxVals ); PointList( unsigned int maxVals ); PointList( long maxVals ); PointList( unsigned long maxVals ); PointList( double maxDist ); PointList( long double maxDist ); For any integer type, this should select the first group of constructor. And for any floating point type, this should select the second group of constructors. Your original two constructors could easily result in an ambiguity between float and unsigned int, if you pass an int, for example. For the other, two argument constructor, you can go with your solution, if you want. That said, i would use a factory function too, because deciding on the type the meaning of the parameter is quite fragile i think. Most people would expect the following result to equal PointList p(floor(1.5)); PointList u((int)1.5); But it would result in a different state of affairs.
1,051,474
1,060,351
Make a window Static as well as allow adding text using CreateWIndowEx()
I'm using CreateWindowEx() function to create an "EDIT" window, i.e. where a user can type. g_hwndMain = CreateWindowEx(0, WC_TEXT, NULL, WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL, 0, 0, 400, 200, phwnd, NULL, g_hInstance, NULL); But I would also like the window to be static. Is there a way to do it during the creation of the window? Or any other function that may be used after the creation of the window? I tried using SetWindowPos function after creating the window using SWP_NOSENDCHANGING and SWP_NOREPOSITION, but that didn't o the trick. ANy ideas? No, I mean Immovable Window. Basically, the window I create should be able to accept text and be immovable at the same time.
Thanks for your help. Ok So far I've done this to handle WM_WINDOWPOSCHANGING message BOOL OnWindowPosChanging(HWND hwnd, WINDOWPOS *pwp) { return 0; } LRESULT CALLBACK WndProc(HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam) { switch (uiMsg) { HANDLE_MSG(hwnd, WM_WINDOWPOSCHANGING, OnWindowPosChanging); } return DefWindowProc(hwnd, uiMsg, wParam, lParam); } and when I create my window, I do this: g_hwndMain = CreateWindowEx(0, TEXT("EDIT"), NULL, WS_BORDER, 0, 0, 400, 200, phwnd, NULL, g_hInstance, NULL); if (!g_hwndMain) { RemoveImages(spHTMLDoc);//Just so I know that the window has been created properly } else{ SetWindowPos(g_hwndMain, HWND_TOP, 500, 500, 300, 300, SWP_NOSENDCHANGING | SWP_SHOWWINDOW ); } The SWP_NOMOVE flag does not let the code change the position of the window, but the user is still able to change the window's position by moving it using a mouse. But this is exactly what I want to prevent. The window should be static. Any thing missing in my code, or any more suggestions?
1,051,480
1,051,535
VS 2008 C++ how to make a project without .net dependency
I am writing a plain vanilla c++ console app using VS 2008. When I create the project, the IDE gives me a choice of .net versions. There is no option for 'none'. When I look at the project properties page, the Targeted Framework has whatever value I chose and is greyed out. When I try and run the app on a windows machine without the clr, it gives me a setup error and quits. There is nothing in my code that has anything to do with .net. How can I escape the clutches of .net and the clr?
Make sure that you chose the "Win32 Console Application" project type. This will give you a C++ only project. Most of the other console options will bind the project to .Net.
1,051,539
1,051,564
Pre/Post function call implementation
I was wondering if I could do pre/post function call in C++ somehow. I have a wrapper class with lots of functions, and after every wrapper function call I should call another always the same function. So I do not want to put that postFunction() call to every single one of the functions like this: class Foo { f1(); f2(); f3(); . . . fn(); } void Foo::f1() { ::f1(); postFunction(); } void Foo::f2() { ::f2(); postFunction(); } etc. Instead I want that postFunction call to come automatically when I call some Foo's member function. Is it possible? It would help maintenance..
Might be a case for RAII! Dun-dun-dunnn! struct f1 { f1(Foo& foo) : foo(foo) {} // pre-function, if you need it void operator()(){} // main function ~f1() {} // post-function private: Foo& foo; } Then you just have to make sure to create a new temporary f1 object every time you wish to call the function. Reusing it will obviously mean the pre/post functions don't get called every time. Could even wrap it like this: void call_f1(Foo& foo) { f1(foo)(); // calls constructor (pre), operator() (the function itself) and destructor (post) } You might experiment a bit with other ways of structuring it, but in general, see if you can't get constructors/destructors to do the heavy lifting for you. Roman M's approach might be a good idea as well. Write one generic wrapper, which takes a functor or function pointer as its argument. That way, it can call pre/post functions before and after calling its argument
1,051,597
1,051,644
Is there a "function size profiler" out there?
After three years working on a C++ project, the executable has grown to 4 MB. I'd like to see where all this space is going. Is there a tool that could report what the biggest space hogs are? It would be nice to see the size by class (all functions in a class), by template (all instantiations), and by library (how much belongs to the C standard library and STL? how much for each library in the exe?) Edit: Note, I am using Visual C++ on Windows.
In Linux, you can use nm to show all symbols in the executable and to sort them in reverse order by size: $ nm -CSr --size-sort <exe> Options: -C demangles C++ names. -S shows size of symbols. --size-sort sorts symbols by size. -r reverses the sort. If you want to get the results per namespace or per class, you can just grep the output for 'namespace::', 'namespace::class_name::', etc.. If you only want to see symbols that are defined in the executable (not ones defined elsewhere, like in libraries) then add --defined-only. Sorting by size should take care of this, though, since undefined symbols aren't going to have a size. For Windows, you should still be able to use nm on your binary files, since nm supports COFF binaries. You can install nm via cygwin, or you could copy your windows executable to a linux box and run nm on it there. You could also try dumpbin, which dumps info about a binary on Windows. You can get info on symbols with the /SYMBOLS switch, but it doesn't look like it directly provides information about their size.
1,051,611
1,059,801
Why do I get a "member function not present" error when evaluating expressions on the VC++ debugger?
I've got a static method, MyClass::myMethod() on another DLL, MyDll.dll. In my code, I call this method, and it compiles and runs fine. But when I try MyClass::myMethod() in the immediate window (or the watch window), I always get: MyClass::myMethod() CXX0052: Error: member function not present Why is that? Update: I've found out that when I use the context operator it works: {,,MyDLL}MyClass::myMethod() I'm not really sure why it's needed, though, so I'm going to wait a bit to see if someone has a nice explanation. Update 2: I was asked to give more information. Unfortunately, what I described is almost all I have. This is in third-party code. The method, which resides on a different DLL, is declared like this: class MyClass { public: // ... _declspec(dllimport) static const char *getDirectory(void); } and it is invoked like this: MyClass::getDirectory () I haven't got the source. It was compiled on Debug mode under VC++9.
Well, I'm not sure why, but the debugger isn't smart enough to know that class is in another DLL, so you have to explictly tell it by using the context operator: {,,MyDLL}MyClass::myMethod()
1,051,618
1,051,671
C++ Casting a byte binary value into a string
How do I convert 6 bytes representing a MAC address into a string that displays the address as colon-separated hex values? Thanks
You probably want a sequence of six bytes to be formatted like so: aa:bb:cc:dd:ee:ff where aa is the first byte formatted in hex. Something like this should do: char MAC[6]; //< I am assuming this has real content std::ostringstream ss; for (int i=0; i<6; ++i) { if (i != 0) ss << ':'; ss.width(2); //< Use two chars for each byte ss.fill('0'); //< Fill up with '0' if the number is only one hexadecimal digit ss << std::hex << (int)(MAC[i]); } return ss.str(); If you dearly want to do this in a cast-like style (guessing from your title here), you can create a MAC class, implement the ostream-operator for it (like my given code) and use boost::lexical_cast.
1,051,667
1,051,698
VC++: How to get the time and date of a file?
How do I get the file size and date stamp of a file on Windows in C++, given its path?
You can use FindFirstFile() to get them both at once, without having to open it (which is required by GetFileSize() and GetInformationByHandle()). It's a bit laborious, however, so a little wrapper is helpful bool get_file_information(LPCTSTR path, WIN32_FIND_DATA* data) { HANDLE h = FindFirstFile(path, &data); if(INVALID_HANDLE_VALUE != h) { return false; } else { FindClose(h); return true; } } Then the file size is available in the nFileSizeHigh and nFileSizeLow members of WIN32_FIND_DATA, and the timestamps are available in the ftCreationTime, ftLastAccessTime and ftLastWriteTime members.
1,052,102
1,052,131
Template instantiation error
I have template function "compare" defined as below. #include<iostream> using namespace std; template<typename T> void compare(const T&a, const T& b) { cout<<"Inside compare"<<endl; } main() { compare("aa","bb"); compare("aa","bbbb"); } When i instantiate compare with string literals of same length, the compiler doesnot complain. When i do it with literals of different length,it says "error: no matching function for call to compare(const char[3],const char[5])" I am confused as compare function should be instantiated with character pointer rather than character array. Should not string literals always decay to pointer?
As stated in Greg's answer and comments, the two different array types (since that's what string literals are) is the problem. You may want to leave the function as-is for generic types, but overload it for character pointers and arrays, this is mostly useful when you want to treat them slightly differently. void compare(char const* a, char const* b) { // do something, possibly use strlen() } template<int N1, int N2> void compare(char const (&a)[N1], char const (&b)[N2]) { // ... } If you want to specify that compare should take character pointers explicitly, then the arrays will automatically convert: compare<char const*>("aa", "bbbb"); On the other hand, maybe compare could be written to work with two different types? This can be useful for other types as well, e.g. maybe it calls f(a) if a.size() < b.size(), and f(b) otherwise (with f overloaded). (T1 and T2 are allowed to be the same type below, and this would replace your function instead of overloading it as the above two.) template<typename T1, typename T2> void compare(T1 const& a, T2 const& b) { // ... }
1,052,168
1,052,197
Thread-safe static variables without mutexing?
I remember reading that static variables declared inside methods is not thread-safe. (See What about the Meyer's singleton? as mentioned by Todd Gardner) Dog* MyClass::BadMethod() { static Dog dog("Lassie"); return &dog; } My library generates C++ code for end-users to compile as part of their application. The code it generates needs to initialize static variables in a thread-safe cross-platform manner. I'd like to use boost::call_once to mutex the variable initialization but then end-users are exposed to the Boost dependency. Is there a way for me to do this without forcing extra dependencies on end-users?
You are correct that static initialization like that isn't thread safe (here is an article discussing what the compiler will turn it into) At the moment, there's no standard, thread safe, portable way to initialize static singletons. Double checked locking can be used, but you need potentially non-portable threading libraries (see a discussion here). Here's a few options if thread safety is a must: Don't be Lazy (loaded): Initialize during static initialization. It could be a problem if another static calls this function in it's constructor, since the order of static initialization is undefined(see here). Use boost (as you said) or Loki Roll your own singleton on your supported platforms (should probably be avoided unless you are a threading expert) Lock a mutex everytime you need access. This could be very slow. Example for 1: // in a cpp: namespace { Dog dog("Lassie"); } Dog* MyClass::BadMethod() { return &dog; } Example for 4: Dog* MyClass::BadMethod() { static scoped_ptr<Dog> pdog; { Lock l(Mutex); if(!pdog.get()) pdog.reset(new Dog("Lassie")); } return pdog.get(); }
1,052,411
1,052,436
running ping with Qprocess, exit code always 2 if host reachable or not
i am using Qprocess to execute ping to check for a host to be online or not... The problem is that the exit code that i recieve from the Qprocess->finished signal is always 2 no matter if i ping a reachable host or an unreachable one.. I am continuously pinging in a QTimer to a host(whose one folder i have mounted at client where the Qt app is running)... when i catch the exit code as returned by ping in a slot connected to QProcess->finished signal.. i always recieve exit code as 2.. i cant use direct system call through system(ping) as it hangs my app for the time ping is active... i want it to be asynchronous so i switched to QProcess... the following is the code snippet: //Pinging function called inside a timer with timout 1000 QString exec="ping"; QStringList params; if(!dBool) { //params << "-c1 1.1.1.11 -i1 -w1;echo $?"; params <<" 1.1.1.11 -i 1 -w 1 -c 1";//wont ping cout<<"\n\npinging 11 ie wont ping"; } else { //params << "-c1 1.1.1.1 -i1 -w1;echo $?"; params <<" 1.1.1.1 -i 1 -w 1 -c 1";//will ping cout<<"\n\npinging 1 ie will ping"; } ping->start(exec,params); // the slot that connects with QProcess->finished signal void QgisApp::pingFinished( int exitCode, QProcess::ExitStatus exitStatus ) { cout<<"\n\nexitCode,exitStatus=="<<exitCode<<","<<exitStatus;//always 2,0!! if(exitCode==0) //if(dBool) { connectivity=true; cout<<"\n\nONLINE"; } else { connectivity=false; cout<<"\n\nOFFLINE"; } } the cout<<"\n\nexitCode,exitStatus=="<<exitCode<<","<<exitStatus line always gives 2,0 as output no matter if 1.1.1.1 is pinged or 1.1.1.11 is pinged on terminal 1.1.1.1 is pingable and 1.1.1.11 is not (i switch bw ips through dBool flag that is set on keypress event to simulate online/offline host so that my app can behave accordingly) Any inputs would be a great help.. Thanks.
I think it's a bad practice to rely on ping.exe exit code as it's undocumented. Furthermore it's been known that in different versions of Windows the exit code is inconsistent. You could: implement your own ping. there are plenty free implementations out there such as this (first one when searching "ping.c" in google). parse ping.exe output and determine if the ping was successful or not. EDIT: Didn't realize you're working with Linux (next time it might be wiser to mention it in your question)... Try this when sending the arguments to ping: params << "1.1.1.11" << "-i" << "1" << "-w" << "1" <<"-c" <<"1"; instead of one big string.
1,052,458
1,052,493
Defining a proper subtraction operator
I wrote an abstraction class for a math object, and defined all of the operators. While using it, I came across: Fixed f1 = 5.0f - f3; I have only two subtraction operators defined: inline const Fixed operator - () const; inline const Fixed operator - (float f) const; I get what is wrong here - addition is swappable (1 + 2 == 2 + 1) while subtraction is not (same goes for multiplication and division). I immediately wrote a function outside my class like this: static inline const Fixed operator - (float f, const Fixed &fp); But then I realized this cannot be done, because to do that I would have to touch the class's privates, which results to using the keyword friend which I loath, as well as polluting the namespace with a 'static' unnecessary function. Moving the function inside the class definition yields this error in gcc-4.3: error: ‘static const Fixed Fixed::operator-(float, const Fixed&)’ must be either a non-static member function or a non-member function Doing as GCC suggested, and making it a non-static function results the following error: error: ‘const Fixed Fixed::operator-(float, const Fixed&)’ must take either zero or one argument Why can't I define the same operator inside the class definition? if there's no way to do it, is there anyway else not using the friend keyword? Same question goes for division, as it suffers from the same problem.
If you need reassuring that friend functions can be OK: http://www.gotw.ca/gotw/084.htm Which operations need access to internal data we would otherwise have to grant via friendship? These should normally be members. (There are some rare exceptions such as operations needing conversions on their left-hand arguments and some like operator<<() whose signatures don't allow the *this reference to be their first parameters; even these can normally be nonfriends implemented in terms of (possibly virtual) members, but sometimes doing that is merely an exercise in contortionism and they're best and naturally expressed as friends.) You are in the "operations needing conversions on the left-hand arguments" camp. If you don't want a friend, and assuming you have a non-explicit float constructor for Fixed, you can implement it as: static inline Fixed operator-(const Fixed &lhs, const Fixed &rhs) { return lhs.minus(rhs); } then implement minus as a public member function, that most users won't bother with because they prefer the operator. I assume if you have operator-(float) then you have operator+(float), so if you don't have the conversion operator, you could go with: static inline Fixed operator-(float lhs, const Fixed &rhs) { return (-rhs) + lhs; // return (-rhs) -(-lhs); if no operator+... } Or just Fixed(lhs) - rhs if you have an explicit float constructor. Those may or may not be as efficient as your friend implementation. Unfortunately the language is not going to bend over backwards to accommodate those who happen to loathe one of its keywords, so operators can't be static member functions and get the effects of friendship that way ;-p
1,052,489
1,052,500
A Unique and Constant Identifier for a pthreads thread?
I presumed that a pthread_t remains constant - for a given thread - for its entire life, but my experimentation seems to be proving this assumption false. If the id for a given thread does not remain constant across its life, how can I store a pthread_t so another thread can use pthread_join to block until the thread is finished? For other reasons it would be useful for me to know how to get a unique identifier for a thread that I can convert back and forth to a pthread_t. Is there a way of doing this? There is lots of great information out there, but I've had a hard time pinning down useful answers for these questions. I'd appreciate any help/advice I can get! edit: Also, i'm not sure why, but everything seems to work as expected when adding sleep(1) and sleeping for 1sec at the front of every new thread (within the thread's function). This is probably grasping as straws, but could pthread_t values change momentarily during the start of a new thread or something??
You cannot rely on a pthread_t being unique, but you can use pthread_equal() to determine whether two thread ids refer to the same thread. NAME pthread_equal -- compare thread IDs SYNOPSIS #include <pthread.h> int pthread_equal(pthread_t t1, pthread_t t2); DESCRIPTION The pthread_equal() function compares the thread IDs t1 and t2. RETURN VALUES The pthread_equal() function will return non-zero if the thread IDs t1 and t2 correspond to the same thread. Otherwise, it will return zero.
1,052,492
1,052,501
Calling inline functions C++
I have an inline member function defined under class MyClass int MyClass::myInlineFunction(); This function is called from several places in my code. There are two ways to call this function Case 1: Using this every time the function is called. mobj->myInlineFunction() ; Case 2: Assign the result of this function to a variable and use it for subsequent accesses var = mobj->myInlineFunction() ; Which one should be preferred??
Case 2 can give you a lot of performance, if the function does something that takes some time. Choose it if you do not need side effects of the function to happen the function would always the return the same result in that context
1,052,620
1,052,648
Checking if number is even by looking at the last bit - are there any other "tricks" like this one?
Recently I discovered, that if I need to see if variable is even ( or odd ), I could just see if last bit of variable equals 0. This discovery, when implemented, replaced few modulo 2 calculations and thus, whole function ran faster. Are there any other "tricks" like this one, where working with bits could replace other calculations, leading to improved function execution time?
I doubt that replacing the use of modulo-two calculations by the equivalent bitwise operation produced faster execution times. Any C++ compiler worth its grain of salt will compile n % 2 and n & 1 to identical machine instructions. Beware of using bit-twiddling hacks as an optimization. First, it's not always clear that the function you are optimizing is a bottleneck. Second, the resulting code is usually harder to maintain and more likely to be incorrect or have subtle bugs. This is what is meant in the famous quote Knuth quote "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." Save your effort. If you truly must pursue this subject, Bit Twiddling Hacks contains a nice list of interesting hacks.
1,052,629
1,052,656
How Program Becomes a Process. How OS makes Program a process
I wanted to know How OS actually makes a program in to process. what are steps Os engages to make program a process. I mean How a Program becomes a Process, what are the parameter OS adds to kernel datastructure before making a program a process Thank you in advance.
Every operating system is going to do this in a different manner. However, in general the following steps will occur in a modern operating system: New address space created Program image loaded into an agreed upon address This may involve relocation of the image, or a dependency. Execution "context" setup Includes stack, and a call into an agreed upon "main" function by a logical thread of execution I'm glossing over lots of nasty little details, but that's a basic overview.
1,052,691
2,980,795
Trouble with QxtGlobalShortcut
I'm trying to set global shortcut for my applcation using QxtGlobalShortcut. Here is my code: QxtGlobalShortcut m_hotkeyHandle; m_hotkeyHandle.setShortcut( QKeySequence("Ctrl+Shift+X") ); m_hotkeyHandle.setEnabled(true); connect( &m_hotkeyHandle, SIGNAL(activated()), this, SLOT(hotkeyPressed()) ); void MainWindow::hotkeyPressed() { QMessageBox::information(this, "Good", "Hot key triggered", "yes", "no"); } But after applcation started i got: QxtGlobalShortcut failed to register: "Ctrl+Shift+X" And my programm doesn't activate after hot key pressing. What should i do?
There was a bug in Qxt-lib 0.5 with shortcut. I spoke with developer and knew that i just need to update library from dev-branch (0.5.1 is worked).
1,052,727
1,052,737
Thread safe singleton implementation in C++
The following is a well known implementation of singleton pattern in C++. However, I'm not entirely sure whether its thread-safe. Based upon answers to similar question asked here previously, it seems it is thread safe. Is that so? //Curiously Recurring Template Pattern //Separates a class from its Singleton-ness (almost). #include <iostream> using namespace std; template<class T> class Singleton { Singleton(const Singleton&); Singleton& operator=(const Singleton&); protected: Singleton() {} virtual ~Singleton() {} public: static T& instance() { static T theInstance; return theInstance; } }; // A sample class to be made into a Singleton class MyClass : public Singleton<MyClass> { int x; protected: friend class Singleton<MyClass>; MyClass() { x = 0; } public: void setValue(int n) { x = n; } int getValue() const { return x; } };
No, this is not thread safe because the static local is not guarded in any way. By default a static local is not thread safe. This means you could run into the following issues Constructor for the singleton runs more than once The assignment to the static is not guaranteed to be atomic hence you could see a partial assignment in multi-threaded scenarios Probably a few more that I'm missing. Here is a detailed blog entry by Raymond Chen on why C++ statics are not thread safe by default. http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx
1,052,805
1,052,986
Programatically get the web page content
I would like to know whether WinInet or WinHttp will get webpage contents quickly or is there any other quicker method for getting webpage content (less than 1 sec). The programming environment which I am using is VC++
As said by the commenters, Internet doesn't guarantee load times. As for the specific API, I'd use XMLHTTPRequest COM object instead of WinInet or WinHttp. P.S. Don't forget to call CoInitialize.
1,052,992
1,055,628
KeyboardProc returning TRUE causes performance drops
I'm developing an interface for an add-on to a game. I can't use the game API (for several reasons including the fact that the code must be game-agnostic) and I need to get keyboard input from the user so I've decided to use a keyboard hook (WH_KEYBOARD) to process user input when certain conditions are met. The problem is that while I can receive and process the input correctly, when my hook returns TRUE instead of CallNextHookEx the system seems to take up a lot of time (well over 800ms) before letting things go on as expected and that's not acceptable because it doesn't even allow for a fluid typing experience. What I have to achieve is preventing the key press message to reach the WndProc, so the question is: what can I do to achieve my target without hurting the game performance so much that the result will be unacceptable? EDIT: due to specific requirements (games using anticheats which might create problems with my code despite it's not cheating-related) subclassing the active wndproc is not an option.
As much as I don't like answering my own question I've found the cause of the delay. The message pump of the games I've tested my code against was implemented with a while(PeekMessage) { GetMessage... } and removing the keyboard input message somehow caused GetMessage to block for sometime. Using PostMessage and WM_NULL helped preventing GetMessage from blocking.