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
3,020,146
3,021,579
resources for embedded projects
Can anyone suggest links/resources for sample project implementations of embedded projects using c++ or gcc.
Many resources are target specific, so you will have to be more specific if you want a specific answer. However http://embedded.com/ is a good general resource, and depending on your geographical location, you may qualify for a free subscription to Embedded Systems Design or Embedded Systems Design Europe paper publications. Apart from Atmel AVR, GCC is targetted for 16/32bit targets, and C++ is generally ambitious and unnecessary for 8 bit, so I am guessing we are considering 16/32bit targets? You might also take a look at: Martin Thomas's ARM-Projects, including a GCC toolchain for Windows. http://embdev.net/ which includes an embedded GCC forum. Building Bare-Metal ARM Systems with GNU A description of bringing up a system using GCC with C and C++ FreeRTOS a well respected and widely used open-source RTOS kernel eCos another open-source RTOS, but somewhat more than a scheduler kernel.
3,020,255
3,020,296
Using new to allocate an array of class elements with an overloaded constructor in C++
As an example say I have a class foo that does not have a default constructor but one that looks like this foo:foo(int _varA,int _varB) { m_VarA = _varA; m_VarB = _varB; } How would I allocate an array of these. I seem to remember trying somthing like this unsuccessfully. foo* MyArray = new foo[100](25,14). I don't think this will work either. foo* MyArray = new foo[100](25,14) Can this be done? I typically do this by writing the default constructor using some preset values for _varA and _varB. Then adding a function to reset _varA and _varB for each element but that will not work for this case. Thanks for the help.
If you are to be able to allocate an array of a class (directly, using new[]), the class must have a default constructor. No default constructor, no dynamic arrays.
3,020,274
3,043,388
Can I write a test that succeeds if and only if a statement does not compile?
I'd like to prevent clients of my class from doing something stupid. To that end, I have used the type system, and made my class only accept specific types as input. Consider the following example (Not real code, I've left off things like virtual destructors for the sake of example): class MyDataChunk { //Look Ma! Implementation! }; class Sink; class Source { virtual void Run() = 0; Sink *next_; void SetNext(Sink *next) { next_ = next; } }; class Sink { virtual void GiveMeAChunk(const MyDataChunk& data) { //Impl }; }; class In { virtual void Run { //Impl } }; class Out { }; //Note how filter and sorter have the same declaration. Concrete classes //will inherit from them. The seperate names are there to ensure only //that some idiot doesn't go in and put in a filter where someone expects //a sorter, etc. class Filter : public Source, public Sink { //Drop objects from the chain-of-command pattern that don't match a particular //criterion. }; class Sorter : public Source, public Sink { //Sorts inputs to outputs. There are different sorters because someone might //want to sort by filename, size, date, etc... }; class MyClass { In i; Out o; Filter f; Sorter s; public: //Functions to set i, o, f, and s void Execute() { i.SetNext(f); f.SetNext(s); s.SetNext(o); i.Run(); } }; What I don't want is for somebody to come back later and go, "Hey, look! Sorter and Filter have the same signature. I can make a common one that does both!", thus breaking the semantic difference MyClass requires. Is this a common kind of requirement, and if so, how might I implement a test for it?
With the latest clarification the problem is simple: void foo(Filter*); void foo(Sorter*); template<typename T> void test() { foo((T*)NULL); } If anyone passes a class that's both a Filter and a Sorter, the overload resolution is ambiguous.
3,020,316
3,020,328
What VS 2010 Template to Chose?
I am just getting started with C++ and wanted to know does it really matter what template you chose in Visual Studio 2010 (for creating executables)? Like if I was creating a console application there is CLR Console Application, Win32 Console Application, and Win32 Project (description says it can be an application or a dll), what would I chose (or could i select Empty Project)?
If you are learning the C++ language itself, you probably want just a console based application. It means basically that you will have a black window that pops up and you can use things like std::cout to output to standard output and std::cin to get input from that console as well. You probably do not want the CLR console based application because that is for C++ / CLI which is a different language from what C++ is. Likewise you could use Win32 or MFC as well but that's meant mostly for GUI applications or applications that you don't want a black window popping up.
3,020,425
3,020,520
C++ Multiple inheritance with interfaces?
Greetings all, I come from Java background and I am having difficulty with multiple inheritance. I have an interface called IView which has init() method.I want to derive a new class called PlaneViewer implementing above interface and extend another class. (QWidget). My implementation is as: IViwer.h (only Header file , no CPP file) : #ifndef IVIEWER_H_ #define IVIEWER_H_ class IViewer { public: //IViewer(); ///virtual //~IViewer(); virtual void init()=0; }; #endif /* IVIEWER_H_ */ My derived class. PlaneViewer.h #ifndef PLANEVIEWER_H #define PLANEVIEWER_H #include <QtGui/QWidget> #include "ui_planeviewer.h" #include "IViewer.h" class PlaneViewer : public QWidget , public IViewer { Q_OBJECT public: PlaneViewer(QWidget *parent = 0); ~PlaneViewer(); void init(); //do I have to define here also ? private: Ui::PlaneViewerClass ui; }; #endif // PLANEVIEWER_H PlaneViewer.cpp #include "planeviewer.h" PlaneViewer::PlaneViewer(QWidget *parent) : QWidget(parent) { ui.setupUi(this); } PlaneViewer::~PlaneViewer() { } void PlaneViewer::init(){ } My questions are: Is it necessary to declare method init() in PlaneViewer interface also , because it is already defined in IView? 2.I cannot complie above code ,give error : PlaneViewer]+0x28): undefined reference to `typeinfo for IViewer' collect2: ld returned 1 exit status Do I have to have implementation for IView in CPP file (because all I want is an interface,not as implementation) ?
Is it necessary to declare method init() in PlaneViewer interface also , because it is already defined in IView? You do not have to declare init() in PlaneViewer, but if you don't PlaneViewer will be an abstract class, meaning that you cannot instantiate it. If you mean to ask if you have to have 'void init();' in the header file for PlaneViewer and in the .cpp file. The answer is yes. I cannot complie above code ,give error : PlaneViewer]+0x28): undefined reference to `typeinfo for IViewer' collect2: ld returned 1 exit status I think either you are not building the same code or your compile command is incorrect. I stripped out the QT stuff and was able to build your code just fine with g++. The error means that the IViewer class was not found by the linker. I get that error if I remove the '=0' part that makes 'IViewer::init()' a pure virtual function. You could also get that error if you uncommented the constructor and/or destructor in IViewer. Do I have to have implementation for IView in CPP file? No. C++ does not care if it is in a .cpp file or a .h file. Unlike Java, the C/C++ preprocessor first resolves all the includes and generates one file containing all the code. It then passes this to the C/C++ compiler. You can actually include a .cpp if you want. Not a good idea though.
3,020,441
3,020,469
Academic question: typename
Possible Duplicate: Why do I need to use typedef typename in g++ but not VS? Hi, recently I accounted with a "simple problem" of porting code from VC++ to gcc/intel. The code is compiles w/o error on VC++: #include <vector> using std::vector; template <class T> void test_vec( std::vector<T> &vec) { typedef std::vector<T> M; /*==> add here typename*/ M::iterator ib=vec.begin(),ie=vec.end(); }; int main() { vector<double> x(100, 10); test_vec<double>(x); return 0; } then with g++ we have some unclear errors: g++ t.cpp t.cpp: In function 'void test_vec(std::vector<T, std::allocator<_CharT> >&)': t.cpp:13: error: expected `;' before 'ie' t.cpp: In function 'void test_vec(std::vector<T, std::allocator<_CharT> >&) [with T = double]': t.cpp:18: instantiated from here t.cpp:12: error: dependent-name 'std::M::iterator' is parsed as a non-type, but instantiation yields a type t.cpp:12: note: say 'typename std::M::iterator' if a type is meant If we add typename before iterator the code will compile w/o pb. If it is possible to make a compiler which can understand the code written in the more "natural way", then for me is unclear why we should add typename? Which rules of "C++ standards"(if there are some) will be broken if we allow all compilers to use without "typename"? kind regards Arman.
Here is a page that explains typename.
3,020,584
3,020,589
Avoid warning 'Unreferenced Formal Parameter'
I have a super class like this: class Parent { public: virtual void Function(int param); }; void Parent::Function(int param) { std::cout << param << std::endl; } ..and a sub-class like this: class Child : public Parent { public: void Function(int param); }; void Child::Function(int param) { ;//Do nothing } When I compile the sub-class .cpp file, I get this error warning C4100: 'param' : unreferenced formal parameter As a practice, we used to treat warnings as errors. How to avoid the above warning? Thanks.
In C++ you don't have to give a parameter that you aren't using a name so you can just do this: void Child::Function(int) { //Do nothing } You may wish to keep the parameter name in the declaration in the header file by way of documentation, though. The empty statement (;) is also unnecessary.
3,020,725
3,020,749
char array to LPCTSTR
May I know how I can perform the following conversion? // el.strCap is char[50] // InsertItem is expecting TCHAR pointer (LPCTSTR) // How I can perform conversion? // I do not have access in both "list" and "el" source code // Hence, there is no way for me to modify their signature. list.InsertItem(i, el.strCap); And No. I do not want to use WideCharToMultiByte They are too cumbersome to be used.
If you're using ATL, then you can use the various macros and helper classes that it includes to do the conversion: char *test = "Hello World"; CA2CT ct(test); list.InsertItem(i, ct); Though saying WideCharToMultiByte is too cumbersome is a bit disingenious, in my opinion. It's easy enough to wrap a call to WideCharToMultiByte and make it return an std::wstring or whatever you need. In fact, that's basically what CA2CT is doing under the covers...
3,020,763
3,021,408
why parent window don't get notifications from child combobox?
I create a simple window with a comboboxex (with inserting few bitmaps), I need to know when user has selected an item from combo-box(I need CBEN_ENDEDIT I think). But Parent window don't get any WM_NOTIFY from that combo-box except one value. Can anyone help me with this please? Why I can't get the notifications ? //Window creating WNDCLASSEX wcx={0}; wcx.cbSize = sizeof(WNDCLASSEX); wcx.lpfnWndProc = WndProc; wcx.hInstance = hInst; RegisterClassEx(&wcx) HWND parent =CreateWindowEx()//-Created with some args //WndProc switch (uMsg) { case WM_CREATE: { //-Creating comboboxex DWORD dwStyle = CBS_DROPDOWNLIST | WS_CHILD |WS_VISIBLE; HWND child = CreateWindowEx(0, WC_COMBOBOXEX,0, dwStyle, x, y, w, h, parent, IDC_CMBX, hinst, 0) } case WM_NOTIFY : { LPNMHDR nmhdr = (LPNMHDR)lParam; //Here nmhdr->code value is always 4294967279 -I think it is NM_SETCURSOR ? } } Thank you very much.
What you probably want is CBN_SELCHANGE. From MSDN: The CBN_SELCHANGE notification message is sent when the user changes the current selection in the list box of a combo box. The user can change the selection by clicking in the list box or by using the arrow keys. The parent window of the combo box receives this notification in the form of a WM_COMMAND message with CBN_SELCHANGE in the high-order word of the wParam parameter. So in this case you have to handle WM_COMMAND instead of WM_NOTIFY and check if the high-order word of the wParam parameter is CBN_SELCHANGE.
3,020,767
3,022,127
Obtaining MFC Feature Pack GUI elements in .NET WinForms
The MFC Feature Pack (and VS 2010) adds out-of-the-box support for several "modern" GUI elements (such as MDI with tabbed documents, the ribbon, and a Visual Studio-style interface with docking panels). These are a boon to those of us that have to support legacy MFC-based applications and want to update their look-and-feel, and a sign that Microsoft has not completely abandoned unmanaged C++ development. However, with the push so strongly in favor of .NET, WinForms, and managed code (and for plenty of good reasons), there seems little reason to develop new applications in unmanaged C++/MFC. The question then becomes how does one obtain these GUI elements in a WinForms application. Almost all of the add-ons and libraries I have found so far cost money, and introduce additional dependencies. I don't have a budget to buy third-party libraries, and the controls provided by Microsoft in MFC for free seem sufficient for our needs. But I still have reservations about learning MFC to develop a new application. Not only does the investment in time seem significant (by all accounts, MFC seems particularly difficult to learn, even for experienced .NET developers--although I am willing to try), but the question of MFC's lifespan is raised as well. Certainly, given the millions of lines of code and existing apps written in native C++, it will be around for some time, but the handwriting seems to be on the wall, so to speak, that it's no longer Microsoft's touted development platform. It seems like these features should be available by now in WinForms without the need for third-party add-ons, or devoting a lot of time and resources to custom-drawing EVERYTHING. Am I just missing something? I find very little online that compares these new features of MFC to what is available in WinForms, mainly because most everything written on MFC pre-dated its most recent update, before which it looked admitted "dated," and with its other flaws, was hardly an appealing platform for new development. With the very recent release of VS 2010, we have a while to wait before WinForms gets updated again. What routes are you guys taking for applications whose customers demand a modern-looking UI on a budget?
Most of these features are provided to .NET developers through WPF, not WinForms. Nothing is going to meet your expectation of "should be available by now in WinForms" because WinForms is not being added to. Like COM before it, "it's not dead, but it's done". I think you have your answer in your question. If you're maintaining an MFC app, go ahead and make it look 21st century. If you know MFC well, go ahead and use it for a new app. If you've made the switch to managed code, and would need to learn MFC to use it, put that energy into learning WPF. There are some "converters" that change WinForms to WPF to save you some time and help you understand WPF more quickly - http://wf2wpf.codeplex.com/ for example.
3,020,913
3,020,949
Shift count negative or too big error - correct solution?
I have the following function for reading a big-endian quadword (in a abstract base file I/O class): unsigned long long File::readBigEndQuadWord(){ unsigned long long qT = 0; qT |= readb() << 56; qT |= readb() << 48; qT |= readb() << 40; qT |= readb() << 32; qT |= readb() << 24; qT |= readb() << 16; qT |= readb() << 8; qT |= readb() << 0; return qT; } The readb() functions reads a BYTE. Here are the typedefs used: typedef unsigned char BYTE; typedef unsigned short WORD; typedef unsigned long DWORD; The thing is that i get 4 compiler warnings on the first four lines with the shift operation: warning C4293: '<<' : shift count negative or too big, undefined behavior I understand why this warning occurs, but i can't seem to figure out how to get rid of it correctly. I could do something like: qT |= (unsigned long long)readb() << 56; This removes the warning, but isn't there any other problem, will the BYTE be correctly extended all the time? Maybe i'm just thinking about it too much and the solution is that simple. Can you guys help me out here? Thanks.
Your way of removing the warning is correct. As you probably do already know, the warning is occurring because you're trying to shift the contents of a byte beyond the boundaries of a word, then store it in the quadword. This operation is undefined. (It will evaluate the right-side of the assignment before assigning the value.) By explicitly casting first, there is now enough space to do the shift, so there's nothing to complain about. Arguably, the compiler should be able to figure out you're going to store it in the quadword, so it should allocate a quadword first and do the shift there, but it might not have been made smart enough to figure it out. Also, I'm not sure about this, but possibly compiling this for x64 will also not generate the warning, as one word is 64 bits?
3,021,134
3,512,429
GCC/XCode equivalent of _CrtCheckMemory?
When dealing with random memory overwrites, in MSVC it is possible to validate the state of the heap at various points with a call to _CrtCheckMemory, and know with at least a small level of confidence that the code up until the check was not responsible for any errors that might cause new or malloc to fail later. In XCode, whats the equivalent way to try and box in a memory overwrite? All I have at the moment is a random failure of a call to new, somewhere deep in the bowels of some code with no real idea of how long the code has been running with a corrupt heap up until that point.
This feature IS actually built into the heap in GCC. As described here The easiest way to enable it is on the XCode::Run menu: Enable Guard Malloc
3,021,333
3,022,238
Can I use memcpy in C++ to copy classes that have no pointers or virtual functions
Say I have a class, something like the following; class MyClass { public: MyClass(); int a,b,c; double x,y,z; }; #define PageSize 1000000 MyClass Array1[PageSize],Array2[PageSize]; If my class has not pointers or virtual methods, is it safe to use the following? memcpy(Array1,Array2,PageSize*sizeof(MyClass)); The reason I ask, is that I'm dealing with very large collections of paged data, as decribed here, where performance is critical, and memcpy offers significant performance advantages over iterative assignment. I suspect it should be ok, as the 'this' pointer is an implicit parameter rather than anything stored, but are there any other hidden nasties I should be aware of? Edit: As per sharptooths comments, the data does not include any handles or similar reference information. As per Paul R's comment, I've profiled the code, and avoiding the copy constructor is about 4.5 times faster in this case. Part of the reason here is that my templated array class is somewhat more complex than the simplistic example given, and calls a placement 'new' when allocating memory for types that don't allow shallow copying. This effectively means that the default constructor is called as well as the copy constructor. Second edit It is perhaps worth pointing out that I fully accept that use of memcpy in this way is bad practice and should be avoided in general cases. The specific case in which it is being used is as part of a high performance templated array class, which includes a parameter 'AllowShallowCopying', which will invoke memcpy rather than a copy constructor. This has big performance implications for operations such as removing an element near the start of an array, and paging data in and out of secondary storage. The better theoretical solution would be to convert the class to a simple structure, but given this involves a lot of refactoring of a large code base, avoiding it is not something I'm keen to do.
According to the Standard, if no copy constructor is provided by the programmer for a class, the compiler will synthesize a constructor which exhibits default memberwise initialization. (12.8.8) However, in 12.8.1, the Standard also says, A class object can be copied in two ways, by initialization (12.1, 8.5), including for function argument passing (5.2.2) and for function value return (6.6.3), and by assignment (5.17). Conceptually, these two operations are implemented by a copy constructor (12.1) and copy assignment operator (13.5.3). The operative word here is "conceptually," which, according to Lippman gives compiler designers an 'out' to actually doing memberwise initialization in "trivial" (12.8.6) implicitly defined copy constructors. In practice, then, compilers have to synthesize copy constructors for these classes that exhibit behavior as if they were doing memberwise initialization. But if the class exhibits "Bitwise Copy Semantics" (Lippman, p. 43) then the compiler does not have to synthesize a copy constructor (which would result in a function call, possibly inlined) and do bitwise copy instead. This claim is apparently backed up in the ARM, but I haven't looked this up yet. Using a compiler to validate that something is Standard-compliant is always a bad idea, but compiling your code and viewing the resulting assembly seems to verify that the compiler is not doing memberwise initialization in a synthesized copy constructor, but doing a memcpy instead: #include <cstdlib> class MyClass { public: MyClass(){}; int a,b,c; double x,y,z; }; int main() { MyClass c; MyClass d = c; return 0; } The assembly generated for MyClass d = c; is: 000000013F441048 lea rdi,[d] 000000013F44104D lea rsi,[c] 000000013F441052 mov ecx,28h 000000013F441057 rep movs byte ptr [rdi],byte ptr [rsi] ...where 28h is the sizeof(MyClass). This was compiled under MSVC9 in Debug mode. EDIT: The long and the short of this post is that: 1) So long as doing a bitwise copy will exhibit the same side effects as memberwise copy would, the Standard allows trivial implicit copy constructors to do a memcpy instead of memberwise copies. 2) Some compilers actually do memcpys instead of synthesizing a trivial copy constructor which does memberwise copies.
3,021,377
3,021,399
How can I use Boost::regex.hpp library in C++?
I tried to use Boost library but I failed, see my code: #include "listy.h" #include <boost/regex.hpp> using namespace boost; ListyCheck::ListyCheck() { } ListyCheck::~ListyCheck() { } bool ListyCheck::isValidItem(std::string &__item) { regex e("(\\d{4}[- ]){3}\\d{4}"); return regex_match(__item, e); } When I tried to compile it I get those messages: /usr/include/boost/regex/v4/regex_match.hpp:50: undefined reference to `boost::re_detail::perl_matcher<__gnu_cxx::__normal_iterator, std::allocator > >, std::allocator, std::allocator > > > >, boost::regex_traits > ::match()' /usr/include/boost/regex/v4/basic_regex.hpp:425: undefined reference to `boost::basic_regex > ::do_assign(char const*, char const*, unsigned int)' /usr/include/boost/regex/v4/perl_matcher.hpp:366: undefined reference to `boost::re_detail::perl_matcher<__gnu_cxx::__normal_iterator, std::allocator > >, std::allocator, std::allocator > > > >, boost::regex_traits > ::construct_init(boost::basic_regex > > const&, boost::regex_constants::_match_flags)' etc...
Those are linker errors. The Boost regex library is not a header-only library like shared_ptr (for example) - you need to link against the .a or .lib or whatever binary library.
3,021,441
4,742,879
Events with QGraphicsItemGroup
In my application I want to use QGraphicsItemGroup for grouping items into one item. I played with it a little and not sure using it because when I want to catch events, events are merged together but I want to handle specific event with specific child. How can I achieve this?
You need to call QGraphicsItemGroup::setHandlesChildEvents(false). This stops the QGraphicsItemGroup trying to handle the event, and lets the child QGraphicsItems handle them instead.
3,021,535
3,027,682
does windows 7 bluetooth stack and API support connection of headsets
We need to write code to search for, pair and connect to a bluetooth headset with Windows 7 Embedded. Once connected the headset will be used as a normal windows audio device. We fully control what software is installed on the system so conflicting stacks and similar concerns are not a problem. We would however like to minimize as far as possible installing extra software such as 3rd party stacks. Therefore my question is: can the built in windows 7 bluetooth stack and C++ API alone be used to create the functionality we need?
Windows 7 does not contain an in-box driver for BT audio, however if you pair an audio device an audio driver should be available from windows update.
3,021,558
3,021,781
How to best use GCC with Visual Studio
I know this thread GCC with Visual Studio? but to me it seems that everything mentioned there is rather outdated and it seems to be the tenor is: don't do it Who knows a better step by step explanation thank you in advance Oops
Well, unfortunately there is still no plugin for Visual Studio. Using makefiles seems to still be the best idea and there are several tools to automate their building. As far as I remember, the best tool for this that I've used is Makefile Wizard, which allows almost automatic VC project to makefile converting. Also to mention, it can be paired with some external building system.
3,021,560
3,021,575
Do not properly deleted pointers fragment memory?
That's basically the question. If I have a pointer int *a = &someIntVar and I do not delete it over the course of the program, does it stay in memory after the program has terminated? Is this a case of data fragmentation? EDIT: My mistake for using a bad example. So int *a = new int[100]; never gets deleted, and even if it gets deleted, an answer says that the pointee is deleted, not the pointer. Yet pointers also have a length. So the question is, on a Windows or Linux OS, does it automatically clean up after pointers? (Assume C++)
Since you have not newed this pointer, you are not leaking memory. Were you to do int* a = new int; and not delete a, then you would leak a. As a rule of thumb, the number of news should equal the number of deletes. When someIntVar goes out of scope, the stack is unwound and its memory will be freed and a will be left dangling, of course.
3,021,572
3,021,632
Two phase Construction in C++
I have as part of assignment to look into a development kit that uses the "two-phase" construction for C++ classes: // Include Header class someFubar{ public: someFubar(); bool Construction(void); ~someFubar(); private: fooObject _fooObj; } In the source // someFubar.cpp someFubar::someFubar : _fooObj(null){ } bool someFubar::Construction(void){ bool rv = false; this->_fooObj = new fooObject(); if (this->_fooObj != null) rv = true; return rv; } someFubar::~someFubar(){ if (this->_fooObj != null) delete this->_fooObj; } Why would this "two-phase" be used and what benefits are there? Why not just instantiate the object initialization within the actual constructor?
A document about Two Phase Construction. The idea is that you cannot return a value from a constructor to indicate failure. The only way to indicate constructor failure is to throw an exception. This is not always desirable, not least because exception safety is a very complex topic. So in this case the construction is split up: a constructor that does not throw, but also does not fully initialize, and a function that does the initialization and can return an indication of success or failure without (necessarily) throwing exceptions.
3,021,854
3,022,248
Signals and threads - good or bad design decision?
I have to write a program that performs highly computationally intensive calculations. The program might run for several days. The calculation can be separated easily in different threads without the need of shared data. I want a GUI or a web service that informs me of the current status. My current design uses BOOST::signals2 and BOOST::thread. It compiles and so far works as expected. If a thread finished one iteration and new data is available it calls a signal which is connected to a slot in the GUI class. My question(s): Is this combination of signals and threads a wise idea? I another forum somebody advised someone else not to "go down this road". Are there potential deadly pitfalls nearby that I failed to see? Is my expectation realistic that it will be "easy" to use my GUI class to provide a web interface or a QT, a VTK or a whatever window? Is there a more clever alternative (like other boost libs) that I overlooked? following code compiles with g++ -Wall -o main -lboost_thread-mt <filename>.cpp code follows: #include <boost/signals2.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <iostream> #include <iterator> #include <string> using std::cout; using std::cerr; using std::string; /** * Called when a CalcThread finished a new bunch of data. */ boost::signals2::signal<void(string)> signal_new_data; /** * The whole data will be stored here. */ class DataCollector { typedef boost::mutex::scoped_lock scoped_lock; boost::mutex mutex; public: /** * Called by CalcThreads call the to store their data. */ void push(const string &s, const string &caller_name) { scoped_lock lock(mutex); _data.push_back(s); signal_new_data(caller_name); } /** * Output everything collected so far to std::out. */ void out() { typedef std::vector<string>::const_iterator iter; for (iter i = _data.begin(); i != _data.end(); ++i) cout << " " << *i << "\n"; } private: std::vector<string> _data; }; /** * Several of those can calculate stuff. * No data sharing needed. */ struct CalcThread { CalcThread(string name, DataCollector &datcol) : _name(name), _datcol(datcol) { } /** * Expensive algorithms will be implemented here. * @param num_results how many data sets are to be calculated by this thread. */ void operator()(int num_results) { for (int i = 1; i <= num_results; ++i) { std::stringstream s; s << "["; if (i == num_results) s << "LAST "; s << "DATA " << i << " from thread " << _name << "]"; _datcol.push(s.str(), _name); } } private: string _name; DataCollector &_datcol; }; /** * Maybe some VTK or QT or both will be used someday. */ class GuiClass { public: GuiClass(DataCollector &datcol) : _datcol(datcol) { } /** * If the GUI wants to present or at least count the data collected so far. * @param caller_name is the name of the thread whose data is new. */ void slot_data_changed(string caller_name) const { cout << "GuiClass knows: new data from " << caller_name << std::endl; } private: DataCollector & _datcol; }; int main() { DataCollector datcol; GuiClass mc(datcol); signal_new_data.connect(boost::bind(&GuiClass::slot_data_changed, &mc, _1)); CalcThread r1("A", datcol), r2("B", datcol), r3("C", datcol), r4("D", datcol), r5("E", datcol); boost::thread t1(r1, 3); boost::thread t2(r2, 1); boost::thread t3(r3, 2); boost::thread t4(r4, 2); boost::thread t5(r5, 3); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); datcol.out(); cout << "\nDone" << std::endl; return 0; }
Is this combination of signals and threads a wise idea? I another forum somebody advised someone else not to "go down this road". It seems to be sound. Can you provide a link to the other thread? Were they explaining their reasoning? Are there potential deadly pitfalls nearby that I failed to see? If they are I fail to see them also. What you need to take care of is that the notifications are thread-safe (the triggering of the signal doesn't switch thread contexts, to your GuiClass::slot_data_changed should be called from all the other threads. Is my expectation realistic that it will be "easy" to use my GUI class to provide a web interface or a QT, a VTK or a whatever window? It will not be easy. To fix this, you'd have to make your notification switch threading contexts. Here's what I would do: Have your GuiClass be an abstract base class, implementing it's own message queue. When GuiClass::slot_data_changed is called by your threads, you lock a mutex and post a copy of the received notification on an internal (private:) message queue. In the thread of the GuiClass you create a function that locks the mutex and looks for notifications in the queue. This function should run in the client code's thread (in the thread of the concrete classes you specialize from the abstract GuiClass). Advantages: your base class encapsulates and isolates the thread context switching, transparently to it's specializations. Disadvantages: your client code has to either run the polling method or allow it to run (as a thread-processing function). it's a bit complicated :) Is my expectation realistic that it will be "easy" to use my GUI class to provide a web interface or a QT, a VTK or a whatever window? Doesn't see so, but it's not so easy. Besides the thread context-switching there may be other issues I'm missing at the moment. Is there a more clever alternative (like other boost libs) that I overlooked? Not other boost libs, but the way you wrote your threads is not good: the joins are made sequentially in your code. To have only one join for all threads, use a boost::thread_group. Instead of: boost::thread t1(r1, 3); boost::thread t2(r2, 1); boost::thread t3(r3, 2); boost::thread t4(r4, 2); boost::thread t5(r5, 3); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); you will have: boost::thread_group processors; processors.create_thread(r1, 3); // the other threads here processors.join_all(); Edit: A thread context is everything that is specific to a particular running thread (thread-specific storage, the stack of that thread, any exceptions thrown in that thread's context and so on). When you have various thread contexts in the same application (multiple threads) you need to synchronize access to resources created within a thread context and accessed from different threads (using locking primitives). For example, let's say you have a, an instance of class A [running in thread tA] doing some stuff and b, an instance of class B [running in the context of thread tB] and b wants to tell a something. The "wants to tell a something" part means that b wants to call a.something() and a.something() will be called in the context of tB (on the stack of thread B). To change this (to have a.something() run in the context of tA), you have to switch the thread context. This means that instead of b telling a "run A::something()", b tells a "run A::something()` in your own thread context". Classical implementation steps: b sends a message to a from within tB a polls for messages from within tA When a finds the message from b, it runs a.something() itself, within tA. This is the switching of threading contexts (the execution of A::something will be executed in tA instead of tB, as it would have been if called directly from b). From the link you provided, it seems this is already implemented by boost::asio::io_service, so if you use that, you don't have to implement it yourself.
3,021,896
3,021,931
Redundant code in exception handling
I've a recurrent problem, I don't find an elegant solution to avoid the resource cleaning code duplication: resource allocation: try { f() } catch (...) { resource cleaning code; throw; } resource cleaning code; return rc; So, I know I can do a temporary class with cleaning up destructor, but I don't really like it because it breaks the code flow and I need to give the class the reference to the all stack vars to cleanup, the same problem with a function, and I don't figure out how does not exists an elegant solution to this recurring problem.
You might want to have a look at boost::scope_exit: http://www.boost.org/doc/libs/1_39_0/libs/scope_exit/doc/html/index.html
3,021,991
3,022,025
Template Parameter Initialization
I wrote some C++ code in which I used Templates. Since I used templates, I could not initialize a couple of template class variables. I got an warning message from valgrind saying Conditional jump or move depends on uninitialized value(s). So is there a way to get around this and/or initialize template variables?? I couldn't think of a way to do it because even if I initailize them as NULL, when I use string data type a run time failure occurres. Thank You!
This is just a guess what you are asking about, so please ignore it if it's wrong. IIUC, your problem is that, with template parameters, you cannot properly default-initialize built-ins and user-defined types. The way to solve this is: T obj = T(); This works for both built-ins and UDTs.
3,022,087
3,022,130
Avoiding 'Buffer Overrun' C6386 warning
In my code, I am using an array xyz of 10 objects. When I am trying to access an element of the array using an unsigned int index like this: xyz[level], I get 'Buffer overrun' warning. Logically, I am pretty sure that level won't exceed 10. How to avoid this warning?
I'm probably teaching my grandmother to suck eggs here, but do remember that "level won't exceed 10" is wrong for an array of size 10: char a[10]; a[10] = '\0'; // Bug, and "Buffer Overrun" warning.
3,022,220
3,022,402
C++ const-reference semantics?
Consider the sample application below. It demonstrates what I would call a flawed class design. #include <iostream> using namespace std; struct B { B() : m_value(1) {} long m_value; }; struct A { const B& GetB() const { return m_B; } void Foo(const B &b) { // assert(this != &b); m_B.m_value += b.m_value; m_B.m_value += b.m_value; } protected: B m_B; }; int main(int argc, char* argv[]) { A a; cout << "Original value: " << a.GetB().m_value << endl; cout << "Expected value: 3" << endl; a.Foo(a.GetB()); cout << "Actual value: " << a.GetB().m_value << endl; return 0; } Output: Original value: 1 Expected value: 3 Actual value: 4 Obviously, the programmer is fooled by the constness of b. By mistake b points to this, which yields the undesired behavior. My question: What const-rules should you follow when designing getters/setters? My suggestion: Never return a reference to a member variable if it can be set by reference through a member function. Hence, either return by value or pass parameters by value. (Modern compilers will optimize away the extra copy anyway.)
Obviously, the programmer is fooled by the constness of b As someone once said, You keep using that word. I do not think it means what you think it means. Const means that you cannot change the value. It does not mean that the value cannot change. If the programmer is fooled by the fact that some other code else can change something that they cannot, they need a better grounding in aliasing. If the programmer is fooled by the fact that the token 'const' sounds a bit like 'constant' but means 'read only', they need a better grounding in the semantics of the programming language they are using. So if you have a getter which returns a const reference, then it is an alias for an object you don't have the permission to change. That says nothing about whether its value is immutable. Ultimately, this comes down to a lack of encapsulation, and not applying the Law of Demeter. In general, don't mutate the state of other objects. Send them a message to ask them to perform an operation, which may (depending on their own implementation details) mutate their state. If you make B.m_value private, then you can't write the Foo you have. You either make Foo into: void Foo(const B &b) { m_B.increment_by(b); m_B.increment_by(b); } void B::increment_by (const B& b) { // assert ( this != &b ) if you like m_value += b.m_value; } or, if you want to ensure that the value is constant, use a temporary void Foo(B b) { m_B.increment_by(b); m_B.increment_by(b); } Now, incrementing a value by itself may or may not be reasonable, and is easily tested for within B::increment_by. You could also test whether &m_b==&b in A::Foo, though once you have a couple of levels of objects and objects with references to other objects rather than values (so &a1.b.c == &a2.b.c does not imply that &a1.b==&a2.b or &a1==&a2), then you really have to just be aware that any operation is potentially aliased. Aliasing means that incrementing by an expression twice is not the same as incrementing by the value of the expression the first time you evaluated it; there's no real way around it, and in most systems the cost of copying the data isn't worth the risk of avoiding the alias. Passing in arguments which have the least structure also works well. If Foo() took a long rather than an object which it has to get a long from, then it would not suffer aliasing, and you wouldn't need to write a different Foo() to increment m_b by the value of a C.
3,022,356
3,022,418
Constructor Overload Problem in C++ Inheritance
Here my code snippet: class Request { public: Request(void); ……….. } Request::Request(void) { qDebug()<<"Request: "<<"Hello World"; } class LoginRequest :public Request { public: LoginRequest(void); LoginRequest(QDomDocument); …………… } LoginRequest::LoginRequest(void) { qDebug()<<"LoginRequest: "<<"Hello World"; requestType=LOGIN; requestId=-1; } LoginRequest::LoginRequest(QDomDocument doc){ qDebug()<<"LoginRequest: "<<"Hello World with QDomDocument"; LoginRequest::LoginRequest(); xmlDoc_=doc; } When call constructor of Overrided LoginRequest LoginRequest *test=new LoginRequest(doc); I came up with this result: Request: Hello World LoginRequest: Hello World with QDomDocument Request: Hello World LoginRequest: Hello World Obviously both constructor of LoginRequest called REquest constructor. Is there any way to cape with this situation? I can construct another function that does the job I want to do and have both constructors call that function. But I wonder is there any solution? Edit: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.3
The code is not doing what you probably think it is doing. The line: LoginRequest::LoginRequest(); constructs a temporary object which is immediately destroyed. as others have suggested, you can put duplicate code in a private function, but this has a lot of issues - specifically, such a function can only perform assignment, not initialisation, and many classes do not support assignment. A somewhat better solution is to implement a single constructor with a default argument: class LoginRequest { .... LoginRequest( QDomDocument d = DefaultDoc() ); };
3,022,457
3,022,825
Nested namespaces, correct static library design issues
I'm currently in the process of developing a fairly large static library which will be used by some tools when it's finished. Now since this project is somewhat larger than anything i've been involved in so far, I realized its time to think of a good structure for the project. Using namespaces is one of those logical steps. My current approach is to divide the library into parts (which are not standalone, but their purpose calls for such a separation). I have a 'core' part which now just holds some very common typedefs and constants (used by many different parts of the library). Other parts are for example some 'utils' (hash etc.), file i/o and so on. Each of these parts has its own namespace. I have nearly finished the 'utils' part and realized that my approach probably is not the best. The problem (if we want to call it so) is that in the 'utils' namespace i need something from the 'core' namespace which results in including the core header files and many using directives. So i began to think that this probably is not a good thing and should be changed somehow. My first idea is to use nested namespaces as to have something like core::utils. Since this will require some heavy refactoring i want to ask here first. What do you think? How would you handle this? Or more generally: How to correctly design a static library in terms of namespaces and code organization? If there are some guidelines or articles about it, please mentoin them too. Thanks. Note: i'm quite sure that there are more good approaches than just one. Feel free to post your ideas, suggestions etc. Since i'm designing this library i want it to be really good. The goal is to make it as clean and FAST as possible. The only problem is that i will have to integrate a LOT of existing code and refactor it, which will really be a painful process (sigh) - thats why good structure is so important)
Well, I would think that in the core.h header, you would have stuff like #include <string> #include <iostream> namespace core { typedef std::string mystring; #define mycout std::cout } And not one using directive, to prevent contaminating the global namespace. In a utils.h header, you would use stuff like: #include "core.h" namespace utils { core::mystring stringfunction(core::mystring &stuff) { core::mystring result; // do stuff return result; } } Hence, there is no mystring anywhere, except in core::. It involves a bit more typing, but that's what namespaces are for, letting yourself know where you're getting the type/function/class from. UPDATE The other side of the story is something like this: core.h header declaring stuff in core namespace like above. utils.h header declaring stuff in core::utils namespace, and after that a namespace utils = core::utils statement. This makes the two approaches identical to the user, and allows you to write stuff like mystring instead of core::mystring in the utils*.h headers and *.cpp files. Something like this for a utils.h: #include "core.h" namespace core { namespace utils { mystring stringfunction(mystring &stuff) { mystring result; // do stuff return result; } } } namespace utils = core::utils; // allow user to type utils::stringfunction This cleans up user- and library code a bit.
3,022,494
3,046,012
How to apply an mpl::transform to an mpl::string?
I'm trying to apply a transformation to an mpl::string, but can't get it to compile. I'm using MS VC++2010 and Boost 1.43.0. The code: #include <boost/mpl/string.hpp> #include <boost/mpl/vector_c.hpp> #include <boost/mpl/transform.hpp> #include <boost/mpl/plus.hpp> #include <boost/mpl/arithmetic.hpp> using namespace boost; int main() { // this compiles OK typedef mpl::vector_c<int, 'abcd', 'efgh'> numbers; typedef mpl::transform<numbers, mpl::plus<mpl::_1, mpl::int_<1> > >::type result_numbers; // this doesn't (error C2039: 'value' : is not a member of 'boost::mpl::has_push_back_arg') typedef mpl::string<'abcd', 'efgh'> chars; typedef mpl::transform<chars, mpl::plus<mpl::_1, mpl::int_<1> > >::type result_chars; } I've posted the full error message at http://paste.ubuntu.com/447759/. The MPL docs say that mpl::transform needs a Forward Sequence, and mpl::string is a Bidirectional Sequence, which I gather is a type of Forward Sequence, so I thought it'd work. Am I doing something wrong, or is this outright impossible? If so, why? Thanks!
Turns out that it works if I use transform_view.
3,022,552
3,022,579
Is there any "standard" htonl-like function for 64 bits integers in C++?
I'm working on an implementation of the memcache protocol which, at some points, uses 64 bits integer values. These values must be stored in "network byte order". I wish there was some uint64_t htonll(uint64_t value) function to do the change, but unfortunately, if it exist, I couldn't find it. So I have 1 or 2 questions: Is there any portable (Windows, Linux, AIX) standard function to do this ? If there is no such function, how would you implement it ? I have in mind a basic implementation but I don't know how to check the endianness at compile-time to make the code portable. So your help is more than welcome here ;) Thank you. Here is the final solution I wrote, thanks to Brian's solution. uint64_t htonll(uint64_t value) { // The answer is 42 static const int num = 42; // Check the endianness if (*reinterpret_cast<const char*>(&num) == num) { const uint32_t high_part = htonl(static_cast<uint32_t>(value >> 32)); const uint32_t low_part = htonl(static_cast<uint32_t>(value & 0xFFFFFFFFLL)); return (static_cast<uint64_t>(low_part) << 32) | high_part; } else { return value; } }
You are probably looking for bswap_64 I think it is supported pretty much everywhere but I wouldn't call it standard. You can easily check the endianness by creating an int with a value of 1, casting your int's address as a char* and checking the value of the first byte. For example: int num = 42; if(*(char *)&num == 42) { //Little Endian } else { //Big Endian } Knowing this you could also make a simple function that does the swapping. You could also always use boost which contains endian macros which are portable cross platform.
3,022,572
3,022,698
Python equivalent of C++ getline()
In C++ we can enter multiple lines by giving our own choice of delimiting character in the getline() function.. however I am not able to do the same in Python!! it has only raw_input() and sys.stdin.readline() methods that read till I press enter. Is there any way to customize this so that I can specify my own delimiter?
Do you still want to press enter to create multiple lines? How do you end the input? Or do you want do specify multiple lines on a single line? If the former, try looping raw_input() until something is written that tells it to stop: lines = [] while True: user_input = raw_input() if user_input.strip() == "": # empty line signals stop break lines.append(user_input) Or to specify multiple lines on a single line using a delimiter: lines = raw_input().split(";")
3,022,729
3,022,826
Linking a template class using another template class (error LNK2001)
I implemented the "Strategy" design pattern using an Abstract template class, and two subclasses. Goes like this: template <class T> class Neighbourhood { public: virtual void alter(std::vector<T>& array, int i1, int i2) = 0; }; and template <class T> class Swap : public Neighbourhood<T> { public: virtual void alter(std::vector<T>& array, int i1, int i2); }; There's another subclass, just like this one, and alter is implemented in the cpp file. Ok, fine! Now I declare another method, in another class (including neighbourhood header file, of course), like this: void lSearch(/*parameters*/, Neighbourhood<LotSolutionInformation> nhood); It compiles fine and cleanly. When starting to link, I get the following error: 1>SolverFV.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall lsc::Neighbourhood<class LotSolutionInformation>::alter(class std::vector<class LotSolutionInformation,class std::allocator<class LotSolutionInformation> > &,int,int)" (?alter@?$Neighbourhood@VLotSolutionInformation@@@lsc@@UAEXAAV?$vector@VLotSolutionInformation@@V?$allocator@VLotSolutionInformation@@@std@@@std@@HH@Z)
It seems it was a pretty rookie mistake. Since Neighbourhood is an abstract class, I must use it always as a pointer (EDIT: or a reference), since it must never be instantiated. Changed signatures and it worked fine. EDIT: Also, thanks to Neil, I know "it's got to be in the header".
3,022,910
3,370,023
Function lfit in numerical recipes, providing a test function
I am trying to fit collected data to a polynomial equation and I found the lfit function from Numerical Recipes. I only have access to the second edition, so am using that. I have read about the lfit function and its parameters, one of which is a function pointer, given in the documentation as void (*funcs)(float, float [], int)) with the help The user supplies a routine funcs(x,afunc,ma) that returns the ma basis functions evaluated at x = x in the array afunc[1..ma]. I am struggling to understand how this lfit function works. An example function I found is given below: void fpoly(float x, float p[], int np) /*Fitting routine for a polynomial of degree np-1, with coefficients in the array p[1..np].*/ { int j; p[1]=1.0; for (j=2;j<=np;j++) p[j]=p[j-1]*x; } When I run through the source code for the lfit function in gdb I can see no reference to the funcs pointer. When I try and fit a simple data set with the function, I get the following error message. Numerical Recipes run-time error... gaussj: Singular Matrix ...now exiting to system... Clearly somehow a matrix is getting defined with all zeroes. I am going to involve this function fitting in a large loop so using another language is not really an option. Hence why I am planning on using C/C++. For reference, the test program is given here: int main() { float x[5] = {0., 0., 1., 2., 3.}; float y[5] = {0., 0., 1.2, 3.9, 7.5}; float sig[5] = {1., 1., 1., 1., 1.}; int ndat = 4; int ma = 4; /* parameters in equation */ float a[5] = {1, 1, 1, 0.1, 1.5}; int ia[5] = {1, 1, 1, 1, 1}; float **covar = matrix(1, ma, 1, ma); float chisq = 0; lfit(x,y,sig,ndat,a,ia,ma,covar,&chisq,fpoly); printf("%f\n", chisq); free_matrix(covar, 1, ma, 1, ma); return 0; } Also confusing the issue, all the Numerical Recipes functions are 1 array-indexed so if anyone has corrections to my array declarations let me know also! Cheers edit: Ok just discovered the problem to this. When copying the numerical recipes code, I accidentally commented out some real code thinking it was just a comment. I no longer get the singular value error
I have since switched to the 3rd edition of NR which has a more understandable routine.
3,023,034
3,024,495
Can you call a CLR Injection into SQL Server from C++?
Does anybody know if you can you call a CLR Injection into SQL Server from C++?
You need to compile your C++ project with /CLR option and use C++/CLI to invoke your CLR Injection code. Certainly that makes your C++ project dependent on .NET Framework.
3,023,160
3,023,221
Save OpenGL output with Alpha?
Right now I'm drawing a cube with OpenGL, I'm using Windows and WGL context. I have blending enabled so my cube looks semi transparent. Basically the background == the clear color (Black). I'd like to be able to save the image in raw RGBA format which I can then make into a png. I basically want the cube to blend in with a NULL background (0,0,0,0). How could I save the OpenGL output and have the background color be (0,0,0,0) (transparent) Without using a color mask (like 255,0,255). Thanks
Just draw the cube, setting the clear color to (0, 0, 0, 0), and save the output using glReadPixels.
3,023,643
3,023,658
Static struct in C++
I want to define an structure, where some math constants would be stored. Here what I've got now: struct consts { //salt density kg/m3 static const double gamma; }; const double consts::gamma = 2350; It works fine, but there would be more than 10 floating point constants, so I doesn't want to wrote 'static const' before each of them. And define something like that: static const struct consts { //salt density kg/m3 double gamma; }; const double consts::gamma = 2350; It look fine, but I got these errors: 1. member function redeclaration not allowed 2. a nonstatic data member may not be defined outside its class I wondering if there any C++ way to do it?
Use a namespace rather than trying to make a struct into a namespace. namespace consts{ const double gamma = 2350; } The method of accessing the data also has exactly the same synatx. So for example: double delta = 3 * consts::gamma;
3,023,760
3,023,811
C++ template specialization
I have a class template <typename T> class C { static const int K=1; static ostream& print(ostream& os, const T& t) { return os << t;} }; I would like to specialize C for int. //specialization for int template <> C<int>{ static const int K=2; } I want the default print method that works for int to remain and just change the constant. For some specializations, I want to keep K=1 and change the print method because there is no << operator. How do I do this?
You could do it like this: template <typename T> class C { static const int K; static ostream& print(ostream& os, const T& t) { return os << t;} }; // general case template <typename T> const int C<T>::K = 1; // specialization template <> const int C<int>::K = 2;
3,023,770
3,023,893
Is "} while (0);" always equal to "break;} while (1);"?
I have compared gcc assembler output of do { // some code } while (0); with do { // some code break; } while (1); The output is equal, with or without optimization but.. It's always that way? No experiment can prove theories, they can only show they are wrong
There is a slight difference: do { // code if ( condition ) continue; // code break; } while(1); Will restart the loop when condition is true, whereas in the } while(0); version, the continue will be equivalent to break. If no continue is present, then they should produce exactly the same code.
3,023,775
3,024,538
Resources for setting up a Visual Studio/C++ development environment
I haven't done much "front-end" development in about 15 years since moving to database development. I'm planning to start work on a personal project using C++ and since I already have MSDN I'll probably end up doing it in Visual Studio 2010. I'm thinking about using Subversion as a version control system eventually. Of course, I'd like to get up and running as quickly as I can, but I'd also like to avoid any pitfalls from a poorly organized project environment. So, my question is, are there any good resources with common best practices for setting up a development environment? I'm thinking along the lines of where to break down a solution into multiple projects if necessary, how to set up a unit testing process, organizing resources, directories, etc. Are there any great add-ons that I should make sure I have set up from the start? Most tutorials just have one simple project, type in your code and click on build to see that your new application says, "Hello World!". This will be a Windows application with several DLLs as well (no web development), so there doesn't need to be a deploy to a web server kind of process. Mostly I just want to make sure that I don't miss anything big and then have to extensively refactor because of it. Thanks!
I would also like a good answer to this question. What I've done is set it up so that each solution makes reference to a $(SolutionDir)\build directory for includes and libraries. That way each project that has dependencies on other projects can access them and versions won't compete. Then there are post-build commands to package up headers and .lib files into a "distribution" folder. I use CC.net to build each package on checkin. When we decide to update a dependency project we "release" it to ourselves, which requires manual tagging, manual copying current.zip into a releases area and giving it a version number, and copying that into the /build of the projects that depend on the upgrade. Everything works pretty great except this manual process at the end. I'd really love to get rid of it but can't seem to. Read an article from ACM about "Continuous Release" that would be really nice to have an implementation of but there isn't any. I keep telling myself I'll make one. If I use "junctions" in the windows filesystem I can link "distribute" to "build" and then build a secondary solution that includes all the projects that are dependent on each other to build a product. When I did that though it encouraged developers to use it for active development, which discouraged TDD and proper releasing.
3,023,909
3,023,939
What is the trick in pAddress & ~(PAGE_SIZE - 1) to get the page's base address
Following function is used to get the page's base address of an address which is inside this page: void* GetPageAddress(void* pAddress) { return (void*)((ULONG_PTR)pAddress & ~(PAGE_SIZE - 1)); } But I couldn't quite get it, what is the trick it plays here? Conclusion: Personally, I think Amardeep's explanation plus Alex B's example are best answers. As Alex B's answer has already been voted up, I would like to accept Amardeep's answer as the official one to highlight it! Thanks you all.
What it does is clears the bits of the address that fit within the mask created by the page size. Effectively it gets the first valid address of a block. PAGE_SIZE must be a power of 2 and is represented by a single bit set in the address. The mask is created by subtracting one from PAGE_SIZE. That effectively sets all the bits that are a lower order than the page size bit. The ~ then complements all those bits to zero and sets all the bits that are a higher order than the mask. The & then effectively strips all the lower bits away, leaving the actual base address of the page containing the original address.
3,023,955
3,024,025
Building WM C++ project outside an IDE
I'm wondering if there is some comprehensive tutorial or someone of you can help me solve this problem. I need to build Windows mobile project written in C++ but I need to do so outside of any IDE. So I would be very grateful if someone could direct me, thank you.
Well you can call devenv directly with the /build switch and pass it the project name and it will build without opening the IDE. Or do you want to be able to build without an IDE even installed? In that case you could write an msbuild script that would do it.
3,024,110
3,024,154
Why compile + link when build a C++ code, instead of generating executable directly
I was asked of this question when mentor an entry-level programmer, I was thinking of this compile + link process so official and usual that I never think about why. One thing I could think of is to improve the development productivity, but should there be any other more compiler-related reasons?
Efficiency. When you compile a program you create an object file for each source file, if you change a source file you only need to recompile that module and then relink (relinking is cheap). If the compiler did everything in one pass it would have to recompile everything for every change. It also fits with the unix philosophy of small programs that do one thing, so you have a pre-processor, a compiler, a linker, a library creator. These steps might now be different modes of the same tool. However there are reasons why you want the compiler to link in one step, there are some optimizations you can do if you allow the compiler to change object files at link time - most modern compilers allow this but it requires them to put extra info into the object files at compile time. It would be better if the compiler could store the entire project in a single database, rather than the mess of sources, resources, browse info files, object files etc - but developers are very conservative!
3,024,136
3,027,877
Link compatibility between C++ and D
D easily interfaces with C. D just as easily interfaces with C++, but (and it's a big but) the C++ needs to be extremely trivial. The code cannot use: namespaces templates multiple inheritance mix virtual with non-virtual methods more? I completely understand the inheritance restriction. The rest however, feel like artificial limitations. Now I don't want to be able to use std::vector<T> directly, but I would really like to be able to link with std::vector<int> as an externed template. The C++ interfacing page has this particularly depressing comment. D templates have little in common with C++ templates, and it is very unlikely that any sort of reasonable method could be found to express C++ templates in a link-compatible way with D. This means that the C++ STL, and C++ Boost, likely will never be accessible from D. Admittedly I'll probably never need std::vector while coding in D, but I'd love to use QT or boost. So what's the deal. Why is it so hard to express non-trivial C++ classes in D? Would it not be worth it to add some special annotations or something to express at least namespaces? Update: "D has namespace support in the works" from Walter Bright.
FWIW Qt has an actively developed binding for D: http://www.dsource.org/projects/qtd I think many components in boost are too highly tied to C++ to be portable meaningfully to other languages. Using e.g. std::vector is possible if you spend the time on writing regular (e.g. namespace-level) functions that forward to the appropriate member functions. Tedious, but affordable (for higher-level components; probably not for std::vector). Also, I very recently checked in the standard library a sealed array and sealed binary heap implementation that use reference counting, malloc/free, and deterministic destruction instead of garbage collection (see http://www.dsource.org/projects/phobos/browser/trunk/phobos/std/container.d). Other containers will follow. These containers use three specific techniques (described in my upcoming article "Sealed Containers") to achieve deterministic destruction without compromising program safety. Hopefully sealed containers will obviate any need to link with STL containers, even for tight applications that can't afford garbage collection.
3,024,197
3,024,202
What does int argc, char *argv[] mean?
In many C++ IDE's and compilers, when it generates the main function for you, it looks like this: int main(int argc, char *argv[]) When I code C++ without an IDE, just with a command line compiler, I type: int main() without any parameters. What does this mean, and is it vital to my program?
argv and argc are how command line arguments are passed to main() in C and C++. argc will be the number of strings pointed to by argv. This will (in practice) be 1 plus the number of arguments, as virtually all implementations will prepend the name of the program to the array. The variables are named argc (argument count) and argv (argument vector) by convention, but they can be given any valid identifier: int main(int num_args, char** arg_strings) is equally valid. They can also be omitted entirely, yielding int main(), if you do not intend to process command line arguments. Try the following program: #include <iostream> int main(int argc, char** argv) { std::cout << "Have " << argc << " arguments:" << std::endl; for (int i = 0; i < argc; ++i) { std::cout << argv[i] << std::endl; } } Running it with ./test a1 b2 c3 will output Have 4 arguments: ./test a1 b2 c3
3,024,314
3,024,441
Boost Binary Serialization Problem
I have a problem using boost serialization using binary archives. It works when using a file stream but I want to store it in my local variable and ultimately save/load it to/from berkeley db. When executing the program I get a boost::archive::archive_exception: 'stream error' when instantiating the binary_iarchive. #include <sys/time.h> #include <string> #include <boost/serialization/serialization.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <fstream> #include <sstream> namespace boost { namespace serialization { template<class Archive> void serialize(Archive & ar, timeval & t, const unsigned int version) { ar & t.tv_sec; ar & t.tv_usec; } }//namespace serialization }//namespace boost int main(int, char**) { timeval t1; gettimeofday(&t1, NULL); char buf[256]; std::stringstream os(std::ios_base::binary| std::ios_base::out| std::ios_base::in); { boost::archive::binary_oarchive oa(os, boost::archive::no_header); oa << t1; } memcpy(buf, os.str().data(), os.str().length()); if(memcmp(buf, os.str().data(), os.str().length()) != 0) printf("memcpy error\n"); timeval t2; { std::stringstream is(buf, std::ios_base::binary| std::ios_base::out| std::ios_base::in); boost::archive::binary_iarchive ia(is, boost::archive::no_header); ia >> t2; } printf("Old(%d.%d) vs New(%d.%d)\n", t1.tv_sec, t1.tv_usec, t2.tv_sec, t2.tv_usec); return 0; } It works when initializing is with os.str(), so I guess my way of copying the data to my buffer or to is is wrong.
Well, for one thing .data() doesn't have a terminal \0. It's not a c-string. I didn't even realize stringstream had a char* constructor (who in their right mind uses them anymore?) but apparently it does and I'd bet it expects \0. Why are you trying to do it that way anyway? You're much better off working in C++ strings. Initialize is with os.str(). Edit: binary data contains lots of \0 characters and the std::string(char*) constructor stops at the first one. Your deserialization routine will then inevitably try to read past the end of the stream (because it isn't complete). Use the iterator constructor for std::string when you pass buf into the stringstream. std::stringstream is(std::string(buf, buf+os.str().length()), flags);
3,024,691
3,024,713
Confusion about pointers and their memory addresses
alright, im looking at a code here and the idea is difficult to understand. #include <iostream> using namespace std; class Point { public : int X,Y; Point() : X(0), Y(0) {} }; void MoveUp (Point * p) { p -> Y += 5; } int main() { Point point; MoveUp(&point); cout << point.X << point.Y; return 0; } Alright, so i believe that a class is created and X and Y are declared and they are put inside a constructor a method is created and the argument is Point * p, which means that we are going to stick the constructor's pointer inside the function; now we create an object called point then call our method and put the pointers address inside it? isnt the pointers address just a memory number like 0x255255? and why wasnt p ever declared? (int * p = Y) what is a memory addres exactly? that it can be used as an argument?
p was declared. void MoveUp (Point * p) { p -> Y += 5; } is a function that will take a pointer to a Point and add 5 to its Y value. It's no different to the following: void f(int n) { printf ("%d\n", n); } : int x = 7; f(x); You wouldn't say n wasn't defined in that case. It's the same for p in your case. Perhaps some comments in the code would help: #include <iostream> using namespace std; class Point { public : int X,Y; Point() : X(0), Y(0) {} // Constructor sets X and Y to 0. }; void MoveUp (Point * p) // Take a Point pointer p. { p -> Y += 5; // Add 5 to its Y value. } int main() { Point point; // Define a Point. MoveUp(&point); // Call MoveUp with its address. cout <<point.X << point.Y; // Print out its values (0,5). return 0; } Pointers are simply a level of indirection. In the code: 1 int X; 2 int *pX = &X; 3 X = 7; 4 *pX = 7; the effect of lines 3 and 4 are identical. That's because pX is a pointer to X so that *pX, the contents of pX, is actually X. In your case, p->Y is the same as (*p).Y, or the Y member of the class pointed to by p.
3,024,724
3,024,742
C++ Preprocessor Decisions
Sorry I know this is basic, but perhaps it doesn't exist or I'm not googling the right words. Is there and an if not (is that ifndef?) an AND and an OR so I could do something like: if not DEBUG and MACOS
I think something like #if !defined(DEBUG) && defined(MACOS) should do it.
3,025,168
3,025,335
Options for open source front end for C++
I am looking for options for an open source C++ compiler front-end (source parser/analyzer) that I could customize for my requirements. I do not need the back end implementation, just that it would help to find a fast and relatively bug free C++ front end that supports most standard features. Any suggestions? [I did google, clang seems to be an option but i'd much prefer peer feedback before i begin with it.] Arpan
Clang and GCC are the two main options. GCC is very complicated (or so I've heard), and Clang is very promising but is immature. GCC-XML uses GCC's frontend to spit out an XML description of the source. GCC-XML's output is not a full abstract source tree (it doesn't contain function bodies), but it would be a lot easier to work with than GCC itself. (The latest release on the GCC-XML page is horribly out of date; if you don't want to mess around with tracking its CVS yourself, you might try downloading a tarball from, e.g., Debian's gccxml page.) Depending on your exact requirements, other options might work: CINT is a C / C++ interpreter. I'm told that it's not very strict in its adherence to C++ standards. ROSE can take C and C++ source and lets you do a variety of transformations on it. The C and C++ front-end of ROSE is licensed from EDG, so it's not open source, but it is freely redistributable. Projects such as Doxygen and SWIG include their own limited C++ parsers. Although these are only intended for extracting documentation and generating interfaces, respectively, they may meet your needs. Edit: For further reading, see "Parsing C++", by Andrew Birkett.
3,025,293
3,025,845
parser with scopes and conditionals
I'm writing a C/C++/... build system (I understand this is madness ;)), and I'm having trouble designing my parser. My "recipes" look like this: global { SOURCE_DIRS src HEADER_DIRS include SOURCES bitwise.c \ framing.c HEADERS \ ogg/os_types.h \ ogg/ogg.h } lib static ogg_static { NAME ogg } lib shared ogg_shared { NAME ogg } (This being based on the super simple libogg source tree) # are comments, \ are "newline escapes", meaning the line continues on the next line (see QMake syntac). {} are scopes, like in C++, and global are settings that apply to every "target". This is all background, and not that relevant... I really don't know how to work with my scopes. I will need to be able to have multiple scopes, and also a form of conditional processing, in the lines of: win32:DEFINES NO_CRT_SECURE_DEPRECATE The parsing function will need to know on what level of scope it's at, and call itself whenever the scope is increased. There is also the problem with the location of the braces ( global { or global{ or as in the example). How could I go about this, using Standard C++ and STL? I understand this is a whole lot of work, and that's exactly why I need a good starting point. Thanks! What I have already is the whole ifstream and internal string/stringstream storage, so I can read word per word.
I would suggest (and this is more or less right out of the compiler textbooks) that you approach the problem in phases. This breaks things down so that the problem is much more manageable in each phase. Focus first on the lexer phase. Your lexing phase should take the raw text and give you a sequence of tokens, such as words and special characters. The lexer phase can take care of line continuations, and handle whitespace or comments as appropriate. By handling whitespace, the lexer can simplify your parser's task: you can write the lexer so that global{, global {, and even global { will all yield two tokens: one representing global and one representing {. Also note that the lexer can tack line and column numbers onto the tokens for use later if you hit errors. Once you've got a nice stream of tokens flowing, work on your parsing phase. The parser should take that sequence of tokens and build an abstract syntax tree, which models the syntactic structures of your document. At this point, you shouldn't be worrying about ifstream and operator>>, since the lexer should have done all that reading for you. You've indicated an interest in calling the parsing function recursively once you see a scope. That's certainly one way to go. As you'll see, the design decision you'll have to repeatedly make is whether you literally want to call the same parse function recursively (allowing for constructions like global { global { ... } } which you may want to disallow syntactically), or whether you want to define a slightly (or even significantly) different set of syntax rules that apply inside a scope. Once you find yourself having to vary the rules: the key is to reuse, by refactoring into functions, as much stuff as you can reuse between the different variants of syntax. If you keep heading in this direction – using separate functions that represent the different chunks of syntax you want to deal with and having them call each other (possibly recursively) where needed – you'll ultimately end up with what we call a recursive descent parser. The Wikipedia entry has got a good simple example of one; see http://en.wikipedia.org/wiki/Recursive_descent_parser . If you find yourself really wanting to delve deeper into the theory and practice of lexers and parsers, I do recommend you get a good solid compiler textbook to help you out. The Stack Overflow topic mentioned in the comments above will get you started: Learning to write a compiler
3,025,373
3,025,683
Scalability of Boost.Asio
I'm curious how far others have pushed Boost.Asio in terms of scalability. I am writing an application that may use close to 1000 socket objects, a handful of acceptor objects, and many thousand timer objects. I've configured it such that there's a thread pool invoking io_service::run and use strands in the appropriate places to ensure my handlers do not stomp on each other. My platform is Red Hat Enterprise Linux with Boost 1.39, though I'm not opposed to upgrading to a more recent version of boost.
We are using 1.39 on several Linux flavors for timers, network (both TCP and UDP), serial (20+ lines, two of which run at 500 kbps), and inotify events, and while we don't have many socket connections, we do have a few hundred async timers at any time. They are in production and they work well, for us. If I were you, I'd make up a quick prototype and performance-test it. Boost 1.43 claims a number of Linux-specific performance improvements in ASIO, but I am yet to benchmark them for our product.
3,025,450
3,025,476
how to convert char * to uchar16 in JNI C++
here's what I am trying to do: typedef uint16_t uchar16_t; uchar16_t buf[32]; // buf will contain timezone information like GMT-6, Eastern Daylight Time, etc char * str = "Test"; for (int i = 0; i <= strlen(str); i++) buf[i] = str[i]; I guess that's not correct since uchar16_t would contain 2 bytes and str contains 1 byte. What is it that I am supposed to do ?
Strlen? buf[32]? Trying to destroy the universe? You want to use a wstringstream. std::wstringstream lols; lols << "Test"; std::wstring cakes; lols >> cakes; Edit@Comment: You shouldn't use strlen because any decent string system allows embedded zeros, and strlen is seriously slow. In addition, you didn't resize your buffer as needed, so if you had a string of size > 31 you would get a buffer overflow. In addition, you would have to (if you did dynamically size your buffer) manually free it afterwards. Both of these things are serious failings of the C string system. My example code makes your standard library writer do all the work and avoid all these problems for you.
3,025,807
3,025,815
What are these c++ statements doing
void useproxynum ( ) { bUseProxy = true; return; }; void useacctnum ( ) { bUseProxy = false; return; }; Can anyone give me some insight into what these c++ statements are doing? There are in a header file. bUseProxy is defined above bool bUseProxy; I'm trying to figure out what useproxynum is (method call?) and I'm also trying to figure out how to find the code behind it. This is in Visual Studio 6.
They are inline method definitions. The return statements are extremely unnecessary. If it were me, i'd replace that with this: void useNum(bool proxy) { bUseProxy = proxy; }
3,025,851
3,026,257
C++ template function specialization using TCHAR on Visual Studio 2005
I'm writing a logging class that uses a templatized operator<< function. I'm specializing the template function on wide-character string so that I can do some wide-to-narrow translation before writing the log message. I can't get TCHAR to work properly - it doesn't use the specialization. Ideas? Here's the pertinent code: // Log.h header class Log { public: template <typename T> Log& operator<<( const T& x ); template <typename T> Log& operator<<( const T* x ); template <typename T> Log& operator<<( const T*& x ); ... } template <typename T> Log& Log::operator<<( const T& input ) { printf("ref"); } template <typename T> Log& Log::operator<<( const T* input ) { printf("ptr"); } template <> Log& Log::operator<<( const std::wstring& input ); template <> Log& Log::operator<<( const wchar_t* input ); And the source file // Log.cpp template <> Log& Log::operator<<( const std::wstring& input ) { printf("wstring ref"); } template <> Log& Log::operator<<( const wchar_t* input ) { printf("wchar_t ptr"); } template <> Log& Log::operator<<( const TCHAR*& input ) { printf("tchar ptr ref"); } Now, I use the following test program to exercise these functions // main.cpp - test program int main() { Log log; log << "test 1"; log << L"test 2"; std::string test3( "test3" ); log << test3; std::wstring test4( L"test4" ); log << test4; TCHAR* test5 = L"test5"; log << test5; } Running the above tests reveals the following: // Test results ptr wchar_t ptr ref wstring ref ref Unfortunately, that's not quite right. I'd really like the last one to be "TCHAR", so that I can convert it. According to Visual Studio's debugger, the when I step in to the function being called in test 5, the type is wchar_t*& - but it's not calling the appropriate specialization. Ideas? I'm not sure if it's pertinent or not, but this is on a Windows CE 5.0 device.
A-HA! So, I broke the problem down into it's smallest part and discovered something about the order in which template functions are matched. First, I broke the program down into this: // main.cpp int main() { Log log; wchar_t* test = L"test"; log << test; return 0; } And // Log.h class Log { public: template <typename T> Log& operator<<( const T* x ); }; template <> Log& Log::operator<<( wchar_t* const & input ); And // Log.ccp #include "Log.h" template <> Log& Log::operator<<( const wchar_t* input ) { printf("wchar_t ptr\n"); return *this; } And sure enough, my template specialization got called. When I added another specialization to the Log header like this template <typename T> Log& operator<<( const T& x ); The compiler started matching the new function instead. This time, however, I didn't include a definition for the template, so the linker complained. The linker showed the following error: error LNK2019: unresolved external symbol "public: class Log & __thiscall Log::operator<<<wchar_t *>(wchar_t * const &)" (??$?6PA_W@Log@@QAEAAV0@ABQA_W@Z) referenced in function _main This told me the type it was trying to match: wchar_t* const & A const pointer, not a pointer-to-const reference! So, now my program works. I just specialize the template like so: template <> Log& Log::operator<<( wchar_t* const & input ); Thanks for the help everyone.
3,025,920
3,026,338
DWMEnableBlurBehind makes my interface controls semi transparent
I have enabled blur on my window. I have some edit fields and some custom controls and I would not want these to be affected by the blur, they are semi transparent as a result. How could I only blur the main window itself, not its child controls (sort of like Chrome). Thanks
Black is treated as transparent since good old GDI does not support alpha channel (the alpha byte in ARGB is always 0) I'm thinking you have to do some sort of owner draw.
3,025,997
3,026,054
Defining static const integer members in class definition
My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type. Why, then, does the following code give me a linker error? #include <algorithm> #include <iostream> class test { public: static const int N = 10; }; int main() { std::cout << test::N << "\n"; std::min(9, test::N); } The error I get is: test.cpp:(.text+0x130): undefined reference to `test::N' collect2: ld returned 1 exit status Interestingly, if I comment out the call to std::min, the code compiles and links just fine (even though test::N is also referenced on the previous line). Any idea as to what's going on? My compiler is gcc 4.4 on Linux.
My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type. You are sort of correct. You are allowed to initialize static const integrals in the class declaration but that is not a definition. Interestingly, if I comment out the call to std::min, the code compiles and links just fine (even though test::N is also referenced on the previous line). Any idea as to what's going on? std::min takes its parameters by const reference. If it took them by value you'd not have this problem but since you need a reference you also need a definition. Here's chapter/verse: 9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer. See Chu's answer for a possible workaround.
3,026,188
3,061,700
How to get rid of void-pointers
I inherited a big application that was originally written in C (but in the mean time a lot of C++ was also added to it). Because of historical reasons, the application contains a lot of void-pointers. Before you start to choke, let me explain why this was done. The application contains many different data structures, but they are stored in 'generic' containers. Nowadays I would use templated STL containers for it, or I would give all data structures a common base class, so that the container can store pointers to the base class, but in the [good?] old C days, the only solution was to cast the struct-pointer to a void-pointer. Additionally, there is a lot of code that works on these void-pointers, and uses very strange C constructions to emulate polymorphism in C. I am now reworking the application, and trying to get rid of the void-pointers. Adding a common base-class to all the data structures isn't that hard (few days of work), but the problem is that the code is full of constructions like shown below. This is an example of how data is stored: void storeData (int datatype, void *data); // function prototype ... Customer *myCustomer = ...; storeData (TYPE_CUSTOMER, myCustomer); This is an example of how data is fetched again: Customer *myCustomer = (Customer *) fetchData (TYPE_CUSTOMER, key); I actually want to replace all the void-pointers with some smart-pointer (reference-counted), but I can't find a trick to automate (or at least) help me to get rid of all the casts to and from void-pointers. Any tips on how to find, replace, or interact in any possible way with these conversions?
Apparently, there is no automated way/trick to convert or find all uses of void-pointers. I'll have to use manual labor to find all void-pointers, in combination with PC-Lint that will give errors whenever there is an incorrect conversion. Case closed.
3,026,253
3,026,344
Finding Local IP via Socket Creation / getsockname
I need to get the IP address of a system within C++. I followed the logic and advice of another comment on here and created a socket and then utilized getsockname to determine the IP address which the socket is bound to. However, this doesn't appear to work (code below). I'm receiving an invalid IP address (58.etc) when I should be receiving a 128.etc Any ideas? string Routes::systemIP(){ // basic setup int sockfd; char str[INET_ADDRSTRLEN]; sockaddr* sa; socklen_t* sl; struct addrinfo hints, *servinfo, *p; int rv; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; if ((rv = getaddrinfo("4.2.2.1", "80", &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return "1"; } // loop through all the results and make a socket for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("talker: socket"); continue; } break; } if (p == NULL) { fprintf(stderr, "talker: failed to bind socket\n"); return "2"; } // get information on the local IP from the socket we created getsockname(sockfd, sa, sl); // convert the sockaddr to a sockaddr_in via casting struct sockaddr_in *sa_ipv4 = (struct sockaddr_in *)sa; // get the IP from the sockaddr_in and print it inet_ntop(AF_INET, &(sa_ipv4->sin_addr.s_addr), str, INET_ADDRSTRLEN); printf("%s\n", str); // return the IP return str; }
Your code already contains the hint: failed to bind socket. But you cut the part of the code that attempts connecting out (did you copy from Stevens UnP?). The socket is not connected to anything, so the network stack has not assigned the local address to it yet. Once you connect the socket the kernel has to select the local address for it according to the routing table. At that point getsockname(2) will work as expected.
3,026,263
3,026,333
How to generate all variations with repetitions of a string?
I want to generate all variations with repetitions of a string in C++ and I'd highly prefer a non-recursive algorithm. I've come up with a recursive algorithm in the past but due to the complexity (r^n) I'd like to see an iterative approach. I'm quite surprised that I wasn't able to find a solution to this problem anywhere on the web or on StackOverflow. I've come up with a Python script that does what I want as well: import itertools variations = itertools.product('ab', repeat=4) for variations in variations: variation_string = "" for letter in variations: variation_string += letter print variation_string Output: aaaa aaab aaba aabb abaa abab abba abbb baaa baab baba babb bbaa bbab bbba bbbb Ideally I'd like a C++ program that can produce the exact output, taking the exact same parameters. This is for learning purposes, it isn't homework. I wish my homework was like that.
You could think of it as counting, in a radix equal to the number of characters in the alphabet (taking special care of multiple equal characters in the alphabet if that's a possible input). The aaaa aaab aaba ... example for instance, is actually the binary representation of the numbers 0-15. Just do a search on radix transformations, implement a mapping from each "digit" to corresponding character, and then simply do a for loop from 0 to word_lengthalphabet_size Such algorithm should run in time linearly proportional to the number of strings that needs to be produced using constant amount of memory. Demonstration in Java public class Test { public static void main(String... args) { // Limit imposed by Integer.toString(int i, int radix) which is used // for the purpose of this demo. final String chars = "0123456789abcdefghijklmnopqrstuvwxyz"; int wordLength = 3; char[] alphabet = { 'a', 'b', 'c' }; for (int i = 0; i < Math.pow(wordLength, alphabet.length); i++) { String str = Integer.toString(i, alphabet.length); String result = ""; while (result.length() + str.length() < wordLength) result += alphabet[0]; for (char c : str.toCharArray()) result += alphabet[chars.indexOf(c)]; System.out.println(result); } } } output: aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc caa cab cac cba cbb cbc cca ccb ccc
3,026,270
3,026,399
Using windows CopyFile function to copy all files with certain name format
Hello! I am updating some C code that copys files with a certain name. basically, I have a directory with a bunch of files named like so: AAAAA.1.XYZ AAAAA.2.ZYX AAAAA.3.YZX BBBBB.1.XYZ BBBBB.2.ZYX Now, In the old code, they just used a call to ShellExecute and used xcopy.exe. to get all the files starting with AAAAA, they just gave xcopy the name of the file as AAAAA.* and it knew to copy all of the files starting with AAAAA. now, im trying to get it to copy with out having to use the command line, and I am running into trouble. I was hoping CopyFile would be smart enough to handle AAAAA.* as the file to be copied, but it doesnt at all do what xcopy did. So, any Ideas on how to do this without the external call to xcopy.exe?
You could also use SHFileOperation or IFileOperation (the latter being only available from Vista upwards but is now the recommended way according to MSDN). SHFileOperation supports wildcards and displays a progress by default, but there's also a flag for silent operation. Check out the following MSDN links for more info: http://msdn.microsoft.com/en-us/library/bb762164(v=VS.85).aspx http://msdn.microsoft.com/en-us/library/bb775771(v=VS.85).aspx
3,026,300
3,026,331
OpenGL: How to clear only a part of the screen?
Is it possible to not clear entire screen when using glClear() function? I need to clear only a part of the screen to save some rendering time, otherwise i would have to redraw half of the screen every frame, even if nothing is happening on the other half. Of course this should be done as quickly (or quickier) as the glClear() is now.
You might want to look into glScissor. From the documentation: While scissor test is enabled, only pixels that lie within the scissor box can be modified by drawing commands.
3,026,542
3,026,549
C++: Syntax error C2061: Unexpected identifier
What's wrong with this line of code? bar foo(vector ftw); It produces error C2061: syntax error: identifier 'vector'
try std::vector instead. Also, make sure you #include <vector>
3,026,557
3,026,567
Function to get X, Y position of an object orbiting a point, given a distance and angle in radians?
I am trying to code a function for a camera that orbits a point. Assume a 3d coordinate plane where Z is up. Ignore Z. Let's say the camera's position starts at (0, 0, z). The object to orbit is at, say (50, 50, z). So we have a distance of ~70 units. Calling the function with {(50, 50, z), 70, x} where x is the position in orbit, in radians, should return where the position of the camera should be. I believe this involves cos and tan but my trig isn't that great... point3d getCameraPosition(point3d objectPosition, float distance, float rotationRadians) { // ??? }
return position + Point(distance*cos(angle), distance*sin(angle))
3,026,649
3,026,719
Getting information about where c++ exceptions are thrown inside of catch block?
I've got a c++ app that wraps large parts of code in try blocks. When I catch exceptions I can return the user to a stable state, which is nice. But I'm not longer receiving crash dumps. I'd really like to figure out where in the code the exception is taking place, so I can log it and fix it. Being able to get a dump without halting the application would be ideal, but I'm not sure that's possible. Is there some way I can figure out where the exception was thrown from within the catch block? If it's useful, I'm using native msvc++ on windows xp and higher. My plan is to simply log the crashes to a file on the various users' machines, and then upload the crashlogs once they get to a certain size.
This is possible with using SEH (structured exception handling). The point is that MSVC implements C++ exceptions via SEH. On the other hand the pure SEH is much more powerful and flexible. That's what you should do. Instead of using pure C++ try/catch blocks like this: try { DoSomething(); } catch(MyExc& exc) { // process the exception } You should wrap the inner code block DoSomething with the SEH block: void DoSomething() { __try { DoSomethingInner(); } __except (DumpExc(GetExceptionInformation()), EXCEPTION_CONTINUE_SEARCH) { // never get there } } void DumpEx(EXCEPTION_POINTERS* pExc) { // Call MiniDumpWriteDump to produce the needed dump file } That is, inside the C++ try/catch block we place another raw SEH block, which only dumps all the exceptions without catching them. See here for an example of using MiniDumpWriteDump.
3,026,666
3,029,006
Display List with GLTesselated objects? (OpenGL)
Is it possible to create a display list for Tesselated objects? If so would it be more efficient? Thanks
Yes -- after tessellation you just have a bunch of triangles, which you can put in a display list about like anything else. Efficiency will depend; on nVidia display lists work quite well, but on ATI a display list is little different from multiple calls to glVertex. If you want to assure efficiency across both, consider using a vertex buffer object instead of a display list. This is also supported by the newer versions of OpenGL (display lists are deprecated).
3,026,682
3,026,781
How to pass a function to a function?
Suppose I have a class with 2 static functions: class CommandHandler { public: static void command_one(Item); static void command_two(Item); }; I have a DRY problem where I have 2 functions that have the exact same code for every single line, except for the function that it calls: void CommandOne_User() { // some code A CommandHandler::command_one(item); // some code B } void CommandTwo_User() { // some code A CommandHandler::command_two(item); // some code B } I would like to remove duplication, and, ideally, do something like this: void CommandOne_User() { Function func = CommandHandler::command_one(); Refactored_CommandUser(func); } void CommandTwo_User() { Function func = CommandHandler::command_one(); Refactored_CommandUser(func); } void Refactored_CommandUser(Function func) { // some code A func(item); } I have access to Qt, but not Boost. Could someone help suggest a way on how I can refactor something like this?
Besides the C way (passing a function pointer) or the C++ way mentioned by Jay here there is the other (modern) c++ way with boost or with a compiler with c++0x support: void Refactored_CommandUser( boost::function<void (Item)> f ) { // alternatively std::function with proper compiler support } With the advantage that this encapsulates a functor, and can be combined with boost::bind (or std::bind) to pass in not only free-function pointers that match the signature exactly, but also other things, like member pointers with an object: struct test { void f( Item ); }; void foo( Item i, std::string const & caller ); void bar( Item i ); int main() { test t; Refactored_CommandUser( boost::bind( &test::f, &t, _1 ) ); Refactored_CommandUser( boost::bind( foo, _1, "main" ) ); Refactored_CommandUser( bar ); // of course you can pass a function that matches directly }
3,026,767
3,026,768
What's the difference between void* and void**?
It's the special property that void* can also be assigned a pointer to a pointer and cast back and the original value is received. I read this line somewhere. Does it means void* and void** are same? What is the difference? Edit void* can hold any pointer. Then what's void** needed for?
One points at a black hole. The other points at the thing pointing at the black hole. They're not really the same thing, but pointers can be converted to void *. You can convert int * to a void * because, well, it's a pointer. void ** is still a pointer (it just points to a pointer), and since it's a pointer, you can convert it to a void *. That make any sense? That said, I don't think I've ever had a use for a void **, but if you needed an array of void *s, then the type would be void **. (In C) void * is often used to hold a pointer to some user data - but you won't know ahead of time what type that data will be. If you had an array of those, then void **. Since you also have this tagged as C++: The previous case doesn't really apply: you could use a std::vector<void *>. Really, void * might be questionable - an abstract base might fit your purposes better. void * is useful mostly in C.
3,026,826
3,027,742
passing unicode string from C# exe to C++ DLL
Using this function in my C# exe, I try to pass a Unicode string to my C++ DLL: [DllImport("Test.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] public static extern int xSetTestString(StringBuilder xmlSettings); This is the function on the C++ DLL side: __declspec(dllexport) int xSetTestString(char* pSettingsXML); Before calling the function in C#, I do a MessageBox.Show(string) and it displays all characters properly. On the C++ side, I do: OutputDebugStringW((wchar_t*)pString);, but that shows that the non-ASCII characters were replaced by '?'.
Just change your export in native DLL to: extern "C" __declspec(dllexport) int xSetTestString(wchar_t* pSettingsXML); This will do the trick. BTW - You cant simply do char* str1 = (wchar_t*)pSettingsXML; because it does not convert the string. You need to use wcstombs_s to convert from wchar_t* to char*. But in your case you don't have to do it. Notes: Best practice IMO is to use TCHAR* instead of wchar_t* directly, and set your native dll project General option Character Set to Use Unicode Character Set. This defines TCHAR* as wchar_t*. Mirosoft natively uses two sets of functions: ANSI, using 1-byte chracter, marked as FunctionNameA and Unicode, using 2-bytes character, marked as FunctionNameW. This Unicode is in fact UTF-16. UTF-8 is a multi-byte string that uses 1-byte for standard character and 2-bytes for non-standard characters. To convert UTF-8 to UTF-16 you can use MultiByteToWideChar function.
3,026,858
3,026,874
Segfault (possibly due to casting)
I don't normally go to stackoverflow for sigsegv errors, but I have done all I can with my debugger at the moment. The segmentation fault error is thrown following the completion of the function. Any ideas what I'm overlooking? I suspect that it is due to the casting of the sockaddr to the sockaddr_in, but I am unable to find any mistakes there. (Removing that line gets rid of the seg fault -- but I know that may not be the root cause here). // basic setup int sockfd; char str[INET_ADDRSTRLEN]; sockaddr* sa; socklen_t* sl; struct addrinfo hints, *servinfo, *p; int rv; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; // return string string foundIP; // setup the struct for a connection with selected IP if ((rv = getaddrinfo("4.2.2.1", NULL, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return "1"; } // loop through all the results and make a socket for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("talker: socket"); continue; } break; } if (p == NULL) { fprintf(stderr, "talker: failed to bind socket\n"); return "2"; } // connect the UDP socket to something connect(sockfd, p->ai_addr, p->ai_addrlen); // we need to connect to get the systems local IP // get information on the local IP from the socket we created getsockname(sockfd, sa, sl); // convert the sockaddr to a sockaddr_in via casting struct sockaddr_in *sa_ipv4 = (struct sockaddr_in *)sa; // get the IP from the sockaddr_in and print it inet_ntop(AF_INET, &(sa_ipv4->sin_addr), str, INET_ADDRSTRLEN); printf("%s\n", str); // return the IP return foundIP; }
It doesn't look like you ever initialize the pointer sa to point at a valid sockaddr (or sockaddr_in) object. If you replace sockaddr* sa; with sockaddr addr; and replace all uses of sa with &addr you should be in better shape. The same is also true of sl. At least according to the documentation for my getsockname the socklen_t* parameter needs to point at a valid socklen_t object initialized to the size in bytes of the address buffer. E.g. socklen_t slen = sizeof addr; and use &slen instead of sl.
3,026,986
3,027,030
C++ namespace alias and forward declaration
I am using a C++ third party library that places all of its classes in a versioned namespace, let's call it tplib_v44. They also define a generic namespace alias: namespace tplib = tplib_v44; If a forward-declare a member of the library in my own .h file using the generic namespace... namespace tplib { class SomeClassInTpLib; } ... I get compiler errors on the header in the third-party library (which is being included later in my .cpp implementation file): error C2386: 'tplib' : a symbol with this name already exists in the current scope If I use the version-specific namespace, then everything works fine, but then ... what's the point? What's the best way to deal with this? [EDIT] FYI for future viewers, this was the ICU library. A solution (at least in my situation) is in the comments to the accepted answer.
It looks like there is an ugly workaround for this, but no good solution. For ACE (with a decent explanation) and Xerces (with a snarky "this is how c++ works" comment), they define macros that you can use to do this "generically". ACE_BEGIN_VERSIONED_NAMESPACE_DECL class ACE_Reactor; ACE_END_VERSIONED_NAMESPACE_DECL XERCES_CPP_NAMESPACE_BEGIN class DOMDocument; class DOMElement; XERCES_CPP_NAMESPACE_END It looks like an unfortunate c++ artifact, try searching around in your tplib for these macros. The standard treats namespaces and namespace aliases as different things. You're declaring tplib as a namespace, so when the compiler tries to assign an alias later, it cannot be both, so the compiler complains.
3,027,002
3,027,020
Clipping users cursor around the X button
This should be simple, and I was hoping to do it in Delphi. The purpose of this is just supposed to be a joke. On a windows form application I don't want the user to be able to click the X button on the main form. I want the cursor to either clip around the X button or just set it's position elsewhere.
Write type TForm1 = class(TForm) private { Private declarations } procedure NcMouseMove(var Message: TWMNCMouseMove); message WM_NCMOUSEMOVE; public { Public declarations } end; procedure TForm1.NcMouseMove(var Message: TWMNCMouseMove); begin inherited; with Message do if HitTest = HTCLOSE then SetCursorPos(XCursor + GetSystemMetrics(SM_CXMENUSIZE), YCursor) end;
3,027,067
3,027,533
Optional Member Objects
Okay, so you have a load of methods sprinkled around your system's main class. So you do the right thing and refactor by creating a new class and perform move method(s) into a new class. The new class has a single responsibility and all is right with the world again: class Feature { public: Feature(){}; void doSomething(); void doSomething1(); void doSomething2(); }; So now your original class has a member variable of type object: Feature _feature; Which you will call in the main class. Now if you do this many times, you will have many member-objects in your main class. Now these features may or not be required based on configuration so in a way it's costly having all these objects that may or not be needed. Can anyone suggest a way of improving this? EDIT: Based on suggestion to use The Null Object Design Pattern I've come up with this: An Abstract Class Defining the Interface of the Feature: class IFeature { public: virtual void doSomething()=0; virtual void doSomething1()=0; virtual void doSomething2()=0; virtual ~IFeature(){} }; I then define two classes which implement the interface, one real implementation and one Null Object: class RealFeature:public IFeature { public: RealFeature(){}; void doSomething(){std::cout<<"RealFeature doSomething()"<<std::endl;} void doSomething1(){std::cout<<"RealFeature doSomething()"<<std::endl;} void doSomething2(){std::cout<<"RealFeature doSomething()"<<std::endl;} }; class NullFeature:public IFeature { public: NullFeature(){}; void doSomething(){std::cout<<"NULL doSomething()"<<std::endl;}; void doSomething1(){std::cout<<"NULL doSomething1()"<<std::endl;}; void doSomething2(){std::cout<<"NULL doSomething2()"<<std::endl;}; }; I then define a Proxy class which will delegate to either the real object or the null object depending on configuration: class Feature:public IFeature { public: Feature(); ~Feature(); void doSomething(); void doSomething1(); void doSomething2(); private: std::auto_ptr<IFeature> _feature; }; Implementation: Feature::Feature() { std::cout<<"Feature() CTOR"<<std::endl; if(configuration::isEnabled() ) { _feature = auto_ptr<IFeature>( new RealFeature() ); } else { _feature = auto_ptr<IFeature>( new NullFeature() ); } } void Feature::doSomething() { _feature->doSomething(); } //And so one for each of the implementation methods I then use the proxy class in my main class (or wherever it's required): Feature _feature; _feature.doSomething();
If a feature is missing and the correct thing to do is ignore that fact and do nothing, you can get rid of your checks by using the Null Object pattern: class MainThing { IFeature _feature; void DoStuff() { _feature.Method1(); _feature.Method2(); } interface IFeature { void Method1(); void Method2(); } class SomeFeature { /* ... */ } class NullFeature { void Method1() { /* do nothing */ } void Method2() { /* do nothing */ } } Now, in MainThing, if the optional feature isn't there, you give it a reference to a NullFeature instead of an actual null reference. That way, MainThing can always safely assume that _feature isn't null.
3,027,368
3,027,431
Sound Manager Classes for Windows
I need some classes for playing short wav sounds, this classes would load this wav files into memory when an instance created, play sounds in background when needed, release this wav files from memory when an instance disposed. How can I do this on C# for windows (.Net 2.0)? (Win API's sndPlaySound, OpenAL or may be any wrapper) Ideally I would love to find an exist solution that simple and able to solve my task. Do you know any solutions for this issue?
Check out the System.Media.SoundPlayer class. http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx System.Media.SystemSounds too. http://msdn.microsoft.com/en-us/library/system.media.systemsounds.aspx
3,027,695
3,027,825
What is the best C++ Mail library used to read EML file / Outlook MSG file?
We have to develop an in-house mail app. Please let me know what the best CPP library used to read EML file and Outlook MSG file?
EML is basically the same as MHT; it's a plain text format which you can parse yourself, and I believe the WebBrowser control can also display the contents of an EML/MHT. MSG is a binary MAPI format. You can use the MAPI libraries to deal with these (Windows only). For more information on how to deal with that, see this page.
3,027,729
3,027,893
I want to trace logs using a Macro multi parameter always null. problem c++ windows
I am using the following way to cout a function's time: #define TIME_COST(message, ...)\ char szMessageBuffer[2048] = {0};\ va_list ArgList;\ va_start(ArgList, message);\ vsprintf_s(szMessageBuffer, 2048, message, ArgList);\ va_end(ArgList); \ string strMessage(szMessageBuffer);\ CQLogTimer t(strMessage); // CQLogTimer is a self destructor,which will cout life time of its own and print szMessageBuffer. However when I use the macro this : void fun { TIME_COST("hello->%s", filePath); XXXXXX } The message generated always is hello->(null) Can Any one help? Many thanks!
The correct version is: #define TIME_COST(message, ...)\ char szMessageBuffer[2048] = {0};\ sprintf_s(szMessageBuffer, 2048, message, __VA_ARGS__);\ string strMessage(szMessageBuffer);\ CQLogTimer t(strMessage); __VA_ARGS__ is not va_list type, but comma-separated arguments, so you need to use sprintf_s, not vsprintf_s.
3,027,857
3,027,879
c++ push_back doesn't work as it is supposed
I have a class symbol_table that has a vector of objects of another class row_st.also I have an enter method where inserts objects of row_st with a passed name into the vector of desired symbol_table.but when I call the enter to enter objects with name : a;b;c;Iwill get the following result: a,b,c;b,c;c.the first element of vector gets the name of all the entered objects. and the second element also gets the name of the later entries. class row_st { public: char* name; type_u type;//int:0,flaot:1;char:2,bool:3,array: int offset; symbol_table *next; symbol_table *current; }; class symbol_table { public: vector <row_st *> row; int type; int header; int starting_stmt; int index; int i; symbol_table *previous; symbol_table(){ header=0; previous=0; index=0;i=0;starting_stmt=0;} }; and here it is the enter method: int enter(symbol_table *table,char* name,type_u type){ row_st *t=new row_st; t->name=name; t->type=type; t->offset=table->index; t->current=table; table->index++; t->next=0; table->row.push_back(t); table->header +=1; return table->row.size()-1; } the push_backed elements all points to the same address.the new call makes the same row_st every time it is called.what should I do?
As Neil Butterworth's answer suggest, the trouble is probably not with this code, but the place where you call it. Using character pointers does not make it impossible to make things work, just harder. The problem in this case is definitely not with push_back. If you posted the method where you call this code it might be possible to see exactly what goes wrong.
3,028,043
3,028,111
How to export some data into .rtf or .doc?
Say I have created a GUI (Qt) that operates with some data(text+image). How I can export that data in one of listed formates in title. I guess it is better to export info .rtf as it is free cross-platform formt(??), isn't it?
See question about RTF reading and writing.
3,028,282
3,030,127
An efficient way to compute mathematical constant e
The standard representation of constant e as the sum of the infinite series is very inefficient for computation, because of many division operations. So are there any alternative ways to compute the constant efficiently?
Since it's not possible to calculate every digit of 'e', you're going to have to pick a stopping point. double precision: 16 decimal digits For practical applications, "the 64-bit double precision floating point value that is as close as possible to the true value of 'e' -- approximately 16 decimal digits" is more than adequate. As KennyTM said, that value has already been pre-calculated for you in the math library. If you want to calculate it yourself, as Hans Passant pointed out, factorial already grows very fast. The first 22 terms in the series is already overkill for calculating to that precision -- adding further terms from the series won't change the result if it's stored in a 64 bit double-precision floating point variable. I think it will take you longer to blink than for your computer to do 22 divides. So I don't see any reason to optimize this further. thousands, millions, or billions of decimal digits As Matthieu M. pointed out, this value has already been calculated, and you can download it from Yee's web site. If you want to calculate it yourself, that many digits won't fit in a standard double-precision floating-point number. You need a "bignum" library. As always, you can either use one of the many free bignum libraries already available, or re-invent the wheel by building your own yet another bignum library with its own special quirks. The result -- a long file of digits -- is not terribly useful, but programs to calculate it are sometimes used as benchmarks to test the performance and accuracy of "bignum" library software, and as stress tests to check the stability and cooling capacity of new machine hardware. One page very briefly describes the algorithms Yee uses to calculate mathematical constants. The Wikipedia "binary splitting" article goes into much more detail. I think the part you are looking for is the number representation: instead of internally storing all numbers as a long series of digits before and after the decimal point (or a binary point), Yee stores each term and each partial sum as a rational number -- as two integers, each of which is a long series of digits. For example, say one of the worker CPUs was assigned the partial sum, ... 1/4! + 1/5! + 1/6! + ... . Instead of doing the division first for each term, and then adding, and then returning a single million-digit fixed-point result to the manager CPU: // extended to a million digits 1/24 + 1/120 + 1/720 => 0.0416666 + 0.0083333 + 0.00138888 that CPU can add all the terms in the series together first with rational arithmetic, and return the rational result to the manager CPU: two integers of perhaps a few hundred digits each: // faster 1/24 + 1/120 + 1/720 => 1/24 + 840/86400 => 106560/2073600 After thousands of terms have been added together in this way, the manager CPU does the one and only division at the very end to get the decimal digits after the decimal point. Remember to avoid PrematureOptimization, and always ProfileBeforeOptimizing.
3,028,583
4,197,016
OAuth authentication for Google API with Qt
I'm trying to get authenticated for receiving and publishing Google Buzz-es from a Qt 4.6(c++) application. I'm looking for a cross-platform solution. Could anyone provide some working solution for this purpose?
You can also try kQOAuth which is a new Qt library for doing OAuth authentication. It will let you do the user authentication very easily too, if you like. Supports OAuth 1.0 and HMAC-SHA1. No external dependencies. http://www.johanpaul.com/blog/2010/10/introducing-kqoauth-easy-and-powerful-oauth-library-for-qt/
3,028,632
8,621,112
Move from *this in an rvalue method?
In C++11, methods can be overloaded on whether or not the expression that denotes the object on which the method is called is an lvalue or an rvalue. If I return *this from a method called via an rvalue, do I need to explicitly move from *this or not? Foo Foo::method() && { return std::move(*this); // Is this move required or not? } Unfortunately, I can't simply test this on my compiler since g++ does not support this feature yet :(
The type of *this is always an lvalue: §9.3.2 [class.this] p1 In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. [...] §5.3.1 [expr.unary.op] p1 The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. So you will need to std::move if you want to invoke the move constructor. The following code snippet shows that: #include <iostream> #include <utility> struct test{ test(){} test(test const&){ std::cout << "copy ctor // #1\n"; } test(test&&){ std::cout << "move ctor // #2\n"; } test f_no_move() &&{ return *this; } test f_move() &&{ return std::move(*this); } }; int main(){ test().f_no_move(); // #1 test().f_move(); // #2 } Using Clang 3.1 (the only compiler I know that implements ref-qualifiers), I get the following output: $ clang++ -std=c++0x -stdlib=libc++ -pedantic -Wall t.cpp $ ./a.out copy ctor // #1 move ctor // #2
3,028,691
3,028,859
Compilation error while compiling an existing code base
While building an existing code base on Mac OS using its native build setup I am getting some basic strange error while compilation phase. Does any of you have any idea, as I have seen it's been discussed earlier as well in this forum without any good reason. I can not see any conflicting files being included. But still I am unable to compile the code because this error appears. Source are like the code given below and compilation error appears $ cat a.h #include <string> #include <sstream> namespace brijesh { typedef std::string String; template<class T> String toString(T value) { std::ostringstream buffer; buffer << value; return buffer.str(); } $ cat b.h #include "a.h" namespace brijesh { class Platform { public: static String getName(); }; } $ cat b.cpp #include "b.h" namespace brijesh { String Platform::getName() { String name = "UNKNOWN"; #ifdef LINUX name = "linux"; #endif #ifdef MACOSX name = "Mac"; #endif return name; } } flags used for compilation g++ -c -o test.o -DRELEASE_VERSION -ggdb -arch ppc -mmacosx-version-min=10.4 -pipe -fpermiss ive -nostdinc -nostdinc++ -isystem /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3 .3 -I/Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++ -I/Developer/SDKs/MacOS X10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/ppc-darwin -isystem /Developer/SDKs/MacOSX10.3.9. sdk/usr/include -F/Developer/SDKs/MacOSX10.3.9.sdk/System/Library/Frameworks -Wreturn-type -D_REENTRANT -D_GNU_SOURCE -D_LARGEFILE64_SOURCE -Wall -Wno-multichar -Wno-unk nown-pragmas -Wno-long-double -fconstant-cfstrings -MP -MMD x.cpp /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/bits/locale_facets.h: In constructor 'std::collate_byname<_CharT>::collate_byname(const char*, size_t)': /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/bits/locale_facets.h:1072: error: '_M_c_locale_collate' was not declared in this scope /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/ppc-darwin/bits/messages_members.h: In constructor 'std::messages_byname<_CharT>::messages_byname(const char*, size_t)': /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/ppc-darwin/bits/messages_members.h:79: error: '_M_c_locale_messages' was not declared in this scope /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/limits: At global scope: /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/limits:897: error: 'float __builtin_huge_valf()' cannot appear in a constant-expression /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/limits:897: error: a function call cannot appear in a constant-expression /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/limits:897: error: 'float __builtin_huge_valf()' cannot appear in a constant-expression /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/limits:897: error: a function call cannot appear in a constant-expression /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/limits:899: error: 'float __builtin_nanf(const char*)' cannot appear in a constant-expression /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/limits:899: error: a function call cannot appear in a constant-expression /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/limits:899: error: 'float __builtin_nanf(const char*)' cannot appear in a constant-expression /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/limits:899: error: a function call cannot appear in a constant-expression /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/limits:900: error: field initializer is not constant /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/gcc/darwin/3.3/c++/limits:915: error: field initializer is not constant
It looks like you're trying to use OS X 10.3 developer tools (Xcode et al) and are trying to target OS X 10.4, which is obviously not going to work. Either change your build command to remove incompatible flags, such as -mmacosx-version-min=10.4, or upgrade to a more current version of OS X + Xcode + SDKs.
3,028,856
3,059,679
How Can I Turn On/Off Caps Lock, Scroll Lock, and Num Lock Programmatically
Is there a method to turn on/off Caps Lock, Scroll Lock and Num Lock on Windows? Please post the code snippet in any language... but my preference is C/C++ or Java. P.S. I'm making a Morse Code program which blinks the Scroll Lock LED.
The Java code is... Get the Toolkit object... Toolkit toolkit = Toolkit.getDefaultToolkit(); To turn on Caps Lock, Scroll Lock, Num Lock... toolkit.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, true); toolkit.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK, true); toolkit.setLockingKeyState(KeyEvent.VK_NUM_LOCK, true); To turn off Caps Lock, Scroll Lock, Num Lock... toolkit.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, false); toolkit.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK, false); toolkit.setLockingKeyState(KeyEvent.VK_NUM_LOCK, false);
3,028,998
3,029,950
Non-blocking TCP buffer issues
I think I'm in a problem. I have two TCP apps connected to each other which use winsock I/O completion ports to send/receive data (non-blocking sockets). Everything works just fine until there's a data transfer burst. The sender starts sending incorrect/malformed data. I allocate the buffers I'm sending on the stack, and if I understand correctly, that's a wrong to do, because these buffers should remain as I sent them until I get the "write complete" notification from IOCP. Take this for example: void some_function() { char cBuff[1024]; // filling cBuff with some data WSASend(...); // sending cBuff, non-blocking mode // filling cBuff with other data WSASend(...); // again, sending cBuff // ..... and so forth! } If I understand correctly, each of these WSASend() calls should have its own unique buffer, and that buffer can be reused only when the send completes. Correct? Now, what strategies can I implement in order to maintain a big sack of such buffers, how should I handle them, how can I avoid performance penalty, etc'? And, if I am to use buffers that means I should copy the data to be sent from the source buffer to the temporary one, thus, I'd set SO_SNDBUF on each socket to zero, so the system will not re-copy what I already copied. Are you with me? Please let me know if I wasn't clear.
Take a serious look at boost::asio. Asynchronous IO is its specialty (just as the name suggests.) It's pretty mature library by now being in Boost since 1.35. Many people use it in production for very intensive networking. There's a wealth of examples in the documentation. One thing for sure - it take working with buffers very seriously. Edit: Basic idea to handling bursts of input is queuing. Create, say, three linked lists of pre-allocated buffers - one is for free buffers, one for to-be-processed (received) data, one for to-be-sent data. Every time you need to send something - take a buffer off the free list (allocate a new one if free list is empty), fill with data, put it onto to-be-sent list. Every time you need to receive something - take a buffer off the free list as above, give it to IO receive routine. Periodically take buffers off to-be-sent queue, hand them off to send routine. On send completion (inline or asynchronous) - put them back onto free list. On receive completion - put buffer onto to-be-processed list. Have your "business" routine take buffers off to-be-processed list. The bursts will then fill that input queue until you are able to process them. You might want to limit the queue size to avoid blowing through all the memory.
3,029,031
3,029,061
Connecting C++ to C#
I've been writing a program in C++ and noticed there is a library in C# that someone else wrote that I would like to link in to my code.... but I'm not sure how to do that. Can someone suggest something? Doubt this matters, but I'm using Windows 7 with MSVC2010. Thanks in advance!
If you're familiar with COM you could access the .NET library through COM. If the library doesn't provide COM interop out of the box you could write a wrapper around it using C# and expose that through COM. If you're going to pull in a .NET library you should be aware that it requires a .NET runtime which may take up valuable resources. If you ware building the application in C++ for performance reasons, maybe you're better off porting the parts of the library you need to C++.
3,029,164
3,054,982
How to encode series of images into VP8 using WebM VP8 Encoder API? (C/C++)
How to transcode RGB images into VP8 frames (Keyframe + some dependent frames)? So I created some images how to turn tham into VP8 now?
First, you need a codec library for VP8: http://www.webmproject.org/code/build-prerequisites/ Using libvpx API you can then encode your RGB frames into VP8 frames.
3,029,412
3,029,415
Unsigned negative primitives?
In C++ we can make primitives unsigned. But they are always positive. Is there also a way to make unsigned negative variables? I know the word unsigned means "without sign", so also not a minus (-) sign. But I think C++ must provide it.
No. unsigned can only contain nonnegative numbers. If you need a type that only represent negative numbers, you need to write a class yourself, or just interpret the value as negative in your program. (But why do you need such a type?)
3,029,523
3,029,526
dynamic vector-like container but whose elements save their indexes?
All the elements should have fixed position in the array after insertion until I explicitly delete them from there. Is there something like this in boost or wherever? Thanks
Use an unordered_map<int, T> or map<int, T>. Or, use a vector<optional<T>>, and set the slot to delete to none_t, instead of actually deleting it.
3,029,545
3,029,583
C++ game loop example
Can someone write up a source for a program that just has a "game loop", which just keeps looping until you press Esc, and the program shows a basic image. Heres the source I have right now but I have to use SDL_Delay(2000); to keep the program alive for 2 seconds, during which the program is frozen. #include "SDL.h" int main(int argc, char* args[]) { SDL_Surface* hello = NULL; SDL_Surface* screen = NULL; SDL_Init(SDL_INIT_EVERYTHING); screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE); hello = SDL_LoadBMP("hello.bmp"); SDL_BlitSurface(hello, NULL, screen, NULL); SDL_Flip(screen); SDL_Delay(2000); SDL_FreeSurface(hello); SDL_Quit(); return 0; } I just want the program to be open until I press Esc. I know how the loop works, I just don't know if I implement inside the main() function, or outside of it. I've tried both, and both times it failed. If you could help me out that would be great :P
Tried with something like SDL_Event e; while( SDL_WaitEvent(&e) ) { if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE) break; } ? You can find many tutorials and example out there; just a fast-search example. Added note: WaitEvent "freezes" the program so you can't do anything .. you just wait; other waiting technics can be desired (as PollEvent, or WaitEvent again after the initializtion of a timer).
3,029,633
3,029,695
How to use dirent.h correctly
I am new to C++ and I am experimenting with the dirent.h header to manipulate directory entries. The following little app compiles but pukes after you supple a directory name. Can someone give me a hint? The int quit is there to provide a while loop. I removed the loop in an attempt to isolate my problem. thanks! #include <iostream> #include <dirent.h> using namespace std; int main() { char *dirname = 0; DIR *pd = 0; struct dirent *pdirent = 0; int quit = 1; cout<< "Enter a directory path to open (leave blank to quit):\n"; cin >> dirname; if(dirname == NULL) { quit = 0; } pd = opendir(dirname); if(pd == NULL) { cout << "ERROR: Please provide a valid directory path.\n"; } return 0; }
If you are using C++, don't use char * or arrays, use std::string: #include <string> .... string dirname; cout<< "Enter a directory path to open (leave blank to quit):\n"; getline( cin, dirname ); if ( dirname == "" ) { exit(1); } .... pd = opendir(dirname.c_str() );
3,029,860
3,030,528
Catch unhandled exception of invisible thread
In my C++ application i use an activeX component that runs its own thread (or several I don't know). Sometimes this components throws exceptions. I would like to catch these exceptions and do recovery instead of my entire application crashing. But since I don't have access to its source code or thread I am unsure how it would be done. The only solution I can think of is to run it in its own process. Using something like CreateProcess and then CreateRemoteThread, unsure how it could be implemented. Any suggestion on how to go about solving this?
Try setting up an exception filter with SetUnhandledExceptionFilter().
3,029,923
3,029,930
Can this example be done with pointers instead of global variable?
This is a simplified example of the problem I have: #include <stdio.h> #include <stdlib.h> void f2(int** a) { printf("a: %i\n", **a); } void f1(int* a) { f2(&a); } int main() { int a = 3; f1(&a); // prints "a: 3" f2(???); return 0; } The problem is that I would like to be able to use f2() both in main() and in f1(). Can that be done without using global variables?
You need to pass a pointer to a pointer, so you need to create a pointer in main() so that you can take its address: int main() { int a = 3; int* aptr = &a; f2(&aptr); return 0; }
3,029,962
3,029,966
boost::function function pointer to parameters?
How does boost::function take a function pointer and get parameters from it? I want wrap a function pointer so that it can be validated before being called. And it would be nice to be able to call it like boost::function is with the () operator and not having to access the function pointer member. Wrapper func; func(5); //Yes :D func.Ptr(5) //Easy to do, but not as nice looking
You need to overload operator(). To determine the return type, arity, and parameter types of a function, you can use something like Boost.TypeTraits: #include <boost/type_traits.hpp> template <typename Function> struct Wrapper { typedef typename boost::function_traits<Function>::arg1_type Arg1T; typedef typename boost::function_traits<Function>::result_type ReturnT; Wrapper(Function func) : func_(func) { } ReturnT operator()(Arg1T arg) { return func_(arg); } Function* func_; }; bool Test(int x) { return x < 42; } int main() { Wrapper<bool(int)> CallsTest(&Test); CallsTest(42); }
3,029,964
3,030,007
Is it safe to take the address of std::wstring's internal pointer?
I have an interface which is used like the following: if (SUCCEEDED(pInterface->GetSize(&size)) { wchar_t tmp = new wchar_t[size]; if (SUCCEEDED(pInterface->GetValue(tmp, size))) { std::wstring str = tmp; // do some work which doesn't throw } delete[] tmp; } Is it safe and portable to do this instead? if (SUCCEEDED(pInterface->GetSize(&size)) { std::wstring str; str.resize(size-1); if (SUCCEEDED(pInterface->GetValue(&str[0], size))) { // do some work } } Now, obviously this works (doesn't crash/corrupt memory) or I wouldn't have asked, but I'm mostly wanting to know if there's a compelling reason not to do this. Edit: Actually I had change this to .resize(size-1), as apparently the null character is taken into account for you (by VS 2010 anyway). Using .resize(size) ended up where appending to the end of the string was resulting in: str.resize(size); pInterface->GetValue(&str[0], size); str contains L"foo\0"; str += L"bar"; str contains L"foo\0bar"; Trying to use the resulting str.c_str ends up looking like L"foo" due to the null in the middle.
As AraK points out, the string storage might not be contiguous, though this is unlikely. You could also consider using a vector: if (SUCCEEDED(pInterface->GetSize(&size)) { std::vector <wchar_t> vtmp( size ); if (SUCCEEDED(pInterface->GetValue( & vtmp[0], size))) { std::wstring str = & vtmp[0]; // or maybe don't bother with the string - just use the vector } } which is more likely to be exception safe.
3,030,033
3,030,046
how to go through a string array and apply functions for different strings?
Ok, this may be really noobish question, but i am wishing there is something i dont know yet. I go through a file, and check which string each line has, depending on the string value i execute a different function for it (or functions). This is how i do it now: Edit: I need to use variables outside the if-else-if range inside the if's, updated code: string s1 = "used"; string s2 = "in"; string s3 = "functions"; if(str == "something"){ something = process(s1, s2); }else if(str == "something else"){ something = process(s2, s3); }else if(str == "something more"){ something = process(s1, s3); something = process(s1, s2); }else if(str == "something again"){ // do more stuff }else if(str == "something different"){ // do more stuff }else if(str == "something really different"){ // do more stuff } I am afraid this will become "slow" after i have to repeat those else if lines a lot... I tried to use switch() statement, but obviously it doesnt work here, is there something similar to switch() to use here?
If you just want to execute different functions, you can use a map from strings to function pointers or functors like boost::function / tr1::function: void f1() { /* ... */ } void f2() { /* ... */ } // ... creating the map: typedef void (*FuncPtr)(); typedef std::map<std::string, FuncPtr> FuncMap; FuncMap fnMap; fnMap["something"] = &f1; fnMap["something else"] = &f2; // ... using the map: FuncMap::const_iterator it = fnMap.find(str); if (it != fnMap.end()) { // is there an entry for str? it->second(); // call the function } As for passing parameters, with the details given so far i'd probably go for passing the unparsed remainder of the line or a list of string tokens to the functions and let them handle those as they see fit: void f1(const std::vector<std::string>& tokens) { /* ... */ } // ... typedef void (*FuncPtr)(const std::vector<std::string>&); typedef std::map<std::string, FuncPtr> FuncMap; // ... std::vector<std::string> tokens = /* ...? */; FuncMap::const_iterator it = fnMap.find(str); if (it != fnMap.end()) { it->second(tokens); } You could also take a look at the interpreter example from Boost.FunctionTypes (header, source file) wether that is similar to your scenario.
3,030,083
3,030,258
What's the C strategy to "imitate" a C++ template ?
After reading some examples on stackoverflow, and following some of the answers for my previous questions (1), I've eventually come with a "strategy" for this. I've come to this: 1) Have a declare section in the .h file. Here I will define the data-structure, and the accesing interface. Eg.: /** * LIST DECLARATION. (DOUBLE LINKED LIST) */ #define NM_TEMPLATE_DECLARE_LIST(type) \ typedef struct nm_list_elem_##type##_s { \ type data; \ struct nm_list_elem_##type##_s *next; \ struct nm_list_elem_##type##_s *prev; \ } nm_list_elem_##type ; \ typedef struct nm_list_##type##_s { \ unsigned int size; \ nm_list_elem_##type *head; \ nm_list_elem_##type *tail; \ int (*cmp)(const type e1, const type e2); \ } nm_list_##type ; \ \ nm_list_##type *nm_list_new_##type##_(int (*cmp)(const type e1, \ const type e2)); \ \ (...other functions ...) 2) Wrap the functions in the interface inside MACROS: /** * LIST INTERFACE */ #define nm_list(type) \ nm_list_##type #define nm_list_elem(type) \ nm_list_elem_##type #define nm_list_new(type,cmp) \ nm_list_new_##type##_(cmp) #define nm_list_delete(type, list, dst) \ nm_list_delete_##type##_(list, dst) #define nm_list_ins_next(type,list, elem, data) \ nm_list_ins_next_##type##_(list, elem, data) (...others...) 3) Implement the functions: /** * LIST FUNCTION DEFINITIONS */ #define NM_TEMPLATE_DEFINE_LIST(type) \ nm_list_##type *nm_list_new_##type##_(int (*cmp)(const type e1, \ const type e2)) \ {\ nm_list_##type *list = NULL; \ list = nm_alloc(sizeof(*list)); \ list->size = 0; \ list->head = NULL; \ list->tail = NULL; \ list->cmp = cmp; \ }\ void nm_list_delete_##type##_(nm_list_##type *list, \ void (*destructor)(nm_list_elem_##type elem)) \ { \ type data; \ while(nm_list_size(list)){ \ data = nm_list_rem_##type(list, tail); \ if(destructor){ \ destructor(data); \ } \ } \ nm_free(list); \ } \ (...others...) In order to use those constructs, I have to create two files (let's call them templates.c and templates.h) . In templates.h I will have to NM_TEMPLATE_DECLARE_LIST(int), NM_TEMPLATE_DECLARE_LIST(double) , while in templates.c I will need to NM_TEMPLATE_DEFINE_LIST(int) , NM_TEMPLATE_DEFINE_LIST(double) , in order to have the code behind a list of ints, doubles and so on, generated. By following this strategy I will have to keep all my "template" declarations in two files, and in the same time, I will need to include templates.h whenever I need the data structures. It's a very "centralized" solution. Do you know other strategy in order to "imitate" (at some point) templates in C++ ? Do you know a way to improve this strategy, in order to keep things in more decentralized manner, so that I won't need the two files: templates.c and templates.h ?
Your example is only one of the many possible uses of templates - generating a generic data structure. This example doesn't need any of the inference which makes templates powerful; asking for something which lets you create generic data structures is not really the same question as asking for something equivalent to C++ templates. Some of the implementation techniques used for <tgmath.h> might give some type inference capabilities, but they is still much weaker and less portable than C++ templates. For the specific example of containers, I wouldn't bother - just create a list with void* data in it, and either use malloc and free to create the data, or give the list have a pair of function pointers to create and destroy values. You can also just rely on the client to manage the data, rather than having the value as a member of the list. If you want to save the indirection, use a variable length array as the data member. As C isn't as type-safe as C++, having void* data isn't an issue. You can do some sophisticated code generation with macros, but there are also other tools to generate code. Personally I like using XSLT for code generation, but then you have a completely non-C-like part of your build process.
3,030,208
3,030,948
Extern variable at specific address
Using C++ and GCC, can I declare an extern variable that uses a specific address in memory? Something like int key __attribute__((__at(0x9000))); AFAIK this specific option only works on embedded systems. If there is such an option for use on the x86 platform, how can I use it?
Easy option: Define int * const key = (int *)0x9000; and refer to *key elsewhere (or use a reference). Pointerless option: All externs have specific addresses! These addresses may not be known until link time, but they must get resolved eventually. If you declare extern int key; then you must supply an address for the symbol key at link time. This can be done using a linker script (see Using ld) or at the linker command line, using the --defsym option. If running gcc, you could use the -Xlinker flag to pass the option on to the linker. In your example, gcc -o outfile -Xlinker --defsym -Xlinker key=0x9000 sourcefile.c The following program, thus compiled, outputs 0x9000. #include <stdio.h> extern int key; int main(void) { printf("%p\n", &key); return 0; } If you have a collection of variables you want to be in some region of memory, a more appropriate method might be to use output sections as suggested by Nikolai, perhaps in conjunction with a custom ld script.
3,030,279
3,030,293
Am I doing something wrong here (references in C++)?
I've been playing around with references (I'm still having issues in this regard). 1- I would like to know if this is an acceptable code: int & foo(int &y) { return y; // is this wrong? } int main() { int x = 0; cout << foo(x) << endl; foo(x) = 9; // is this wrong? cout << x << endl; return 0; } 2- Also this is from an exam sample: Week & Week::highestSalesWeek(Week aYear[52]) { Week max = aYear[0]; for(int i = 1; i < 52; i++) { if (aYear[i].getSales() > max.getSales()) max = aYear[i]; } return max; } It asks about the mistake in this code, also how to fix it. My guess is that it return a local reference. The fix is: Week & max = aYear[0]; Is this correct/enough?
The first one is correct. For the second one, there are infinite number of solutions :), but this would be mine: Week Week::highestSalesWeek(Week aYear[52]) // return a copy of the week { Week max = aYear[0]; for(int i = 1; i < 52; i++) { if (aYear[i].getSales() > max.getSales()) max = aYear[i]; } return max; } If max is a reference, you would modify the first element of aYear everytime you do: max = aYear[i] Also, you could use a pointer to return a reference to the week: Week & Week::highestSalesWeek(Week aYear[52]) { Week* max = &aYear[0]; for(int i = 1; i < 52; i++) { if (aYear[i].getSales() > max->getSales()) max = &aYear[i]; } return *max; }
3,030,655
3,030,678
strongly typed C++0x enumeration comparison
why aren't instances of strongly typed C++0x enumerations comparable to each other? Update: They are comparable in gcc 4.6; I'm not sure if it worked in gcc 4.4.
If you use strongly typed enumerations, it's like making your enum a realy type, a class. Then it follows the same rules as for classes. Instances of different classes can't be compared to each other by default. You have to define a comparison function (or member function) to make them comparable. Therefore making an enumeration strongly typed makes it follows this very same rule.
3,030,970
3,031,044
Windows program written using MFC is a C++ program?
Every C++ books that I've read says something like this:- All C++ programs have a main() function. main() function is the starting point for all C++ programs. All C++ programs begin its execution from the main() function. However, I found that Windows programs written using MFC do not have any main() function. It use WinMain() function as the program starting point. So can I say that Windows program written using MFC is not a C++ program? Then, what kind of program it is? Thanks.
The answer to this question is a little more complicated than yes or no. It depends largely, on how strict you make your definition of "C++ program". A Windows subsystem program built with MSVC will not generally have a main function. MFC is a C++ language framework for building Windows subsystem programs (at least in contemporary practice). For the purposes of "Is a program written without a main function using a C++ compiler a C++ program, and if not, what is it?" MFC is irrelevant. The main function, can be talked about in terms of "freestanding" and "hosted" implementations. Only "hosted" implementations are required by the standard to have main as an entry point. That said, you'd be hard pressed to call Microsoft's implementation of the CRT and the language "freestanding" with a straight face. So we could make the question more specific "Is an MFC application a conforming, hosted C++ program?" and the answer to that would be "Technically, very technically, no." Re: freestanding vs. hosted: Any run of the mill C++ user land application is generally going to be hosted, that is have the benefit of the standard library et. al. Examples of freestanding scenarios might in an embedded system or an operating system kernel. For example when writing an OS kernel you can't rely on the presence of functionality like malloc or new because you're implementing the services (virtual memory, processes, etc.) that will ultimately used to implement things like malloc and new.
3,031,011
3,031,035
Is a display list best for this? (OpenGL)
I'm rendering 2D polygons with the GLUTesselator the first time, then they are stored in a display list for subsequent use. I think VBO's might be faster, but since I can't access the stuff that the tesselator outputs, and since it uses mixes of gl_triangle, quad, strip etc, i'm not sure how I could do this, even though I would like to use VBO's once the GLUTesselator is done with them for optimal performance. Thanks
It's been a while since I've used the GLU tesselator, but as I recall it just adds standard triangles to your vertex list. One of the callback functions that you pass into it will be receiving the new vertices and putting them somewhere. This happens in your code, so the data isn't hidden from you. Display lists are better than rendering in immediate mode, but generally they are a very poor choice compared to VBOs. Update: "Professional"-market OpenGL drivers like Quadro and FireGL will have more effort put into their display list implementation than consumer level cards. But even then the amount of optimization that they can do is much less than old-school 3D programmers from the SGI days think they get. The display list is supposed to capture state changes and other factors, but still take into consideration other states that may change independently of the display list. It's been a couple years since I had hard information on current driver implementations, but at point a display list would hold your geometry data in software and upload them like a plain vertex array since it may need to know certain gl states to make adjustments to the data before uploading to GPU memory. Basically, a display list gives you theoretical flexibility to make changes at execution time that it needs to know before it can upload the data. A VBO locks down the format in a way that can go straight into memory at creation time.
3,031,105
3,031,123
Exclude subexpression from regex in c++
Suppose I was trying to match the following expression using regex.h in C++, and trying to obtain the subexpressions contained: /^((1|2)|3) (1|2)$/ Suppose it were matched against the string "3 1", the subexpressions would be: "3 1" "3" "1" If, instead it were matched against the string "2 1", the subexpressions would be: "2 1" "2" "2" "1" Which means that, depending on how the first subexpression evaluates, the final one is in a different element in the pmatch array. I realise this particular example is trivial, as I could remove one of the sets of brackets, or grab the last element of the array, but it becomes problematic in more complicated expressions. Suppose all I want are the top-level subexpressions, the ones which aren't subexpressions of other subexpressions. Is there any way to only get them? Or, alternatively, to know how many subexpressions are matched within a subexpression, so that I can traverse the array irrespective of how it evaluates? Thanks
There are two common approaches to solving this problem: Named capturing groups: (?P<name>), so you can pull out captured groups explicitly by name. Non-capturing groups, usually: (?: blah), such that the group doesn't become part of the resulting group list, and the rest will remain in the expected order. It's unclear which regex dialect you're using, so I don't know if it supports either approach, but check out this regex comparison chart. Turning the (1|2) group into a non-capturing group would look like: /^((?:1|2)|3) (1|2)$/
3,031,198
3,031,518
Is it good practice to use assert() in class mutators?
For example: void Date::month(unsigned int inMonth) { assert(inMonth <= 12); _month = inMonth; } If this is not good practice, what is the correct way to go about this?
You shouldn't use assert to ensure that an argument to a public member function is valid. The reason is that there's no way for clients of your class to react to a failed assertion in any meaningful way (the fact that asserts are removed from release builds does not help either). As a rule of thumb, assert should only be used for things that are strictly under your control (e.g., an argument of a private method). In this case you're better off throwing a std::invalid_argument exception: void Date::month(unsigned int month) { if(month == 0 || month > 12) { throw std::invalid_argument("a month must be in the [1-12] range"); } _month = month; }
3,031,336
3,031,339
error C2440: '=' : cannot convert from 'std::string []' to 'std::string []'
now what is wrong with this code! Header: #pragma once #include <string> using namespace std; class Menu { public: Menu(string []); ~Menu(void); }; Implementation: #include "Menu.h" string _choices[]; Menu::Menu(string items[]) { _choices = items; } Menu::~Menu(void) { } compiler is complaining: error C2440: '=' : cannot convert from 'std::string []' to 'std::string []' There are no conversions to array types, although there are conversions to references or pointers to arrays there is no conversion! so what is it on about? please help, just need to pass a bloody array of strings and set it to Menu class _choices[] attribute. thanks
Array's cannot be assigned, and your arrays have no sizes anyway. You probably just want a std::vector: std::vector<std::string>. This is a dynamic array of strings, and can be assigned just fine. // Menu.h #include <string> #include <vector> // **Never** use `using namespace` in a header, // and rarely in a source file. class Menu { public: Menu(const std::vector<std::string>& items); // pass by const-reference // do not define and implement an empty // destructor, let the compiler do it }; // Menu.cpp #include "Menu.h" // what's with the global? should this be a member? std::vector<std::string> _choices; Menu::Menu(const std::vector<std::string>& items) { _choices = items; // copies each element }