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
652,193
657,909
Serialize and send a data structure using Boost?
I have a data structure that looks like this: typedef struct { unsigned short m_short1; unsigned short m_short2; unsigned char m_character; } MyDataType; I want to use boost::serialization to serialize this data structure, then use boost::asio to transmit it via TCP/IP, then have another application receive the...
For such simple structure, boost::serialization is overkill and huge overhead. Do simpler: vector<uint16_t> net(3,0); net[0]=htons(data.m_short1); net[1]=htons(data.m_short2); net[2]=htons(data.character); asio::async_write(socket,buffer((char*)&net.front(),6),callback); vector<uint16_t> net(3,0); asio::async_read(s...
652,503
652,619
unix-fork-monitor-child-progress
I have an application where a bit of parallel processing would be of benefit. For the purposes of the discussion, let's say there is a directory with 10 text files in it, and I want to start a program, that forks off 10 processes, each taking one of the files, and uppercasing the contents of the file. I acknowledge th...
In this kind of situation where you only want to monitor the progress, the easiest alternative is to use shared memory. Every process updates it progress value (e.g. an integer) on a shared memory block, and the master process reads the block regularly. Basically, you don't need any locking in this scheme. Also, it is ...
652,542
669,687
Strange SAL annotation warning
I'm trying to use Micosoft's SAL annotation for my project, however I get the following warning, and I don't know why. As an example, I created a new C++ console application, and have this code: #include <sal.h> class Whatever { public: _Check_return_ int Method(__in int number) ; }; int main() { return 0; } ...
The problem may be because you are mixing SAL annotation types. Although made very clear on MSDN, there are two types of SAL annotation: attribute and ... er ... not. The #defines in <sal.h> VC2005 use the non-attribute versions and start with an underscore followed by a lowercase letter. The newer VC2008 versions exp...
652,605
670,429
Why won't MFC::CHttpFile 'PUT' for me?
My code talks to a little Java application provided by a vendor. This Java app sets up a web server at localhost:57000 which is used to control the state of 'the machine'. For the purpose of this question, I need to change the state of 'the machine' from 'off' to 'on'. To make this happen I'm supposed to HTTP PUT th...
I wound up replacing the MFC classes with my own low level socket code to send exactly the same text in exactly the same order as Curl did. It seemed like the little embedded 'jetty' Java server just objected to one of the headers generated by the MFC classes.
652,683
652,689
G++ Compiler won't allow recursion?
I have created a very simple program that uses recursion. I'm using the g++ compiler. I can compile it, but when I try to run it I get an error message that says SEGMENTATION FAULT. Here's my code: #include <iostream.h> using namespace std; int Recurse(int); int main(int argc, char *argv[]) { Recurse(10); ...
In your recursive call, you're using the postfix -- (numTimes--), rather than the prefix version (--numTimes). As a result, the value of numTimes is decremented after the recursive call. This means that Recurse is called with 10 infinitely. Use the prefix version (which will decrement it before the call), or just pass ...
652,715
652,737
std::allocator construct/destroy vs. placement new/p->~T()
For a project of mine, I am writing some STL containers from scratch (I have my reasons). Since I am mimicking the functionality and interfaces of the STL so closely I am doing my best to keep with the policy "if it has the same name as a standard construct, it will conform to the standard as much as possible." So, of ...
The allocator could add logging statements before and after construction/destruction, or any other side effects it cared to do. Of course the actual construction has to occur by calling placement new and the destructor, but it doesn't say in the rulebook that nothing else must happen in the construct/destroy functions
652,779
653,758
Automatically separate class definitions from declarations?
I am using a library that consists almost entirely of templated classes and functions in header files, like this: // foo.h template<class T> class Foo { Foo(){} void computeXYZ() { /* heavy code */ } }; template<class T> void processFoo(const Foo<T>& foo) { /* more heavy code */ } Now this is bad because compile t...
We use lzz which splits out a single file into a separate header and translation unit. By default, it would normally put the template definitions into the header too, however, you can specify that you don't want this to happen. To show you how you might use it consider the following: // t.cc #include "b.h" #include "c...
652,788
652,945
What is the worst real-world macros/pre-processor abuse you've ever come across?
What is the worst real-world macros/pre-processor abuse you've ever come across (please no contrived IOCCC answers *haha*)? Please add a short snippet or story if it is really entertaining. The goal is to teach something instead of always telling people "never use macros". p.s.: I've used macros before... but usually ...
From memory, it looked something like this: #define RETURN(result) return (result);} int myfunction1(args) { int x = 0; // do something RETURN(x) int myfunction2(args) { int y = 0; // do something RETURN(y) int myfunction3(args) { int z = 0; // do something RETURN(z) Yes that's r...
652,813
652,837
Macros and Visual C++
I'm trying to get a better understanding of what place (if any) Macros have in modern C++ and Visual C++, also with reference to Windows programming libraries: What problem (if any) do Macros solve in these situations that cannot be solved without using them? I remember reading about Google Chrome's use of WTL for Macr...
All of those Macros are defined in public sdk header files, so you can go read what they do yourself if you want. Basically what is happening here is you're generating a WndProc function using Macros. Each MSG_WM_* entry is a case statement that handles the given window message by translating its arguments from wPara...
652,815
844,281
Has anyone ever had a use for the __COUNTER__ pre-processor macro?
The __COUNTER__ symbol is provided by VC++ and GCC, and gives an increasing non-negative integral value each time it is used. I'm interested to learn whether anyone's ever used it, and whether it's something that would be worth standardising?
It's used in the xCover code coverage library, to mark the lines that execution passes through, to find ones that are not covered.
653,150
653,164
Equivalence of <limits> and <climits>
Is this guaranteed to be always true: std::numeric_limits<int>::max() == INT_MAX What does C++ standard say about it? I could not find any reference in the standard that would explicitly state this, but I keep reading that those should be equivalent. What about C99 types that are not in C++98 standard for compilers t...
My copy of the C++ 2003 standard says that the numeric_limits<>::max() and min() templates will return values: Equivalent to CHAR_MIN, SHRT_MIN, FLT_MIN, DBL_MIN, etc. Equivalent to CHAR_MAX, SHRT_MAX, FLT_MAX, DBL_MAX, etc However, those are in footnotes. ISO/IEC Directives Part 3: "[Footnotes] shall not contain req...
653,178
653,188
"Unable to find an entry point named [function] in dll" (c++ to c# type conversion)
I have a dll which comes from a third party, which was written in C++. Here is some information that comes from the dll documentation: //start documentation RECO_DATA{ wchar_t Surname[200]; wchar_t Firstname[200]; } Description: Data structure for receiving the function result. All function result will be stored as U...
First make sure the function is actually exported: In the Visual Studio Command Prompt, use dumpbin /exports whatever.dll
653,211
653,235
STL class for reference-counted pointers?
This should be trivial but I can't seem to find it (unless no such class exists!) What's the STL class (or set of classes) for smart pointers? UPDATE Thanks for the responses, I must say I'm surprised there's no standard implementation. I ended up using this one: http://archive.gamedev.net/reference/articles/article106...
With the exception of the already mentionned TR1 shared_ptr, there is no reference-counted pointer in STL. I suggest you use boost::shared_ptr (downloading boost will be enough, there is nothing to compile, its implementation is header-only). You may also want to have a look at smart pointers from Loki libraries (again...
653,336
5,058,059
Should a buffer of bytes be signed or unsigned char buffer?
Should a buffer of bytes be signed char or unsigned char or simply a char buffer? Any differences between C and C++? Thanks.
Should a buffer of bytes be signed char or unsigned char or simply a char buffer? Any differences between C and C++? A minor difference in how the language treats it. A huge difference in how convention treats it. char = ASCII (or UTF-8, but the signedness gets in the way there) textual data unsigned char = b...
653,423
653,448
pointer to objects within a class, C++ newbie question
why in C++, for objects A,B //interface, case #1 class A { B bb; } A::A() { //constructor bb = B(); } //interface, case #2 class A { B *bb; } A::A() { //constructor bb = new B(); } Why case #2 work but not #1?? Edit: I got it now. But for case #1, if an instance of A is freed, will its bb also be automatically f...
The question as for me was how to make A::A() { //constructor bb = new B(); } but without new. And I suppose the code in the question is not a real code. Just why 'new' works but simple assignment doesn't. And my answer is following. If I understood the question in a wrong way or the answer itself is wrong - please l...
653,787
653,806
Direct3D10: No 32bit ARGB format?
Im starting to add d3d10 support to go along with my existing d3d9 graphics backend. The problem is all the existing code (in several applications...) uses ARGB formatted colours however I couldnt find a format mode that matches for d3d10. Does d3d10 not support ARGB colour formats at all or have I just missed somethin...
Looking at the relevant enum type, I (too) fail to find any AxRxGxBx formats. So it seems you need to do the swizzling by yourself, then. This is extremely suitable for SSE optimization of course, check if your compiler is able to optimize the code into something that uses SSE and performance should be fine. Think abou...
653,980
654,025
List of common C++ Optimization Techniques
Can I have a great list of common C++ optimization practices? What I mean by optimization is that you have to modify the source code to be able to run a program faster, not changing the compiler settings.
Two ways to write better programs: Make best use of language Code Complete by Steve McConnell Effective C++ Exceptional C++ profile your application Identify what areas of code are taking how much time See if you can use better data structures/ algorithms to make things faster There is not much language specific op...
654,154
654,180
Profiling programs written in C or C++
What would you suggest the best tool to profile C/C++ code and determine which parts are taking the most time. Currently, I'm just relying on logs but ofcourse the information is not accurate since unnecessary delays are introduced. Preferrably, the tool would also be able to detect/suggest areas which could be optimiz...
I can heartily recommend callgrind in combination with KCachegrind.
654,197
655,253
Port GNU C++ programs to Visual C++
How do you port C++ programs with makefile made from GNU C++ in Linux to Visual C++?
One thing I can suggest is to use CMake. If you implement your build system with CMake to auto-generate the makefiles for GCC on Linux, it takes only minor modifications to auto-generate projects and solutions for VC++. Of course, this means learning a whole new build tool, so it may not be for you. It's only a suggest...
654,220
654,316
Is using .h as a header for a c++ file wrong?
Is using .h as a header for a c++ file wrong? I see it all over the place, especially with code written in the "C style". I noticed that Emacs always selects C highlighting style for a .h header, but c++ for hpp or hh. Is it actually "wrong" to label your headers .h or is it just something which annoys me? EDIT: Ther...
It's not wrong to call your C++ headers .h. There are no rules of what extensions your code must use. For your non-headers, MSVC uses .cpp and on Linux, .cc as well. There is no one global standard, and .h is definitely very widely used. But I'd say calling your headers .hpp (I've seen .hh a few times as well) is a lot...
654,389
654,398
Reporting tool for C++ that shows number of times executed given a line
I would to know if there is a tool in C++ that gives you a report where it displays the following: The source code of the whole project. Usually one HTML page per source file. Beside the source code, there are line numbers, for readability purposes of course. And for each line, at the left of the line number, there i...
Have a look at that list of Code Coverage Tools for C and C++.
654,428
654,432
What is the order in which the destructors and the constructors are called in C++
What is the order in which the destructors and the constructors are called in C++? Using the examples of some Base classes and Derived Classes
The order is: Base constructor Derived constructor Derived destructor Base destructor Example: class B { public: B() { cout<<"Construct B"<<endl; } virtual ~B() { cout<<"Destruct B"<<endl; } }; class D : public B { public: D() { cout<<"Construct D"<<endl; } virtual ~D() { ...
654,609
654,947
How much functionality is "acceptable" for a C++ struct?
My first post so please go easy on me! I know that there's no real difference between structs and classes in C++, but a lot of people including me use a struct or class to show intent - structs for grouping "plain old data" and classes for encapsulated data that has meaningful operations. Now, that's fine but at what p...
Class vs. struct Using class or struct keyword is a matter of taste together with the 'feeling' it produces on the reader. Technically they are equivalent, but readability is better if structs are used for PODs and C-struct types and classes for anything else. Basic things that should go in a C++ struct: constructor th...
654,645
654,727
using const to prevent datatype changing and value changing
Is there a difference between using const: Cannot change the datatype but can change the value of a or b int add(const int a, const int b); Can change the datatype but cannot change the value of a or b int add(int const a, int const b); Cannot change the datatype and cannot change the value of a or b int add(const in...
I don't know how one is supposed to changed the datatype of a variable in C++ ... 'const' is a promise you make to the compiler about not modifying a value. It complains when you don't (probably uncovering z bug in the process). It also helps it to do various optimizations. Here are some const examples and what they me...
654,713
654,724
.o files vs .a files
What is the difference between these two file types. I see that my C++ app links against both types during the construction of the executable. How to build .a files? links, references, and especially examples, are highly appreciated.
.o files are objects. They are the output of the compiler and input to the linker/librarian. .a files are archives. They are groups of objects or static libraries and are also input into the linker. Additional Content I didn't notice the "examples" part of your question. Generally you will be using a makefile to genera...
654,751
654,801
Using a C++ header with .NET language
I trying to use a ".h" file from Windows SDK in a .NET language (maybe C#), but without success. This header exposes some Windows Media player functionality through COM. If I use Win32 C++, I can use it with no problems, so I thought that I could use Managed C++ as a "Bridge" to expose it to C#. The header file is the ...
You can use PInvoke to Interop with Win32. If you are trying to use a COM object you should be able to add a reference to the project. Have you looked at this article? More practically you need to understand the kind of work that you are doing. If you are going to be doing lots of pointer arithmetic then I would recomm...
654,853
654,881
Why would one use function pointers to member method in C++?
A lot of C++ books and tutorials explain how to do this, but I haven't seen one that gives a convincing reason to choose to do this. I understand very well why function pointers were necessary in C (e.g., when using some POSIX facilities). However, AFAIK you can't send them a member function because of the "this" para...
Functors are not a priori object-oriented (in C++, the term “functor” usually means a struct defining an operator () with arbitrary arguments and return value that can be used as syntactical drop-in replacements to real functions or function pointers). However, their object-oriented problem has a lot of issues, first a...
655,027
655,144
when should a member function be both const and volatile together?
I was reading about volatile member function and came across an affirmation that member function can be both const and volatile together. I didn't get the real use of such a thing. Can anyone please share their experience on practical usage of having member function as const and volatile together. I wrote small class t...
You asked for a practical example of volatile member functions. Well i can't think of one because the only situations i could imagine are so low-level that i would not consider using a member function in the first place, but just a plain struct with data-members accessed by a volatile reference. However, let's put a co...
655,065
655,086
When should I use the new keyword in C++?
I've been using C++ for a short while, and I've been wondering about the new keyword. Simply, should I be using it, or not? With the new keyword... MyClass* myClass = new MyClass(); myClass->MyField = "Hello world!"; Without the new keyword... MyClass myClass; myClass.MyField = "Hello world!"; Fro...
Method 1 (using new) Allocates memory for the object on the free store (This is frequently the same thing as the heap) Requires you to explicitly delete your object later. (If you don't delete it, you could create a memory leak) Memory stays allocated until you delete it. (i.e. you could return an object that you ...
655,122
655,152
Doing a run-around of existing application to make database changes, good idea?
We have an existing "legacy" app written in C++/powerbuilder running on Unix with it's own Sybase databases. For complex organizational(existing apps have to go through lot of red-tape to be modified) and code reasons(no re-factoring has been done in yrs so the code is spaghetti), so it's difficult to get modification...
Good idea? No. Sometimes necessary? Yes. Living in a world where you sometimes have to do things you know aren't a good idea? Priceless. In general, you should always follow best practices. For everything else, there's kludges.
655,202
655,304
git and C++ workflow, how to handle object and archive files?
I use git to interface with an SVN repository. I have several git branches for the different projects I work on. Now, whenever I switch from one branch to another using 'git checkout ', all the compiled executables and object files from the previous branch are still there. What I would like to see is that switching fr...
What you want is a full context, not just the branch... which is generally out of scope for a version control tool. The best way to do that is to use multiple repositories. Don't worry about the inefficiency of that though... Make your second repository a clone of the first. Git will automatically use links to avoid ha...
655,257
655,275
Two's complement binary form
In a TC++ compiler, the binary representation of 5 is (00000000000000101). I know that negative numbers are stored as 2's complement, thus -5 in binary is (111111111111011). The most significant bit (sign bit) is 1 which tells that it is a negative number. So how does the compiler know that it is -5? If we interpret t...
The compiler doesn't know. If you cast -5 to unsigned int you'll get 32763.
655,378
655,448
Howto read chunk of memory as char in c++
Hello I have a chunk of memory (allocated with malloc()) that contains bits (bit literal), I'd like to read it as an array of char, or, better, I'd like to printout the ASCII value of 8 consecutively bits of the memory. I have allocated he memory as char *, but I've not been able to take characters out in a better way ...
int numBytes = 512; char *pChar = (char *)malloc(numBytes); for( int i = 0; i < numBytes; i++ ){ pChar[i] = '8'; } Since this is C++, you can also use "new": int numBytes = 512; char *pChar = new char[numBytes]; for( int i = 0; i < numBytes; i++ ){ pChar[i] = '8'; }
655,450
655,464
Passing a smart pointer as argument inside a class: scoped_ptr or shared_ptr?
I have a class that creates an object inside one public method. The object is private and not visible to the users of the class. This method then calls other private methods inside the same class and pass the created object as a parameter: class Foo { ... }; class A { private: typedef scoped_ptr<Foo> FooPt...
Use here simple std::auto_ptr as you can't create objects on the stack. And it is better to your private function just simply accept raw pointer. Real usage is that you don't have to catch all possible exceptions and do manual delete. In fact if your object is doesn't modify object and your API return object for sure y...
655,650
655,679
How to program a RPG game in C++ with SDL?
I want to know how to program a 2D RPG game in C++ with SDL. I have searched, but was unable to find anything good. Many of the articles were too basic and didn't delve into anything practical. Can anyone help give me some articles, free books or other resources so I can learn how to program a RPG using C++ and SDL? E...
Do you have examples of articles that are too simple? Are these too simple: devshed or gpwiki ? You might consider studying the topics separately. For example Bruce Eckels has, IMO, the best C++ books, "Thinking in C++ I & II" that will take you from novice to expert (including SQA techniques like unit testing) and the...
655,957
2,363,905
Why do I keep getting "Must declare the Scalar variable "@Param1"" when performing a parameterized query in C++ using ADO?
Here is the code. A Few notes about it. DStr is an string class that is internal to our company. It functions much like CString. I can connect to the database and run non-parameterized queries. Also this insert works fine if I do not use parameters. The cmd->Execute statment throws an exception. This is where I a...
ADO refuses to work with named parameters in dynamic queries. You have to either convert named parameters into parameter placeholders: DStr sql = "INSERT INTO [User] (UserName, DisplayName) VALUES (?, ?)"; or use a stored procedure instead. Create the procedure: CREATE PROCEDURE spUserInsert @Param1 nvarchar(50), ...
655,997
656,015
Modern C++ Design Generic programming and Design Patterns Applied
I have purchase this book for our group in the company, perhaps, to improve our design skills and ultimately have a better programming practices. As I read it, I find, mostly, a set of nifty tricks that can be used with template, and not sure if it is worthwhile - and not detrimental-to incorporate it into our code...
Outside of standard template uses, the operation I find most useful about the information talked about generic C++ programming, is the ability to use templates to create compile time errors for invalid code scenarios. Once you get the hang of it you can become very efficient at turning a class of what would be a runti...
656,224
656,523
When should I use C++ private inheritance?
Unlike protected inheritance, C++ private inheritance found its way into mainstream C++ development. However, I still haven't found a good use for it. When do you guys use it?
Note after answer acceptance: This is NOT a complete answer. Read other answers like here (conceptually) and here (both theoretic and practic) if you are interested in the question. This is just a fancy trick that can be achieved with private inheritance. While it is fancy it is not the answer to the question. Besides ...
656,651
656,667
Virtual inheritance in C++ usages/tricks
I've never used it in the professional software even though in our shop, and others I have worked for, we design large scale systems. The only time I messed with virtual inheritance was during my interview in a company. Nonetheless, I played with it during afterhours. Do you guys use it? Do you understand how it work...
The main point with virtual inheritance is to prevent derived classes from inheriting multiple copies of different superior classes. This can occur in any case where there may be multiple inheritance -- as you correctly note, the "diamond problem", which is to say where the inheritance graph is a DAG instead of a str...
656,655
656,853
GetOpenFileName() with OFN_ALLOWMULTISELECT flag set
I'm trying to use the GetOpenFileName() common dialog box call to pop open a dialog box and allow the user to select multiple files. I've got the OFN_ALLOWMULTISELECT flag set, as well as OFN_EXPLORER set so I get the "new style" file selection box. When I set up my OPENFILENAME structure, I have ofn.lpstrFile pointing...
An interesting problem. I guess you could just allocate all of memory; just in case! But this document suggests using a Hook proc: http://support.microsoft.com/kb/131462 And all in delightfull understandable non OO C!
656,706
656,735
Installing Root CA Cert via code on Win32
We've just set up a new remote access solution using Microsoft's TS Gateway, which requires a couple of somewhat fiddly steps on the end users behalf in order to get it working (installing our root ca cert, requirement of RDP 6.1 client etc). In order to make this setup process as easy as possible (a lot of these users...
First you need to open the root certificate store... HCERTSTORE hRootCertStore = CertOpenSystemStore(NULL,"ROOT"); Then add the certificate using one of the CertAdd functions, such as CertAddEncodedCertificateToStore. CertAddEncodedCertificateToStore(hRootCertStore,X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,pCertData,cb...
656,948
657,113
a class-key must be declared when declaring a friend
The g++ compiler complains with this error when I declare a friend thusly: friend MyClass; instead of friend class MyClass; Why should the class keyword be required? (the Borland C++ compiler, BTW, does not require it.) Couldn't the compiler simply look-up MyClass in the symbol table and tell it was declared as a cl...
I was surprised about this (and as a result deleted a previous incorrect answer). The C++03 standard says in 11.4: An elaborated-type-specifier shall be used in a friend declaration for a class. Then to make sure there's no misunderstanding, it footnotes that with: The class-key of the elaborated-type-spec...
657,141
657,166
How to avoid blocking (C++, Win32)
I'm making a dll that has to respond to an application's requests. One of the application's requirements is that a call should not take long to complete. Say, I have a function foo(), which is called by the host application: int foo(arg){ // some code i need to execute, say, LengthyRoutine(); return 0; } L...
Spawning another thread is pretty much the best way to do it, just make sure you set the result variables before you set the variable that says you're finished to avoid race conditions. If this is called often you might want to spawn a worker thread ahead of time and reuse it to avoid thread start overhead. There is an...
657,155
669,621
How to enable_shared_from_this of both parent and derived
I have simple base and derived class that I want both have shared_from_this(). This simple solution: class foo : public enable_shared_from_this<foo> { void foo_do_it() { cout<<"foo::do_it\n"; } public: virtual function<void()> get_callback() { return boost::bind(&foo::foo_do_it,share...
Sorry, but there isn't. The problem is that shared_ptr<foo> and shared_ptr<bar1> are different types. I don't understand everything that's going on under the hood, but I think that when the constructor returns and is assigned to a shared_ptr<foo>, the internal weak_ptr<bar1> sees that nothing is pointing to it (because...
657,248
657,258
Is it acceptable for a C++ programmer to not know how null-terminated strings work?
Is there any way for a C++ programmer with 1,5 years of experience to have no idea that null-terminated strings exist as a concept and are widely used in a variety of applications? Is this a sign that he is potentially a bad hire?
What does he use -- std::string only? Does he know about string literals? What is his take on string literals? There's too little detail to tell you if he's a bad hire, but he sounds like he needs a bit more talking to than most.
657,281
657,312
How do you model application states?
I'm writing a game, and I want to model its different states (the Game Maker analogy would be frames, I guess) in a clean, object-oriented way. Previously, I've done it in the following way: class Game { enum AppStates { APP_STARTING, APP_TITLE, APP_NEWGAME, APP_NEWLEVEL, APP_PLAYING, APP_PA...
The following article gives a nice, simple way to manage game states: http://gamedevgeek.com/tutorials/managing-game-states-in-c/ Basically, you maintain a stack of game states, and just run the top state. You're right that many states would only have one instance, but this isn't really a problem. Actually, though, man...
657,472
657,479
What programs are there for parser generation?
I recently took a class at school where we had to learn Scheme to build a parser for a simple made up scheme-like language. As the semester went on, we added to our parser to make it more and more interesting. Since then, on my own time, I've started writing my own parser that's quite a bit neater than what I did in cl...
lex and yacc (or rather, flex and bison) are powerful tools that will help you generate parsers for regular languages with ease.
657,511
657,521
C++ compiler that supports C++0x features?
Is where any C++ compiler that supports C++0x features already?
Both the 2008 Visual C++ 'Feature Pack' and g++ support some features. The list of C++0x features supported by g++. The Visual C++ 2008 Feature Pack ... includes an implementation of TR1. Portions of TR1 are scheduled for adoption in the upcoming C++0x standard as the first major addition to the ISO 2003 standard C++...
657,724
657,780
How to add a conditional breakpoint in Visual C++
I want to add a breakpoint condition to my code in VC++ Express 2005, so that the breakpoint only triggers if a local variable meets a specified criteria. e.g. bool my_test(UIDList test_list) { foo(test_list); bar(test_list); // I have a breakpoint here, but only want it to trigger if test_list.Length() > 0 ...
use the DebugBreak(); function: bool my_test(UIDList test_list) { foo(test_list); if (bar(test_list) /* or whatever check :) */) // I have a breakpoint here, but only want it to trigger if test_list.Length() > 0 DebugBreak(); } print(test_list); } Or you can always use assert(expression) bool m...
657,783
661,228
How does Intel TBB's scalable_allocator work?
What does the tbb::scalable_allocator in Intel Threading Building Blocks actually do under the hood ? It can certainly be effective. I've just used it to take 25% off an apps' execution time (and see an increase in CPU utilization from ~200% to 350% on a 4-core system) by changing a single std::vector<T> to std::vecto...
There is a good paper on the allocator: The Foundations for Scalable Multi-core Software in Intel Threading Building Blocks My limited experience: I overloaded the global new/delete with the tbb::scalable_allocator for my AI application. But there was little change in the time profile. I didn't compare the memory usage...
657,920
657,935
Should lookup tables be static
I have a Message class which parses text messages using lookup tables. I receive a lot of messages and create and destroy a lot of objects so I thought I declare those lookup tables as static members to prevent initializing the same tables with the same values again and again. Is it the correct approach or there's more...
This sounds like the right way to do it, although I'd expect the compiler to optimize this. Have you benchmarked your application and does declaring the tables as static speed it up? Also note that if you have many large lookup tables, performance will increase, but the tables will be hold in memory all the time.
657,964
657,968
Is using NULL references OK?
I came across this code: void f(const std::string &s); And then a call: f( *((std::string*)NULL) ); And I was wondering what others think of this construction, it is used to signal that function f() should use some default value (which it computes) instead of some user provided value. I am not sure what to think of i...
No. It is undefined behaviour and can lead to code to do anything (including reformatting you hard disk, core dumping or insulting your mother). If you need to be able to pass NULL, then use pointers. Code that takes a reference can assume it refers to a valid object. Addendum: The C++03 Standard (ISO/IEC 14882, 2nd e...
658,016
658,135
expat parser: memory consumption
I am using expat parser to parse an XML file of around 15 GB . The problem is it throws an "Out of Memory" error and the program aborts . I want to know has any body faced a similar issue with the expat parser or is it a known bug and has been rectified in later versions ?
I've used expat to parse large files before and never had any problems. I'm assuming you're using SAX and not one of the expat DOM wrappers. If you are using DOM, then that's your problem right there - it would be essentially trying to load the whole file into memory. Are you allocating objects as you parse the XML a...
658,133
658,180
c++: when to use pointers?
After reading some tutorials I came to the conclusion that one should always use pointers for objects. But I have also seen a few exceptions while reading some QT tutorials (http://zetcode.com/gui/qt4/painting/) where QPaint object is created on the stack. So now I am confused. When should I use pointers?
If you don't know when you should use pointers just don't use them. It will become apparent when you need to use them, every situation is different. It is not easy to sum up concisely when they should be used. Do not get into the habit of 'always using pointers for objects', that is certainly bad advice.
658,355
658,529
Why a child window may not receive mouse events?
I have a custom WTL control which is a panel with a list and a custom scroll bar. class Panel : public ATL::CWindowImpl<Panel>, public WTL::CDoubleBufferImpl<Panel> { public: DECLARE_WND_CLASS("Panel") BEGIN_MSG_MAP_EX(Panel) MSG_WM_CREATE(OnCreate) MSG_WM_DESTROY(OnDestroy) MSG_WM_SIZE...
Found it. The problem was in the scroll bar class declaration: class CScrollBase : public ATL::CWindowImpl<CScrollBase, WTL::CStatic> Changing to: class CScrollBase : public ATL::CWindowImpl<CScrollBase> makes the scroll bar work on the panel.
658,403
658,495
How would you implement a basic event-loop?
If you have worked with gui toolkits, you know that there is a event-loop/main-loop that should be executed after everything is done, and that will keep the application alive and responsive to different events. For example, for Qt, you would do this in main(): int main() { QApplication app(argc, argv); // init...
I used to wonder a lot about the same! A GUI main loop looks like this, in pseudo-code: void App::exec() { for(;;) { vector<Waitable> waitables; waitables.push_back(m_networkSocket); waitables.push_back(m_xConnection); waitables.push_back(m_globalTimer); Waitable* whatHappene...
659,000
659,586
RegisterDeviceNotification Returns NULL but notifications still recieved
I'm using RegisterDeviceNotification to watch for changes to a USB device, using the WM_DEVICECHANGE event. However, when I call RegisterDeviceNotification() it returns NULL for the notification handle, which should indicate that it failed. But GetLastError() returns ERROR_SUCCESS and the notifications actually go th...
Make sure you are not making another Win32 API call between RegisterDeviceNotification and GetLastError. Check the value of devBrHdr.dbch_hdevnotify. It should contain the same handle returned by RegisterDeviceNotification. Was the m_hDriver value obtained from a call to CreateFile?
659,166
661,791
Write C++ in a graphical scratch-like way?
I am considering the possibility of designing an application that would allow people to develop C++ code graphically. I was amazed when I discovered Scratch (see site and tutorial videos). I believe most of C++ can be represented graphically, with the exceptions of preprocessor instructions and possibly function point...
Writing code is the easiest part of a developers day. I don't think we need more help with that. Reading, understanding, maintaining, comparing, annotating, documenting, and validating is where - despite a gargantuan amount of tools and frameworks - we still are lacking. To dissect your pros: Intuitive and simple for...
659,231
659,447
Crossing assignment operators?
It's time for my first question now. How do you cross assignments operators between two classes? class B; class A { public: A &operator = ( const B &b ); friend B &B::operator = ( const A &a ); //compiler error }; class B { public: B &operator = ( const A &a ); friend A &A::operator = ( const B &b ); }; I searched f...
The reason for the compiler error is a circular dependency. Each of your operator=() functions require knowledge of the operator=() function inside the other class, so no matter which order you define your classes in, there will always be an error. Here is one way to sort it out. It isn't very elegant, but it will do w...
659,270
659,278
Why is there a special new and delete for arrays?
What is wrong with using delete instead of delete[]? Is there something special happening under the covers for allocating and freeing arrays? Why would it be different from malloc and free?
Objects created with new[] must use delete[]. Using delete is undefined on arrays. With malloc and free you have a more simple situation. There is only 1 function that frees the data you allocate, there is no concept of a destructor being called either. The confusion just comes in because delete[] and delete look si...
659,376
659,438
Are there any good beginner tutorials for threads in windows? C++
Looking for a good site or book that explains windows threads, preferably for a beginner. Maybe has a example program to run, etc....
You want Chapter 20 of Programming Windows by Charles Petzold "Multitasking and Multithreading". It also covers related things like synchronization, and events. This book is a classic, and probably one of the best ways to get a very good understanding of how Windows Win32 programming works with C++. Otherwise you can s...
659,581
659,593
Replace giant switch statement with what?
I have a code that parses some template files and when it finds a placeholder, it replaces it with a value. Something like: <html> <head> <title>%title%</title> </head> <body bgcolor="%color%"> ...etc. In code, the parser finds those, calls this function: string getContent(const string& name) { if (name == "ti...
Use a dictionary that maps tag names to a tag handler.
659,825
659,863
System::Windows::Forms::Form::ShowDialog()
I have a 2 forms setup my first form will call another form with the ShowDialog() method when I receive data from the serial port ShowDialog() throws InvalidOperation with additionnal information "DragDrop registration did not succeed" any hints on how to solve this?
Cheesy google search answer... but it seems to address your issue: http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/269b8950-2ef9-483f-8124-e2725ffd5d83/
660,517
660,596
Minor question regarding templeted functions in templated class
I am trying to understand some C++ syntax: template<class T> class Foo { Foo(); template<class U> Foo(const Foo<U>& other); }; template<class T> Foo<T>::Foo() { /*normal init*/ } template<class T> template<class U> Foo<T>::Foo(const Foo<U>& other) { /*odd copy constructed Foo*/ } So, I wrote code like thi...
It has to have separate template clauses for each template that is involved. Here, two templates are involved, that all deserve their (non-empty) template clauses: The class template Foo The constructor template Consider this case which fails because of the ambiguity as to where the parameter U belongs to template<ty...
660,667
660,753
iostream and large file support
I'm trying to find a definitive answer and can't, so I'm hoping someone might know. I'm developing a C++ app using GCC 4.x on Linux (32-bit OS). This app needs to be able to read files > 2GB in size. I would really like to use iostream stuff vs. FILE pointers, but I can't find if the large file #defines (_LARGEFILE_SO...
This has already been decided for you when libstdc++ was compiled, and normally depends on whether or not _GLIBCXX_USE_LFS was defined in c++config.h. If in doubt, pass your executable (or libstdc++.so, if linking against it dynamically) through readelf -r (or through strings) and see if your binary/libstdc++ linked ag...
660,838
660,864
C++ Optimization on negative integers
Lets say we have a negative integer say int a; is there a faster implementation of -a? Do I have to do some bitwise operation on this?
To clarify Pax's statement, C++ compilers are not mandated to use two's complement, except in 1 case. When you convert a signed type to an unsigned type, if the number is negative, the result of the conversion must be the 2's complement representation of the integer. In short, there is not a faster way than -a; even if...
661,273
661,285
What happens when passing reference to literal in C++?
What happens here: double foo( const double& x ) { // do stuff with x } foo( 5.0 ); Does the compiler create an anonymous variable and sets its value to 5.0? Does the x reference a memory location in read-only memory? This is a weird phrasing, I know... edit: I forgot the const keyword...
A temporary variable is created for this purpose and it's usually created on stack. You could try to const_cast, but it's pontless anyway, since you can no longer access a variable once the function returns.
661,338
662,250
SSE SSE2 and SSE3 for GNU C++
Is there a simple tutorial for me to get up to speed in SSE, SSE2 and SSE3 in GNU C++? How can you do code optimization in SSE?
Sorry don't know of a tutorial. Your best bet (IMHO) is to use SSE via the "intrinsic" functions Intel provides to wrap (generally) single SSE instructions. These are made available via a set of include files named *mmintrin.h e.g xmmintrin.h is the original SSE instruction set. Begin familiar with the contents of Inte...
661,346
680,077
Moving an engineering application from standalone to internal to CAD
I have a large MFC C++ application that I would be very keen to port into AutoCAD and IntelliCAD. AutoDesk offer Object ARX for this purpose, which replaces the older and slower ADS technology. IntelliCAD, afaik only supports ADS. Has anyone out there done this, and if so which tools did you use and what pitfalls di...
Have a look at my answers to a couple of previous AutoCAD questions Open source cad drawing (dwg) library in C# .Net CAD component that can read/write dxf/ dwg files If you were looking for the same code base to work both inside and outside of AutoCAD then the RealDWG approach may work for you since the code is the sa...
661,464
661,477
How internally this works int const iVal = 5; (int&)iVal = 10;
I wanted to know how the following works @ compiler level. int const iVal = 5; (int&)iVal = 10; A bit of m/c or compiler level answer would be great full. Thanks in advance.
It is undefined behavior. In the first line you define a constant integer. Henceforth, in your program, the compiler is permitted to just substitute iVal with the value 5. It may load it from memory instead, but probably won't, because that would bring no benefit. The second line writes to the memory location that your...
661,481
661,495
Nested struct in templated class with std::map::const_iterator?
The folowing code generates a syntax error at the line where the iterator is declared: template <typename T> class A { public: struct B { int x, y, z; }; void a() { std::map<int, B>::const_iterator itr; // error: ; expected before itr } std::vector<T> v; std::map<int,...
You need a typename: typename std::map<int, B>::const_iterator itr; The iterator is a dependant type (depends on B) and when you have this situation the compiler requires you to clarify it with a typename. There is a reasonable discussion of the issue here.
661,617
661,737
Is there a better way to design this message passing code?
class A was using below two functions to build and send messages 1 & 2 builder::prepareAndDeliverMsg1(msg1_arg1,msg1_arg2) { } builder::prepareAndDeliverMsg2(msg2_arg1,msg2_arg2) { } Now, a new class B is introduced, which would like to do what A was doing in two stages stage1->prepare stage2->deliver I was thinking...
To expand on Darks idea you can have a base class that implements the combined prepare and delivers in terms of the separate functions and allows deriving classes to override those as required: class base { virtual bool prepareMsg1() = 0; virtual bool prepareMsg2() = 0; virtual bool deliverMsg1() = 0; v...
661,862
661,983
C++ Memory Management for Texture Streaming in Videogames
this is a "hard" question. I've found nothing interesting over the web. I'm developing a Memory Management module for my company. We develop games for next-gen consoles (Xbox 360, PS3 and PC... we consider PC a console!). We'll need in future, for our next games, to handle texture streaming for large game worlds that c...
I did a lot of study recently regarding memory management and this is the most informative and helpful article I found on the net. http://www.ibm.com/developerworks/linux/library/l-memory/ Based on that paper the best and fastest result you will get is to divide your 64 MB into equal sized chunks. The size of chunks wi...
661,907
664,970
VC++ : How to prevent esc from closing a dialog box (not mfc)
How could I prevent esc from closing a dialog box? I searched for this topic, but all I found was for MFC (You can overwrite PreTranslateMessage function in MFC). but my program is written in Windows API, not MFC. I tried to catch all Keyboard messages in Dialog procedure, but none of them works. I also tried using sub...
You can determine whether it's from the system menu easily enough -- check out the "return value" section of this MSDN page to see how. If you can't determine whether it's from the ESCAPE key or a button, you could always get around that by using a different identifier for your Cancel button.
662,084
662,095
What's the difference between the WIN32 and _WIN32 defines in C++
I know that WIN32 denotes win32 compilation but what is _WIN32 used for?
WIN32 is a name that you could use and even define in your own code and so might clash with Microsoft's usage. _WIN32 is a name that is reserved for the implementor (in this case Microsoft) because it begins with an underscore and an uppercase letter - you are not allowed to define reserved names in your own code, so t...
662,328
662,356
What is a simple C or C++ TCP server and client example?
I need to quickly implement a very small C or C++ TCP server/client solution. This is simply to transfer literally an array of bytes from one computer to another - doesn't need to be scalable / over-complicated. The simpler the better. Quick and dirty if you can. I tried to use the code from this tutorial, but I couldn...
I've used Beej's Guide to Network Programming in the past. It's in C, not C++, but the examples are good. Go directly to section 6 for the simple client and server example programs.
662,378
662,408
Error in returning a pointer from a function that points to an array
I'm in a bit of a fiddle in that I don't know why my code brings up the following error when compiling: 1>..\SA.cpp(81) : error C2664: 'CFE' : cannot convert parameter 1 from 'int' to 'int []' 1> Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast Essenti...
Where does Energy come from? If it's a double[] then you can't just cast it to an int*. std::vector<int> is guaranteed to be contiguous, so if you want to convert a std::vector<int> VectorName to an const int* use &VectorName[0]. If, on the other hand, your CFE function modifies the array is passed, it's probably bette...
662,440
662,614
Palette Animation in OpenGL
I am making an old-school 2d game, and I want to animate a specific color in my texture. Only ways I know are: opengl shaders. animating one color channel only. white texture under the color-animated texture. But I don't want to use shaders, I want to make this game as simple as possible, not many extra openGL functi...
How about just using paletted textures? There are extensions to do just that. If using extensions is out of question you can just make palette handling by your own. Just do your palette tricks, there are lot of them, and just write RGB texture using palette. Ofcourse this limits number of colors, but thats whole point ...
662,845
662,922
Why is std::for_each a non-modifying sequence operation?
I just read in the C++ standard that std::for_each is a non-modifying sequence operation, along with find, search and so on. Does that mean that the function applied to each element should not modify them? Why is that? What could possibly go wrong? Here is a sample code, where the sequence is modified. Can you see anyt...
See this defect report they say The LWG believes that nothing in the standard prohibits function objects that modify the sequence elements. The problem is that for_each is in a secion entitled "nonmutating algorithms", and the title may be confusing. A nonnormative note should clarify that. But also note this one. T...
662,918
662,936
How do I concatenate multiple C++ strings on one line?
C# has a syntax feature where you can concatenate many data types together on 1 line. string s = new String(); s += "Hello world, " + myInt + niceToSeeYouString; s += someChar1 + interestingDecimal + someChar2; What would be the equivalent in C++? As far as I can see, you'd have to do it all on separate lines as it do...
#include <sstream> #include <string> std::stringstream ss; ss << "Hello, world, " << myInt << niceToSeeYouString; std::string s = ss.str(); Take a look at this Guru Of The Week article from Herb Sutter: The String Formatters of Manor Farm
662,976
662,981
How do I convert from stringstream to string in C++?
How do I convert from std::stringstream to std::string in C++? Do I need to call a method on the string stream?
​​​​​​​ yourStringStream.str()
663,071
663,114
Stopping a thread in Win32/MFC
I was reading through some threading related code and found this piece of code: MyThread::start() { //Create a thread m_pThread = AfxBeginThread(/*some parameters*/) //Create a duplicate handle for the created thread m_hDuplicateHandle = DuplicateHandle(/* some more parameters*/) } MyThread::stop() { //Set ...
AfxBeginThread returns a CWinThread* and MFC assumes it will be managing the handle associated with the thread. So in order to safely use the handle directly you need to duplicate it, otherwise when the thread ends MFC may have closed the handle before you get to the WaitForSingleObject call. If you were working direc...
663,072
663,091
How to catch an exception thrown in a critical section?
I'm working on win 32 multithreading with c++. Scenario: I have a function used by multiple threads. This function as a critical sections (or any kind of construct that can lock a resource). In the critical section an exception is thrown. At this point I need to take care of unlocking the resource in the exception catc...
The idea is to encapsulate the act of acquiring and releasing the critical section in an object such that constructing the object acquires the CS and destroying the object releases it. struct CSHolder { explicit CSHolder(CRITICAL_SECTION& cs): lock(cs) { ::EnterCriticalSection(&lock); } ~CSHolder() ...
663,145
663,164
Any library that overloaded boolean operators?
Have you ever seen any library/code that overloaded boolean operators, which is said to be evil? and What advantages does it give to the user?
The standard library itself overloads operator ! for input streams, so perhaps "evil" is a touch strong? But I suspect that you were talking about && and ||. The reason for not overlaoding these is that their short-circuting abilities cannot be duplicated in the user defined overloads, and no I am not aware of any lib...
663,209
664,401
Can someone explain about Linux library naming?
When I create a library on Linux, I use this method: Build: libhelloworld.so.1.0.0 Link: libhelloworld.so.1.0.0 libhelloworld.so Link: libhelloworld.so.1.0.0 libhelloworld.so.1 The versioning is so that if you change the public facing methods, you can build to libhelloworld.so.2.0.0 for example (and leave 1.0.0 where...
From an old email I sent to a colleague about this question: Let's look at libxml as an example. First of all, shared objects are stored in /usr/lib with a series of symlinks to represent the version of the library availiable: lrwxrwxrwx 1 root root 16 Apr 4 2002 libxml.so -> libxml.so.1.8.14 lrwxrwxrwx 1 root r...
663,280
663,334
What's the advantage of this indirect function call?
I found the following code in a library: class Bar { public: bool foo(int i) { return foo_(i); } private: virtual bool foo_(int i) = 0; }; Now I'm wondering: Why would you use this indirection? Could there be any reasons why the above would be better than the simple alternative: class Bar { public: virtual ...
This is the Non-Virtual Interface Idiom (NVI). That page by Herb Sutter has a good bit of detail about it. However, temper what you read there with what the C++ FAQ Lite says here and here. The primary advantage of NVI is separating interface from implementation. A base class can implement a generic algorithm and pr...
663,326
663,348
if (!this) { return false; }
I stumbled upon this piece of code which seems totaly broken to me, but it does happen that this is null. I just don't get how this can be null it is inside a normal method call such as myObject->func(); inside MyObject::func() we have if (!this) { return false; } is there any way I can have the first line to throw a...
If you have: MyObject *o = NULL; o->func(); What happens next depends on whether func is virtual. If it is, then it will crash, because it needs an object to get the vtable from. But if it's not virtual the call proceeds with the this pointer set to NULL. I believe the standard says this is "undefined behaviour", so ...
663,447
663,577
Getting Started with OLE - What's a good learning project choice?
I suspect that I will shortly have a need to write an "integration" library that will need to call an OLE object on Windows from Java. I have done Java to C/C++ integration on windows before (using C/C++ and JNI) - so I'm not new to that part of the equation. However; I'd like to try out writing a C/C++ wrapper around ...
Yes, you can do OLE with VC++ Express, I'd recommend to install Windows Platform SDK. You don't need MFC to use office applications. With VC++ Express 2005 you can install the older version of Platform SDK 2003 R1 which includes ATL, which are convenient wrappers around COM functionality. If you can't install it you c...
663,449
663,502
What is the best way to attach a debugger to a process in VC++ at just the right point in time?
When debugging, sometimes you need to attach an already running process instead of just starting the application in a debugger. It's common for myself to put in a Sleep() or MessageBox call, so that it's easier to attach a debugger. I worry that some of these may be committed eventually to source control. What is the...
you can use DebugBreak, check these links: http://www.epsilon-delta.net/articles/vc6_debug.html#breaking-with-debugbreak http://blogs.msdn.com/calvin_hsia/archive/2006/08/25/724572.aspx
663,546
663,809
can one make concurrent scalable reliable programs in C as in erlang?
a theoretical question. After reading Armstrongs 'programming erlang' book I was wondering the following: It will take some time to learn Erlang. Let alone master it. It really is fundamentally different in a lot of respects. So my question: Is it possible to write 'like erlang' or with some 'erlang like framework', wh...
Yes, it is possible, but... Probably the best answer for this question is given by Robert Virding’s First Rule: “Any sufficiently complicated concurrent program in another language contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Erlang.” Very good rule is use the right too...
663,624
663,685
What is the best practice for a shared library primary header file in C++?
When I create shared libraries, I have a header file (but with no file name extension) in the root of the library source named the same as the library. So for example, if my library was called libirock.so, then I'd have a file called irock in the project root. This file will include all of the most important headers in...
There is nothing in the standard governing "allowed", "prohibited" or "best practices" regarding extensions for filenames. Use whichever form you prefer. On some platforms there's a convenience factor to having an file extensions for registered types. For what it's worth <string.h> and <string> are totally different he...
663,724
663,775
wrong argument conversion preferred when calling function
I'm writing a program under MS Visual C++ 6.0 (yes, I know it's ancient, no there's nothing I can do to upgrade). I'm seeing some behavior that I think is really weird. I have a class with two constructors defined like this: class MyClass { public: explicit MyClass(bool bAbsolute = true, bool bLocation = false) :...
Explicit will not help here as the constructor is not a part of the implicit conversion, just the recipient. There's no way to control the preferred order of conversions, but you could add a second constructor that took a const char*. E.g: class MyClass { public: MyClass(bool bAbsolute = true, bool bLocation = fals...
663,811
664,183
Why do I get the "unrecognised emulation mode: 32" error in Eclipse?
How come I get this error when compiling with the -m32 argument? unrecognised emulation mode: 32 I'm compiling using g++ on an x86_64 machine. It happens in one project, but not the other... Any hints? Note: I'm using Eclipse CDT, so perhaps this is an IDE specific gocha? Rephrased question Perhaps a better question ...
It seems that in Eclipse, you must specify -m32 in the miscelanious linker options, if it's specified in the compiler options. The "unrecognised emulation mode: 32" error message appears when your reference a library path that doesn't exist - which is weird!
663,870
663,889
c++ class why need main?
Hello I'm writing a little project in c++ where I would like to have some classes that does some work, I wrote the interfaces and the implementation of the classes. The thing that surprises me is that I cannot have a simple class without a main(), I would like to have a class that once instantiated, It's methods can be...
but I don't need (nor want) a main() in the class implementation. The function main is your entry-point. That is where execution begins. You need to have one and only one such function. But compiler give me "undefined reference to main" for animal.cpp, but I don't need a main there, or do I need it? Now, your probl...
664,123
664,134
'default' as a variable name
While debugging some code, I came across an array named default. I thought that keywords were not allowed as variable names. #include "stdafx.h" #include <stdio.h> int main() { int default = 5; printf("%d\n", default); return 0; } Now the above code compiles without a hitch on VS 2008. Isn't 'default' a keyword? H...
It's a known issue in VC++. Basically by-design for C++/CLI compatibility.
664,273
664,289
Boost lambda bewilderment
Why is callback called once only? bool callback() { static bool res = false; res = !res; return res; } int main(int argc, char* argv[]) { vector<int> x(10); bool result=false; for_each(x.begin(),x.end(),var(result)=var(result)||bind(callback)); return 0; }
The || expression short circuits after the first time bind returns true. The first time you evaluate result = result || bind(...) // result is false at this point bind is called, because that's the only way to determine the value of false || bind(...). Because bind(...) returns true, result is set to true. Every oth...
664,320
664,361
Can I pass C++ strings into a method in the style of a stream?
I'd like to do this: MyClass mc = MyClass("Some string" << anotherString); Thanks for your answers, I have decided to re-write this question based on what you've told me, as it's gotten a little messy. Eventually, I read C++ format macro / inline ostringstream, and decided to use a macro, as it's not really possible t...
I think you should look at this question for some hints as to what will be required to get the behavior you want. This sort of thing seems to a bit difficult.
664,698
664,775
How to I draw pixels as a texture to a polygon in OpenGL?
In C++ OpenGL, I want to draw each pixel manually (as a texture I assume) on to a simple square primitive, or indeed 2 polygons forming a square. I have no idea where to start, or what phrases to look for. Am I looking for texture mapping or creating textures? Most examples are to load from a file, but I dont want to d...
Take a close look at glTexImage2D. This is the call that loads the image in OpenGL for a 2D Texture. glTexImage2D actually takes a raw pointer to the pixel data in the image. You can allocate memory yourself, and set the image data directly (however you want), then call this function to pass the image to OpenGL. Once...
665,112
665,147
How the buffer of cout work?
I know that cout have buffer several days ago, and when I google it, it is said that the buffer is some like a stack and get the output of cout and printf from right to left, then put them out(to the console or file)from top to bottem. Like this, a = 1; b = 2; c = 3; cout<<a<<b<<c<<endl; buffer:|3|2|1|<- (take “<-” a...
You are mixing a lot of things. To date: Implementation details of cout Chained calls Calling conventions Try to read up on them separately. And don't think about all of them in one go. printf("i=%d i++=%d i--=%d\n" , i , i++ ,i-- ); The above line invokes undefined behavior. Read the FAQ 3.2. Note, what you obser...
665,509
7,857,736
Redirecting standard output to syslog
I'm planning to package OpenTibia Server for Debian. One of the things I want to do is add startup via /etc/init.d and daemonization of the otserv process. Thing is, we should probably redirect output to syslog. This is usually done via the syslog() function. Currently, the code is swarmed with: std::cout << "Stuff to ...
Not sure whether a straight "C" answer suffices; but in "C" you can use underlying stdio features to plug the (FILE*) directly into syslog calls, without an intervening "logger" process. Check out http://mischasan.wordpress.com/2011/05/25/redirecting-stderr-to-syslog/