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
525,903
525,904
Opening a file with std::string
This should be a fairly trivial problem. I'm trying to open an ofstream using a std::string (or std::wstring) and having problems getting this to work without a messy conversion. std::string path = ".../file.txt"; ofstream output; output.open(path); Ideally I don't want to have to convert this by hand or involve c-style char pointers if there's a nicer way of doing this?
In the path string, use two dots instead of three. Also you may use 'c_str()' method on string to get the underlying C string. output.open(path.c_str());
525,926
526,398
Window message procedures in Linux vs Windows
In Windows when you create a window, you must define a (c++) LRESULT CALLBACK message_proc(HWND Handle, UINT Message, WPARAM WParam, LPARAM LParam); to handle all the messages sent from the OS to the window, like keypresses and such. Im looking to do some reading on how the same system works in Linux. Maybe it is because I fall a bit short on the terminology but I fail to find anything on this through google (although Im sure there must be plenty!). Is it still just one single C function that handles all the communication? Does the function definition differ on different WMs (Gnome, KDE) or is it handled on a lower level in the OS? Edit: Ive looked into tools like QT and WxWidgets, but those frameworks seems to be geared more towards developing GUI extensive applications. Im rather looking for a way to create a basic window (restrict resize, borders/decorations) for my OGL graphics and retrieve input on more than one platform. And according to my initial research, this kind of function is the only way to retrieve that input. What would be the best route? Reading up, learning and then use QT or WxWidgets? Or learning how the systems work and implement those few basic features I want myself?
In principle it is absolutely the same. However, it has nothing to do with communication with the OS (nor does it on win32, using user32.dll is entirely optional) A GUI application has an event loop somewhere, which processes messages from a queue at some level. There are a lot of libraries typically used to "hide" this behaviour - you can use them (and indeed, you should). If anything, the Xlib event system is even more perverse than Win32's user32.dll one, and is less widely understood, therefore fewer people use it directly. In Linux or in Windows, applications can use the low-level GUI, or can use a library. Most use a library. Applications can also choose to do neither and operate without a GUI (server applications typically do this). Applications can create multiple threads, one of which sits in an event loop, and others work differently. This is a popular approach too. Most GUI applications use a higher level library for their GUI Non-interactive applications, e.g. server applications, don't use the GUI at all and don't use the libraries (e.g. XLib, user32.dll) Applications which don't lend themselves to an "Event loop" (e.g. Games) typically use a separate thread to process their event loop. These things are largely true on Win32 and Linux.
525,934
525,952
Memory Allocation in std::map
I am doing a report on the various C++ dictionary implementations (map, dictionary, vectors etc). The results for insertions using a std::map illustrate that that the performance is O(log n). There are also consistent spikes in the performance. I am not 100% sure what's causing this; I think they are caused by memory allocation but I have been unsuccessful in finding any literature / documentation to prove this. Can anyone clear this matter up or point me in the right direction? Cheers.
You are right: it is O(log n) complexity. But this is due to the sorted nature of map (normally binary tree based). Also see http://www.sgi.com/tech/stl/UniqueSortedAssociativeContainer.html there is a note on insert. It’s worst case is O(log n) and amortized O(1) if you can hint where to do the insert. Maps are normally based on binary trees and need to be balanced to keep good performance. The load spikes you are observing probably correspond to this balancing process
526,270
526,682
Standard behavior of tellp on empty ostringstream
I have a question on the standard behavior of calling tellp on an empty ostringstream. I have a function foo which calls tellp the first thing: void foo(std::ostream& os) { std::ostream::pos_type pos = os.tellp(); // do some stuff. } int main() { std::ostringstream os; foo(os); } In Visual Studio 2005, calling this function with a newly created and empty ostringstream results in the pos variable to be set to an invalid pos_type, which in Visual Studio 2005 is set to pos_type(_BADOFF). ofstream does not have the same behavior, where tellp returns pos_type(0), which is a valid pos_type. Is this standard conforming behavior? Is this behavior consistent with other compilers?
27.6.2.4: pos_type tellp(); Returns: if fail() != false, returns pos_type(-1) to indicate failure. Otherwise, returns rdbuf()->pubseekoff(0, cur, out). And pubseekoff returns -1 on fail. But am not sure why this happens for you in the case of ostringstream, maybe was too tired to find the words about undefined or implementation-dependent. Using my common sense I would say that for ostringstream this should give 0, for default constructed ostream -1, and for ostream with freshly opened file 0.
526,474
526,480
Using C code from C++ using autotools
I am writing a (my first) C++ class on top of some code written in C, but I can only get the C++ to compile by declaring the C functions in a extern block. My project uses autotools; is there any way to automate this process so I don't have to maintain two header files?
Yes create wrapper header files which include your C header files like so... //Wrapper.h #ifdef __cplusplus extern "C" { #include "Actual.h" } #else #include "Actual.h" #endif //Use.cpp #include "Wrapper.h" int main() { return 0; } //Use.c #include "Wrapper.h" /*or #include "Actual.h" */ int main() { return 0; }
526,583
527,138
modify an open file c++
Under Windows is there a way to modify a file/executable opened by another process using c++?
The OS holds the executable file open for read-only sharing as long as it's running, so there's no way to modify it directly. You can, however, open it for reading (if you specify read-sharing in your CreateFile call), and make a modified copy of it, while it's running. I don't know if that's what you had in mind, but if it's your own program you're doing this to, you can start the new copy and have it pick up where the previous one left off... not straightforward, but not all that difficult either.
526,761
528,902
Set QLineEdit focus in Qt
I am having a qt question. I want the QLineEdit widget to have the focus at application startup. Take the following code for example: #include <QtGui/QApplication> #include <QtGui/QHBoxLayout> #include <QtGui/QPushButton> #include <QtGui/QLineEdit> #include <QtGui/QFont> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget *window = new QWidget(); window->setWindowIcon(QIcon("qtest16.ico")); window->setWindowTitle("QtTest"); QHBoxLayout *layout = new QHBoxLayout(window); // Add some widgets. QLineEdit *line = new QLineEdit(); QPushButton *hello = new QPushButton(window); hello->setText("Select all"); hello->resize(150, 25); hello->setFont(QFont("Droid Sans Mono", 12, QFont::Normal)); // Add the widgets to the layout. layout->addWidget(line); layout->addWidget(hello); line->setFocus(); QObject::connect(hello, SIGNAL(clicked()), line, SLOT(selectAll())); QObject::connect(line, SIGNAL(returnPressed()), line, SLOT(selectAll())); window->show(); return app.exec(); } Why does line->setFocus() sets the focus on the line widget @app startup only if it is placed after laying out the widgets and if used before it's not working?
Keyboard focus is related to widget tab order, and the default tab order is based on the order in which widgets are constructed. Therefore, creating more widgets changes the keyboard focus. That is why you must make the QWidget::setFocus call last. I would consider using a sub-class of QWidget for your main window that overrides the showEvent virtual function and then sets keyboard focus to the lineEdit. This will have the effect of always giving the lineEdit focus when the window is shown.
526,797
526,893
Good tools for creating a C/C++ parser/analyzer
What are some good tools for getting a quick start for parsing and analyzing C/C++ code? In particular, I'm looking for open source tools that handle the C/C++ preprocessor and language. Preferably, these tools would use lex/yacc (or flex/bison) for the grammar, and not be too complicated. They should handle the latest ANSI C/C++ definitions. Here's what I've found so far, but haven't looked at them in detail (thoughts?): CScope - Old-school C analyzer. Doesn't seem to do a full parse, though. Described as a glorified 'grep' for finding C functions. GCC - Everybody's favorite open source compiler. Very complicated, but seems to do it all. There's a related project for creating GCC extensions called GEM, but hasn't been updated since GCC 4.1 (2006). PUMA - The PUre MAnipulator. (from the page: "The intention of this project is to provide a library of classes for the analysis and manipulation of C/C++ sources. For this purpose PUMA provides classes for scanning, parsing and of course manipulating C/C++ sources."). This looks promising, but hasn't been updated since 2001. Apparently PUMA has been incorporated into AspectC++, but even this project hasn't been updated since 2006. Various C/C++ raw grammars. You can get c-c++-grammars-1.2.tar.gz, but this has been unmaintained since 1997. A little Google searching pulls up other basic lex/yacc grammars that could serve as a starting place. Any others? I'm hoping to use this as a starting point for translating C/C++ source into a new toy language. Thanks! -Matt (Added 2/9): Just a clarification: I want to extract semantic information from the preprocessor in addition to the C/C++ code itself. I don't want "#define foo 42" to disappear into the integer "42", but remain attached to the name "foo". This, unfortunately, excludes several solutions that run the preprocessor first and only deliver the C/C++ parse tree)
Parsing C++ is extremely hard because the grammar is undecidable. To quote Yossi Kreinin: Outstandingly complicated grammar "Outstandingly" should be interpreted literally, because all popular languages have context-free (or "nearly" context-free) grammars, while C++ has undecidable grammar. If you like compilers and parsers, you probably know what this means. If you're not into this kind of thing, there's a simple example showing the problem with parsing C++: is AA BB(CC); an object definition or a function declaration? It turns out that the answer depends heavily on the code before the statement - the "context". This shows (on an intuitive level) that the C++ grammar is quite context-sensitive.
526,855
526,872
How should I deploy an MFC application?
I created an application in VS 2008 Express as an MFC app just to take advantage of the easy GUI creation. I might re-do this app in pure win32 since no other MFC classes are used (just a button and a text box, the button fires off the main program, all win32). My only question that determines whether I stay in MFC or port it over to pure win32 is this: How difficult is it to deploy an MFC app? What do I need to do (in VS 2008) to make sure it works on another machine?
Statically link MFC and it's just another .exe. You can just give that to the user or create an installer with either the microsoft .msi tool or a regular setup.exe with something like innosetup. Edit - the error message in your comment is about another dll that is part of a 3rd party library. You can't (easily) take a DLL and incorporate it into your app. the licensing may also require you to ship their DLL as a separate lib.
527,166
527,179
Creating a new vector using a transform
I have a vector of integers and I want to convert it to a vector of pairs (pair consists of a bool and a int). My current code is simple like this: std::vector<int> a; std::vector<std::pair<bool,int> > b; a.push_back(1); a.push_back(2); a.push_back(3); for(int i = 0; i < a.size(); ++i) { b.push_back(std::make_pair(false, a[i])); } Is there any way to do this without writing the loop myself? Probably using some algorithms?
1. You could make a functor and std::for_each: struct F { F(std::vector<std::pair<bool,int> > &b) : m_b(b){ } void operator()(int x) { m_b.push_back(std::make_pair(false, x)); } std::vector<std::pair<bool,int> > &m_b; }; std::for_each(a.begin(), a.end(), F(b)); Though this may prove to be more trouble than it's worth. But at least it would be reusable :). Maybe there is something that could be done with boost::bind. 2. EDIT: I was thinking you might be able to use bind with a back inserter and transform. something like this: std::transform(a.begin(), a.end(), std::back_inserter(b), boost::bind(std::make_pair<bool, int>, false, _1)); I tried this with std::bind1st, i thought it should have worked, but i could only get it to succeed with boost::bind. I'll keep trying... 3. EDIT: here's a non-boost solution: std::transform(a.begin(), a.end(), std::back_inserter(b), std::bind1st(std::ptr_fun(std::make_pair<bool, int>), false)); 4. EDIT: here's a C++11 solution (which is my current favorite): std::for_each(begin(a), end(a), [&b](int v) { b.emplace_back(false, v); }); or even simpler: for(int v : a) { b.emplace_back(false, v); }
527,413
527,983
how boost::function and boost::bind work
I dislike having magic boxes scattered all over my code...how exactly do these two classes work to allow basically any function to be mapped to a function object even if the function<> has a completely different parameter set to the one im passing to boost::bind It even works with different calling conventions (i.e. member methods are __thiscall under VC, but "normal" functions are generally __cdecl or __stdcall for those that need to be compatible with C.
boost::function allows anything with an operator() with the right signature to be bound as the parameter, and the result of your bind can be called with a parameter int, so it can be bound to function<void(int)>. This is how it works (this description applies alike for std::function): boost::bind(&klass::member, instance, 0, _1) returns an object like this struct unspecified_type { ... some members ... return_type operator()(int i) const { return instance->*&klass::member(0, i); } where the return_type and int are inferred from the signature of klass::member, and the function pointer and bound parameter are in fact stored in the object, but that's not important Now, boost::function doesn't do any type checking: It will take any object and any signature you provide in its template parameter, and create an object that's callable according to your signature and calls the object. If that's impossible, it's a compile error. boost::function is actually an object like this: template <class Sig> class function { function_impl<Sig>* f; public: return_type operator()(argument_type arg0) const { return (*f)(arg0); } }; where the return_type and argument_type are extracted from Sig, and f is dynamically allocated on the heap. That's needed to allow completely unrelated objects with different sizes bind to boost::function. function_impl is just an abstract class template <class Sig> class function_impl { public: virtual return_type operator()(argument_type arg0) const=0; }; The class that does all the work, is a concrete class derived from boost::function. There is one for each type of object you assign to boost::function template <class Sig, class Object> class function_impl_concrete : public function_impl<Sig> { Object o public: virtual return_type operator()(argument_type arg0) const=0 { return o(arg0); } }; That means in your case, the assignment to boost function: instantiates a type function_impl_concrete<void(int), unspecified_type> (that's compile time, of course) creates a new object of that type on the heap assigns this object to the f member of boost::function When you call the function object, it calls the virtual function of its implementation object, which will direct the call to your original function. DISCLAIMER: Note that the names in this explanation are deliberately made up. Any resemblance to real persons or characters ... you know it. The purpose was to illustrate the principles.
527,663
527,670
Optimising Iterator Definitions
This is a (hopefully) really simple question - I have been told recently that using C++ style initialisation is better than traditional (and more common) assignment. So this code: std::SomeSTLContainer::const_iterator it = container.begin(); std::SomeSTLContainer::const_iterator itEnd = container.end(); would be 'slower' or less efficient than: std::SomeSTLContainer::const_iterator it ( container.begin() ); std::SomeSTLContainer::const_iterator itEnd ( container.end() ); I understand the reason for this - the first example causes default construction and initialisation then subsequent assignment rather than specific construction and direct assignment in the second example. However, on modern processors / compilers, does it really make a difference?
I have been told recently that using C++ style initialisation is better than traditional (and more common) assignment. This is simply wrong. I understand the reason for this - the first example causes default construction and initialisation then subsequent assignment rather than specific construction and direct assignment in the second example. However, on modern processors / compilers, does it really make a difference? No, it doesn't make a difference. The C++ standard explicitly allows the assignment in that case to be omitted so that the same code will be produced. In practice, all modern C++ compilers do this. Additionally, Charles is right: this would never call the assignment operator but rather the copy constructor. But as I've said, even this doesn't happen.
527,700
527,736
What is a good desktop programming language to learn for a web developer?
I'm want to learn a desktop programming language, preferably C, C++ or C#. I'm a PHP/HTML/CSS programmer and I would like to get into desktop applications. I need something pretty powerful and I would like to be able to create applications with Windows GUI's. What would the Stack Overflow community recommend? Is there any knowledge I should have before diving into these languages?
edit: A web programmer wants to create Windows applications and you recommend C? What's wrong with you people?! /edit Obviously C#. C# will be easier to get into and will let you build Windows applications using WinForms or WPF and all the new Microsoft toys in .NET. If you know your way around PHP, you should already be familiar with the syntax, object oriented concepts, exception handling, etc. I suggest you don't complicate your life with C and definitely not with C++ if all you want is to create Windows GUIs. They do provide a good educational experience and they are useful for more advanced things (cross platform development using other toolkits for instance) but at the price of a steeper learning curve and reduced productivity. Also, if you are a web developer, C# is the only language among the 3 options that you can (realistically, heh) use for the web. ASP.NET is not a bad framework and might be worth investigating too.
527,742
527,788
Overloading operator<< for primitive types. Is that possible?
Hey. Is it possible to overload operator<< for primitive types? Fx lets say that I want to write a std::endl each time want to write a int. Can I overload operator<< for int, so that it automatic puts a std::endl to the output? I have tried with this, std::ostream& operator<<(std::ostream& strm, int & i) { strm << i << std::endl; return strm; } but it doesn't work. I cant recall the compiler error message, but I think that I'm getting operator overloading all wrong any ways. I try to call the above overloaded operator<< in this way, int main() { int i = 2; std::out<<"Here is an int " << i; return 0; } But it doesn't work at all. Maybe I can't overload POD types?
As zabzonk said, the standard library provides an (ostream&, int) overload so you can't define another. To simulate what you were doing (though it is completely pointless in its present form :) : class EndlinedInteger { public: EndlinedInteger(int i) : i(i) { } friend ostream& operator<<(ostream&, EndlinedInteger const&); private: int i; }; ostream& operator<<(ostream& out, EndlinedInteger const& ei) { out << ei.i << endl; return out; } int main() { EndlinedInteger i = 2; std::cout<<"Here is an int " << i; }
527,887
527,897
C/C++ optimize data structures, array of arrays or just array
Working with a program that uses 16bytes 4v4 one byte matrices : unsigned char matrix[4][4]; and a few 256bytes 16v16 one byte matrices: unsigned char bigMatrix[16][16]; Very often due to data manipulation I am forced to loop column wise in the program making cache misses. Will the performance improve if I use an array instead, i.e. unsigned char matrix[16]; unsigned char matrix[256]; and access the elements by using some variables to retrieve elements, i.e. matrix[variableA*variableB + i]; where variableA*variableB+i needs to be recalculated every time I want to access an element. I only want speed optimization and memory is of no problem. Will this help, as in give some performance hit or loss, or is the difference too small to even care ?
It makes no difference. The data is laid out in the exact same way in either case, and is accessed in the same way too. I'd be surprised if it didn't generate exactly the same assembly, even. However, with a 256byte table, you're unlikely to get cache misses in any case. The CPU's L1 cache is typically between 32 and 128KB, so I doubt you're getting many cache misses in any case.
527,999
529,022
Is it OK to use C-style cast for built-in types?
After reading here a lot of answers about C-style casting in C++ I still have one little question. Can I use C-style casting for built-in types like long x=(long)y; or it's still considered bad and dangerous?
I would not, for the following reasons: Casts are ugly and should be ugly and stand out in your code, and be findable using grep and similar tools. "Always use C++ casts" is a simple rule that is much more likely to be remembered and followed than, "Use C++ casts on user-defined types, but it's OK to use C-style casts on built-in types." C++ style casts provide more information to other developers about why the cast is necessary. C-style casts may let you do conversions you didn't intend -- if you have an interface that takes in (int*) and you were using c-style casts to pass it a const int*, and the interface changes to take in a long*, your code using c-style casts will continue to work, even if it's not what you wanted.
528,107
528,374
Is it possible to use boost library in visual studio 2008 64 bit version?
I tried to use boost library in 64 bit mode of VS2008 but I'm getting "header file not found" errors. is it any possible to use boost library under 64 bit mode of VS2008? it worked fine in 32 bit mode. that's why I'm suspicuous bout 64 but ;( Or anybody have good link to show setting up 64 bit mode to use boost? thanks
Boost works fine with VS2008. Are you sure you have your include paths set up correctly? I usually a reference to the boost libraries to the Options|Projects and Solutions|VC++ Directories settings. Make sure you set the "Include Files" setting for both win32 and x64. Most of the libraries are header only and it doesn't matter if you're building 32-bit or 64-bit.
528,117
528,125
Compiler Error with const function
I am not sure whether I am missing something basic. But I am unable to understand why the compiler is generating the error for this code: class A { }; class B { public: B(); A* get() const; private: A* m_p; }; B::B() { m_p = new A; } A* B::get() const { //This is compiling fine return m_p; } class C { public: A* get() const; private: A m_a; }; A* C::get() const { //Compiler generates an error for this. Why? return &m_a; } EDIT: The compiler error is : error C2440: 'return' : cannot convert from 'const class A *' to 'class A *' Conversion loses qualifiers
const in the function signature tells the compiler that the object's members may not be modified. Yet you return a non-const pointer to a member, thus allowing a violation of that promise. In your class B, you make/break no promise since you don't return a pointer to a member, you return a copy of it (and the member happens to be a pointer).
528,409
528,974
customizing assert macro
On Windows/c++, I want to customize the assert dialog box to ignore an assertion forever, so I can be more aggressive with assertions. I understand how hard it is to write a correct assert macro, and do not wish to do this, just hook the dialog code. Is there an easy way (or concise hack) to do this? article on assert macro dangers (googlecache) update: more aggressive => use far more frequently and for noncrash bugs. I want to be able to ignore an assertion forever so if a minor bug assertion occurs in a loop it doesn't effectively halt my process.
Look into the _CrtSetReportHook function or the newer _CrtSetReportHook2. You can use it to install a hook that remembers "seen" messages, and reports them as handled when seen again.
528,494
713,682
Use domain-specific-language files inside C++ project
I am developping a DSL with its own graphical editor. Such files have a .own extension. I also have a small tool that compiles .own files into .h files. X.own --> X.h and X/*.h I have written a simple .rules file to launch the generation. My problem is the following : Most of my source files include X.h, but a change in X.own does not mean the generated X.h (or any other generated file) will be different. This is dealt with by the generator through the use of temporary files and file comparison. But Visual Studio does not seem to know how to deal with all this. If i set the "output file(s)" property to the right file(s), it always assumes they will be changed. If i don't, it generates its build process assuming they won't be ! How can i make things right ? 1) Launch custom build tool 2) Compute build process based on dependencies
jheriko's answer is interesting, because it provides a way to launch custom tool, then generate build dependencies. But it's not very usable, because you then lose all possibilities to use "custom build tools" toolkit, in which you can choose to always compile files with some precise extension manually skip custom build for a particular file in a particular project configuration (and visualize this decision) There is no way (or at least i have found none) to "have it all". The only way i have found is to have the custom build tool return a non-zero number when files have been updated, with a message to the user explaining that it is not an error and inviting him to launch build again. The next time, custom build tool is launched again (not optimal, but the tool i use is pretty fast) but modifies no new file, and build process goes on, using valid dependencies. Note : the approach described above does not work with Incredibuild, which seems to ignore project build order.
528,559
528,588
C/C++ best way to send a number of bytes to stdout
Profiling my program and the function print is taking a lot of time to perform. How can I send "raw" byte output directly to stdout instead of using fwrite, and making it faster (need to send all 9bytes in the print() at the same time to the stdout) ? void print(){ unsigned char temp[9]; temp[0] = matrix[0][0]; temp[1] = matrix[0][1]; temp[2] = matrix[0][2]; temp[3] = matrix[1][0]; temp[4] = matrix[1][1]; temp[5] = matrix[1][2]; temp[6] = matrix[2][0]; temp[7] = matrix[2][1]; temp[8] = matrix[2][2]; fwrite(temp,1,9,stdout); } Matrix is defined globally to be a unsigned char matrix[3][3];
IO is not an inexpensive operation. It is, in fact, a blocking operation, meaning that the OS can preempt your process when you call write to allow more CPU-bound processes to run, before the IO device you're writing to completes the operation. The only lower level function you can use (if you're developing on a *nix machine), is to use the raw write function, but even then your performance will not be that much faster than it is now. Simply put: IO is expensive.
528,854
528,983
using C++ boost regex
I am not an expert in boost, though I have used ublas extensively. Recently, my supervisor asked me to build boost regex for the gcc platform. My question is: Why can't I use the regex as it is, like ublas? Please give detailed answer.
I'm assuming that by "can't use the regex as it is" you mean "without having to build it seperately". Short answer: uBLAS is "header-only" (http://www.boost.org/doc/libs?view=filtered_header-only), and Regex is not. A "header-only" library's implementation entirely resides in header (.hpp) files. To use it, one only has to #include these headers. A "non-header-only" ("normal"?) library has headers declaring the library's interface, but the implementation is in .cpp files, which are built seperately and then linked into the final executable. In Boost, the .cpp files are normally in boost/libs/<library-name>/src.
529,071
529,137
XCode automatically deactivating breakpoints
I'm using xcode in C++. I'm trying to debug my project, but at random intervals, it seems to ignore my breakpoints. There are three things that it does: 1) Sometimes, when I run, it automatically switches to "de-activate break points" mode. (the relevant button goes light and says "Activate") 2) Sometimes when I run, ALL of my breakpoints go "can't find" mode, with the yellow insides. I need to click twice on them to get them back dark blue (once to light blue = inactive, once to dark blue = active) 3) Sometimes, when I run, my breakpoint is dark blue, the button says "deactivate" and it still just ignores my breakpoint, running straight past it. This makes it very difficult to debug my program... I should add that I'm using XCode 3.1 beta on OSX 10.5.6, in case that matters. thanks.
Try unchecking the Load symbols lazy in the Debugging panel in Preferences alt text http://img.skitch.com/20090209-gj947qk7dxdyms1wij4q5em2f2.jpg
529,210
529,942
Change Properties.settings for a .net deployed application
Hi All, I have two .net applications, these applications want to talk to each other, I made a setting in the first project as follows [CompilerGeneratedAttribute()] [GeneratedCodeAttribute("SettingsSingleFileGenerator", "9.0.0.0")] public sealed partial class Settings :ApplicationSettingsBase { [UserScopedSettingAttribute()] [DebuggerNonUserCodeAttribute()] [DefaultSettingValueAttribute("False")] public bool BeginWorking { get { return ((bool)(this["BeginWorking"])); } set { this["BeginWorking"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool Result { get { return ((bool)(this["Result"])); } set { this["Result"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool Completed{ get { return ((bool)(this["Completed"])); } set { this["Completed"] = value; } } } the second project may set the BeginWorking setting for the first project in order to tell it to work, and waits for the Completed setting to be set and get the result from the Result setting. Is that possible and how?? I feel it may be not easy to answer but excuse me I'm get unable to think more. Thanks All
User level app settings are isolated in a subdirectory of AppData. One app cannot find the settings of another app. Just use a plain file.
529,284
529,344
C/C++ AQtime profiler questions
I need to profile my console program with AQ. It is in one big file (for optimizations purposes). void function1(); void function2() // etc more declarations int main{ //alot of loops, and function uses function1(); function1(); } Profiling on "Elapsed time" default profile just gives me that main is using 100% and that it took 40sec to do its job. Nothing on how much time the functions that were called inside the main took time, only how many times they were called, which says nothing. Am I missing something in configuring AQtime as I cant find it? Would like to get how much time the functions took time to do it's job..
AQtime will only profile the routines you tell it to profile. Its startup wizard is pretty helpful in terms of helping you configure this correctly; I'd recommend paying pretty careful attention to it, but the general procedure is: Create an area. Configure that area for line or routine profiling. Add source files to the area. In this case, just your one file. Now profile. The general rule is that if you don't tell AQtime to instrument the routine, it will not be instrumented. There is a default area for all code in your application, but it is for routine profiling, not line profiling, only.
529,697
529,715
How do I make a pointer to a multidimensional array which has an unknown size?
how do I make a pointer to a multidimensional array, which have a unknown size? I've tried this: int **triangles; triangles = new int[numTriangles][3]; But i get this error: cannot convert 'int (*)[3]' to 'int**' in assignment
triangles = new int[numTriangles*3]; Then access it as: triangles[numTriangles*triangleIndex+vertexIndex] = blah; But this is tedious and error prone so I suggest using boost.multi_array instead, or rolling your own (really simple): template<class T> class Matrix { public: Matrix(int _w, int _h) : data(_w*_h), w(_w), h(_h) { } T & operator()(int x, int y) { return data[y * w + x]; } T const& operator()(int x, int y) const { return data[y * w + x]; } private: std::vector<T> data; int w, h; }; // usage: int main() { Matrix<float> triangles(numTriangles, 3); triangles(triangleIndex, vertexIndex) = blah; } If, on the other hand, you actually want an array of triangles, rather than a twodimensional array, just use a vector<Triangle> where Triangle is a class :)
529,706
530,084
Using Iterator parsing with Boost::Spirit Grammars
When I attempt to use the iterator form of parsing for a Spirit grammar I get a argument passing conversion error from the iterator type to const char*. How do I fix this? There are some restrictions. I'm using an iterator adapter on large inputs, so it is not feasible for me to convert to a C style string. Here is sample code demonstrating the issue: #include <boost/spirit/core.hpp> #include <boost/spirit/iterator/file_iterator.hpp> #include <vector> #include <string> using std; using boost::spirit; struct ex : public grammar<route_grammar> { template <typename ScannerT> struct defintion { definition(ex const& self) { expression = real_p; } rule<ScannerT> expression; rule<ScannerT> const& start() const { return expression; } }; int main() { file_iterator<char> first; file_iterator<char> last = first.make_end(); ex ex_p; parse_info<file_iterator<char> > info = parse(first, last, ex_p, space_p); return 0; } This code breaks with: error: cannot convert const boost::spirit::file_iterator<char_t, boost::spirit::fileiter_impl::mmap_file_iterator<char_t> > to const char* in argument passing
Hard to tell from the code as posted, since it contains a few basic errors. After correction of these, it compiles fine on my machine (with MSVC++7.1): #include <boost/spirit/core.hpp> #include <vector> #include <string> using namespace std; using namespace boost::spirit; struct ex : public grammar<ex> { template <typename ScannerT> struct definition { definition(ex const& self) { expression = real_p; } rule<ScannerT> expression; rule<ScannerT> const& start() const { return expression; } }; }; int main() { vector<char> v; v.push_back('3'); v.push_back('.'); v.push_back('2'); ex ex_p; parse_info<vector<char>::iterator> info = parse(v.begin(), v.end(), ex_p, space_p); return 0; }
529,875
529,996
C++ Passing a dynamicly allocated 2D array by reference
This question builds off of a previously asked question: Pass by reference multidimensional array with known size I have been trying to figure out how to get my functions to play nicely with 2d array references. A simplified version of my code is: unsigned int ** initialize_BMP_array(int height, int width) { unsigned int ** bmparray; bmparray = (unsigned int **)malloc(height * sizeof(unsigned int *)); for (int i = 0; i < height; i++) { bmparray[i] = (unsigned int *)malloc(width * sizeof(unsigned int)); } for(int i = 0; i < height; i++) for(int j = 0; j < width; j++) { bmparray[i][j] = 0; } return bmparray; } I don't know how I can re-write this function so that it will work where I pass bmparray in as an empty unsigned int ** by reference so that I could allocate the space for the array in one function, and set the values in another.
Use a class to wrap it, then pass objects by reference class BMP_array { public: BMP_array(int height, int width) : buffer(NULL) { buffer = (unsigned int **)malloc(height * sizeof(unsigned int *)); for (int i = 0; i < height; i++) { buffer[i] = (unsigned int *)malloc(width * sizeof(unsigned int)); } } ~BMP_array() { // TODO: free() each buffer } unsigned int ** data() { return buffer; } private: // TODO: Hide or implement copy constructor and operator= unsigned int ** buffer };
530,244
530,725
calling C# from c++ com add-in
I have a COM add-in written in C++ (not C++ / CLI). I want to call a C# library objects/methods from this C++ com library. I guess the CCW comes into picture here, which i am currently reading about. Are there any quick pointers to this stuff from your experience? Also, i have a method in my Com add-in that i would like my C# library code to call - i.e. a method pointer invocation. Can you help telling me how i can do this please - i.e. how do i go about passing the method pointer to the C# code so it can call on it later. Thanks.
I have this links for you: COM Interop Part 1 Sample Create DCOM application from within .Net environment: Part V C++ to C# call
530,282
532,434
Do I need to create an interface for every self-created class I use in XPCOM?
I'm a noob to XPCOM development. In the course of writing XPCOM code in C++, I need to create addtional classes for use inside my XPCOM component. Do I need to create another XPCOM component for such classes? Can't I just add the new class in the header file?
No, not at all. XPCOM describes the external interface. "Internal" classes are compiled by your C++ compiler. That compiler won't snitch on you, so XPCOM will never know they exist. For your own sanity, it does make sense to keep those internal classes in their own header.
530,462
530,512
In C++ does std::multiset keep a stable sorting order?
Suppose I have two items, a and b, that compare the same. So a < b is false, and b < a is false. If these items are inserted into a std::multiset (or std::multimap) as keys, do I have any guarantees of their final sorted order? I've checked a couple of references, but I couldn't find the answer. I'm tempted to think that there are no guarantees and that it's left up to each particular implementation. Thanks.
This thread implies that it is not guaranteed by the current standard but is met by all known current implementations, and gives a link to the C++0x draft standard that includes a guarantee.
530,519
530,557
std::mktime and timezone info
I'm trying to convert a time info I reveive as a UTC string to a timestamp using std::mktime in C++. My problem is that in <ctime> / <time.h> there is no function to convert to UTC; mktime will only return the timestamp as local time. So I need to figure out the timezone offset and take it into account, but I can't find a platform-independent way that doesn't involve porting the whole code to boost::date_time. Is there some easy solution which I have overlooked?
mktime assumes that the date value is in the local time zone. Thus you can change the timezone environment variable beforehand (setenv) and get the UTC timezone. Windows tzset Can also try looking at various home-made utc-mktimes, mktime-utcs, etc.
530,614
530,618
Print leading zeros with C++ output operator?
How can I format my output in C++? In other words, what is the C++ equivalent to the use of printf like this: printf("%05d", zipCode); I know I could just use printf in C++, but I would prefer the output operator <<. Would you just use the following? std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;
This will do the trick, at least for non-negative numbers(a) such as the ZIP codes(b) mentioned in your question. #include <iostream> #include <iomanip> using namespace std; cout << setw(5) << setfill('0') << zipCode << endl; // or use this if you don't like 'using namespace std;' std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl; The most common IO manipulators that control padding are: std::setw(width) sets the width of the field. std::setfill(fillchar) sets the fill character. std::setiosflags(align) sets the alignment, where align is ios::left or ios::right. And just on your preference for using <<, I'd strongly suggest you look into the fmt library (see https://github.com/fmtlib/fmt). This has been a great addition to our toolkit for formatting stuff and is much nicer than massively length stream pipelines, allowing you to do things like: cout << fmt::format("{:05d}", zipCode); And it's currently being targeted by LEWG toward C++20 as well, meaning it will hopefully be a base part of the language at that point (or almost certainly later if it doesn't quite sneak in). (a) If you do need to handle negative numbers, you can use std::internal as follows: cout << internal << setw(5) << setfill('0') << zipCode << endl; This places the fill character between the sign and the magnitude. (b) This ("all ZIP codes are non-negative") is an assumption on my part but a reasonably safe one, I'd warrant :-)
530,741
531,290
What's the difference between a procedural program and an object oriented program?
I'm fairly new to programming but I've been reading some interesting discussions on StackOverflow about various programming approaches. I'm still not 100% clear on what the difference is between procedural programming and object oriented programming. It sounds like object oriented programming still uses procedures (methods) but everything is organized differently because the object is the star of the show. But it seems to me that procedures still allow you to do all of the same things. Like in C, you can put all of your similar procedures into a library. So couldn't you really say that a library in C is similar to an object in C++?
The difference between the two is subtle but significant. In a procedural program, modules interact by reading and writing state that is stored in shared data structures. In an object oriented program, modules in the form of objects interact by sending messages to other objects.
531,133
531,141
Should I put many functions into one file? Or, more or less, one function per file?
I love to organize my code, so ideally I want one class per file or, when I have non-member functions, one function per file. The reasons are: When I read the code I will always know in what file I should find a certain function or class. If it's one class or one non-member function per header file, then I won't include a whole mess when I include a header file. If I make a small change in a function then only that function will have to be recompiled. However, splitting everything up into many header and many implementation files can considerately slow down compilation. In my project, most functions access a certain number of templated other library functions. So that code will be compiled over and over, once for each implementation file. Compiling my whole project currently takes 45 minutes or so on one machine. There are about 50 object files, and each one uses the same expensive-to-compile headers. Maybe, is it acceptable to have one class (or non-member function) per header file, but putting the implementations of many or all of these functions into one implementation file, like in the following example? // foo.h void foo(int n); // bar.h void bar(double d); // foobar.cpp #include <vector> void foo(int n) { std::vector<int> v; ... } void bar(double d) { std::vector<int> w; ... } Again, the advantage would be that I can include just the foo function or just the bar function, and compilation of the whole project will be faster because foobar.cpp is one file, so the std::vector<int> (which is just an example here for some other expensive-to-compile templated construction) has to be compiled in only once, as opposed to twice if I compiled a foo.cpp and bar.cpp separately. Of course, my reason (3) above is not valid for this scenario: After just changing foo(){...} I have to recompile the whole, potentially big, file foobar.cpp. I'm curious what your opinions are!
IMHO, you should combine items into logical groupings and create your files based on that. When I'm writing functions, there are often a half a dozen or so that are tightly related to each other. I tend to put them together in a single header and implementation file. When I write classes, I usually limit myself to one heavyweight class per header and implementation file. I might add in some convenience functions or tiny helper classes. If I find that an implementation file is thousands of lines long, that's usually a sign that there's too much there and I need to break it up.
531,477
531,489
Strange assembly from array 0-initialization
Inspired by the question Difference in initalizing and zeroing an array in c/c++ ?, I decided to actually examine the assembly of, in my case, an optimized release build for Windows Mobile Professional (ARM processor, from the Microsoft Optimizing Compiler). What I found was somewhat surprising, and I wonder if someone can shed some light on my questions concerning it. These two examples are examined: byte a[10] = { 0 }; byte b[10]; memset(b, 0, sizeof(b)); They are used in the same function, so the stack looks like this: [ ] // padding byte to reach DWORD boundary [ ] // padding byte to reach DWORD boundary [ ] // b[9] (last element of b) [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] // b[0] = sp + 12 (stack pointer + 12 bytes) [ ] // padding byte to reach DWORD boundary [ ] // padding byte to reach DWORD boundary [ ] // a[9] (last element of a) [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] // a[0] = sp (stack pointer, at bottom) The generated assembly with my comments: ; byte a[10] = { 0 }; 01: mov r3, #0 // r3 = 0 02: mov r2, #9 // 3rd arg to memset: 9 bytes, note that sizeof(a) = 10 03: mov r1, #0 // 2nd arg to memset: 0-initializer 04: add r0, sp, #1 // 1st arg to memset: &a[1] = a + 1, since only 9 bytes will be set 05: strb r3, [sp] // a[0] = r3 = 0, sets the first element of a 06: bl memset // continue in memset ; byte b[10]; ; memset(b, 0, sizeof(b)); 07: mov r2, #0xA // 3rd arg to memset: 10 bytes, sizeof(b) 08: mov r1, #0 // 2nd arg to memset: 0-initializer 09: add r0, sp, #0xC // 1st arg to memset: sp + 12 bytes (the 10 elements // of a + 2 padding bytes for alignment) = &b[0] 10: bl memset // continue in memset Now, there are two things that confuses me: What's the point of lines 02 and 05? Why not just give &a[0] and 10 bytes to memset? Why isn't the padding bytes of a 0-initialized? Is that only for padding in structs? Edit: I was too curious to not test the struct case: struct Padded { DWORD x; byte y; }; The assembler for 0-initializing it: ; Padded p1 = { 0 }; 01: mov r3, #0 02: str r3, [sp] 03: mov r3, #0 04: str r3, [sp, #4] ; Padded p2; ; memset(&p2, 0, sizeof(p2)); 05: mov r3, #0 06: str r3, [sp] 07: andcs r4, r0, #0xFF 08: str r3, [sp, #4] Here we see in line 04 that a padding indeed occur, since str (as opposed to strb) is used. Right?
The reason for lines 2 and 5 is because you specified a 0 in the array initializer. The compiler will initialize all constants then pad out the rest using memset. If you were to put two zeros in your initializer, you'd see it strw (word instead of byte) then memset 8 bytes. As for the padding, it's only used to align memory accesses -- the data shouldn't be used under normal circumstances, so memsetting it is wasteful. Edit: For the record, I may be wrong about the strw assumption above. 99% of my ARM experience is reversing code generated by GCC/LLVM on the iPhone, so my assumption may not carry over to MSVC.
531,684
531,727
What is the best way to take screenshots of a Window with C++ in Windows?
What is the best (easiest) way to take a screenshot of an running application with C++ under Windows?
You have to get the device context of the window (GetWindowDC()) and copy image (BitBlt()) from it. Depending on what else you know about the application you will use different methods to find which window's handle to pass into GetWindowDC().
531,722
531,758
C++ for the C# Programmer
I have a good understanding of OO from java and C# and I'm lucky in my engineering courses to have been exposed to the evils of both assembler and C (pointers are my playground :D ). However, I've tried looking into C++ and the thing that gets me is the library code. There are so many nice examples of how to perform the bread and butter tasks in java and C#, but I've not been able to find a good explanation of how to do these things in C++. I'd love to expand my knowledge into C++ to add to my skillset but I've not had a chance to be exposed to people and communities that are keen on these things. Could anyone here recommend some good open source projects or tutorials which are useful. Bonus marks if they involve coming from java or C# into this environment.
I'd suggest that you work your way through the excellent Andrew Koenig and Barbara Moo book "Accelerated C++" (sanitised Amazon link). This book teaches you C++ rather than assume that you know C and then look at the C++ bits bolted on. In fact, you dive in and are using STL containers in the early chapters. Highly recommended.
531,916
531,928
error C2039: 'memchr' : is not a member of '`global namespace''
It has been quite a while since I am getting this error in the standard <cstring> header file for no apparent reason. A google search brought up many answers but none of them worked.
Ok I fixed it myself. It was a stupid mistake! I have a file called "String.h" in a library project which is being picked up by the <cstring> header. Probably because I have added the path to <String.h> as an additional include directory in my test project (where I am getting this error.) Hope this helps someone.
531,941
533,372
How to set up Google C++ Testing Framework (gtest) with Visual Studio 2005
It is not documented on the web site and people seem to be having problems setting up the framework. Can someone please show a step-by-step introduction for a sample project setup?
What Arlaharen said was basically right, except he left out the part which explains your linker errors. First of all, you need to build your application without the CRT as a runtime library. You should always do this anyways, as it really simplifies distribution of your application. If you don't do this, then all of your users need the Visual C++ Runtime Library installed, and those who do not will complain about mysterious DLL's missing on their system... for the extra few hundred kilobytes that it costs to link in the CRT statically, you save yourself a lot of headache later in support (trust me on this one -- I've learned it the hard way!). Anyways, to do this, you go to the target's properties -> C/C++ -> Code Generation -> Runtime Library, and it needs to be set as "Multi-Threaded" for your Release build and "Multi-Threaded Debug" for your Debug build. Since the gtest library is built in the same way, you need to make sure you are linking against the correct version of it, or else the linker will pull in another copy of the runtime library, which is the error you saw (btw, this shouldn't make a difference if you are using MFC or not). You need to build gtest as both a Debug and Release mode and keep both copies. You then link against gtest.lib/gtest_main.lib in your Release build and gtestd.lib/gtest_maind.lib in your Debug build. Also, you need to make sure that your application points to the directory where the gtest header files are stored (in properties -> C/C++ -> General -> Additional Include Directories), but if you got to the linker error, I assume that you already managed to get this part correct, or else you'd have a lot more compiler errors to deal with first.
531,957
551,134
Editor core buffer type and syntax highlighting
I've been thinking a lot about making an editor core functionality wise compatible to vim, similar to yzis. The biggest questions are what buffer type to use. Requirement are: possibility to implement fast syntax highlighting, regex on top of it. possibility to implement multiple syntax highlightings in a single file. similar to textmates scopes proper moving marks on delete inserts. so that they properly adjust in column. unlike in vim. handle and highlight at least 100 mb files without too big issues and memory overhead. Possible buffer types: gap buffers line based editing I read that gap buffers can cause rather big memory fragmentation at longer runs. Also the emacs syntax highlighting engine is very slow.(dunno why, maybe not really related to the buffer type) So the questions: what buffer type would be best for a fast programming editor? what's a fast/complete regex engine? (maybe this includes the next point). TextMate uses oniguruma, is that a wise choice? what's fast syntax highlighting engine? About the mark and syntax highlighting. How do emacs overlays work, would they help? Thanks, Reza
A good text editor should be useful for all kinds of work a programmer might do, and that includes opening files that may sometimes be several gigabytes in size. Therefore I would not recommend a mind set where everything is to be buffered in RAM. I would recommend setting up a search tree of slices representing the file, where a single slice may be: A reference to a range of bytes in the actual file on disk, or A reference to an edited "page". When you open a file you start by inserting a single item into the tree, which is simply a range representing the whole file, e.g. for a 10-MiB file: std::map<size_t, slice_info> slices; slices[0].size = 10*1024*1024; When the user edits the file, create a "page" which is some reasonable size, say 4 KiB, around the edit point. The tree is spliced at that point. In the example, the edit point is at 5 MiB: size_t const PAGE_SIZE = 4*1024; slices[0].size = 5*1024*1024; slices[5*1024*1024].size = PAGE_SIZE; slices[5*1024*1024].buffer = create_buffer(file, 5*1024*1024, PAGE_SIZE); slices[5*1024*1024 + PAGE_SIZE].size = 5*1024*1024 - PAGE_SIZE You can use memory-mapped files both for the read-only buffer (the source file) and for the copied editable buffers (the latter would be placed in a temp directory). This also allows recovery should the editor crash. Using fixed-size pages will reduce fragmentation of the memory heap a lot since all blocks have the same size, and inserting text will never require moving more than 4 KiB of data ahead of you. This is a simplified description to give the general idea without getting into too many gritty details. A real implementation would most likely need to be more sophisticated, e.g. allow for a variable amount of data in a page to cope with pages that overflow, and merge together many small slices so that running a regex substitution across a large file does not create too many small buffers. There probably needs to be a limit for the number of slices you should have in the tree simultaneously, but a key point is that when you start inserting somewhere you should make sure that you are working with a slice that isn't too big. For regex, I don't think the performance is much of a problem as long as the whole editor doesn't hang while running it. Try Boost.Regex, it will most likely be fast enough for your needs, and it is also generic enough to plug in any buffering strategy you need. The same applies to syntax highlighting, if you run it in the background it won't disturb the user so much while he is typing. You can use the slice approach to your benefit here: Each slice can have a mutex that can be locked during an editing operation, allowing syntax highlighting or "intellisense" type analysis to run in a background thread. You can store the state of the syntax highlighting engine so that whenever you make edits in a slice you can restart the syntax highlighting from the beginning of that slice, rather than from the beginning of the file. I am not aware of any freestanding syntax highlighting engines, but they are usually based on regex substitution (see e.g. the syntax highlighting files in vim).
531,998
532,121
Is there a way to set the environment path programmatically in C++ on Windows?
Is there a way to set the global windows path environment variable programmatically (C++)? As far as I can see, putenv sets it only for the current application. Changing directly in the registry (HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment) is also an option though I would prefer API methods if there are?
MSDN Says: Calling SetEnvironmentVariable has no effect on the system environment variables. To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates. Note that the values of the environment variables listed in this key are limited to 1024 characters.
532,092
532,105
Weird behaviour of C++ destructors
#include <iostream> #include <vector> using namespace std; int main() { vector< vector<int> > dp(50000, vector<int>(4, -1)); cout << dp.size(); } This tiny program takes a split second to execute when simply run from the command line. But when run in a debugger, it takes over 8 seconds. Pausing the debugger reveals that it is in the middle of destroying all those vectors. WTF? Note - Visual Studio 2008 SP1, Core 2 Duo 6700 CPU with 2GB of RAM. Added: To clarify, no, I'm not confusing Debug and Release builds. These results are on one and the same .exe, without even any recompiling inbetween. In fact, switching between Debug and Release builds changes nothing.
Running in the debugger changes the memory allocation library used to one that does a lot more checking. A program that does nothing but memory allocation and de-allocation is going to suffer much more than a "normal" program. Edit Having just tried running your program under VS I get a call stack that looks like ntdll.dll!_RtlpValidateHeapEntry@12() + 0x117 bytes ntdll.dll!_RtlDebugFreeHeap@12() + 0x97 bytes ntdll.dll!_RtlFreeHeapSlowly@12() + 0x228bf bytes ntdll.dll!_RtlFreeHeap@12() + 0x17646 bytes msvcr90d.dll!_free_base(void * pBlock=0x0061f6e8) Line 109 + 0x13 bytes msvcr90d.dll!_free_dbg_nolock(void * pUserData=0x0061f708, int nBlockUse=1) msvcr90d.dll!_free_dbg(void * pUserData=0x0061f708, int nBlockUse=1) msvcr90d.dll!operator delete(void * pUserData=0x0061f708) desc.exe!std::allocator<int>::deallocate(int * _Ptr=0x0061f708, unsigned int __formal=4) desc.exe!std::vector<int,std::allocator<int> >::_Tidy() Line 1134 C++ Which shows the debug functions in ntdll.dll and the C runtime being used.
532,248
532,271
Communication between inherited classes
I have 3 classes in different files: X | ------- | | Y Z I will be creating several objects of inherited classes Y and Z. A specific function in class Z should be executed only if some flag variable is set by class Y. Where should I create this flag variable (which class) and what should be the declaration be like (static/extern)?
Consider template method as a replacement for the infamous flags.
532,524
532,546
How can you parse simple C++ typedef instructions?
I'd like to parse simple C++ typedef instructions such as typedef Class NewNameForClass; typedef Class::InsideTypedef NewNameForTypedef; typedef TemplateClass<Arg1,Arg2> AliasForObject; I have written the corresponding grammar that i'd like to see used in parsing. Name <- ('_'|letter)('_'|letter|digit)* Type <- Name Type <- Type::Name Type <- Name Templates Templates <- '<' Type (',' Type)* '>' Instruction <- "typedef" Type Name ';' Once this is parsed, all i'll want to do is to generate xml with the same information (but layed out differently) What is the most effective language for writing such a program ? How can you achieve this ? EDIT : What i have come up with using Boost Spirit (it's not perfect, but it's good enough for me, at least for now) rule<> sep_p = space_p; rule<> name_p = (ch_p('_')|alpha_p) >> *(ch_p('_')|alpha_p|digit_p); rule<> type_p = name_p >> !(*sep_p >>str_p("::") >> *sep_p>> name_p) >> *(*sep_p >> ch_p('*') ) >> !(*sep_p >> str_p("const")) >> !(*sep_p >> ch_p('&')); rule<> templated_type_p = name_p >> *sep_p >> ch_p('<') >> *sep_p >> (*sep_p>>type_p>>*sep_p)%ch_p(',') >> ch_p('>') >> *sep_p; rule<> typedef_p = *sep_p >> str_p ("typedef") >> +sep_p >> (type_p|templated_type_p) >> +sep_p >> name_p >> *sep_p >> ch_p(';') >> *sep_p; rule<> typedef_list_p = *typedef_p;
I would alter the grammar slightly ShortName <- ('_'|letter)('_'|letter|digit)* Name <- ShortName Name <- Name::ShortName Type <- Name Type <- Name Templates Templates <- '<' Type (',' Type)* '>' Instruction <- "typedef" Type Name ';' Also your grammar leaves out the following cases Multiple typedef targets. Pointer targets Function pointers (this is by far the most difficult) Parsing a grammar (i love the irony) is a fairly straight forward operation. If you wanted to actually use the grammar in a functional way, I would say the best bet is a lex/yacc combination. But from your question it appears that you want to spit it out to another format. There really isn't a language designed for this so I would say use whatever language you're most comfortable with. Edit The OP asked about multiple typedef targets. It's perfectly legally for a typedef declaration to have more than 1 target. For Example: typedef _SomeStruct SomeStruct, *PSomeStruct This creates 2 typedef names. SomeStruct which is equivalent to "struct _SomeStruct" PSomeStruct which is equivalent to "struct _SomeStruct*"
532,663
532,890
Why does wgluseFontBitmaps consume too much memory on some computers?
I'm creating a game in OpenGL which loads the entire Arial Unicode MS font when it loads. The program uses on avg. 10 megs of memory on my computer (op sys is WinXP SP2) and runs without problems, but when I move the program to my laptop (with Vista) the wglUseFontBitmaps hangs and allocates memory fluently and never returns. This problem occured recently and I have no idea why and never had such problem before. Why does wglUseFontBitmaps do this and how to fix it? update: I tried an older version and it runs but eats 400megs of memory (so it is not a new problem)
How many glyph display lists are you trying to generate with wglUseFontBitmaps()? Can you show us your invocation? Perhaps Vista is trying to do all 60000-some-odd glyphs in one go, and XP is doing some sort of on-demand construction? I've had good luck with FreeType2 and MS Arial Unicode, though it does take some time to get up to speed with the API. This tutorial can be C++-ized to great effect.
532,702
532,821
Any way to make this relatively simple (nested for memory copy) C++ code more efficient?
I realize this is kind of a goofy question, for lack of a better term. I'm just kind of looking for any outside idea on increasing the efficiency of this code, as it's bogging down the system very badly (it has to perform this function a lot) and I'm running low on ideas. What it's doing it loading two image containers (imgRGB for a full color img and imgBW for a b&w image) pixel-by-individual-pixel of an image that's stored in "unsigned char *pImage". Both imgRGB and imgBW are containers for accessing individual pixels as necessary. // input is in the form of an unsigned char // unsigned char *pImage for (int y=0; y < 640; y++) { for (int x=0; x < 480; x++) { imgRGB[y][x].blue = *pImage; pImage++; imgRGB[y][x].green = *pImage; imgBW[y][x] = *pImage; pImage++; imgRGB[y][x].red = *pImage; pImage++; } } Like I said, I was just kind of looking for fresh input and ideas on better memory management and/or copy than this. Sometimes I look at my own code so much I get tunnel vision... a bit of a mental block. If anyone wants/needs more information, by all means let me know.
I think the array accesses (are they real array accesses or operator []?) are going to kill you. Each one represents a multiply. Basically, you want something like this: for (int y=0; y < height; y++) { unsigned char *destBgr = imgRgb.GetScanline(y); // inline methods are better unsigned char *destBW = imgBW.GetScanline(y); for (int x=0; x < width; x++) { *destBgr++ = *pImage++; *destBW++ = *destBgr++ = *pImage++; // do this in one shot - don't double deref *destBgr++ = *pImage++; } } This will do two multiplies per scanline. You code was doing 4 multiplies per PIXEL.
532,755
532,806
What are the valid values of the expression (uninitialized_bool ? 1 : 2)?
What is the set of valid outputs for the following, according to the standard? bool x; cout << (x ? 1 : 2); edit: unknown(google) has got it. In gcc my code was crashing because of sprite.setFrame(isPressed ? 0 : 1) with the conditional returning 28!
Using a bool value in ways described by This Standard as "undefined" such as by examining the value of an unitialized automatic variable, might cause it to behave as it is neither true or false. Welcome to the world of undefined behaviour. But first, why would you want to do that?
532,779
542,784
Is there anything like GhostDoc for C++
When I'm developing in C#, I heavily use GhostDoc to speed up the process of commenting my code. I'm currently working on a C++ project and I haven't found an equivalent tool. I know about Doxygen, but from what I know it is used to create documentation outside the code, not comments in the code. Are there any good equivalent tools? I would prefer one that runs in VS, but I could handle one that works in any IDE. (Before someone brings it up, I don't rely solely on GhostDoc to create comments. I just use it to create the starting point for my comments.)
Visual Assist helps by providing custom scripts executed while typing (or on other). For example, you can have a script for comments like this : /************************************************************************/ /* My comment : $end$ */ /************************************************************************/ That would be suggested (via a combo-box exactly like intellisense) when you start typing "/**" for example. When you select this suggestion (via Enter/Space/Click - customizable), it will insert the script where your cursor is and just replace markers that are between '$' characters by special values (like the current file name for example). Here the $end$ marker will make the cursor be at this position when the script is executed. This way, you continue typing smoothly. For example with the previous script set, typing exactly : /** this is a test comment to show you one of the many features Visual Assit! will simply give : /************************************************************************/ /* My comment : this is a test comment to show you one of the many features Visual Assit! */ /************************************************************************/ It's really easy to customize and the behavior of the suggestion (read : intellisense++) system is customizable.
532,780
535,133
CATIA-CAA CATKeyboardEvent
I know there are only a few CAA Programmers in the world but I try it anyway... I can't get keyboard events to work. I found this code which looks reasonable but the Notification doesn't fire. AddAnalyseNotificationCB(CATFrmLayout::GetCurrentLayout()->GetCurrentWindow()->GetViewer(), CATKeyboardEvent::ClassName(), (CATCommandMethod)&PROTrvTreeView::OnKeyboardEvent, NULL); void PROTrvTreeView::OnKeyboardEvent(CATCommand * ipCmd, CATNotification * ipEvt, CATCommandClientData iobjData) { cout<< "KeyboardEvent" <<endl; } Anyone any idea?
There is a much denser group of developers for CAA at: http://www.3ds.com/alliances/c-java-developers/forum/ The same question came up, with several people mentioning that this API was unauthorized, and therefore you can't rely on it, even if it works. The other samples there are essentially the same code as yours, but the only one that purports to work doesn't use CATKeyboardEvent::ClassName, but instead uses CATKeybdEvent. Might be worth a try.
533,038
533,561
redirect std::cout to a custom writer
I want to use this snippet from Mr-Edd's iostreams article to print std::clog somewhere. #include <iostream> #include <iomanip> #include <string> #include <sstream> int main() { std::ostringstream oss; // Make clog use the buffer from oss std::streambuf *former_buff = std::clog.rdbuf(oss.rdbuf()); std::clog << "This will appear in oss!" << std::flush; std::cout << oss.str() << '\\n'; // Give clog back its previous buffer std::clog.rdbuf(former_buff); return 0; } so, in a mainloop, I will do something like while (! oss.eof()) { //add to window text somewhere } Here's the ostringstream docs but I'm having trouble understanding the best way to do this. I have a method that displays the text, I just want to call it with any data in the ostringstream. What is the easiest/best way to get anything sent to std::clog redirected to a method of my choice? is it as above, and fill in the while !eof part (not sure how), or is there a better way, say by overloading some 'commit' operator somewhere that calls my method? I'm loking for quick and easy, I really don't want to start defining sinks and such with boost iostreams as the article does - that stuff is way over my head.
I encourage you to look at Boost.IOStreams. It seems to fit your use-case nicely, and using it is surprisingly simple: #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream_buffer.hpp> #include <iostream> namespace bio = boost::iostreams; class MySink : public bio::sink { public: std::streamsize write(const char* s, std::streamsize n) { //Do whatever you want with s //... return n; } }; int main() { bio::stream_buffer<MySink> sb; sb.open(MySink()); std::streambuf * oldbuf = std::clog.rdbuf(&sb); std::clog << "hello, world" << std::endl; std::clog.rdbuf(oldbuf); return 0; }
533,065
533,085
C++ class member function naming rules
I'm trying to encapsulate some functions from the C socket library into my own C++ class. I'd like to define a member function that uses the same name as its corresponding C function, but with a different signature. For example, I'd like to write the function ssize_t MyClass::write(const void *buf); which makes a call to ssize_t write(int fd, const void *buf, size_t count); When I compile I get the following errors error: no matching function for call to ‘MyClass::write(int&, const char*&, size_t)’ note: candidates are: ssize_t MyClass::write(const char*) I have the correct #include statements to make the call to the C socket library, but my definition of a write function seems to be shadowing it. If I change the name of my class defined function to something else, everything seems to work fine. I'm reasonably sure that changing my function name is going to be my final solution, but could someone tell me the name of the C++ naming rule that causes this behavior? I'd like to read up on it so I know what I'm doing in the future.
Have you tried calling the C function expliciting that it lives in the global namespace, like ::write?
533,076
533,201
Understanding C++ compilers from a Java / C# perspective
I'm a moderately experienced Java / C# programmer, and I've recently started learning C++. The problem is, I'm having trouble understanding how to structure the various header and code files. This seems mostly due to my lack of understanding as to how the compiler links everything together. I've tried reading some textbooks, but my preconceptions are heavily colored by my Java and C# knowledge. For example, I'm having a hard time coming to grips with the fact that methods and the like can be defined in a namespace rather than only in a class definition. I've found plenty of C++ -> Java/C# guides, but practically nothing to go the other way. Are there any good resources out there for easing the Java/C# -> C++ transition, particularly with respect to understanding the compiling process?
The C++ FAQ is an excellent resource about all the idiosyncrasies of C++, but it's probably a little more advanced than you're looking for -- most of the questions (not just the answers) are mysteries even to fairly experienced C++ developers. I think if you google for C++ tutorials, you'll be able to find something. You may also want to try learning assembly language (or at least getting a quick introduction as to how things actually happen in a microprocessor), as both C and C++ are quite close to the hardware in the way they do things. This is where their speed and power comes from, but it comes at the price of some of the nicer abstractions Java offers. I can try to answer your specific questions asked above, but I don't know how well I'll do. One of the keys to understanding the relationship between header files and cpp files is understanding the idea of a "translation unit". A Java class file can be considered a translation unit as it is the basic unit that is compiled into a binary form. In C++, pretty much every cpp file is a translation unit (there are exceptions if you're doing weird stuff). A header file may be included in multiple translation units (and must be included everywhere that uses whatever is defined in the header). The #include directive literally just does a text substitution -- the contents of the included file are inserted verbatim where the #include directive is. You normally want your class interface to be defined in the header file, and the implementation in the cpp file. This is because you don't want to be exposing your implementation details to other translation units that may include the header. In C++, everything, including classes, aren't really rich objects, but just chunks of memory that the compiler assigns meaning to... by compiling the same header information into each translation unit, the compiler guarantees that all the translation units have the same understanding of what a chunk of memory represents. Because of the lack of rich data after compile time, things like reflection are impossible. The second step in the C++ build process is linking, which is where the linker takes all the compiled translation units and looks for symbols (usually function calls, but also variables) used in a translation unit but not defined there. It then looks for another translation unit that defines that symbol and "links" them together, so that all calls to a particular function are directed to the translation unit that defines it. In the case of class methods, they must be called through a class instance, which is behind the scenes just a pointer to a piece of memory. When the compiler sees these types of method calls, it outputs code that calls a function, implicitly passing the pointer, known as the this pointer, to the function as the first argument. You can have functions that do not belong to classes (not methods, as you said, because a method is properly a member function of a class and thus cannot exist without a class) because the linker has no concept of a class. It will see a translation unit that defines a function and another that calls a function and tie them together. That ended up being a lot longer than I expected, and of course is an oversimplification, but it is accurate to the best of my knowledge and the level of detail provided... hope it helps some. At least it should give you a starting point for some googling.
534,007
534,073
Performance on strings initialization in C++
I have following questions regarding strings in C++: 1>> which is a better option(considering performance) and why? 1. string a; a = "hello!"; OR 2. string *a; a = new string("hello!"); ... delete(a); 2>> string a; a = "less"; a = "moreeeeeee"; how exactly memory management is handled in c++ when a bigger string is copied into a smaller string? Are c++ strings mutable?
All the following is what a naive compiler would do. Of course as long as it doesn't change the behavior of the program, the compiler is free to make any optimization. string a; a = "hello!"; First you initialize a to contain the empty string. (set length to 0, and one or two other operations). Then you assign a new value, overwriting the length value that was already set. It may also have to perform a check to see how big the current buffer is, and whether or not more memory should be allocated. string *a; a = new string("hello!"); ... delete(a); Calling new requires the OS and the memory allocator to find a free chunk of memory. That's slow. Then you initialize it immediately, so you don't assign anything twice or require the buffer to be resized, like you do in the first version. Then something bad happens, and you forget to call delete, and you have a memory leak, in addition to a string that is extremely slow to allocate. So this is bad. string a; a = "less"; a = "moreeeeeee"; Like in the first case, you first initialize a to contain the empty string. Then you assign a new string, and then another. Each of these may require a call to new to allocate more memory. Each line also requires length, and possibly other internal variables to be assigned. Normally, you'd allocate it like this: string a = "hello"; One line, perform initialization once, rather than first default-initializing, and then assigning the value you want. It also minimizes errors, because you don't have a nonsensical empty string anywhere in your program. If the string exists, it contains the value you want. About memory management, google RAII. In short, string calls new/delete internally to resize its buffer. That means you never need to allocate a string with new. The string object has a fixed size, and is designed to be allocated on the stack, so that the destructor is automatically called when it goes out of scope. The destructor then guarantees that any allocated memory is freed. That way, you don't have to use new/delete in your user code, which means you won't leak memory.
534,044
29,600,223
How do I tear down observer relationship in multithreaded C++?
I have a Subject which offers Subscribe(Observer*) and Unsubscribe(Observer*) to clients. Subject runs in its own thread (from which it calls Notify() on subscribed Observers) and a mutex protects its internal list of Observers. I would like client code - which I don't control - to be able to safely delete an Observer after it is unsubscribed. How can this be achieved? Holding the mutex - even a recursive mutex - while I notify observers isn't an option because of the deadlock risk. I could mark an observer for removal in the Unsubscribe call and remove it from the Subject thread. Then clients could wait for a special 'Safe to delete' notification. This looks safe, but is onerous for clients. Edit Some illustrative code follows. The problem is how to prevent Unsubscribe happening while Run is at the 'Problem here' comment. Then I could call back on a deleted object. Alternatively, if I hold the mutex throughout rather than making the copy, I can deadlock certain clients. #include <set> #include <functional> #include <boost/thread.hpp> #include <boost/bind.hpp> using namespace std; using namespace boost; class Observer { public: void Notify() {} }; class Subject { public: Subject() : t(bind(&Subject::Run, this)) { } void Subscribe(Observer* o) { mutex::scoped_lock l(m); observers.insert(o); } void Unsubscribe(Observer* o) { mutex::scoped_lock l(m); observers.erase(o); } void Run() { for (;;) { WaitForSomethingInterestingToHappen(); set<Observer*> notifyList; { mutex::scoped_lock l(m); notifyList = observers; } // Problem here for_each(notifyList.begin(), notifyList.end(), mem_fun(&Observer::Notify)); } } private: set<Observer*> observers; thread t; mutex m; }; Edit I can't Notify observers while holding the mutex because of the deadlock risk. The most obvious way this can happen - the client calls Subscribe or Unsubscribe from inside Notify - is easily remedied by making the mutex recursive. More insidious is the risk of intermittent deadlock on different threads. I'm in a multithreaded environment, so at any point in a thread's execution, it will typically hold a sequence of locks L1, L2, ... Ln. Another thread will hold locks K1, K2, ... Km. A properly written client will ensure that different threads will always acquire locks in the same order. But when clients interact with my Subject's mutex - call it X - this strategy will be broken: Calls to Subscribe / Unsubscribe acquire locks in the order L1, L2, ... Ln, X. Calls to Notify from my Subject thread acquire locks in the order X, K1, K2, ... Km. If any of the Li or Kj can coincide down any call path, the client suffers an intermittent deadlock, with little prospect of debugging it. Since I don't control the client code, I can't do this.
The "ideal" solution would involve using shared_ptr and weak_ptr. However, in order to be generic, it also has to account for the issue of Subject being dropped before some of its Observer (yes, that can happen too). class Subject { public: void Subscribe(std::weak_ptr<Observer> o); void Unsubscribe(std::weak_ptr<Observer> o); private: std::mutex mutex; std::set< std::weak_ptr<Observer> > observers; }; class Observer: boost::noncopyable { public: ~Observer(); void Notify(); private: std::mutex; std::weak_ptr<Subject> subject; }; With this structure, we create a cyclic graph, but with a judicious use of weak_ptr so that both Observer and Subject can be destroyed without coordination. Note: I have assumed, for simplicity, that an Observer observes a single Subject at a time, but it could easily observe multiple subjects. Now, it seems that you are stuck with unsafe memory management. This is a quite difficult situation, as you can imagine. In this case, I would suggest an experiment: an asynchronous Unsubscribe. Or at least, the call to Unsubscribe will be synchronous from the outside, but be implemented asynchronously. The idea is simple: we will use the event queue to achieve synchronization. That is: the call to Unsubscribe posts an event in the queue (payload Observer*) and then waits when the Subject thread has processed the Unsubscribe event(s), it wakes up the waiting thread(s) You can use either busy-waiting or a condition variable, I would advise a condition variable unless performance dictates otherwise. Note: this solution completely fails to account for Subject dying prematurely.
534,088
534,320
Several machines running same software, some won't connect to firebird
I'm pretty perplexed... I've got 5 different test computers, all relatively blank Windows XP machines running similar hardware specs. I run a silent install of the FireBird (Classic) database and my application. Some computers require "localhost:" (or 127.0.0.1) before the database location to make a connection, and some simply don't work at all! This is running the exact same software across the board. Does anybody have any suggestions as to what needs to happen to make the connection string universal, or what I could be doing wrong?? It's firebird version 2.1.1.17910 Classic By the way, i tried connecting to the same database using FlameRobin (a small db management tool) and it worked just fine on the computers that don't connect. Any more information necessary just let me know! Thanks a lot in advance
For anybody's future reference, the answer is in the services. Apparently it's not being registered as a service for some reason, and on the working computers, was at some point registered, probably through some sort of far earlier tests of Interbase is my best guess. C:\Windows\System32\drivers\etc and opening up the file 'services' and adding the following line allows the server to run properly. gds_db 3050/tcp
534,183
534,373
compiling c++ applications so they can work on other computers as well
So I have this very simply SDL application I want to be able to pass to my friend without having him download a whole bunch of SDL packages. how can I go about this? I was told to use this line to compile: (note that I use ubuntu linux and so does my friend, and that this application compiles and runs without the "-Wl,-Bstatic" options just fine.) g++ test-sdl.cpp -o test-sdl -Wl,-Bstatic -lSDL_image -lSDL But then I get this error: /usr/bin/ld: cannot find -lgcc_s collect2: ld returned 1 exit status why am I getting this error? how do I fix it? do I even have to do this in this way? Is there a different/easier/alternative way? Am I asking for so much by wanting to save my friend the hassle of downloading packages he will probably never use anyway? Thanks.
In the long run your best bet would be to figure out how to build .debs and then your friend's system's package management can take care of installing all the dependencies needed. If you want to distribute the packages more widely, using the platform's native packaging system as intended will save you and your users a lot of headaches. Take a look at Ubuntu's guide to packaging and pbuilder. Personally, I learned how to do this for my own projects (on Debian) from the Martin Krafft Debian book, and find using yada streamlines the process considerably.
534,201
534,259
Is it possible to measure function coverage with gcov?
Currently we use gcov with our testing suite for Linux C++ application and it does a good job at measuring line coverage. Can gcov produce function/method coverage report in addition to line coverage? Looking at the parameters gcov accepts I do not think it is possible, but I may be missing something. Or, probably, is there any other tool that can produce function/method coverage report out of statistics generated by gcc? Update: By function/method coverage I mean percentage of functions that get executed during tests.
I guess what you mean is the -f option, which will give you the percentage of lines covered per function. There is an interesting article about gcov at Dr. Dobb's which might be helpful. If "man gcov" doesn't show the -f flag, check if you have a reasobably recent version of the gcc suite. Edit: to get the percentage of functions not executed you can simply parse through the function coverage output, as 0.00% coverage should be pretty much equivalent to not called. This small script prints the percentage of functions not executed: #!/bin/bash if test -z "$1" then echo "First argument must be function coverage file" else notExecuted=`cat $1 | grep "^0.00%" | wc -l` executed=`cat $1 | grep -v "^0.00%" | wc -l` percentage=$(echo "scale=2; $notExecuted / ($notExecuted + $executed) * 100" |bc) echo $percentage fi
534,215
534,243
How to get unique hardware/software signature from a windows pc in c/c++
I'm developing a small windows app using c++ and i would like to get some kind of fingerprint of the software/hardware on a pc so that i can allow the app to be run only on certain pc's. I am aware that the app can be cracked but i'm really interested in implementing something like this. Any ideas how could i achieve this?
It basically depends on how tight you want to couple your software to the underlying hardware. For example you could get some hardware information from the registry, read out the MAC address from the LAN card, retrieve the gfx manufacturer, the CPU id, etc. and hash all these data. You could then use this hash as a challenge code which is sent to your company. The customer then receives the signed (with your private key) version of this hash. Upon start up your application is able to check if the signature of the hash is good or bad (i.e. has been signed by your company). This not only binds your software to a certain hardware configuration, but also forces the crackers to patch your application (because they would need to patch the public key from your executable and replace it in order to write a keygen). Many people consider twice installing a crack obtained from various sources in contrast to just entering a valid serial copied from a keygen. Edit: In order to check the signature of the hash, anything from RSA over DSA to ECC can be used. I can recommend Crypto++ or libTomCrypt for that.
534,555
534,902
Using SFINAE to detect POD-ness of a type in C++
The original title here was Workaround for SFINAE bug in VS2005 C++ This is tentative use of SFINAE to make the equivalent for the is_pod template class that exists in TR1 (In VS2005 there's no TR1 yet). It should have its value member true when the template parameter is a POD type (including primitive types and structs made of them) and false when it's not (like with non-trivial constructors). template <typename T> class is_pod { public: typedef char Yes; typedef struct {char a[2];} No; template <typename C> static Yes test(int) { union {T validPodType;} u; } template <typename C> static No test(...) { } enum {value = (sizeof(test<T>(0)) == sizeof(Yes))}; }; class NonPOD { public: NonPod(const NonPod &); virtual ~NonPOD(); }; int main() { bool a = is_pod<char>::value; bool b = is_pod<NonPOD>::value; if (a) printf("char is POD\n"); if (b) printf("NonPOD is POD ?!?!?\n"); return 0; } The problem is, not only VS 2005 doesn't have TR1, it won't care about the union above (which shouldn't be valid when the template parameter is not a POD), so both a and b evaluate to true. Thanks for the answers posted below. After reading carefully them (and the code) I realized that what I was trying to do was really a wrong approach. The idea was to combine SFINAE behavior with an adaptation to the template must_be_pod (which I found in the book Imperfect C++, but it can be found in another places, too). Actually, this would require a quite particular set of rules for SFINAE, which are not what the standard defines, obviously. This is not really a bug in VS, after all.
The biggest problem with your approach is you don't do SFINAE here - SFINAE only applies to parameter types and return type here. However, of all the SFINAE situations in the standard, none applies to your situation. They are arrays of void, references, functions, or of invalid size type member that is not a type pointers to references, references to references, references to void pointer to member of a non-class type invalid conversions of template value parameters function types with arguments of type void const/volatile function type That's probably why in Boost documentation, there is: Without some (as yet unspecified) help from the compiler, ispod will never report that a class or struct is a POD; this is always safe, if possibly sub-optimal. Currently (May 2005) only MWCW 9 and Visual C++ 8 have the necessary compiler-_intrinsics.
534,861
534,936
compiling a C++ class in Xcode: error during compilation: stl vector
I have a C++ class that compiles fine on linux with gcc and on widows in visual studio. boid.h: #ifndef BOID_CLASS_HEADER_DEFINES_H #define BOID_CLASS_HEADER_DEFINES_H #include "defines.h" class Boid { public: // Initialize the boid with random position, heading direction and color Boid(float SceneRadius,float NormalVel); ..... protected: ... }; #endif and in boid.cpp: #include "Boid.h" // Initialize the boid with random position, heading direction and color Boid::Boid(float SceneRadius,float NormalVel) { .... } However, I get the following error when I compile this code in Xcode: Compiling Boid.h: "error: vector: No such file or directory" Any ideas? I thought you could take C/C++ code and compile it in Xcode without issues? Thanks EDIT: Added defines.h (also added #endif to sample, but that was in the original code) EDIT 2: I am getting a different error after a commenting out a couple of includes there were empty: the vector error above. #ifndef BOID_NAV_DEFINES_H #define BOID_NAV_DEFINES_H #include <stdlib.h> #include <vector> #include "Vector3d.h" #include "Point3d.h" #include "win_layer.h" #endif
Are you including the C++ header in a .m file? .m files are treated as .c files with Objective-C extensions. .mm files are treated as .cpp files with Objective-C extensions, then it's called Objective-C++ Just rename any .m file to .mm, right-click or ctrl-click and select rename on the file in Xcode.
535,223
535,260
Why can't I push this object onto my std::list?
Just started programming in C++. I've created a Point class, a std::list and an iterator like so: class Point { public: int x, y; Point(int x1, int y1) { x = x1; y = y1; } }; std::list <Point> pointList; std::list <Point>::iterator iter; I then push new points onto pointList. Now, I'm needing to iterate through all the points in pointList, so I need to loop using the iterator. This is where I get screwed up. for(iter = pointList.begin(); iter != pointList.end(); iter++) { Point currentPoint = *iter; glVertex2i(currentPoint.x, currentPoint.y); } Update You guys were right, the problem isn't in my iterating the list. It appears the problem is when I am attempting to push something on to the list. Exact error: mouse.cpp: In function void mouseHandler(int, int, int, int)': mouse.cpp:59: error: conversion fromPoint*' to non-scalar type `Point' requested Those lines are: if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { Point currentPoint = new Point(x, y); pointList.push_front(currentPoint); } What does it conversion between Point* to non-scalar type Point? I'm just trying to create new points and push them onto the list here.
That should be a valid bit of code. #include <iostream> #include <list> class Point { public: int x, y; Point(int x1, int y1) { x = x1; y = y1; } }; int main() { std::list<Point> points; points.push_back(Point(0, 0)); points.push_back(Point(1, 1)); points.push_back(Point(2, 2)); std::list<Point>::iterator iter; for(iter = points.begin(); iter != points.end(); ++iter) { Point test = *iter; std::cout << test.x << ", " << test.y << "; "; } std::cout << std::endl; return 0; } Using this code: jasons-macbook41:~ g++ test.cpp jasons-macbook41:~ ./a.out 0, 0; 1, 1; 2, 2; jasons-macbook41:~ Although I wouldn't create a temporary copy of the Point as your code does. I'd rewrite the loop like this: for(iter = points.begin(); iter != points.end(); ++iter) { std::cout << iter->x << ", " << iter->y << "; "; } An iterator is syntactically similar to a pointer. EDIT: Given your new problem, drop the "new" from the construction line. That's creating a pointer to a Point, as opposed to a Point on the stack. This would be valid: Point* temp = new Point(0, 0); Or this: Point temp = Point(0, 0); And you'd be better off with the latter.
535,317
535,338
Checking value exist in a std::map - C++
I know find method finds the supplied key in std::map and return an iterator to the element. Is there anyway to find the value and get an iterator to the element? What I need to do is to check specified value exist in std::map. I have done this by looping all items in the map and comparing. But I wanted to know is there any better approach for this. Here is what I have wrote bool ContainsValue(Type_ value) { bool found = false; Map_::iterator it = internalMap.begin(); // internalMap is std::map while(it != internalMap.end()) { found = (it->second == value); if(found) break; ++it; } return found; } Edit How about using another map internally which stores value,key combination. So I can call find on it? Is find() in std::map doing sequential search? Thanks
You can use boost::multi_index to create a bidirectional map - you can use either value of the pair as a key to do a quick lookup.
535,444
535,647
Custom manipulator for C++ iostream
I'd like to implement a custom manipulator for ostream to do some manipulation on the next item being inserted into the stream. For example, let's say I have a custom manipulator quote: std::ostringstream os; std::string name("Joe"); os << "SELECT * FROM customers WHERE name = " << quote << name; The manipulator quote will quote name to produce: SELECT * FROM customers WHERE name = 'Joe' How do I go about accomplishing that? Thanks.
It's particularly difficult to add a manipulator to a C++ stream, as one has no control of how the manipulator is used. One can imbue a new locale into a stream, which has a facet installed that controls how numbers are printed - but not how strings are output. And then the problem would still be how to store the quoting state safely into the stream. Strings are output using an operator defined in the std namespace. If you want to change the way those are printed, yet keeping the look of manipulators, you can create a proxy class: namespace quoting { struct quoting_proxy { explicit quoting_proxy(std::ostream & os):os(os){} template<typename Rhs> friend std::ostream & operator<<(quoting_proxy const& q, Rhs const& rhs) { return q.os << rhs; } friend std::ostream & operator<<(quoting_proxy const& q, std::string const& rhs) { return q.os << "'" << rhs << "'"; } friend std::ostream & operator<<(quoting_proxy const& q, char const* rhs) { return q.os << "'" << rhs << "'"; } private: std::ostream & os; }; struct quoting_creator { } quote; quoting_proxy operator<<(std::ostream & os, quoting_creator) { return quoting_proxy(os); } } int main() { std::cout << quoting::quote << "hello" << std::endl; } Which would be suitable to be used for ostream. If you want to generalize, you can make it a template too and also accept basic_stream instead of plain string. It has different behaviors to standard manipulators in some cases. Because it works by returning the proxy object, it will not work for cases like std::cout << quoting::quote; std::cout << "hello";
535,592
535,595
Any nice place to communicate with c++/game developers?
I'm a game programmer working in Korea. I started Stackoverflow recently and I found it helps me a lot. Also I think communicating with other developers is a good way to learning and improving myself. Stackoverflow is the only site I know to communicate (especially in English). Any other nice place to communicate(ask/answer/talk) with game developers(or C++ programmers, network programmers)?
Gamedev.net has a great community of game developers, along with tons of great articles and resources related to game programming.
535,688
535,698
Passing a variable of type int[5][5] to a function that requires int**
I'd like to test a function that takes runtime-allocated multidimensional arrays, by passing it a hardcoded array. The function has a signature of void generate_all_paths(int** maze, int size) and the array is defined as int arr[5][5] = {REMOVED}. I'm not exactly sure how to properly coerce the array for the function (or if that is impossible).
This multi dimensional array topic unfortunately confuses so many C++ programmers. Well, here is the solution: void generate_all_paths(int (*maze)[5], int size); That is what the function declaration has to look like. An alternative, but fully equivalent is void generate_all_paths(int maze[][5], int size); Both are creating a parameter that is a pointer to an array of 5 integers. You can then pass your array of arrays of 5 integers to that function: generate_all_paths(arr, 5); Because your array's first element is an array of 5 integers, it will be converted automatically (implicitly) to a pointer to that first element when passed to that function. In the comments, you have shown you are bound to an int**, because both your inner and outer dimension must have runtime values. A multi-dimensional array can not be used anymore. What you can do for testing purposes then is to create an array of pointers like this: int store[5 * 5] = { ..... }; int *arr[5] = { store, store + 5, store + 10, store + 15, store + 20 }; Then, actually, you can have your function accept a int**. As the first element of you array then is a int*, it will be converted to a int** automatically. Another way of doing this is keeping the data in the 2 dimensional array, but just creating a "view" structured of pointers to that array: int *arr[5] = { store[0], store[1], store[2], store[3], store[4] }; Where store is your int[5][5] array. Since store[n] accesses the n'th sub-array of that two-dimensional array and the element type of it is int, the pointer-converted type of it is int*, which will be compatible again.
535,713
536,137
How do you make sense of the error: cannot convert from 'int []' to 'int []'
When compiling the following code: void DoSomething(int Numbers[]) { int SomeArray[] = Numbers; } the VS2005 compiler complains with the error C2440: 'initializing' : cannot convert from 'int []' to 'int []' I understand that really it's trying to cast a pointer to an array which is not going to work. But how do you explain the error to someone learning C++?
There are three things you need to explain to the person you're trying to help: Arrays can't be passed by value to a function in C++. To do what you are trying to do, you need to pass the address of the start of the array to DoSomething(), as well as the size of the array in a separate int (well, size_t, but I wouldn't bother saying that) argument. You can get the address of the start of some array myArray with the expression &(myArray[0]). Since this is such a common thing to want to do, C++ lets you use just the name of the array -- e.g. myArray -- to get the address of its first element. (Which can be helpful or confusing, depending on which way you look at it.) To make things even more confusing, C++ allows you to specify an array type (e.g. int Numbers[]) as a parameter to a function, but secretly it treats that parameter as though it was a declared as a pointer (int *Numbers in this case) -- you can even do Numbers += 5 inside DoSomething() to make it point to an array starting at the sixth position! When you declare an array variable such as SomeArray in C++, you must either provide an explicit size or an "initialiser list", which is a comma-separated list of values between braces. It's not possible for the compiler to infer the size of the array based on another array that you are trying to initialise it with, because... You can't copy one array into another, or initialise one array from another in C++. So even if the parameter Numbers was really an array (say of size 1000) and not a pointer, and you specified the size of SomeArray (again as say 1000), the line int SomeArray[1000] = Numbers; would be illegal. To do what you want to do in DoSomething(), first ask yourself: Do I need to change any of the values in Numbers? If so, do I want to prevent the caller from seeing those changes? If the answer to either question is "No", you don't in fact need to make a copy of Numbers in the first place -- just use it as is, and forget about making a separate SomeArray array. If the answer to both questions is "Yes", you will need to make a copy of Numbers in SomeArray and work on that instead. In this case, you should really make SomeArray a C++ vector<int> instead of another array, as this really simplifies things. (Explain the benefits of vectors over manual dynamic memory allocation, including the facts that they can be initialised from other arrays or vectors, and they will call element constructors when necessary, unlike a C-style memcpy().)
536,123
536,187
Unicode Basics on Windows
I have a C++ library which I deliver to other developers. One of them needs i18n, so he asked me if I could add L prefix to the strings in the API. I don't know much about i18n so I have some basic questions: When I compile my lib with Unicode, can other developers use this build as usual ? Or shall developers also change their Visual Studio settings to use unicode ? When I compile my lib with Unicode, do I need to change all the strings in headers and .cpp files? Or is it sufficient to add L prefix to strings in header files ? Thanks in advance! Paul
Adding the L prefix changes the string from a char array into a short array. A better alternative is to wrap all your strings with the "TEXT" macro, i.e. TEXT("My string") If your build is a Unicode build, all your strings become an array of shorts, but if not, they remain as an array of chars. Windows also provides the following types: LPWSTR = short * LPTSTR = short *, or char * if UNICODE not defined LPSTR = char * Don't forget though; even though you've prefixed L or wrapped TEXT to your strings, you need to make sure you're calling the right functions. Standard Windows string API such as lstrlen automatically switch from char * to short * if UNICODE is defined, but you'll need to make sure you're not using functions that only use char *. Functions that your library exports that use strings will also break older applications that use your library since those applications will still be passing and array of chars rather than shorts, so you'll probably want to work in some sort of backwards compatibility in there.
536,148
536,265
C++ string parsing (python style)
I love how in python I can do something like: points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas How can this be done in C++ without too much headache? Performance is not very important, this parsing only happens one time, so simplicity is more important. P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens, it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.
I`d do something like this: ifstream f("data.txt"); string str; while (getline(f, str)) { Point p; sscanf(str.c_str(), "%f, %f, %f\n", &p.x, &p.y, &p.z); points.push_back(p); } x,y,z must be floats. And include: #include <iostream> #include <fstream>
536,267
536,290
C++ slicing in Java / C#
Can C++ slicing apply to other languages too, like Java/C#?
Slicing means that if you assign a subclass instance to a superclass variable, the extra information contained by subclass is "sliced" off, because the superclass variable doesn't have the extra space to store this extra information of the subclass. This doesn't happen in Java nor with C#, because all object variables are references; when you assign a subclass instance to a superclass variable, you actually just copy the reference; the subclass object itself remains intact.
536,314
536,348
Texturing Spheres with Cubemaps (not reflection maps)
I want to texture a sphere with a cube map. So far my research has thrown up many many results on Google involving making OpenGL auto generate texture coordinates, but I want to generate my own coordinates. Given an array of coordinates comprising the vertexes of an imperfect sphere (height mapped but essentially a sphere) centered on 0,0,0, how would one generate texture coordinates for a cube map?
Are you doing this via GLSL? In that case textureCube accepts a vec3 as texture coordinate, which is a unit vector on a sphere. In your case you would take the coordinate of your fragment with respect to the center of the sphere, normalize it and pass it as a coordinate. No need to worry about the internal representation as six two-dimensional textures. uniform samplerCube cubemap; varying vec3 pos; // position of the fragment w.r.t. the center of the sphere /* ... */ vec4 color = textureCube(cubemap, normalize(pos).stp); It works like that also in fixed-pipeline OpenGL. By the way, here is how the coordinates are used internally: the largest coordinate in absolute value is used to select which one of the six textures is read from (the sign selects positive or negative). The other two coordinates are used to lookup the texel in the selected map, after being divided by the largest coordinate.
536,439
537,304
Is modern C++ becoming more prevalent?
When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". std::vector was definitely an advanced topic, something you could learn about if you really wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and SFINAE and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1. My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole? Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using std::vector, and do memory management by manually calling new/delete from their top-level code? As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions? (disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "Modern C++ Design: Generic Programming and Design Patterns Applied", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))
Here's how I think things have evolved. The first generation of C++ programmers were C programmers, who were in fact using C++ as C with classes. Plus, the STL wasn't in place yet, so that's what C++ essentially was. When the STL came out, that advanced things, but most of the people writing books, putting together curricula, and teaching classes had learned C first, then that extra C++ stuff, so the second generation learned from that perspective. As another answer noted, if you're comfortable writing regular for loops, changing to use std::for_each doesn't buy you much except the warm fuzzy feeling that you're doing things the "modern" way. Now, we have instructors and book writers who have been using the whole of C++, and getting their instructions from that perspective, such as Koenig & Moo's Accelerated C++ and Stroustrup's new textbook. So we don't learn char* then std::strings. It's an interesting lesson in how long it takes for "legacy" methods to be replaced, especially when they have a track record of effectiveness.
536,464
536,498
Factory object vs factory function
I have an ABC with several derived classes. To create these derived classes I use the factory pattern: .h file: class derivedFactory { public: base* createInstance(); }; .cpp file: base* derivedFactory::createInstance() { return new derived(); } Is there any advantage to this over just having a free function: .h file: base* derivedFactoryFunction(); .cpp file: base* derivedFactoryFunction() { return new derived(); } Also: I use the abstract factory pattern for dependency injection. I might use an inheritance hierarchy based on the ABC: class objectCreator { public: base* create() = 0; }; Is there any advantage to using this over a function pointer: boost::function<base* ()> factory_ptr; Using boost::bind/lambda this seems to make my code more composable, and if I wish I can wrap a real factory object in it. I can see that there may be a slight performance decrease but this is much to worry about as it is only called during startup.
It depends on how flexible your factory needs to be. If the factory needs external information (like from a configuration file, program options, etc) to determine how to construct objects, than an object makes sense. If all you will ever need is in the arguments to factory, than a function is probably fine. The only advantage I can see to having a pointer is for testing, where you can use a different factory function.
536,469
536,523
I have VS C++ Express. Is there a way to create .DEF files?
I would be extremely appreciative if anybody can help me. I am learning C++ and I have been trying figure this one out. Basically, VS C++ Express does not come with the .DEF template. What other way can I go about creating this file? Is there a parameter I can set in VS so that the linker can create this on the fly? Thanks!!!
You can find the syntax of a DF file defined in places like Exporting from a DLL Using DEF Files Module-Definition (.def) Files The bottom of the first link also mentions alternatives to DEF files (e.g. the __declspec(dllexport) directive). If you don't have a template to create a DEF file, you can create the file manually using your text editor (using the syntax defined above). After you've created it, then add it to your project's linker options (so that the linker uses it).
536,771
536,833
With this technology, would it be possible to compile and run silverlight IL in Flash?
I don't really understand this article. But it sounds like you can compile C/C++ for flash. If that's possible, how hard would it be to compile and run Mono inside flash? Sounds stupid I know...maybe I'm going crazy with my age.
Probably is possible, at the first time, but just compile. Let me see if I got where you want go. Mono can run on-the-fly code, but even now that there is a C# Shell it first compiles to IL (and maybe JIT) and after that it executes. With that technology will be possible to make Flash generate .NET assemblies, but not run them! We will need a .NET IL to AS3 bytecode converter in order to run .NET assemblies in Flash. Probably you are thinking in this, right? But that's not crazy at all, it's compatibility!
536,865
536,901
libstdc++ 64bit and 32bit version on the same machine
I am trying to cross compile a version of my software for a 64bit platform. Can I have the 32bit and 64bit version of libstdc++ installed on the same machine without too much worries of breaking my linux install. The Os is 32bit ubuntu. I have not cross compiled before and just wanted to check that if I set my CFLAGS and LDFLAGS for the appropriate CPU I should be ok once I have the correct versions of libstdc++ installed. I checked a 64bit version of ubuntu however this has a symbolic link lib64 -> lib this would mess up lots if this is the case on a 32bit machine too anyone know how to sort this? I am hitting the following error at the moment [exec] /usr/bin/ld: skipping incompatible /usr/lib/gcc/i486-linux-gnu/4.2.4/libstdc++.so [exec] /usr/bin/ld: skipping incompatible /usr/lib/gcc/i486-linux-gnu/4.2.4/libstdc++.a when searching for -lstdc++ [exec] /usr/bin/ld: skipping incompatible and so on till [exec] /usr/bin/ld: cannot find -lstdc++ [exec] collect2: ld returned 1 exit status Which seems to be due to fact I do not have the 64bit version of libstdc++
Sure you can. Just put them into /usr/lib and /usr/lib64, respectively. Can't check it on Ubuntu, but on Fedora they get there right from the packages: [~#] repoquery -q -l libstdc++.i386 /usr/lib/libstdc++.so.6 /usr/lib/libstdc++.so.6.0.10 [~#] repoquery -q -l libstdc++.x86_64 /usr/lib64/libstdc++.so.6 /usr/lib64/libstdc++.so.6.0.10
537,027
537,099
Is it best practice to use COM properties or COM setters and getters in C++?
I am relatively new to development within COM, and I was wondering what the community standard was for access of COM object properties. I have seen both of the following conventions in code: comObjectPtr->PutValue(value); and comObjectPtr->Value = value; and both seem to work, but I was wondering if there was an inherent advantage or disadvantage to either approach and why.
If I remember correctly, using the property assignment will throw an exception vs. a HRESULT returned in the setter if there is a problem. Same thing is true of the getter method calls vs. property. A "benefit" of using the property is that you can use the prop-get values directly instead of having to declare a variable and getting it before using.
537,595
537,635
Which sector of software industry uses C++?
Like most people, I learnt C++ after C. I learnt C++ because it was one of those languages which fetched jobs. I am still studying (doing masters) though. One of my cousins has been working as a developer for around 12 years. He advises me to learn Java so that I can land up in a good job. He says only few sectors like tele communications use C++ and almost all the enterprise software is developed in Java. I am working as a student technician in my university. The job involves Windows programming in C++. I learnt core Java. I do not know any of those Struts, Hibernate or whatever is out there. To be on the safer side, I am planning to master both. But I think Java is an ocean, though it's easier to program in Java than C++ (this is my opinion. C++ lovers don't kill me). What do you geeks and professionals out there advise me. Do you think I should learn both of them. Which sectors of the software industry use C++?
Best advice I ever got as an undergraduate was from my languages professor, who told me (paraphrasing here): "Don't memorize languages; don't marry yourself to a language. They're just tools. They all do the same basic things. Instead of learning a specific language, learn the foundations of good software development. Then you'll be able to take any language and be successful with it." I feared learning new languages before he told me that. Afterwords, I took his advice to heart and it's made all the difference. Languages are just tools in your toolbox. If you can program and write good software in one language, you can do it in another.
537,820
537,851
What's a good HTML template engine for C++?
Possible Duplicate: C++ HTML template framework, templatizing library, HTML generator library Planning to write a website in C++. Would like to use a template system like Clearsilver, but maybe there's a better alternative?
Wt (pronounced 'witty') is a C++ library and application server for developing and deploying web applications. It is not a 'framework', which enforces a way of programming, but a library.
538,056
538,107
JIT compiler vs offline compilers
Are there scenarios where JIT compiler is faster than other compilers like C++? Do you think in the future JIT compiler will just see minor optimizations, features but follow a similar performance, or will there be breakthroughs that will make it infinitely superior to other compilers? It looks like the multi core paradigm has some promise but it's not universal magic. Any insights?
Yes, there certainly are such scenarios. JIT compilation can use runtime profiling to optimize specific cases based on measurement of the characteristics of what the code is actually doing at the moment, and can recompile "hot" code as necessary. That's not theoretical; Java's HotSpot actually does this. JITters can optimize for the specific CPU and memory configuration in use on the actual hardware where the program happens to be executing. For example, many .NET applications will run in either 32-bit or 64-bit code, depending upon where they are JITted. On 64 bit hardware they will use more registers, memory, and a better instruction set. Virtual method calls inside of a tight loop can be replaced with static calls based on runtime knowledge of the type of the reference. I think there will be breakthroughs in the future. In particular, I think that the combination of JIT compilation and dynamic typing will be significantly improved. We are already seeing this in the JavaScript space with Chrome's V8 and TraceMonkey. I expect to see other improvements of similar magnitude in the not-too-distant future. This is important because even so-called "statically typed" languages tend to have a number of dynamic features.
538,300
538,452
check what number a string ends with in C++
In a C++ MD2 file loader, I have a lot of frames, each with a name that ends with a number, such as stand0 stand1 stand2 stand3 stand4 ... stand10 stand11 run0 run1 run2 etc. How do I get what the string is without the number behind? e.g. a function that changed "stand10" to just "stand"
Just to complete it, one with find_first_of: string new_string = str.substr(0, str.find_first_of("0123456789")); just one line :) Also, for these things, I like to use regular expressions (althought this case is very simple): string new_string = boost::regex_replace(str, boost::regex("[0-9]+$"), "");
538,476
538,510
Change tab stop size in rendered HTML using Qt's QLabel class
I'm rendering some HTML in a QT QLabel. The HTML looks like this: <pre>foo\tbar</pre> (note that I've put "\t" where there is a tab chracter in the code). This renders fine, but the tab character appears to be rendered as eight spaces, whereas I want it to be redered as 4. How can I change this without having to change the source HTML?
According to W3 (HTML4): The horizontal tab character (decimal 9 in [ISO10646] and [ISO88591]) is usually interpreted by visual user agents as the smallest non-zero number of spaces necessary to line characters up along tab stops that are every 8 characters. We strongly discourage using horizontal tabs in preformatted text since it is common practice, when editing, to set the tab-spacing to other values, leading to misaligned documents. It's implementation-defined, essencially. Most, if not all, browsers/renderers use eight spaces for tabs. This cannot be configured in Qt. It is, however somewhat trivial to go through your HTML and replace tabs with however many spaces you wish. Write a simple parser for that. Pseudocode: for each <pre> block { for each line in block { position_in_line = 0 for each character in line { if character is a tab { remove tab character do { add a space character ++position_in_line } while position_in_line % 8 != 0 } else { ++position_in_line } } } } In case you're curious, HTML3 specifies the use of eight-character tabs: Within <PRE>, the tab should be interpreted to shift the horizontal column position to the next position which is a multiple of 8 on the same line; that is, col := (col+8) mod 8.
538,560
538,566
Getting first byte in a char* buffer
I have a char* buffer and I am interested in looking at the first byte in the char* buffer, what is the most optimal way to go about this. EDIT: Based on the negative votes I might want to explain why this question, I am aware of methods but in the code base that I have been looking for getting first byte people do all kinds of crazy things like do a copy of the buffer , copy it to a stream and then do a get.
Just use char firstByte = buffer[0];
538,609
538,627
High resolution timer with C++ and Linux?
Under Windows there are some handy functions like QueryPerformanceCounter from mmsystem.h to create a high resolution timer. Is there something similar for Linux?
It's been asked before here -- but basically, there is a boost ptime function you can use, or a POSIX clock_gettime() function which can serve basically the same purpose.
538,623
538,675
How portable is an STL typedef?
Is the following code portable? template<typename In> struct input_sequence_range : public pair<In,In> { input_sequence_range(In first, In last) : pair<In,In>(first, last) { } }; template<typename Arr> input_sequence_range<Arr*> iseq(Arr* a, typename iterator_traits<Arr*>::difference_type n) { return input_sequence_range<Arr*>(a, a + n); } template<typename Iter> input_sequence_range<Iter> iseq(Iter first, Iter last) { return input_sequence_range<Iter>(first, last); } Specifically I question the portability of overloading on std::iterator_traits<>::difference_type. If it's typedeffed to, say, int* (as bizzare as that may be; I think the standard doesn't forbid this) then calling iseq() for an array of ints would be ambiguous. What does the standard guarantee about iterator_traits<> typedefs?
difference_type must be an integral type so int* is out.
538,661
538,691
How do I draw text with GLUT / OpenGL in C++?
How do I draw a text string onto the screen using GLUT / OpenGL drawing functions?
There are two ways to draw strings with GLUT glutStrokeString will draw text in 3D (source: uwa.edu.au) and glutBitmapString will draw text facing the user (source: sourceforge.net)
538,711
538,777
How do I delete the closest "Point" object in a STD::List to some x,y?
I have a point class like: class Point { public: int x, y; Point(int x1, int y1) { x = x1; y = y1; } }; and a list of points: std::list <Point> pointList; std::list <Point>::iterator iter; I'm pushing points on to my pointList (although the list might contain no Points yet if none have been pushed yet). I have two questions: How can I delete the closest point to some arbitrary (x, y) from the list? Lets say I have the x,y (5,12) and I want to find the Point in the list closest to that point and remove it from the STD::List. I know I'll have to use the distance formula and I'll have to iterate through the list using an iterator but I'm having some trouble conceptualizing how I'll keep track of which point is the closest as I iterate through the list. How can I return an array or list of points within x radius of a given (x,y)? Similar to the last question except I need a list of pointers to the "Point" objects within say 5 radius of a given (x,y). Also, should I return an array or a List? If anyone can help me out, I'm still struggling my way through C++ and I appreciate it.
Use a std::list::iterator variable to keep track of the closest point as you loop through the list. When you get to the end of the list it will contain the closest point and can be used to erase the item. void erase_closest_point(const list<Point>& pointList, const Point& point) { if (!pointList.empty()) { list<Point>::iterator closestPoint = pointList.begin(); float closestDistance = sqrt(pow(point.x - closestPoint->x, 2) + pow(point.y - closestPoint->y, 2)); // for each point in the list for (list<Point>::iterator it = closestPoint + 1; it != pointList.end(); ++it) { const float distance = sqrt(pow(point.x - it->x, 2) + pow(point.y - it->y, 2)); // is the point closer than the previous best? if (distance < closestDistance) { // replace it as the new best closestPoint = it; closestDistance = distance } } pointList.erase(closestPoint); } } Building a list of points within a radius of a given point is similar. Note that an empty radius list is passed into the function by reference. Adding the points to the list by reference will eliminate the need for copying all of the points when returning the vector by value. void find_points_within_radius(vector<Point>& radiusListOutput, const list<Point>& pointList, const Point& center, float radius) { // for each point in the list for (list<Point>::iterator it = pointList.begin(); it != pointList.end(); ++it) { const float distance = sqrt(pow(center.x - it->x, 2) + pow(center.y - it->y, 2)); // if the distance from the point is within the radius if (distance > radius) { // add the point to the new list radiusListOutput.push_back(*it); } } } Again using copy if: struct RadiusChecker { RadiusChecker(const Point& center, float radius) : center_(center), radius_(radius) {} bool operator()(const Point& p) { const float distance = sqrt(pow(center_.x - p.x, 2) + pow(center_.y - p.y, 2)); return distance < radius_; } private: const Point& center_; float radius_; }; void find_points_within_radius(vector<Point>& radiusListOutput, const list<Point>& pointList, const Point& center, float radius) { radiusListOutput.reserve(pointList.size()); remove_copy_if(pointList.begin(), pointList.end(), radiusListOutput.begin(), RadiusChecker(center, radius)); } Note that the sqrt can be removed if you need extra performance since the square of the magnitude works just as well for these comparisons. Also, if you really want to increase performance than consider a data structure that allows for scene partitioning like a quadtree. The first problem is closely related to collision detection and there is a ton of valuable information about that topic available.
538,738
539,992
Looking for a Hash Function /Ordered Int/ to /Shuffled Int/
I am looking for constant time algorithm can change an ordered integer index value into a random hash index. It would nice if it is reversible. I need that hash key is unique for each index. I know that this could be done with a table look up in a large file. I.E. create an ordered set of all ints and then shuffle them randomly and write to a file in random sequence. You could then read them back as you need them. But this would require a seek into a large file. I wonder if there is a simple way to use say a pseudo random generator to create the sequence as needed? Generating shuffled range using a PRNG rather than shuffling the answer by erikkallen of Linear Feedback Shift Registers looks like the right sort of thing. I just tried it but it produces repeats and holes. Regards David Allan Finch
The question is now if you need a really random mapping, or just a "weak" permutation. Assuming the latter, if you operate with unsigned 32-bit integers (say) on 2's complement arithmetics, multiplication by any odd number is a bijective and reversible mapping. Of course the same goes for XOR, so a simple pattern which you might try to use is e.g. unsigned int hash(int x) { return (((x ^ 0xf7f7f7f7) * 0x8364abf7) ^ 0xf00bf00b) * 0xf81bc437; } There is nothing magical in the numbers. So you can change them, and they can be even randomized. The only thing is that the multiplicands must be odd. And you must be calculating with rollaround (ignoring overflows). This can be inverted. To do the inversion, you need to be able to calculate the correct complementary multiplicands A and B, after which the inversion is unsigned int rhash(int h) { return (((x * B) ^ 0xf00bf00b) * A) ^ 0xf7f7f7f7; } You can calculate A and B mathematically, but the easier thing for you is just to run a loop and search for them (once offline, that is). The equation uses XORs mixed with multiplications to make the mapping nonlinear.
538,810
538,821
How do I get the current mouse position in C++ / OpenGL?
I know that I can use a Mouse callback function for when a user clicks the mouse, but what if I want to know the current x/y position without the user clicking? Will I have to use a different callback that gets called on any mouse movement and keep track of the x/y myself or is there a function I can call within GLUT/OpenGL to get it?
Register a glutPassiveMotionFunc callback function See info about callbacks
538,856
539,007
Iterating hierarchy of nodes - Visitor and Composite?
Let's imagine I have a collection of nodes that I use for my Renderer class later on. Then I have a Visitor class that can visit node or whole collection. It's simple because my collection of nodes it's simply a wrapper to the std::list with few extra methods. The problem is I'd like to have a tree like structure for nodes(instead of simple list) so a node can have a parent and n children. That would be handy as I'd like to be able to pass to my Renderer a node and render everything "below" that node. The answer probably is Composite. How can I use together Visitor and Composite? I've read that its often a good combo but my implementations look pretty bad... I'm missing sth.
I have something very similar implemented for our system. I wanted a way to compose hierarchy of geometrical object and render them into the volume. I used composite pattern to compose my description (root was Node and then derived child was compositeNode (list of Nodes). CompositeNode has method accept() which accepts a visitor (Visitor) and then inside the accept() you do visitor->visit(this). Thus your visitor hierarchy has base class as NodeVisitor and derived visitors like RenderVisitor (renders objects), ReportVisitor (dumped node info into text). Your base class will need to accept both base and specialized node types. So yes, combo works and I have working code but I agree that design takes more effort than what you would read online (Wiki or toy example). Hope this helps
539,058
539,099
How do I have an icon displayed when a setup CD is autoplayed in Windows
I have a setup CD to install a visual studio C++ application I made. It has three files: setup.exe, AUTORUN.INF, and app.msi. When I insert the CD the Windows AutoPlay popup shows a generic icon. How do I have my own icon displayed for setup.exe. I also want this for the drive icon after I insert the CD, I think they're related.
I hate autostart. In AUTORUN.INF, you can specify the drive icon just next to the setup program: [AutoRun] open=setup.exe icon=*youricon*.ico
539,218
539,230
How do I specify a publisher for the setup.exe when a setup CD is autoplayed in Windows
I have a setup CD to install a visual studio C++ application I made. The AutoPlay popup shows "Publisher not specified" for running setup.exe. How do I specify a publisher?
You need to Sign the executable with a digital certificate. This is to verify that the executable has not been tampered with and is from the publisher.
539,251
539,307
Getting the size of an indiviual field from a c++ struct field
The short version is: How do I learn the size (in bits) of an individual field of a c++ field? To clarify, an example of the field I am talking about: struct Test { unsigned field1 : 4; // takes up 4 bits unsigned field2 : 8; // 8 bits unsigned field3 : 1; // 1 bit unsigned field4 : 3; // 3 bits unsigned field5 : 16; // 16 more to make it a 32 bit struct int normal_member; // normal struct variable member, 4 bytes on my system }; Test t; t.field1 = 1; t.field2 = 5; // etc. To get the size of the entire Test object is easy, we just say sizeof(Test); // returns 8, for 8 bytes total size We can get a normal struct member through sizeof(((Test*)0)->normal_member); // returns 4 (on my system) I would like to know how to get the size of an individual field, say Test::field4. The above example for a normal struct member does not work. Any ideas? Or does someone know a reason why it cannot work? I am fairly convinced that sizeof will not be of help since it only returns size in bytes, but if anyone knows otherwise I'm all ears. Thanks!
You can calculate the size at run time, fwiw, e.g.: //instantiate Test t; //fill all bits in the field t.field1 = ~0; //extract to unsigned integer unsigned int i = t.field1; ... TODO use contents of i to calculate the bit-width of the field ...
539,358
540,039
Calling functions in a DLL from C++
I have a solution in VS 2008 with 2 projects in it. One is a DLL written in C++ and the other is a simple C++ console application created from a blank project. I would like know how to call the functions in the DLL from the application. Assume I am starting with a blank C++ project and that I want to call a function called int IsolatedFunction(int someParam) How do I call it?
There are many ways to do this but I think one of the easiest options is to link the application to the DLL at link time and then use a definition file to define the symbols to be exported from the DLL. CAVEAT: The definition file approach works bests for undecorated symbol names. If you want to export decorated symbols then it is probably better to NOT USE the definition file approach. Here is an simple example on how this is done. Step 1: Define the function in the export.h file. int WINAPI IsolatedFunction(const char *title, const char *test); Step 2: Define the function in the export.cpp file. #include <windows.h> int WINAPI IsolatedFunction(const char *title, const char *test) { MessageBox(0, title, test, MB_OK); return 1; } Step 3: Define the function as an export in the export.def defintion file. EXPORTS IsolatedFunction @1 Step 4: Create a DLL project and add the export.cpp and export.def files to this project. Building this project will create an export.dll and an export.lib file. The following two steps link to the DLL at link time. If you don't want to define the entry points at link time, ignore the next two steps and use the LoadLibrary and GetProcAddress to load the function entry point at runtime. Step 5: Create a Test application project to use the dll by adding the export.lib file to the project. Copy the export.dll file to ths same location as the Test console executable. Step 6: Call the IsolatedFunction function from within the Test application as shown below. #include "stdafx.h" // get the function prototype of the imported function #include "../export/export.h" int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // call the imported function found in the dll int result = IsolatedFunction("hello", "world"); return 0; }
539,536
539,570
Disambiguate operator[] binding
I'm trying to compile code from an open source project, and I'm running into a problem where gcc claims that a particular line of code has an ambiguous interpretation. The problem involves a templated class and these two methods: template <class X> class A { public: X& operator[] (int i) { ... } operator const X* () { ... } }; When this is used along the lines of this: A<B*> a; B* b = a[i]; gcc complains about the ambiguous resolution of a[i]. The problem is made more clear by replacing the definition of A with its specific instantiation: class A_B { public: B*& operator[] (int i) { ... } operator B* const * () { ... } }; The problem is that there are two ways of interpreting B* b = a[i]: // First interpretation (array-like behaviour first) B*& b1 = a[i]; B* b2 = (B*) b1; // Second interpretation (casting behaviour first) B* const * b1 = (B* const *) a; B* b2 = b1[a]; My question is this: Is there some way to provide a preferred interpretation, preferably by making the casting version undesirable without an explicit cast, so that I don't have to modify every line that tries to invoke A[]? I realize that the interpretation is legitimately ambiguous, but I know what the intention of the code is, and I would like to communicate that to the compiler with minimal changes. Edit: It seems my example doesn't cause the bug in question, so I'm not correctly summarizing the original code, nor correctly identifying the problem. I'll try to get an example that produces the problem first, sorry folks.
The following code compiles for me with g++ 3.x. I don't think your analysis of the problem is correct, but in any case could you post the error message you are getting. template <class X> struct A { X& operator[] (int i) { static X x; return x; } operator const X* () { return 0; } }; class B {}; int main() { A<B*> a; B* b = a[0]; }
539,628
539,827
Why doesn't this C++ STL allocator allocate?
I'm trying to write a custom STL allocator that is derived from std::allocator, but somehow all calls to allocate() go to the base class. I have narrowed it down to this code: template <typename T> class a : public std::allocator<T> { public: T* allocate(size_t n, const void* hint = 0) const { cout << "yo!"; return 0; } }; int main() { vector<int, a<int>> v(1000, 42); return 0; } I expect "Yo!" to get printed, followed by some horrible error because I don't actually allocate anything. Instead, the program runs fine and prints nothing. What am I doing wrong? I get the same results in gcc and VS2008.
You will need to provide a rebind member template and the other stuff that is listed in the allocator requirements in the C++ Standard. For example, you need a template copy constructor which accepts not only allocator<T> but also allocator<U>. For example, one code might do, which a std::list for example is likely to do template<typename Allocator> void alloc1chunk(Allocator const& alloc) { typename Allocator::template rebind< wrapper<typename Allocator::value_type> >::other ot(alloc); // ... } The code will fail if there either exist no correct rebind template, or there exist no corresponding copy constructor. You will get nowhere useful with guessing what the requirements are. Sooner or later you will have to do with code that relies on one part of those allocator requirements, and the code will fail because your allocator violates them. I recommend you take a look at them in some working draft your your copy of the Standard in 20.1.5.
539,824
541,827
Problem with thread-safe queue?
I'm trying to write a thread-safe queue using pthreads in c++. My program works 93% of the time. The other 7% of the time it other spits out garbage, OR seems to fall asleep. I'm wondering if there is some flaw in my queue where a context-switch would break it? // thread-safe queue // inspired by http://msmvps.com/blogs/vandooren/archive/2007/01/05/creating-a-thread-safe-producer-consumer-queue-in-c-without-using-locks.aspx // only works with one producer and one consumer #include <pthread.h> #include <exception> template<class T> class tsqueue { private: volatile int m_ReadIndex, m_WriteIndex; volatile T *m_Data; volatile bool m_Done; const int m_Size; pthread_mutex_t m_ReadMutex, m_WriteMutex; pthread_cond_t m_ReadCond, m_WriteCond; public: tsqueue(const int &size); ~tsqueue(); void push(const T &elem); T pop(); void terminate(); bool isDone() const; }; template <class T> tsqueue<T>::tsqueue(const int &size) : m_ReadIndex(0), m_WriteIndex(0), m_Size(size), m_Done(false) { m_Data = new T[size]; pthread_mutex_init(&m_ReadMutex, NULL); pthread_mutex_init(&m_WriteMutex, NULL); pthread_cond_init(&m_WriteCond, NULL); pthread_cond_init(&m_WriteCond, NULL); } template <class T> tsqueue<T>::~tsqueue() { delete[] m_Data; pthread_mutex_destroy(&m_ReadMutex); pthread_mutex_destroy(&m_WriteMutex); pthread_cond_destroy(&m_ReadCond); pthread_cond_destroy(&m_WriteCond); } template <class T> void tsqueue<T>::push(const T &elem) { int next = (m_WriteIndex + 1) % m_Size; if(next == m_ReadIndex) { pthread_mutex_lock(&m_WriteMutex); pthread_cond_wait(&m_WriteCond, &m_WriteMutex); pthread_mutex_unlock(&m_WriteMutex); } m_Data[m_WriteIndex] = elem; m_WriteIndex = next; pthread_cond_signal(&m_ReadCond); } template <class T> T tsqueue<T>::pop() { if(m_ReadIndex == m_WriteIndex) { pthread_mutex_lock(&m_ReadMutex); pthread_cond_wait(&m_ReadCond, &m_ReadMutex); pthread_mutex_unlock(&m_ReadMutex); if(m_Done && m_ReadIndex == m_WriteIndex) throw "queue empty and terminated"; } int next = (m_ReadIndex +1) % m_Size; T elem = m_Data[m_ReadIndex]; m_ReadIndex = next; pthread_cond_signal(&m_WriteCond); return elem; } template <class T> void tsqueue<T>::terminate() { m_Done = true; pthread_cond_signal(&m_ReadCond); } template <class T> bool tsqueue<T>::isDone() const { return (m_Done && m_ReadIndex == m_WriteIndex); } This could be used like this: // thread 1 while(cin.get(c)) { queue1.push(c); } queue1.terminate(); // thread 2 while(!queue1.isDone()) { try{ c = queue1.pop(); } catch(char const* str){break;} cout.put(c); } If anyone sees a problem with this, please say so :)
If you want anything with decent performance I would strongly suggest dumping your R/W lock and just use a very simple spinlock. Or if you really think you can get the performance you want with R/W lock, i would roll your own based on this design(single word R/W Spinlock) from Joe Duffy.
539,877
539,887
Should non-public functions be unit tested and how?
I am writing unit tests for some of my code and have run into a case where I have an object with a small exposed interface but complex internal structures as each exposed method runs through a large number of internal functions including dependancies on the object's state. This makes the methods on the external interface quite difficult to unit test. My initial question is should I be aiming to unit test these internal functions as well, as they are simpler and hence easier to write tests for? My gut feeling says yes, which leads to the follow-up question of if so, how would I go about doing this in C++? The options I've come up with are to change these internal functions from private to protected and use either a friend class or inheritence to access these internal functions. Is this the best/only method of doing this will preserving some of the semantics of keeping the internal methods hidden?
Short answer: yes. As to how, I caught a passing reference on SO a few days ago: #define private public in the unit testing code evaluated before the relevant headers are read... Likewise for protected. Very cool idea. Slightly longer answer: Test if the code is not obviously correct. Which means essentially any code that does something non-trivial. On consideration, I am wondering about this. You won't be able to link against the same object file that you use in the production build. Now, unit testing is a bit of an artificial environment, so perhaps this is not a deal-breaker. Can anyone shed some light on the pros and cons of this trick?
539,908
541,841
Interprocess Communication Between C# application and unmanaged C++ application
I have two Windows services, the first one written in C# and the second written in unmanaged C++, I want to know how can I do two-way interprocess communication.
If the interprocess communication is always going to be done on the same machine, named pipes is the way to go because they are faster than other options. However, if there is even the slightest chance that this communication might occur across machine boundaries at some point, go with the socket approach. For C++, you'll need the winsock2.h header file. In C#, use the System.Net.Sockets namespace. It's been a while since I've done unmanaged C++, but my recollection is that you'll have to write less C++ code if you create the server on the C++ side and then use the TcpClient class on the C# side.
539,939
540,193
Isn't it possible to use 'Repeats' in the lookaheads for boost:regex?
I'm trying to extract some variables in my C++ code nested in blocks for example, if I have DEL_TYPE_NONE, DEL_TYPE_DONE, DEL_TYPE_WAIT, I'd like to match "DEL_TYPE_NONE" "DEL_TYPE_DONE" "DEL_TYPE_WAIT" I made my pattern like this, std::string pat("(?<=^[ \\t]?)[A-Z0-9_]+(?=,$)"); but I'm keep getting error message when compiler is tyring to read my pattern. I don't understand but there is problem with ? mark after \\t If I get rid of ? mark then it compiles and find only "DEL_TYPE_WAIT" why can't I use Repeats in the Lookahead? plz help me I'm totaly lost here ;( thank you
I found the answer. No from this manual Lookbehind (?<=pattern) consumes zero characters, only if pattern could be matched against the characters preceding the current position (pattern must be of fixed length).