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,530,771
3,530,807
Passing variable arguments to another function that accepts a variable argument list
So I have 2 functions that both have similar arguments void example(int a, int b, ...); void exampleB(int b, ...); Now example calls exampleB, but how can I pass along the variables in the variable argument list without modifying exampleB (as this is already used elsewhere too).
You can't do it directly; you have to create a function that takes a va_list: #include <stdarg.h> static void exampleV(int b, va_list args); void exampleA(int a, int b, ...) // Renamed for consistency { va_list args; do_something(a); // Use argument a somehow va_start(args, b); examp...
3,530,848
3,530,908
Reading File Remotely in C++
Is there way that I can read the file from remote server using fopen or any other api. Thanks Avinash
Try libcurl. It is a rich library that can work many types of servers.
3,530,889
3,538,521
Unit Testing in Qt with Highly Dependent Functions
I'm new to unit testing. I want to code unit tests in Qt, but my functions(login, request etc...) heavily depend on other resources such as a server. How can I supply a block box in this situation? Do you know any open source project which I can examine unit test classes for similar situations?
There's a linker trick that you can use. You know which methods and classes your code uses. Get a header files and declarations of those classes and make a small implementation of each that returns values you would like. Then compile those and link in right order. This will then use your own implementation of those met...
3,531,010
3,535,843
Syslog custom priorities
Is there a way one can use custom priorities in syslog daemon or rsyslog daemon? i.e. i am unable to locate a configuration change which achives it.. the other thing i can do is perhaps play with it's source. Cheers!
Is there a way one can use custom priorities in syslog daemon or rsyslog daemon? Syslog output is something admins look into. And the syslog is managed by the user-space daemon. What that means, if you would manage somehow to cram your own custom priorities into the syslog() call, the receiving side, likewise the use...
3,531,060
3,531,105
How to initialize a static const member in C++?
Is it possible to initialize a static const value outside of the constructor? Can it be initialized at the same place where member declarations are found? class A { private: static const int a = 4; /*...*/ };
YES you can but only for int types. If you want your static member to be any other type, you'll have to define it somewhere in a cpp file. class A{ private: static const int a = 4; // valid static const std::string t ; // can't be initialized here ... ... }; // in a cpp file where the static variable will exist ...
3,531,155
3,531,209
Odd Parameter I dont understand in gridlabd threadpool.c
I'm working on the open project gridlabd hosted at sourceforge. I was trying to call the create_thread function: static __inline int create_thread(void * (*proc)(void *), void *arg) I just don't understand for the life of me what in the world void * (*proc)(void *) means.
void * (*proc)(void *) is a pointer to a function which returns void* and accepts void* as an argument.
3,531,296
3,531,395
Have I found a bug in Clang?
I tried to compile the code below with Clang class Prasoon{ static const int dummy = 0; }; int const Prasoon::dummy = 0; int main(){} The above code did not give any error when compiled with Clang. prasoon@prasoon-desktop ~ $ clang++ --version clang version 2.8 (trunk 107611) Target: i386-pc-linux-gnu Thread mod...
Yes, you have found a bug. The rule is expressed in the standard: 9.4.2-3: If a static data member is of const literal type, its declaration in the class definition can specify a brace-or- equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. A sta...
3,531,368
3,532,989
Open source virtual machine
I'm looking for an open source virtual machine that's: fast and as lightweight as possible supports a minimal set of bytecode (like LLVM IR) easily embedable from a C++ application Cross platform (Linux, Windows and OS X) x86 support
Why filter out LLVM ? It's a set of C libraries I guess it's not as easy to embed than Lua, but LLVM is so great that it would probably overcome the hassle of integrating it. See this SO question, does it help ?
3,531,532
3,531,589
A Clean Syntax for Changing Static Member Initialisation Behaviour
I recently read that Java now sports initialisation blocks like the following: class C { public C() { /* Instance Construction */ } static { /* Static Initialisation */ } { /* Instance Initialisation */ } } I was particularly interested in the static block. It got me thinking about the static initialisat...
Seems not worth the effort to me for the most part. You're really not improving readability, the unusual construct is going to confuse future programmers maintaining your code, and the addition of the new class increases complexity, thereby exposing you to the potential for more bugs. I can see how you rarely might ne...
3,531,700
3,531,839
How can I find the IP address of a mapped network drive in C++?
I have a list of possible paths to use for a default input data directory (X:\Data; Y:\Data; Z:\Data). All of the possible paths are mapped network drives. I can check this using GetDriveType(pathStr) == DRIVE_REMOTE. To determine the best one, I have narrowed down the list by selecting only paths that exist. Sometimes...
WNetGetUniversalName is one possibility.
3,531,811
3,531,872
Is there a C++ way to write file with any type of data?
Like this function in C: size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream ); I've looked in C++ file stream and found this one: ostream& write ( const char* s , streamsize n ); this one only accepts char* instead of void* but does it really matter if I use a C-style fwrite function in c++?
Streams are probably what you're looking for unless I misunderstand your question. There are many flavors that handle different jobs, like outputting to a file: #include <cstdlib> #include <fstream> #include <string> using namespace std; int main() { ofstream f("c:\\out.txt"); const char foo[] = "foo"; ...
3,531,956
3,532,029
Catch derived exception when returning reference of base class type?
I'm writing a windows application in C++ and encountered the following problem when working with exceptions. I have a base exception class from which all other exceptions derive from. In the base class I have a method for the error message of any exception. That method then returns the exception (through '*this'). Now,...
It would be much simpler to separate the extend() call and the re-throwing of the exception: catch ( DerivedException& exc ) { exc.extend( "message2" ); throw; } This way extend() doesn't have to return anything and always the right exceptions are thrown/caught.
3,532,031
3,532,061
What's wrong with the c++ code below?
HRESULT SaveGraphFile(IGraphBuilder *pGraph, WCHAR *wszPath) { const WCHAR wszStreamName[] = L"ActiveMovieGraph"; HRESULT hr; IStorage *pStorage = NULL; // First, create a document file that will hold the GRF file hr = StgCreateDocfile( wszPath, STGM_CREATE │ STGM_TRANSACTED │ S...
Your pipes aren't really pipes. The character between the STGM constants should be | (ASCII 124), but what you have is ¦ (ASCII 166, which isn't strictly speaking ASCII at all). It looks like you're the victim of a faulty copy-paste.
3,532,058
3,532,413
Thread-ring benchmark
Today I was doing the thread ring exercise from the Programming Erlang book and googled for other solutions to compare. I found that the language shootout has exactly the same problem as a benchmark. I had the impression that this is an area where Erlang should be fast, but turns out that C and C++ are again on top. My...
Ultimately, message-passing on modern machines is implemented using some form of shared memory to pass the messages (along with either locks or atomic instructions). So all the C and C++ implementations are really doing is inlining the implementation of message-passing straight into their code. A similar benchmark th...
3,532,309
3,532,320
Multiple preprocessor directives on one line in C++
A hypothetical question: Is it possible to have a C++ program, which includes preprocessor directives, entirely on one line? Such a line would look like this: #define foo #ifdef foo #define bar #endif What are the semantics of such a line? Further, are there any combinations of directives which are impossible to const...
A preprocessing directive must be terminated by a newline, so this is actually a single preprocessing directive that defines an object-like macro, named foo, that expands to the following token sequence: # ifdef foo # define bar # endif Any later use of the name foo in the source (until it is #undefed) will expand to ...
3,532,435
3,532,464
How to change indentation etc of a piece of code?
Possible Duplicates: Code polisher / reformater for C, C++ or Fortran Best C++ Code Formatter/Beautifier I am working as part of a team on a C++ project. Part of the code is a highly modified version of a large-ish external library, which doesn't conform to our coding conventions. The library uses this style: void m...
There are lots of programs which do this for you. Like: Astyle (recommended) Indent Uncrustify etc. These are called "beautifers" or "pretty printers" Some editors can also fix this stuff on run time, without modifying the actual source files. (I believe Eclipse/emacs can do this) Still, I can't help but ask why you ...
3,532,493
3,532,800
Contents of string change when exiting loop
I have a simple function, that checks if the strings given match a certain condition, then generate a 3rd string based on the 2 ones received as arguments. The 3rd string is fine but when I return it it suddenly turn into "\n". string sReturn = ""; if (sText.size() != sPassword.size()) { //Checks to see if the tex...
You don't have to initialize string with empty character array like: std::string sReturn = ""; Default constructor meant to do it for you and is much more efficient. Correct code: std::string sReturn; Assigning an empty string to sReturn on each iteration in your loop is incorrect. Not to mention that to clear a str...
3,532,533
3,533,034
Program for Tv Tuner
I want to develop my own tv tuner program mainly for live stream. Looked at OpenCV but I still prefer to have something that I own, mainly due to customization. Search over the web and cant seem to find a good site on how to start. The only clues that I have are things like DirectX, DirectShow. From what it seems, i be...
You are right. Both the tuners and webcam allow you to read a strream. The tuner also allows you the change the channel etc. A good point to see how it all works is MediaPortal an Open Source .net HTPC applicaiiont http://www.team-mediaportal.com/
3,532,848
3,533,351
stl predicate with different types
I have a vector of ordered container classes where I need to know the index of the container that has a given element so, I would like to do the following, but this obviously doesn't work. I could create a dummy Container to house the date to find, but I was wondering if there was a nicer way. struct FooAccDateComp {...
upper_bound needs to be able to evaluate expressions like Comp(date,container), but you've only provided Comp(container,date). You'll need to provide both: struct FooAccDateComp { bool operator()(const Container& c, const MyDate& d) const { return c.myDate < d; } bool operator()(const MyDate& d, con...
3,533,044
3,533,123
Matrix compression methods
In an application I've been working on, I have to send a 256 x 256 matrix over a socket. I'm developing a visualization client for a offshore system simulator that runs on a cluster, and this matrix is a heightmap representing the current state of the oceanic surface. This is an realtime application, so speed is a must...
If you are far enough offshore and/or in calm sea states, breaking waves are not likely to be a big problem. If this is the case, then the surface will be nicely continuous, and will likely look a lot like the superposition of multiple sine/cosine waves in X and Y. 2-D FFTs of the surface might give you some insight. ...
3,533,117
3,551,979
Best way to learn about Direct X
I want to begin looking at Direct X, but don't just want to try and throw myself into it. What are some good resources to get ones feet wet?
I highly recommend Toymaker's tutorials. Helped me greatly when I was first starting out with DX and was just as good as a reference later on. The other thing to do would to set up some small projects that use DX that increase in difficulty as you go. If you'd like a starter list (from easy to hard): Compiling using ...
3,533,136
3,533,189
c++ is_str_empty predicate
std::vector<std::wstring> lines; typedef std::vector<std::wstring>::iterator iterator_t; iterator_t eventLine = std::find_if(lines.begin(), lines.end(), !is_str_empty()); how do I define is_str_empty? i don't believe boost supplies it.
Use mem_fun / mem_fun_ref: iterator_t eventLine = std::find_if(lines.begin(), lines.end(), std::mem_fun_ref(&std::wstring::empty)); If you want when the string is NOT empty, then: iterator_t eventLine = std::find_if(lines.begin(), lines.end(), std::not1(std::mem_fun_ref(&std::wstring::empty)));
3,533,251
3,533,316
Why does the standard library have find and find_if?
Couldn't find_if just be an overload of find? That's how std::binary_search and friends do it...
A predicate is a valid thing to find, so you could arrive at ambiguities. Consider find_if is renamed find, then you have: template <typename InputIterator, typename T> InputIterator find(InputIterator first, InputIterator last, const T& value); template <typename InputIterator, typename Predicate> InputIterator find...
3,533,429
3,550,960
C++/Windows: How to report an out-of-memory exception (bad_alloc)?
I'm currently working on an exception-based error reporting system for Windows MSVC++ (9.0) apps (i.e. exception structures & types / inheritance, call stack, error reporting & logging and so on). My question now is: how to correctly report & log an out-of-memory error? When this error occurs, e.g. as an bad_alloc th...
pre-allocate the buffer(s) you need link statically and use _beginthreadex instead of CreateThread (otherwise, CRT functions may fail) -- OR -- implement the string concat / i2a yourself Use MessageBox (MB_SYSTEMMODAL | MB_OK) MSDN mentions this for reporting OOM conditions (and some MS blogger described this behavior...
3,533,494
4,800,799
QT Embedded: How to generate an event to ESC (Escape), F1 and such keys
I'm working on an embedded software in QT that uses LIRC to handle RC (Remote Control) key presses. I managed to map all the RC keys so directFB is getting keypresses like these: 00000000000011b7 00 MENU 00000000000011a7 00 EXIT 0000000000001193 00 RED I've created a QT class that uses sockets to grab LIRC keys and ge...
The use of the current focused widget in the postEvent solves the problem. I was having some issues in the LIRC configuration that was generating some "not that right" key codes. If anyone need help on that, I'll be glad to help. Thanks
3,533,503
3,533,527
Using Singleton in different classes
How do you create a instance of a singleton that can be used in other classes? For Example: //Singleton_Class.h #ifndef Singleton_Class #define Singleton_Class class Singleton { private: static Singleton _instance; Singleton() {} ~Singleton() {} Singleton(const Singleton &); Singleton & operator=(const S...
You need to define the instance variable in one of your source (.cpp) files, not in the header file. If the instance variable is defined in the header file, then when that header file is included in multiple source files, it ends up getting defined multiple times (which is what the error says).
3,533,589
3,533,692
Can virtual functions have default parameters?
If I declare a base class (or interface class) and specify a default value for one or more of its parameters, do the derived classes have to specify the same defaults and if not, which defaults will manifest in the derived classes? Addendum: I'm also interested in how this may be handled across different compilers and ...
Virtuals may have defaults. The defaults in the base class are not inherited by derived classes. Which default is used -- ie, the base class' or a derived class' -- is determined by the static type used to make the call to the function. If you call through a base class object, pointer or reference, the default deno...
3,533,655
3,533,691
Unable to access const static members in class
I have read this document Initializing static array of strings (C++)? and tried to test in my compiler if everything would be fine here is copy of code #include <iostream> #include <string> using namespace std; class MyClass { public: const static char* MyClass::enumText[]; }; const char* MyClass::enumText...
#include <iostream> #include <string> using namespace std; class MyClass { public: const static char* enumText[]; }; const char* MyClass::enumText[] = {"a","b","c","d"}; int main() { std::cout<<MyClass::enumText[0]<<endl; return 0; }
3,533,670
3,533,823
Dynamic cast and multiple inheritance
The dynamic_cast operator is returning zero (0) when I apply to a pointer that points to an instance of a multiply inherited object. I don't understand why. The hierarchy: class Field_Interface { public: virtual const std::string get_field_name(void) const = 0; // Just to make the class abstract. }; class Reco...
Note: For simplicity, I am using fundamental pointers in this example. Actual code uses boost::shared_ptr. And that's your problem right there: You cannot dynamic_cast a shared_ptr<A> to a shared_ptr<B> since those two types are not actually related to each other, even if A and B are. Luckily in the specific case in ...
3,533,811
3,533,901
String allocation trouble with 'new'
When in doubt, turn to Stackoverflow... I'm having a problem with string allocation. My goal is to store n length of a passed quoted string. I check m_p for null because I think in debug mode MS likes to set the address to 0xcccccccc instead of 0x00000000. I passed 1 into length. But when I allocate it using new, I'm ...
If you want to store n characters of a passed quoted string, you need to take into account that strncpy doesn't append null character if the length of the source string is greater than or equal to the length argument. So you have to take care of it: strncpy(m_p, str, length); // or strncpy(m_p, str, m_size-1); m_p[leng...
3,533,880
3,535,213
Elegant non-const reference to a QVariantMap node?
Basically I need to generate a nested QVariantMap. (Think JSON): { "foo" : 1, "bar" : { "node" : 0 } } I do this in Qt this way: QVariantMap r, r_bar; r["foo"] = QVariant(1); r_bar["node"] = QVariant(0); r["bar"] = r_bar; Which is very inconvenient for large nested structures. Is there an elegant way of doing this,...
You could use only one map like this: r["foo"] = QVariant(1); r["bar/node"] = QVariant(0); The only problem with this approach is that you lose the ability to iterate sub maps. There is no easy way to find out the subnodes of the "bar" node.
3,533,968
3,534,067
How can I compile binary?
I'm a .net developer by heart and usually write web applications. However I've been given the binary of a small project and I need to compile it (I think). It is only two files: mfile.h and mfile.cpp. From looking at the code the .h file is a header file that contains constants and the cpp file is the actual codefil...
Wish you were running VS 6, in which case you'd just load the .cpp file, click "build", click "okay" when it says it's going to create a project for you, and off you go. With VS 2008, you want to: Move these files into a directory by themselves Select File -> New -> Project from Existing code... Accept "Visual C++ Pro...
3,534,070
3,534,108
What does "#define STR(a) #a" do?
I'm reading the phoneME's source code. It's a FOSS JavaME implementation. It's written in C++, and I stumbled upon this: // Makes a string of the argument (which is not macro-expanded) #define STR(a) #a I know C and C++, but I never read something like this. What does the # in #a do? Also, in the same file, there's: /...
In the first definition, #a means to print the macro argument as a string. This will turn, e.g. STR(foo) into "foo", but it won't do macro-expansion on its arguments. The second definition doesn't add anything to the first, but by passing its argument to another macro, it forces full macro expansion of its argument. So...
3,534,336
3,534,789
Way to set up class template with explicit instantiations
After asking this question and reading up a lot on templates, I am wondering whether the following setup for a class template makes sense. I have a class template called ResourceManager that will only be loading a few specific resources like ResourceManager<sf::Image>, ResourceManager<sf::Music>, etc. Obviously I defin...
Yes. This is perfectly legittamate. You may want to hide the fact that it is templatised behind a typedef (like std::basic_string does) then put a comment in the header not to use the template explicitly. ResourceManager.h template<typename T> class ResourceManager { T& getType(); }; // Do not use ResourceManager<...
3,534,442
3,534,530
What does "#define FOO(template)" do?
I've found some weird C++ preprocessor clauses, like: #define COMPILER_FLOAT_ENTRIES_DO(template) and #define COMPILER_FLOAT_ENTRIES_DO(template) \ template(jvm_fadd) \ template(jvm_fsub) \ template(jvm_f2d) What does passing "template" reserved word to a #define, and calling template(something) mean? I co...
#define COMPILER_FLOAT_ENTRIES_DO(template) so COMPILER_FLOAT_ENTRIES_DO(x) gets replaced with with ''. In other words, it removes that macro from the code. #define COMPILER_FLOAT_ENTRIES_DO(template) \ template(jvm_fadd) \ template(jvm_fsub) \ template(jvm_f2d) so COMPILER_FLOAT_ENTRIES_DO(x) gets replaced...
3,534,585
3,534,651
SAXParser does not understand encoding 'EUC-JP'
sax parser throws exception when I parse following file <?xml version='1.0' encoding='EUC-JP'?> <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>·Ñ³meeting</body> </note> If I remove first line and line with Japanese characters then parser works. <note> <to>George</to> <from>Joh...
Hard to say without knowing for sure what SAX parser you're using. Does this help? http://www.lllf.uam.es/~antonio/documentos/xerces/faq-parse.html#faq-20
3,534,812
3,535,871
How does the template parameter of std::function work? (implementation)
In Bjarne Stroustrup's home page (C++11 FAQ): struct X { int foo(int); }; std::function<int(X*, int)> f; f = &X::foo; //pointer to member X x; int v = f(&x, 5); //call X::foo() for x with 5 How does it work? How does std::function call a foo member function? The template parameter is int(X*, int), is &X::foo convert...
After getting help from other answers and comments, and reading GCC source code and C++11 standard, I found that it is possible to parse a function type (its return type and its argument types) by using partial template specialization and function overloading. The following is a simple (and incomplete) example to impl...
3,534,934
3,535,186
iOS — Determining whether Accelerate.framework is available at runtime
Is there any way to determine whether the Accelerate.framework is available at runtime from straight C or C++ files? The examples I've found for conditional coding all seem to require Objective-C introspection (e.g., respondsToSelector) and/or Objective-C apis (e.g., UIDevice's systemVersion member)
The usual trick for this is that you weak link against the framework and then check a function pointer exported by that framework for the actual availability. If the framework failed to link because it is not available then the function will be NULL. So for Accelerate.framework you would do something like this: #includ...
3,535,024
3,535,215
container of mixed types in C++ (similar to nsdictionary)
What I would like to do (in C++) is create a 'Parameter' data type which has a value, min, and max. I would then like to create a container for these types. E.g. I have the following code: template <typename T> class ParamT { public: ParamT() { } ParamT(T _value):value(_value) { ...
It's a tough concept to implement in C++, as you're seeing. I'm always a proponent of using the Boost library, which has already solved it for you. You can typedef the complex boost variant template class to something more usable in your specific domain, so typedef boost::variant< int, float, bool > ParamT; class P...
3,535,282
3,535,346
What's so special about file descriptor 3 on linux?
I'm working on a server application that's going to work on Linux and Mac OS X. It goes like this: start main application fork of the controller process call lock_down() in the controller process terminate main application the controller process then forks again, creating a worker process eventually the controller kee...
syslog(3) may keep a file descriptor to syslogd's socket open; closing this under its feet is likely to cause problems. A closelog(3) call may help.
3,535,287
3,535,360
Does order matter in specialization of a function in class template
Consider something like... template<typename T> class Vector { ... bool operator==( const Vector<float> &rhs ) { // compare and return } bool operator==( const Vector<T> &rhs ) { // compare and return } ... }; Notice how the specialization is above the non specialized version. If I were to put th...
As written, I believe you have an error. You aren't specializing operator==, you're overloading it. You aren't allowed to overload on a template parameter like that. If your method were a free function, then you could specialize it. For instance template <typename T> void Foo(Vector<T> x) { std::cout << "x" << st...
3,535,327
3,535,347
Name mangling problems when using GNU linker to link to VC++ compiled library
In asking this question, I'm looking for either better understanding of the situation or preferably a solution. I'm created C++ code and I would like to be able to use the Eclipse CDT IDE rather than Visual Studios, (my workplace is more Eclipse friendly). This implies that, practically speaking, I must use the GNU to...
Unless you place most of the code in HyDE.lib with extern "C" blocks, then your best bet is to recompile it with G++. Even if you do place it in extern "C" blocks, I would still reccomend compiling it with G++ as it usually (but not always) has better support for standards than MSVC.
3,535,693
3,535,709
How to specialize member functions based on class template argument
What the question says. In addition, is it possible to do this inline? Here is a small example just to give an idea... template<typename T> class Foo { public: Foo() :z(0.0) {} void do( const Foo<T> &f ) { z = f.z; } // specialize 'do' for Foo<int>, possible inline? private: T z; };
You can sort of get this behavior by making the member function a member function template and using SFINAE (substitution failure is not an error). For example: template <typename U> typename std::enable_if<!std::is_integral<U>::value && std::is_same<T, U>::value, void>::type f(const Foo<U>& x...
3,535,714
3,538,787
I have .H file, how to open its public methods to .Net library?
I have such .H file (from here) /* FFmpeg simple Encoder */ #ifndef __VIDEO_ENCODER_H__ #define __VIDEO_ENCODER_H__ #include "ffmpegInclude.h" #include <Windows.h> #include <string> class VideoEncoder { private: // output file name std::string outputFilename; // output format. AVOutputFormat *pOu...
I believe what you're looking for is C++/CLI ( http://en.wikipedia.org/wiki/C++/CLI and http://msdn.microsoft.com/en-us/library/xey702bw.aspx ). While I'm no expert myself, I think you might be able to get away with changing the class declaration to namespace MyNamespace { public ref class VideoEncoder { ...
3,535,822
3,535,831
What is the difference between infinite while loops and for loops?
I see the different conventions used in many books I had read, where you would create infinite loops with either loop structure such as: while() foo(); for(;;) foo(); But really, what are the differences I should know about? which one is better?
They're semantically the equivalent. (x;y;z) { foo; } is equivalent to x; while (y) { foo; z; }. They're not exactly equivalent in further versions of the standard, in the example of for (int x = 0; y; z), the scope of x is the for block and is out of scope after the loop ends, whereas with int x; while (y) x it's stil...
3,535,824
3,535,904
C++: Is "my text" a std::string, a *char or a c-string?
I have just done what appears to be a common newbie mistake: First we read one of many tutorials that goes like this: #include <fstream> int main() { using namespace std; ifstream inf("file.txt"); // (...) } Secondly, we try to use something similar in our code, which goes something like this:...
So, is "string" a std::string, a c-string or a *char, or does it depend on the context? Neither C nor C++ have a built-in string data type, so any double-quoted strings in your code are essentially const char * (or const char [] to be exact). "C string" usually refers to this, specifically a character array with a ...
3,536,029
3,536,297
Disabling C++0x features in VC 2010?
Does C++0x mode in VC++ 2010 has an off switch? I am working on a project that supposed to compile on non 0x compilers, and therefore I want to compile against the current standard. (Even if non of the new features are being used directly, there are still subtleties that makes C++0x more premissive). The closest switch...
No, language extensions are typically non-standard vendor specific additions. C++0X features: There is no direct way to switch off these features. One workaround is to not use them. However, note that there will still be marked difference in performance across versions of VC runtime. VC10 implements move semantics and...
3,536,060
3,537,695
Resources on how to create a NSIS plugin
Is there documentation on how to write a NSIS plugin? Where can I find it?
It is a simple Dynamic-Link Library (DLL) with DLL exports. The only "documentation" is the example plugin and its header file(s). References NSIS Nightly Repository on SourceForge MSDN Dynamic-Link Libraries Reference MSDN Exporting from a DLL
3,536,194
3,536,267
C++ inline assembly function not working properly
I get a different return value each time, so I'm doing something wrong. If I replace the add with a basic inc, it returns correctly. Here is the code. #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <iostream> using namespace std; int Add ( int _Number1, int _Number2 ); int main ( int _ArgumentCount, char...
__declspec (naked) means the function is created without any prolog or epilog code -- so if you want to access formal parameters, you need to write prolog code of your own to give you access to them. Your xor is also accomplish nothing, since you immediately overwrite eax with another value. Also note that any identifi...
3,536,370
3,536,469
Should clients have access to debug symbols for bug reporting purposes?
When shipping software to a client, should debug symbols (.PDBs) be bundled with it? If the client finds a bug or vulnerability in the software, a full stack trace (and a memory dump if possible) would be very helpful for the vendor in reproducing it. What are the pros/cons of giving clients debug symbols?
Clients don't need debug symbols to send crash dumps to vendors. Automated systems like Windows Error Reporting make it possible for clients to report crash dumps to vendors without even having to know what a crash dump is. And clients can always send you a kernel crash dump or a user mode minidump manually. You do nee...
3,536,372
3,536,513
Defining static members in C++
I am trying to define a public static variable like this : public : static int j=0; //or any other value too I am getting a compilation error on this very line : ISO C++ forbids in-class initialization of non-const static member `j'. Why is it not allowed in C++ ? Why are const members allowed to be i...
(1.) Why is it not allowed in C++ ? From Bjarne Stroustrup's C++ Style and Technique FAQ: A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule w...
3,536,377
3,536,915
Failure when retrieving string from the end of a file
I have a simple application which takes a text and password, generates a text writes it in a file then tries to retrieve it and decrypt it. Before the encryption the 'pad' is generated which is a string generated from the password with the length of the text. The problem comes in when I try to retrieve the text, becaus...
I made the following 2 edits: ofstream mann(file.c_str(), ios::app|ios::binary); while (getline(frau, foobar)) { decrypted += foobar; decrypted += "\n"; } When I opened the file for reading I also added ios::binary and when I was adding to the decrypted string I added the "\n" which was being removed by the 'ge...
3,536,434
3,536,450
would the memory pointed by auto_ptr leak in case of never ending application?
I need to run an application in an embedded system continuously. While implementing this application, i need to allocate lot of memory from Heap. If i use auto_ptr for those, when will that be freed ? As per my understanding, memory pointed by auto pointers would be freed upon exiting/terminating the application. It wo...
Memory pointed by auto_ptr is released when auto_ptr instance is destroyed. For local auto_ptr instance, defined in a function, this happens when function exits. If auto_ptr instance is class member, it is destroyed when container class instance is destroyed. Global auto_ptr instance is destroyed when the program exits...
3,536,459
3,555,114
Erlang - C and Erlang
There are certain common library functions in erlang that are much slower than their c equivalent. Is it possible to have c code do the binary parsing and number crunching, and have erlang spawn processes to run the c code?
Of course C would be faster, in the extreme case, after optimizations. If by faster you mean faster to run. Erlang would be by far, faster to write. Depending on the speed requirements you have Erlang is probably "fast enough", and it will save you days of searching for bugs in C. C code will only be faster after opt...
3,536,600
3,539,509
Do you debug C++ code in Vim? How?
The question is to all you people, who use Vim to develop C++ applications. There was a period in my life, which can be described as 'I hate Vim!!!'..'Vim is nice!' However, having grown up mostly on Microsoft development IDEs, I've got used to those F5-F11 shortcuts when debugging code, watch window, call stack and th...
In contrast with the other answers, there are at least three options that do just what you require: clewn, pyclewn and vimgdb. All three projects are related. vimgdb is a patch against Vim and requires Vim to be recompiled. clewn is a standalone program that communicates with Vim through the Netbeans socket interface. ...
3,536,627
30,169,535
Is MFC only available with Visual Studio, and not Visual C++ Express?
Is MFC only available with Visual Studio, or is it also possible to use it with Visual C++ Express?
Now there exists a solution to this problem, for all the people want to use a free version. Visual Studio Community 2013 comes with the MFC (Microsoft Foundation Classes) included. Download link: https://www.visualstudio.com/products/visual-studio-community-vs Edit: Visual Studio Community 2015 is now also released.
3,536,634
3,538,276
Getting File Associations using Windows API
I'm working on a console based file browser for Windows in C++ and am having difficulties getting together a context menu that lists actions associated with a file and calls commands on them. The biggest issue right now is getting the actions tied to the file types. I know of the process to open and tweak the registry ...
Consider using IContextMenu. IContextMenu is how Windows Explorer accesses the context menu for files and items. This article by Raymond Chen has sample code for how to access IContextMenu for a given file path and use it to fill an HMENU with the set of available commands. It's the first of a series of articles that...
3,536,698
3,536,931
Multiple return statements vs Multiple goto statements : which one would be preferable?
I read that both multiple returns and multiple goto statements are bad programming practice. I have a function which can detect some 8 types of errors. In case of error, should i return error code or should i use goto statment to go to end of function and return from there. Whenever memory freeing is required before r...
If you look at how goto is used in C code, such as the Linux kernel, it is used to do resource cleanup prior to returning from a function. Multiple labels are used to deallocate resources in the reverse order of acquisition, with earlier parts of the code jumping to later goto labels. In C++, instead you should use RAI...
3,536,715
3,556,262
Mouse disappears on code break
I am using Ogre3D and sometimes when there is a break (or an exception) and it breaks into visual studio, my mouse cursor fails to appear. This is very annoying as most of the time I have to restart the game because I cannot watch any variables when it breaks. Everything else works, just the mouse disappears and stays ...
I have found the solution (not by myself, but with help :) A direct link to the discussion of the issue: Ogre3D Forum In case that link ever goes down, here is the quick answer which I hope will help somebody in the future with the same problem. OIS locks the mouse exclusively for the app and if you want it to appea...
3,536,924
3,536,939
Calling a main-like function using argv[]
I have some code here to call minizip(), a boilerplate dirty renamed main() of the minizip program, but when I compile, I get *undefined reference to `minizip(int, char**)*. Here's the code. int minizip(int argc, char* argv[]); void zipFiles(void) { char arg0[] = "BBG"; char arg1[] = "-0"; char arg2[] = "out.zip"; ...
Is all of that code in the same file? If not, and if the caller is C++ code and minizip is C code, the caller might need the minizip declaration within an extern "C" block to indicate that it will be calling a C function and therefore will need C linkage. (Also, don't retype error messages. Copy and paste them so tha...
3,537,030
3,537,117
getline returning empty string
I'm having problems with the getline instruction from fstream. this is a snippet from my code: boolean_1=true; while(true) { if(boolean_1) { //some stuff } else { save_file.open("save.txt", fstream::in); //some stuff save_file.close(); } mission_file.open(filename,...
It's impossible to see from the code extracts that you've posted but it sounds like you are re-using the same std::fstream object for each cycle. It would be clearer to create a new local object inside the loop at the point at which you need to re-open the file. If you must re-use the same fstream object to open a new ...
3,537,072
3,537,175
How to write a single function for creating dissimilar objects for dissimilar classes based on classname parameter?
I need to write a function which could create any type object. It receives class name as parameter. If classes are similar, we can derive all those classes from a single base class and let function return Base *. User of the function could use runtime polymorphism to use the returned object. In this case, function look...
Boost already has 2 possible solutions to your problem: Boost.Variant and Boost.Any. But preferably you should avoid such a design in the first place if you can. If one function returns unrelated objects and you can't refactor to give the types a common interface, you should probably split it into multiple functions.
3,537,105
3,537,132
Why do I need special libraries (binaries) built for each Visual C++ version?
There are a lot of C++ libraries (most?) that come with special binaries built for each Visual C++ version (2003, 2005, 2008, 2010). What's the problem about linking a C++ library built for Visual C++ 2008 with Visual C++ 2010?
Each Visual Studio version carries an updated (and different) version of the C and/or C++ runtime. This msdn page (under: "What problems exist...") explains quite nicely what the issue is. What is described there for msvcrt.dll <-> msvcrt10.dll is valid for every msvcrtXX.dll there is. It should not present any notewor...
3,537,110
3,537,220
Problem getting input from user
Here's the code : cout << "Please enter the file path: "; string sPath; getline(cin, sPath); cout << "Please enter the password: "; string sPassword; getline(cin, sPassword); Problem is, when I run it it displays "Please enter the file path: " then it displays "Please enter the password: " and then waits for the passw...
It looks like the rest of the line that was input for GetCH still remains in the buffer at the time that you call getline, i.e. at least a \n and this is what you are reading in the first getline call. The program doesn't block waiting for user input because the getline request can be satisfied by the partial line stil...
3,537,145
3,537,190
Doxygen C++ conventions
I'm at the beginning of a C++ project and I've been using Doxygen from the start. I'd like to know how you use Doxygen in your project, i.e. I have several questions: 1. Where do you put your Doxygen comments? Header or sources? I think that they should go to the header, because that's where I look to find out how to u...
1. Where do you put your Doxygen comments? Header or sources? I can't answer this because I actually don't currently remember where I tend to document in terms of header versus source. 2. Do you document all methods? Almost completely yes. Every single method gets some form of documentation, unless it is instantly ...
3,537,251
3,537,297
Chart library for Qt
Is there any open-source or free chart library for Qt? I only need XY charts, not bar charts or anything else.
There's two I know of: Qwt QtiPlot: the app is paid, but the code is not I think (you can download the source)
3,537,335
3,537,348
for each in GCC and GCC version
how can I use for each loop in GCC? and how can i get GCC version? (in code)
Use a lambda, e.g. // C++0x only. std::for_each(theContainer.begin(), theContainer.end(), [](someType x) { // do stuff with x. }); The range-based for loop is supported by GCC since 4.6. // C++0x only for (auto x : theContainer) { // do stuff with x. } The "for each" loop syntax is an MSVC extension. It is not...
3,537,360
3,537,807
Calculating Binomial Coefficient (nCk) for large n & k
I just saw this question and have no idea how to solve it. can you please provide me with algorithms , C++ codes or ideas? This is a very simple problem. Given the value of N and K, you need to tell us the value of the binomial coefficient C(N,K). You may rest assured that K <= N and the maximum value of N is 1,000,0...
Notice that 1009 is a prime. Now you can use Lucas' Theorem. Which states: Let p be a prime. If n = a1a2...ar when written in base p and if k = b1b2...br when written in base p (pad with zeroes if required) Then (n choose k) modulo p = (a1 choose b1) * (a2 choose b2) * ... * (ar choose br) modulo p. i.e. remaind...
3,537,368
3,537,430
C++ - building static library question
I built libbz2 (static variant) using MinGW (GCC 4.5.0) compilation system and now try to import this library into my MSVS2008 project. I've done these things already and everything worked fine, for example, with zlib (which means that created C libraries are actually interchangeable). However, when doing the same with...
I read your answer, but I think there's an easier (automatic) way of doing the manual merging of object files: use the CFLAG -static-libgcc, which will link in the necessary functions (what you are describing and doing manually).
3,537,383
3,537,594
VIM open compile error in existing or new tab
When I compile or run a file from VIM all error references are opened in the last active buffer regardless if the file is open already in another vim tab. This behavior is very annoying. Is there any way to force vim to behave like ':tab drop' on compile errors? (See http://vim.wikia.com/wiki/Edit_a_file_or_jump_to_it_...
You're looking for the 'switchbuf' option. If you set switchbuf=useopen,usetab,newtab, then any window/tab that is already displaying the buffer with the error will be focused. If there isn't a window/tab displaying the buffer, then a new tab will be created in which to display it.
3,537,429
3,595,297
The application failed to initialize properly (0xc0150002)
I'm trying to compile an SFML program I've writting in Visual C++ 2010. It compiles fine, but when I run the executable I get this error: The application failed to initialize properly (0xc0150002). Click on OK to terminate the application. This happens every time I try to run an application that uses SFML, I have inc...
Microsoft Visual Studio 2010 wasn't compatible with the 2008 builds of SFML. I fixed the problem by not using 2010 and using Dev-C++ insead.
3,537,470
3,537,504
LNK1561 Linking Error in MSVS2010 when main is defined
I have been making several projects to compile small SDL code tutorials from a tutorial site in Microsoft Visual Studio 2010 using C++>Empty Projects; and all of these projects have compiled fine. In all of these projects I've used this version of main for my entry point: int main (int argc, char* args[]) { //code....
Okay nevermind, I knew it would be something stupid I overlooked... I set the subsystem wrong in the Linker options of my project properties.
3,537,542
3,683,127
A doxygen eclipse plugIn automatically generating stub documentation?
I'am looking for an eclipse-plugin for doxygen code documentation. I have found the eclox-plugIn ( http://home.gna.org/eclox/ ). I would like find out, how can it automatically generate a "empty" doxygen comment, which could be filled out later or what is the better choice for a documentation eclipse plugIn? For exampl...
See updated solution. Old answer: In eclipse helios in window->preferences you can do: c/c++->Code Style->Code Templates->Comments + Automatically add comments for new methods and classes You can configure the comment style here, but it is not as smart as it should be. If you find something better, I would be very hap...
3,537,641
3,537,702
Boost.Fusion Functional: Calling functions with default arguments
Is it possible to use boost::fusion::invoke function to call a function that has default arguments without specifying those? Example: void foo(int x, int y = 1, int z = 2) { std::cout << "The sum is: " << (x + y + z) << std::endl; } ... // This should call foo(0). It doesn't work because the type of foo is void (*...
You can use bind (more info): boost::fusion::invoke(boost::bind(foo, _1, 1, 2), boost::fusion::vector<int>(0));
3,537,688
3,537,930
Which language/framework for HPC: Java/.Net/Delphi/C/C++/Objective-C?
I have deliberated endlessly over which language/framework best suits the following. I need to develop a HPC framework. All processing will be completely OO. It will pass objects between instances (external) and internally between threads & engines. The Objects will be an extension of Active Messages. These instances c...
Here is my run down of some options (in no particular order): C/C++ If all you care about is performance (and nothing else), these will provide. Direct access to system level constructs, such as processor affinity and inline assembly can certainly have an impact on performance. However there a 2 main drawbacks to the...
3,537,842
3,538,409
Fastest type for std::map key?
I would like to use the partitions of a graph as the key to a std::map I could represent this as a std vector of nodes. Or I could convert it into a more compact 'custom' binary format (bitset?), or a string representation. For simplicitiy's sake, we can say there is no inherent order to partitions of a graph. Which w...
If you're going to have that many entries and performance is critical, I would suggest to definitely use unordered_map. If you are using C++1x it's in the standard library; otherwise you can get it from boost. If performance is really critical you can go even further and use boost::intrusive. It contains "intrusive" ve...
3,537,966
3,537,982
Is there an alternative to using static_cast<int> all the time?
I have an enumeration called StackID, and throughout my code I have to static_cast it to int quite a bit - e.g. StackID somestack; int id = static_cast<int>(somestack); Is there a shorthand alternative to doing this cast over and over again ? I have heard of "implicit" conversions - is that something I can use here? (...
Is there something you should use instead? Probably not. If you're doing enum casts to int I would question if you're using enums properly (or if you're having to interface with a legacy API.) That being said you don't have to static_cast enums to ints. That'll happen naturally. See this article from MSN on enums a...
3,537,969
3,537,998
Nested classes: Access to protected member of enclosing class from a nested protected class
This code compiles on msvc/g++: class A{ protected: int i; class B{ public: A* a; B(A* a_) :a(a_){ } void doSomething(){ if (a) a->i = 0;//<---- this part } }; public: A() :i(0){ } }; As you can see, B gets a...
In the C++03 standard, 11.8p1 says: The members of a nested class have no special access to members of an enclosing class. However, the resolution for defect report 45 (to the standard) states the opposite, and hence defines the behavior you see: A nested class is a member and as such has the same access rights as...
3,538,001
3,538,016
Help understanding this?
I have this algorithm that I found here, just one thing puzzles me about it: Clear the stencil buffer to 1. Pick an arbitrary vertex v0, probably somewhere near the polygon to reduce floating-point errors. For each vertex v[i] of the polygon in clockwise order: let s be the segment v[i]->v[i+1] (whe...
If I recall correctly, the triangles you have to draw are v0 - v[i] - v[i+1]
3,538,009
3,538,038
The C++ Programming language, Definitions vs Declarations exercise (simple, if tedious help needed XD)
I've been working through Bjarne Stroustrup's "The C++ Programming Language" (2nd edition - I know I should really get a new copy but this is a library book!), and had a few questions about one of his simpler questions. In Chapter 2, when talking about Declarations and Constants, he lists a set of declarations, some of...
typedef complex point; is not a definition in C++, but only in C. You also cannot, from what I know, provide a non-defining declaration for pi without changing its meaning, because the definition it shows has internal linkage, but if you put extern const double pi; you will give it external linkage (possibly conflicti...
3,538,070
3,538,090
how to find classes present in a c++ library (.lib)?
what tool can I use to find classes present in a C++ static library (.lib) ? This information is for building a library in one solution and use it in another solution by giving lib as input to linker. As the lib can come from 3rd parties, its difficult to find what services it is offering.
Usually from the documentation and headers. If you don't have that, you could use dumpbin -exports or dumpbin -symbols on it to get a list of exported functions (mostly, -symbols for static librarys, -exports for a link library for a DLL). If the code was written in (Microsoft) C++, and the public names are mangled, th...
3,538,109
3,538,136
What is the cleanest way to extend this design for tree-rewriting?
I have a tree of objects, where each object has a std::vector of pointers to its children. The class of the object has a rewrite() method that is recursively applied to alter the object and its children, typically with the following transformations, where [N] is the object being rewritten and (M) is the element that re...
Looks like, for speed, you'll need a "back-pointer" from each child node to its parent node. This way you can follow the chain of parent pointers given a pointer to any node all the way to the root, if that's what you need (I'm not sure how else you planned to find the root given just a pointer to an inner node, witho...
3,538,150
3,538,159
is it possible to compile code for WinCE platform through VisualStudio in WIndows?
I need to compile code written in Visual studio 2008 in Windows XP for WinCE mobile platform. How to do it in Visual studio 2008 by changing target platform settings ?
For Visual Studio 2008 see this MSDN page as a starting point. For C++ this page is the index page and this page tells you how to build and debug. There are a fair number of steps in terms of compiler options and what additional files you need so I won't quote them here.
3,538,168
3,538,198
What are the c++ compiler optimization techniques in Visual studio
I want to know compiler optimization strategies for generating optimized object code for my c++ app in Visual studio. Currently i am using default settings.
In short: the main things you would want to play around with are the /O1 and /O2 flags. They set the optimization to either minimize size or maximize speed. There are a bunch of other settings but you don't really want to be playing around with these unless you really know what you are done and have already measured, ...
3,538,477
3,538,490
C for Java Programmer?
Possible Duplicate: Should I learn C before learning C++? As a professional (Java) programmer and heavy Linux user I feel it's my responsibility to learn some C (even though I may never use it professionally), just to make me a better coder. Two questions : Should I try C or C++ first - I realise they are differen...
C is simple to learn, difficult to master. as a Java programmer the barrier will be memory and structure .. and undoing the damage Java may have done to the algorithm producing portions of your brain ;) I would recommend getting familiar with the GCC toolchain on your Linux box, through tutorials on the Internet. Then ...
3,538,637
3,538,656
Call a function in class members (C++)
Z.h struct Z { Z(); ~Z(); void DoSomethingNasty(); } X.h struct X { X(); ~X(); void FunctionThatCallsNastyFunctions(); } MainClass.h #include "Z.h" #include "X.h" struct MainClass { MainClass(); ~MainClass(); private: Z _z; X _x; } X.cpp X::FunctionThatCallsNastyFunctions()...
The compiler is giving you an error because _z doesn't exist within the X class; it exists within the MainClass class. If you want to call a method on a Z object from X, you either need to give X its own Z object or you have to pass one to it as a parameter. Which of these is appropriate depends on what you're trying t...
3,538,708
3,538,980
Using modal progress bar dialogs in Windows CE?
I'm writing a Windows CE application in C++ directly applying the WINAPI. In this application I parse a text file, which may or may not be large and thus may or may not take a while to load; and as I will add functionality to load files across the wireless network, I figured it would be best to add a progress bar. My a...
You don't have to do anything particularly tricky or unusual. Just create the modal dialog box with DialogBox(). In the WM_INITDIALOG handler of your dialog box procedure, create the background thread to load the file. As the loading progresses, send the PBM_SETPOS message to the progress bar control to update it. W...
3,538,807
3,539,664
Linkage of various const/static variables
I have a few questions about the linkage from the following variables. By examples of 7.1.1/7 of C++03 and experimenting with compilers (Comeau, Clang and GCC), I came to the following linkage kinds: First static, then extern static int a; // (a) extern int a; // (b) valid, 'a' still internal It's clear to me with ac...
const double pi1 = 3.14; // (e) extern const double pi1; // (f) valid and 'pi1' is internal My interpretation is as follows. When considering the linkage of a name we consider previous declarations as well as the one being interpreted at this point in the parse. This is why static int a; extern int a; is OK, but exter...
3,538,959
3,538,965
C++: Can't work with simple pointers?
I apologize as this is so simple, I was working with my own XOR swap method and wanted for the heck of it compare the speed difference between reference and pointer use (do not spoil it for me!) My XOR ptr function is as follows: void xorSwapPtr (int *x, int *y) { if (x != y && x && y) { *x ^= *y; ...
x and y are ints; xorSwapPtr takes two int*s, so you need to pass the addresses of x and y, not x and y themselves: xorSwapPtr(&x, &y);
3,539,113
3,539,163
c++ check cursor position
im trying to see if the cursor is inside my game not on the menue or the border inside the game. i don't konw what function should i use? i thought of using GetcursorPos() but is there better function?
GetCursorPos() returns the mouse position. ScreenToClient() is usually next. That works for polling the mouse. A more typical approach in a game loop is calling PeekMessage() inside the loop so you can see the WM_MOUSEMOVE message. More efficient because you don't burn any time worrying about the mouse when the user...
3,539,230
3,539,250
How to receive strings from C# in Visual-C++ based .net DLL?
How to receive strings from C# in Visual-C++ based .net DLL? In C++ (using clr) I have this code: #include "stdafx.h" ##include <Windows.h> #include <string> #include <windows.h> namespace NSST { public ref class Wrapper { public: Wrapper() {} static void init_1(std::string a, std::string b){} stati...
You can't use std::string, you should use System::String^: static void init_1(System::String^ a, System::String^ b);
3,539,334
3,539,357
How to turn System::String^ into std::string?
So i work in clr, creating .net dll in visual c++. I tru such code: static bool InitFile(System::String^ fileName, System::String^ container) { return enc.InitFile(std::string(fileName), std::string(container)); } having encoder that normaly resives std::string. but here the compiler (visual studio) gives me C266...
If you're using VS2008 or newer, you can do this very simply with the automatic marshaling added to C++. For example, you can convert from System::String^ to std::string via marshal_as: System::String^ clrString = "CLR string"; std::string stdString = marshal_as<std::string>(clrString); This is the same marshaling us...
3,539,549
7,527,770
Can I add numbers with the C/C++ preprocessor?
For some base. Base 1 even. Some sort of complex substitution -ing. Also, and of course, doing this is not a good idea in real life production code. I just asked out of curiosity.
You can relatively easy write macro which adds two integers in binary. For example - macro which sums two 4-bit integers in binary : #include "stdio.h" // XOR truth table #define XOR_0_0 0 #define XOR_0_1 1 #define XOR_1_0 1 #define XOR_1_1 0 // OR truth table #define OR_0_0 0 #define OR_0_1 1 #define OR_1_0 1 #defin...
3,539,583
3,539,688
boost asio deadline_timer
I expected the code below to print Hello, world! every 5 seconds, but what happens is that the program pauses for 5 seconds and then prints the message over and over with no subsequent pauses. What am I missing? #include <iostream> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using n...
You're creating the deadline_timer as a local variable and then immediately exiting the function. This causes the timer to destruct and cancel itself, and calls your function with an error code which you ignore, causing the infinite loop. Using a single timer object, stored in a member or global variable, should fix th...
3,539,600
3,539,618
Const confusion in C++
Possible Duplicate: Why is my return type meaningless? Hi, I'm confused about a particular const conversion. I have something like // Returns a pointer that cannot be modified, // although the value it points to can be modified. double* const foo() { static double bar = 3.14; return &bar; } int...
The return value cannot be modified. That is, the pointer cannot be modified. However, because at the call site, the return value is an rvalue (without a defined = operator), it cannot be modified anyway. If the return value was an lvalue (e.g. a reference), this would be possible: double* &foo() { static double ...
3,539,601
3,539,633
C++ for iphone crash
Im developing a game engine for iphone in C++ but im getting a crash with my Matrix class. I hope you can see whats wrong because i stare my self blind on the crash. /* * Copyright (c) 2010 Johnny Mast * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associate...
You have one visible problem and one invisible problem. First the invisible one. The fact that you're crashing in setupMatrix is almost certainly because you haven't allocated enough (or any) space for the matrix array. We'll need to see where that's done to be certain but it's a fairly safe bet. One possibility, if yo...
3,539,785
3,539,794
What are the caveats to using inline optimization in C++ functions?
What would be the benefits of inlining different types of function and what are the issues that would I would need to watch out for when developing around them? I am not so useful with a profiler but many different algorithmic applications it seems to increase the speed 8 times over, if you can give any pointers that'd...
Inline functions are oft' overused, and the consequences are significant. Inline indicates to the compiler that a function may be considered for inline expansion. If the compiler chooses to inline a function, the function is not called, but copied into place. The performance gain comes in avoiding the function call, st...
3,539,875
3,539,887
Header Files Mystery
Possible Duplicate: what is the difference between #include <filename> and #include “filename” Why do we use Quotation Marks ("...") for custom build classes and braces for built in classes(<...>)?
Yeah, from what I've heard, angle brackets (<'s) are used to denote that the header was provided with the compiler, OR that the compiler has been told about a directory in which the header file can be found (-I). Quotes ("'s) are usually used for header files within the source tree. But like others have mentioned, it's...
3,539,951
3,540,010
WinINet trouble downloading file to client?
I'm curious why I'm having trouble with this function. I'm downloading a PNG file on the web to a destination path. For example, downloading the Google image to the C: drive: netDownloadData("http://www.google.com/intl/en_ALL/images/srpr/logo1w.png", "c:\file.png"); The file size is correct after downloading. Nothing r...
What data type is String? Avoid storing binary data in strings because NULLs in the data can potentially cause problems. Just write the buffer as and when you read it: // Load information to file. fp = fopen(strDestPath, "wb"); if (fp == NULL) return false; // Read file. while (InternetReadFile(hFile, buffer, 102...
3,540,041
3,540,064
Declaring array using a variable in C++
I am writing a program that needs to take text input, and modify individual characters. I am doing this by using an array of characters, like so: char s[] = "test"; s[0] = '1'; cout << s; (Returns: "1est") But if I try and use a variable, like so: string msg1 = "test"; char s2[] = msg1; s2[0] = '1'; cout << s1[0] I ...
C-style arrays require literal values for initialization. Why use C-style arrays at all? Why not just use std::string... string msg1 = "test"; string s2 = msg1; s2[0] = '1'; cout << s2[0];