question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,900,868
1,900,952
Transitioning from desktop app written in C++ to a web-based app
We have a mature Windows desktop application written in C++. The application's GUI sits on top of a windows DLL that does most of the work for the GUI (it's kind of the engine). It, too, is written in C++. We are considering transitioning the Windows app to be a web-based app for various reasons. What I would like ...
See also Can a huge existing application be ported to the web? How? Sorry there are no good solutions, just less bad ones.... Firstly as you already develop for windows I am assuming that you are used to using the Microsoft development tools, I would not give the same answer for a desktop application that is comi...
1,900,924
1,901,917
Behaviour of std::partition when called on empty container?
I ran into a problem when calling std::partition on an empty container (std::list). std::list<int>::iterator end_it = std::partition(l.begin(), l.end(), SomeFunctor(42)); std::list<int>::iterator it = l.begin(); while (it != end_it) { // do stuff } If the list is empty, std::partition returns an iterator, that is n...
Right now, there really is no good answer. The Library Working Group of the C++ committee issue number 1205 covers exactly this question. That issue includes both a primary and an alternative proposed resolution but neither has been accepted or rejected yet (and I don't like either one). Since the standard doesn't give...
1,901,049
1,901,677
Boost (v1.33.1) Thread Interruption
How can I interrupt a sleeping/blocked boost::thread? I am using Boost v1.33.1, upgrading is not an option. Thank you.
A quick perusal of the documentation for boost.thread in 1.33 suggests that there is no portable way to achieve interruption. Thread interruption was introduced (for threads in one of the boost "interruption points") in 1.35. As a result the only option I can think of is to use signals (which aren't in 1.33 either, so ...
1,901,162
1,901,358
How to tunnel TCP over reliable UDP?
Assume I have a reliable UDP library, and want to tunnel arbitrary TCP connections over it. This is my current approach to doing so, but I feel that it may not be very efficient. Any suggestions are very welcome. Client establishes a reliable UDP connection to server. Client runs a local SOCKS5 proxy, which receives d...
The most efficient way is when the two endpoints directly communicate to each other. If they communicate with different protocols, you need at least one proxy / gateway / traffic converter / whatever. In this case, there is no way around two of these converters, as you now have 3 parts involved: End point client, netwo...
1,901,483
1,901,511
Min and Max values for integer variable at compile time in C++
Is there a simple, clean way of determining at compile time the max and min values for a variable of some (otherwise unknown at the moment) integer variable or type? Using templates? For example: // Somewhere in a large project is: typedef unsigned long XType; typedef char YType; // ... // Somewhere else XType a; ...
Check out boost integer_traits.
1,901,682
1,901,813
C++ Data Timeout with Blocking Call
I have a main loop which is fully data-driven: it has a blocking call to receive data and stores it as the 'most recent' (accessed elsewhere). Each piece of data has an associated lifespan, after which the data timesout and can no longer be considered valid. Each time I receive data I reset the timeout. Unfortunately I...
Since the expiration of data is an asynchronous event, you'll need to use an asynchronous timer. As you're using boost, you may want to look into Boost.Asio, which provides you with deadline_timer objects that can be used in conjunction with callback handlers. (See here for more information.) The callback handler wi...
1,901,768
1,901,831
Implicit invocation of operator [C++]
I defined two classes: class Token_ { public: virtual char operator*()const = 0;//this fnc cannot run implicitly protected: Token_() { } Token_(const Token_&); Token_& operator=(const Token_&); }; and second: class Operator : public Token_ { public: Operator(const char ch):my_data_(to...
token is a pointer to a Token_ object, not a Token_ object itself, thus the * operator in the switch statement dereferences only the pointer (thereby only obtaining the object), but doesn't then continue to call the operator you defined. Try instead: switch(*(*token)) { The use of your custom operator * might be a bit...
1,901,781
1,901,991
SSE2 - "The system cannot execute the specified program"
I recently developed a Visual C++ console application which uses inline SSE2 instructions. It works fine on my computer, but when I tried it on another, it returns the following error: The system cannot execute the specified program Note that the program worked on the other computer before introducing the SSE2 code. An...
Most likely the use of the SSE2 instructions is requiring a DLL which isn't present on the second system. Here's a blog entry on how to figure out exactly which one: How to Debug 'The System cannot Execute the specified program' message
1,902,003
1,902,073
Does the visual studio 2008 profiler work with unmanaged C++?
I know that VS 2008 Team Edition has a profiler, but I'm also aware of the recent trend they have at Microsoft of completely ignoring unmanaged languages (what's the last time unmanaged C++ got something cool in the IDE?!).. For example I know for a fact that the IDE "Unit Tests" and "Code Metrics" features don't work ...
Yes, it works with native code.
1,902,464
1,902,940
Is there a better way to bring names into class scope other than to typedef them?
I keep running into this issue: class CCreateShortcutTask : public CTask { public: CCreateShortcutTask( CFilename filename, // shortcut to create (or overwrite) Toolbox::Windows::CShellLinkInfo definition // shortcut definition ) ... Having to spell out ...
I think there is a confusion on typedefs. Using private typedefs is perfectly suitable (and often used). This relies on the fact that in C++ a typedef does not introduce a new type, but a synonym! namespace VeryLongNamespaceYoullNeverWantToSeeAgain { class SuchAStupidNameShouldBeBanned { public: typedef xxx i...
1,902,810
1,903,311
What shall I do while waiting in a thread
I have a main program which creates a collection of N child threads to perform some calculations. Each child is going to be fully occupied on their tasks from the moment their threads are created till the moment they have finished. The main program will also create a special (N+1)th thread which has some intermittent t...
A ready-to-use condition class for WIN32 ;) class Condition { private: HANDLE m_condition; Condition( const Condition& ) {} // non-copyable public: Condition() { m_condition = CreateEvent( NULL, TRUE, FALSE, NULL ); } ~Condition() { CloseHandle( m_condition ); } void Wait() {...
1,902,832
1,902,900
resize versus push_back in std::vector : does it avoid an unnecessary copy assignment?
When invoking the method push_back from std::vector, its size is incremented by one, implying in the creation of a new instance, and then the parameter you pass will be copied into this recently created element, right? Example: myVector.push_back(MyVectorElement()); Well then, if I want to increase the size of the vec...
At least with GCC, it doesn't matter which you use (Results below). However, if you get to the point where you are having to worry about it, you should be using pointers or (even better) some form of smart pointers.. I would of course recommend the ones in the boost library. If you wanted to know which was better to us...
1,902,976
1,906,674
MSVC - Any way to check if function is actually inlined?
I have to check whether a function is being inlined by the compiler. Is there any way to do this without looking at assembly (which I don't read). I have no choice in figuring this out, so I would prefer if we could not discuss the wisdom of doing this. Thanks!
Generate a "MAP" file. This gives you the addresses of all non-inlined functions. If your function appears in this list, it's not inlined, otherwise it's either inlined or optimized out entirely (e.g. when it's not called at all).
1,903,008
1,903,614
Why not call FreeLibrary from entry point function?
I'm writing a DLL that needs to call a separate DLL dynamically multiple times. I would like to keep the callee loaded and then just unload it when my DLL is unloaded. But according to Microsoft, that's a bad idea. The entry point function should only perform simple initialization tasks and should not call any oth...
I think I've found the answer. The entry-point function should perform only simple initialization or termination tasks. It must not call the LoadLibrary or LoadLibraryEx function (or a function that calls these functions), because this may create dependency loops in the DLL load order. This can result in...
1,903,055
1,903,142
Inheriting from a virtual template class in C++
How do I inherit from a virtual template class, in this code: // test.h class Base { public: virtual std::string Foo() = 0; virtual std::string Bar() = 0; }; template <typename T> class Derived : public Base { public: Derived(const T& data) : data_(data) { } virtual std::string Foo(); virtual std::string ...
You need to define template<typename T> std::string Derived<T>::Foo() { ... } and template<typename T> std::string Derived<T>::Bar() { ... } in the header file. When the compiler is compiling test.cpp it doesn't know all the possible values of T that you might use in other parts of the program. I think there are some ...
1,903,066
1,903,522
Wrapping a PropertySheet; how to handle callbacks?
I'm writing an (unmanaged) C++ class to wrap the Windows PropertySheet. Essentially, something like this: class PropSheet { PROPSHEETHEADER d_header; public: PropSheet(/* parameters */); INT_PTR show(); private: static int CALLBACK *propSheetProc(HWND hwnd, UINT msg, LPARAM lParam); ...
As you are showing the property sheet modally, you should be able to use the parent window (i.e. its handle) of the property sheet to map to an instance, using ::GetParent() on the hwndDlg parameter of PropSheetProc().
1,903,173
1,903,724
Problem assigninging values to a struct in C++ to a structure passed from C#
I have a function in C# that is passing an array of structures into a DLL written in C++. The struct is a group of ints and when I read out the data in the DLL all the values come out fine. However if I try to write to the elements from C++ the values never show up when I try to read then back in C#. C# [StructLayout(L...
I found the answer posted to another question: How to marshall array of structs in C#? When marshaling apparently the default is to marshal the parameters as In. Otherwise they need to be explicitly declared as Out or In, Out. After specifying that explicitly my code the example now works. Thanks to his Skeetness for t...
1,903,190
1,903,281
Optimal way to perform a shift operation on an array
Suppose I have an array unsigned char arr[]= {0,1,2,3,4,5,6,7,8,9}; Is there a way to perform shift operation on them besides just copying them all into another array. We can easily do it using linked lists but I was wondering if we can use a shift operator and get work done faster. Note: The data in this question is ...
If you want a circular shift of the elements: std::rotate(&arr[0], &arr[1], &arr[10]); ... will do the trick. You'll need to #include the algorithm header.
1,903,248
1,905,486
C++ client for Java RMI? Or any other way to use Java from C++?
We need to use a Java library from C++ code. An idea that I had is that if we could build a C++ client for Java RMI (ideally using some framework or wizard), than we could run the Java lib as a separate server. This seem cleaner than trying to run Java VM within a C++ application. Alternatively, if you have any other ...
JNI was the intended solution to the problem of C/C++ to Java integration. It's not difficult. Message Queues are better for larger grained interactions, or remote interactions where the message queue is accessible over the network. CORBA and RMI were also intended to be network access mechanisms. From your descr...
1,903,303
1,903,325
xerces-c++ compile/linking question
After installing Xerces-C++ (XML library): ./configure --disable-shared ./make ./make-install ldconfig And writing the simple program (xmlval.cpp): #include <stdio> #include <xercesc/dom/DOM.hpp> int main() { std::cout << "HI" << std::endl; } And compiling: /usr/bin/g++ -L/usr/local/lib -I/usr/local/include -o x...
You seem to miss linking with curl, try adding -lcurl.
1,903,532
1,903,567
Set a file wide breakpoint in gdb
I'm trying to understand how a piece of code is working. I've enabled a breakpoint for a function, but it looks like it never gets hit. So, I'd like to break whenever ANY function within this class is invoked. Is this possible? Thanks!
Try rbreak regex - for example: rbreak ^MyClass:: Noteworthy fact: There is an implicit .* leading and trailing the regular expression you supply, so to match only functions that begin with foo, use ^foo.
1,903,846
1,903,879
C++ convert decimal hours into hours, minutes, and seconds
I have some number of miles and a speed in MPH that I have converted into the number of hours it takes to travel that distance at that speed. Now I need to convert this decimal number into hours, minutes, and seconds. How do I do this? My best guess right now is: double time = distance / speed; int hours = time; // dou...
I don't know c++ functions off the top of my head, however this "psuedocode" should work. double time = distance / speed; int hours = time; double minutesRemainder = (time - hours) * 60; int minutes = minutesRemainder; double secondsRemainder = (minutesRemainder - minutes) * 60; int seconds = secondsRemainder; Correct...
1,903,917
1,903,946
Compiling a static lib inside a exe
I have a dll and an exe, both of which I have the sources to. For the DLL I have compiled completely statically and therefore, I would assume that the the .lib is also static. However, when I include that lib in my C++ VC++ 2008 project under Linker > Input > Additional Dependencies . I set the compile mode to /MT (mul...
The 'compile mode' setting that you are referring to is the setting for the runtime library that gets linked with whatever library or executable you produce. If your project is set up to produce a DLL (check the main project page), then it'll still produce a DLL no matter what you're putting into the runtime library se...
1,903,954
4,609,795
Is there a standard sign function (signum, sgn) in C/C++?
I want a function that returns -1 for negative numbers and +1 for positive numbers. http://en.wikipedia.org/wiki/Sign_function It's easy enough to write my own, but it seems like something that ought to be in a standard library somewhere. Edit: Specifically, I was looking for a function working on floats.
The type-safe C++ version: template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } Benefits: Actually implements signum (-1, 0, or 1). Implementations here using copysign only return -1 or 1, which is not signum. Also, some implementations here are returning a float (or T) rather than an int,...
1,904,078
1,914,717
How do I create a WT project in MSVC?
If anyone has used WT successfully with MSVC (mine is 2005), could you please provide some details on how this can be done? I have installed WT fine , then ran some examples. The problems begin when I try to create a project of my own, as simple as hello.C. I get a thousand compiler errors like this one : C:\Program F...
Well after searching and googling around for some days , it seems that using CMake is a must in order to build a WT project. This page explains the procedure. Hopefully it will save you some time.
1,904,340
1,904,363
Global Variable Count
How to count the number of global variables in C++ with a program that I can run with Grep?
A better method is to have your compiler print a map file. Most map files list all the global variables and their locations. If you're lucky, the map file may even indicate which translation unit the global variable belongs to.
1,904,592
1,904,596
Building VOIP into an application (C++ specifically)
Are there existing libraries and frameworks which allow VOIP to be built into a bespoke application without reinventing the wheel? A customer is interested by the possibility for a C++ desktop application and while it's not hugely useful (they could just use skype), it is quite cool. I believe some technologies like Di...
Well, since Asterisk is open source, that's a good place to start. Check out Astxx "The goal of Astxx is to provide a fully functional and easy to use C++ wrapper for Asterisk enabling developers to write Asterisk related software using the full range of what C++ has to offer. This includes AGI scripts and accessing t...
1,904,606
1,904,627
C++ RTTI and Derived Classes
My C++ is a bit rusty. Here's what I'm attempting to do: class Cmd { }; class CmdA : public Cmd { }; class CmdB : public Cmd { }; ... Cmd *a = new CmdA (); Cmd *b = new CmdB (); First problem: cout << typeid (a).name () cout << typeid (b).name () both return Cmd * types. My desired result is CmdA* and CmdB*. Any w...
Ah but typeid(a).name() will be Cmd* because its defined as Cmd*. typeid(*a).name() should return CmdA http://en.wikipedia.org/wiki/Typeid Also, the base class of whatever you pass to typeid must have virtual functions, otherwise you get back the base class. MSDN has a more eloquent explanation for that: If the expres...
1,904,635
1,904,659
warning C4003 and errors C2589 and C2059 on: x = std::numeric_limits<int>::max();
This line works correctly in a small test program, but in the program for which I want it, I get the following compiler complaints: #include <limits> x = std::numeric_limits<int>::max(); c:\...\x.cpp(192) : warning C4003: not enough actual parameters for macro 'max' c:\...\x.cpp(192) : error C2589: '(' : illegal toke...
This commonly occurs when including a Windows header that defines a min or max macro. If you're using Windows headers, put #define NOMINMAX in your code, or build with the equivalent compiler switch (i.e. use /DNOMINMAX for Visual Studio). Note that building with NOMINMAX disables use of the macro in your entire progr...
1,904,636
1,904,648
Decent tool/library for C++ to handle XML?
I need to do some XML-related job (parsing, comparison etc). Is there any C++ library for this that you know works good ? Preferrably for Win XP. Thanks.
PugiXml will do it.
1,904,760
1,904,812
Tool to create wizards in C++
The MFC concept (using PropertySheet / PropertyPages) to build a wizard has let me down many times and for several reasons. I googled the subject somewhat but could not turn up with any library or tool that would help me create my wizards easier. Any recommendations would help a lot.
Did you look at this article: http://www.codeguru.com/cpp/w-d/dislog/wizards/article.php/c5083/ LogicNP Software
1,904,796
1,906,624
specializing functions on stl style container types
If i have a type T, what is a useful way to inspect it at compile time to see whether its an STL-style container (for an arbitrary value type) or not? (Assumption: pointers, reference, etc. already stripped) Starting code: template<class T> // (1) void f(T&) {} template<class T> // (2) void f(std::vector<T>&) {} vo...
STLcontainers by definition have a typedef iterator, with 2 methods begin() and end() retruning them. This range is what the container contains. If there's no such range, it's not a container in the STL sense. So I'd sugegst something along the line of (not checked) template<typename CONTAINER> void f(CONTAINER& c, ...
1,904,846
1,906,180
DirectX: How do you initialize the vertex buffer and index buffer for a cone?
How do you initialize the vertex buffer and index buffer for a cone in DirectX 9 in C++?
Well its fairly easy. A cone has a single point at one end. At the other end you have a circle. Obviously the more points you have in that circle the more circular it looks. You can plot a circle using x = r * cos( theta ); y = r * sin( theta ); To make any triangle you can do it by plugging theta and theta plus som...
1,904,993
1,943,845
Change brightness of blitted bitmap using Allegro
I'm using the Allegro game library to make a tile game. I want the tiles to get exponentially brighter. Unfortunately Allegro does not have a "Brighten" feature. What I then decided to do, was blit a tile to the buffer, then for each pixel that it just blited for that tile, I increased their rgb values and putpixel. Th...
You can use: draw_lit_sprite what it does is take a BITMAP and draw it using a "light" that you have to set before by using this function: set_trans_blender so basically, what you have to do is: //Init allegro code here init_allegro_stuff(); //It takes as arguments red, green, blue, alpha //so in this ...
1,905,058
1,905,065
Open Source Executable Editor
I have a native C++ windows app that i would like to edit. Are there any open source tools for me to do this on Windows? I want to edit the executable directly.
Allow me to direct you toward this Stack Overflow question, the accepted answer of which links to this hex editor comparison chart, including license info.
1,905,070
1,905,651
Unit testing an executable project
Maybe I am not thinking about this correctly. I am starting my second project using unit tests. My first project I rolled my own, for this project I am trying out Boost::test. My question is, what are the proper procedures for unit testing projects that compile into executables? It seems like everything I see out the...
The project can be compiled as a library and this library linked, possibly statically, in two separate executables: the "project", which will be delivered, and the unit tests. Now the problem seems to originate from your IDE, which one is it ? Does it allow to create two binaries for one project ?
1,905,079
1,905,094
Using exceptions to abort series of user inputs - Good? Bad?
Consider a scenario where a console application asks for a series of inputs, one after the other. Each input is validated before proceeding to the next. Now if an input made by the user is invalid, an error message is shown and the user is asked if he/she wants to continue. If the user chooses no, the input process is ...
I, personally, would do it something like this: bool valid = read("Name") && read("Age") && read("Sex") && read("DoB"); It's equivalent to the first code you posted. The && operator in C++ evaluates terms left-to-right and stops when a false outcome is encountered. This is not a compile...
1,905,228
1,911,785
Suppress unused variable warning in C++ => Compiler bug or code bug?
Presently, I am using the following function template to suppress unused variable warnings: template<typename T> void unused(T const &) { /* Do nothing. */ } However, when porting to cygwin from Linux, I am now getting compiler errors on g++ 3.4.4 (On linux I am 3.4.6, so maybe this is a bug fix?): Write.cpp: In mem...
It is a compiler bug and there are no known work arounds: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=42655 It is fixed in v4.4.
1,905,237
1,905,248
Where in memory is vtable stored?
Where in memory is vtable stored?
Depends on compiler. In VC++, the vtable pointer stored at the beginning of the object allocation, before any member data. (Provided your class has at least one virtual member function.) There also may be multiple vtable pointers, if your class multiply-inherits from other classes with vtables. The vtables themselves a...
1,905,336
1,905,354
structure on a heap memory
This question was recently asked to me in an interview for which i went confused!! "How do you initialize a structure in the heap memory ?" could anybody please tell me the correct answer for this? btw:how exactly are stack and heap memory are different from each other? And looking about the above question some might a...
The stack lives exactly as long as the function instance defining it -- when that function intance returns, that memory's free for recycling (if it's housing a proper C++ object w/destructor and all, that dtor will be called). The heap lives until explicitly freed. "How do you initialize a struct" (on either kind of m...
1,905,417
1,905,424
array vs vector vs list
I am maintaining a fixed-length table of 10 entries. Each item is a structure of like 4 fields. There will be insert, update and delete operations, specified by numeric position. I am wondering which is the best data structure to use to maintain this table of information: array - insert/delete takes linear time due to...
Use STL vector. It provides an equally rich interface as list and removes the pain of managing memory that arrays require. You will have to try very hard to expose the performance cost of operator[] - it usually gets inlined. I do not have any number to give you, but I remember reading performance analysis that describ...
1,905,439
1,905,502
Overload operators as member function or non-member (friend) function?
I am currently creating a utility class that will have overloaded operators in it. What are the pros and cons of either making them member or non-member (friend) functions? Or does it matter at all? Maybe there is a best practice for this?
Each operator has its own considerations. For example, the << operator (when used for stream output, not bit shifting) gets an ostream as its first parameter, so it can't be a member of your class. If you're implementing the addition operator, you'll probably want to benefit from automatic type conversions on both side...
1,905,450
1,905,513
What is the difference between AddressOf in c# and pointer in c++
I am confused in AddressOf in c# and pointer in c++ ? Am i right that Addressof is manage execution and pointer is unmanage execution or something else?
AddressOf is a VB operator, and doesn't exist in C#. It creates a delegate to a procedure. The delegate can be used later to call the procedure in code that does not include the procedure's name. A pointer in C/C++ is a representation of an address in memory. You can create a pointer to a function and use it to call t...
1,905,787
1,905,827
pros and cons of smart pointers
I came to know that smart pointer is used for resource management and supports RAII. But what are the corner cases in which smart pointer doesn't seem smart and things to be kept in mind while using it ?
Smart pointers don't help against loops in graph-like structures. For example, object A holds a smart pointer to object B and object B - back to object A. If you release all pointers to both A and B before disconnection A from B (or B from A) both A and B will hold each other and form a happy memory leak. Garbage colle...
1,905,876
1,905,881
Which STL container to use if I want it to ignore duplicated elements?
I am looking for some STL (but not boost) container, which after the following operations will contain 2 elements: "abc" and "xyz": std::XContainer<string> string_XContainer; string_XContainer.push_back("abc"); string_XContainer.push_back("abc"); string_XContainer.push_back("xyz"); By the way, I need it just in order ...
std::set is the one you are after. A set will contain at most one instance of each element, compared according to some comparator function you define. This would be one approach to get the number of unique strings. From your example, the strings were already in sorted order? If that's the case, then you could just c...
1,905,951
1,906,157
is there a design pattern that isolate 'methods' from member?
basically, i want to have something like: class DataProcessor{ }; however, in the future, i will need to pass DataProcessor's instance to some other functions, because DataProcessor contains some crucial data. what I got in mind is to separate the members from methods: class DataProcessorCore{}; class DataProce...
Maybe the Strategy Pattern is the one you are looking for. This would give you the oppurtunity to change the methods working on your data at runtime. wiki: strategy pattern
1,906,000
1,906,168
C++ by-reference argument and C linkage
I have encountered a working (with XLC8 and MSFT9 compilers) piece of code, containing a C++ file with a function defined with C linkage and a reference argument. This bugs me, as references are C++ only. The function in question is called from C code, where it is declared as taking a pointer argument to the same type ...
My copy of n3000.pdf (from here), has this to say in section 7.5—Linkage specifications: 9. Linkage from C++ to objects defined in other languages and to objects defined in C++ from other languages is implementation-defined and language-dependent. Only where the object layout strategies of two language implementations...
1,906,126
1,906,159
Simple C++ (or c) libraries for things such as fetching URL's
I am needing to write some code that I can compile and run on Windows, OS/X, and iPhone. The iphone is fairly limited in what you can include. Are there any simple libraries or websites that provide source code for basic things that could be compiled and use on the iPhone as well as everything else?
One of the popular libraries for HTTP access from C is libcurl. A quick search showed that other people have been able to compile cURL at least as a static library for use in iPhone apps.
1,906,166
1,906,222
Inter-Process Communication Recommendation
I'm searching for a light-weight, fast and easy way to handle Inter Process Communication between some programs on a Linux machine. Currently, I'm thinking Named Pipe, because it's provided by the OS itself. Are there any caveats about the performance or usability? Would Shared Memory be better? I don't think I need a...
Boost has a nice InterProcess library that is cross-platform and quite intuitive. I have only toyed with it though, so there might be better alternatives out there. However, if you don't really need shared memory, I would stick with a messaging approach. You'll avoid deadlocks and race conditions. The pipe principle is...
1,906,238
1,906,353
Macro definition for message mapping
Formerly I asked a question and got a fair response. But I am stucked with below macro definitions. The below definitions generates a Message Map function like it is in MFC Message Map. But the code below does not compile. Whole statements starting with this-> are problematic ones except the one in MSG_HANDLER this->me...
The "illegal escape sequence" part tells me that you have traling whitespace after your \. Therefore the next lines are not part of the macro.
1,906,505
1,906,527
C++: #include file search?
This MSDN document quotes: look for include files in the same directory of the file that contains the #include statement, and then in the directories of any files that include (#include) that file Wait, what? What does that actually mean (the bold stuff)?
It probably means that if foo/bar/baz.c includes ../bog/bog.h, and the latter contains #include "fix.h" it would find foo/bar/fix.h. In other words, it looks in the directory that contained the C file that included the header containing the include. Clear? :) So, the file layout rendered as gorgeous ASCII graphics, is...
1,906,561
1,906,842
communication between c++ and c# through pipe
I want to send data from a c# application to a c++ application through a pipe. Here is what I've done: this is the c++ client: #include "stdafx.h" #include <windows.h> #include <stdio.h> int _tmain(int argc, _TCHAR* argv[]) { HANDLE hFile; BOOL flg; DWORD dwWrite; char szPipeUpdate[200]; hFile = CreateFile...
At a guess, I'd say you don't need the "\.\Pipe\" prefix when creating the pipe in the server. The examples of calling the NamedPipeServerStream constructor that I've seen just pass-in the pipe name. E.g. using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("BvrPipe")) You can list the open pipes, and t...
1,906,565
1,906,804
PHP extension library accessing PHP superglobals
I have written a PHP extension library in C++. I am writing the extension for PHP 5.x ad above. I need to access PHP superglobals in my C++ code. Does anyone know how to do this?. A code snippet or pointer (no pun inteded) to a similar resource (no pun ...) would be greatly appreciated.
What data do you actually need? - Best way for most data is to refer to the C structure they are coming from. For instance with request data you can check the sapi_globals, accessible using the SG() macro, session data is available via the session module, ... If you really need access to a super global you can find it ...
1,906,605
1,918,944
ntdll!kifastsystemcallret
My program is crashing at the end of execution, and couldnt even see stack unwind info. all i can see is this " ntdll!kifastsystemcallret", can some throw some light?
KiFastSystemCallRet means that the thread is in a syscall - an unfortunate aspect of x86 NT syscall dispatch is that it will not return the context back to the original place, but has to return to a static location in ntdll, which will fix up the context and put you back where you came from. Paste in the stacks and we ...
1,906,691
1,906,942
How to prevent a file from being tampered with
I want to store confidential data in a digitally signed file, so that I know when its contents have been tampered with. My initial thought is that the data will be stored in NVPs (name value pairs), with some kind of CRC or other checksum to verify the contents. I am thinking of implementing the creating (i.e. writin...
First, note that "signing" data (to notice when it has been tampered with) is a completely separate and independent operation from "encrypting" data (to prevent other people from reading it). That said, the OpenPGP standard does both. GnuPG is a popular implementation: http://www.gnupg.org/gph/en/manual.html Basically ...
1,906,784
1,906,827
PHP extension that uses memcached
I am thinking of writing a PHP extension library that will use the memcached library. It is trivial to simply link my library to the memcache shlib. However, I am not sure what will happen if my (extension library) user already uses memcache on his/her website. My questions are: Is it possible to have (possibly diffe...
Mind that there are two memcache extensions for PHP, one is called memcache, the other memcached, the first uses it's own implementation of the memcache protocol, the later uses the library. If you're using the first you shouldn't have a conflcit but have to take care of memcache on your own. I'd suggest building an e...
1,907,012
1,908,140
Which STL containers require the use of CAdapt?
The CAdapt class is provided by Microsoft in order to enable using classes that override the address of operator (operator&) in STL containers. MSDN has this to say about the use of CAdapt: Typically, you will use CAdapt when you want to store CComBSTR, CComPtr, CComQIPtr, or _com_ptr_t objects in an STL container suc...
What is the full list of STL containers with which CAdapt should be used? None. Implementations should assume operator& is overloaded, and use the correct expression &reinterpret_cast<char&>(obj) Now, there is another question that you didn't ask: My VC++ STL implementation doesn't agree. It does provide CAdapt as a...
1,907,069
1,907,156
Confused about CWnd::OnLButtonDown() and CTreeCtrl::OnLButtonDown()
MFC Library Reference CWnd::OnLButtonDown void CMyCla::OnLButtonDown(UINT nFlags, CPoint point) { CWnd::OnLButtonDown(nFlags, point); } void CMyTreeCla::OnLButtonDown(UINT nFlags, CPoint point) { CTreeCtrl::OnLButtonDown(nFlags, point); } I know the inheritance. class CTreeCtrl : public CWnd { ...... } Is...
I think this is what you want. In your class header, you will need to declare the message map, and also write the function header. Class myCWnd : public CWnd { DECLARE_MESSAGE_MAP() //note, no semi colon afx_msg void OnLButtonDown( UINT nFlags, CPoint pt ); }; in the cpp file: BEGIN_MESSAGE_MAP(myCWnd, CWnd) ...
1,907,175
1,907,206
References on statemachine optimization and code generation?
As a follow-up to my state machines as a C++-like language extension question, I'd like some more help. My compiler has been extended to parse my state machine extensions and now I'm beginning semantic analysis and code generation. There is a description on this page. Can anyone point me to good references on state mac...
Theres a good chapter or two on state machines in Allen Hollub's book "Compiler Design In C", which also includes lots of (C I'm afraid) code. The book is about writing compiler-compiler type tools, so must cover generation, though it's a few years since I've read it.
1,907,214
1,907,353
Why are "inlined" static consts not allowed, except ints?
Possible Duplicate Why can't I have a non-integral static const member in a class? struct Example { static const int One = 1000; // Legal static const short Two = 2000; // Illegal static const float Three = 2000.0f; // Illegal static const double Four = 3000.0; // Illegal static const string Five ...
The int and the short are legal, and if your compiler doesn't allow them then your compiler is bust: 9.4.2/4: ... If the 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. I...
1,907,668
1,907,739
What do I need to know about memory in C++?
I've been doing my best to learn C++ but my previous training will fall short in one major issue: memory management. My primary languages all have automatic garbage collection, so keeping track of everything has never really been necessary. I've tried reading up on memory management in C++ online, but I have this sha...
You really, really need to read a good book - learning C++ frankly is not possible without one. I recommend Accelerated C++, by Koenig & Moo, two of the originators of C++.
1,907,795
1,907,822
What is going on at the top of this function
I'm currently looking at a function example that I can't seem to figure out using MFC in Visual C++. The function is as follows CMFC_OSG_MDIView::CMFC_OSG_MDIView() :mOSG(0L) { } I understand everything here except the mOSG(0L) snippet. mOSG was declared in the MFC_OSG _MDIView class as follows: cOSG* mOSG;
CMFC_OSG_MDIView::CMFC_OSG_MDIView() :mOSG(0L) { } The above is a constructor, for a class called CMFC_OSG_MDIView. :mOSG(0L) is called initializer list, which is executed when an object is created. The init-list gets called before the body of the constructor, and it is the correct place to initialize the member varia...
1,907,921
1,907,953
Can using 0L to initialize a pointer in C++ cause problems?
In this question an initializer is used to set a pointer to null. Instead of using value of 0 value of 0L is used. I've read that one should use exactly 0 for null pointers because exact null pointer representation is implementation-specific. Can using 0L to set a pointer to null cause problems while porting?
From the standard (4.10.1): A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero so I guess 0L is ok.
1,908,269
1,908,651
Best way to add python scripting into QT application?
I have a QT 4.6 application (C++ language) and i need to add python scripting to it on windows platform. Unfortunately, i never embed python before, and it seems to be a lot of different ways to do so. Can anyone share his wisdom and point me into some articles/documentation i can read to perform a specified task in le...
Edit: You can use PythonQt (not PyQt) that allow you to use Python with Qt. I think this is what you are searching for. Here a documentation on the official website: http://doc.qt.digia.com/qq/qq23-pythonqt.html.
1,908,341
1,908,551
Is C++ the single language that have both pointers and references?
Amongst the programming languages I know and those I've been exposed to, C++ looks like the only one to have both pointers and references. Is it true?
Algol 68 and Pascal certainly do. IIRC, Ada does too, though I don't remember all the details. PL/I did as well -- it may (easily) have been the first to include both. Algol 68's references were really more like C++ pointers though. In C++, once you initialize a reference, it always refers to the same object. In Algol ...
1,908,512
1,908,536
C++ - Hold the console window open?
My question is super simple, but I'm transitioning from C# to C++, and I was wondering what command holds the console window open in C++? I know in C#, the most basic way is: Console.ReadLine(); Or if you want to let the user press any key, its: Console.ReadKey(true); How do you do this in C++? The only reason I ask ...
How about std::cin.get(); ? Also, if you're using Visual Studio, you can run without debugging (CTRL-F5 by default) and it won't close the console at the end. If you run it with debugging, you could always put a breakpoint at the closing brace of main().
1,908,634
1,908,694
CSocket doesn't receive OnClose or OnReceive when you disable network connection on the client side
I've created a client server application with c++ CSocket. when I connect the client to the server and after that I close the client with normal X button or end task it with taskmanager , server CSocket receives the OnClose event. The problem is when I disable the internet connection on windows that the client is runni...
The client side is shutdown without being able to close the connection to the server via a FIN or RST. For the server to detect that the client is dead it must either have data to send (which would fail) or must send periodic TCP keepalive probes. TCP_KEEPALIVE can be set as a socket option.
1,909,036
1,909,066
Support for C++ refactoring in VS (auto-updating references and header/cpp)
In Visual C# I can rename an entity at its definition, and with two clicks all references to that entity get updated. How do I do this in Visual C++? If it's not supported, is there another IDE that supports it? Note that in the C++ case I also want automatic header/implementation synchronization, so I hardly ever need...
VS won't do it alone, but with an add-in like Visual Assist X (Whole Tomato Software) it does quite nicely.
1,909,092
1,910,052
QT4: Transparent Window with rounded corners
How can I create a partially transparent window with rounded borders (no standard borders)? (I used Qt::FramelessWindowHint to disable standard borders) I tried stylesheets, but border-radius and opacity doesn't seem to have any effect on the window, it only works on children of the enclosing widget. My second idea was...
I had a similar problem where I wanted to paint on a toplevel widget and have only the painted part appear. setWindowOpacity changed the opacity of the painted part, which I didn't want. this->setAttribute(Qt::WA_TranslucentBackground, true); changed the opacity of the widget without the painted part. I just tried t...
1,909,127
1,909,164
How to bind c++ dll to my C# program - winCE
i need to bind C++ dll to my C# WinCE program. (scanner dll) how i can do it ? thank's in advance
You need to use Interop to call into unmanaged code. using System.Runtime.InteropServices; // DllImport public class Win32 { [DllImport("User32.Dll")] public static extern void SetWindowText(int h, String s); } Here is an article that discusses the topic in detail (also where the code is sourced from). http://msdn...
1,909,136
1,909,144
How to get rid of this Constructor error?
I've taken 2 OOP C# classes, but now our professor is switching over to c++. So, to get used to c++, I wrote this very simple program, but I keep getting this error: error C2533: 'Counter::{ctor}' : constructors not allowed a return type I'm confused, because I believe I have coded my default constructor right. Here's...
You forgot the semi-colon at the end of your class definition. Without the semi-colon, the compiler thinks the class you just defined is the return type for the constructor following it in the source file. This is a common C++ error to make, memorize the solution, you'll need it again. class Counter { private: int coun...
1,909,608
1,909,638
Why MS Visual Studio 2008 has 2 copies of <sstream> STL file?
This and this. "c:\Program Files\Microsoft Visual Studio 9.0\VC\crt\src\sstream" "c:\Program Files\Microsoft Visual Studio 9.0\VC\include\sstream" And the files have small differences. Why 2 files ? Thank you.
I don't know why the files are different, but the one in the src directory is part of the runtime library source, and shouldn't be used by users of the library. The other file is the one included when you do #include <sstream>.
1,909,644
1,911,906
Vista/Win7 Bass and treble volume
I'm having a hard time with this crazy Vista/Win 7 architecture, it might be just me but its hard to get used to it :| So, my current problem is that I cant set the bass and treble values for my sound card, I found that there is a IAudioBass and IAudioTreble interfaces which can do this, but I'm getting lost how to cre...
You want to start with the IMMDeviceEnumerator API which allows you to discover which of the endpoints on your sound card you want to modify. You then activate an IDeviceTopology interface. You can walk the IDeviceTopology enumerating parts and activate the IAudioBass and IAudioTreble interfaces off of those parts. Th...
1,909,734
1,912,511
boosts buffer into char* (no std::string)
So, it may be sounds as a realy newbies question... And proboly it is newbies :) I try to turn infomation from boost::asio::streambuf which I got, using read_until into char*. I've found realy many examples of turning it into std::string, but I'd mad, if use bufer -> std::string -> c_str in an application, needs a high...
You are assuming that converting a std::string into a C string hurts performance. This should not be assumed. std::string is often implemented as a wrapper around a C string. If you are unhappy with current performance, start by using a run-time profiler on your code.
1,909,853
1,910,024
Does the caller need to Release the IShellBrowser* obtained via the undocumented WM_GETISHELLBROWSER (WM_USER+7) message?
Several have pointed out that there exists an undocumented message that retrieves the IShellBrowser interface pointer from the common dialog HWND for the file open & save dialogs. But there is conflicting information (or no information) on whether that pointer is AddRef'd, or if it is just the raw address returned, and...
No. You might find the following link useful: The Rules of the Component Object Model . Excerpt: Reference-Counting Rules Rule 1: AddRef must be called for every new copy of an interface pointer, and Release called for every destruction of an interface pointer, except where subsequent rules explicitly permit...
1,909,945
1,909,977
Force derived class to call base function
If I derive a class from another one and overwrite a function, I can call the base function by calling Base::myFunction() inside the implementation of myFunc in the derived class. However- is there a way to define in my Base class that the base function is called in any case, also without having it called explicitly in...
No, this is not possible. But you can simulate it by calling a different virtual function like so: class Base { public: void myFunc() { before(); doMyFunc(); after(); } virtual void doMyFunc() = 0; };
1,910,121
1,910,180
Which Design Pattern / RTTI
I'm looking for the best way to dispatch objects to the correct "target" object. I have a base command class: Cmd, two sub-classes: BufferCmd and StateCmd. Command "GotoLine" is derived from BufferCmd and "ChangeCmd" is derived from StateCmd. BufferCmds are intended to go to a Buffer class and StateCmds are intended ...
Sounds more like you want the aptly-named Command pattern. The key is to move the differing parameters of accept() into the constructor of each class derived from Cmd. For example, GotoLineCommand's constructor would take the line and the buffer objects as parameters to its constructor, and it would store a pointer or...
1,910,153
1,910,227
_popen: do not show the shell window (SW_HIDE)
When I execute the _popen command in c++ mfc it opens a shell window which I don't like, is it possible to make it hidden? for example when you try to execute commands with ShellExecute function it has the option to hide the shell window with SW_HIDE.
Note from documentation: If used in a Windows program, the _popen function returns an invalid file pointer that causes the program to stop responding indefinitely. _popen works properly in a console application. To create a Windows application that redirects input and output, see Creating a Child Process with Redirecte...
1,910,426
1,910,436
C++ Eclipse Galileo getting it to display line numbers - how?
EDIT: jldupont's suggestion (see below) did the trick Window -> Preferences -> General -> Editors -> Text Editors -> Show line numbers I just installed Eclipse Galileo (first time) and am programing in C++ and couldn't get the editor to display the line numbers... When i Googled it I got these directions: Go to Wi...
Window -> Preferences -> General -> Editors -> Text Editors -> Show line numbers
1,910,712
1,910,767
Dereference vector pointer to access element
If i have in C++ a pointer to a vector: vector<int>* vecPtr; And i'd like to access an element of the vector, then i can do this by dereferncing the vector: int a = (*vecPtr)[i]; but will this dereferencing actually create a copy of my vector on the stack? let's say the vector stores 10000 ints, will by dereferencing...
10000 ints will not be copied. Dereferencing is very cheap. To make it clear you can rewrite int a = (*vecPtr)[i]; as vector<int>& vecRef = *vecPtr; // vector is not copied here int a = vecRef[i]; In addition, if you are afraid that the whole data stored in vector will be located on the stack and you use vector<int>...
1,910,733
1,910,834
how can I map an int to a corresponding string in C/C++
I have 20 digits and I would like to associate them with strings. Is there a faster way besides using a switch case statement to achieve this. I need to convert an int to a corresponding string and the numbers aren't necessarily packed. Some code in Qt as well might be useful? Example: The following digits and str...
easier way to use map std::map<int, std::string> mymap; mymap[1] = "foo"; mymap[10] = "bar"; // ... int idx = 10; std::string lookup = mymap[idx];
1,910,832
1,910,992
Why aren't pointers initialized with NULL by default?
Can someone please explain why pointers aren't initialized to NULL? Example: void test(){ char *buf; if (!buf) // whatever } The program wouldn't step inside the if because buf is not null. I would like to know why, in what case do we need a variable with trash on, specially pointers addressing t...
We all realize that pointer (and other POD types) should be initialized. The question then becomes 'who should initialize them'. Well there are basically two methods: The compiler initializes them. The developer initializes them. Let us assume that the compiler initialized any variable not explicitly initialized by...
1,911,018
1,911,279
what does std::endl represent exactly on each platform?
Thinking about UNIX, Windows and Mac and an output stream (both binary and text), What does std::endl represent, i.e. <CR><LF>, <LF> or <CR>? Or is it always the same no matter what platform/compiler? The reason I'm asking is that I'm writing a TCP client that talks a protocol that expects each command to end in <CR><L...
The code: stream << std::endl; // Is equivalent to: stream << "\n" << std::flush; So the question is what is "\n" mapped too. On normal streams nothing happens. But for file streams (in text mode) then the "\n" gets mapped to the platfrom end of line sequence. Note: The read converts the platform end of line sequenc...
1,911,075
1,911,082
G++ not finding <iostream.h> in Ubuntu
I just installed Ubuntu and tried making the famed "Hello World" program to make sure that all the basics were working. For some reason though, g++ fails to compile my program with the error: "'cout' is not a member of 'std'". I've installed the build-essential package. Am I missing something else? #include <iostrea...
Use #include <iostream> - iostream.h is not standard and may differ from the standard behaviour. See e.g. the C++ FAQ lite entry on the matter.
1,911,112
1,939,455
Remote C++ Debugging with RSE
I'm stuck after step 3 in trying to setup remote cross-debugging with Eclipse/RSE: Installed RSE 3.1 on Eclipse 3.5 Setup a SSH connection profile to my remote device built binaries using a cross-compiler Now I can't find the Eclipse option to transfer the binaries to my device and debug using gdb. Under Debug Config...
I have not used the remote launch/debug facilities, but maybe these slides from EclipseCon 2008 can help you. The remote launch was AFAIK moved into CDT itself for Galileo. Here's the FAQ entry from RSE about remote debugging.
1,911,117
1,911,160
Is there a use for uninitialized pointers in C or C++?
In one of the comments in this question, it was brought out that initializing C++ pointers by default would break compatibility with C. That's fine, but why would something like this matter? I would think the only time it would actually matter is if I wanted an uninitialized pointer for some reason. But I can't think...
This is a very specialized optimized case for Video Games (basically an embedded system). We used to use them for Load-In-Place data behavior in our Video Games to speed up loading (and avoid fragmentation). Basically we would create console-side (Playstation) objects in a PC cooker. Then to reduce fragmentation over...
1,911,162
1,911,187
Can't compile std::list iterator with template
When I try to compile this I get this error: error: expected `;' before 'it' Why I can't declare this iterator? Where is the problem? #include <list> template <typename Z> class LBFuncBase: public LBBaseBlock<Z> { void Something() { std::list<LBBaseBlock< Z >* >::iterator it; } };
Try: typename std::list<LBBaseBlock< Z >* >::iterator it; Edit: See "Why do you sometimes need to write typename" for an explanation.
1,911,203
1,911,222
way to implement IPC
what is the preferred way to implement IPC over windows ? i know of several like : named pipe, shared memory, semaphors ? , maybe COM (though i'm not sure how)... i wanted to know what's considered the most robust,fast,least error prone and easy to maintain/understand.
Take a look at boost::interprocess. Shared memory is probably the fastest in general, but somewhat error-prone and limited to local processes. COM is fully versioned and automatically supports remote IPC, but obviously it's platform-specific. For a large-scale application you might want to consider something like Activ...
1,911,260
1,911,276
File-specific compilation options in Visual Studio 2008
If I had a project structured like this... a.cpp b.cpp c.cpp ...and I wanted to compile a.cpp and b.cpp with one set of compiler options, and c.cpp with another set, how would I do that?
I think the easiest way would be to separate them into different projects based on the compiler options you require, and then set up your dependencies appropriately to link them all into your final executable.
1,911,434
1,911,472
C++ fancy template code problem
I try to get a (for me) rather complex construct of templated code to work. what i have: a class shaderProperty of generic type class IShaderProperty { public: virtual ~IShaderProperty() {} }; struct IShaderMatth; //forward declaration template<typename ShadeType> struct ShaderMatth;//forward declaration template <ty...
Forward declaring ShaderMatth is not enough to use the code shaderMatth->properties. It must be defined before that line.
1,911,561
1,911,593
Resize a file (down)
I'm attempting to shrink a file in place. I'm replacing the contents of one file with those of another and when I'm done I want to make sure if the source file is smaller than the dest file, the dest file shrinks correctly. (Why: because the dest file is a backup and writing to the media is very expensive, so I only wr...
"net helpmsg 1224" -> The requested operation cannot be performed on a file with a user-mapped section open. And from MSDN for SetEndOfFile: If CreateFileMapping is called to create a file mapping object for hFile, UnmapViewOfFile must be called first to unmap all views and call CloseHandle to close the file ...
1,911,563
1,912,468
thread synchronization
let's say i have a blocking method , let's call in Block(). as i don't want my main thread to block i might create a worker thread, that instead will call Block. however, i have another condition. i want the call to block to return in 5 seconds top, otherwise, i want to let the main thread know the call to Block failed...
I would suggest using the boost::threads library for this. You can periodically check if the blocking thread is joinable (ie, still working) and then interrupt it after five seconds. You will then need to write the blocking function to handle that interruption and cleanly exit. #include <boost/thread/thread.hpp> void ...
1,911,572
1,911,629
Would VS2008 c++ compiler optimize the following if statement?
if (false == x) { ...} as opposed to: if (!x) { ... } and if (false == f1()) { ...} as opposed to: if (!f1()) { ... } I think the if(false == ... version is more readable. Do you agree, or have another trick you can propose? Will it be just as fast? Thanks. This is why I do not like !x: if (25 == a->function1(12345...
A good compiler should generate the same code for both code blocks. However, instead of worrying about false == f1() vs. !f1(), you should be way more worried about the short-circuit evaluation in this example: if (25 == a->function1(12345, 6789) && 45 == b->function1(12345, 6789) && !c->someOtherFunction(123))...
1,911,654
1,911,946
Use of a Union to avoid Dynamic Allocation Headaches
I'm curious if it's a good idea to use a union when accessing Win32 APIs that return variable length structures, to avoid manually managing the allocated memory. Consider the following: void displayServices(std::wostream& log, std::tr1::shared_ptr<void> manager, LPENUM_SERVICE_STATUS currentServiceToDisplay, DWORD numb...
One problem with your union approach is that the whole idea of using an union is rather forced and completely unnecessary. All you seem to want to do is the replace dynamic memory allocation with a local static buffer of some "large" size. Then just do it explicitly unsigned char buffer[8000]; QUERY_SERVICE_CONFIG ...
1,911,777
1,911,833
C++ problem with std::pair and forward declarations
Unfortunately I still got a problem with my templated code from here: C++ fancy template code problem on line 49 in the file 'utility': error C2440: 'Initializing': cannot convert from 'const int' to 'IntersectionData *' error C2439: 'std::pair<_Ty1,_Ty2>::second': member could not be initialized how could i figure ...
Try explicitly casting the NULL to IntersectionData * in your call to make_pair(). if(traceCols){ traceCols->push_back(make_pair(MaterialMatth(), (IntersectionData *)NULL)); }
1,911,822
1,911,883
Using istream_iterator and reading from standard input or file
I'm writing in Microsoft Visual C++ and I'd like my program to either read from standard input or a file using the istream_iterator. Googling the internets hasn't shown how simple I think it must be. So for example, I can write this pretty easily and read from standard input: #include <iostream> #include <string> #incl...
You can assign to the iterator after constructing it: int main(int argc, char** argv) { ifstream file; istream_iterator<string> my_it; if(argc == 2) { file.open(argv[1]); my_it = istream_iterator<string>(file); } else { my_it = istream_iterator<string>(cin); } }
1,911,950
1,911,960
How to customize windows default right click pop-up menu
I have two questions. My first one is, that how can i "put" something into the default windows right click pop-up menu? I mean, if i click with the right mouse button on an .exe, then the default things appers(like cut, copy, send to, run as...), but how can i put there one extra line, like "MyApp", which will start my...
1) Sounds like you're looking to simply alter or add to the context menu that is provided by Windows Explorer. It's really just a matter of registry settings. See here for a good example. 2) If you follow the zip example of the link above you'll see that the path to the target file is passed to the zip application. You...
1,912,047
1,912,082
Difference between a program that crashes and program that hangs
What is the difference (or causes) between a program that crashes and a program that hangs (becomes unresponsive) in C++? For sure, accessing invalid memory causes a program to crash. Deadlock in threads may cause a program to hang. What are the other causes? Does exhausting all memory causes a program to hang? or cras...
Crashing is normally caused by an illegal instruction, e.g. accessing invalid memory, dividing by zero, etc. Usually this manifests itself as a well-known exception which is handled by the operating system. Hanging can be broken up into 2 fairly high level categories: Deadlock, usually caused by 2 threads competing f...
1,912,056
1,912,120
VisualStudio C++ Linker problem with template classes
I still can't get it to work.. After I had to separate implementation from definition of one of my generic classes because of a forward declaration, i now get Linker errors when trying to build. IShader.h: template <typename ShadeType> class IShader { public: template <typename T> bool getProperty(const std::string& ...
Your only providing a linkable object for the class in the translation unit, but the member function is templated on another parameter and has also to be explicitly specified. I don't know if there is a more elegant way, but one compilable version would be: template bool IShader<bool>::getProperty<bool> ...
1,912,106
1,912,116
Nominal case first vs. Positive boolean expressions
As the topic states, sometimes these issues conflict. For example... In this case, the nominal case is first, but the expression is negative. if ( !foo.IsDead() ) { DoThis(); } else { DoThat(); } In this case, the expression is positive, but the nominal case is last. if ( foo.IsDead() ) { DoThat(); } else { Do...
I prefer option two as it's slightly clearer / easier to read. But you're heading for religious war territory I suspect. In terms of flipping the name of the function, I'd only change if isAlive() is the most likely outcome. That is, I think the code is clearer if the most likely outcome is your boolean expression equa...