question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,358,398
2,478,893
Templates - Exercises
As I mentioned in my yesterday's post, I'm trying to teach myself templates from the book: Templates: The Complete Guide. And although I'm finding this book very nicely presented and material there is explained really well there are no exercises attached after each chapter to test your knowledge, like it is in The C++ Language by B.S for example and had done all exercises from "The C++" I really feel benefit from doing them. So what I'm asking today is: Does anyone know where can I get exercises with templates.
C++ Template Metaprogramming; Concepts, Tools, and Techniques from Boost and beyond - this book really rocks.
2,358,516
2,358,540
Iterator vs. Reference vs. Pointer
I have a class that spawns an arbitrary number of worker object that compute their results into a std::vector. I'm going to remove some of the worker objects at certain points but I'd like to keep their results in a certain ordering only known to the class that spawned them. Thus I'm providing the vectors for the output in the class A. I have (IMO) three options: I could either have pointers to the vectors, references or iterators as members. While the iterator option has certain draw backs (The iterator could be incremented.) I'm unsure if pointers or references are clearer. I feel references are better because they can't be NULL and a cruncher would require the presence of a vector. What I'm most unsure about is the validity of the references. Will they be invalidated by some operations on the std::list< std::vector<int> >? Are those operations the same as invalidating the iterators of std::list? Is there another approach I don't see right now? Also the coupling to a container doesn't feel right: I force a specific container to the Cruncher class. Code provided for clarity: #include <list> #include <vector> #include <boost/ptr_container/ptr_list.hpp> class Cruncher { std::vector<int>* numPointer; std::vector<int>& numRef; std::list< std::vector<int> >::iterator numIterator; public: Cruncher(std::vector<int>*); Cruncher(std::vector<int>&); Cruncher(std::list< std::vector<int> >::iterator); }; class A { std::list< std::vector<int> > container; boost::ptr_list< std::vector<int> > container2; std::vector<Cruncher> cruncherList; };
If an iterator is invalidated, it would also invalidate a pointer/reference that the iterator was converted into. If you have this: std::vector<T>::iterator it = ...; T *p = &(*it); T &r = *p; if the iterator is invalidated (for example a call to push_back can invalidate all existing vector iterators), the pointer and the reference will also be invalidated. From the standard 23.2.4.2/5 (vector capacity): Notes: Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. The same general principal holds for std::list. If an iterator is invalidated, the pointers and references the iterator is converted into are also invalidated. The difference between std::list and std::vector is what causes iterator invalidation. A std::list iterator is valid as long as you don't remove the element it is referring to. So where as std::vector<>::push_back can invalidate an iterator, std::list<>::push_back cannot.
2,358,524
2,358,557
Why does this separate definition cause an error?
Challenge: I have this code that fails to compile. Can you figure out what's wrong? It caused headache to me once. // header namespace values { extern std::string address; extern int port; } // .cpp file std::string ::values::address = "192.0.0.1"; int ::values::port = 12; It looks correct on the first sight. How many and which are the errors!?
One error: std::string values::address = "192.0.0.1"; is the proper form, otherwise the parse is std::string::values::address = "192.0.0.1"; and there is no member "values" with a member "address" inside "string"... it will work for builtin types, as they cannot ever contain members.. so int::values is an unambigous parse, int ::values, because the prior doesn't make sense. std::string (::values::address) = "192.0.0.1"; works too. Note that if you typedef int sometype; that you'd have the same problem using sometype as you do with string above, but not with "int".
2,358,799
2,415,794
Mapping a class and a member function
Can someone suggest me a way to map a template classes with a set of member functions from another class? Whenever i call one of the function inside a template class, it should call the associated member function of the other class. Updating with a use-case template<int walktype> class Walker { Node* node; bool walk() { switch(walktype) case 1: node->firstwalk(); case 2: node->secondwalk(); ...... } }; Please consider the above one as a pseudo-code. I want the switch-case decision to be taken at the compile time. Thanks, Gokul.
I found a way to do it using boost::mpl::map. I need to create a type out of the function and use that type as a template parameter for the class and associate this class with the original class using boost::mpl::map. Thanks, Gokul.
2,359,019
2,359,052
C++: Avoiding dual maintenance in inheritance hierarchies
When creating a C++ inheritance structure, you have to define member functions exactly the same in multiple places: If B is an abstract base class, and D, E, and F all inherit from B, you might have this: class B { virtual func A( ... params ) = 0; }; class D : public B { func A( ... params ); }; /* ... etc... similar implementations for E and F */ So, there is obviously some duplication here. If the interface to B is large, you may have many places to change if the interface needs to change. A coworker suggested some trickery with an embedded craftily-created #includes, ala: class D: public B { #include "B_Interface.h" // B_Interface.h is a specially crafted .h file } This seems a little kludgy? Is it? Is there a better solution to avoid dual maintenance? Also, maybe the solution here is really better tools to support the language, like Visual Assist X? Edit: Assume the derived classes must have unique implementations.
Actually, the biggest problem with changing an interface usually is all the code that uses it, not the code that implements it. If it's easy to change it for the implementer, it would probably make life harder for the users.
2,359,344
2,359,509
google-test: code coverage
Is it possible to get code coverage done by tests using google test framework?
Yes, I've successfully used both free (gcov) and commercial (CTC++) tools. No special steps are needed, just follow the documentation. More details can be found in this blog http://googletesting.blogspot.dk/2014/07/measuring-coverage-at-google.html
2,359,413
2,360,541
Equivalent for TzSpecificLocalTimeToSystemTime() on win2k?
One of our developers used this call: TzSpecificLocalTimeToSystemTime() but unfortunately we cannot keep it as the code must work on Win2K as well. What alternatives are there for similar functionality?
There is no equivalent, not even with WINE. It relies on timezone info stored in the registry, retrieved with GetTimeZoneInformation(). Note how the WINE code ends up in find_reg_tz_info(). That info is just missing in Win2k. You'd have to create your own timezones table.
2,359,585
2,361,295
Lining up Qt GroupBox labels
Is there an easy way to ensure that controls in different groupboxes on a Qt dialog line up correctly using layouts? If not, is there a way to line them up using code in the dialog's constructor? For example, here is a form with two groupboxes containing controls that are laid out using a grid: alt text http://lh3.ggpht.com/_4pUyapZ-mEE/S4w93l4Ab5I/AAAAAAAACQE/mJraY0z1jyI/groupbox1.png Here is how I want it to look: alt text http://lh5.ggpht.com/_4pUyapZ-mEE/S4w93rKiEBI/AAAAAAAACQI/nlt7mul79p8/groupbox2.png Note that these dialogs will end up translated into different languages so what might be the longest label in English won't necessarily be the same label in German.
I don't think there is an easy solution since you have to separated and not connected layouts. What you could do is after you set up the layouts is iterating over all label strings and measure their size with QWidget::fontMetrics() on their label widget, remeber the maximum value and call QWidget::setMinimumWidth(). That you can also do after translating strings (if you do it dynamically at run-time).
2,359,626
2,360,025
Answer to a practice interview question
I'm just going through a bunch of C++ interview questions just to make sure there's nothing obvious that I don't know. So far I haven't found anything that I didn't know already, except this: long value; //some stuff value &= 0xFFFF; The question is "what's wrong with this code?" And hints that it's something to do with target architectures. Unless the answer is just "value isn't initialized", I can't see any problem. As far as I can tell, it's just masking the 2 least significant bytes of the value, and long is guaranteed to be at least 2 bytes, so there's no problem there. Could it possibly be that long might only be 2 bytes on the target architecture, and you might be losing the sign bit? Or perhaps that the 0xFFFF is an int and int is only 2 bytes? Thanks in advance.
This problem with this code is that it does a bit-wise operation on a signed value. The results of such operations on negative values vary greatly for different integer representations. For example consider the following program: #include <iostream> int main(void) { long value; value = -1; // Some stuff value &= 0xffff; std::cout << "Value = " << value << std::endl; } On a two's-complement architecture the result is: Value = 65535 On a one's-complement architecture the result is: Value = 65534 On a sign-and-magnitude architecture the result is: Value = 1
2,359,811
2,359,993
Working with GNU regex functions in C or C++
Can anyone give me complete example program how to work with GNU regex functions in gcc C or C++ (http://docs.freebsd.org/info/regex/regex.info.GNU_Regex_Functions.html), with re_pattern_buffer, re_compile_fastmap? For example, translate this small Python program: import re unlucky = re.compile('1\d*?3') nums = ("13", "31", "777", "10003") for n in nums: if unlucky.search(n) is None: print "lucky" else: print "unlucky" Thanks!
Okay, before delving into the code, I should mention that you may want to use a higher-level library. You did say C++, so that opens you up to Boost.Regex and the like. Even if you want to stay with C, there are better options. I find the POSIX functions somewhat cleaner, not to mention more portable. // Tell GNU to define the non-standard APIs #define _GNU_SOURCE // This is actually the same header used for the POSIX API. // Except then you obviously don't need _GNU_SOURCE #include <regex.h> #include <stdio.h> #include <string.h> int main() { struct re_pattern_buffer pat_buff; // Put a re_pattern_buffer on the stack // The next 4 fields must be set. // If non-zero, applies a translation function to characters before // attempting match (http://www.delorie.com/gnu/docs/regex/regex_51.html) pat_buff.translate = 0; // If non-zero, optimization technique. Don't know details. // See http://www.delorie.com/gnu/docs/regex/regex_45.html pat_buff.fastmap = 0; // Next two must be set to 0 to request library allocate memory pat_buff.buffer = 0; pat_buff.allocated = 0; char pat_str[] = "1[^3]*3"; // This is a global (!) used to set the regex type (note POSIX APIs don't use global for this) re_syntax_options = RE_SYNTAX_EGREP; // Compile the pattern into our buffer re_compile_pattern(pat_str, sizeof(pat_str) - 1, &pat_buff); char* nums[] = {"13", "31", "777", "10003"}; // Array of char-strings for(int i = 0; i < sizeof(nums) / sizeof(char*); i++) { int match_ret; // Returns number of characters matches (may be 0, but if so there's still a match) if((match_ret = re_match(&pat_buff, nums[i], strlen(nums[i]), 0, NULL)) >= 0) { printf("unlucky\n"); } else if(match_ret == -1) // No match { printf("lucky\n"); } // Anything else (though docs say -2) is internal library error else { perror("re_match"); } } regfree(&pat_buff); } EDIT: I added more explanation of the required fields, and the regfree. I had the lucky/unlucky backwards before, which explains part of the discrepancy. The other part is that I don't think any of the regex syntaxes available here support lazy operators (*?). In this case, there's a simple fix, using "1[^3]*3".
2,359,820
2,359,873
How do I make a custom system wide mouse cursor animation?
I write software for the disabled. One of the problems is difficulty tracking the mouse pointer. I want to have the mouse cursor glow (or similar effect. Maybe water like ripples around it) when the user needs to locate it. How is this done? I know it's possible because it's used in a variety of software.
Have a look at Realworld Cursor Editor found here. Edit: As the OP pointed out, the OP was looking for a way of creating an animated cursor programmatically, using Win32API. AFAIK it cannot be done or is long-winded way of doing it, the 'LoadCursor' function can load the cursor from an embedded resource or a file on disk with an extension .ani, hence my answer in support for the usage of Realworld Cursor Editor which can create an .ani file containing animated cursors, the other way of doing it is to use the 'Control Panel' > 'Mouse', click on 'Pointers' tab-page on the dialog itself to set it as system-wide settings. Here is a sample of how an animated cursor gets loaded here. Hope this helps, Best regards, Tom.
2,360,048
2,360,052
Using STL's list object
I want to create a list of queues in C++ but the compiler gives me some cryptic messages: #include <list> #include <queue> class Test { [...] list<queue> list_queue; [...] } Output: error C2143: syntax error : missing ';' before '<' error C4430: missing type specifier - int assumed. Note: C++ does not support default-int error C2238: unexpected token(s) preceding ';' It gives me the same error even if I use int as the template paramenter. What's going on? (btw, I'm using VC++ 2008 EE)
queue is a template class as well, so you'll need to specify the element type contained in your queues. Also, - is not a legal identifier character in C++; perhaps you meant _? std::list<std::queue<SOME_TYPE_HERE> > list_queue;
2,360,063
2,360,329
PCRECPP (pcre) extract hostname from url code problem
I have this simple piece of code in c++: int main(void) { string text = "http://www.amazon.com"; string a,b,c,d,e,f; pcrecpp::RE re("^((\\w+):\\/\\/\\/?)?((\\w+):?(\\w+)?@)?([^\\/\\?:]+):?(\\d+)?(\\/?[^\\?#;\\|]+)?([;\\|])?([^\\?#]+)?\\??([^#]+)?#?(\\w*)"); if(re.PartialMatch(text, &a,&b,&c,&d,&e,&f)) { std::cout << "match: " << f << "\n"; // should print "www.amazon.com" }else{ std::cout << "no match. \n"; } return 0; } When I run this it doesn't find a match. I pretty sure that the regex pattern is correct and my code is what's wrong. If anyone familiar with pcrecpp can take a look at this Ill be grateful. EDIT: Thanks to Dingo, it works great. another issue I had is that the result was at the sixth place - "f". I edited the code above so you can copy/paste if you wish.
The problem is that your code contains ??( which is a trigraph in C++ for [. You'll either need to disable trigraphs or do something to break them up like: pcrecpp::RE re("^((\\w+):\\/\\/\\/?)?((\\w+):?(\\w+)?@)?([^\\/\\?:]+):?(\\d+)?(\\/?[^\\?#;\\|]+)?([;\\|])?([^\\?#]+)?\\??" "([^#]+)?#?(\\w*)");
2,360,116
2,360,186
How to prevent paging for one program / process?
I have a program that requires much memory, like 2/3 of all the physical ram. After some runtime my operating system begins to swap the program to hdd. But I need the program to respond very fast all the time, so I need to prevent paging for that process. How can you prevent the OS to swap one process? Thanks for any help!
At the start of the program, call: mlockall(MCL_CURRENT | MCL_FUTURE); (If you do not have the source to the program, you'll have to debauch the process with ptrace to do this). Be aware that this will increase the chances of memory allocations made by the process failing.
2,360,305
2,360,469
Noob at C++: how to do an associative array of object => value?
I'm trying to create a global (singleton) class that can associate any type of object with an integer value. I was thinking of using a map<T*, int> variable, but was wondering if there was any other way to do it. UPDATE: Here is a prototype of my class. Let me know what I'm doing wrong ! It compiles and work fine, but I'm not sure if it could be done in a better way. For instance, int addr = (int)&objectA; looks pretty ugly. UPDATE 2: I've chosen to go the inheritance way as proposed by Potatoswatter. That will be much easier considering what I'm trying to achieve. Thanks everyone for the feedback ! #include <iostream> #include <map> #include <string> using namespace std; struct PortPin { int port; int pin; }; class Carte { public: void associate(int object_address, int port, int pins); map<int, PortPin> map_; }; void Carte::associate(int object_address, int port, int pins) { PortPin values = {port, pins}; map_[object_address] = values; } class A { public: A() {} }; class B { public: B() {} }; void main() { Carte carte; A objectA; B objectB; int addr = (int)&objectA; carte.associate(addr, 2, 7); cout << "Port: " << carte.map_[addr].port << " Pin: " << carte.map_[addr].pin; }
You should use a base class. struct PortPin { int port; int pin; bool is_valid; PortPin() { is_valid = false; } void associate( int in_port, int in_pin ) { port = in_port; pin = in_pin; is_valid = true; } }; class A : public PortPin { public: A() {} }; class B : public PortPin { public: B() {} }; … A blah; A.associate(2,7); The kind of pointer arithmetic you're trying to do isn't treading water, it's treading fiery acid. It's not really that important to be able to associate any object. Were you going to associate your singleton with a PortPin? Always derive every class from an appropriate base to acquire needed services. If you're concerned about the memory (a dozen or two bytes at most) taken by the PortPin base, you can create an empty base class to give you a T* type with which to key your map. However, consider that each map entry takes three pointers plus the data, hence being at least twice as big as the PortPin struct itself. And it will leak unless you're careful, and that will cause mysterious bugs when addresses are reused. (This problem would be all but impossible to eliminate if you really can't constrain the key classes.) Finally, the map is much slower and more tedious than just accessing a field.
2,360,563
2,360,575
Why exception with this regular expression pattern (tr1::regex)?
I came accross a very strange problem with tr1::regex (VS2008) that I can't figure out the reason for. The code at the end of the post compiles fine but throws an exception when reaching the 4th regular expression definition during execution: Microsoft C++ exception: std::tr1::regex_error at memory location 0x0012f5f4.. However, the only difference I can see (maybe I am blind) between the 3rd and 4th one is the 'NumberOfComponents' instead of 'SchemeVersion'. At first I thought maybe both (3rd and 4th) are wrong and the error from the 3rd is just triggered in the 4th. That seems not to be the case as I moved both of them around and put multiple other regex definitions between them. The line in question always triggers the exception. Does anyone have any idea why that line std::tr1::regex rxNumberOfComponents("\\NumberOfComponents:(\\s*\\d+){1}"); triggers an exception but std::tr1::regex rxSchemeVersion("\\SchemeVersion:(\\s*\\d+){1}"); doesn't? Is the runtime just messing with me? Thanks for the time to read this and for any insights. T PS: I am totally sure the solution is so easy I have to hit my head against the nearest wall to even out the 'stupid question' karma ... #include <regex> int main(void) { std::tr1::regex rxSepFileIdent("Scanner Separation Configuration"); std::tr1::regex rxScannerNameIdent("\\ScannerName:((\\s*\\w+)+)"); std::tr1::regex rxSchemeVersion("\\SchemeVersion:(\\s*\\d+){1}"); std::tr1::regex rxNumberOfComponents("\\NumberOfComponents:(\\s*\\d+){1}"); std::tr1::regex rxConfigStartIdent("Configuration Start"); std::tr1::regex rxConfigEndIdent("Configuration End"); return 0; }
You need to double-escape your backslashes - once for the regex itself, a second time for the string they're in. The one that starts with S works because \S is a valid regex escape (non-whitespace characters). The one that starts with N does not (because \N is not a valid regex escape). Instead, use "\\\\SchemeVersion: et cetera.
2,360,588
2,360,600
C++ const iterator C2662
Having problems iterating. Problem has to do with const correctness, I think. I assume B::getGenerate() should be const for this code to work, but I don't have control over B::getGenerate(). Any help is greatly appreciated. Thanks in advance, jbu Code follows: int A::getNumOptions() const { int running_total = 0; BList::const_iterator iter = m_options.begin(); while(iter != m_options.end()) { if(iter->getGenerate()) //this is the line of the error; getGenerate() returns bool; no const in signature { running_total++; } } return running_total; } 1>.\A.cpp(118) : error C2662: 'B::getGenerate()' : cannot convert 'this' pointer from 'const B' to 'B &'
Well, if getGenerate is non-const, your iterator must be non-const. And if that's the case, your getNumOptions will also have to be non-const. If getGenerate isn't under you control, there isn't anything else you can do. But if that method could be const, bring it up with whoever implemented that method; tell them it should be const.
2,360,597
2,360,673
C++ Exceptions questions on rethrow of original exception
Will the following append() in the catch cause the rethrown exception to see the effect of append() being called? try { mayThrowMyErr(); } catch (myErr &err) { err.append("Add to my message here"); throw; // Does the rethrow exception reflect the call to append()? } Similarly, if I rewrite it this way, will bit slicing occur if the actual exception is derived by myErr? try { mayThrowObjectDerivedFromMyErr(); } catch (myErr &err) { err.append("Add to my message's base class here"); throw err; // Do I lose the derived class exception and only get myErr? }
In both cases, since you catch by reference, you are effectively altering the state of the original exception object (which you can think of as residing in a magical memory location which will stay valid during the subsequent unwinding -- 0x98e7058 in the example below). However, In the first case, since you rethrow with throw; (which, unlike throw err;, preserves the original exception object, with your modifications, in said "magical location" at 0x98e7058) will reflect the call to append() In the second case, since you throw something explicitly, a copy of err will be created then thrown anew (at a different "magical location" 0x98e70b0 -- because for all the compiler knows err could be an object on the stack about to be unwinded, like e was at 0xbfbce430, not in the "magical location" at 0x98e7058), so you will lose derived-class-specific data during the copy-construction of a base class instance. Simple program to illustrate what's happening: #include <stdio.h> struct MyErr { MyErr() { printf(" Base default constructor, this=%p\n", this); } MyErr(const MyErr& other) { printf(" Base copy-constructor, this=%p from that=%p\n", this, &other); } virtual ~MyErr() { printf(" Base destructor, this=%p\n", this); } }; struct MyErrDerived : public MyErr { MyErrDerived() { printf(" Derived default constructor, this=%p\n", this); } MyErrDerived(const MyErrDerived& other) { printf(" Derived copy-constructor, this=%p from that=%p\n", this, &other); } virtual ~MyErrDerived() { printf(" Derived destructor, this=%p\n", this); } }; int main() { try { try { MyErrDerived e; throw e; } catch (MyErr& err) { printf("A Inner catch, &err=%p\n", &err); throw; } } catch (MyErr& err) { printf("A Outer catch, &err=%p\n", &err); } printf("---\n"); try { try { MyErrDerived e; throw e; } catch (MyErr& err) { printf("B Inner catch, &err=%p\n", &err); throw err; } } catch (MyErr& err) { printf("B Outer catch, &err=%p\n", &err); } return 0; } Result: Base default constructor, this=0xbfbce430 Derived default constructor, this=0xbfbce430 Base default constructor, this=0x98e7058 Derived copy-constructor, this=0x98e7058 from that=0xbfbce430 Derived destructor, this=0xbfbce430 Base destructor, this=0xbfbce430 A Inner catch, &err=0x98e7058 A Outer catch, &err=0x98e7058 Derived destructor, this=0x98e7058 Base destructor, this=0x98e7058 --- Base default constructor, this=0xbfbce430 Derived default constructor, this=0xbfbce430 Base default constructor, this=0x98e7058 Derived copy-constructor, this=0x98e7058 from that=0xbfbce430 Derived destructor, this=0xbfbce430 Base destructor, this=0xbfbce430 B Inner catch, &err=0x98e7058 Base copy-constructor, this=0x98e70b0 from that=0x98e7058 Derived destructor, this=0x98e7058 Base destructor, this=0x98e7058 B Outer catch, &err=0x98e70b0 Base destructor, this=0x98e70b0 Also see: Scope of exception object in C++ Throwing ... "by reference"
2,360,649
2,365,474
GC with C# and C++ in same solution
I have a solution consisting of a number of C# projects. It was written in C# to get it operational quickly. Garbage collections are starting to become an issue—we are seeing some 100 ms delays that we'd like to avoid. One thought was to re-write it in C++, project by project. But if you combine C# with unmanaged C++, will the threads in the C++ projects also be frozen by garbage collections? UPDATE Thanks for your replies. This is, in fact, an app where 100 ms might be significant. It was probably a poor decision to build it in C#, but it was essential that it be up and running quickly at the time. Right now, we're using Windows' Multimedia Timers to fire an event every 5 ms. We do see some 100+ ms gaps, and we've confirmed by checking the GC counters that these always occur during a collection. Optimization is on; built in Release mode.
I work as a .NET developer at a trading firm where, like you, we care about 100 ms delays. Garbage collection can indeed become a significant issue when dependable minimal latency is required. That said, I don't think migrating to C++ is going to be a smart move, mainly due to how time consuming it would be. Garbage collection occurs after a certain amount of memory has been allocated on the heap over time. You can substantially mitigate this issue by minimizing the amount of heap allocation your code creates. I'd recommend trying to spot methods in your application that are responsible for significant amounts of allocation. Anywhere objects are constructed is going to be a candidate for modification. A classic approach to fighting garbage collection is utilizing resource pools: instead of creating a new object every time a method is called, maintain a pool of already-constructed objects, borrowing from the pool on every method call and returning the object to the pool once the method has completed. Another no-brainer involves hunting down any ArrayList, HashTable, or similar non-generic collections in your code that box/unbox value types, leading to totally unnecessary heap allocation. Replace these with List<T>, Dictionary<TKey, TValue>, and so on wherever possible (here I am specifically referring to collections of value types such as int, double, long, etc.). Likewise, look out for any methods you may be calling which box value type arguments (or return boxed value types). These are just a couple of relatively small steps you can take to reducing your garbage collection count, but they can make a big difference. With enough effort it can even be possible to completely (or at least nearly) eliminate all generation 2 garbage collections during the continuous operations phase (everything except for startup and shutdown) of your application. And I think you'll find that generation 2 collections are the real heavy-hitters. Here's a paper outlining one company's efforts to minimize latency in a .NET application through resource pooling, in addition to a couple of other methods, with great success: Rapid Addition leverages Microsoft .NET 3.5 Framework to build ultra-low latency FIX and FAST processing So to reiterate: I would strongly recommend investigating ways to modify your code so as to cut down on garbage collection over converting to an entirely different language.
2,361,040
2,361,057
Calling member level functions from a dynamic link library using pinvoke in C#?
How would I use DLLImport pinvoke to invoke a function i wrote in a class in an unmanaged DLL? It always throws that the entry point doesn't exist in the dll. EX: class Foo { int __declspec(dllexport) Bar() {return 0;} }; Bar is in the Foo class. when I use pinvoke as: [DLLImport("Test.dll")] public static extern int Bar(); When using it i get an exception saying that the entry point does not exist in the DLL. Is it possible to call functions directly from classes?
Not easily... To call a member function, the first "hidden" argument has to be a pointer to the C++ class who's member function you are calling. And C++ functions are name mangeled, so you need to find the name mangeled name of the function you are calling. In short: It is easier to create a C++/CLI wrapper of your C++ class to do this.
2,361,223
2,364,938
crash - adding to a map and set STL - c++
I have a cd , dvd. book media program. Currently, i am trying to add book information to a set. I am getting a nasty crash. error: Unhandled exception at 0x00449d76 in a04xc.exe: 0xC0000005: Access violation reading location 0x00000014. So, obviously its trying to access memory its not suppose to? just not sure why or what i need to do to add information? Its coming from this line in this function... const Item* Library::addBook(const string& title, const string& author, const int nPages) { Book* item = new Book(title,author,nPages); allBooks.insert(item); // add to set of all books allBooksByAuthor[author]->insert(item); // causing error.. return item; } here is the driver.. // add items to library cout << ">>> adding items to library:\n\n"; item = library->addBook("The Curious Incident of the Dog in the Night-Time", "Mark Haddon", 240); if (item != NULL) { library->addKeywordForItem(item, "autism"); library->addKeywordForItem(item, "Asperger's Syndrome"); library->printItem(cout, item); } here is part of the library cpp where i am having problems with addbooks function #include "Library.h" #include "book.h" ItemSet allBooks; // for my sets defined in the Items cpp ItemSetMap allBooksByAuthor; void Library::addKeywordForItem(const Item* item, const string& keyword) { //item->addKeyword(keyword); } const ItemSet* Library::itemsForKeyword(const string& keyword) const { return NULL; } void Library::printItem(ostream& out, const Item* const item) const { } // book-related functions const Item* Library::addBook(const string& title, const string& author, const int nPages) { Book* item = new Book(title,author,nPages); allBooks.insert(item); // add to set of all books allBooksByAuthor[author]->insert(item); // add to set of books by this author return item; } here is the items class #pragma once #include <ostream> #include <map> #include <set> #include <string> #include "Item.h" using namespace std; typedef set<Item*> ItemSet; typedef map<string,Item*> ItemMap; typedef map<string,ItemSet*> ItemSetMap; class Library { public: // general functions void addKeywordForItem(const Item* const item, const string& keyword); const ItemSet* itemsForKeyword(const string& keyword) const; void printItem(ostream& out, const Item* const item) const; // book-related functions const Item* addBook(const string& title, const string& author, int const nPages); const ItemSet* booksByAuthor(const string& author) const; const ItemSet* books() const; // music-related functions const Item* addMusicCD(const string& title, const string& band, const int nSongs); void addBandMember(const Item* const musicCD, const string& member); const ItemSet* musicByBand(const string& band) const; const ItemSet* musicByMusician(const string& musician) const; const ItemSet* musicCDs() const; // movie-related functions const Item* addMovieDVD(const string& title, const string& director, const int nScenes); void addCastMember(const Item* const movie, const string& member); const ItemSet* moviesByDirector(const string& director) const; const ItemSet* moviesByActor(const string& actor) const; const ItemSet* movies() const; }; here is book.h #ifndef BOOK_H #define BOOK_H #pragma once #include "item.h" using namespace std; class Book : public Item { public: Book(const string& title, const string& author, const int nPages); ~Book(); const int getPages() const; const string getAuthor() const; virtual void print(ostream& out) const; private: int numPages; string Author; }; ostream& operator<<(ostream& out, const Book* book); #endif I am just learning STL and i am having a hard time learning whats going on here. i understand set. I am just not sure in my situation map is for? is it adding item to author? and them adding them both to ItemSetMap? typedef set<Item*> ItemSet; typedef map<string,Item*> ItemMap; typedef map<string,ItemSet*> ItemSetMap; so, how can i fix this crash? am i not adding author to item correctly? Thank You..
The correct answer is to change the map to contain set objects, rather than pointers, as JonM says. However, if you are constrained to store pointers, then you will need to manually create a new set when it's needed. For a new author, using allBooksByAuthor[author] will insert a new entry with a null pointer, which you mustn't dereference. In that case, you'll need to create a new set and update the pointer in the map. You could also look at allBooksByAuthor.find(author), which has different behaviour for a new author. You'll then need to make sure that the sets are deleted when they are removed from the map, and any remaining ones are deleted when the map is deleted, otherwise the memory allocated for them will be lost for ever. This kind of resource leak is one reason why you should never deal with raw pointers like this; storing objects in the map would completely take care of memory management for you. Since this is homework, I won't give you any code - this should be enough to get you started.
2,361,258
2,361,268
Unable to open file from C++ DLL
I have an application for which GUI is written in C# and the logic is written in C++ DLL. The DLL should open a file to read data from it. I have the data.txt file in the same folder as the DLL. When I call fopen("data.txt","r") the value returned is NULL. What could be the problem? Please help me in this regard. Thanks, Rakesh.
The location of the dll file is not relevant. The path of your open must contain the complete path or the file will be opened to your applications current working directory.
2,361,290
2,361,489
Moving objects from one Boost ptr_container to another
I want to move certain element from a to b: boost::ptr_vector<Foo> a, b; // ... b.push_back(a.release(a.begin() + i))); The above code does not compile because the release function returns boost::ptr_container_detail::static_move_ptr<...>, which is not suitable for pushing back. How should I proceed? EDIT: I found out that the object returned has .get() .release() that provides a raw pointer (that may also lead to some exception safety issues). I would, however, prefer not relying on undocumented internal functionality, so feel free to share any better solutions...
boost::ptr_vector<Foo> a, b; // transfer one element a[i] to the end of b b.transfer( b.end(), a.begin() + i, a ); // transfer N elements a[i]..a[i+N] to the end of b b.transfer( b.end(), a.begin() + i, a.begin() + i + N, a );
2,361,388
2,362,467
How to workaround gcc-3.4 bug (or maybe this is not a bug)?
Following code fails with a error message : t.cpp: In function `void test()': t.cpp:35: error: expected primary-expression before '>' token t.cpp:35: error: expected primary-expression before ')' token Now I don't see any issues with the code and it compiles with gcc-4.x and MSVC 2005 but not with gcc-3.4 (which is still quite popular on some platforms). #include <string> #include <iostream> struct message { message(std::string s) : s_(s) {} template<typename CharType> std::basic_string<CharType> str() { return std::basic_string<CharType>(s_.begin(),s_.end()); } private: std::string s_; }; inline message translate(std::string const &s) { return message(s); } template<typename TheChar> void test() { std::string s="text"; std::basic_string<TheChar> t1,t2,t3,t4,t5; t1=translate(s).str<TheChar>(); // ok char const *tmp=s.c_str(); t2=translate(tmp).str<TheChar>(); // ok t3=message(s.c_str()).str<TheChar>(); // ok t4=translate(s.c_str()).str<TheChar>(); // fails t5=translate(s.c_str()).template str<TheChar>(); // ok std::cout << t1 <<" " << t2 <<" " << t3 << " " << t4 << std::endl; } int main() { test<char>(); } Is it possible to workaround it on the level of translate function and message class, or maybe my code is wrong, if so where? Edit: Bugs related to template-functions in GCC 3.4.6 says I need to use keyword template but should I? Is this a bug? Do I have to write a template keyword? Because in all other cases I do not have to? And it is quite wired I do not have to write it when I use ".c_str()" member function. Why gcc-4 not always an option This program does not starts when compiled with gcc-4 under Cygwin #include <iostream> #include <locale> class bar : public std::locale::facet { public: bar(size_t refs=0) : std::locale::facet(refs) { } static std::locale::id id; }; std::locale::id bar::id; using namespace std; int main() { std::locale l=std::locale(std::locale(),new bar()); std::cout << has_facet<bar>(l) << std::endl; return 0; } And this code does not compiles with gcc-4.3 under OpenSolaris 2009- broken concepts checks... #include <map> struct tree { std::map<int,tree> left,right; };
As mentioned elsewhere, that seems to be a compiler bug. Fair enough; those exist. Here's what you do about those: #if defined(__GNUC__) && __GNUC__ < 4 // Use erroneous syntax hack to work around a compiler bug. t4=translate(s.c_str()).template str<TheChar>(); #else t4=translate(s.c_str()).str<TheChar>(); #endif GCC always defines __GNUC__ to the major compiler version number. If you need it, you also get __GNUC_MINOR__ and __GNUC_PATCHLEVEL__ for the y and z of the x.y.z version number.
2,361,517
2,361,543
Problem with Visual C++ program-- can't find the Debug CRT
I have a friend who's taking over a Visual C++ project from me and is having trouble running it. It's a graphics application and it uses the Qt GUI library. The reason I mention this is because of the error below. He can build and link the program using Visual Studio 2010, but when he runs it this message comes up in the event viewer: Activation context generation failed for "D:\Test\Qt\4.2.2\bin\QtGuid4.dll". Dependent Assembly Microsoft.VC80.DebugCRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b", type="win32", version="8.0.50608.0" could not be found. Please use sxstrace.exe for detailed diagnosis. When we do as the message asks and run sxstrace.exe, here's what we see: Begin Activation Context Generation. Input Parameter: Flags = 0 ProcessorArchitecture = Wow32 CultureFallBacks = en-US;en ManifestPath = D:\Test\Qt\4.2.2\bin\QtGuid4.dll AssemblyDirectory = D:\Test\Qt\4.2.2\bin\ --------------- INFO: Parsing Manifest File D:\Test\Qt\4.2.2\bin\QtGuid4.dll. INFO: Manifest Definition Identity is (null). INFO: Reference: Microsoft.VC80.DebugCRT,processorArchitecture="x86"type="win32",version="8.0.50608.0" INFO: Resolving reference Microsoft.VC80.DebugCRT,processorArchitecture="x86""win32",version="8.0.50608.0". INFO: Resolving reference for ProcessorArchitecture WOW64. INFO: Resolving reference for culture Neutral. INFO: Applying Binding Policy. INFO: No publisher policy found. INFO: No binding policy redirect found. INFO: Begin assembly probing. INFO: Did not find the assembly in WinSxS. INFO: Attempt to probe manifest at C:\Windows\assembly\GAC_32\Microsoft.VC80.DebugCRT\8.0.50608.0__1fc8b3b9a1e18e3b\Microsoft.VC80.DebugCRT.DLL. INFO: Did not find manifest for culture Neutral. INFO: End assembly probing. INFO: Resolving reference for ProcessorArchitecture x86. INFO: Resolving reference for culture Neutral. INFO: Applying Binding Policy. INFO: No publisher policy found. INFO: No binding policy redirect found. INFO: Begin assembly probing. INFO: Did not find the assembly in WinSxS. INFO: Attempt to probe manifest at C:\Windows\assembly\GAC_32\Microsoft.VC80.DebugCRT\8.0.50608.0__1fc8b3b9a1e18e3b\Microsoft.VC80.DebugCRT.DLL. INFO: Attempt to probe manifest at D:\Test\Qt\4.2.2\bin\Microsoft.VC80.DebugCRT.DLL. INFO: Attempt to probe manifest at D:\Test\Qt\4.2.2\bin\Microsoft.VC80.DebugCRT.MANIFEST. INFO: Attempt to probe manifest at D:\Test\Qt\4.2.2\bin\Microsoft.VC80.DebugCRT\Microsoft.VC80.DebugCRT.DLL. INFO: Attempt to probe manifest at D:\Test\Qt\4.2.2\bin\Microsoft.VC80.DebugCRT\Microsoft.VC80.DebugCRT.MANIFEST. INFO: Did not find manifest for culture Neutral. INFO: End assembly probing. ERROR: Cannot resolve reference Microsoft.VC80.DebugCRT,processorArchitecture="x86", publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50608.0". Sorry for the length of that message, but I thought it might jog some memories. Is this a case of his not having the Visual C++ 2005 (I believe that's where the VC80 comes from) C runtime libraries installed? If so, can he download the VC++ redistribution package and install it, and will all be well then? Or is this a completely different problem?
If your friend doesn't have VS2005 installed, he will not have the debug runtime libraries for it. They're not part of the redistributable runtimes and IIRC, Microsoft prohibits you from distributing them yourself so you have to have VS2005 installed in order to get them. I would suggest that he'd rebuild the affected library if possible; I vaguely recollect that there are a couple of articles out on the web on how to rebuilding the GPL QT using Visual Studio, which I believe is not officially supported. Mixing C++ runtimes requires a lot of care and you can fall into a fairly nasty trap if you don't get it exactly right. If rebuilding all libraries with VS2010 is not an option, your friend will have to get hold of VS2005. It might be worth checking if MS still offers the Express Edition of VS2005 for download.
2,361,523
2,361,535
string to PCWSTR -> strange return(C++)
i'm really new to C++-programming and i've got an a problem with writing into a xml document. I'm using a slightly changed example of xml outputter from msdn (http://msdn.microsoft.com/en-us/library/ms766497(VS.85).aspx). HRESULT CreateAndAddTestMethodNode(string name) { HRESULT hr = S_OK; IXMLDOMElement* pElement = NULL; CHK_HR(CreateAndAddElementNode(pXMLDom, L"method", L"\n\t", pClass, &pMethod)); CHK_HR(CreateAndAddAttributeNode(pXMLDom, L"name", stringToPCWSTR(name), pMethod)); //more Attribute Nodes (deleted for better overview ;) ) CleanUp: SAFE_RELEASE(pMethod); return hr } I'm giving a string to CreateAndAddTestMethodNode which convert it with stringtopcwstr to a pcwstr, or should do it. //convert string to pcwstr PCWSTR stringToPCWSTR (const std::string& str) { int len; int slength = (int)str.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, buf, len); std::wstring result(buf); delete[] buf; PCWSTR pResult = result.c_str(); return pResult; } But it only returns something like "0x00bb9908 "ﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮ" which causes an access violation in one of the next methods. It would be really great if someone could give me clue where i did the failure. Thank You.
The result of c_str() gets destroyed along with the result string (when it goes out of scope). You will need to explicitly allocate memory for it.
2,361,530
2,361,550
Error in compiling C++ code?
This is my test.cpp: #include <iostream.h> class C { public: C(); ~C(); }; int main() { C obj; return 0; } When I compile it using the command g++ test.cpp, I get this error message: In file included from /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/backward/iostream.h:31, from test.cpp:1: /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/backward/backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header. Please consider using one of the 32 headers found in section 17.4.1.2 of the C++ standard. Examples include substituting the header for the header for C++ includes, or instead of the deprecated header . To disable this warning use -Wno-deprecated. /cygdrive/c/Users/aswinik_sattaluri/AppData/Local/Temp/ccoYkiAS.o:test.cpp:(.text+0x131): undefined reference to `C::C()' /cygdrive/c/Users/aswinik_sattaluri/AppData/Local/Temp/ccoYkiAS.o:test.cpp:(.text+0x13c): undefined reference to `C::~C()' collect2: ld returned 1 exit status Compiling with gcc test.cpp gives similar messages and even more: In file included from /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/backward/iostream.h:31, from test.cpp:1: /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/backward/backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header. Please consider using one of the 32 headers found in section 17.4.1.2 of the C++ standard. Examples include substituting the header for the header for C++ includes, or instead of the deprecated header . To disable this warning use -Wno-deprecated. /cygdrive/c/Users/aswinik_sattaluri/AppData/Local/Temp/cc3ntGx0.o:test.cpp:(.text+0xd): undefined reference to `std::basic_string, std::allocator >::size() const' /cygdrive/c/Users/aswinik_sattaluri/AppData/Local/Temp/cc3ntGx0.o:test.cpp:(.text+0x60): undefined reference to `std::basic_string, std::allocator >::operator[](unsigned int) const' /cygdrive/c/Users/aswinik_sattaluri/AppData/Local/Temp/cc3ntGx0.o:test.cpp:(.text+0x9f): undefined reference to `std::basic_string, std::allocator >::operator[](unsigned int) const' /cygdrive/c/Users/aswinik_sattaluri/AppData/Local/Temp/cc3ntGx0.o:test.cpp:(.text+0xce): undefined reference to `std::basic_string, std::allocator >::operator[](unsigned int) const' /cygdrive/c/Users/aswinik_sattaluri/AppData/Local/Temp/cc3ntGx0.o:test.cpp:(.text+0x131): undefined reference to `C::C()' /cygdrive/c/Users/aswinik_sattaluri/AppData/Local/Temp/cc3ntGx0.o:test.cpp:(.text+0x13c): undefined reference to `C::~C()' /cygdrive/c/Users/aswinik_sattaluri/AppData/Local/Temp/cc3ntGx0.o:test.cpp:(.text+0x165): undefined reference to `std::ios_base::Init::Init()' /cygdrive/c/Users/aswinik_sattaluri/AppData/Local/Temp/cc3ntGx0.o:test.cpp:(.text+0x180): undefined reference to `std::ios_base::Init::~Init()' collect2: ld returned 1 exit status Note that I haven't set LD_LIBRARY_PATH: bash-3.2$ echo $LD_LIBRARY_PATH bash-3.2$
You have declared the existence of the C constructor and destructor, but have not provided implementations. Try: class C { public: C() {} ~C() {} }; And, for C++ programs, use g++ to compile (as in your first attempt).
2,361,717
2,361,928
Adding member functions to a Boost.Variant
In my C++ library I have a type boost::variant<A,B> and lots of algorithms getting this type as an input. Instead of member functions I have global functions on this type, like void f( boost::variant<A,B>& var ). I know that this can also be achieved with templates, but this is not suitable for my design. I am very fine with this style of programming: boost::variant<A, B> v; f( v ); but some of the users of this library are not used to it, and since the Boost.Variant concept is hidden by a type definition, they feel like calling v.f(). To achieve this, I can think of two possibilities: 1) overriding from boost::variant and 2) re-implementing boost::variant and adding my own member functions. I am not sure whether these ideas are good or not. Can you give me some help with this please? Are there other possibilities?
Another possibility: Use aggregation. Then you do not directly expose the boost.variant to the users of the library, giving you way more freedom for future improvements, and may simplify some debugging tasks by a significant amount. General Advice: Aggregation is less tightly coupled than inheritance, therefore better by default, except you know a use-case where you explicitly want to pass your object instance to already existing functions only taking variants. And even than the base class should have been designed with inheritance in mind. Example for Aggregation for Your Problem: As far as I understand it, the free functions already exist, and take a variant. Just define a class with the sole data member of the variant, and provide public member functions which do nothing but invoke the already existing free functions with the member variant, like class variant_wrapper { boost::variant<A,B> m_variant; public: variant_wrapper(...) : m_variant(...) {} // whatever c_tor you need. void f() { f(m_variant); } }; Using this approach you abstract away the fact that you are using boost.variant for your implementation (which you already do through a typedef for the library's users), giving you the freedom of later changing that (for optimization or feature extensions or whatever), you can decide to make the values immutable, have a more simple approach to debug accesses to your algorithms, etc. etc.. The disadvantage with the aggregation is that you cannot just pass the wrapper to a static_visitor, but as your users shall not know that there is a variant, and you know to simply pass the member variable, I do not see a big issue here. Final rant: C++ is not Java. You need to fix the users of the library... What you would like to have are C# extension methods; such things do not exist in C++. However, I would not reimplement/implementation-copy boost.variant (maintenance burden), and I would not inherit from it. Use aggregation where possible.
2,361,750
2,362,744
BOOST_FOREACH implicit use of reference?
I am wondering if there is any benefit to getting a reference to a vector prior to calling BOOST_FOREACH or whether a method call which returns a reference will be automatically used? For example which of the two following loops will be equivalent to the third loop? vector<float>& my_method(); void main() { // LOOP 1 ------------------------------- vector<float>& temp_vector = my_method(); BOOST_FOREACH(float element, temp_vector) cout << element << endl; // LOOP 2 ------------------------------- vector<float> temp_vector = my_method(); BOOST_FOREACH(float element, temp_vector) cout << element << endl; // Which loop is this one most like? ---- BOOST_FOREACH(float element, my_method()) cout << element << endl; }
Looking through BOOST_FOREACH metaprogramming madness I see that the collection gets copied if it's an rvalue, a "lightweight proxy", which you can define for your types by specializing boost::foreach::is_lightweight_proxy. Hence, lvalue is not copied. Instead, its pointer is taken as a temporary. Crucial bit is this: # define BOOST_FOREACH_SHOULD_COPY(COL) \ (true ? 0 : boost::foreach_detail_::or_( \ BOOST_FOREACH_IS_RVALUE(COL) \ , BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL))) Then it's used as one of the arguments to the function that is used to evaluate a container into a temporary variable: template<typename T> inline auto_any<T> contain(T const &t, boost::mpl::true_ *) // rvalue { return t; } template<typename T> inline auto_any<T *> contain(T &t, boost::mpl::false_ *) // lvalue { // Cannot seem to get sunpro to handle addressof() with array types. #if BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x570)) return &t; #else return boost::addressof(t); #endif } I have Boost v1.38 installed in my system.
2,361,873
2,362,206
Forward declare a global type inside a namespace
I want to use an 3rd party library without using its header file. My code resides in its own namespace, therefore I can't use conventional forward declaration as I don't want to pollute the global namespace. Currently I have something like that: 3rd-party-library.h---- typedef struct {...} LibData; void lib_func (LibData *); my-source.h----- namespace foo { /*forward declaration of LibData*/ class Abcd { public: void ghj(); private: Libdata *data_; }; }//namespace foo my-source.cpp----- #include "my-source.h" #include <3rd-party-library.h> namespace foo { typedef ::LibData LibData; void Abcd::ghj() { //do smth with data_ } }//namespace foo Is it possible to forward declare a global type in a way that it would reside in an namespace? Plain simple typedef does not work.
For a forward declaration to work, you need to forward declare an object in the proper namespace. Since the original object resides in the global namespace, you need to forward declare it in the global namespace. If you don't like that, you can always wrap the thing in your own structure: namespace foo { struct libDataWrapper; } and in your own cpp define this structure. Or you can always resort to void* and the like, if you're up to that sort of thing.
2,361,927
2,361,940
Pointer to [-1]th index of array
How does a pointer points to [-1]th index of the array produce legal output everytime. What is actually happening in the pointer assignment? #include<stdio.h> int main() { int realarray[10]; int *array = &realarray[-1]; printf("%p\n", (void *)array); return 0; } Code output: manav@workstation:~/knr$ gcc -Wall -pedantic ptr.c manav@workstation:~/knr$ ./a.out 0xbf841140 EDIT: If this scenario is valid, then can i use this to define an array whose index start from 1 instead of 0, namely: array[1], array[2],...
Youre simply getting a pointer that contains the address of that "imaginary" location, i.e. the location of the first element &realarray[0] minus the size of one element. This is undefined behavior, and might break horribly if, for instance, your machine has a segmented memory architecture. It's working because the compiler writer has chosen to implement the arithmetic as outlined above; that could change at any moment, and another compiler might behave totally differently.
2,361,934
2,361,990
Unable to write to console screen from C++ DLL
I want to print messages onto the console screen from a C++ DLL. The front end for this application is in C#. I used AllocConsole() fundtion to create a console from the C++ DLL. The window is being created but no messages were being printed when I try to print a message. Please help me fix this problem. Thanks, Rakesh.
You need to redirect your output stream to the newly created console. freopen("conin$", "r+t", stdin); freopen("conout$", "w+t", stdout); freopen("conout$", "w+t", stderr);
2,361,944
2,365,834
How to Save custom DockWidgets
I want to save my custom DockWidgets (inherited from QDockWidget) with the saveState() / restoreState() function my MainWindow provides. I have two questions: 1. How can I save and restore my Dockwidgets? - I already tried registering my custom DockWidgets as a QMetaType and implementing the default Constructor, copy Constructor, Destructor and Streaming operators. 2. How can I identify the loaded DockWidgets? - For example: If 2 DockWidgets where saved and I load them with restoreState(), is there a way to get pointers to these loaded Widgets? Thanks, Tobias
Did you read the QMainWindow::saveState documentation? Are your objects uniquely named? (QObject::setObjectName) As a side note, QObjects should NOT have a copy constructor, see Q_DISABLE_COPY
2,362,097
2,362,117
Why is the size of an empty class in C++ not zero?
Possible Duplicate: C++: What is the size of an object of an empty class? Why does the following output 1? #include <iostream> class Test { }; int main() { std::cout << sizeof(Test); return 0; }
The standard does not allow objects (and classes thereof) of size 0, since that would make it possible for two distinct objects to have the same memory address. That's why even empty classes must have a size of (at least) 1.
2,362,152
2,362,179
Assigning char value in one array to char value in another array
Sounds easy, but I've got a bug and I'm not sure what's causing it? nopunccount = 0; char *ra = new char[sizeof(npa)]; while (nopunccount <= strlen(npa)) { ra[nopunccount] = npa[strlen(npa) - nopunccount]; nopunccount++; } ra never gets a value into it and I have verified that npa has char values to provide within the nopunccount range. Any help is appreciated // :)
nopunccountstarts as 0, so in the first iteration of the loop the character assigned to ra[0] is npa[strlen(npa)]. This is the terminating '\0' of that string. So the resulting string in ra starts with a '\0' and is therefore considered to be ending at that first byte by the usual string functions.
2,362,454
2,362,490
Checking if an iterator references an item in a list
i just want to check, if the iterator points on an object in a list. What's the cmd? Thank you. :) SkyThe EDIT: Hmm,.. ok i tried it. Now there is a Error: "Expression: list iterators incompitable" Maybe some code: #include <list> list<obj> list; list<obj>::iterator it; if(it != list.end()){ //here the error pops up when i debug vShowStatus(); }else{ cout << "..."; }
if (it!=collection.end()) std::cout << "Iterator points to data" << std::endl; else std::cout << "Iterator does not point to data" << std::endl;
2,362,694
2,362,957
How to represent this "tree" data?
Ive got some data (not that the data actually exists until after I solved this...) I need to be able to manipulate within my program. However I cant work out a suitable structure for storing this in. The data represents a set of paths and nodes. There is one input (which may in some cases no be present) then a number of paths between nodes ending with outputs (an end may not have an output, but an output is always at the end). Each input, node and output has a position, and the data overall can be manipulated graphically, so whatever structure I use needs to be easy to change the contents of at runtime in potentially unpredictable ways (such as changing the input to an output, and then making another output the input). I considered using a tree structure where each item had a parent (except root) and a number of children, eg like: Input | node--- | | | | | Output | | | Node---Output | |---Output | Node----Node | | Node Output However I can see a number of problems with this such as if there is no input, or its removed / changed / etc... This is a visual example. The > is an input O nodes and [] outputs. http://unisonmodules.co.uk/wjnewbery/data.png @Everyone suggesting using a tree structure like I already mentioned If a tree is in fact suitable, how do I overcome the issues where a given set of data doesn't even have an input/root, like say the one below. What happens then? Do I need to totally rebuild the tree if the input node/point/whatever changes (via a remove then add)? How do I do that? http://unisonmodules.co.uk/wjnewbery/data2.png I'll take a look at graphs.
Seems you should really need more freeform structure than a tree. Each node can have a number of nodes connected to it; each connection has a direction. Any node can have input or output attached. Enforcing no circular connections and only one input would be up to you upon tree creation and update. The structures could be multiply linked lists and go like this: struct Node { NodeContentType type; //Input, Output, None. InOutNode* content; //pointer to input or output Link* links; //pointer to first connection (if any), NULL if none. } struct Link { Node* node; //node this connection links to. Link* next; //pointer to next connection } Example tree: INPUT | root | branch1---leaf2---output2 | leaf1 | output1 could go like this: (order is obviously wrong...) Node root = { Input, &input_function, &link1 }; Link link1 = { &branch1, NULL }; Node branch1 = { None, NULL, &link2 }; Link link2 = { &leaf1, &link3 }; Link link3 = { &leaf2, NULL }; Node leaf1 = { Output, &output_function1, NULL }; Node leaf2 = { Output, &output_function2, NULL };
2,362,797
2,362,818
Converting a char array to something that can be appended to a ostringstream
std::ostringstream parmStream; char parmName[1024]; THTTPUrl::Encode(parmName, pParm->Name().c_str(), 1024); //I want to add the value of the paramName to the parmStream worked b4 when parmName was a string but obv not now parmStream << "&" << parmName + "="; Gives me the following .. error: invalid operands of types \u2018char [1024]\u2019 and \u2018const char [2]\u2019 to binary \u2018operator+\u2019 Cheers for the help in advance
Try parmStream << "&" << parmName << "="; I haven't check your code but it looks like the error is pointing to the fact you are trying to add the "=" to a standard C string.
2,362,905
2,363,340
How to build a static C++ library using Xcode?
I am trying to create a static library in Xcode using C++ ( All my files are .h or .cpp ). I tried deleting main.cpp and then adding a target to my project to build a "Static" library. Since I'm not using Cocoa, I assumed that I needed to add a BSD Static Library, but I have tried other static library options with no apparent results. It doesn't build ( doesn't show any errors though, but it's like nothing happened). In the following picture "Untitled" is my static library. ( as you can see libUntitled.a is red, even after I built the project. ) alt text http://grab.by/2LWZ
Are your source files checked against the new target? Otherwise, open the Build window, unfold the messages pane so you can see what the compiler is actually doing and where it places the .a file (if at all). That might help you to track down what's going on.
2,363,219
2,363,514
vector assignation on uninitialized memory chunk and similar issues
vector<vector<string> > test for example. g++, you can do test.reserve(10); test[0] = othervector; test[9] = othervector; It doesn't crash. Theory says you shouldn't do it like that because you are assigning a vector to a chunk of memory that believes it is a vector. But it works just like the next one: #include <string> #include <vector> #include <iostream> using namespace std; int main(){ vector<string> first_vector; vector<string> &second_vector = *(vector<string>*)new char[sizeof(vector<string>)]; first_vector.push_back("whatever"); first_vector.push_back("whatever2"); first_vector.push_back("whatever3"); second_vector = first_vector; cout << "0 " << second_vector[0] << " \n"; cout << "1 " << second_vector[1] << " \n"; cout << "2 " << second_vector[2] << " \n"; } This looks to me like the assignment operator of a vector actually copies all, or at least enough fields of the vector implementation for this to work, rendering a perfectly valid vector in the uninitialized. Well, this is clearly undefined behavior to me, only problem is that it works as expected, I found quite a lot of these in a codebase I'm currently inspecting. Are there more cases like this one in the rest of the containers? Never seen one that looks so easy to make a mistake but that it actually works even if you make the mistake. EDIT: This is not about how to do the above properly or complain about the compilers behavior, its trying to find similar issues easy to happen and really difficult to spot later, like this one.
"Are there more cases like this one in the rest of the containers?" Tons. And I'm not kidding. I can come up with literally thousands of them, all over the standard. For instance, almost all functions that take an iterator range can break in nasty ways if you pass in two unrelated iterators. They might also "work" silently but wrongly, in particular if you pass in two vector iterators. Similarly, in all implementations I know of, for any type T reinterpret_cast<T&>(&random_bytes).operator=(T()); may work for some values of random_bytes. It's still UB.
2,363,225
2,363,744
Controlling USB Access of Windows CE6
I am looking to find a way to programatically (C++) control/secure access to the USB ports on a Windows CE device that will only have a single login, and then be left running a real-time application. Ideally, being able to have a password entered into the running application, which then opens up/enables USB functionality, would be the easiest to integrate, but any solution will be taken into consideration. I'm not really bothered about what type of device is plugged in, although this would be a bonus. I just want to stop someone being able to use Pen Drives without authorisation on the running system, but still allow authorised engineers a way to update software and copy log files etc. I know that could be done in the BIOS, but I don't want to have to reboot to toggle this functionality, as the software running needs to stay running, and I'd rather not let inexperienced people into the BIOS... Is there any way this can be done in C++ for Windows CE6?
You need to modify the USB host driver to ask for the authenticaion from the user (or better yet have it coordinate with some authentication app/servce). You could then make it as complex as you'd like, associating users with device classes, device vendors or even down to a device serial number. The driver source ships with Platform Builder, so it shouldn't be too difficult to do.
2,363,284
2,514,216
IHostAssemblyStore::ProvideAssembly causes exception "The located assembly's manifest definition does not match the assembly reference"
PostSharp 2.0 includes a CLR host and implements IHostAssemblyStore::ProvideAssembly. From managed code, I invoke: Assembly.Load("logicnp.cryptolicensing, Version=3.0.0.0, Culture=neutral, PublicKeyToken=4a3c0a4c668b48b4") My implementation of IHostAssemblyStore::ProvideAssembly receives the following input for the first parameter pBindInfo: 0x002cd578 { dwAppDomainId=1 lpReferencedIdentity=0x03c123f8 "logicnp.cryptolicensing, version=3.0.0.0, culture=neutral, publickeytoken=4a3c0a4c668b48b4" lpPostPolicyIdentity=0x03c14620 "logicnp.cryptolicensing, version=3.0.0.0, culture=neutral, publickeytoken=4a3c0a4c668b48b4, processorarchitecture=x86" } My implementation then returns the right stream. Note that the binding identity of that file is "logicnp.cryptolicensing, version=3.0.0.0, culture=neutral, publickeytoken=4a3c0a4c668b48b4". When I return this file from ProvideAssembly, the CLR throws the following exception: Could not load file or assembly 'logicnp.cryptolicensing, Version=3.0.0.0, Culture=neutral, PublicKeyToken=4a3c0a4c668b48b4' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) So the assembly I returned does not match the post-policy reference, which is true, but this post-policy reference is incorrect. I wonder if there is any workaround to this issue or if I am misunderstanding something. This is an important issue for me and I have many users complaining on our support forum. PS. Configuration: CLR 2.0 x86 or x64 (latest updates installed), Windows 7 x64. I also posted this question on MSDN Forum at http://social.msdn.microsoft.com/Forums/en/clr/thread/93efa20f-5423-4d55-aa3d-dadcc462d999.
The question has been answered on http://social.msdn.microsoft.com/Forums/en/clr/thread/93efa20f-5423-4d55-aa3d-dadcc462d999. Basically, it is a documentation bug: Instead of returning ERROR_FILE_NOT_FOUND from IHostAssemblyStore::ProvideAssembly (as specified in documentation), the host implementation should return COR_E_FILENOTFOUND (defined in corerror.h).
2,363,332
2,363,349
No match for call to '(std::pair<unsigned int, unsigned int>) (unsigned int&, unsigned int)'
I don't know what's wrong with the follwing code, it should read numbers and put their value with the position together in a vector of pairs and then sort them and print out the positions. I removed the part with sort - i thought the problem was there, but i received an error on compilation again. #include <iostream> #include <vector> #include <algorithm> #include <utility> using namespace std; int main(void) { unsigned int n,d,a[65],b[65],s,i,j,t,us=0; pair<unsigned int,unsigned int> temp; vector< pair<unsigned int,unsigned int> > v; cin >> n; for(i=0;i<n;i++) { cin >> t; temp(t, i+1); v.push_back(temp); } cin >> d; for(i=0;i<d;i++) cin >> a[i] >> b[i]; for(i=0;i<v.size();i++) { cout << v[i].first << " -- " << v[i].second << endl; } return 0; } Please tell me where is the problem. Thanks.
The problem is temp(t, i+1); You need to set the first and second manually temp.first = t; temp.second = i + 1; Alternatively you can declare temp inside the loop (probably what I'd do). for(i=0;i<n;i++) { cin >> t; pair<unsigned int,unsigned int> temp(t, i+1); v.push_back(temp); } Or a second alternate, use the make_pair helper function, and do away with temp completely (thanks to KennyTM for the reminder) for(i=0;i<n;i++) { cin >> t; v.push_back(make_pair(t, i+1)); } Hope this helps
2,363,363
2,363,447
Calling virtual functions inside member functions
I'm reading Thinking in C++ by Bruce Eckel. In Chapter 15 (Volume 1) under the heading "Behaviour of virtual functions inside constructor", he goes What happens if you’re inside a constructor and you call a virtual function? Inside an ordinary member function you can imagine what will happen – the virtual call is resolved at runtime because the object cannot know whether it belongs to the class the member function is in, or some class derived from it. For consistency, you might think this is what should happen inside constructors. Here Bruce's trying to explain that when you call a virtual function inside an object's constructor, polymorphism isn't exhibited i.e. the current class' function will only be called and it will not be some other derived class version of that function. This is valid and I can understand it, since the constructor for a class will not know beforehand if it's running for it or for someother dervied object's creation. Moreover, if it does so, it'll be calling functions on a partially created object, which is disastrous. While my confusion suddenly arose because of the first sentence where he states about the ordinary member function, where he says the virtual call will be resolved @ run-time. But wait, inside any member function of a class, when you call another function (be it virtual or non-virtual) it's own class version will only be called, right? E.g. class A { virtual void add() { subadd(); } virtual subadd() { std::cout << "A::subadd()\n"; } }; class B : public A { void add() { subadd(); } void subadd() { std::cout << "B::subadd()\n"; } }; In the above code, in A::add() when a call to subadd() is made, it'll always call A::subadd() and the same holds true for B as well, right? So what is he meaning by "the virtual call is resolved at runtime because the object cannot know whether it belongs to the class the member function is in, or some class derived from it" ? Is he explaining it with respect to a call via a base class pointer? (I really suspect so) In which case he shouldn't be writing "Inside an ordinary member function"; from my understanding so far, any call of a member function from inside another member function of the same class is not polymorphic, please correct me if am getting it wrong.
You are wrong - a further derived class could override some of the virtual functions, meaning that a static call would be wrong. So, to extend your example: class C : public B { public: // Not overriding B::add. void subadd() { std::cout << "C::subadd\n"; } }; A *a = new C; a->add(); This dynamically calls B::add, which in turn dynamically calls C::subadd. A static call to B::subadd would be wrong, since the dynamic type is C and C overrides the function. In your example, the duplication of A::add as B::add is unnecessary - both will call subadd polymorphically whatever the dynamic type of the object.
2,363,436
2,363,466
Why can't I create a std::stack of std::ifstreams?
Why does the following not work: #include <iostream> #include <fstream> #include <stack> std::stack<std::ifstream> s; -PT
std::stack (like all STL containers) requires that its contained type be "assignable". In STL-speak, that means that it must have a copy constructor and an operator=. std::ifstream has neither of these. You can imagine why you would not want to be able to copy and assign I/O streams; the semantics of what should happen when there are two copies of the same stream are not obvious. Should a read from or write to one copy affect the position of the other copy? Should closing one stream close the other? etc. If you want to have "a container of std::ifstreams", then what you really should make is "a container of std::ifstream*s". Non-const pointers are always assignable. The caveat is that in this case of course you have to make sure that you delete the pointers yourself before destructing the container, since the container will not do that for you.
2,363,500
11,921,312
Does anyone have an easy solution to parsing Exp-Golomb codes using C++?
Trying to decode the SDP sprop-parameter-sets values for an H.264 video stream and have found to access some of the values will involve parsing of Exp-Golomb encoded data and my method contains the base64 decoded sprop-parameter-sets data in a byte array which I now bit walking but have come up to the first part of Exp-Golomb encoded data and looking for a suitable code extract to parse these values.
Exp.-Golomb codes of what order ?? If it you need to parse H.264 bit stream (I mean transport layer) you can write a simple functions to make an access to scecified bits in the endless bit stream. Bits indexing from left to right. inline u_dword get_bit(const u_byte * const base, u_dword offset) { return ((*(base + (offset >> 0x3))) >> (0x7 - (offset & 0x7))) & 0x1; } This function implement decoding of exp-Golomb codes of zero range (used in H.264). u_dword DecodeUGolomb(const u_byte * const base, u_dword * const offset) { u_dword zeros = 0; // calculate zero bits. Will be optimized. while (0 == get_bit(base, (*offset)++)) zeros++; // insert first 1 bit u_dword info = 1 << zeros; for (s_dword i = zeros - 1; i >= 0; i--) { info |= get_bit(base, (*offset)++) << i; } return (info - 1); } u_dword means unsigned 4 bytes integer. u_byte means unsigned 1 byte integer. Note that first byte of each NAL Unit is a specified structure with forbidden bit, NAL reference, and NAL type.
2,363,715
2,363,738
Questions Regarding the Implementation of a Simple CPU Emulator
Background Information: Ultimately, I would like to write an emulator of a real machine such as the original Nintendo or Gameboy. However, I decided that I need to start somewhere much, much simpler. My computer science advisor/professor offered me the specifications for a very simple imaginary processor that he created to emulate first. There is one register (the accumulator) and 16 opcodes. Each instruction consists of 16 bits, the first 4 of which contain the opcode, the rest of which is the operand. The instructions are given as strings in binary format, e.g., "0101 0101 0000 1111". My Question: In C++, what is the best way to parse the instructions for processing? Please keep my ultimate goal in mind. Here are some points I've considered: I can't just process and execute the instructions as I read them because the code is self-modifying: an instruction can change a later instruction. The only way I can see to get around this would be to store all changes and for each instruction to check whether a change needs to be applied. This could lead to a massive amounts of comparisons with the execution of each instruction, which isn't good. And so, I think I have to recompile the instructions in another format. Although I could parse the opcode as a string and process it, there are instances where the instruction as a whole has to be taken as a number. The increment opcode, for example, could modify even the opcode section of an instruction. If I were to convert the instructions to integers, I'm not sure then how I could parse just the opcode or operand section of the int. Even if I were to recompile each instruction into three parts, the whole instruction as an int, the opcode as an int, and the operand as an int, that still wouldn't solve the problem, as I might have to increment an entire instruction and later parse the affected opcode or operand. Moreover, would I have to write a function to perform this conversion, or is there some library for C++ that has a function convert a string in "binary format" to an integer (like Integer.parseInt(str1, 2) in Java)? Also, I would like to be able to perform operations such as shifting bits. I'm not sure how that can be achieved, but that might affect how I implement this recompilation. Thank you for any help or advice you can offer!
Parse the original code into an array of integers. This array is your computer's memory. Use bitwise operations to extract the various fields. For instance, this: unsigned int x = 0xfeed; unsigned int opcode = (x >> 12) & 0xf; will extract the topmost four bits (0xf, here) from a 16-bit value stored in an unsigned int. You can then use e.g. switch() to inspect the opcode and take the proper action: enum { ADD = 0 }; unsigned int execute(int *memory, unsigned int pc) { const unsigned int opcode = (memory[pc++] >> 12) & 0xf; switch(opcode) { case OP_ADD: /* Do whatever the ADD instruction's definition mandates. */ return pc; default: fprintf(stderr, "** Non-implemented opcode %x found in location %x\n", opcode, pc - 1); } return pc; } Modifying memory is just a case of writing into your array of integers, perhaps also using some bitwise math if needed.
2,363,736
2,365,555
How do I store the value of a register into a memory location pointed to by a pointer?
I have the following code: void * storage = malloc( 4 ); __asm { //assume the integer 1 is stored in eax mov eax, storage //I've tried *storage as well but apparently it's illegal syntax } /* other code here */ free(storage); However, in the code, when I dereference the storage pointer ( as in *(int *)storage ), I do not get 1. So, what is the proper way of storing the value of a register into the memory pointed to by a C++ pointer?
Are you sure you know what you really need? You requested the code that would store the register value into the memory allocated by malloc ("pointed to by a pointer"), i.e. *(int*) storage location, yet you accepted the answer that stores (or at least attempts to store) the value into the pointer itself, which is a completely different thing. To store eax into the memory "pointed to by a pointer", i.e. into *(int*) storage as you requested, you'd have to do something like that mov edi, dword ptr storage mov dword ptr [edi], eax (I use the "Intel" right-to-left syntax for assembly instructions, i.e. mov copies from right operand to left operand. I don't know which syntax - right-to-left or left-to-right - your compiler is using.) Note also that in mov edi, dword ptr storage the dword ptr part is completely optional and makes no difference whatsoever.
2,363,810
2,363,841
Does anyone know what the "-FC" option does in gcc g++?
Does anyone know what the "-FC" option does in g++? I have it in my SConstruct script that builds the command line g++ command, I have searched google
You know, if all fails, read the manual :-). Fdir Add the framework directory dir to the head of the list of directories to be searched for header files. These directories are interleaved with those specified by -I options and are scanned in a left-to-right order. [...] Source: http://gcc.gnu.org/onlinedocs/gcc-4.4.3/gcc/Darwin-Options.html#Darwin-Options So -FC will apparently add the framework directory "C" to the header file search path.
2,363,888
2,363,923
If I allocate memory in one thread in C++ can I de-allocate it in another
If I allocate memory in one thread in C++ (either new or malloc) can I de-allocate it in another, or must both occur in the same thread? Ideally, I'd like to avoid this in the first place, but I'm curious to know is it legal, illegal or implementation dependent. Edit: The compilers I'm currently using include VS2003, VS2008 and Embedded C++ 4.0, targetting XP, Vista, Windows 7 and various flavours of Windows CE / PocketPC & Mobile. So basically all Microsoft but across an array of esoteric platforms.
Generally, malloc/new/free/delete on multi threaded systems are thread safe, so this should be no problem - and allocating in one thread , deallocating in another is a quite common thing to do. As threads are an implementation feature, it certainly is implementation dependant though - e.g. some systems require you to link with a multi threaded runtime library.
2,363,899
2,364,242
Is there a way to get an event from windows on every new process that is started?
I want to get a notification each time a new process is started by the operating system. Note that I need to that in native code (I know it can be done in managed code using System.Management members). Extra points if there is a way to get it before the process starts running :) (i.e in during its initialization) Thanks.
The problem with using a driver is that you will require permission to install it, but otherwise I think is the safest method. In user space you can try to create a window hook which will work if such application uses a windows, but is otherwise quite obnoxious. On the other hand you can try to use WMI, which is the underlying technology used in C#. You can look for pointers in this anwers and this examples.
2,364,077
2,364,874
serialize in .NET, deserialize in C++
I have a .NET application which serializes an object in binary format. this object is a struct consisting of a few fields. I must deserialize and use this object in a C++ application. I have no idea if there are any serialization libraries for C++, a google search hasn't turned up much. What is the quickest way to accomplish this? Thanks in advance. Roey. Update : I have serialized using Protobuf-net , in my .NET application, with relative ease. I also get the .proto file that protobuf-net generated, using GetProto() command. In the .proto file, my GUID fields get a type of "bcl.guid", but C++ protoc.exe compiler does not know how to interpret them! What do I do with this?
If you are using BinaryFormatter, then it will be virtually impossible. Don't go there... Protocol buffers is designed to be portable, cross platform and version-tolerant (so it won't explode when you add new fields etc). Google provide the C++ version, and there are several C# versions freely available (including my own) - see here for the full list. Small, fast, easy. Note that the v1 of protobuf-net won't handle structs directly (you'll need a DTO class), but v2 (very soon) does have tested struct support.
2,364,312
2,364,750
Fast 64 bit comparison
I'm working on a GUI framework, where I want all the elements to be identified by ascii strings of up to 8 characters (or 7 would be ok). Every time an event is triggered (some are just clicks, but some are continuous), the framework would callback to the client code with the id and its value. I could use actual strings and strcmp(), but I want this to be really fast (for mobile devices), so I was thinking to use char constants (e.g. int id = 'BTN1';) so you'd be doing a single int comparison to test for the id. However, 4 chars isn't readable enough. I tried an experiment, something like- long int id = L'abcdefg'; ... but it looks as if char constants can only hold 4 characters, and the only thing making a long int char constant gives you is the ability for your 4 characters to be twice as wide, not have twice the amount of characters. Am I missing something here? I want to make it easy for the person writing the client code. The gui is stored in xml, so the id's are loaded in from strings, but there would be constants written in the client code to compare these against. So, the long and the short of it is, I'm looking for a cross-platform way to do quick 7-8 character comparison, any ideas?
Are you sure this is not premature optimisation? Have you profiled another GUI framework that is slow purely from string comparisons? Why are you so sure string comparisons will be too slow? Surely you're not doing that many string compares. Also, consider strcmp should have a near optimal implementation, possibly written in assembly tailored for the CPU you're compiling for. Anyway, other frameworks just use named integers, for example: static const int MY_BUTTON_ID = 1; You could consider that instead, avoiding the string issue completely. Alternatively, you could simply write a helper function to convert a const char[9] in to a 64-bit integer. This should accept a null-terminated string "like so" up to 8 characters (assuming you intend to throw away the null character). Then your program is passing around 64-bit integers, but the programmer is dealing with strings. Edit: here's a quick function that turns a string in to a number: __int64 makeid(const char* str) { __int64 ret = 0; strncpy((char*)&ret, str, sizeof(__int64)); return ret; }
2,364,412
2,364,473
Executing a command from C++, What is expected in argv[0]?
I am using execv() to run commands from /bin/ such as 'ls', 'pwd', 'echo' from my c++ program, and I am wondering what value I should provide in argv[0]; const char * path = getPath(); char ** argv = getArgs(); execv(path,argv);
argv[0] is supposed to be the program name. It's passed to the program's main function. Some programs differentiate their behavior depending on what string argv[0] is. For example the GNU bash shell will disable some of its features if called using sh instead of bash. Best give it the same value that you pass to path. In linux, argv[0] is the process name displayed by the top utility (which it probably gets from reading entries in /proc/)
2,364,574
2,364,652
Receiving response(s) from N number of clients in reply to a broadcast request over UDP
I am implementing a kind of IP finder for a particular type of network multimedia device. I want to find out all the alive devices of that type in the LAN, with their IP address and other details. The device has its own way of device discovery. It works as follows: A client sends a broadcast request over the LAN via UDP. The destination port number is fixed. In reply, all the servers in the LAN that understand the format of this request will respond to this request providing information about themselves. I am broadcasting the UDP request message using sendto(). Now my problem is that I don't know how many devices (i.e.servers) will respond to the request. How many times will I have to call recvfrom()? When will I come to know that I have handled the response from all the devices? Or in general, is recvfrom() the right choice for receiving response from multiple servers? Is there any better (or CORRECT if I am wrong here) way of accomplishing the same? I am programming in C/C++, planning to code for both Windows and Linux. Many thanks in advance. Edit: So with the help of all the network programming wizards out here, I have found the solution to my problem :) select() is just the thing for me... Thanks a lot to all of you who took out time to help me
How many times will I have to call recvfrom()? When will I come to know that I have handled the response from all the devices/servers? If you don't know the number of devices/servers, you cannot know how many times you will need to call recvfrom() or when you've handled all the responses. You might consider using a select() loop (until timeout) and call recvfrom() when data is available to read. This might be in the main thread or a separate thread. If the data arrives faster than it can be processed, you will lose datagrams. This will depend largely on the speed that the data is parsed and stored after it is received. If processing the data is an intensive operation, it may be necessary to do the processing in a separate thread or store the data until the receive loop times out and then proceed with processing it. Since UDP is unreliable, looping to rebroadcast a few times should help account for some of the loss and the processing should account for duplicates. The following pseudocode is how I might approach the problem: /* get socket to receive responses */ sd = socket( ... ); do { /* set receive timeout */ timeout.tv_sec = 5; /* broadcast request */ sendto( ... ); /* wait for responses (or timeout) */ while(select(sd+1, &readfds, NULL, NULL, &timeout) > 0) { /* receive the response */ recvfrom( ... ); /* process the response (or queue for another thread / later processing) */ ... /* reset receive timeout */ timeout.tv_sec = 5; } /* process any response queued for later (and not another thread) */ } while (necessary); Or in general, is recvfrom() the right choice for receiving response from multiple servers? recvfrom() is commonly used with connectionless-mode sockets because it permits the application to retrieve the source address of received data.
2,364,662
2,364,680
For how long the iterator returned by std::set.find() lives?
I need to keep track of std::set element by saving the iterator returned by set.find(). My questions is does insertion and removing other elements invalidates the obtained iterator? From a simple test I did I can see it is not, but I'd like to ensure this feature is by design.
It never invalidates iterators or pointers/references to the elements. Only if you remove the element itself does the iterator or pointer/reference become invalid. 23.1.2/8: The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.
2,364,774
2,372,507
Why do I need to compile DateTime in boost if I am not using to_string or from_string?
When compiling a Visual Studio 2005 project that references a mix of c++ managed/unmanaged code, I get the following error: 1>LINK : fatal error LNK1104: cannot open file 'libboost_date_time-vc80-mt-1_42.lib' I have followed the Getting Started Guide. Of relevance is this snippet: "Boost.DateTime has a binary component that is only needed if you're using its to_string/from_string or serialization features, or if you're targeting Visual C++ 6.x or Borland." I have done a global search for "to_string" and "from_string". There are no occurrences in the code of these DateTime methods. In the documentation for the DateTime library itself, there is this snippet: "The library has a few functions that require the creation of a library file (mostly to_string, from_string functions). Most library users can make effective use of the library WITHOUT building the library, but simply including the required headers. If the library is needed, the Jamfile in the build directory will produce a "static" library (libboost_date_time) and a "dynamic/shared" library (boost_date_time) that contains these functions." How would I got about resolving this issue? The easy solution is to build the library or use the Windows binary installer from BoostPro, however it bothers me that the compilred library is being required when according to the documentation I am not in the situation that requires it. Another question is the DateTime documenation seems to indiciate that its "mostly to_string, from_string)", could my code perhaps be referencing some other function that would require creating the library file? Does anyone know what other functions are included? Are there functions that themselves wrap around or call to_string or from_string? The only inclusion I am using is: #include <boost/date_time/gregorian/gregorian.hpp>
Project compiles and links cleanly after the following troubleshooting: I defined BOOST_LIB_DIAGNOSTIC - to see what diagnostic output I could get from the auto linker. Not too informative: 1>Linking to lib file: libboost_date_time-vc80-mt-1_42.lib 1>LINK : fatal error LNK1104: cannot open file 'libboost_date_time-vc80-mt-1_42.lib' I then defined BOOST_ALL_NO_LIB=1 - disables all auto linking. Project now compiles and links cleanly. Boost headers use pragma to signal compilers when to look for a lib file. While the date_time library does not do this, other headers within boost it depends on do.
2,365,031
2,366,070
Does Hinnant's unique_ptr implementation incorrectly fail to convert derived-to-base in this case?
I'm currently trying to use Howard Hinnant's unique_ptr implementation, and am running into a compile error. Here is some sample code: struct Base {}; struct Derived : public Base {}; void testfun(boost::unique_ptr<Base>); void test() { unique_ptr<Derived> testDerived; unique_ptr<Base> testBase(move(testDerived)); // ok, construct base explicitly from derived testfun(move(testBase)); // ok, pass base to testfun which expects base testfun(unique_ptr<Base>(move(testDerived))); // ok, explicitly converts to unique_ptr<Base> testfun(move(testDerived)); // error on this line } The error I get is In function 'void test()': error: no matching function for call to 'boost::unique_ptr<Base, boost::default_delete<Base> >::unique_ptr(boost::unique_ptr<Base, boost::default_delete<Base> >)' note: candidates are: boost::unique_ptr<T, D>::unique_ptr(boost::detail_unique_ptr::rv<boost::unique_ptr<T, D> >) [with T = Base, D = boost::default_delete<Base>] note: boost::unique_ptr<T, D>::unique_ptr(boost::unique_ptr<T, D>&) [with T = Base, D = boost::default_delete<Base>] error: initializing argument 1 of 'void testfun(boost::unique_ptr<Base, boost::default_delete<Base> >)' from result of 'boost::unique_ptr<T, D>::unique_ptr(boost::unique_ptr<U, E>, typename boost::enable_if_c<((((! boost::is_array<U>::value) && boost::detail_unique_ptr::is_convertible<typename boost::unique_ptr<U, boost::default_delete<U> >::pointer,typename boost::detail_unique_ptr::pointer_type<T, D>::type>::value) && boost::detail_unique_ptr::is_convertible<E,D>::value) && ((! boost::is_reference<D>::value) || boost::is_same<D,E>::value)), void>::type*) [with U = Derived, E = boost::default_delete<Derived>, T = Base, D = boost::default_delete<Base>]' It seems like the offending line should not fail. Is this a bug in the implementation, a limitation of the implementation due to the lack of C++0x language features, or a misunderstanding of the rules of unique_ptrs? (Note, I know this won't work at run-time because I'm moving the same thing more than once; I'm just trying to figure out the compile-time error.)
Further research has lead me to this note, leading me to believe that this is a known limitation of the implementation: 3 of the tests currently fail for me (fail at compile time, supposed to compile, run and pass). These are all associated with the converting constructor specified in [unique.ptr.single.ctor]. When the source and target are of different type, this emulation demands that the conversion be explicit, and refuses to compile on implicit conversions: unique_ptr<base> b(unique_ptr<derived>()); // ok unique_ptr<base> b = unique_ptr<derived>(); // causes 3 compile time failures under unique.ptr/unique.ptr.single/unique.ptr.single.ctor .
2,365,156
2,365,275
adding string objects to an array via loop
What i'm trying to do is create a template array class that will store values of a data type into an array. I have it working fine with int values, however working with string objects things start to break down. I've taken out the block of code and tried it on it's own and I do get the same error. I'm sure I've learnt this, and I'm almost positive that the answer is something simple, trying to wrap my head around the pace in which we're learning c++ is a little crazy at times! My best guess right now, is that I would need to tokenize the string and look for spaces. I tend to over think things though which lead to more confusion - thus me seeking out a answer here! The code: // Test String: Hello World this is a String Object int stringSize = 7; int count = 0; string s[stringSize]; cout << "\nEnter " << stringSize << " one-word string values:\n"; while (count < stringSize) { string tmpVal; cin >> tmpVal; s[count] = tmpVal; count ++; }
string s[stringSize]; is illegal because stringSize is not a constant. You must either use dynamic memory (i.e. string* s = new string [stringSize];), include stringsize as a template argument (don't do this, it doesn't actually solve the problem), use a fixed size value, or use an existing structure (I'd suggest vector, as in Bill's answer). The code below works fine on my compiler: int main(int argc, char *argv[]) { int stringSize = 7; int count = 0; string* s = new string [stringSize]; cout << "\nEnter " << stringSize << " one-word string values:\n"; while (count < stringSize) { string tmpVal; cin >> tmpVal; s[count] = tmpVal; count ++; } delete[] s; }
2,365,180
2,393,158
Socket connect() always succeeds (TCP over ActiveSync)
I'm using TCP/IP over ActiveSync to connect from Windows CE device to Windows XP desktop. The WinSock connect() function always succeeds, no matter whether desktop server application is actually running. The following simplified code demonstrates this issue: #include "stdafx.h" #include <Winsock2.h> int _tmain(int argc, _TCHAR* argv[]) { const int Port = 5555; const char * HostName = "ppp_peer"; WSADATA wsadata; if (WSAStartup(MAKEWORD(1, 1), &wsadata) != 0) return 1; struct hostent * hp = gethostbyname(HostName); if (hp == NULL) return 1; struct sockaddr_in sockaddr; memset(&sockaddr, 0, sizeof(sockaddr)); sockaddr.sin_family = AF_INET; sockaddr.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr; sockaddr.sin_port = htons(Port); int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == SOCKET_ERROR) return 1; int result = connect(sock, (struct sockaddr*)&sockaddr, sizeof(sockaddr)); // result always 0 (success) here closesocket(sock); return 0; } Is this a bug? If not, what is a correct way to determine that the server is actually online? Only to try to use the established connection (recv/send data)? Device: Windows CE 5.0, WinSock 2.2; Desktop: Windows XP, SP3, ActiveSync 4.5.
So, I did not find the way to check if this is 'real' connection, other than to ignore this issue and try to use this connection. If it is not 'real', the communication will fail.
2,365,212
2,365,270
Cannot explain why std::istream_iterator set std::ios_base in error state
I am trying to conert a vector into a stream and back. While the first part works without issues, the last line of the following code put std::ios_base is an error state. Have you got any idea why it is so? Apparently myVecOut is equal to myVec after the code executes.... std::vector<double> myVec( 3 ); std::stringstream temp; std::copy(myVec.begin(), myVec.end(), std::ostream_iterator<double>(temp, " ")); std::cout << temp.str() << std::endl; std::vector<double> myVecOut; std::copy(std::istream_iterator<double>(temp), std::istream_iterator<double>(), std::back_inserter(myVecOut));
It's set into fail state, because copy does not know how many items to read. It reads as long as the stream is in a .good() non-.fail() state. While skipping the last space, it hits the end, and sets both eof (because it tried to read beyond the end) and fail (because it could not read the double it wanted to). Call .clear() afterwards to clear those error bits. The difference between the iterators comparing non-equal while .good() is true and while .fail() is false is that istream_iterator will still advance even if the stream is in an eof state. The following further examines it: std::stringstream a; a << "1.1 2.2"; std::copy(std::istream_iterator<double>(a), std::istream_iterator<double>(), std::ostream_iterator<double>(std::cout, " ")); Now, after we read "2.2", the eof state is set (because it tried to read beyond "2"). But the begin and end iterator won't yet compare equal, because the fail state is not set, and thus .fail() does not return true (while .good() would have returned false, because it considers .eof() in addition). Only after the next read, when it could not read another double anymore, the fail state is set, and then the iterators compare equal, and the loop within std::copy exits.
2,365,531
2,365,780
Can C++ projects use T4 in Visual Studio 2010?
T4 did not work for C++ projects in Visual Studio 2008 since it did not use msbuild for C++ projects. (Yes there were workarounds) In Visual Studio 2010, C++ projects uses MsBuild, so do anyone know if C++ projects can use T4 in the same way as C# or VB?
The main integration mechanism for T4 in C# and Visual Basic projects is the TextTemplatingFileGenerator custom tool. Although in Visual Studio 2010 C++ projects now use MSBuild, they still don't support custom tools. As a workaround, you could use T4 Toolbox, which allows you to put a .tt file in a C# or Visual Basic project and have the files it generates added to your C++ project automatically.
2,365,599
2,365,928
C++: High speed stack
As far as I assume, std::stack and all such 'handmade' stacks work much slower than stack which is applications one. Maybe there's a good low-level 'bicycle' already? (Stack realization). Or it's a good idea to create new thread and use it's own stack? And how can I work directly with application stack? (asm {} only?)
The only way in which std::stack is significantly slower than the processor stack is that it has to allocate memory from the free store. By default, it uses std::deque for storage, which allocates memory in chunks as needed. As long as you don't keep destroying and recreating the stack, it will keep that memory and not need to allocate more unless it grows bigger than before. So structure code like this: std::stack<int> stack; for (int i = 0; i < HUGE_NUMBER; ++i) do_lots_of_work(stack); // uses stack rather than: for (int i = 0; i < HUGE_NUMBER; ++i) do_lots_of_work(); // creates its own stack If, after profiling, you find that it's still spending too long allocating memory, then you could preallocate a large block so you only need a single allocation when your program starts up (assuming you can find an upper limit for the stack size). You need to get into the innards of the stack to do this, but it is possible by deriving your own stack type. Something like this (not tested): class PreallocatedStack : public std::stack< int, std::vector<int> > { public: explicit PreallocatedStack(size_t size) { c.reserve(size); } }; EDIT: this is quite a gruesome hack, but it is supported by the C++ Standard. More tasteful would be to initialise a stack with a reserved vector, at the cost of an extra allocation. And don't try to use this class polymorphically - STL containers aren't designed for that. Using the processor stack won't be portable, and on some platforms might make it impossible to use local variables after pushing something - you might end up having to code everything in assembly. (That is an option, if you really need to count every last cycle and don't need portability, but make sure you use a profiler to check that it really is worthwhile). There's no way to use another thread's stack that will be faster than a stack container.
2,365,612
2,370,831
Qt C++ WebKit windowCloseRequested Signal
I am trying to connect QWebpage::windowCloseRequested() to a slot that just prints out a debug message. When I call window.close(); in JavaScript it doesn't bubble the signal up or call the slot... connect(webView->page(), SIGNAL(windowCloseRequested()),this, SLOT(windowCloseRequested())); The slot is setup, it is in my window.h file as a slot like this: public slots: void windowCloseRequested(); And the function is defined as: void MyWindow::windowCloseRequested(){ qDebug() << "I was called"; } When I compile, there are no errors, there were before saying I had the slots wrong, I figured that part out, no more error, but now when I click a link, or call window.close() with javascript in a loaded webpage, it doesn't do anything. If I manually call the function, it prints out the debug message. Any pointers, or help/solutions would be appreciated. Note, this code above is based on the Tabwidget.cpp code for a browser example. It's the best reference I could find.
Attaching an onclick to an <a> tag is ... questionable. Use a span, and blammo, it works. This is why you should take breaks when coding, or else you make really dumb mistakes that waste time.
2,365,624
2,365,645
Should I delete the string members of a C++ class?
If I have the following declaration: #include <iostream> #include <string> class DEMData { private: int bitFldPos; int bytFldPos; std::string byteOrder; std::string desS; std::string engUnit; std::string oTag; std::string valType; int idx; public: DEMData(); DEMData(const DEMData &d); void SetIndex(int idx); int GetIndex() const; void SetValType(const char* valType); const char* GetValType() const; void SetOTag(const char* oTag); const char* GetOTag() const; void SetEngUnit(const char* engUnit); const char* GetEngUnit() const; void SetDesS(const char* desS); const char* GetDesS() const; void SetByteOrder(const char* byteOrder); const char* GetByteOrder() const; void SetBytFldPos(int bytFldPos); int GetBytFldPos() const; void SetBitFldPos(int bitFldPos); int GetBitFldPos() const; friend std::ostream &operator<<(std::ostream &stream, DEMData d); bool operator==(const DEMData &d) const; ~DEMData(); }; what code should be in the destructor? Should I "delete" the std::string fields?
Your destructor only has to destroy the members for which you allocate resources. so no, you don't "delete" strings. You delete pointers you allocate with new Your destructor doesn't have to be more than ~DEMData() { }
2,365,663
2,429,591
Run time determination of compilation options
I need to be able to determine at run time what compilation options were use to build the executable. Is there a way to do this? EDIT: I'm particularly interested in detecting optimization settings. The reason is that I'm writing commercial software that must run as fast as possible. While I am just modifying and testing the system I don't do all the optimizations because it takes too long. But I am worried that I may accidentally go and release an unoptimized version of the program. What I'd like to do is have the program give me a visual warning at start up saying something like "This is the slow version - do not release". EDIT: Maybe I could write some little utility to run as a pre-build step? Is the command line stored in some file somewhere? If it is then I could extract it, then write it to some include file as a string and hey presto! EDIT: My choice is not between debug and release. Debug is way too slow - I reserve that strictly for debugging. My day to day choice is between optimized and super-optimized (including the slow-to-compile link time compilation, or even profile guided optimization). EDIT: I often make changes to the complex compilation process, different libraries, different pre-defined macros, different source files etc. It seems clumsy to have to maintain multiple, almost-identical project files differing only in a couple of optimization flags. I would much prefer to just, as-and-when-required switch a couple of flags in a single project and re-compile. I just want the executable to self test how it was created. EDIT: IIRC there is some way to ask the visual studio to create a makefile. Can I ask visual studio to create this makefile for me as a pre-build step?
To do this right you will need to create an additional configuration called, say "SuperOptimised". You now have the standard configurations ("Debug" and "Release") and a third "SuperOptimised". The problem with this is that it makes the configuration management of the project much harder, to change a common setting between the three configurations, you need to make that change in three places. The solution to that is to use "Property Sheets" (".vsprops" files) and the "Property Manager" tab. You can create a property sheet that is common across all three configurations, and specific sheets for Release, Debug and SuperOptimised. Combine the common settings with the specific settings (using property inheritance) to manage the configurations - the "Property Manager" tab allows you to do this. You can change the ".vsprops" files to change common settings across configurations without changing the configurations themselves. More info on Property Sheets here: http://msdn.microsoft.com/en-us/library/a4xbdz1e(VS.80).aspx Finally if you want to check which configuration was build at runtime, use the preprocessor to define a macro value in the "SuperOptimised" .vsprops file, say "SUPEROPTIMISED". You can then check whether you have the right build with: #ifndef SUPEROPTIMISED // Warn the user that this is not a shipping build #endif This may all seem like a lot of work, but managing non-trivial projects (and especially multi-project workspaces) through property sheets greatly reduces the chance of error when making configuration changes.
2,365,900
2,365,937
C++: create betwen-startups relevent functor list
I create something like a list of functors (functions pointers). Then I write them in binary form into file. The problem is, that, functor - is a simple function pointer. (correct me if I'm wrong.) But the address of function is different from one run to another. So, the question - is there any way to create list of functors that will be relevant all the time?
I'd recommend some kind of paired data structure with an identifier on one side and the function pointer on the other. If there are enough of them something like a map: typedef void (*fptr_t)(); // or whatever your function pointer type is std::map<std::string, fptr_t> fptr_map; Your application should build this map when it is first needed and cache the result. Then when you "write" the function pointers to a file, you should write the unique std::string keys instead. When the application "reads" the function pointers it will read in the keys and map them to the function pointers for that invocation of the program.
2,366,067
2,366,085
Is there a difference in declaring instances of inherited classes in these different ways?
If I have a class called "Animal", and a derived class "Bird : public Animal", I can create a Bird these two ways: Animal *sparrow = new Bird; Bird *sparrow = new Bird; Both compile fine and work as expected. Are they equivalent? Should I prefer one over the other?
The line, in itself, doesn't demonstrate the difference. However, assume Bird declares a method Fly that doesn't exist on Animal. You wouldn't be able to do: Animal* a = new Bird; a->Fly(); on the other hand, this is legal: Bird* b = new Bird; b->Fly(); The distinction here is a result of the fact that C++ is a statically typed language. The static type of the variable is what the compiler cares about when it's verifying things like method calls. Since the static type of the variable a is Animal which doesn't have a Fly method, the compiler will not allow you to call Fly on it (not all animals are able to fly, so you'll have to explicitly cast to Bird: dynamic_cast<Bird*>(a)->Fly() is legal). The expression new Bird will have the type Bird*. If you assign a value of a derived type to a variable of a based type, the compiler will not complain (all Birds are Animals, so it should always work). Basically, the compiler upcasts Bird* to Animal*. The reverse is not true. Not all Animals are Birds, so you'll have to take the responsibility and do the cast explicitly and tell the compiler that I know that object is really a Bird*. Only in that case the compiler will let you to use Bird-specific features. So, in general, if you need to use a Bird-specific member, you'd better use Bird* b = new Bird;.
2,366,072
2,366,112
How do I use a manipulator to format my hex output with padded left zeros
The little test program below prints out: And SS Number IS =3039 I would like the number to print out with padded left zeros such that the total length is 8. So: And SS Number IS =00003039 (notice the extra zeros left padded) And I would like to know how to do this using manipulators and a stringstream as shown below. Thanks! The test program: #include <iostream> #include <sstream> #include <string> #include <vector> int main() { int i = 12345; std::stringstream lTransport; lTransport << "And SS Number IS =" << std::hex << i << '\n'; std::cout << lTransport.str(); }
Have you looked at the library's setfill and setw manipulators? #include <iomanip> ... lTransport << "And SS Number IS =" << std::hex << std::setw(8) ; lTransport << std::setfill('0') << i << '\n'; The output I get is: And SS Number IS =00003039
2,366,461
2,366,533
STL Structures in Static Memory 'Losing' Data Across Threads
I'm writing a multi-threaded demo program using pthreads, where one thread loads data into an STL queue, and another thread reads from it. Sounds trivial, right? Unfortunately, data pushed into the queue is vanishing. I'm not new to multithreading, nor am I unfamiliar with memory structures - however, this has me stumped. These are my declarations for the queue itself and the mutex that protects it, which are located in a header included by the client code: static std::queue<int32_t> messageQueue; static pthread_mutex_t messageQueueLock; When the program starts up, it initializes the mutex with the process shared attribute: pthread_mutexattr_t sharedAttr; pthread_mutexattr_init(&sharedAttr); pthread_mutexattr_setpshared(&sharedAttr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&messageQueueLock, &sharedAttr); It then launches the 'producer' thread and 'consumer' threads, and lets them do their thing. The producer thread pushes a new item onto the queue and then goes to sleep. Here are the lines where it adds something to the queue: pthread_mutex_lock(&messageQueueLock); messageQueue.push(message); pthread_mutex_unlock(&messageQueueLock); It then sleeps and lets the consumer thread take over. However, when the consumer thread checks for items in the queue, the queue is magically empty. I have stepped through the program using gdb. Below is the output of my run. You can see where the producer adds something to the queue, I print the queue's size to make sure it's there, there is a context switch to the consumer thread, I print the queue's size again, and it's empty. Check it out: (gdb) b main_ex.cpp:70 Breakpoint 1 at 0x100006a24: file main_ex.cpp, line 70. (gdb) run Starting program: a.out Reading symbols for shared libraries ++. done Creating the mutex. Producer thread starting up. PRODUCER: Creating a message to send. PRODUCER: Adding the message to the queue. [Switching to process 7432] Breakpoint 1, yourProcess () at main_ex.cpp:70 70 pthread_mutex_lock(&messageQueueLock); (gdb) n 71 messageQueue.push(message); (gdb) p messageQueue.size() $1 = 0 (gdb) n 72 pthread_mutex_unlock(&messageQueueLock); (gdb) p messageQueue.size() $2 = 1 (gdb) b consumer.cpp:81 Breakpoint 2 at 0x1000043f7: file consumer.cpp, line 81. (gdb) c Continuing. PRODUCER: Sleep time! [Switching to process 7432] Breakpoint 2, Producer::processMessageQueue (this=0x1001000c0) at producer.cpp:81 81 pthread_mutex_lock(&messageQueueLock); (gdb) n 83 if(messageQueue.empty()) { (gdb) p messageQueue.size() $3 = 0 (gdb) quit So, I'm really not sure what is going on. The queue is only ever accessed in a critical section (both read/write), the queue is static, and the header is if-def'd to not be multi-included. I'm grateful for any help anyone can offer!
Header guards protect from multiple inclusion per translation unit. However, different translation units will re-include them. In your case, it seems they are each getting their very own static queue and mutex. Also, consider even if you were correct: Without re-including the header, the translation unit would have no idea what queue and mutex are! You'd be trying to use some undeclared identifier. You need extern, which is actually the opposite of static: extern std::queue<int32_t> messageQueue; extern pthread_mutex_t messageQueueLock; Then in one unit, actually define them: std::queue<int32_t> messageQueue; pthread_mutex_t messageQueueLock;
2,366,468
2,366,514
SetWindowsHookEx() , the hook is not maintained? (possibly)
I am trying to learn the Windows API. Currently I am having a lot of trouble trying to get hooks to work. I have some sample code I have been messing around with for a few days - it has a GUI written in C# or something, and a dll in C++. The dll has this function externalized: bool __declspec(dllexport) InstallHook(){ g_hHook = SetWindowsHookEx(WH_CBT, (HOOKPROC) CBTProc, g_hInstance, 0); return g_hHook != NULL; } CBT Proc is this, also in the dll: LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam){ if (nCode < 0) return CallNextHookEx(g_hHook, nCode, wParam, lParam); /* Something should go here to do stuff when certain nCodes are recieved.*/ return 0; } When I run this guys code, everything works fine. He has a call to InstallHook() buried somewhere in his C# GUI, and if I put a breakpoint in the CBTProc function, I can see that it is called over and over by the system. As I don't really understand C#, I am trying to cut it out with the following (tiny) console application: int _tmain(int argc, _TCHAR* argv[]){ bool bbbb = InstallHook(); Sleep(2000); return 0; } My problem is that if I do this, the hook no longer works. With the debugger I can see that InstallHook() is called correctly, and that g_hHook in that function is not null, but the CBTProc function is not called at all - its as if the system forgets about the hook as soon as it leave the InstallHook() function. Can anyone shine light on this issue? I've been pulling my hair out for days trying to get it to work, but I have had no luck.
I suspect this is because you have console application and system does not send notifications about activating, creating, moving, etc. of console windows. Try to make it normal windows application.
2,366,690
2,366,725
storing a pointer to a member function
I'm wrapping an existing C API to make it easier to use in my VS2008 C++ program. The C API is expecting an array of "TABLE_ENTRY" structures that include a function pointer as in the code below. But, I'm having difficulty storing a pointer to a member function in the function pointer. Can anybody point out what I may be doing wrong? Thanks, PaulH My code looks basically like this: struct TABLE_ENTRY; // forward decl typedef int (WINAPI *MYPROC )(DWORD msg, TABLE_ENTRY* entry); struct TABLE_ENTRY { const char* description; DWORD value; MYPROC callback; }; class MyClass { public: MyClass() : description( "Some Description" ), some_value( 1 ) { }; int MyProc( DWORD msg, TABLE_ENTRY* my_entry ) { return 0; }; TABLE_ENTRY* operator*() { entry_.description = description.c_str(); entry_.value = some_value; // error C2440: '=' : cannot convert from 'boost::_bi::bind_t<R,F,L>' to 'MYPROC' entry_.callback = boost::bind< int >( &MyClass::MyProc, this ); return &entry_; }; TABLE_ENTRY entry_; std::string description; DWORD some_value; }; class MyClassCollection { public: TABLE_ENTRY* GetTable() { // is this okay or is it Evil & wrong? return ( &collection_.front() )->operator*(); }; void Add( MyClass& my_class ) { collection_.push_back( my_class ); } private: std::vector< MyClass > collection_; }; int _tmain( int argc, _TCHAR* argv[] ) { MyClass class1; MyClass class2; MyClassCollection collection; collection.Add( class1 ); collection.Add( class2 ); TABLE_ENTRY* table = collection.GetTable(); TABLE_ENTRY entry1 = table[ 0 ]; // should be class1's table TABLE_ENTRY entry2 = table[ 1 ]; // should be class2's table return 0; }
boost::bind creates a functor, i.e. an instance of a class that implements operator(). This is not interchangeable with plain C function pointers.
2,366,739
2,366,788
Create files from file names in another file C++
I am working on sorting several large files in C++. I have a text file containing the names of all the input files, one on each line. I would like to read the file names in one at a time, store them in an array, and then create a file with each of those names. Right now, I am using fopen and fread, which require character arrays (I am trying to optimize for speed), so my filenames are read into an array of character arrays. Those arrays, however, need to have a maximum size fixed in advance, so if the filename is smaller than the maximum, the rest is full of garbage. Then, when I try to use that array as the filename in fopen(), it doesn't recognize the file because it has garbage at the end of the string. How can I solve this problem? Here is my code: #include <iostream> #include <fstream> #include <string> #include "stdafx.h" #define NUM_INPUT_FILES 4 using namespace std; FILE *fp; unsigned char *buff; FILE *inputFiles[NUM_INPUT_FILES]; int _tmain(int argc, _TCHAR* argv[]) { buff = (unsigned char *) malloc(2048); char j[8]; char outputstring[] = "Feelings are not supposed to be logical. Dangerous is the man who has rationalized his emotions. (David Borenstein)"; fp = fopen("hello.txt", "r"); string tempfname[NUM_INPUT_FILES]; //fp = fopen("hello.txt", "r"); for(int i=0;i<NUM_INPUT_FILES;i++) { fgets(tempfname[i], 20, fp); cout << tempfname[i]; } fclose(fp); for(int i=0; i<NUM_INPUT_FILES;i++) { fp = fopen(tempfname[i], "w"); //fwrite(outputstring, sizeof(char), sizeof outputstring/sizeof(char), fp); if(fp) { fclose(fp);} else cout << "sorry" << endl; } return 0; } Also, how do I find the size of a buffer to write it out with fwrite()? Thank you very much, bsg
As Don Knuth said, premature optimization is the root of all evil. Your filenames are definitely not the bottleneck! Just use std::string for them. You'd need to replace fp = fopen(tempfname[i], "w"); with fp = fopen(tempfname[i].c_str(), "w"); however.
2,366,879
2,366,998
operator new overloading and alignment
I'm overloading operator new, but I recently hit a problem with alignment. Basically, I have a class IBase which provides operator new and delete in all required variants. All classes derive from IBase and hence also use the custom allocators. The problem I'm facing now is that I have a child Foo which has to be 16-byte aligned, while all others are fine when aligned to 8-byte. My memory allocator however aligns to 8-byte boundaries only by default, so now the code in IBase::operator new returns an unusable piece of memory. How is this supposed to be solved correctly? I can simply force all allocations to 16 bytes, which will work fine until a 32-byte aligned type pops up. Figuring out the alignment inside operator new doesn't seem to be trivial (can I do a virtual function call there to obtain the actual alignment?) What's the recommended way to handle this? I know malloc is supposed to return a piece of memory which is suitably aligned for everything, unfortunately, this "everything" doesn't include SSE types and I'd really like to get this working without requiring the user to remember which type has which alignment.
This is a possible solution. It will always choose the operator with the highest alignment in a given hierarchy: #include <exception> #include <iostream> #include <cstdlib> // provides operators for any alignment >= 4 bytes template<int Alignment> struct DeAllocator; template<int Alignment> struct DeAllocator : virtual DeAllocator<Alignment/2> { void *operator new(size_t s) throw (std::bad_alloc) { std::cerr << "alignment: " << Alignment << "\n"; return ::operator new(s); } void operator delete(void *p) { ::operator delete(p); } }; template<> struct DeAllocator<2> { }; // ........... Test ............. // different classes needing different alignments struct Align8 : virtual DeAllocator<8> { }; struct Align16 : Align8, virtual DeAllocator<16> { }; struct DontCare : Align16, virtual DeAllocator<4> { }; int main() { delete new Align8; // alignment: 8 delete new Align16; // alignment: 16 delete new DontCare; // alignment: 16 } It's based on the dominance rule: If there is an ambiguity in lookup, and the ambiguity is between names of a derived and a virtual base class, the name of the derived class is taken instead. Questions were risen why DeAllocator<I> inherits DeAllocator<I / 2>. The answer is because in a given hierarchy, there may be different alignment requirements imposed by classes. Imagine that IBase has no alignment requirements, A has 8 byte requirement and B has 16 byte requirement and inherits A: class IBAse { }; class A : IBase, Alignment<8> { }; class B : A, Alignment<16> { }; Alignment<16> and Alignment<8> both expose an operator new. If you now say new B, the compiler will look for operator new in B and will find two functions: // op new Alignment<8> IBase ^ / \ / \ / // op new \ / Alignment<16> A \ / \ / \ / B B -> Alignment<16> -> operator new B -> A -> Alignment<8> -> operator new Thus, this would be ambiguous and we would fail to compile: Neither of these hide the other one. But if you now inherit Alignment<16> virtually from Alignment<8> and make A and B inherit them virtually, the operator new in Alignment<8> will be hidden: // op new Alignment<8> IBase ^ / / \ / / \ / // op new / \ / Alignment<16> A \ / \ / \ / B This special hiding rule (also called dominance rule) however only works if all Alignment<8> objects are the same. Thus we always inherit virtually: In that case, there is only one Alignment<8> (or 16, ...) object existing in any given class hierarchy.
2,367,171
2,367,255
SIMD Sony Vector Math Library in OS X with C++
I'm currently writing a very simple game engine for an assignment and to make the code a lot nicer I've decided to use a vector math library. One of my lecturers showed me the Sony Vector Math library which is used in the Bullet Physics engine and it's great as far as I can see. I've got it working on Linux nicely but I'm having problems porting it to work on OS X (intel, Snow Leopard). I have included the files correctly in my project but the C++ version of the library doesn't seem to compile. I can get the C version of the library working but it has a fairly nasty API compared to the C++ version and the whole reason of using this library was to neaten the code in the first place. http://glosx.blogspot.com/2008/07/sony-vector-math-library.html This blog post that I've stumbled upon seems to suggest something's up with the compiler? It's fairly short so I couldn't take a lot of information from it. When I try to use the C++ version I get the following errors (expanded view of each error): /usr/include/vectormath/cpp/../SSE/cpp/vectormath_aos.h:156:0 /usr/include/vectormath/cpp/../SSE/cpp/vectormath_aos.h:156: error: '__forceinline' does not name a type second error: /Developer/apps/gl test/main.cpp:7:0 In file included from /Developer/apps/gl test/main.cpp /usr/include/vectormath/cpp/vectormath_aos.h:38:0 In file included from /usr/include/vectormath/cpp/vectormath_aos.h /usr/include/vectormath/cpp/../SSE/cpp/vectormath_aos.h:330:0 In file included from /usr/include/vectormath/cpp/../SSE/cpp/vectormath_aos.h /usr/include/vectormath/cpp/../SSE/cpp/vecidx_aos.h:45:0 Expected constructor, destructor, or type conversion before '(' token in /usr/include/vectormath/cpp/../SSE/cpp/vecidx_aos.h Finally two errors at the end of the main.cpp file: Expected '}' at the end of input Expected '}' at the end of input I've Googled my heart out but I can't seem to find any answers or anything to point me in the right direction so any help will be greatly received. Thanks,
Which compiler are you using on OS X ? There are 4 to choose from in the standard Xcode 3.2 install and the default is gcc 4.2. You might be better off trying gcc 4.0.
2,367,180
2,367,201
Change the address of a member function in C++
in C++, I can easily create a function pointer by taking the address of a member function. However, is it possible to change the address of that local function? I.e. say I have funcA() and funcB() in the same class, defined differently. I'm looking to change the address of funcA() to that of funcB(), such that at run time calling funcA() actually results in a call to funcB(). I know this is ugly, but I need to do this, thanks! EDIT---------- Background on what I'm trying to do: I'm hoping to implement unit tests for an existing code base, some of the methods in the base class which all of my modules are inheriting from are non-virtual. I'm not allowed to edit any production code. I can fiddle with the build process and substitute in a base class with the relevant methods set to virtual but I thought I'd rather use a hack like this (which I thought was possible). Also, I'm interested in the topic out of technical curiosity, as through the process of trying to hack around this problem I'm learning quite a bit about how things such as code generation & function look-up work under the hood, which I haven't had a chance to learn in school having just finished 2nd year of university. I'm not sure as to I'll ever be taught such things in school as I'm in a computer engineering program rather than CS. Back on topic The the method funcA() and funcB() do indeed have the same signature, so the problem is that I can only get the address of a function using the & operator? Would I be correct in saying that I can't change the address of the function, or swap out the contents at that address without corrupting portions of memory? Would DLL injection be a good approach for a situation like this if the functions are exported to a dll?
No. Functions are compiled into the executable, and their address is fixed throughout the life-time of the program. The closest thing is virtual functions. Give us an example of what you're trying to accomplish, I promise there's a better way.
2,367,202
2,367,232
C++ Pointer in Function
I know that technically all three ways below are valid, but is there any logical reason to do it one way or the other? I mean, lots of things in c++ are "technically valid" but that doesn't make them any less foolish. int* someFunction(int* input) { // code } or int *someFunction(int *input) { // code } or int * someFunction(int * input) { // code } I personally think the third one is annoying, but is there a "correct" way? I am typically more inclined to use the first one (as the second looks more like it's being used as the dereference operator - which it isn't)
All are equivalent. Choose the flavor that suits you best. Just be sure whichever you chose, you apply that choice in every case. Where your stars and curly braces go is far less important than putting them in the same place every time. Personally, I prefer int* someFunction(int* input);, but who cares?
2,367,293
2,367,374
turning a std::vector of objects in to an array of structures
I have a VS2008 C++ program where I'm wrapping a C API for use in a C++ program. The C API is expecting an array of TABLE_ENTRY values as shown below. Other than copying the data from each of the MyClass structures in to a new TABLE_ENTRY structure in MyClassCollection::GetTable(), is there a way to get the functionality I'm looking for? Thanks, PaulH struct TABLE_ENTRY { const char* description; DWORD value; }; class MyClass { public: MyClass( const char* desc, DWORD value ) : description( desc ), some_value( 1 ) { }; TABLE_ENTRY* GetTable() { entry_.description = description.c_str(); entry_.value = some_value; return &entry_; }; TABLE_ENTRY entry_; std::string description; DWORD some_value; }; class MyClassCollection { public: TABLE_ENTRY* GetTable() { return collection_.front()->GetTable(); }; void Add( MyClass* my_class ) { collection_.push_back( my_class ); } private: std::vector< MyClass* > collection_; }; int _tmain( int argc, _TCHAR* argv[] ) { MyClass class1( "class1", 1 ); MyClass class2( "class2", 2 ); MyClassCollection collection; collection.Add( &class1 ); collection.Add( &class2 ); TABLE_ENTRY* table = collection.GetTable(); // table is to be used by the C API. Therefore, these next // calls should function as shown. TABLE_ENTRY entry1 = table[ 0 ]; // should be class1's table (works) TABLE_ENTRY entry2 = table[ 1 ]; // should be class2's table (full of junk) return 0; }
I'd go for copying to a vector<TABLE_ENTRY> and pass &entries[0] to the C API. And, I would not store the TABLE_ENTRYs in your C++ class. I'd only make them just as you call the API, and then throw them away. That's because the TABLE_ENTRY duplicates the object you copy from, and it is storing a direct char* pointer to a string who's memory is managed by a std::string. If you modify the source string (and cause reallocation), you have a dangling pointer.
2,367,395
2,367,415
Global function header and implementation
how can I divide the header and implementation of a global function? My way is: split.h #pragma once #include <string> #include <vector> #include <functional> #include <iostream> void split(const string s, const string c); split.cpp #include "split.h" void split(const string& s, const string& c){ ... } main.cpp // main.cpp : Defines the entry point for the console application. // #include <string> #include <vector> #include <functional> #include <iostream> #include "stdafx.h" #include "split.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { vector<string> v; string s = "The;;woraaald;;is;;not;;enoaaaugh"; string c = " aaa ;; ccc"; split(s,c); return 0; } And errors are: Error 1 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int ...\split.h 8 Error 2 error C2146: syntax error : missing ',' before identifier 's' ...\split.h 8 How can I solve this problem? thx
In header file use std:: namespace qualifier - std::string
2,367,487
2,367,546
Why isn't copy constructor being called like I expect here using map?
I am having problems using my custom class with a std::map. The class dynamically allocates memory for members, and I do not want to use pointer in the map because I want to ensure that the class takes care of deleting all allocated memory. But the problem I am having is after I add item to map, when that block of code goes out of scope, the objects destructor is called even though it is still on the map. I made a fake bit of code below that shows what I mean. The output is: So the problem is why is the final destructor being called? Thanks in advance and sorry for the long question. Constructor Called Num:0034B7E8 Default Constructor Called Num:00000000 Copy Constructor Called Num:CCCCCCCC Copy Constructor Called Num:CDCDCDCD destructor called Num:CCCCCCCC destructor called Num:00000000 destructor called Num:0034B7E8 Inserted Num:0034B7E8 class myClass { public: myClass(int num) { mnNum = new int(); cout << "Constructor Called Num:" << mnNum << endl; } myClass() : mnNum(NULL) { cout << "Default Constructor Called Num:" << mnNum << endl; } myClass(const myClass &copy) { mnNum = new int(copy.mnNum); cout << "Copy Constructor Called Num:" << mnNum << endl; } ~myClass() { delete mnNum; mnNum = NULL; } int* mnNum; }; map<string,myClass> mvMyMap; void testFunction() { myClass lcObj(1); mvMyMap["Test"] = lcObj; } int _tmain(int argc, _TCHAR* argv[]) { testFunction(); cout << "Inserted Num:" << mvMyMap["Test"].mnNum << endl; return 0; }
myClass needs a custom assignment operator, in addition to the copy constructor. So when you make an assignment, you'll leak the original value on the left, and eventually double delete the value on the right.
2,367,521
2,367,576
SendInput (C++) is not working
The return value is 4 and I'm running Visual Studio in administrative mode so permissions should be ok. I don't see anything typed out though. Any help? I'm using Windows 7 x64. INPUT input[4]; input[0].type = INPUT_KEYBOARD; input[0].ki.wVk = 0; input[0].ki.wScan = 'a'; input[0].ki.dwFlags = KEYEVENTF_SCANCODE; input[0].ki.time = 0; input[0].ki.dwExtraInfo = 0; input[1].type = INPUT_KEYBOARD; input[1].ki.wVk = 0; input[1].ki.wScan = 'a'; input[1].ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE; input[1].ki.time = 0; input[1].ki.dwExtraInfo = 0; input[2].type = INPUT_KEYBOARD; input[2].ki.wVk = 0; input[2].ki.wScan = 'a'; input[2].ki.dwFlags = KEYEVENTF_SCANCODE; input[2].ki.time = 0; input[2].ki.dwExtraInfo = 0; input[3].type = INPUT_KEYBOARD; input[3].ki.wVk = 0; input[3].ki.wScan = 'a'; input[3].ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE; input[3].ki.time = 0; input[3].ki.dwExtraInfo = 0; int retval = SendInput(4, input, sizeof(INPUT)); if(retval > 0) { wxLogDebug("SendInput sent %i", retval); } else { wxLogError("Unable to send input commands. Error is: %i", GetLastError()); }
You need to send both KeyDown and KeyUp events for each key. To send a KeyUp event, set dwFlags to KEYEVENTF_KEYUP. Also, you need to use wVk instead of wScan. (wScan is only used with KEYEVENTF_UNICODE)
2,367,597
2,367,679
Null checking the null object pattern
The main goal of the Null Object Pattern is to ensure that a usable object is provided to the client. So we want to replace the following code... void Class::SetPrivateMemberA() { m_A = GetObject(); } void Class::UseA() { if (m_A != null) { m_A.Method(); } else { // assert or log the error } } ...with this implementation: void Class::SetPrivateMemberA() { m_A = GetObject(); } void Class::UseA() { m_A.Method(); } The problem I am thinking of is that GetObject() still returns an object, a NULL Object or otherwise. I like the idea of not checking for null repeatedly and trusting that the object sent back is usable, but why wouldn't I just do that in the first implementation? Is the advantage of the Null Object pattern just a slight increase in trust to clean up code? With the second implementation, is it not still a good practice to check that it is not null before calling A.Method()?
You're correct that, if you're sure you're never returning nulls, just skip the null check before calling the method in your first implementation. Likewise, if you do need to do something special in the case that UseA() needs to do something differently on a null object, that you need to explicitly check for a null object anyway. However, what null object pattern really helps with is those situations where it doesn't really matter. Take, for example, most observer patterns. If you implement your observer pattern as a member of your class for which there can only be one observer, and want to announce to the observer that your class did something, it doesn't matter to the class whether the observer is null or not. This is also illustrated with empty container classes, which are essentially the null object pattern: Instead of returning a null container from a query, you simply return an empty container. For things like iterating through all entries of a container, it often won't matter whether it's empty or not, so getting rid of the need of a null check makes the code more maintainable/more readable. However, if you want to populate a view of your data set, you still need to explicitly show a different "No entries." that checks for an empty container. Edit for clarity One problem is only looking at it from the call site. Like most design patterns, this needs to encompass both sides to be fully utilized. Consider: public PossiblyNull GetSomethingNull() { if (someBadSituation()) return null; else return SomehowProduceSomething(); } vs public PossiblyEmpty GetSomethingEmpty() { if (someBadSituation()) return StaticEmptySomething(); else return ProdueSomethingYay(); } Now, your call code, instead of looking like public void DoSomethingWithChild(Foo foo) { if (foo != null) { PossiblyNull bar = foo.GetSomething(); if (bar != null) bar.DoSomething(); } } it can be public void DoSomethingWithChild(Foo foo) { if (foo != null) foo.GetSomething().DoSomething(); }
2,367,891
2,367,920
adding to a set STL - C++
I have a media program. i am adding CD,dvd,book info. I managed to get the book info added to the set. I am now adding the CD info. I have most of the Cd info added but i have a seperate function for adding band members. thats where i need help! I am getting a cast error: error C2440: 'type cast' : cannot convert from 'const Item *const ' to 'CD' CD.h #ifndef CD_H #define CD_H #pragma once #include "item.h" class CD : public Item { public: CD(const string& theTitle, const string& theBand, const int snumber); const string addBandMember(const string& member); const int getNumber() const; const string getMusician() const; const string getBand() const; virtual void print(ostream& out) const; ~CD(); private: string band; string musicians; string title; int number; }; ostream& operator<<(ostream& out, const CD* cd); #endif CD.cpp const string CD::addBandMember(const string &member) { return this->musicians = member; }
In Library::addBandMember you're trying to cast a pointer to a class type you need to cast to CD* not CD And you probably don't want the 2 const in const Item* const musicCD since you want to modify the musicCD ! finally your CD::addBandMember method doesn't seem to add a band member but replace it.
2,367,911
2,368,021
Multithreaded application concept
I have a small architecture doubt about organizing code in separate functional units (most probably threads?). Application being developed is supposed to be doing the following tasks: Display some images on a screen (i.e. slideshow) Read the data from external device through the USB port Match received data against the corresponding image (stimulus) Do some data analysis Plot the results of data analysis My thoughts were to organize the application into the following modules: GUI thread (+ image slideshow) USB thread buffering the received data Thread for analyzing/plotting data (main GUI thread should not be blocked while plotting the data which might consume some more time) So, what do you generally think about this concept? Is there anything else you think that might be a better fit in this particular scenario?
A lot of this depends on how much is involved in performing 3 (Do some data analysis.) and 4 (Plot analyzed data.) My instincts would be: Definitely have a separate thread for reading the data off the USB. Assuming for a moment that 3 is dependent on reading the data, then I would do 3 in the same thread as reading the data. This will simplify your signaling to the GUI when the data is ready. This also assumes the processing is quick, and won't block the USB port (How is that being read? IO completion ports?). If the processing takes time then you need a separate thread. Likewise if image slide processing show takes a long time, this should be done in a separate thread. If this can be quickly recalculated depending say in a paint function, I would keep it as part of the main GUI. There is some overhead with context switch of threads, and for each thread added complexity of signaling. So I would only add a thread to solve blocking of the GUI and the USB port. It may be possible to do all of this in just two threads.
2,367,969
2,367,978
What would the evaluation order of x = x++ + ++x; be?
Possible Duplicate: Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…) In Java the evaluation order is specified to be left-to-right. Is this the case for C and C++ as well, or is it implementation dependent? I do remember that the evaluation order is unspecified for function arguments, but what about sub-expressions?
It is unspecified which of the arguments to + is evaluated first - but that doesn't even matter, because in C and C++, modifying the same object twice without an intervening sequence point is completely undefined behaviour. Here you're modifying x three times without an intervening sequence point, so you're well into here be dragonnes territory ;) The relevant part of the C99 standard is "6.5 Expressions": 2 Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored. and 3 The grouping of operators and operands is indicated by the syntax. Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified. It's possible to write legal code that demonstrates the unspecified order of evaluation - for example: #include <stdio.h> int foo(void) { puts("foo"); return 1; } int bar(void) { puts("bar"); return 2; } int main() { int x; x = foo() + bar(); putchar('\n'); return x; } (It is unspecified whether you get output of foobar or barfoo).
2,368,231
2,368,258
makefiles and using eclipse for Linux programs and C++
can anyone point me in the direction of a good tutorial on how makefiles work and also how to start a basic program from scratch using eclipse? I am using eclipse version 3.4.1 for fedora and C++. Thanks in advance.
CDT is the plugin used in eclipse for C++ development. Follow the link for a quick project creation tutorial. The same link has some information on how Eclipse uses makefiles.
2,368,424
2,368,438
Sorting a vector using threads
Are the vectors defined in the C++ STL re-entrant or thread safe? Can I use two threads and work(in this case sort) on two halfs of a vector without using a mutex? For example: int size = (Data_List.size())/2; Thread A() { ................ // Do we need to lock Data_list with a mutex sort(Data_List.begin(),Data_List.begin()+size,cmp); } Thread B() { ....// Do we need to lock Data_list with a mutex sort(Data_List.begin()+(size+1),Data_List.end(),cmp); } My Question is do we need to lock the access of Data_List using a mutex? Note: the cmp function is a regular int comparision function.
As long as the threads are working on different regions of memory and your comparison function only works with that memory and local variables, you should be ok. Essentially, you are "locking" each half of the table by dividing the work between the threads and only letting the thread work on its half of the data.
2,368,679
2,368,770
Using a std::string iterator to find the start and end of it's string
Given just a std::string iterator, is it possible to determine the start and end points of the string? Supposing that I don't have access to the string object and so cannot call string.begin() and string.end(), and all I can do is increment or decrement the iterator and test the value. Thanks, Phil
The short answer is no. The long answer is, because iterators aren't expected to know about the containers or ranges that are iterating over, they are only expected to Be able to jump to the next element (inc or dec to next or prev) Dereference themselves so as to reveal a reference to the value they are pointing to And over course compare themselves with other iterators most importantly an "end" iterator of some kind. Furthermore certain types iterators may do more than just the above, but principally they are all required to have/perform the above in some form or another.
2,368,728
2,368,794
Can normal maps be generated from a texture?
If I have a texture, is it then possible to generate a normal-map for this texture, so it can be used for bump-mapping? Or how are normal maps usually made?
Yes. Well, sort of. Normal maps can be accurately made from height-maps. Generally, you can also put a regular texture through and get decent results as well. Keep in mind there are other methods of making a normal map, such as taking a high-resolution model, making it low resolution, then doing ray casting to see what the normal should be for the low-resolution model to simulate the higher one. For height-map to normal-map, you can use the Sobel Operator. This operator can be run in the x-direction, telling you the x-component of the normal, and then the y-direction, telling you the y-component. You can calculate z with 1.0 / strength where strength is the emphasis or "deepness" of the normal map. Then, take that x, y, and z, throw them into a vector, normalize it, and you have your normal at that point. Encode it into the pixel and you're done. Here's some older incomplete-code that demonstrates this: // pretend types, something like this struct pixel { uint8_t red; uint8_t green; uint8_t blue; }; struct vector3d; // a 3-vector with doubles struct texture; // a 2d array of pixels // determine intensity of pixel, from 0 - 1 const double intensity(const pixel& pPixel) { const double r = static_cast<double>(pPixel.red); const double g = static_cast<double>(pPixel.green); const double b = static_cast<double>(pPixel.blue); const double average = (r + g + b) / 3.0; return average / 255.0; } const int clamp(int pX, int pMax) { if (pX > pMax) { return pMax; } else if (pX < 0) { return 0; } else { return pX; } } // transform -1 - 1 to 0 - 255 const uint8_t map_component(double pX) { return (pX + 1.0) * (255.0 / 2.0); } texture normal_from_height(const texture& pTexture, double pStrength = 2.0) { // assume square texture, not necessarily true in real code texture result(pTexture.size(), pTexture.size()); const int textureSize = static_cast<int>(pTexture.size()); for (size_t row = 0; row < textureSize; ++row) { for (size_t column = 0; column < textureSize; ++column) { // surrounding pixels const pixel topLeft = pTexture(clamp(row - 1, textureSize), clamp(column - 1, textureSize)); const pixel top = pTexture(clamp(row - 1, textureSize), clamp(column, textureSize)); const pixel topRight = pTexture(clamp(row - 1, textureSize), clamp(column + 1, textureSize)); const pixel right = pTexture(clamp(row, textureSize), clamp(column + 1, textureSize)); const pixel bottomRight = pTexture(clamp(row + 1, textureSize), clamp(column + 1, textureSize)); const pixel bottom = pTexture(clamp(row + 1, textureSize), clamp(column, textureSize)); const pixel bottomLeft = pTexture(clamp(row + 1, textureSize), clamp(column - 1, textureSize)); const pixel left = pTexture(clamp(row, textureSize), clamp(column - 1, textureSize)); // their intensities const double tl = intensity(topLeft); const double t = intensity(top); const double tr = intensity(topRight); const double r = intensity(right); const double br = intensity(bottomRight); const double b = intensity(bottom); const double bl = intensity(bottomLeft); const double l = intensity(left); // sobel filter const double dX = (tr + 2.0 * r + br) - (tl + 2.0 * l + bl); const double dY = (bl + 2.0 * b + br) - (tl + 2.0 * t + tr); const double dZ = 1.0 / pStrength; math::vector3d v(dX, dY, dZ); v.normalize(); // convert to rgb result(row, column) = pixel(map_component(v.x), map_component(v.y), map_component(v.z)); } } return result; }
2,368,772
2,368,938
How to lock Queue variable address instead of using Critical Section?
I have 2 threads and global Queue, one thread (t1) push the data and another one(t2) pops the data, I wanted to sync this operation without using function where we can use that queue with critical section using windows API. The Queue is global, and I wanted to know how to sync, is it done by locking address of Queue? Is it possible to use Boost Library for the above problem?
One approach is to have two queues instead of one: The producer thread pushes items to queue A. When the consumer thread wants to pop items, queue A is swapped with empty queue B. The producer thread continues pushing items to the fresh queue A. The consumer, uninterrupted, consumes items off queue B and empties it. Queue A is swapped with queue B etc. The only locking/blocking/synchronization happens when the queues are being swapped, which should be a fast operation since it's really a matter of swapping two pointers.
2,369,288
2,370,374
Image conversion : RGBA to RGB
assuming i had RGBA (32 bits) output from frame-grabber, with alpha channel unused (values retained while filled by frame-grabbers), is there any effective conversion method to RGB (24 bits) ? I am dealing with 5 MegaPixels streaming images so speed does matter too. keep in mind that data in alpha channel can be discarded.
Just copy the data and skip the unused alpha bytes. If speed is important for you, you may want to use SSE or MMX and use the built-in bit-shuffling instructions. That is usually a bit faster than ordinary c-code. 5 megapixels doesn't sound like that much of data unless you have to do it at 100fps though.
2,369,387
2,369,391
Tinyxml to print attributes
I'm trying to get std::string from attribute's value with TinyXml. The only thing I can get is a const char * val, and I can't find any way to convert from const char * to a std::string. so two possible answers to that: 1. How to get a string of an attribute with TinyXml? 2. How to convert const char * val to string val. this is the code I have now: TiXmlElement* data; data->Attribute("some_name"); // return const char * which seems like unconvertible. After googeling, I tried this: char * not_const= const_cast<char *> (data->Attribute("some_name")); There are no errors in the code itself, but after compiling and running I get exceptions.
std::string has a constructor that takes char const*. You don't need a char* for that. std::string str = data->Attribute("some_name"); However, be aware that std::string doesn't like NULL values, so don't give it any.
2,369,392
2,369,479
Inheriting both abstract class and class implementation in C++
I hope this is a simple question. Can I inherit both an abstract class and it's implementation? That is, can the following be made to work? class A { virtual void func1() = 0; } class B { void func1() { /* implementation here */ } } class C : public A, public B { } I've tried a few variations, and am getting compile errors complaining about unimplemented methods in class C. I can save a lot of repeated code if I can make this work, however. Is it possible? I solved this by creating a "composite class" called D which inherits from A & B, but contains the implementation code previously contained in B. This makes my inheritance model less clean, but it solves the problem without requiring code duplication. And, as I noted in the comments below, it makes my naming conventions pretty gross. class A { virtual void func1() = 0; } class B { // Other stuff } class D : public A, public B { void func1() { /* implementation here */ } } class C : public D { }
As Kirill pointed out: Your premise is wrong. Class B in your example does not inherit class A (it needs to be declared to do that first). Thus, B.func1() is something entirely different to A.func1() for the compiler. In class C it is expecting you to provide an implementation of A.func1() Somebody above posted something along the lines of: class C : public A, public B { // implement A::func1() virtual void func1() { // delegate to inherited func1() in class B B::func1(); } }
2,369,416
2,369,442
Creating a Cross-Platform C++ Library
I wanted to create a cross-platform 2D game engine, and I would like to know how to create a cross-platform project with Makefile, so I can compile it to the platforms I choose with custom rule for any platform. I'm working on the windows enviroment with Visual C++ Express 2008, so it would be nice if I can use Visual C++ Express as the IDE. My platforms are YET the Nintendo DS and the PC. Please instruct me what to do. Thanks in advance, Tamir.
Don't use make, use a cross-platform tool like cmake, it will take care of the platform-specific generation for you. Like on Windows, it will generate the project files to use Visual Studio; on Linux, it will generate the GNU make files for you. You can set it up to find the right versions of the right libraries and everything. Cmake is great. CMake is not a compiler (neither is make) - it is a cross-platform build automation system. It allows you to develop on any platform and it defaults to assuming you're developing for the platform you're running. You can specify parameters if you want to do other things. However, most of the "cross-platform" stuff is still left to your code. I would also recommend a library that has been tested on many platforms, like Boost. Using Boost can help keep all your code working smoothly on any system and there is basically no overhead to using it.
2,369,431
2,369,709
What is the use of a C++ class containing an "implementation" and "interface" pointer to itself?
I'm studying some source codes and I'm just wondering why a class (or classes) is often implemented this way: class EventHandler { ... EventDispatcher* m_Dispatcher; virtual bool ProcEvent( EventHandler* Sender, int Task, int Event, void* Param ); ... }; class ClassA: public EventHandler { ... ClassA* m_Impl; ClassA* m_Iface; ... public: // virtual functions virtual bool ProcEvent( EventHandler* Sender, int Task, int Event, void* Param ); virtual void OnDataWritten(const PIOResult&) {;} ... // sample functions void SetImplement( ClassA* aImpl ); void SetInterface( ClassA* aIface ); ClassA* GetImplement() { return m_Impl; } ClassA* GetInterface() { return m_Iface; } bool GetData( list& aList ); }; // Implementation of some sample functions; Most of its function contain more // or less the same format as below, with the return m_Impl->XXX having the same // name as the function being defined (e.g. A::XXX) bool ClassA::GetData( list&lt Data &gt& aList ) { if( m_Impl ) return m_Impl->GetData( aList ); else return false; } class ClassAFactory: public EventHandler { private: ClassAFactory* m_Impl; ClassAFactory* m_Iface; protected: virtual ClassA* MakeTransport(); virtual bool ProcEvent( EventHandler* Sender, int Task, int Event, void* Param ); virtual ClassA* CreateClassA() { return 0; } ... }; // In some member function of ClassB (ClassB inherits ClassA) switch( status ) { case 1: GetInterface()->OnDataWritten(); case 2: // ... }; I believe it's for some design pattern but I'm not familiar with it. It could help me understand if I know what it is. Can anyone help me point out which it could be or what is the use of these classes such that it is implemented this way? I think it's for some event handling and used together with some factory but I'm not sure.
I am afraid the names used do not have the usual meaning, so without examples of what is put in or how they are used, it's going to be difficult to guess. There are 2 design patterns that you should check, that make heavy use of this kind of self-recursion (at class level*): The Decorator Pattern The Composite Pattern And I am afraid that you are looking at something that fails to emulate either of those. In the Decorator, the point is to add functionality. To this end you have an Interface of which derives a Concrete class and a Wrapper interface. Then various wrappers will derive of Wrapper and you can chain them: Interface* interface = new Wrapper2( new Wrapper1 ( new Concrete() ) ); Each wrapper add some functionality, whereas here we only have perfect forwarding... so it's not a Decorator. The Composite pattern is different. Its goal is to hide whether you treat with a collection of elements or a single element. The usual example is a tree: you can apply operations either to an entire subtree or just a leaf node if it's implemented with a Composite Pattern. Once more, there is not such thing here. So my best guess is that you have either a wild design (perhaps a misguided attempt to emulate a well-known pattern) or you haven't given enough information (source code) for us to figure out the role. It seems strange anyway. *Note: by self-recursion at class level I mean that an object of class A points to another object of class A, but this does not mean (certainly) that it points to the same instance... otherwise we would have a Stack Overflow (pun intended). This not the same instance bit is certainly worth checking during the SetImplementation call: note that any cyclic reference would cause death by recursion.
2,369,525
2,369,772
how to tell if a stream is closed in C before calling fclose()
I have a failing C program, and i've narrowed it down to a fork()ed child trying to close stdout and stderr, which were closed by its parent process before calling fork() - i assume those streams were passed on to the child process. how can i tell if a stream is closed in C before attempting to close it using something like fclose(stdout)
C programs on UNIX expect to have a file descriptors 0, 1 and 2 open when they are started. If you do not want them to go anywhere, open /dev/null and dup it to those file descriptors.
2,369,541
2,369,593
Where is `%p` useful with printf?
After all, both these statements do the same thing... int a = 10; int *b = &a; printf("%p\n",b); printf("%08X\n",b); For example (with different addresses): 0012FEE0 0012FEE0 It is trivial to format the pointer as desired with %x, so is there some good use of the %p option?
They do not do the same thing. The latter printf statement interprets b as an unsigned int, which is wrong, as b is a pointer. Pointers and unsigned ints are not always the same size, so these are not interchangeable. When they aren't the same size (an increasingly common case, as 64-bit CPUs and operating systems become more common), %x will only print half of the address. On a Mac (and probably some other systems), that will ruin the address; the output will be wrong. Always use %p for pointers.
2,369,545
2,369,632
Can I catch an exception relating to a .DLL file not been found
I have a 3rd party component that includes a .LIB and .DLL file. In order to use the component I link the .LIB into my C++ program, and distribute the .DLL with application. The functionality provided is very specific, and only relevent to a small sub-set of my users, but distributing the .DLL incurs a license fee. One work around here is to have two versions of my app, one which links in the 3rd party component, the other that doesn't, but I'd rather avoid the extra time involved in maintaining and distributing a second build. Ideally, I'd like to simply exclude the .DLL from the distribution, but if I do this I get the error 'This application has failed to start because XXXXX.DLL was not found. Re-Installing the application may fix this problem'. Is this an exception that I can catch and deal with in my code? Alternatively, can I delay the loading of the .DLL until an attempt is made to call the specific functionality provided, and handle it then, or simply check for the existence of the .DLL and act accordingly? The environment is VS 2003 and VS 2008.
There is no way to stop the binding after linked with the dll. The only way that youo have is if you dynamically load the dll during runtime. Dll resolving is done before your exe starts running. Code could look somehow like that. If this does not work for your third party dll you could write an own dll that wrapps the third party dll and which can be loaded dynamically at runtime. HINSTANCE lib = LoadLibraryEx("C:\dlls\thirdparty.dll", NULL, LOAD_WITH_ALTERED_SEARCH_PATH); if(0 != lib) { // Dll is present so use it typedef CObj ( __cdecl *tFunction ) (const wchar_t*, const int&); tFunction functionEntry = (tFunction)(GetProcAddress( lib,"EntryFunction")); assert(0 != functionEntry); // call the function CObj obj = functionEntry(L"Hello", 1); } else { // dll not present } Update: Please make sure that you use fullpath to your dll to make sure not any dll is pulled that has this name.
2,369,553
2,369,605
iphone compiler inherited templated base classes with passed through type not being expanded in time (just look)
Try this out: template <typename T> class Base { public: int someBaseMember; }; template <typename T> class Test: public Base<T> { public: void testFunc() { someBaseMember = 0; } }; In vc++ and the psp compiler (and any other compiler I've encountered) the above will work fine, with the iphone compiler (for device, gcc 4.2 I think, with the -fpermissive flag set) I get an error saying 'someBaseMember is not defined' on the 'someBaseMember = 0;' line The iphone compiler seems to be 'parsing' templated code a lot sooner than other compilers do, (from what I can tell, most others don't even syntax check them until you actually CALL the function, or instantiate an instance.) From what I can tell its parsing it so soon that it hasn't even parsed the base class yet :S its like it doesn't exist. Any Ideas?
The error that you are getting is correct (the other compilers should not accept the code and are doing so erroneously); the variable someBaseMember depends on the template instantation of Base<T>, but this dependence has not been expressed in your usage, and hence the compiler is correct in attempting to resolve it independently of the template parameter. You can resolve this problem by making this dependence explicit, thereby forcing the compiler to resolve the variable using the template instantation. You can use either of the following: this->someBaseMember = 0; OR Base<T>::someBaseMember = 0; Either of the above should result in the resolution mechanism you want. EDIT You might want to see the relevant section of the C++ FAQ Lite: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19 http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18
2,369,629
2,369,649
An unhandled win32 exception occurred in MyApp.exe
WinXP used. When I click the default cross icon to close my application. The win form of my application disappeared, but MyApp process still alive in the processes list when I open the task manager window. About 5 seconds later, throw out the unhandled win32 exception error. Where can I set the break point? I don't know how to debug it. Thanks. [updated] What is the exception received? When I run MyApp.exe(Debug Version). Visual Studio Just-In-Time Debugger Window An unhandled win32 exception occurred in MyApp.exe[520] The [520] always changed to different numbers. such as [5904],[304],etc.
Attach your Vc to the program. Enable catch of all exeptions. Close your application and see where it stops.