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 effectiv... | 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 ... |
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 si... | 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 ... |
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 w... | 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-cl... |
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 ex... | 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 g... | 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 interfac... |
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:
Vers... | 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>... |
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 environmen... | 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.
Ple... | 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::utilit... | 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 usi... |
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... | 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,... |
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 ... | 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 a... |
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... | 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 ... |
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... | 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 ... |
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 i... | 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 emp... |
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:... | 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 characte... |
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... | 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 ... |
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 "... | 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:
;----------------------------------------------... | 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 vis... |
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[](ba... | (*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 m... | 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 obje... |
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... | 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... |
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 cal... |
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 ... | 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... |
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 ... | 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 w... |
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 )
... |
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 option... | 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 t... | 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 ... |
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 usin... | 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... | 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 direct... |
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,... | 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... |
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 differe... | 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 wha... |
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 asserti... | 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!"... | 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... |
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... |
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 fig... | 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 respond... |
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... | 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... |
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 ... | 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 ... |
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 ... | 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... |
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 wa... | 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 cor... | 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... |
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 thi... | 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... |
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 ... | 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, d... | 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,
... |
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 ... | 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), ti... | 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 on... |
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... | 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, st... |
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 t... | 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 t... |
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 <... |
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... | 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 c... |
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 i... | 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... |
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 d... | 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... | 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;
... |
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 ... | 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 separatio... |
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(""... | 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 eve... |
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, jus... | 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... |
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 muc... | 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 c... |
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 megabyt... | 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 virtu... |
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... | 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 t... | 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 bi... |
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 usin... |
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 c... |
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( pInterfac... | 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 ... |
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(_visito... | 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 ... |
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... | 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/d... |
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 typ... |
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 cla... | 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;
ch... | 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... |
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 IS... | 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 m... |
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 differen... | 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 BoxHa... |
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 argumen... | 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 o... |
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>
usin... | 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 lan... | 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 wit... |
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 *a... | 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)
{
... | 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 po... |
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 point... | 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 (n... |
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] << ... | 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 ... | 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 p... |
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 <... | 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 consol... |
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 wou... | 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 resu... | 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 r... |
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 coul... | 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... |
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 ... | 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 execut... | 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 functio... | 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... | 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)
{d... | 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();... |
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 prolo... | 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_COMM... | 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 ... |
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,... | 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 myMu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.