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
601,970
601,984
How do I utilise all the cores for nmake?
I just got a new quad core computer and noticed that nmake is only using 1 process. I used to use make which had the switch -j4 for launching 4 processes. What is the nmake equivalent? [edit] Based on the information below I have been able to add a command to my qmake project file: QMAKE_CXXFLAGS += /MP Which effectively did it for me. Many thanks.
According to MSDN, there's no such option for nmake. You can however make the compiler build multiple files in parallel by using the /MP option with the VC++ command line compiler and passing multiple files at the same time: > cl /MP a.cpp b.cpp c.cpp However note that most Makefiles don't call the compiler like this - they usual invoke the compiler separate for each individual source file, which would prevent the /MP option from doing anything useful.
602,108
609,269
Design for generic options to algorithms
I want to know if there is a design pattern for specifying options to a set of algorithms. I am using C++. Let me describe my problem. I am having a set of algorithms and these algorithms have different options. I want to design a single point access to these algorithms. Something similar to a strategy pattern. This single point access is a controller class which takes input as a generic options class. Depending upon the options, a suitable algorithm will be used. I want to generalize these options so that i can extend algorithms and the client. Thanks, Amol
Building on Konrad's suggestion of using policy types, if your algorithms require parameters at construction time, you can handle this cleanly by requiring that any Policy class has a nested type called Params, and then provide a constructor inside fancy_algorithm<Policy> that takes an argument of this type and passes it to the contained Policy object: template <typename Policy> class fancy_algorithm : private Policy { public: typedef typename Policy::Params Params; // Need to redeclare :( explicit fancy_algorithm(Params params = Params()) : Policy(params) {} }; Any relevant parameters need to be packaged into a single object of type Policy::Params. The Policy class is always constructed with a single argument of type Policy::Params. To work with policy classes that (may) require no parameters, provide a default constructor (or use the implicitly declared one) in Params, not in Policy. This way, by using a default value for the fancy_algorithm<Policy> constructor as above, we enable convenient default-construction of a fancy_algorithm<Policy> whenever Policy::Params has a default constructor (i.e. when the Policy doesn't require any parameters). No safety is lost: if Policy::Params lacks a default constructor (indicating that some parameters are required), any attempt to default-construct a fancy_algorithm<Policy> object will fail at compile time. Example: struct multiply_by_params { multiply_by_params(int x /* = 42 */) : _x(x) {} // See bottom int get() const { return _x; } // Or, just make multiply_by a friend private: int _x; }; struct multiply_by { typedef multiply_by_params Params; multiply_by(Params p) : _x(p.get()) { /* Other initialisation */ } // Other code implementing the strategy (e.g. an operator()()) ... private: int _x; }; fancy_algorithm<multiply_by> a(69); // Always compiles fancy_algorithm<multiply_by> b; // Compiles iff /* = 42 */ is uncommented
602,175
602,219
Debugging a DLL in VS2005 (C++)
I have a dll project in a solution that I want to debug. The calling application is in a different path and the DLL must be placed inside that path. When I build the debug version and copy+paste the produced DLL into the calling application's path, I get an error message that there are no symbols and that the binary wasn't built by the project. It asks me if I want to continue. This method used to work in visual c++ 6.0 but now it never hits any breakpoints.. How do I do this in VS2005? Thanks.
Make sure the pdb file for the dll is also in the application's path. Or alternatively compile your dll with the /Z7 compiler option, that will trigger the old-style debug info as it was used in MSVC 6.0. If you compile like this, you will be able to copy just the dll. Or alternatively in the 'Modules' window, right-click your dll and select 'Load Symbols', then point the dialog to the original location of your dll.
602,410
602,424
may COM server reallocate ([in, out] CACLSID * arg)?
With a COM interface method declared as this: [ object, uuid(....), ] interface IFoo : IUnknown { HRESULT Foo([in, out] CACLSID * items); } With regards to marshalling, is the server allowed to reallocate the counted array? (I think it is, but I am not sure anymore) Its current implementation only replaces the existing ID's, but I'd like to implement a change (that would not break contract) that may return more items without introducing a new interface. [edit] please note that CACLSID is already an array, containing a count and a pointer.
I have not done COM for a very long time but is it even possible to allocate a new array? In that case should it not be CACLSID ** items ?
602,580
602,594
How can I use C++ class in Python?
I have implemented a class in C++. I want to use it with Python. Please suggest step by step method and elaborate each step. Somthing like this... class Test{ private: int n; public: Test(int k){ n=k; } void setInt(int k){ n = k; } int getInt(){ return n; } }; Now, in Python >>> T1 = Test(12) >>> T1.getInt() 12 >>> T1.setInt(32) >>> T1.getInt() 32 Please suggest.How can I do this ? NOTE: I would like to know manual way to do that. I don't want any third party library dependency.
Look into Boost.Python. It's a library to write python modules with C++. Also look into SWIG which can also handle modules for other scripting languages. I've used it in the past to write modules for my class and use them within python. Works great. You can do it manually by using the Python/C API, writing the interface yourself. It's pretty lowlevel, but you will gain a lot of additional knowledge of how Python works behind the scene (And you will need it when you use SWIG anyway).
602,593
602,760
Template or abstract base class?
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++? I see mainly two possibilities: Use an abstract base class and pass concrete object in Use a template Here is a little example, implemented in the various versions: Version 1: Abstract base class class Brake { public: virtual void stopCar() = 0; }; class BrakeWithABS : public Brake { public: void stopCar() { ... } }; class Car { Brake* _brake; public: Car(Brake* brake) : _brake(brake) { brake->stopCar(); } }; Version 2a: Template template<class Brake> class Car { Brake brake; public: Car(){ brake.stopCar(); } }; Version 2b: Template and private inheritance template<class Brake> class Car : private Brake { using Brake::stopCar; public: Car(){ stopCar(); } }; Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)? I realize there is not a big difference between version 2a and 2b, see C++ FAQ. Can you comment on these possibilities?
This depends on your goals. You can use version 1 if you Intend to replace brakes of a car (at runtime) Intend to pass Car around to non-template functions I would generally prefer version 1 using the runtime polymorphism, because it is still flexible and allows you to have the Car still have the same type: Car<Opel> is another type than Car<Nissan>. If your goals are great performance while using the brakes frequently, i recommend you to use the templated approach. By the way, this is called policy based design. You provide a brake policy. Example because you said you programmed in Java, possibly you are not yet too experienced with C++. One way of doing it: template<typename Accelerator, typename Brakes> class Car { Accelerator accelerator; Brakes brakes; public: void brake() { brakes.brake(); } } If you have lots of policies you can group them together into their own struct, and pass that one, for example as a SpeedConfiguration collecting Accelerator, Brakes and some more. In my projects i try to keep a good deal of code template-free, allowing them to be compiled once into their own object files, without needing their code in headers, but still allowing polymorphism (via virtual functions). For example, you might want to keep common data and functions that non-template code will probably call on many occasions in a base-class: class VehicleBase { protected: std::string model; std::string manufacturer; // ... public: ~VehicleBase() { } virtual bool checkHealth() = 0; }; template<typename Accelerator, typename Breaks> class Car : public VehicleBase { Accelerator accelerator; Breaks breaks; // ... virtual bool checkHealth() { ... } }; Incidentally, that is also the approach that C++ streams use: std::ios_base contains flags and stuff that do not depend on the char type or traits like openmode, format flags and stuff, while std::basic_ios then is a class template that inherits it. This also reduces code bloat by sharing the code that is common to all instantiations of a class template. Private Inheritance? Private inheritance should be avoided in general. It is only very rarely useful and containment is a better idea in most cases. Common case where the opposite is true when size is really crucial (policy based string class, for example): Empty Base Class Optimization can apply when deriving from an empty policy class (just containing functions). Read Uses and abuses of Inheritance by Herb Sutter.
602,936
602,979
Print Date and Time In Visual Studio C++ build?
How would I print the date and time for the purposes of the build. Ie: When the console for my application starts up I want to do this: Binary Build date: 03/03/2009 @ 10:00AM I think this would be a super useful function for all applications to have behind the scenes for programmers, especially in a team environment. Is there a simple way to do this using Visual Studio 2008 in C++. Thanks.
Use preprocessor's __DATE__ and __TIME__. printf("Binary build date: %s @ %s\n", __DATE__, __TIME__); For making sure that cpp file that contains this code is really compiled, I use touch-utility for file as a pre-build step: touch file.cpp Touch.bat: @copy nul: /b +%1 tmp.$$$ @move tmp.$$$ %1
603,114
608,267
Fonts for Carbon OpenGL app on OS X
I'm trying to add text rendering to a Carbon OpenGL app I'm developing for OS X. Since the aglUseFont is now deprecated, I'm looking for another way to add text as well as be able to query the glyph properties (i.e. width, height, spacing, etc) So far I've investigated CoreText and ATSUI but both without much luck. Please help me!! Thanks!
In the end I just went with good old glBitmap for my fonts. Found an apple dev sample that created rendered each character and got its pertinent info (width, height, offset, etc.) However, if I get the time to do some more work on it later, I plan on using the FreeType project as was suggested above. Thanks!
603,378
603,448
c++ namespace usage and naming rules
On the project we are trying to reach an agreement on the namespace usage. We decided that the first level will be "productName" and the second is "moduleName". productName::moduleName Now if the module is kind of utility module there is no problem to add third namespace. For example to add "str": productName::utilityModuleName::str - to divide space where all "strings" related stuff will go. If the module is the main business module we have many opportunities and almost no agreement. For example class productName::mainModuleName::DomainObject and class productName::mainModuleName::DomainObjectSomethingElseViewForExample can be both at namespace productName::mainModuleName::domainObject class Data class ViewForExample Why should we create inner not private classes and not namespaces? Why should we create class where all methods are static (except cases when this class is going to be template parameter)? Project consist of 1Gb of source code. So, what is the best practice to divide modules on namespaces in the c++?
What namespaces are for: Namespaces are meant to establish context only so you don't have naming confilcts. General rules: Specifying too much context is not needed and will cause more inconvenience than it is worth. So you want to use your best judgment, but still follow these 2 rules: Don't be too general when using namespaces Don't be too specific when using namespaces I would not be so strict about how to use namespace names, and to simply use namespaces based on a related group of code. Why namespaces that are too general are not helpful: The problem with dividing the namespace starting with the product name, is that you will often have a component of code, or some base library that is common to multiple products. You also will not be using Product2 namespaces inside Product1, so explicitly specifying it is pointless. If you were including Product2's files inside Product1, then is this naming conversion still useful? Why namespaces that are too specific are not helpful: When you have namespaces that are too specific, the line between these distinct namespaces start to blur. You start using the namespaces inside each other back and forth. At this time it's better to generalize the common code together under the same namespace. Classes with all static vs templates: "Why should we create inner not private classes and not namespaces? Why should we create classes where all methods are static" Some differences: Namespaces can be implied by using the using keyword Namespaces can be aliased, classes are types and can be typedef'ed Namespaces can be added to; you can add functionality to it at any time and add to it directly Classes cannot be added to without making a new derived class Namespaces can have forward declarations With classes you can have private members and protected members Classes can be used with templates Exactly how to divide: "Project consist of 1Gb of source code. So, what is the best practice to divide modules on namespaces in the c++?" It's too subjective to say exactly how to divide your code without the exact source code. Dividing based on the modules though sounds logical, just not the whole product.
603,390
603,632
Inline member functions in C++
ISO C++ says that the inline definition of member function in C++ is the same as declaring it with inline. This means that the function will be defined in every compilation unit the member function is used. However, if the function call cannot be inlined for whatever reason, the function is to be instantiated "as usual". (http://msdn.microsoft.com/en-us/library/z8y1yy88%28VS.71%29.aspx) The problem I have with this definition is that it does not tell in which translation unit it would be instantiated. The problem I encountered is that when facing two object files in a single static library, both of which have the reference to some inline member function which cannot be inlined, the linker might "pick" an arbitrary object file as a source for the definition. This particular choice might introduce unneeded dependencies. (among other things) For instance: In a static library A.h: class A{ public: virtual bool foo() { return true; } }; U1.cpp: A a1; U2.cpp: A a2; and lots of dependencies In another project main.cpp: #include "A.h" int main(){ A a; a.foo(); return 0; } The second project refers the first. How do I know which definition the compiler will use, and, consequently which object files with their dependencies will be linked in? Is there anything the standard says on that matter? (Tried, but failed to find that) Thanks Edit: since I've seen some people misunderstand what the question is, I'd like to emphasize: If the compiler decided to create a symbol for that function (and in this case, it will, because of 'virtualness', there will be several (externally-seen) instantiations in different object file, which definition (from which object file?) will the linker choose?)
When you have an inline method that is forced to be non-inlined by the compiler, it will really instantiate the method in every compiled unit that uses it. Today most compilers are smart enough to instantiate a method only if needed (if used) so merely including the header file will not force instantiation. The linker, as you said, will pick one of the instantiations to include in the executable file - but keep in mind that the record inside the object module is of a special kind (for instance, a COMDEF) in order to give the linker enough information to know how to discard duplicated instances. These records will not, therefore, result in unwanted dependencies between modules, because the linker will use them with less priority than "regular" records to resolve dependencies. In the example you gave, you really don't know, but it doesn't matter. The linker won't resolve dependencies based on non-inlined instances alone ever. The result (in terms of modules included by the linker) will be as good as if the inline method didn't exist.
604,024
604,227
Now to remove elements that match a predicate?
I have a source container of strings I want to remove any strings from the source container that match a predicate and add them into the destination container. remove_copy_if and other algorithms can only reorder the elements in the container, and therefore have to be followed up by the erase member function. My book (Josuttis) says that remove_copy_if returns an iterator after the last position in the destination container. Therefore if I only have an iterator into the destination container, how can I call erase on the source container? I have tried using the size of the destination to determine how far back from the end of the source container to erase from, but had no luck. I have only come up with the following code, but it makes two calls (remove_if and remove_copy_if). Can someone let me know the correct way to do this? I'm sure that two linear calls is not the way to do this. #include <iostream> #include <iterator> #include <vector> #include <string> #include <algorithm> #include <functional> using namespace std; class CPred : public unary_function<string, bool> { public: CPred(const string& arString) :mString(arString) { } bool operator()(const string& arString) const { return (arString.find(mString) == std::string::npos); } private: string mString; }; int main() { vector<string> Strings; vector<string> Container; Strings.push_back("123"); Strings.push_back("145"); Strings.push_back("ABC"); Strings.push_back("167"); Strings.push_back("DEF"); cout << "Original list" << endl; copy(Strings.begin(), Strings.end(),ostream_iterator<string>(cout,"\n")); CPred Pred("1"); remove_copy_if(Strings.begin(), Strings.end(), back_inserter(Container), Pred); Strings.erase(remove_if(Strings.begin(), Strings.end(), not1(Pred)), Strings.end()); cout << "Elements beginning with 1 removed" << endl; copy(Strings.begin(), Strings.end(),ostream_iterator<string>(cout,"\n")); cout << "Elements beginning with 1" << endl; copy(Container.begin(), Container.end(),ostream_iterator<string>(cout,"\n")); return 0; }
I see your point, that you'd like to avoid doing two passes over your source container. Unfortunately, I don't believe there's a standard algorithm that will do this. It would be possible to create your own algorithm that would copy elements to a new container and remove from the source container (in the same sense as remove_if; you'd have to do an erase afterward) in one pass. Your container size and performance requirements would dictate whether the effort of creating such an algorithm would be better than making two passes. Edit: I came up with a quick implementation: template<typename F_ITER, typename O_ITER, typename FTOR> F_ITER move_if(F_ITER begin, F_ITER end, O_ITER dest, FTOR match) { F_ITER result = begin; for(; begin != end; ++begin) { if (match(*begin)) { *dest++ = *begin; } else { *result++ = *begin; } } return result; } Edit: Maybe there is confusion in what is meant by a "pass". In the OP's solution, there is a call to remove_copy_if() and a call to remove_if(). Each of these will traverse the entirety of the original container. Then there is a call to erase(). This will traverse any elements that were removed from the original container. If my algorithm is used to copy the removed elements to a new container (using begin() the original container for the output iterator will not work, as dirkgently demonstrated), it will perform one pass, copying the removed elements to the new container by means of a back_inserter or some such mechanism. An erase will still be required, just as with remove_if(). One pass over the original container is eliminated, which I believe is what the OP was after.
604,050
605,635
Switch from Microsofts STL to STLport
I'm using quite much STL in performance critical C++ code under windows. One possible "cheap" way to get some extra performance would be to change to a faster STL library. According to this post STLport is faster and uses less memory, however it's a few years old. Has anyone made this change recently and what were your results?
I haven't compared the performance of STLPort to MSCVC but I'd be surprised if there were a significant difference. (In release mode of course - debug builds are likely to be quite different.) Unfortunately the link you provided - and any other comparison I've seen - is too light on details to be useful. Before even considering changing standard library providers I recommend you heavily profile your code to determine where the bottlenecks are. This is standard advice; always profile before attempting any performance improvements! Even if profiling does reveal performance issues in standard library containers or algorithms I'd suggest you first analyse how you're using them. Algorithmic improvements and appropriate container selection, especially considering Big-O costs, are far more likely to bring greater returns in performance.
604,329
604,528
how-to: programmatic install on windows?
Can anyone list the steps needed to programatically install an application on Windows. Aside from copying the files where they need to be, what are the additional steps needed so that your app will be a first-class citizen in Windows (i.e. show up in the programs list, uninstall list...etc.) I tried to google this, but had no luck. BTW: This is for an unmanaged c++ application (developed in Qt), so I'd rather not involve the .net framework if I don't have to.
I think the theme to the answers you'll see here is that you should use an installation program and that you should not write the installer yourself. Use one of the many installer-makers, such as Inno Setup, InstallSheild, or anything else someone recommends. If you try to write the installer yourself, you'll probably do it wrong. This isn't a slight against you personally. It's just that there are a lot of little details that an installer should consider, and a lot of things that can go wrong, and if you want to write the installer yourself, you're just going to have to get all those things right. That means lots of research and lots of testing on your part. Save yourself the trouble. Besides copying files, installation tasks vary quite a bit depending on what your program needs. Maybe you need to put an icon on the Start menu; an installer tool should have a way to make that happen very easily, automatically filling in the install location that the customer chose earlier in the installation, and maybe even choosing the right local language for the shortcut's label. You might need to create registry entries, such as for file associations or licensing. Your installer tool should already have an easy way to specify what keys and values to create or modify. You might need to register a COM server. That's a common enough action that your installer tool probably has a way of specifying that as part of the post-file-copy operation. If there are some actions that your chosen installer tool doesn't already provide for, the tool will probably offer a way to add custom actions, perhaps through a scripting language, or perhaps through linking external code from a DLL you would write that gets included with your installer. Custom actions might include downloading an update from a specific Web site, sending e-mail, or taking an inventory of what other products from your company are already installed. A couple of final things that an installer tool should provide are ways to apply upgrades to an existing installation, and a way to uninstall the program, undoing all those installation tasks (deleting files, restoring backups, unregistering COM servers, etc.).
604,372
604,386
about c++ exceptions. func() throw()
i am reading this page http://www.cplusplus.com/doc/tutorial/exceptions.html it says if i write function() throw(); no exceptions can be thrown in that function. I tried in msvc 2005 writing throw(), throw(int), throw() and nothing at all. each had the exact same results. Nothing. I threw int, char*, another type and it was all caught the same way. It looks like throw doesnt affect it at all. What does function() throw() actually do?
See this article for details on C++ exception specifications and Microsoft's implementation: Microsoft Visual C++ 7.1 ignores exception specifications unless they are empty. Empty exception specifications are equivalent to __declspec(nothrow), and they can help the compiler to reduce code size. [...] If it sees an empty exception specification, it will assume you know what you are doing and optimize away the mechanics for dealing with exceptions. If your function throws anyway - well, shame on you. Use this feature only if you are 100% positive your function does not throw and never will.
604,431
604,505
C++ reading unsigned char from file stream
I want to read unsigned bytes from a binary file. So I wrote the following code. #include <iostream> #include <fstream> #include <vector> #include <istream> std::string filename("file"); size_t bytesAvailable = 128; size_t toRead = 128; std::basic_ifstream<unsigned char> inf(filename.c_str(), std::ios_base::in | std::ios_base::binary) ; if (inF.good()) { std::vector<unsigned char> mDataBuffer; mDataBuffer.resize(bytesAvailable) ; inF.read(&mDataBuffer[0], toRead) ; size_t counted = inF.gcount() ; } This results in reading in always 0 bytes as shown by the variable counted. There seem to be references on the web saying that I need to set the locale to make this work. How to do this exactly is not clear to me. The same code works using the data type 'char' instead of 'unsigned char' The above code using unsigned char seems to work on Windows but fails running in a colinux Fedora 2.6.22.18 . What do I need to do to get it to work for linux?
C++ does require the implementation only to provide explicit specializations for two versions of character traits: std::char_traits<char> std::char_traits<wchar_t> The streams and strings use those traits to figure out a variety of things, like the EOF value, comparison of a range of characters, widening of a character to an int, and such stuff. If you instantiate a stream like std::basic_ifstream<unsigned char> You have to make sure that there is a corresponding character trait specialization that the stream can use and that this specialization does do useful things. In addition, streams use facets to do actual formatting and reading of numbers. Likewise you have to provide specializations of those too manually. The standard doesn't even require the implementation to have a complete definition of the primary template. So you could aswell get a compile error: error: specialization std::char_traits could not be instantiated. I would use ifstream instead (which is a basic_ifstream<char>) and then go and read into a vector<char>. When interpreting the data in the vector, you can still convert them to unsigned char later.
604,470
604,918
Getting at unmanaged C++ functions from C#
I have some ANSI standard C code which is authoritative. What that means is that although I have the source, I can not translate to another language nor modify calling arguments, as those actions would invalidate the authority. There are over 150 functions. I can make incidental changes, such as change the file names from .C to .CPP so that it compiles using Visual Studio 2009's C++ compiler, which I have done. Compiler directives and such can also be added. I can also go through a wrapper layer, if necessary. Another restriction is my company does not want me to use the unsafe key word in any C# code. I need to get at these functions from a C# program. A typical C/C++ function looks like this: double SomeFunction(double a, double[3] vec, double[3][3] mat); Where the array contents are sometimes input, sometimes output, and rarely both. I first tried making an unmanaged DLL (with the functions marked Extern C). Functions with only simple arguments (int, double) worked fine, but I could not determine how to Marshal the arrays. (Actually, I did find some sample code, but it was extremely complex and unreasonable to duplicate 150 times.) I then tried two projects within the same solution, one in C++ and the other in C#. In the C++ project, I created a managed function which just called the original function which was marked as unmanaged. This was extremely clean and simple, and again, simple arguments worked fine. But for arrays, I couldn't find how to make the argument types match across the C# to C++ boundary: Argument '2': cannot convert from 'double[]' to 'double*' (and as mentioned above, I can't use unsafe to get a pointer). Certainly what I am trying to do must be possible. What is the best way to get at these functions? (Sample code using the above function would be really cool.)
Sample C/C++ implementation: extern "C" __declspec(dllexport) double SomeFunction(double a, double vec[3], double mat[3][3]) { double sum = a; for (int ix = 0; ix < 3; ++ix) { sum += vec[ix]; for (int iy = 0; iy < 3; ++iy) { sum += mat[ix][iy]; } } return sum; } Sample C# usage: private void Form1_Load(object sender, EventArgs e) { double[] vec = new double[3]; double[,] mat = new double[3, 3]; for (int ix = 0; ix < 3; ++ix) { vec[ix] = ix; for (int iy = 0; iy < 3; ++iy) { mat[ix, iy] = (ix + 1) * iy; } } double sum = SomeFunction(1, vec, mat); } [System.Runtime.InteropServices.DllImport("cpptemp8.dll")] private static extern double SomeFunction(double a, double[] vec, double[,] mat);
604,522
604,527
Performing equivalent of "Kill Process Tree" in C++ on windows
We have a C++ task that will fork a new process. That process in turn may have several child processes. If the task runs past an allotted time, we will want to kill that forked process. However, we don't want to orphan the processes it has spawned. We want them all to die. I have used Process Explorer and it has a "Kill Process Tree" option, similar to Windows Task Manager's "End Process Tree", so I'm guessing/assuming there is a public API to do this. Has anyone done this, or know of a reference to a public API that does?
You might want to consider the "Jobs API". CreateJobObject and friends. You can enforce children processes to stay within the Job, by setting appropriate attribute. Then you can call TerminateJobObject whenever you want. Clarification: this is NOT what Task Manager does.
604,857
616,463
How can I view DOMString (from apache xerces library) in MS visual studio debugger?
I am working on code (legacy code) which uses Apache Xerces-C library. I am trying to view the value of DOMString (and other related DOM objects) in Microsoft Visual Studio Debugger but in vain. I have tried the following 1) I Added the following in the autoexp.dat file: ;------------------------------------------------------------------------------ ;Xerces DOMString=<fHandle->fDSData->fData,su> ;------------------------------------------------------------------------------ Result: Same behavior, it shows the memory location 2) I tried to quick watch the DOMString variable using "var,su" syntax Result: "" I have asked this question at the Apache Xerces General mailing list. In case someone encountered this problem and had a workaround, it would be of great help to me.
After looking at the Xerces library code and it's usage in my code base (we included only headers), I figured out that there was a preprocessor directive (XML_DEBUG) for debugging. You have to build your project (which is using Xerces project/libaray) by adding this preprocessor directive if not added already. In visual studio right click on project -> properties -> C/C++ -> Preprocessor and then add XML_DEBUG in Preprocessor Definitions Along with this you need to edit autoexp.dat file as mentioned in the post above. Hope this helps.
605,037
605,040
C++: Convenient way to access operator[] from within class?
I have a C++ class that overloads operator[], the array subscript/brackets operator. This is awfully convenient outside of my class, where I can write foo[bar]. However, I can't figure out how to use this notation when I'm implementing methods inside my class. I know I can write operator[](bar) or this->operator[](bar) but those are fairly unwieldy and take away a lot of the convenience of the operator in the first place. (I also know I can just add a new method that calls the operator.) Is there a way I can write this[bar] or this->[bar] or something similarly nice?
(*this)[bar]; works fine for me.
605,067
605,100
Treating classes as first-class objects
I was reading the GoF book and in the beginning of the prototype section I read this: This benefit applies primarily to languages like C++ that don't treat classes as first class objects. I've never used C++ but I do have a pretty good understanding of OO programming, yet, this doesn't really make any sense to me. Can anyone out there elaborate on this (I have used\use: C, Python, Java, SQL if that helps.)
For a class to be a first class object, the language needs to support doing things like allowing functions to take classes (not instances) as parameters, be able to hold classes in containers, and be able to return classes from functions. For an example of a language with first class classes, consider Java. Any object is an instance of its class. That class is itself an instance of java.lang.Class.
605,533
605,544
Does casting to an int after std::floor guarantee the right result?
I'd like a floor function with the syntax int floor(double x); but std::floor returns a double. Is static_cast <int> (std::floor(x)); guaranteed to give me the correct integer, or could I have an off-by-one problem? It seems to work, but I'd like to know for sure. For bonus points, why the heck does std::floor return a double in the first place?
The range of double is way greater than the range of 32 or 64 bit integers, which is why std::floor returns a double. Casting to int should be fine so long as it's within the appropriate range - but be aware that a double can't represent all 64 bit integers exactly, so you may also end up with errors when you go beyond the point at which the accuracy of double is such that the difference between two consecutive doubles is greater than 1.
605,539
605,564
expand size of vector passed as memory
I am passing my vector to a function that expects a c array. It returns the amount of data it filled (similar to fread). Is there a way i can tell my vector to change its size to include the amount that function has passed in? of course i make sure the vector has the capacity() to hold that amount of data.
No, there is no supported way to "expand" a vector so it contains extra values that have been directly copied in. Relying on "capacity" to allocate non-sized memory that you can write to is definitely not something you should rely on. You should ensure your vector has the required amount of space by resizing before calling the function and then resizing to the correct value afterwards. E.g. vector.resize(MAX_SIZE); size_t items = write_array(&(vec[0]), MAX_SIZE) vector.resize(items);
605,915
608,880
Unit test that a class is non copyable, and other compile-time properties
Is there a way to test compile-time errors, but without actually generating the error? For example, if I create a class which is non-copyable, I'd like to test the fact that trying to copy it will generate a compiler error, but I'd still like to execute the other runtime tests. struct Foo { int value_; Foo(int value) : value_(value) {} private: Foo(const Foo&); const Foo& operator=(const Foo&); }; int main() { Foo f(12); assert(f.value_ == 12); assert(IS_COMPILER_ERROR(Foo copy(f);)); } // Would like this to compile and run fine. I guess this can't be done as simply as that, but is there an idiomatic way to do this, or should I roll my own solution (maybe using scripts compiling separate tests files and testing the results?)? N.B.: I took non-copyable only to illustrate my point, so I'm not interested in answers about using boost::noncopyable and such.
You can do it using make. Each test will be a code snippet. Here's a working example with 2 tests for VC++. (I've used 2 batch files for pass test and fail test). I'm using GNU make here. Makefile: FAILTEST = .\failtest.bat PASSTEST = .\passtest.bat tests: must_fail_but_passes \ must_pass_but_fails must_fail_but_passes: @$(FAILTEST) $@.cpp must_pass_but_fails: @$(PASSTEST) $@.cpp must_pass_but_fails.cpp struct Foo { int value_; Foo(void) : value_(0) {} private: Foo(const Foo&); const Foo& operator=(const Foo&); }; int main() { Foo f(12); return 0; } must_fail_but_passes.cpp struct Foo { int value_; Foo(int value) : value_(value) {} private: Foo(const Foo&); const Foo& operator=(const Foo&); }; int main() { Foo f(12); return 0; } passtest.bat @echo off cl /nologo %1 >NUL if %errorlevel% == 0 goto pass @echo %1 FAILED :pass failtest.bat @echo off cl /nologo %1 >NUL if not %errorlevel% == 0 goto pass @echo %1 FAILED :pass Note that cl.exe (i.e. Visual Studio compiler) need to be in your path for this to "just work" Have fun! P.S. I doubt that this would make me famous though :-)
606,004
606,757
C++ multi-dimensional data handling
Many times, I find myself having to define a container for multi-dimensional data. Let's take an example: I have many Chips, each Chip has many Registers, each Register has many Cells, and each Cell has many Transistors. At some stage of my C++ program I have to read this data, and later I have to use it. I cannot use any external storage for this data: file, data-base, etc. So, should I create some multi-dimensional STL container? A map of maps of vectors, or something like that... ? Or should I create classes (structs) for each of them? Cell class that contains a vector of Transistors, and then a Register class that contains a vector of Cells, etc? But what if later I want to access my data by Transistor, and not by Chip? Any other way? Thank you EDIT: Forgot to mention: I cannot use boost.
Implement full classes for them. Your code will be cleaner in the end. Whenever I ignore this axiom, it comes back to haunt me. I implemented a hierarchical 3-tiered string collection in terms of std::pairs of std::strings and std:pairs. It was quick and simple, and when I had to replace one layer and then another with a class to contain extra attributes, it was surprisingly easy to do. But in the end, the code was a mess and I wasn't happy documenting it. Lesson learned again, and again, and again...
606,036
606,805
How might I retrieve the version number of a Windows EXE or DLL?
How to retrieve at runtime the version info stored in a Windows exe/dll? This info is manually set using a resource file.
Here is a C++ way of doing it, using the standard Windows API functions: try { TCHAR szFileName[ MAX_PATH ]; if( !::GetModuleFileName( 0, szFileName, MAX_PATH ) ) throw __LINE__; DWORD nParam; DWORD nVersionSize = ::GetFileVersionInfoSize( szFileName, &nParam ); if( !nVersionSize ) throw __LINE__; HANDLE hMem = ::GetProcessHeap(); if( !hMem ) throw __LINE__; LPVOID lpVersionData = ::HeapAlloc( hMem, 0, nVersionSize ); if( !lpVersionData ) throw __LINE__; if( !::GetFileVersionInfo( szFileName, 0, nVersionSize, lpVersionData ) ) throw __LINE__; LPVOID pVersionInfo; UINT nSize; if( !::VerQueryValue( lpVersionData, _T("\\"), &pVersionInfo, &nSize ) ) throw __LINE__; VS_FIXEDFILEINFO *pVSInfo = (VS_FIXEDFILEINFO *)pVersionInfo; CString strVersion; strVersion.Format( _T(" version %i.%i.%i.%i"), pVSInfo->dwProductVersionMS >> 16, pVSInfo->dwProductVersionMS & 0xFFFF, pVSInfo->dwProductVersionLS >> 16, pVSInfo->dwProductVersionLS & 0xFFFF ); GetDlgItem( IDC_ABOUT_VERSION )->SetWindowText( strAppName + strVersion ); if( !HeapFree( hMem, 0, lpVersionData ) ) throw __LINE__; } catch( int err ) { ASSERT( !err ); // always break on debug builds to inspect error codes and such DWORD dwErr = ::GetLastError(); // handle memory cleanup... } Note that the catch part is purely educational - in a real situation you would properly cleanup after the memory allocation and actually use the error code!
606,135
606,182
monitor with operator overloading c++
I would like to write a wrapper class with all operators overloaded such that I can detect when we write/read or modify its contents. For instance: probe<int> x; x = 5; // write if(x) { // read x += 7; // modify } Anyone already did that? If not which operators must I overload to be sure I dont miss anything?
You can't, I think. operator?: isn't overloadable. Also, if T::T(int) is defined, T foo = 4 is legal but T foo = probe<int>(4) isn't. There's at most one user-defined conversion. Furthermore, because probe is not a POD, the behavior of your program can change.
606,138
606,164
Are the C++ ARM compilers bundled along with VS2008 redistributable?
Are the VS2008 C++ ARM compilers targeting the WinCE operating system redistributable? Or does Microsoft provide a separate redistributable package (SDK?) ? I am looking for a C++ ARM compiler (actually a complete build environment) for WinCE which I can distribute along with my application for free. What are my options here?
I'd be rather suprised if it were, your use case is rather uncommon. I don't remember seeing them in the redist.txt file, either. My first instinct would be GCC, as it can target ARM and is also redistributable under GPL.
606,270
606,373
Launching a C# dialog from an unmanaged C++ mfc active x dll
I've been told to write a dialog in C# which must be instantiated from an unmanaged c++ dll. We do this in other places in our code by simply adding a managed c++ class to the C++ project, then calling the C# dll from the managed c++ class. However I'm finding that doesn't work for me from where I have to do it. I think because the c++ dll is an MFCActiveX project. As soon as i set the clr on any file in this project, it will no longer register correctly. When i attempt to register it, i get three errors, then a message that it registered. However when i try to use it i get a 0x80040111 "ClassFactory cannot supply requested class" error. If anyone has any idea what the problem is here i would greatly appreciate it. I either need to be able to accomplish this (preferred) or prove that it's not possible. Thanks
I can't see how a MFCActiveX project would prevent you from creating the C# class in this way. Unless it simply does not allow for a managed class to be added. If you can't get the managed C++ class trick to work, another option is to use COM. It's possible to register a factory of sorts in the C# project as a COM object. Say give it the following interface [ComVisible(true)] [Guid("babe87fc-1467-4913-a1d3-47eeedf1afb5")] public interface IDialogFactory { void Create(); } You'd also have to create a backing class as well. But then you could register the managed assembly and use COM to access it.
606,471
606,518
wifstream equivalent to _wfopen's "mode" parameter?
I'm having troubles opening a Unicode file in C++ using fstreams instead of the older FILE-based file handling functions. When opening a file using _wfopen, I can specify a mode to tell it what character encoding to use. Eg: _wfopen_s(&file, fileName, unicode ? L"r+, ccs=UTF-16LE" : L"r+" ); This works fine. When using wifstream though, I get both the byte-order mark at the beginning of the file, and the rest of the file appears in memory interlaced with 0x00. Clearly it's just reading in each character as a byte. My question is: is there any equivalent to the 'mode' parameter above for use with fstreams? It's not terrible if there isn't, I just prefer the syntax of streams over FILEs. Thanks!
You could try setting using a conversion facet for the stream. Check the files codecvt.h and codecvt.cpp as an example.
606,527
610,789
Convert VARIANT to...?
Note: Attempting to invoke a method of an interface, of which the return type is _variant_t Code: _variant_t resultsDataString; _bstr_t simObjectNames; simObjectNames = SysAllocString (L"TEST example 3"); resultsDataString = pis8->GetSimObject (simObjectNames); inline function illustrated below, contained in .tli FILE: inline _variant_t IS8Simulation::GetSimObject ( _bstr_t Name ) { VARIANT _result; VariantInit(&_result); HRESULT _hr = get_SimObject(Name, &_result); if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this)); return _variant_t(_result, false); } Note: resultsDataString is of struct tagVARIANT: VARTYPE vt is 9 (unsigned short) IDispatch IDispatch interface pointer Question How can I then convert or extract the value? Possible using VariantChangeType? Another way? Edit: Note: Looking to transform the following, Visual Basic code to Visual C++ MFC or ATL, if need be Ideally, pure C++ Visual basic equivalent: Public example1, example2 As SIMUL8.S8SimObject Dim numberOfexamples As Variant Dim resultString As Variant Set example1 = MySimul8.SimObject("Example 1") Set example2 = MySimul8.SimObject("Example 2") numberOfexamples = example1.CountContents + example2.CountContents resultString = CStr(numberOfexamples) & "*"
It appears you are using C++ as a COM client by relying on the VC++ compiler's built-in COM support. To make coding the client "easier" you've used #import to generate C++ wrapper classes that attempt to hide all the COM details from you - or at least make the COM details simpler. So you're not using the COM SDK directly, but are using a client-side framework (I think of it like a light-weight COM-only framework akin to ATL or MFC). Your example code, however, seems to be mixing the direct low-level COM SDK (VARIANTs, BSTR, SysAllocString) with the #import COM framework (_variant_t, _bstr_t, XXXXPtr). COM from C++ is complicated at first - so in a perfect world I would suggest getting to know the basics of COM before going too far forward. However, if you just want something to work I would guess this is #import-style-of-COM-clients version of the VB code you provided: _variant_t example1Var; _variant_t example1Var; SIMUL8::S8SimObjectQIPtr example1; // I'm guessing at this type-name from the VB code SIMUL8::S8SimObjectQIPtr example2; example1Var = pis8->GetSimObject(_bstr_t(L"Example 1")); example2Var = pis8->GetSimObject(_bstr_t(L"Example 2")); if (example1Var.vt == VT_DISPATCH && example2Var.vt == VT_DISPATCH) { // **UPDATE** to try to spoon feed the QI ptr... example1 = IDispatchPtr((IDispatch*)example1Var); example2 = IDispatchPtr((IDispatch*)example2Var); // Does this screw-up reference counting? int numberOfexamples = example1->CountContents + example2->CountContents; } UPDATE: Documentation on #import This makes using COM from C++ much easier, but is yet one other thing to learn...
606,728
606,742
How to cast from bool to void*?
I'm trying to build cairomm for gtkmm on windows using mingw. Compilation breaks at a function call which has a parameter which does a reinterpret_cast of a bool to a void*. cairo_font_face_set_user_data(cobj(), &USER_DATA_KEY_DEFAULT_TEXT_TO_GLYPHS, reinterpret_cast<void*>(true), NULL); This is where the code breaks, and reason is "invalid reinterpret_cast from bool to void*". Why is this happening, and how can I modify this line to get it to compile? Need help
I see this is user data and you have control over what is done with the value, cast the bool to an int first: reinterpret_cast<void *> (static_cast<int> (true)). Doing this makes sense in that the void* parameter takes the place of template functions in this ANSI-C library. All you need is a true/false value. So, there should be no danger in temporarily encoding this as a pointer as long as it is well documented as such. Really, you would be better off with this: reinterpret_cast<void *> (1) or reinterpret_cast<void *> (+true).
607,259
607,335
Using static variable along with templates
I have a template class defined in a header file like this. Here I have defined a static variable as well: #ifndef TEST1_H_ #define TEST1_H_ void f1(); static int count; template <class T> class MyClass { public: void f() { ++count; } }; #endif And I have defined main() function in a different cpp file like this: int main(int argc, char* argv[]) { MyClass<int> a; a.f(); f1(); cout<<"Main:" << count << "\n"; return 0; } I have implemented function f1() in a different cpp file like this: void f1() { MyClass<int> a; a.f(); cout<<"F1: " <<count <<"\n"; } When I compiled this using VC6, I got the output as "F1:0 Main:2". How is this possible? Also, in general how should I handle if I want to use static variables along with templates?
You're getting two copies of the same variable because you've declared a static variable in a header file. When you declare a global variable static this way, you're saying it's local to the compilation unit (the .o file). Since you include the header in two compilation units, you get two copies of count. I think what you really want here is a static template member variable associated with each instance of the template class. It would look like this: template <class T> class MyClass { // static member declaration static int count; ... }; // static member definition template<class T> int MyClass<T>::count = 0; This will get you a count for each instantiation of your template. That is, you'll have a count for MyClass<int>, MyClass<foo>, MyClass<bar>, etc. f1() would now look like this: void f1() { MyClass<int> a; a.f(); cout<<"F1: " << MyClass<int>::count <<"\n"; } If you want a count for all instantiations of MyClass (regardless of their template parameters), you do need to use a global variable. However, you probably don't want a global variable directly because you run the risk of using it before it gets initialized. You can get around this by making a global static method that returns a reference to your count: int& my_count() { static int count = 0; return count; } Then accessing it from within your class like this: void f() { ++my_count(); } This will ensure that count gets initialized before it's used, regardless of which compilation unit you access it from. See the C++ FAQ on static initialization order for more details.
607,299
607,336
C++ Assertions that Can Display a Custom String with Boost or STL?
I really want to be able to go: (in C++) assert( num > 0, "The number must be greater than zero!"); In C# XNA, they have a method that does exactly this: Debug.Assert( num > 0, "The number must be greater than zero!"); Is there some way to do this so that the runtime gives me a meaning full error not just "an assertion failed" error?
You can use this in most any assertion: assert(("The number must be greater than zero!", num > 0));
607,458
607,629
Storing a list of arbitrary objects in C++
In Java, you can have a List of Objects. You can add objects of multiple types, then retrieve them, check their type, and perform the appropriate action for that type. For example: (apologies if the code isn't exactly correct, I'm going from memory) List<Object> list = new LinkedList<Object>(); list.add("Hello World!"); list.add(7); list.add(true); for (object o : list) { if (o instanceof int) ; // Do stuff if it's an int else if (o instanceof String) ; // Do stuff if it's a string else if (o instanceof boolean) ; // Do stuff if it's a boolean } What's the best way to replicate this behavior in C++?
Your example using Boost.Variant and a visitor: #include <string> #include <list> #include <boost/variant.hpp> #include <boost/foreach.hpp> using namespace std; using namespace boost; typedef variant<string, int, bool> object; struct vis : public static_visitor<> { void operator() (string s) const { /* do string stuff */ } void operator() (int i) const { /* do int stuff */ } void operator() (bool b) const { /* do bool stuff */ } }; int main() { list<object> List; List.push_back("Hello World!"); List.push_back(7); List.push_back(true); BOOST_FOREACH (object& o, List) { apply_visitor(vis(), o); } return 0; } One good thing about using this technique is that if, later on, you add another type to the variant and you forget to modify a visitor to include that type, it will not compile. You have to support every possible case. Whereas, if you use a switch or cascading if statements, it's easy to forget to make the change everywhere and introduce a bug.
607,677
607,739
Returning the addresses of objects created outside the main() function
I am trying to create a link list, but I am having trouble creating objects inside a function and assigning pointers to their addresses, since I believe they go out of scope when the function exits. Is this true? And, if so, how can I create an object outside the main and still use it?
Create the objects with the new operator. ie void foo( myObject* bar1, myObject* bar2 ) { bar1 = new myObject(); bar2 = new myObject(); // do something } int main( int argc, char* argv[] ) { myObject* thing1; myObject* thing2; foo( thing1, thing2 ); // Don't forget to release the memory! delete thing1; delete thing2; return 0; }
607,713
607,894
How do I debug while running my program in Valgrind?
I was finishing up a code mod and wanted to run my program through Valgrind to make sure I've got all memory accounted for, but my program failed an assertion that doesn't fail when running on its own. Is it possible to stop in the debugger while running from Valgrind? I'm currently wading through the manual, but figured I could get my answer faster from you all.
I discovered the --db-attach=yes argument. This will stop every time an error is detected and ask if you want to enter the debugger at this point. For my program, this is proving to be difficult to use, however. I read a file from standard input for initialization, and I think Valgrind is interpreting EOLs as responding to its prompts.
607,770
607,808
Nameless enums in templates
Alot templated code looks like this: template <typename T> class foo { enum { value = <some expr with T> }; }; An example can be seen here in the prime check program and I've seen it in a Factorial implementation once too. My question is why use a nameless enum? Is there a particular reason to this? A static const int could work as well for example? edit: @Benoît: Thanks for the link, it provided the insight I was looking for!
A static const variable would take up memory (like Sean said), whereas enums do not take any memory. They only exist in the compiler's world. At runtime they are just regular integers. Other than that it would work, except for bad implementation of the standard by the compiler. There is a thorough thread on the subject in boost mailing-list :
607,836
607,880
How ubiquitous is hash_map?
The hash_map and hash_set headers aren't included in the C++ standard yet, but they're available as extensions with all the compilers I've used lately. I'm wondering how much I can rely on these in real code without sacrificing portability. I'm working on tools projects that need to run on a host of architectures and compilers, including: Linux (x86_64, AMD/Intel): GCC, Intel, Portland Compilers AIX (Power): GCC, xlC Cray XT Series (AMD): GCC, Portland, Pathscale Compilers IBM Blue Gene Series (Power): xlC, GCC SGI Altix (Itanium): Intel compilers Windows: Not really a priority, but feel free to provide useful answers. I realize some of these are pretty exotic, but that's not the point. What are your experiences with STL extensions across multiple platforms and compilers? Are they ubiquitous yet? Would you use them in your project?
I would probably look for the boost equivelant and use that. At least they have some pressure from their users to be platform independent. I can't imagine what would happen if you filed a bug against GCC and Intel compilers and told them to reconcile their differences on how hash_map was implemented. At best you would be able to get them to talk to each other. Suppose you even acheived that, then you've only fixed how Intel and GCC compilers are different. Good luck getting everyone else together and solving the problem within a few years. At least with boost you know any differences across platforms are being worked out by one organization.. EDIT The boost equivalent is apparently unordered set or unordered map. (thanks Head Geek)
607,864
607,905
disable vector fill value on resize? c++
I'm in a situation where i must use a c style function that returns the len copied. I decided i should resize to max, then resize to the length returned expand size of vector passed as memory I know resize sets the value to fillValue (always 0?). So theres going to be pointless initialization (hopefully less then a mb each time) 60times every second. Is there a way ti disable the initiation on resize?
Basically no. Elements in the vector are default constructed upon a resize (for an integer this results in 0). Assuming you are using reserve() to ensure that resize() does not allocate memory I would not worry about this unless it proves to be a performance issue later on. If you are concerned you may wish to consider just using a regular array and storing the item count in a separate variable. This will give you the best performance. Update: John asked: Is the constructor really guaranteed to zero that memory? I thought that was undefined? Yes and no. The primitive types (int, bool, float, etc) do have default constructors that initialize them to zero. However unlike regular classes or structs the compiler does not automatically call them. E.g int a; // uninitialized int b = int(); // initialized to 0 Because vector::resize uses the latter form when adding items you are guaranteed that the elements created will be correctly initialized to zero. This is true of all the STL collections that implicitly create elements.
607,976
647,496
How can I output execution display to console in Eclipse for remote C++?
I'm using Eclipse 3.4.1 with Hp/UX plugin for remote debugging of C/C++. It works very fine, except for one issue: whenever I compile my projects, the output display is Eclipse's console view, but when I run or debug any projects, the output window is the old and not-so-good MS-DOS command window. I haven't find any way to change this behavior. How do I set the execution output display to Eclipse console? Update: Environment: running Eclipse 3.4.1 on Windows XP and debugging C/C++ applications on an HP/UX server. CDT version is 5.0.0.
Which version of CDT are you using? Because from this "hello world" guide it seems the spawner.dll pretty much handles this console redirection for you.
608,082
608,093
convert vector of strings/doubles to arrays
I am using matheval library. Its functions take c-style parameters, for example: #include<matheval.h> char * evaluator_evaluate(void * evaluator, int count, char **names, double *values); In my case, I want to convert std::vector of names and std::vector of values to char ** and double * Also, every name correspond to a unique value, and there could be repetitions. What is the best way to arrange names and values elegantly in terms of data structures? For now, I use vectors, and both contains repetitions. Edit Please keep in mind that order of names and values matters and should match. Thanks
Internally, the standard requires that a vector<> is equivalent to an array. You can take the address of vector[0] and the resulting pointer will point to a contiguous area of memory where the data is stored, in the same order as the vector. This pointer is valid until or unless the vector<> is resized. For std::string values (or any other object, for that matter), though, you will only get an array of string objects.
608,097
608,132
C++ - Circular array with lower/upper bounds?
I want to create something similar to a double linked list (but with arrays) that works with lower/upper bounds. A typical circular array would probably look like: next = (current + 1) % count; previous = (current - 1) % count; But what's the mathematical arithmetic to incorporate lower/upper bounds properly into this ? 0 (lower bound item 1) 1 2 (upper bound item 1) 3 (lower bound item 2) 4 (upper bound item 2) So that: -> next on index 2 for item 1 returns 0 -> previous on index 0 for item 1 returns 2 -> next on index 4 for item 2 returns 3 -> previous on index 3 for item 2 returns 4 Thank you ! NOTE: Can't use external libraries.
In general mathematical terms: next === current + 1 (mod count) prev === current - 1 (mod count) where === is the 'congruent' operator. Converting this to the modulus operator, it would be: count = upper - lower next = ((current + 1 - (lower%count) + count) % count) + lower prev = ((current - 1 - (lower%count) + count) % count) + lower It would be up to you to find out the upper & lower bounds for each item. You could store this in a binary tree for fast retrieval. Maybe I'm not understanding your question. (note that this assumes lower < upper, and lower > 0)
608,175
608,185
What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?
I've been working on the Cell processor and I'm trying to create a struct that will hold an spe_context_ptr_t, which will be used within the thread to launch an spe context and will also hold a pointer to something else that will be passed to the spu context from within the thread (currently I'm trying to just make it a generic pointer, but in actuality it will be a pointer to another structure I've defined). When I try and compile, I get the following error: spu/../common.h:38: error: expected specifier-qualifier-list before 'spe_context_ptr_t' // here is the offending line(s) typedef struct _PTHREAD_BLOCK { spe_context_ptr_t * context; // Error happens here uintptr32_t args; } PTHREAD_BLOCK;
The compiler doesn't know that spe_context_ptr_t is a type. Check that the appropriate typedef is in scope when this code is compiled. You may have forgotten to include the appropriate header file.
608,206
608,261
return underlying array from vector
Will the array be deallocated and if so, what is a workaround? double * GetArrayFromVector( std::map<std::string, double> m, char ** names, int count ) { if(!names) return 0; std::vector<double> vec(m.size()); for (int i=0; i<count; ++i) { if(!names[i]) return 0; std::map<std::string, double>::iterator iter=m.find(name[i]); if(iter!=m.end()) vec.push_back(iter->second); else return 0; } return &vec[0]; } Thanks a lot
Divide your function on two. Make your functions make just one action: 1. fill vector from map. 2. create array from vector. Don't forget to pass map by const reference. Main note: caller of the GetArrayFromVector is responsible for memory deallocation. void FillVector( const std::map<std::string, double>& m, std::vector< double >& v, char ** names, int count ) { ....... } double* createArray( const std::vector< double >& v ) { double* result = new double [v.size()]; memcpy( result, &v.front(), v.size() * sizeof( double ) ); return result; } // and finally your function double* GetArrayFromVector( const std::map<std::string, double>& m, char ** names, int count ) { std::vector< double > v; FillVector( m, v, names, count ); return CreateArray( v ); }
608,228
608,249
VC++ 6.0 vector access violation crash. Known bug?
I'm trying to use a std::vector<>::const_iterator and I get an 'access violation' crash. It looks like the std::vector code is crashing when it uses its own internal First_ and Last_ pointers. Presumably this is a known bug. I'm hoping someone can point me to the correct workaround. It's probably relevant that the crashing function is called from an external library? const Thing const* AClass::findThing (const std::string& label) const { //ThingList_.begin() blows up at run time. Compiles fine. for (std::vector<Thing*>::const_iterator it = ThingList_.begin(); it != ThingList_.end(); ++it) { //Irrelevant. } return 0; } Simply calling ThingList_.size() also crashes. This is sp6, if it matters.
If you're passing C++ objects across external library boundaries, you must ensure that all libraries are using the same runtime library (in particular, the same heap allocator). In practice, this means that all libraries must be linked to the DLL version of MSVCRT.
608,255
608,396
How to set text in Carbon textfield on OSX?
I'm trying to set the text of a textfield using the Carbon API like this: ControlID editId = {'EDIT', 3}; ControlRef ctrl; GetControlByID(GetWindowRef(), &editId, &ctrl); CFStringRef title = CFSTR("Test"); OSErr er = SetControlData(ctrl, kControlEntireControl, kControlEditTextTextTag, CFStringGetLength(title), title); CFRelease(title); I'm using the C++ code template of XCode, so GetWindowRef() is a call to the predefined TWindow class. The OSErr return value gives me noErr, but my textfield only contains garbage. It doesn't matter if I set the attribute of my textfield to Unicode or not. Any ideas what is wrong here?
What does the GetControlID(...) return? Is it noErr? As a ControlRef is also a HIViewRef, you can also use the function: HIViewSetText to set the text. This is documented to work with functions that accept kControlEditTextCFStringTag. By the way, the line you wrote: CFRelease(title); Will cause problems. One should only release objects that have been made using functions that have Create or Copy in the API name. You'll want to read: "Introduction to Memory Management Programming Guide for Core Foundation" -- search in the Xcode documentation.
608,329
608,412
Boost adjacency_list help needed
I'm trying to use Boost's adjacency_list type and I'm having trouble understanding the documentation. Say I define a class named State and I instantiate one instance for each state in the USA: class State { ... }; State california, oregon, nevada, arizona, hawaii, ... I want to enter these into a boost::adjacency_list the vertices are states and the edges are borders. For the states I listed above, I think the graph would have this data: california : oregon, nevada, arizona hawaii : oregon : california, nevada nevada : oregon, california, arizona arizona : california, nevada I understand how to put ints into the graph and I considered just making an array of states and inserting their array index into the graph, but it seems like I should be able to just say: add_edge(california, oregon, graph); but of course that doesn't work. Please help! Edit: Here's an example of almost exactly what I need.
Reading up on boost::adjacency_list, it appears you are supposed to use properties for the vertices rather than something like a class: struct VertexProperties { std::string stateName; }; typedef adjacency_list<listS, listS, bidirectionalS, VertexProperties> Graph; Graph adjacentStates(50); property_map<Graph, std::string VertexProperties::*>::type stateName = get(&VertexProperties::stateName, adjacentStates); add_edge(vertex("california", adjacentStates), vertex("oregon", adjacentStates), adjacentStates); (Poorly) adapted from an example in boost.
608,370
608,485
C++ string memory management
Last week I wrote a few lines of code in C# to fire up a large text file (300,000 lines) into a Dictionary. It took ten minutes to write and it executed in less than a second. Now I'm converting that piece of code into C++ (because I need it in an old C++ COM object). I've spent two days on it this far. :-( Although the productivity difference is shocking on its own, it's the performance that I would need some advice on. It takes seven seconds to load, and even worse: it takes just exactly that much time to free all the CStringWs afterwards. This is not acceptable, and I must find a way to increase the performance. Are there any chance that I can allocate this many strings without seeing this horrible performace degradation? My guess right now is that I'll have to stuff all the text into a large array and then let my hash table point to the beginning of each string within this array and drop the CStringW stuff. But before that, any advice from you C++ experts out there? EDIT: My answer to myself is given below. I realized that that is the fastest route for me, and also step in what I consider the right direction - towards more managed code.
You are stepping into the shoes of Raymond Chen. He did the exact same thing, writing a Chinese dictionary in unmanaged C++. Rico Mariani did too, writing it in C#. Mr. Mariani made one version. Mr. Chen wrote 6 versions, trying to match the perf of Mariani's version. He pretty much rewrote significant chunks of the C/C++ runtime library to get there. Managed code got a lot more respect after that. The GC allocator is impossible to beat. Check this blog post for the links. This blog post might interest you too, instructive to see how the STL value semantics are part of the problem.
608,409
608,427
Select template argument at runtime in C++
Suppose I have a set of functions and classes which are templated to use single (float) or double precision. Of course I could write just two pieces of bootstrap code, or mess with macros. But can I just switch template argument at runtime?
No, you can't switch template arguments at runtime, since templates are instantiated by the compiler at compile-time. What you can do is have both templates derive from a common base class, always use the base class in your code, and then decide which derived class to use at runtime: class Base { ... }; template <typename T> class Foo : public Base { ... }; Base *newBase() { if(some condition) return new Foo<float>(); else return new Foo<double>(); } Macros have the same problem as templates, in that they are expanded at compile-time.
608,507
610,905
Wine linker error: trying to create .lnk
I'm trying to create an .lnk file programatically. I would prefer to use C, but C++ is fine (and is what all the MSDN stuff is in). The relevant code sample is: #include <windows.h> #include <shobjidl.h> #include <shlguid.h> HRESULT CreateLink(LPCSTR lpszPathObj, LPCSTR lpszPathLink, LPCSTR lpszDesc) { HRESULT hres; IShellLink* psl; /* Get a pointer to the IShellLink interface. */ hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl); return hres; } I'm trying to comple with wineg++ using: wineg++ -mno-cygwin -o t t2.cpp And I'm getting the following errors: t2-Tw9YPp.o: In function `CreateLink(char const*, char const*, char const*)': t2.cpp:(.text+0x34): undefined reference to `IID_IShellLinkA' /usr/bin/ld: t2-Tw9YPp.o: relocation R_386_GOTOFF against undefined hidden symbol `IID_IShellLinkA' can not be used when making a shared object /usr/bin/ld: final link failed: Bad value collect2: ld returned 1 exit status winegcc: i486-linux-gnu-g++ failed Any ideas?
The solution seems to be to change the includes section to: #define INITGUID #include <windows.h> #include <shobjidl.h> #include <shlguid.h> #include <initguid.h> ie, add #define INITGUID before everything and include #include <initguid.h> I have no idea why this works. I also had to add -lole32 to fix an error that came up after the cited one was resolved. The code compiles... now to see if I can make it do what I need.
608,584
608,615
Possible to trap write to address (x86 - linux)
I want to be able to detect when a write to memory address occurs -- for example by setting a callback attached to an interrupt. Does anyone know how? I'd like to be able to do this at runtime (possibly gdb has this feature, but my particular application causes gdb to crash).
If you want to intercept writes to a range of addresses, you can use mprotect() to mark the memory in question as non-writeable, and install a signal handler using sigaction() to catch the resulting SIGSEGV, do your logging or whatever and mark the page as writeable again.
609,076
609,130
The role of scripting languages in game Programming
So I've been running into a debate at work about what the proper role of a scripting language is in game development. As far as I can tell there are two schools of thought on this: 1) The scripting language is powerful and full featured. Large portions of game code are written in the language and code is only moved into C++ when performance dictates that it's necessary. This is usually something like Lua or Unrealscript. 2) This scripting language is extremely limited. Almost all game code is in C++ and the language is only there to expose the underlying functionality to designers. My frustration comes from seeing approach number two frequently abused, with large systems implemented in a language that does not have the features that make that code maintainable. So I started out supporting approach number one, but after talking to some designers I realized that many of them seem to prefer number two, and its mostly programmers who prefer one. So I'm still left wondering which approach is better. Am I just seeing bad code and blaming the tool instead of the programmer, or do we need really need a more complex tool?
I think designers need to see a language suitable for them. That's not negotiable: they have to spend their time designing, not programming. If scripting allows fast development of product-worthy game code, then the programmers should be doing it too. But it has to be product-worthy: doing everything twice doesn't save time. So you have to keep scripting in its place. If a developer can script the inventory system in a week, or write it in C++ in a month, then you want full-featured scripting, if only to give you more time to hand-optimise the parts that might conceivably hit performance limits. So not the inventory, or the high-score table, or the key-mapping system, or high-level game logic like what the characters are supposed to be doing. That can all be scripted if doing so saves you any time at all to spend on speeding up the graphics and the physics: programmers need to be able to work out exactly what the bottlenecks are, and senior programmers can make a reasonable prediction what won't be. Designers probably shouldn't know or care whether the programmers are using the scripting language to implement game code. They shouldn't have an opinion whether (1) is good or bad. So even if the programmers are right to want (1), why is this inconveniencing the designers? How have they even noticed that the scripting language is full-featured, if all they ever need is a fairly small number of standard recipes? Something has gone wrong, but I don't think it's that Lua is too good a language. One possibility is that using the same scripting language for both, becomes an obstacle to drawing a sharp line between the interfaces used by designers, and the interfaces internal to the game code. That, as I said at the top, is not negotiable. Even if they're using the same scripting language, programmers still have to provide the designers with the functionality that they need to do their job. Just because designers use Lua to code up AI strategies and conversation trees, and Lua is full-featured language capable of writing a physics engine, doesn't mean your designers are expected to write their own physics engine. Or use more than 10% of Lua's capabilities. You can probably do both (1) and (2), mind. There's no reason you can't give the programmers Lua, and the designers some miniature under-featured DSL which is "compiled" into Lua with a Lua script.
609,203
609,236
Read file names from a directory
I was wondering if there's an easy way in C++ to read a number of file names from a folder containing many files. They are all bitmaps if anyone is wondering. I don't know much about windows programming so I was hoping it can be done using simple C++ methods.
Boost provides a basic_directory_iterator which provides a C++ standard conforming input iterator which accesses the contents of a directory. If you can use Boost, then this is at least cross-platform code.
609,332
609,350
What is the benefit to limiting throws allowed by a C++ function?
What is the benefit of declaring the possible exception-throws from a C++ function? In other words, what does adding the keyword throw() actually do? I've read that a function declaration such as void do_something() throw(); should guarantee that no exceptions originate from the do_something() function; however, this doesn't seem to hold true of functions called within do_something(), thus making it a weak guarantee. Please outline the usefulness (and best-use cases) of this language feature.
No one explains this better than Sutter http://www.ddj.com/architect/184401544 The short version is Never write an exception specification Except possibly an empty one
609,349
609,353
Reading file names with C++
Is there a way to read file names from a folder using purely C (or C++)? That means without including windows.h (no FindFirstFile(), etc...). It doesn't look like fstream has this functionality. I know that file names are operating system dependent, but I was hoping there is some library that will allow it in Windows.
boost filesystem is a nice solution. Of course under the hood, it will still be using the windows API calls (when you build on windows), but this is abstracted away from you.
609,411
609,468
How to create multiple objects in the same function but without overwriting each other?
I'm trying to create an object in a function, but I am running into the problem that variable names have to be defined at runtime. Is there something I can do like with arrays that allows ne to dynamically create a variable in a function and preferably give it a different name from the one created when the function was called last? ***I'm working in C++ EDIT: I can't give any code because I don't have any right now. All I have right now is pseudo code. Basically, I'm trying to create a linked list, but the addNewItem() method that I want to use would require using the same method to create different objects. EDIT: Technically, we're not making a linklist, just more of a proof of concept to understand how they work. EDIT: Here's the code: #include "linklist.h" #include <iostream> using namespace std; struct linklist { Student * obj; linklist * next; }; linklist * head; int main() { } void addStudent(char * newsdnt) { if(!head){ linklist * a = new linklist; a->obj = new Student(newsdnt); a->next = 0; head = a; return; }else{ linklist * a = new linklist; a->obj = new Student(newsdnt); a->next = 0; if(!head->next){ head->next = a; // Can only have one or two items in list } } }
If you want a linked list - call new to create each new node and then add it to the list. Smth like this: void addStudent(char * newsdnt) { linklist* a = new linklist; a.obj = new Student(newsdnt); a.next = 0; if( head == 0 ) { head = a; } else { linklist* whereToAdd = head; while( whereToAdd.next != 0 ) { whereToAdd = whereToAdd.next; } whereToAdd.next = a; } }
609,419
609,431
How Do I Downgrade a C++ Visual Studio 2008 Project to 2005
How can I downgrade a C++ Visual Studio 2008 project to visual studio 2005? Maybe there is a converter program that someone knows of or otherwise a process that I can undertake. Thanks.
I have no idea how well it works, but here's an open source converter tool: http://sourceforge.net/projects/vspc that was an extension to the tool outlined in this article: http://www.codeproject.com/KB/macros/vsconvert.aspx
609,852
609,878
Separate holder class from the reader
Continuing from the question that I asked here: C++ multi-dimensional data handling In my example: I have many Chips, each Chip has many Registers, each Register has many Cells, and each Cell has many Transistors. I asked whether to use one complex STL container for them, or to implement full classes for them. And, as advised, I chose to implement full classes for them. I have: class Chip { map<RegisterLocation, Register> RegistersPerLocation; }; class Register { map<CellLocation, Cell> CellsPerLocation; }; // etc.. Now, I need to fill the data to the classes, and I can't decide: Should reading the data be responsibility of these classes, or should they just wrap the containers and the reading will be done outside. I mean I have to choose one of the following: Either: class Chip { map<RegisterLocation, Register> RegistersPerLocation; public: void AddRegisterPerLocation(RegisterLocation, Register); }; void ReadChipData(Chip & chip) { for (RegisterLocation loc = 0; loc < 10; loc++) { Register reg; ReadReg(reg); chip.AddRegisterPerLocation(loc, reg); } } void ReadReg(Register & reg) { for (CellLocation loc = 0; loc < 10; loc++) { Cell cell; ReadCell(cell); reg.AddRegisterPerLocation(loc, cell); } } //etc... Or: class Chip { map<RegisterLocation, Register> RegistersPerLocation; public: void ReadData(); }; void Chip::ReadData() { for (RegisterLocation loc = 0; loc < 10; loc++) { Register reg; reg.ReadData(); RegistersPerLocation[loc] = reg; } } //etc... void ReadChipData(Chip & chip) { chip.ReadData(); } Thank you.
If you are thinking of tying the reader/writer to the domain objects in order to follow the principle of encapsulation, you are correct to a certain extent. But remember: You bind not just any action, but a valid behavior. Valid as in makes sense for the object in the domain. Another thing to keep in mind is separation of concerns. Serializability is not a Chip's intrinsic behavior -- modeling that into the domain object would be unfair IMO. YMMV. Separate the reading(and writing) from the classes. As the library does. Expose iterators if you have to. And you can overload the '<<' and '>>' operators for syntactic sugar ;) A minor nit on the classes -- a template based approach looks so promising. Here's some code I cooked up: you can try the following as well. (I've successfully compiled and run this on a MS VS2005 but check it out on your system. Also, can someone fix the tabbing -- feeling too lazy to do this :P) /*+-----------8<----------------------------8<-----------+*/ #include <vector> #include <iostream> #include <algorithm> #include <map> #include <iterator> /* mother template */ template<class _Item> struct Hardware { Hardware() : _myCont(2 + ::rand() % 5) {} private: typename vector<_Item> _myCont; // i/o friends template<class _Item> friend ostream& operator<<(ostream& output, const Hardware<_Item>& me); template<class _Item> friend istream& operator>>(istream& in, const Hardware<_Item>& me); }; /* actual domain objects */ /* base object */ struct Transistor { }; /* built objects */ typedef Hardware<Transistor> Cell; typedef Hardware<Cell> Register; typedef Hardware<Register> Chip; /* poorman's introspection utility */ template<class T> const char *who() { return ""; } template<> const char *who<Transistor>() { return "Transistor"; } template<> const char *who<Cell>() { return "Cell"; } template<> const char *who<Register>() { return "Register"; } template<> const char *who<Chip>() { return "Chip"; } /* writer/serialize out */ template<class T> ostream& operator<<(ostream& out, const Hardware<T>& hw) { // whatever you need to do to write // os << chip works fine, because you will provide a specialization out << "[ " << ::who<Hardware<T>>() << " ]\n\t"; std::copy(hw._myCont.begin(), hw._myCont.end(), std::ostream_iterator< T >(std::cout, "\n\t")); return out; } /* specialize for base object */ ostream& operator<< (ostream& out, const Transistor& hw) { out << "[ " << ::who<Transistor>() << " ]\n"; return out; } /* reader/serialize in */ template<class T> istream& operator>>(istream& in, const Hardware<T>& hw) { // whatever you need to do to read // similarly in >> chip works fine, return in; } // driver showing relationships // Chip -> Register -> Cell -> Transistor int main() { Transistor t; std::cout << t << std::endl; Cell ce; std::cout << ce << std::endl; Register r; std::cout << r << std::endl; Chip C; std::cout << C << std::endl; } /*+-----------8<----------------------------8<-----------+*/ Caveat: Haven't tested, so there may be quite a few compiler errors/warnings. But this should give you an idea of what I am trying to say.
609,937
609,952
What is the benefit of inheriting from std::binary_function (or std::unary function)?
What is the benefit of inheriting from std::binary_function (or std::unary_function)? For example I have such code: class Person { public: Person(); Person(int a, std::string n); Person(const Person& src); int age; std::string name; }; Person::Person() : age(0) , name("") {}; Person::Person(int a, std::string n) : age(a) , name(n) {}; Person::Person(const Person& src) { age = src.age; name = src.name; }; struct PersonPrint : public std::unary_function<Person, void>{ void operator() (Person p){ std::cout << " Person age: " << p.age << " name: " << p.name << std::endl; } }; struct PersonGreater : public std::binary_function<Person, Person, bool>{ bool operator()(const Person& p1, const Person p2){ if (p1.age > p2.age) return true; if (p1.name.compare(p2.name) > 0) return true; return false; } }; int main(int count, char** args) { std::vector<Person> personVec; Person p1(10, "Person1"); Person p2(12, "Person2"); Person p3(12, "Person3"); personVec.push_back(p1); personVec.push_back(p2); personVec.push_back(p3); std::cout << "before sort: " << std::endl; std::for_each(personVec.begin(), personVec.end(), PersonPrint()); std::sort(personVec.begin(), personVec.end(), PersonGreater()); std::cout << "after: " << std::endl; std::for_each(personVec.begin(), personVec.end(), PersonPrint()); } But I also could write this code without inheritance form std::unary_function/std::binary_function? struct PersonPrint { void operator() (Person p) { std::cout << " Person age: " << p.age << " name: " << p.name << std::endl; } }; struct PersonGreater { bool operator()(const Person& p1, const Person p2) { if (p1.age > p2.age) return true; if (p1.name.compare(p2.name) > 0) return true; return false; } }; UPDATED std::binary_function and std::unary_function are deprecated as of C++11 see comment by @AlexandreC.
Inheritance from [unary|binary]_function just gives you an additional typedefs in your class: For unary_function argument_type result_type For binary_function first_argument_type second_argument_type result_type Which are those types you pass to [unary|binary]_function. In your case there is no benefits. If you ever going to use your Functors with other std Functors modificators like not1, bind1st you have to inherit from [unart|binart]_function. And if you are going to store this template information for your purpose it is better to use ready solution.
609,956
610,146
Is std::list<>::sort stable?
I couldn't find any definitive answer to this question. I suppose most implementation use merge sort that is stable but, is the stability a requirement or a side effect?
C++ Standard ISO/IEC 14882:2003 says: 23.2.2.4/31 Notes: Stable: the relative order of the equivalent elements is preserved. If an exception is thrown the order of the elements in the list is indeterminate.
610,269
610,284
Finding and replacing string tokens in a file in C++ using win32 API
I'm trying to find a way to replace all instances of a string token in a file with another string. How can I do this in C++ with the win32 API? In other languages this is an easy thing to do, but in C++ I am just lost. EDIT: For some context, this is for a WiX custom action. So portability is not a main priority, just the most simplest solution.
If the file fits in memory – it's simpler. Call OpenFile() to open file, GetFileSize() to determine file size, allocate enough memory, call ReadFile() to read file, then CloseFile. Do replacement in memory (use strstr() or similar function), then again OpenFile(), WriteFile(), CloseFile(). If the file is large - create a temporary file and read the source file in chunks and write filtered text to the temporary file, then call DeleteFile() to delete the original file and MoveFile() to move the filtered file.
610,396
610,461
Languages faster than C++
It is said that Blitz++ provides near-Fortran performance. Does Fortran actually tend to be faster than regular C++ for equivalent tasks? What about other HL languages of exceptional runtime performance? I've heard of a few languages suprassing C++ for certain tasks... Objective Caml, Java, D... I guess GC can make much code faster, because it removes the need for excessive copying around the stack? (assuming the code is not written for performance) I am asking out of curiosity -- I always assumed C++ is pretty much unbeatable barring expert ASM coding.
Fortran is faster and almost always better than C++ for purely numerical code. There are many reasons why Fortran is faster. It is the oldest compiled language (a lot of knowledge in optimizing compilers). It is still THE language for numerical computations, so many compiler vendors make a living of selling optimized compilers. There are also other, more technical reasons. Fortran (well, at least Fortran77) does not have pointers, and thus, does not have the aliasing problems, which plague the C/C++ languages in that domain. Many high performance libraries are still coded in Fortran, with a long (> 30 years) history. Neither C or C++ have any good array constructs (C is too low level, C++ has as many array libraries as compilers on the planet, which are all incompatible with each other, thus preventing a pool of well tested, fast code).
610,682
610,784
Do .bss section zero initialized variables occupy space in elf file?
If I understand correctly, the .bss section in ELF files is used to allocate space for zero-initialized variables. Our tool chain produces ELF files, hence my question: does the .bss section actually have to contain all those zeroes? It seems such an awful waste of spaces that when, say, I allocate a global ten megabyte array, it results in ten megabytes of zeroes in the ELF file. What am I seeing wrong here?
Has been some time since i worked with ELF. But i think i still remember this stuff. No, it does not physically contain those zeros. If you look into an ELF file program header, then you will see each header has two numbers: One is the size in the file. And another is the size as the section has when allocated in virtual memory (readelf -l ./a.out): Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align PHDR 0x000034 0x08048034 0x08048034 0x000e0 0x000e0 R E 0x4 INTERP 0x000114 0x08048114 0x08048114 0x00013 0x00013 R 0x1 [Requesting program interpreter: /lib/ld-linux.so.2] LOAD 0x000000 0x08048000 0x08048000 0x00454 0x00454 R E 0x1000 LOAD 0x000454 0x08049454 0x08049454 0x00104 0x61bac RW 0x1000 DYNAMIC 0x000468 0x08049468 0x08049468 0x000d0 0x000d0 RW 0x4 NOTE 0x000128 0x08048128 0x08048128 0x00020 0x00020 R 0x4 GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x4 Headers of type LOAD are the one that are copied into virtual memory when the file is loaded for execution. Other headers contain other information, like the shared libraries that are needed. As you see, the FileSize and MemSiz significantly differ for the header that contains the bss section (the second LOAD one): 0x00104 (file-size) 0x61bac (mem-size) For this example code: int a[100000]; int main() { } The ELF specification says that the part of a segment that the mem-size is greater than the file-size is just filled out with zeros in virtual memory. The segment to section mapping of the second LOAD header is like this: 03 .ctors .dtors .jcr .dynamic .got .got.plt .data .bss So there are some other sections in there too. For C++ constructor/destructors. The same thing for Java. Then it contains a copy of the .dynamic section and other stuff useful for dynamic linking (i believe this is the place that contains the needed shared libraries among other stuff). After that the .data section that contains initialized globals and local static variables. At the end, the .bss section appears, which is filled by zeros at load time because file-size does not cover it. By the way, you can see into which output-section a particular symbol is going to be placed by using the -M linker option. For gcc, you use -Wl,-M to put the option through to the linker. The above example shows that a is allocated within .bss. It may help you verify that your uninitialized objects really end up in .bss and not somewhere else: .bss 0x08049560 0x61aa0 [many input .o files...] *(COMMON) *fill* 0x08049568 0x18 00 COMMON 0x08049580 0x61a80 /tmp/cc2GT6nS.o 0x08049580 a 0x080ab000 . = ALIGN ((. != 0x0)?0x4:0x1) 0x080ab000 . = ALIGN (0x4) 0x080ab000 . = ALIGN (0x4) 0x080ab000 _end = . GCC keeps uninitialized globals in a COMMON section by default, for compatibility with old compilers, that allow to have globals defined twice in a program without multiple definition errors. Use -fno-common to make GCC use the .bss sections for object files (does not make a difference for the final linked executable, because as you see it's going to get into a .bss output section anyway. This is controlled by the linker script. Display it with ld -verbose). But that shouldn't scare you, it's just an internal detail. See the manpage of gcc.
610,916
610,919
Easiest way to flip a boolean value?
I just want to flip a boolean based on what it already is. If it's true - make it false. If it's false - make it true. Here is my code excerpt: switch(wParam) { case VK_F11: if (flipVal == true) { flipVal = false; } else { flipVal = true; } break; case VK_F12: if (otherVal == true) { otherValVal = false; } else { otherVal = true; } break; default: break; }
You can flip a value like so: myVal = !myVal; so your code would shorten down to: switch(wParam) { case VK_F11: flipVal = !flipVal; break; case VK_F12: otherVal = !otherVal; break; default: break; }
610,934
610,949
Why would you use 'extern "C++"'?
In this article the keyword extern can be followed by "C" or "C++". Why would you use 'extern "C++"'? Is it practical?
The language permits: extern "C" { #include "foo.h" } What if foo.h contains something which requires C++ linkage? void f_plain(const char *); extern "C++" void f_fancy(const std::string &); That's how you keep the linker happy.
611,095
611,110
Writing BMP data getting garbage
I'm working on understanding and drawing my own DLL for PDF417 (2d barcodes). Anyhow, the actual drawing of the file is perfect, and in correct boundaries of 32 bits (as monochrome result). At the time of writing the data, the following is a memory dump as copied from C++ Visual Studio memory dump of the pointer to the bmp buffer. Each row is properly allocated to 36 wide before the next row. Sorry about the wordwrap in the post, but my output was intended to be the same 36 bytes wide as the memory dump so you could better see the distortion. The current drawing is 273 pixels wide by 12 pixels high, monochrome... 00 ab a8 61 d7 18 ed 18 f7 a3 89 1c dd 70 86 f5 f7 1a 20 91 3b c9 27 e7 67 12 1c 68 ae 3c b7 3e 02 eb 00 00 00 ab a8 61 d7 18 ed 18 f7 a3 89 1c dd 70 86 f5 f7 1a 20 91 3b c9 27 e7 67 12 1c 68 ae 3c b7 3e 02 eb 00 00 00 ab a8 61 d7 18 ed 18 f7 a3 89 1c dd 70 86 f5 f7 1a 20 91 3b c9 27 e7 67 12 1c 68 ae 3c b7 3e 02 eb 00 00 00 ab 81 4b ca 07 6b 9c 11 40 9a e6 0c 76 0a fc a3 33 70 bb 30 55 87 e9 c4 10 58 d9 ea 0d 48 3e 02 eb 00 00 00 ab 81 4b ca 07 6b 9c 11 40 9a e6 0c 76 0a fc a3 33 70 bb 30 55 87 e9 c4 10 58 d9 ea 0d 48 3e 02 eb 00 00 00 ab 81 4b ca 07 6b 9c 11 40 9a e6 0c 76 0a fc a3 33 70 bb 30 55 87 e9 c4 10 58 d9 ea 0d 48 3e 02 eb 00 00 00 ab 85 7e d0 29 e8 14 f4 0a 7a 05 3c 37 ba 86 87 04 db b6 09 dc a0 62 fc d1 31 79 bc 5c 0a 8e 02 eb 00 00 00 ab 85 7e d0 29 e8 14 f4 0a 7a 05 3c 37 ba 86 87 04 db b6 09 dc a0 62 fc d1 31 79 bc 5c 0a 8e 02 eb 00 00 00 ab 85 7e d0 29 e8 14 f4 0a 7a 05 3c 37 ba 86 87 04 db b6 09 dc a0 62 fc d1 31 79 bc 5c 0a 8e 02 eb 00 00 00 ab 85 43 c5 30 e2 26 70 4a 1a f3 e4 4d ce 2a 3f 79 cd bc e6 de 73 6f 39 b7 9c db ce 6d 5f be 02 eb 00 00 00 ab 85 43 c5 30 e2 26 70 4a 1a f3 e4 4d ce 2a 3f 79 cd bc e6 de 73 6f 39 b7 9c db ce 6d 5f be 02 eb 00 00 00 ab 85 43 c5 30 e2 26 70 4a 1a f3 e4 4d ce 2a 3f 79 cd bc e6 de 73 6f 39 b7 9c db ce 6d 5f be 02 eb 00 00 Here is the code to WRITE the file out -- verbatim immediately at the time of the memory dump from above FILE *stream; if( fopen_s( &stream, cSaveToFile, "w+" ) == 0 ) { fwrite( &bmfh, 1, (UINT)sizeof(BITMAPFILEHEADER), stream ); fwrite( &bmi, 1, (UINT)sizeof(BITMAPINFO), stream ); fwrite( &RGBWhite, 1, (UINT)sizeof(RGBQUAD), stream ); fwrite( ppvBits, 1, (UINT)bmi.bmiHeader.biSizeImage, stream ); fclose( stream ); } Here's what ACTUALLY Gets written to the file. 00 ab a8 61 d7 18 ed 18 f7 a3 89 1c dd 70 86 f5 f7 1a 20 91 3b c9 27 e7 67 12 1c 68 ae 3c b7 3e 02 eb 00 00 00 ab a8 61 d7 18 ed 18 f7 a3 89 1c dd 70 86 f5 f7 1a 20 91 3b c9 27 e7 67 12 1c 68 ae 3c b7 3e 02 eb 00 00 00 ab a8 61 d7 18 ed 18 f7 a3 89 1c dd 70 86 f5 f7 1a 20 91 3b c9 27 e7 67 12 1c 68 ae 3c b7 3e 02 eb 00 00 00 ab 81 4b ca 07 6b 9c 11 40 9a e6 0c 76 0d 0a fc a3 33 70 bb 30 55 87 e9 c4 10 58 d9 ea 0d 48 3e 02 eb 00 00 00 ab 81 4b ca 07 6b 9c 11 40 9a e6 0c 76 0d 0a fc a3 33 70 bb 30 55 87 e9 c4 10 58 d9 ea 0d 48 3e 02 eb 00 00 00 ab 81 4b ca 07 6b 9c 11 40 9a e6 0c 76 0d 0a fc a3 33 70 bb 30 55 87 e9 c4 10 58 d9 ea 0d 48 3e 02 eb 00 00 00 ab 85 7e d0 29 e8 14 f4 0d 0a 7a 05 3c 37 ba 86 87 04 db b6 09 dc a0 62 fc d1 31 79 bc 5c 0d 0a 8e 02 eb 00 00 00 ab 85 7e d0 29 e8 14 f4 0d 0a 7a 05 3c 37 ba 86 87 04 db b6 09 dc a0 62 fc d1 31 79 bc 5c 0d 0a 8e 02 eb 00 00 00 ab 85 7e d0 29 e8 14 f4 0d 0a 7a 05 3c 37 ba 86 87 04 db b6 09 dc a0 62 fc d1 31 79 bc 5c 0d 0a 8e 02 eb 00 00 00 ab 85 43 c5 30 e2 26 70 4a 1a f3 e4 4d ce 2a 3f 79 cd bc e6 de 73 6f 39 b7 9c db ce 6d 5f be 02 eb 00 00 00 ab 85 43 c5 30 e2 26 70 4a 1a f3 e4 4d ce 2a 3f 79 cd bc e6 de 73 6f 39 b7 9c db ce 6d 5f be 02 eb 00 00 00 ab 85 43 c5 30 e2 26 70 4a 1a f3 e4 4d ce 2a 3f 79 cd bc e6 de 73 6f 39 b7 9c db ce 6d 5f be 02 eb 00 00 Notice the start of the distortion with the "0d" in the result from reading the file back in the 4th line, about the 15th byte over... Then, there are a few more staggered around which in total, skew the image off by 9 bytes worth... Obviously, the drawing portion is working ok as everything remains properly aligned in memory for the 12 lines.
Shouldn't you open the file in a compound mode i.e. writable & binary as in wb+? Notice the start of the distortion with the "0d" That's ASCII code for Carriage Return (CR) -- added on some OSes with newline (where a newline is actually a sequence of CR/LF). This should go away once you start writing the output in binary mode. Your code looks neat otherwise. Cheers!
611,263
611,279
Efficient string concatenation in C++
I heard a few people expressing worries about "+" operator in std::string and various workarounds to speed up concatenation. Are any of these really necessary? If so, what is the best way to concatenate strings in C++?
The extra work is probably not worth it, unless you really really need efficiency. You probably will have much better efficiency simply by using operator += instead. Now after that disclaimer, I will answer your actual question... The efficiency of the STL string class depends on the implementation of STL you are using. You could guarantee efficiency and have greater control yourself by doing concatenation manually via c built-in functions. Why operator+ is not efficient: Take a look at this interface: template <class charT, class traits, class Alloc> basic_string<charT, traits, Alloc> operator+(const basic_string<charT, traits, Alloc>& s1, const basic_string<charT, traits, Alloc>& s2) You can see that a new object is returned after each +. That means that a new buffer is used each time. If you are doing a ton of extra + operations it is not efficient. Why you can make it more efficient: You are guaranteeing efficiency instead of trusting a delegate to do it efficiently for you the std::string class knows nothing about the max size of your string, nor how often you will be concatenating to it. You may have this knowledge and can do things based on having this information. This will lead to less re-allocations. You will be controlling the buffers manually so you can be sure that you won't copy the whole string into new buffers when you don't want that to happen. You can use the stack for your buffers instead of the heap which is much more efficient. string + operator will create a new string object and return it hence using a new buffer. Considerations for implementation: Keep track of the string length. Keep a pointer to the end of the string and the start, or just the start and use the start + the length as an offset to find the end of the string. Make sure the buffer you are storing your string in, is big enough so you don't need to re-allocate data Use strcpy instead of strcat so you don't need to iterate over the length of the string to find the end of the string. Rope data structure: If you need really fast concatenations consider using a rope data structure.
611,323
611,677
Can you call C++ functions from Ada?
Can you call C++ functions from Ada? I'm wondering if there is a way to do this directly, without doing the implementation in C and writing a C++ wrapper & and Ada wrapper, e.g. I would like to go c++ -> Ada rather than c++ -> c -> Ada.
The problem with Ada to C++ is that C++ does NOT have a defined ABI. Each compiler is allowed to define the most effecient ABI it can. Thus interfacing from other languages (Ada) is a pain as you would need your Ada compiler to know which compiler the C++ was compiled with before it could generate the correct code to call any C++ method/function. On the other hand the C ABI is well defined a standard across all compilers and as such provides a nice convenient interface for any language to connect with.
611,703
611,724
Pointer to a Pointer question
I have a class with a (non smart) pointer to an interface object (lets call it pInterface) and I am building a nested class which also needs access to that interface. I am going to get around this by passing the pointer to the interface into the constructor of the nested class like so: CNestedClass someClass( pInterface, ... ); However I am unsure of the best way of storing this pointer in the nested class. I could use: 1) A scoped (or other smart) pointer (to the original object) 2) A pointer to a pointer What would you guys suggest and why? EDIT: I should clarify - the nested class will need to call methods on the interface object, however it does not create it (or modify the object 'pointed' to ), the parent class is responsible for that.
The use a pointer to a pointer is if either class may alter the value of the pointer - e.g. by deleting the existing object and replacing it with a new one. This allows both classes to still use the same object by dereferencing the pointer-to-pointer. If not your concern is ensuring the object remains valid throughout the lifetime of both classes. If the nested class lives shorter you don't really have to worry. If it's the same, provided you clean-up in the correct order (e.g. nested class first, object later) then again, you don't have to worry If the nested class could persist after the owner is destroyed then you must implement a way to ensure the object also persists. If you need to ensure the lifetime of the object it could be done via reference counting-semantics, either manually or through a smart-pointer interface. For a smart pointer then boost::shared_ptr would be a good choice. shared_ptr allows the ownership of an object to be shared amount multiple pointers. When the last shared_ptr goes out of scope, the object is deleted. (note this is not the case with auto_ptr, where an object are exclusively owned). Things to be aware of; When using boost::shared_ptr be sure the nested class has a copy of the shared_ptr and not a reference/pointer. std::auto_ptr behaves quite differently, objects are exclusively owned and not shared boost::shared_ptr can only work with heap objects, e.g pointers returned from a call to 'new' Example: typedef boost::shared_ptr<Interface> shared_interface; class NestedClass { shared_interface mInterface; // empty pointer } void NestedClass::setInterface(shared_interface& foo) { mInterface= foo; // take a copy of foo. } void ParentClass::init( void ) { // mInterface is also declared as shared_interface mInterface = new Interface(); mNestedClass->setInterface(mInterface); }
611,892
611,914
I need to create a simple callback in c++? Should I use boost::function?
Suppose I have some code like this: class Visitor { public: Visitor(callBackFunction) {} void visit() { //do something useful invokeCallback(); } } class ClassThatCanBeVisited { Visitor &visitor; public: ClassThatCanBeVisited(Visitor &_visitor) : visitor(_visitor){} void someUsefulMethod() { int data= 42; visitor.visit(data); } }; void callBackFunction() { //do something useful in the context of the Main file } int main() { Visitor visitor; ClassThatCanBeVisited foo(visitor); foo.someUsefulMethod(); } I need to create a simple callback that will be called whenever the Visitor::visit() is called. I know that I probably should put the code of the callback inside my Visitor, but it is in a different context, so I would like to pass the callBackFunction() to the Visitor so he could invoke my callback function. I looked for things on the web and saw boost::function, but c++ already has the basic functors. Which one should I use for better clarity of the code? The callback is going to be a simple void() function, but it might grow, you never know the future :) What is the recommended way to do this?
You can use callback interface and its hierarchy if you don't want to use boost::function. class VisitorCallback { public: virtual void handle( const Visitor& ) = 0; }; If you have or can use boost::function - use it, it is a good way to get rid of all those callback classes. Edit: @edisongustavo: boost::function and boost::bind won't probably make your code more readable. But it will give you an opportunity to pass free functions ( I mean functions out of class and static class functions ) as callback as well as existing functions of any class. With boost functions you can pass functions with for example 2 parameters as callback which expect only one parameter. typedef boost::function< void ( int ) > IntExpectingCallback; void TwoIntFunction( int, int ); { } ... IntExpectingCallback callback = boost::bind( TwoIntFunction, 5, _1 ); But again, this won't make your code more readable unless all your team knows and favor boost.
611,929
612,276
Detect Debug Mode in Managed C++
What's the best way to detect whether an app is running in debug mode in Managed C++/C++/CLI?
array<Object^>^ debuggableAttributes = Assembly::GetExecutingAssembly()->GetCustomAttributes(DebuggableAttribute::typeid, false); Console::WriteLine(debuggableAttributes->Length > 0); (The compiler adds a DebuggableAttribute to an assembly when compiled in debug mode)
612,019
612,165
library for doing diffs
I've been tasked with creating a tool that can diff and merge the configuration files for my company's product. The configurations are stored as either XML or URL-encoded strings. I'm looking for a library, preferably open source with a license compatible with commercial software, that can do these diffs. Our app is written in C++, so C++ libraries would be best, but I'm willing to look at libraries that are C#-specific since I can write a wrapper that exposes it to C++ via COM. Three-way diffs would be ideal, but two-way is acceptable. If it has an understanding of XML, that would also be a plus (since XML nodes can be reordered without changing the document, etc). Any library suggestions? Should I even consider writing my own diff tools in the hopes of giving it semantic knowledge of our formats? Thanks to this similar question, I've already discovered this google library, which seems really great, but I'm still looking for other options. It also seems to be able to output the diffs in HTML format (using the <ins> and <del> tags that I didn't know existed before I discovered it), which could be really handy, but it seems to be a unified diff only. I'm going to need to display the results in a web browser, and probably have to build an interface for doing the merges in the browser as well. I don't expect a library to be able to help with these tasks, but it must produce output in a format that is amenable to me building this on top of it. I'm currently envisioning something along the lines of TortoiseMerge (side-by-side diffs, not unified), except browser-based. Any tips/tricks/design ideas on how to present this would be appreciated too.
For diffing the XML I would propose that you normalize it first: sort all the elements in alphabetic order, then generate a stream of tokens/xml that represents the original document but is independent of the original formatting. After running the diff, parse the result to get a tree containing what was added / removed.
612,097
612,176
How can I get the list of files in a directory using C or C++?
How can I determine the list of files in a directory from inside my C or C++ code? I'm not allowed to execute the ls command and parse the results from within my program.
UPDATE 2017: In C++17 there is now an official way to list files of your file system: std::filesystem. There is an excellent answer from Shreevardhan below with this source code: #include <string> #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::string path = "/path/to/directory"; for (const auto & entry : fs::directory_iterator(path)) std::cout << entry.path() << std::endl; } Old Answer: In small and simple tasks I do not use boost, I use dirent.h. It is available as a standard header in UNIX, and also available for Windows via a compatibility layer created by Toni Ronkko. DIR *dir; struct dirent *ent; if ((dir = opendir ("c:\\src\\")) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir (dir)) != NULL) { printf ("%s\n", ent->d_name); } closedir (dir); } else { /* could not open directory */ perror (""); return EXIT_FAILURE; } It is just a small header file and does most of the simple stuff you need without using a big template-based approach like boost (no offence, I like boost!).
612,328
612,350
Difference between 'struct' and 'typedef struct' in C++?
In C++, is there any difference between: struct Foo { ... }; and: typedef struct { ... } Foo;
In C++, there is only a subtle difference. It's a holdover from C, in which it makes a difference. The C language standard (C89 §3.1.2.3, C99 §6.2.3, and C11 §6.2.3) mandates separate namespaces for different categories of identifiers, including tag identifiers (for struct/union/enum) and ordinary identifiers (for typedef and other identifiers). If you just said: struct Foo { ... }; Foo x; you would get a compiler error, because Foo is only defined in the tag namespace. You'd have to declare it as: struct Foo x; Any time you want to refer to a Foo, you'd always have to call it a struct Foo. This gets annoying fast, so you can add a typedef: struct Foo { ... }; typedef struct Foo Foo; Now struct Foo (in the tag namespace) and just plain Foo (in the ordinary identifier namespace) both refer to the same thing, and you can freely declare objects of type Foo without the struct keyword. The construct: typedef struct Foo { ... } Foo; is just an abbreviation for the declaration and typedef. Finally, typedef struct { ... } Foo; declares an anonymous structure and creates a typedef for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. This means it also cannot be forward-declared. If you want to make a forward declaration, you have to give it a name in the tag namespace. In C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name. See Michael Burr's answer for the full details.
612,374
612,392
What is the best way to initialize a bitfield struct in C++?
In C++, I have a class which contains an anonymous bitfield struct. I want to initialize it to zero without having to manually write out all fields. I can imagine putting the initialization in three places: Create a constructor in the bitfield Zero out in the initializer list of the constructor for the containing class Zero out in the body of the constructor for the containing class This bitfield has many fields, and I'd rather not list them all. For example see the following code: class Big { public: Big(); // Bitfield struct struct bflag_struct { unsigned int field1 : 1; unsigned int field2 : 2; unsigned int field3 : 1; // ... unsigned int field20 : 1; // bflag_struct(); <--- Here? } bflag; unsigned int integer_member; Big *pointer_member; } Big::Big() : bflag(), // <--- Can I zero bflag here? integer_member(0), pointer_member(NULL) { // Or here? } Is one of these preferable? Or is there something else I'm missing? Edit: Based on the accepted answer below (by Ferruccio) I settled on this solution: class Big { // ... struct bflag_struct { unsigned int field 1 : 1; // ... bflag_struct() { memset(this, 0, sizeof *this); }; } // ... }
You could always do this in your constructor: memset(&bflag, 0, sizeof bflag);
612,739
612,758
"The Debugger has exited due to signal 10" when writing a char* iteration
So I have a program that makes char* stuff lowercase. It does it by iterating through and manipulating the ascii. Now I know there's probably some library for this in c++, but that's not the point - I'm a student trying to get a grasp on char*s and stuff :). Here's my code: #include <iostream> using namespace std; char* tolower(char* src); int main (int argc, char * const argv[]) { char* hello = "Hello, World!\n"; cout << tolower(hello); return 0; } char* tolower(char* src) { int ascii; for (int n = 0; n <= strlen(src); n++) { ascii = int(src[n]); if (ascii >= 65 && ascii <= 90) { src[n] = char(ascii+32); } } return src; } ( this is not for an assignment ;) ) It builds fine, but when I run it it I get a "The Debugger has exited due to signal 10" and Xcode points me to the line: "src[n] = char(ascii+32);" Thanks! Mark
Yowsers! Your "Hello World!" string is what is called a string literal, this means its memory is part of the program and cannot be written to. You are performing what is called an "in-place" transform, e.g. instead of writing out the lowercase version to a new buffer you are writing to the original destination. Because the destination is a literal and cannot be written to you are getting a crash. Try this; char hello[32]; strcpy(hello, "Hello, World!\n"); Also in your for loop, you should use <, not <=. strlen returns the length of a string minus its null terminator, and array indices are zero-based.
612,753
612,772
Implementing friend (available in C++) functionality in C#
Ok, let's leave the debate of whether friendship breaks encapsulation, and actually try elegantly come up with a coherent design. It is a two fold function: 1) General question on how to implement: public class A { friend class B; } 2) Why do I need this functionality? Some of my classes implement ISerializable interface. However, I want to make ISerializable methods protected in the Derived class so that I don't expose them to a client (as well as in the documentation). However, internal classes should be able to access them. What is the General way to solve this problem in C#? Note: I am using friendship as defined in the current C++ standard. Thanks
Leaving the InternalsVisibleTo stuff to one side, you only have two choices when it comes to implementing interfaces: Implement them with public methods Implement them using explicit interface implementation In both cases anyone can call the methods, but using explicit interface implementation you can only call the methods "via" an interface expression (e.g. you could cast a variable of the actual type to the ISerializable). There's no such concept as "internally" implementing an interface.
613,131
613,200
Dependency Injection and Runtime Object Creation
I've been trying to follow the principles of Dependency Injection, but after reading this article, I know I'm doing something wrong. Here's my situation: My application receives different types of physical mail. All the incoming mail passes through my MailFunnel object. While it's running, MailFunnel receives different types of messages from the outside: Box, Postcard and Magazine. Each mail type needs to be handled differently. For example, if a Box comes in, I may need to record the weight before delivering it. Consequently, I have BoxHandler, PostcardHandler and MagazineHandler objects. Each time a new message comes into my MailFunnel, I instantiate a new corresponding MailHandler object. For example: class MailFunnel { void NewMailArrived( Mail mail ) { switch (mail.type) { case BOX: BoxHandler * bob = new BoxHandler(shreddingPolicy, maxWeightPolicy); bob->get_to_work(); break; case POSTCARD: PostcardHandler * frank = new PostcardHandler(coolPicturePolicy); frank->get_to_work(); break; case MAGAZINE: MagazineHandler * nancy = new MagazineHandler(censorPolicy); nancy->get_to_work(); break; } } private: MaxWeightPolcy & maxWeightPolicy; ShreddingPolicy & shreddingPolicy; CoolPicturePolicy & coolPicturePolicy; CensorPolicy & censorPolicy; } On one hand, this is great because it means that if I get five different pieces of mail in, I immediately have five different MailHandlers working concurrently to take care of business. However, this also means that I'm mixing object creation with application logic - a big no-no when it comes to Dependency Injection. Also, I have all these policy references hanging around in my MailFunnel object that MailFunnel really doesn't need. The only reason that MailFunnel has these objects is to pass them to the MailHandler constructors. Again, this is another thing I want to avoid. All recommendations welcome. Thanks!
This looks more like a factory to me. Move the invocation of the get_to_work() method out of the invocation and return the handler. The pattern works pretty well for a factory. class MailHandlerFactory { IMailHandler* GetHandler( Mail mail ) { switch (mail.type) { case BOX: return new BoxHandler(shreddingPolicy, maxWeightPolicy); break; case POSTCARD: return new PostcardHandler(coolPicturePolicy); break; case MAGAZINE: return new MagazineHandler(censorPolicy); break; } } private: MaxWeightPolcy & maxWeightPolicy; ShreddingPolicy & shreddingPolicy; CoolPicturePolicy & coolPicturePolicy; CensorPolicy & censorPolicy; } class MailFunnel { MailHandlerFactory* handlerFactory; MailFunnel( MailHandlerFactory* factory ) { handlerFactory = factory; } void NewMailArrived( Mail mail ) { IMailHandler handler = handlerFactory.GetHandler(mail); handler.get_to_work(); } }
613,282
613,437
How do I push An instance of a c++ class wrapped with swig onto a lua stack?
I have a class that is wrapped with swig, and registered with lua. I can create an instance of this class in a lua script, and it all works fine. But say I have an instance of a class made in my c++ code with a call to new X, and I have la lua_state L with a function in it that I want to call, which accepts one argument, an instance of X... How do I call that function. Here is (some) of the code in question (I've omitted the error handling stuff): main.cpp class GuiInst; extern "C" { int luaopen_engine (lua_State *L); } int main() { GuiInst gui=new GuiInst; lua_State *L=luaL_newstate(); luaopen_engine(L); //this is swigs module int error=luaL_loadfile(L,"mainmenu.lua")|| lua_pcall(L, 0, 0, 0); lua_getglobal(L,"Init"); //Somehow push gui onto lua stack... lua_pcall(L, 1, 0, 0)); lua_close(L); } mainmenu.lua function Init(gui) vregion=gui:CreateComponent("GuiRegionVertical"); end At the moment all I have found that can work is to expose some functionality from the swig generated cpp file, and call that. This is bad for a few reasons... It won't work if I have multiple modulles and I had to change the default linkage specification in the swig file (using -DSWIGRUNTIME=). I add the following to main.cpp extern "C" { struct swig_module_info; struct swig_type_info; int luaopen_engine (lua_State *L); swig_module_info *SWIG_Lua_GetModule(lua_State* L); void SWIG_Lua_NewPointerObj(lua_State* L,void* ptr,swig_type_info *type, int own); swig_type_info *SWIG_TypeQueryModule(swig_module_info *start,swig_module_info *end,const char *name); } //and then to push the value... SWIG_Lua_NewPointerObj(L,gui,SWIG_TypeQueryModule(SWIG_Lua_GetModule(L),SWIG_Lua_GetModule(L),"GuiInst *"),0); That gets a pointer to the module, then a pointer to the type, then calls swigs function to register it. It was an unreasonable thing to have to dig into a file that's not supposed to be human readable (so it says at the top of the file) and is just MESSY! (but it does work!) Surely theres a better way to accomplish what I'm trying to do. PS from a high level pov what I want is to have lua not refcount the Gui components which are created by the Object Factory in GuiInst, in case I'm going about this wrong. This is my first time exposing functionality to a scripting language apart from some very simple (and non-swig) python modules, so I'm prepared to take advice. Thanks for any advice! Response to comment by RBerteig GuiInst's contructor is #defined to private when swig runs to prevent lua constructing instances of it, so that won't work for me. What I was trying to prevent was the following (in lua): r=engine.GuiRegionVertical() r:Add(engine.GuiButton()) which would call "g=new GuiButton" then register it with the GuiRegionVertical (which needs to store a pointer for various reasons), then call "delete g", and the GuiRegionVertical is left with a dangling pointer to g. I suspect what really needs to happen is that GuiRegionVertical::Add(GuiButton*) should increment the ref count of the GuiButton*, and then GuiRegionVertical's destructor should decrement the refcounts of all of its contents, though i'm not sure how this should be done with swig. That would remove the need for the private constructors, the Gui Object Factory and the nasty externs. Am I going about this Wrong? Thanks.
There is a simple and direct answer, that may not be the most efficient answer. SWIG produces wrappers for manipulating objects from the scripting language side. For objects, it also synthesizes a wrapped constructor. So, the direct solution is to just let the Lua interpreter call SWIG's constructor to create the new object. For the wrapped engine.GuiInst class, you almost certainly can do something like: int main() { lua_State *L=lua_open(); luaopen_engine(L); //this is swigs module int error=luaL_loadfile(L,"mainmenu.lua")|| lua_pcall(L, 0, 0, 0); luaL_dostring(L, "Init(engine.new_GuiInst())"); lua_close(L); } For a one-shot case like script startup, the penalty of running a string constant through luaL_dostring() is not bad at all. I'd look harder to avoid it in an event callback or an inner loop, however. It does seem like there ought to be a way to convert a pointer directly into a wrapped object, I'm not spotting it in my own handful of SWIG generated wrappers. Edit: Of course, the Lua fragment can be decomposed to API calls that get the engine table global on the stack, extract from it the new_GuiInst member, call it, then call the global Init, but the little bit of efficiency comes at the cost of some clarity. As for dealing with objects that shouldn't be constructed by accident in user code, as the clarified question indicates, my first impulse would be to let SWIG generate the constructor function, keep a private reference if needed later, and remove it from the table. Even a C module is (usually) just a table whose members contain function values. Being implemented in C doesn't make them read-only unless extra effort is taken. So, you could always retrieve the value of engine.new_GuiInst and park it in the registry (see luaL_ref() and the discussion in section 3.5 of the Lua Reference Manual of the pseudo-index LUA_REGISTRYINDEX for the details) for later use. Then, before letting any user code run, simply do the equivalent of engine.new_GuiInst = nil. I should note that for the C data types I've been playing with most recently, SWIG created two constructors for each type, named new_TYPE and TYPE. Both were visible in the module's table, and you would want to set both names to nil. If have much less experience with SWIG wrapping C++ classes, and the result may differ... You might want to check and review the whole content of the engine table returned by SWIG, and create a proxy object that contains only the methods you want available to your users. You can also change the environment seen by the user script so that it only has the proxy available, and names the proxy engine as well. There has been a fair amount of discussion of sandboxing user scripts on the Lua list and at the lua-users wiki.
613,361
613,377
Generating Random Number with Certain Rate
I have the following C++ code that tried to generate a random number. The idea is we given some rate "x" and number of runs; we hope it would generate the number as many as (x * number of runs times). #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <time.h> using namespace std; int main () { // Initialize Random Seed srand (time(NULL)); string line; double SubsRate = 0.003; double nofRuns = 1000000; for (unsigned i=0; i < nofRuns ; i++) { int toSub = rand() % 1000 + 1; if (toSub == (SubsRate * 1000)) { cout << toSub << " Sub" << endl; } } return 0; } Hence if we run the code above K times with this command: $ a=0 ; while test $a -lt 10 ; do ./MyCode | wc -l ; a=`expr $a + 1` ; done We expect it to generate number "3" as many as ~3000 times in 1M runs. But some how my code above my code above only generate number "3" as many as 900 ~ 1000 times. How can I improve on my code above?
In other words, you are checking that the result == 3, not that the result is <= 3. 3 will only happen, one in 1000 times, but <= 3 will happen at the rate you want.
613,423
613,425
Winsock: Windows networking programming in C++
I need books that truely explian sockets in windows in C++ ive been looking at tutorials but they dont tell what anything means they dont go into great detail so i need come books on Winsock in C++ for windows
This is by far the best, most up to date book on the subject: Network Programming for Microsoft Windows. One of the nice things about this book is that is shows the range of styles from blocking sockets to completion ports.
613,479
613,501
Where can I find standard BNF or YACC grammar for C++ language?
I'm trying to work on a kind of code generator to help unit-testing an legacy C/C++ blended project. I don't find any kind of independent tool can generate stub code from declaration. So I decide to build one, it shouldn't be that hard. Please, anybody can point me a standard grammar link, better described by yacc language. Hope I'm not reinventing wheel, please help me out in that case. Best Regards, Kevin
From the C++ FAQ Lite: 38.11 Is there a yacc-able C++ grammar? The primary yacc grammar you'll want is from Ed Willink. Ed believes his grammar is fully compliant with the ISO/ANSI C++ standard, however he doesn't warrant it: "the grammar has not," he says, "been used in anger." You can get the grammar without action routines or the grammar with dummy action routines. You can also get the corresponding lexer. For those who are interested in how he achieves a context-free parser (by pushing all the ambiguities plus a small number of repairs to be done later after parsing is complete), you might want to read chapter 4 of his thesis. There is also a very old yacc grammar that doesn't support templates, exceptions, nor namespaces; plus it deviates from the core language in some subtle ways. You can get that grammar here or here.
613,642
613,660
Invalid Conversion Problem in C++
I have the following snippet: string base= tag1[j]; That gives the invalid conversion error. What's wrong with my code below? How can I overcome it. Full code is here: #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <time.h> using namespace std; int main ( int arg_count, char *arg_vec[] ) { if (arg_count < 3 ) { cerr << "expected one argument" << endl; return EXIT_FAILURE; } // Initialize Random Seed srand (time(NULL)); string line; string tag1 = arg_vec[1]; string tag2 = arg_vec[2]; double SubsRate = 0.003; double nofTag = static_cast<double>(atoi(arg_vec[3])); vector <string> DNA; DNA.push_back("A"); DNA.push_back("C"); DNA.push_back("G"); DNA.push_back("T"); for (unsigned i=0; i < nofTag ; i++) { int toSub = rand() % 1000 + 1; if (toSub <= (SubsRate * 1000)) { // Mutate cout << toSub << " Sub" << endl; int mutateNo = 0; for (int j=0; j < tag1.size(); j++) { mutateNo++; string base = tag1[j]; // This fail int dnaNo = rand() % 4; if (mutateNo <= 3) { // Mutation happen at most at 3 position base = DNA[dnaNo]; } cout << tag1[j] << " " << dnaNo << " " << base << endl; //cout << base; } cout << endl; } else { // Don't mutate //cout << tag1 << endl; } } return 0; } Why do I get an Invalid conversion from char to const char* when looping over a string?
The std::string operator [] returns a single char. string cannot be instantiated with a single char. Use: string base = string( 1, tag1[j] ) instead
613,739
613,761
Delaying array size in class definition in C++?
Is there some way to delay defining the size of an array until a class method or constructor? What I'm thinking of might look something like this, which (of course) doesn't work: class Test { private: int _array[][]; public: Test::Test(int width, int height); }; Test::Test(int width, int height) { _array[width][height]; }
What Daniel is talking about is that you will need to allocate memory for your array dynamically when your Test (width, height) method is called. You would declare your two dimensional like this (assuming array of integers): int ** _array; And then in your Test method you would need to first allocate the array of pointers, and then for each pointer allocate an array of integers: _array = new *int [height]; for (int i = 0; i < height; i++) { _array [i] = new int[width]; } And then when the object is released you will need to explicit delete the memory you allocated. for (int i = 0; i < height; i++) { delete [] _array[i]; _array [i] = NULL; } delete [] _array; _array = NULL;
613,799
614,053
is there a use for &func or class::func in c++?
This seems inconsistent. Why do we use &Example::func instead of Example::func? is there a use for Example::func or &exampleFunction? it doesnt seem like we can make a reference to a function so that rules out Example::func. and i cant think of a way to use &exampleFunction since exampleFunction already returns a pointer. #include <iostream> class Example { public: void func() { std::cout <<"print me\n"; } }; void exampleFunction() { std::cout << "print me too\n"; } typedef void (Example::*ExampleFunc_t)(); typedef void (*ExampleFunction_t)(); int main() { Example e; ExampleFunc_t f = &Example::func; ExampleFunction_t f2 = exampleFunction; (e.*f)(); f2(); return 0; }
Because that's how the standard defines pointers to functions. You actually always have to use the address operator & to get a pointer to a function, but for regular functions and static member function, an implicit conversion from function to pointer-to-function is defined in the standard. This is not defined for a (non static) memberfunction because you can't obtain an lvalue to a non static memberfunction. From the C++ standard: 4.3 Function-to-pointer conversion An lvalue of function type T can be converted to an rvalue of type “pointer to T .” The result is a pointer to the function. with footnote 52: This conversion never applies to non-static member functions because an lvalue that refers to a non-static member function cannot be obtained. I think that they'd rather only allow &function, for consistency reasons, but that the implicit conversion is simply an artifact of the C heritage...
613,807
613,820
About Comparing String With String
I tried to make character by character comparison under string type, with the following code: vector <int> getQuality(string seedTag, vector <string> &MuTag) { vector <int> Quals; for (unsigned i = 0; i<MuTag.size(); i++) { Quals.push_back(-40); cout << MuTag[i] << " " << seedTag[i] << endl; if (MuTag[i] == seedTag[i]) { // This line 33 with error Quals.push_back(40); } } return Quals; } But why it gives such error: Mycode.cc:33: error: no match for 'operator==' in '(+ MuTag)->std::vector<_Tp, _Alloc>::operator[] [with _Tp = std::string, _Alloc = std::allocator<std::string>](((long unsigned int)i)) == seedTag. std::basic_string<_CharT, _Traits, _Alloc>::operator[] [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](((long unsigned int)i) How can I resolve it?
You are trying to compare a string (MuTag[i]) with a char (seedTag[i]).
613,825
613,840
is there any tristate type in c++ stl?
is there any tristate type in c++ stl?
No, but there is boost tribool.
613,968
614,026
Software optimization for virtual machines
When you know that your software (not a driver, not part of the os, just an application) will run mostly in a virtualized environment are there strategies to optimize your code and/or compiler settings? Or any guides for what you should and shouldn't do? This is not about a 0.0x% performance gain but maybe, just maybe there are simple things that will improve performance drastically or things that seem simple but are known to be disastrous in virtualized environments. For example enabling CONFIG_PARAVIRT in a kernel build is easily done and can boost performance a lot. Now I'm looking for similar things for applications, if there are any. In my case it will be C++ Code and probably VMWare but I want to keep the question as language/product-agnostic as possible. I wonder if there even are such strategies or if this would be a complete waste of time - after all the concept of virtualization is that you don't have to care too much about it.
The only advice that I can give you is careful use of mlock() / mlockall() .. while looking out for buggy balloon drivers. For instance, if a Xen guest is booted with 1GB, then ballooned down to 512 MB, its very typical that the privileged domain did NOT look at how much memory the paravirtualized kernel was actually promising to processes (i.e. Committed_AS). Actually, with Xen, unless this value is placed on Xenbus, the privileged host has no idea what such a balloon will do. I believe this also coincides with KVM, depending upon how the kernel is configured .. but your question presumes that we know nothing about such things :) So, protect stuff (be careful, but prudent) that simply can not be paged out, always account for the 'sky is falling' scenario. Likewise, use of posix_fadvise() / posix_madvise() to tell the PV kernel just how much you do or do not need buffering is always a good idea. Beyond that, there's very little that you can do .. since you're talking only to the paravirtualized kernel, which is designed to make processes oblivious to virtualization in the first place. I don't use KVM much (yet), though I plan to explore it more in the future. However, 90% of the stuff that I have been writing lately is specifically designed to run on paravirtualized Xen guests. Sorry to be a little Xen / C centric, but that's where my experience is and pv_ops is in mainline (soon also xen-0 ops) :) Good question, btw :) Edit: When I said 'careful but prudent' , I meant one step above conservative. If your program allocates some job structure that most functions need, lock it. If your allocating buffers to read huge files, don't lock them .. and be sure to call posix_fadvise() to let the kernel know you only intend to access it once (if that's the case). Also, be sure to advise the kernel on your use of memory mapped files, especially if they serve to organize concurrency. In short, help your host kernel manage memory, don't let critical allocated blocks get thrown into dirty paging, don't assume your program is more important than anything else by locking everything it allocates :) Sorry for the ambiguity. The best phrase I could come up with was 'careful, but prudent'.
614,012
614,029
Howto Restart Loop in C++ (Finding Unique Sequence Over Random Runs)
The following codes try to generate random strings over K runs. But we want the newly generated strings to be totally different with its reference string. For that I tried to use "continue" to restart the random string generation process. However it doesn't seem to work. What's wrong with my approach below? #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <time.h> using namespace std; // In this code we want to print new string that is entirely different with // with those in initVector template <typename T> void prn_vec(std::vector < T >&arg, string sep="") { // simple function for printing vector for (int n = 0; n < arg.size(); n++) { cout << arg[n] << sep; } } int main ( int arg_count, char *arg_vec[] ) { // This is reference string vector <string> initVec; initVec.push_back("A"); initVec.push_back("A"); initVec.push_back("A"); initVec.push_back("A"); vector <string> DNA; DNA.push_back("A"); DNA.push_back("C"); DNA.push_back("G"); DNA.push_back("T"); for (unsigned i =0; i< 10000; i++) { vector <string> newString; for(unsigned j=0; j<initVec.size(); j++) { int dnaNo = rand() % 4; string newBase = DNA[dnaNo]; string oldBase = initVec[j]; int sameCount = 0; if (newBase == oldBase) { sameCount++; } if (sameCount == initVec.size()) { continue; } newString.push_back(newBase); } cout << "Run " << i << " : "; prn_vec<string>(newString); cout << endl; } return 0; }
Your code looks fine on first glance, unless I am missing a big part of your requirements. Read this before you use rand(). Except of course, the continue part. What you are trying to do is see if this is the same as the initVector or not, right? A simple comparison would do before you push it in or print to the console. int sameCount = 0; if (newBase == oldBase) { sameCount++; } // sameCount can be 1 at most, 0 otherwise // this check never return true if (sameCount == initVec.size()) { continue; } The sameCount variable is initialized each time you create a new entry to the newString and goes out of scope at the closing } of the for loop. So, it will not be incremented to function as a proper check against duplicate generation. You should ideally, use a std::set and keep inserting in it. Duplicates are not allowed and you are saved from a lot of trouble. More on using rand() srand() and random number generation: From the comp.lang.c FAQ: [...]the low-order bits of many random number generators are distressingly non-random If you want to keep your randome numbers in the range [0, 1, ... N - 1] a better method compared to the simple rand() % N (as advised in the link) is to use the following: (int)((double)rand() / ((double)RAND_MAX + 1) * N) Now, if you were to run your program, every time you will get the same set of 10000 odd random DNA strands. Turns out this is because: It's a characteristic of most pseudo-random number generators (and a defined property of the C library rand) that they always start with the same number and go through the same sequence. from another FAQ of comp.lang.c. To get different strands across runs try the following: #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <ctime> #include <cstdlib> using namespace std; int main ( int arg_count, char *arg_vec[] ) { // most pseudo-random number generators // always start with the same number and // go through the same sequence. // coax it to do something different! srand((unsigned int)time((time_t *)NULL)); // This is reference string string initVec("AAAA"); // the family string DNA("ACGT"); for (unsigned i =0; i< 5; i++) { string newString; for(unsigned j=0; j<initVec.size(); j++) { int dnaNo = (int)((double)rand() / ((double)RAND_MAX + 1) * 4); char newBase = DNA[dnaNo]; newString += newBase; } // ideally push in a std::set // for now keep displaying everything if (newString != initVec) { cout << "Run " << i << " : " << newString << endl; } } return 0; }
614,094
614,101
Why does this simple string assignment segfault?
I’ve got the following code: #include <iostream> using namespace std; int main() { char* a = "foo"; char* b = "bar"; a = b; cout << a << ", " << b << endl; return 0; } This compiles and works, ie. prints bar, bar. Now I would like to demonstrate that what goes on here is not copying a string. I would like to change b and show that a also changes. I came up with this simple code: #include <iostream> using namespace std; int main() { char* a = "foo"; char* b = "bar"; a = b; b[1] = 'u'; // ← just this line added cout << a << ", " << b << endl; return 0; } …but it segfaults. Why? The interesting thing is that the following modification runs just fine: #include <iostream> using namespace std; int main() { char* a = "foo"; char b[] = "bar"; // ← declaration changed here a = b; b[1] = 'u'; cout << a << ", " << b << endl; return 0; } Why doesn’t it segfault like the previous one? I guess I am missing some important difference between the pointer-style and the array-style string initialization.
You cannot change string constants, which is what you get when you use the pointer-to-literal syntax as in the first code samples. See also this question: Is a string literal in c++ created in static memory?.
614,233
614,261
Undefined reference to function template when used with string (GCC)
I need to write a templated function replace_all in C++ which will take a string, wstring, glibmm::ustring etc. and replace all occurrences of search in subject with replace. replace_all.cc template < class T > T replace_all( T const &search, T const &replace, T const &subject ) { T result; typename T::size_type done = 0; typename T::size_type pos; while ((pos = subject.find(search, done)) != T::npos) { result.append (subject, done, pos - done); result.append (replace); done = pos + search.size (); } result.append(subject, done, subject.max_size()); return result; } test.cc #include <iostream> template < class T > T replace_all( T const &search, T const &replace, T const &subject ); // #include "replace_all.cc" using namespace std; int main() { string const a = "foo bar fee boor foo barfoo b"; cout << replace_all<string>("foo", "damn", a) << endl; return 0; } When I try to compile this using gcc 4.1.2 g++ -W -Wall -c replace_all.cc g++ -W -Wall -c test.cc g++ test.o replace_all.o I get: test.o: In function `main': test.cc:(.text+0x13b): undefined reference to ` std::basic_string<char, std::char_traits<char>, std::allocator<char> > replace_all< std::basic_string<char, std::char_traits<char>, std::allocator<char> > >( std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const& ) ' collect2: ld returned 1 exit status But when I uncomment #include "replace_all.cc" in test.cc and compile this way: g++ -W -Wall test.cc The program links and produces expected output: damn bar fee boor damn bardamn b Why linking fails and what can I do to make it work?
You can't link templates as compiler don't know which code to generate before someone tries to use ( instantiate ) templates. You can "ask" compiler to instantiate template if you knows which types are you going to use or if you know that they are limited. If you want - put this to your .cc file: template std::string replace_all( std::string const& search, std::string const& replace, std::string const& subject ); template glibmm::ustring replace_all( glibmm::ustring const& search, glibmm::ustring const& replace, glibmm::ustring const& subject );
614,242
615,767
What is the best way to get the hash of a QPixmap?
I am developing a graphics application using Qt 4.5 and am putting images in the QPixmapCache, I wanted to optimise this so that if a user inserts an image which is already in the cache it will use that. Right now each image has a unique id which helps optimises itself on paint events. However I realise that if I could calculate a hash of the image I could lookup the cache to see if it already exists and use that (it would help more for duplicate objects of course). My problem is that if its a large QPixmap will a hash calculation of it slow things down or is there a quicker way?
A couple of comments on this: If you're going to be generating a hash/cache key of a pixmap, then you may want to skip the QPixmapCache and use QCache directly. This would eliminate some overhead of using QStrings as keys (unless you also want to use the file path to locate the items) As of Qt4.4, QPixmap has a "hash" value associated with it (see QPixmap::cacheKey() ). The documentation claims "Distinct QPixmap objects can only have the same cache key if they refer to the same contents." However, since Qt uses shared-data copying, this may only apply to copied pixmaps and not to two distinct pixmaps loaded from the same image. A bit of testing would tell you if it works, and if it does, it would let you easily get a hash value. If you really want to do a good, fairly quick cache with removing duplications, you might want to look at your own data structure that sorts according to sizes, color depths, image types, and things such as that. Then you would only need to hash the actual image data after you find the same type of image with the same dimensions, bit-depths, etc. Of course, if your users generally open a lot of images with those things the same, it wouldn't help at all. Performance: Don't forget about the benchmarking stuff Qt added in 4.5, which would let you compare your various hashing ideas and see which one runs the fastest. I haven't checked it out yet, but it looks pretty neat.
614,325
614,407
warning LNK4099: PDB 'vc80.pdb' was not found after switching to vista
I'm getting several of the following warnings in VS2005 on an old project after moving from my old XP to a new vista PC: UnitTest++.vsnet2005.lib(TestRunner.obj) : warning LNK4099: PDB 'vc80.pdb' was not found with 'c:\projects\blah.lib' or at 'c:\projects\blah\debug\vc80.pdb'; linking object as if no debug info I know that this warnign can be ignored but I don't like warnings. The warnings all relate to a third party library (UnitTest++) I'm statically linking to. I can't see how this can be related to vista but both PCs have the same quantity of vc80.pdb files in the same locations after a build so I am confused as to how to fix this issue. Any ideas welcome. Edit: Ok it's gone away. Just in case anyone expeeriences any thing similar I did three things but not sure what clicked it over: 1: copy any old vc80.pdb next to the lib, built it, and then deleted the pdb 2: changed the properties->c/c++->debug information format from edit and continue to database only, built it, and switched it back again 3: rebuilt the third party library (this seems most likely but I'm sure this was the first thing I did yesterday to no effect...)
have you tried to clean/rebuild UnitTest++ library projects (if it is build form sources)?
614,437
614,470
Elegant way to read business rules stored in XML file
I have to read business rules stored in XML file (I am using VC++/MFC/MSXML). XML consists of rules. Each rule has a set of conditions and actions. What would be an elegant OOP design for such system? What design patterns would you use if you where a designer of such system? update: Rules are put in sequence and executed one buy one if all conditions of rule are met. example of xml: <rules> <!-- rule no. 1 --> <rule name="rule no. 1"> <conditions> <condition name="condition no. 1" type="ATTR_EMPTY"> <parameters> <parameter name="attribute_name">ttt</parameter> <parameter name="workflow_id">3</parameter> <parameter name="workflow_state_id">5</parameter> </parameters> </condition> <condition name="condition no. 2" type="ATTR_EMPTY"> <parameters> <parameter name="attribute_name">ttt</parameter> <parameter name="enviroment_id">3</parameter> </parameters> </condition> </conditions> <actions> <action name="action no. 1" type="ATTR_CLEAR"> <parameters> <parameter name="attribute_name">ttt</parameter> </parameters> </action> </actions> </rule> </rules>
Difficult to tell from such a brief description, but I would make each rule an object which manages its own conditions and actions. The rules would be created by a factory from the XML and stored in some sort of dictionary.
614,492
614,555
How do I find my program's main(...) function?
I am currently porting a project with a few hundred code files and dependencies onto several third-party libraries to Mac Os. I've finally gotten to the point where the program compiles without warnings or errors, but it does not seem to execute my own main function. Instead it seems to execute some other main function which seems to belong to a third party. This function writes some diagnostic-looking data to the console and exits afterwards: (gdb) continue Current language: auto; currently c++ // // This is an automatically generated file. // Do not edit. // const unsigned short expTable[] = { 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, ... 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, }; Debugger stopped. Program exited with status value:0. I can't use the debugger to find out where this main function resides because, while the stack trace seems valid, gdb doesn't show me the correct line number and file name for each stack entry (See this unsolved question for details). The search took several minutes to complete, but did not return any results. My project is using SDL among other libraries, but I am award of SDL_Main() and the underlying problems and have built my project on top of a perfectly fine working SDL project template. So I am quite sure that my own main function is valid. Do you have any idea what might be going wrong? I'm currently out of ideas on how to find and remove the rogue main function. Thanks, Adrian EDIT: As I just found out, I made a mistake while searching file files with the string "This is an automatically generated". I just found several dozen files with the same string, all belonging to FreeImage, one of the third party libraries I am using. So, the problem seems to be related to FreeImage, but I am not still not sure how to proceed since I have compiled Freeimage as a library with the enclosed MacOs makefile and included only the library. I will try to rebuild a newer version of FreeImage and see it if that fixed my problem.
Could it be an initializer for a static object that fails before your main() is called?
614,540
614,705
Where can I find the binaries for arm-wince-pe-gcc?
I am looking for a version of the gcc (C++) compiler targeting the ARM uP and WindowsCE operating system. Thus far I have only been able to locate compilers which either target the ARM uP but produce ELF executables (GNUARM etc) or they do target windows CE but have not been updated since 2003. I believe the exact name of the compiler I am looking for is arm-wince-pe-gcc as mentioned In the GCC documentation but I have no clue how to get hold of a binary. Any/all help will be greatly appreciated.
I found a binary version of the required compiler here: http://sourceforge.net/project/showfiles.php?group_id=173455&package_id=198682 choose 0.51.0/cygwin-cegcc-cegcc-0.51.0-1.tar.gz file for download.
614,718
614,762
Wrapping a data structure
I have a data structure that I want to access / modify in different ways in different situations. I came up with this: class DataStructure { public: int getType(); private: // underlying data containers }; class WrapperBase { public: void wrap(DataStructure *input) {dataStructure = input;} protected: DataStructure *dataStructure; }; class WrapperOne : public WrapperBase { public: // @Mykola: I know bytes 4-10 in an array of type one specify the date // so this method will format those bytes and return them Data getDate() }; class WrapperTwo : public WrapperBase { public: // @Mykola: There is mostly just a chunk of data in packet type two. So this // method will turn 4 bytes into an int at position index and return that int dataAt(int index); }; One problem I see here is that WrapperBase isn't abstract even though it should be. I could of course add some pure virtual dummy function or an assert(0) in the constructor but that seems too hackish a solution. Or should I get rid of the inheritance entirely since it's only really done for code-reuse? Any other problems with this solution? Or am I on the wrong track entirely? Edit @ Paul Why do I want to do this? Well, I get several 1000 arrays of serialized data, which I want to add to a dataset. The first few bytes of each array tell me what sort of data it is, which dictates how I have process it. So then I do something like: // some place in the program dataSet.processData(dataStructure); // in the data set class DataSet::processData(DataStructure *dataStructure) { if(dataStructure->getType() == TYPE_ONE) { WrapperOne wrapperOne; wrapperOne.wrap(dataStructure); processDataTypeOne(wrapperOne); } // repeat the above for other data types } I could of course put all the logic in the processDataTypeOne function, and that was what I was doing in the beginning, but operating on the raw data structure turned into an ugly mess of index operations. That's why I'd like to wrap it in an object, which will hide all that.
Make your wrappers to be a data. Create factory that will return either data or different wrappers. Here is what I mean. class DataStructure { public: typedef int DataType; DataStructure( int id ): id_( id ) {} DataStructure( const DataStructure& dataStructure ); virtual ~DataStructure(); virtual void Set( const DataType& data ) { data_ = data; } virtual DataType Get() const { return data_; } int id() const { return id_; } private: DataType data_; int id_; }; class WrapperBase : public DataStructure { public: WrapperBase( DataStructure* dataStructure ): DataStructure( dataStructure->id() ), dataStructure_( dataStructure ) {} virtual void Set( const DataType& data ); virtual DataType Get() const; protected: DataStructure* dataStructure_; }; class WrapperOne : public WrapperBase { public: WrapperOne( DataStructure* dataStructure ); virtual void Set( const DataType& data ); virtual DataType Get() const; }; class WrapperTwo : public WrapperBase { public: WrapperTwo( DataStructure* dataStructure ); virtual void Set( const DataType& data ); virtual DataType Get() const; }; DataStructure* getWrapper( DataStructure* dataStructure ) { switch ( dataStructure->id() ) { case 1: return new WrapperOne( dataStructure ); case 2: return new WrapperTwo( dataStructure ); default: return new DataStructure( *dataStructure ); } } void processData(DataStructure *dataStructure) { std::auto_ptr<DataStructure> wrapper( getWrapper( dataStructure ) ); processDataImpl( wrapper.get() ); }
614,794
614,925
Detecting superfluous #includes in C/C++?
I often find that the headers section of a file get larger and larger all the time but it never gets smaller. Throughout the life of a source file classes may have moved and been refactored and it's very possible that there are quite a few #includes that don't need to be there and anymore. Leaving them there only prolong the compile time and adds unnecessary compilation dependencies. Trying to figure out which are still needed can be quite tedious. Is there some kind of tool that can detect superfluous #include directives and suggest which ones I can safely remove? Does lint do this maybe?
It's not automatic, but doxygen will produce dependency diagrams for #included files. You will have to go through them visually, but they can be very useful for getting a picture of what is using what.
614,842
614,940
Why does this code corrupt memory?
This is a fairly newbie question which should be answerable reasonably quickly... Basically, after the first call to Printf in echo, the contents of args is corrupted. It sounds to me like i'm passing the pointers around incorrectly. But can't figure out why? #define MAX_PRINT_OUTPUT 4096 void Echo(char *args[MAX_COMMAND_ARGUMENTS], int argCount) { for (int i = 1; i < argCount; ++i) { Printf("%s ", args[i]); Printf("\n"); } }; void Printf(const char *output, ...) { va_list args; char formattedOutput[MAX_PRINT_OUTPUT]; va_start(args, output); vsnprintf(formattedOutput, sizeof(formattedOutput), output, args); va_end(args); g_PlatformDevice->Print(formattedOutput); }; void RiseWindows::Print(const char *output) { //Corruption appears to occur as soon as this function is entered #define CONSOLE_OUTPUT_SIZE 32767 char buffer[CONSOLE_OUTPUT_SIZE]; char *pBuffer = buffer; const char *pOutput = output; int i = 0; while (pOutput[i] && ((pBuffer - buffer) < sizeof(buffer) - 1)) { if (pOutput[i] == '\n' && pOutput[i+1] == '\r' ) { pBuffer[0] = '\r'; pBuffer[1] = '\n'; pBuffer += 2; ++i; } else if (pOutput[i] == '\r') { pBuffer[0] = '\r'; pBuffer[1] = '\n'; pBuffer += 2; } else if (pOutput[i] == '\n') { pBuffer[0] = '\r'; pBuffer[1] = '\n'; pBuffer += 2; } else { *pBuffer = pOutput[i]; ++pBuffer; } ++i; } *pBuffer = 0; SendMessage(this->ConsoleWindow.hwndBuffer, EM_LINESCROLL, 0, 0xffff); SendMessage(this->ConsoleWindow.hwndBuffer, EM_SCROLLCARET, 0, 0); SendMessage(this->ConsoleWindow.hwndBuffer, EM_REPLACESEL, 0, (LPARAM)buffer); }; NOTE This is not production code, just proof of concept. EDIT g_PlatformDevice is of type RiseWindows, if that wasn't clear... EDIT This is on a windows xp platform running under vs2008 UPDATE For anyone interested, the problem appears to have been an overflowed call stack, further down the stack then this another large array was being defined. Refactoring this eliminated the memory corruption. So chalked up to stack battering!
You haven't mentioned what environment this code runs under. It could be you are blowing your stack. You are declaring a 32767 byte array on the stack in RiseWindows::Print. On some embedded system environments that I am familiar with that would be bad news. Can you increase your stack size and/or allocate that buffer on the heap just to test that theory? You may want to make that buffer a std::vector instead, or possibly a private member vector to avoid allocating and reallocating it every time you call Print. Along those lines, how big is MAX_PRINT_OUTPUT?
614,875
615,116
Caching expensive data in C++ - function-scoped statics vs mutable member variables
I've got a relatively expensive data-fetching operation that I want to cache the results of. This operation is called from const methods, roughly like this: double AdjustData(double d, int key) const { double factor = LongRunningOperationToFetchFactor(key); return factor * d; } I'd like AdjustData to remain const, but I want to cache out the factor so I only fetch it the first time. At present I'm using a mutable map<int, double> to store the result (the map being from key to factor), but I'm thinking using a function-scoped static might be a better solution - this factor is only needed by this function, and is irrelevant to the rest of the class. Does that seem like a good way to go? Are there any better options? What things might I think about, particularly with regard to thread-safety. Thanks, Dom
I would wrap the implementation of LongRunningOperationToFetchFactor with something like this. I am using Boost scoped locks but you can so something similar with other locking frameworks. #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <map> using namespace std; static boost::mutex myMutex; static map<int,double> results; double CachedLongRunningOperationToFetchFactor( int key ) { { boost::mutex::scoped_lock lock(myMutex); map<int,double>::iterator iter = results.find(key); if ( iter != results.end() ) { return (*iter).second; } } // not in the Cache calculate it result = LongRunningOperationToFetchFactor( key ); { // we need to lock the map again boost::mutex::scoped_lock lock(myMutex); // it could be that another thread already calculated the result but // map assignment does not care. results[key] = result; } return result; } If this really is a long running operation then the cost of locking the Mutex should be minimal. It was not quite clear from you question but if the function LongRunningOperationToFetchFactor is a member function of you class then you want the map the be mutable map in that same class. I single static mutex for access is still fast enough though.