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
1,415,779
2,045,189
Why are C++ inheritance mechanisms opaque?
Why, for example, is there no language support to examine a vtable? Why can't I replace a member function with a new one? I have a gut feeling that there are ways to put such features to good use. Are there any other languages out there which allow me to do such things?
The main reason is that keeping vtable as an implementation detail allows any concrete implementation to optimize it as it sees fit; this means that it can e.g. trim or even eliminate vtable altogether if it can prove that there are no virtual calls for a given method (or all methods). Or it may replace a vtable dispat...
1,415,913
1,415,962
Sleep() becomes less accurate after replacing a PC? (C++)
I have a program that was built in C++ (MFC, Visual Studio 6.0) several years ago and has been running on a certain Windows machine for quite some time (more than 5 years). The PC was replaced a month ago (the old one died), and since then the program's timing behavior changed. I need help understanding why. The main f...
The time resolution on XP is around 10ms - the system basically "ticks" every 10ms. Sleep is not a very good way to do accurate timing for that reason. I'm pretty sure win2000 has the same resolution but if I'm wrong that could be a reason. You can change that resolution , atleast down to 1ms - see http://technet.micr...
1,416,009
1,416,071
Get year from boost ptime
I'm converting an existing program to C++ and here need to manipulate Sybase timestamps. These timestamps contain date and time info, which to my knowledge can be best handled by a boost::posix_time::ptime variable. In a few places in the code I need to get the year from the variable. My question is: how can I most eff...
Skip the ostringstream. Otherwise, you may benefit from "using namespace..." #include <boost/date_time/local_time/local_time.hpp> #include <iostream> int main() { using namespace boost::posix_time; std::cout << second_clock::local_time().date().year() << std::endl; return 0; }
1,416,082
1,416,104
Drawing issues with c++
I'm sort of new to c++ and i'm trying to create a game. I have a 2d array RECT_GRID of rectangles. I have a 2d array GRID of unsigned short. I fill the rectangle array during WM_CREATE The WM_PAINT event paints rectangles for all the elements in the array. The color of the rectangle is based on the value of GRID[x][y] ...
My first guess, if you're a total GDI/C++ newbie, is that you are probably creating a lot of Pens and Brushes. These are constrained resources in Windows. You can only create so many of them before you start to tax your resources. So either make your Brushes and Pens and Windows, etc all at once and re-use them, or ...
1,416,094
1,416,187
Revert exception specifications behavior under VC++ 9.0
I'm working on old code that relies heavily on the exception specifications behavior described in the language standard. Namely, calls to std::unexpected() on exception specification violations of the form described below. foo() throw(T) { /*...*/ } Nothrow specifications are indeed guaranteed to not throw, but throw(...
As you mentioned, Visual Studio has an "interesting" way of dealing with exception specifications: throw() has its normal meaning (the function must not throw) anything else (including no exception specification) is interpreted as throw(...) There is no way to circumvent this. However, the C++ community pretty much a...
1,416,096
1,417,002
C++ Debug builds broke in Snow Leopard Xcode
After upgrading to Xcode 3.2 and Snow Leopard, my debug builds are broken and fail at runtime. Stringstreams do not seem to work. They work in Release mode. I've narrowed it down to a combination of GCC 4.2, OSX SDK 10.6 and the _GLIBCXX_DEBUG pre-processor symbol. These are the defaults for new Xcode projects' Debu...
STL debug mode is not supported in gcc 4.2 at this time. You can use gcc 4.0 with STL debug mode, or remove the debug mode preprocessor macros from your Debug configuration and keep using gcc 4.2.
1,416,273
1,424,817
Parse out Non-Alpha Numeric characters from SQLCHAR object
I currently have a bunch of SQLCHAR objects from a database query. The query results are stored in a std::string and then binded to the individual SQLCHAR variables. Some of these variables need to be parsed in order to remove any non-alphanumeric characters. What is the best approach here? I have implemented a basic p...
consider this pseudocode bool is_not_alnum(char c){return !isalnum(c);} unsigned char* s = ()blah_as_sql_char; //somehow its gotta cast to cstr right? std::remove_if(s, strlen(s), is_not_alnum); SQLCHAR result = (SQLCHAR)s; //cast it back however http://www.cplusplus.com/reference/clibrary/cctype/isalnum/ http://www.s...
1,416,345
1,416,382
C++ template specialization of function: "illegal use of explicit template arguments"
The following template specialization code: template<typename T1, typename T2> void spec1() { } Test case 1: template< typename T1> //compile error void spec1<int>() { } Test case 2: template< typename T2> //compile error void spec1<int>() { } generates the following compilation error: error C2768: 'spec1' : ill...
Function templates cannot be partially specialised, only fully, i.e. like that: template<> void spec1<char, int>() { } For why function templates cannot be partially specialised, you may want to read this. When you specialise partially (only possible for classes), you'd have to do it like that: template <typename T1>...
1,416,468
1,416,499
c++ operator overload and usage
bool operator()(Iterator it1, Iterator it2) const { return (*it1 < *it2); } Can someone explain this function for me, thanks! is this means overload the operator ()? after overload this, how to use it ?
It means something like if you have a class called Compare for example: Compare cmp; .... if(cmp(it1, it2)) { std::cout << "First element is greater"; } else { std::cout << "Second element is greater"; } Your object becomes like a function and it is called in C++ world Functor.
1,416,474
1,416,931
How is variant_row implemented in database template library(C++)?
is there anyone have read the source code of dtl in c++? I found there is a class called variant_row, it used to store all kinds of data, and i tried to read the source code, but it is really hard for me, can someone explain how it is implemented and the class struct? Thanks !
Consider investigating the implementation of BOOST.Variant and BOOST.Optional, They are definitions of a general purpose "generic" types. http://www.boost.org/doc/libs/1_40_0/doc/html/variant.html http://www.boost.org/doc/libs/1_40_0/libs/optional/doc/html/index.html
1,416,797
1,418,635
Reference to Lua function in C/C++
I have a functions nested relatively deeply in a set of tables. Is there a way in C/C++ to get a "reference" to that function and push that (and args) onto the stack when I need to use it?
This is what the reference system is for. The function call r = luaL_ref(L, LUA_REGISTRYINDEX) stores the value on the top of the stack in the registry and returns an integer that can be stored on the C side and used to retrieve the value with the function call lua_rawgeti(L, LUA_REGISTRYINDEX, r). See the PiL chapter,...
1,417,061
1,417,881
Automatic increment of build number in Qt Creator
I would like to have a variable (or #define) in C++ source that will increment each time I use Qt Creator to build source code. Is there any way I can do this, perhaps some Qt Creator plugin or similar? If there is a way to do it if I use "make" on command line to build?
In your .pro file, you can create a variable that contains the results of a command-line program. You can then use that to create a define. BUILDNO = $$(command_to_get_the_build_number) DEFINES += BUILD=$${BUILDNO} If you just want a simple incrementing number, you could use a pretty simple script: #!/bin/bash number...
1,417,121
1,417,124
Getting ring 0 mode in C++ (Windows)
How I can get ring 0 operating mode for my process in Windows 7(or Vista)?
Allowing arbitrary code to run in ring 0 violates basic OS security principles. Only the OS kernel and device drivers run in ring 0. If you want to write ring 0 code, write a Windows device driver. This may be helpful. Certain security holes may allow your code to run in ring 0 also, but this isn't portable because the...
1,417,298
1,417,348
How is insert iterator work in c++
there is insert iterator in database template library or other library, Can someone tell me how it work ? Thanks!
It is a template class so you should be able to look it up in the implementation. However, the idea is that it stores an iterator (current location) and a reference (pointer) to a container (that is being inserted in). Then it overloads operator= like this: insert_iterator& operator= (typename Container::const_referenc...
1,417,355
1,417,582
'There is no source code available for the current location.' when throwing an exception in C++ Visual Studio
I have a problem in catching an exception. I am trying to rethrow an exception and I get a message: There is no source code available for the current location. The code is very simple: #include <exception> using namespace std; try { throw exception("Asas"); } catch (const exception& e) { cout<< "Error msg" <<...
Your question is so misleading, it's very hard to give you back anything but more questions. You write you get this message when you're trying to rethrow, but it's very unclear what you mean: Is this a compiler error, a run-time error, or something you get while you're debugging? If the latter (which I assume), why ar...
1,417,473
1,417,598
Call Python from C++
I'm trying to call a function in a Python script from my main C++ program. The python function takes a string as the argument and returns nothing (ok.. 'None'). It works perfectly well (never thought it would be that easy..) as long as the previous call is finished before the function is called again, otherwise there ...
When you say "as long as the previous call is finished before the function is called again", I can only assume that you have multiple threads calling from C++ into Python. The python is not thread safe, so this is going to fail! Read up on the Global Interpreter Lock (GIL) in the Python manual. Perhaps the following ...
1,417,484
1,417,499
Memory and Register panels in Visual Studio 2008 missing
When I still had VS2005 there were a Memory and a Register panel available while debugging C/C++ projects. I think they could be activated from the Debug menu, I'm not sure anymore. The problem is that in VS2008 (Pro) I can't find them nowhere. I thought that it may be some corruption of the program files, but after in...
I've seen something similar, where if you've installed SQL Server first, then you get the "Business Intelligence" configuration of Visual Studio, which is missing a bunch of stuff. Go to Tools / Import and Export Settings... / Reset all settings.
1,417,907
1,417,924
Sizeof in C++ and how to calculate pointer length?
Can someone explain the following code snippet for me? // Bind base object so we can compute offsets // currently only implemented for indexes. template<class DataObj> void BindAsBase(DataObj &rowbuf) { // Attempting to assign working_type first guarantees exception safety. working_type = DTL_TYPEID_NAME (rowbu...
sizeof(rowbuf) returns the length in bytes of an object of type DataObj. Note that rowbuf is no pointer, but it is a reference which is quite a difference. If you want to calculate the size of y DataObj pointer use sizeof(&rowbuf) or sizeof(DataObj*).
1,418,015
1,418,703
How to get Python exception text
I want to embed python in my C++ application. I'm using Boost library - great tool. But i have one problem. If python function throws an exception, i want to catch it and print error in my application or get some detailed information like line number in python script that caused error. How can i do it? I can't find an...
Well, I found out how to do it. Without boost (only error message, because code to extract info from traceback is too heavy to post it here): PyObject *ptype, *pvalue, *ptraceback; PyErr_Fetch(&ptype, &pvalue, &ptraceback); //pvalue contains error message //ptraceback contains stack snapshot and many other information ...
1,418,019
1,418,055
Casting pointer as template argument: Comeau & MSVC compile, GCC fails
Consider the following code: template<int* a> class base {}; int main() { base<(int*)0> test; return 0; } Both Comeau and MSVC compile this without issues (except for Comeau warning about an unused variable), while GCC fails on the base<(int*)0> test; line, stating In function `int main()': a casts to a t...
From a draft standard (emphasis added): 14.1.3 A non-type template-parameter shall have one of the following (option- ally cv-qualified) types: ... --pointer to object, accepting an address constant expression desig- nating a named object with external linkage, ... Apparently, it's not legal to instanti...
1,418,036
1,418,247
C++ implicit function calls
Will c++ implicit function calls be a feature of C++0x ? It is an interesting feature, but I haven't seen any progress on this and the GCC C++0x page didn't even mention it. See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1611.pdf
No they will not be included in the next standard update to C++ (C++0x). The idea of implicit function calls (informally: use of a niladic function name in an expression evaluates to a function call instead of decaying to its address) is interesting, and it wasn't dismissed by the committee as a bad idea. It was clas...
1,418,068
1,418,152
What are the operations supported by raw pointer and function pointer in C/C++?
What are all operations supported by function pointer differs from raw pointer? Is > , < , <= , >=operators supported by raw pointers if so what is the use?
For both function and object pointers, they compile but their result is only guaranteed to be consistent for addresses to sub-objects of the same complete object (you may compare the addresses of two members of a class or array) and if you compare a function or object against itself. Using std::less<>, std::greater<> a...
1,418,125
18,652,863
Eclipse CDT generated getters / setters name
Is there a way (either via the UI, or in config files) to change the names of the C++ getters/setters generated by Eclipse CDT from the Java-style getSomething() to the more C++ like something() ?
It's now possible via the following menu:
1,418,141
1,418,299
C++ error when opening file
when I try to open a file for reading in my console application i get this error message: "Unhandled exception at 0x1048766d (msvcp90d.dll) in homework1.exe: 0xC0000005: Access violation writing location 0x00000000." It works fine when I compile and run the program on my macbook but when I run it on my desktop using V...
If you want to check if the file is open or not, don't use fin.bad() instead: while( !fin.is_open() ) { ... }
1,418,225
1,418,397
In the Visual Studio debugger, what does {null=???} mean?
I was debugging a C++ program in VS 2003, and a boost variable showed up as having the value {null=???}. What does that mean?
Typically when you see ??? in the C++ debugger, it means the underlying expression evaluator had problems accessing the memory for the particular expression. So it's likely the value points to invalid or inaccessible memory. It's also possible that this session is using an autoexp.dat file and it points to a member th...
1,418,399
1,418,727
Gradient Brush in Native C++?
In c#, you can use drawing2d.lineargradientbrush, but in c++ right now I only found the CreateSolidBrush function. Is there a function in the native gdi dll to create a gradient brush? I couldn't find anything like this at msdn. Thanks
To draw a vertical gradient: void VerticalGradient(HDC hDC, const RECT& GradientFill, COLORREF rgbTop, COLORREF rgbBottom) { GRADIENT_RECT gradientRect = { 0, 1 }; TRIVERTEX triVertext[ 2 ] = { GradientFill.left - 1, GradientFill.top - 1, GetRValue(rgbTop) << 8, ...
1,418,476
1,418,520
BHO Handle OnSubmit event
Basically I want to develop a BHO that validates certain fields on a form and auto-places disposable e-mails in the appropriate fields (more for my own knowledge). So in the DOCUMENTCOMPLETE event I have this: for(long i = 0; i < *len; i++) { VARIANT* name = new VARIANT(); name->vt = VT_I4; name->intVal = i...
Once you have the pointer to the element you want to sink events for, you would QueryInterface() it for IConnectionPointContainer and then connect to that: REFIID riid = DIID_HTMLFormElementEvents2; CComPtr<IConnectionPointContainer> spcpc; HRESULT hr = form->QueryInterface(IID_IConnectionPointContainer, (void**)&spcpc...
1,418,756
1,418,783
How to use bind1st and bind2nd?
I would like to learn how to use binding functions. Here is the idea: I have this function which takes to parameters: void print_i(int t, std::string separator) { std::cout << t << separator; } And I would like to do: std::vector<int> elements; // ... for_each(elements.begin(), elements.end(), std::bind2nd(pri...
The argument to bind2nd must be an AdaptableBinaryFunction. A plain binary function does not fulfill this requirement (an adaptable function required typedefs for its return and argument types, a plain function type does not provide any typedefs). You could use std::bind which is probably the better choice anyway.
1,418,831
1,420,944
C++ 2D tessellation library?
I've got some convex polygons stored as an STL vector of points (more or less). I want to tessellate them really quickly, preferably into fairly evenly sized pieces, and with no "slivers". I'm going to use it to explode some objects into little pieces. Does anyone know of a nice library to tessellate polygons (partiti...
CGAL has packages to solve this problem. The best would be probably to use the 2D Polygon Partitioning package. For example you could generate y-monotone partition of a polygon (works for non-convex polygons, as well) and you would get something like this: The runnning time is O(n log n). In terms of ease of use this...
1,418,965
1,434,328
C++ Executable distribution strategy
Recently I have asked a question about what I should use to create self-contained executables that would be deployed under a number of Linux distribution. I got very scared at first, but after reading about C++ a little, I managed to get the first version of my executable going. After a day full of joy, I just hit the ...
You might give this technique a try.
1,419,099
1,420,198
Reading/writing QObjects
I think I can write a QObject like this by taking advantage of the Q_PROPERTYs: QDataStream &operator<<(QDataStream &ds, const Object &obj) { for(int i=0; i<obj.metaObject()->propertyCount(); ++i) { if(obj.metaObject()->property(i).isStored(&obj)) { ds << obj.metaObject()->property(i).read(&obj)...
This seems to work. QDataStream &operator>>(QDataStream &ds, Object &obj) { QVariant var; for(int i=0; i<obj.metaObject()->propertyCount(); ++i) { if(obj.metaObject()->property(i).isStored(&obj)) { ds >> var; obj.metaObject()->property(i).write(&obj, var); } } ret...
1,419,169
1,419,201
std::string::assign() causes segfault
I have a std::vector<uint8_t> that contains strings at specific offsets. Here's a shortened dump: ... @128 00 00 00 00 00 00 00 00 73 6F 6D 65 74 68 69 33 ........somethin @144 38 36 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ng.............. @160 00 00 00 00 00 00 00 00 31 2E 32 2E 33 00 00 00 ........1.2.3......
There is likely a mismatched free/delete somewhere else in your code that is delaying the symptom until now. When you use freed memory, the operating system is free to continue as long as it sees fit. Try running the program in valgrind. valgrind uses its own malloc and free so it can alert you to incorrect news and de...
1,419,186
1,419,833
Troubles at Including (Linking) a static library inside another one
I'll try to explain shortly what I want to do: A project using a static library which have another one as depandency. It produce a project called MyProject linking on MyLib1 linking on MyLib2. Here is the compile order: MyLib2 MyLib1 (linking to MyLib2) MyProject (linking to MyLib1) I'm using Visual Studio 2008 and I...
First, never include *.cpp files. Second, use forward declaration of your external functions: void appellib2(void); void appellib1(void) { appellib2(); } Third, right-click each project in the Solution Explorer, and select "Project dependencies..." and set-up proper dependencies: MyProject -> MyLib1 -> MyLib2. At...
1,419,314
1,419,557
A confusion about parallel_accumulate in C++ Concurrency in action
In the following example (Chapter 2), Anthony Williams is trying to parallelize the standard accumulate function. my question is why is he doing this: unsigned long const max_threads=(length+min_per_thread-1)/min_per_thread; why add length and subtract 1? why not just: unsigned long const max_threads=length/mi...
The problem with using unsigned long const max_threads=length/min_per_thread; is caused by the truncation rounding used during integer division if length = 7 min_per_thread = 5 then max_threads = length / min_per_thread = 1 while max threads should actually be 2 length + min_per_thread - 1 = 11 max_threads = (le...
1,419,342
1,419,513
C++: How to localize an already-written program
I want to localize a program I already written.. It's fairly big (almost 50k lines) and ideally I want a system that allows me (the programmer) to do the least amount of work possible, and without major changes to the program - if possible none at all. I looked at gettext() and liked it a lot, but it's unclear to me ho...
After a lot of playing around with gettext() and xgettext I think I found a way myself (sorry onebyone but I didn't like your approach.. There must be hundreds of arrays like that and I would have to import all of them in main(), that's a lot of extern and a lot of extra work :/). Anyways, this is how I think it can th...
1,419,449
1,419,453
Piping to process with c++
I have finally worked out how to get stdin and stdout to pipe between the main app and a process created with CreateProcess (win32) or exec (linux). Now I am interested in harnessing the piping nature of an app. The app I am running can be piped into: eg: cat file.txt | grep "a" If I want to run "grep", sending the ...
Yes, that's exactly what you do: read from stdin and write to stdout. One of the strokes of genius behind linux is the simplicity of redirecting input and output almost effortlessly, as long as your apps obey some very simple, basic rules. For example: send data to stdout and errors or informational messages to stderr...
1,419,463
1,419,504
Forward typedef declarations, effect on build times, and naming conventions
I am curious about the impact my typedef approach has on my builds. Please consider the following example. #include "SomeClass.h" class Foo { typedef SomeClass SomeOtherName; SomeOtherName* storedPointer; void setStoredPointer(SomeOtherName* s); } void Foo::setStoredPointer(SomeOtherName* s) { store...
Would typedef class SomeClass SomeOtherName; do the trick for you? With that, the compilation unit that's using the typedef only for pointers or references doesn't need to #include the SomeClass header.
1,419,581
1,419,628
How to access most frequently used programs in OS and most recent files of programs programmatically?
I need to gain access to the list of most recently used programs and list of recently opened files in Windows OS programatically. These are the items you generally see once you click start in windows. I am looking to use C# but if its better in Managed C++ I will do that too.
I think for files you can access recent directory. string folderName = Environment.GetFolderPath (Environment.SpecialFolder.Recent); DirectoryInfo recentFolder=new DirectoryInfo(folderName); FileInfo[] files=recentFolder.GetFiles();
1,419,681
1,419,925
Boost Library, how to get determinant from lu_factorize()?
I am trying to calculate a determinant using the boost c++ libraries. I found the code for the function InvertMatrix() which I have copied below. Every time I calculate this inverse, I want the determinant as well. I have a good idea how to calculate, by multiplying down the diagonal of the U matrix from the LU deco...
The permutation matrix pm contains the information you'll need to determine the sign change: you'll want to multiply your determinant by the determinant of the permutation matrix. Perusing the source file lu.hpp we find a function called swap_rows which tells how to apply a permutation matrix to a matrix. It's easily ...
1,419,883
1,424,514
How to prevent Flikkering on picturebox of windows mobile
I have a transparent rectangle on a picture box,if i click next,the next image comes and transparent rectangle is drawn.The problem is flickering,while moving from one image to another image,the transparent rectangle flickers.please help me how to get rid of this problem.i want to eliminate flicker,please help. Thanks
How are you implementing it? I had a similar problem and implemented my own picturebox by inheriting from Control, overriding OnPaint to draw my image and transparent background etc, and also overriding OnPaintBackground and doing nothing. (The default behaviour of OnPaintBackground is to paint the background of the co...
1,419,963
1,419,983
does C++ automatically cast const ints to floats?
I am aware that casting ints to floats (and vice versa) is fairly expensive. However, does the compiler automatically do it at compile time for constants in your code? For e.g. is there any difference between float y = 123; float x = 1 / y; and float y = 123.f; float x = 1.f / y; I see some code that does the latter,...
Yes, the compiler will do the conversion automatically. Your two blocks of code are identical. It is not an optimization. Turning off optimization won't make the compiler include the int-to-float conversion in the executable code, unless it's a very poor-quality implementation. It's not for safety, either. The compiler...
1,420,009
1,420,072
I don't get this C/C++ Joke
After reading this article on thedailywtf.com, I'm not sure that I really got the joke. It says there that some guy changed the code from int function() { int x; char data_string[15]; ... x = 2; strcpy(data_string,"data data data"); ... } to int function() { int x = 2; char data_string[15] = "data d...
Depending on the compiler and compiler options, initialization like this char data_string[15] = "data data data"; results in a lot of move instructions to copy the literal data to stack. Calling strcpy requires less instructions. Doing this kind of thing all over a large codebase can increase the binary size significa...
1,420,029
1,420,100
How to break out of a loop from inside a switch?
I'm writing some code that looks like this: while(true) { switch(msg->state) { case MSGTYPE: // ... break; // ... more stuff ... case DONE: break; // **HERE, I want to break out of the loop itself** } } Is there any direct way to do that? I know I can use a flag, and break from the...
Premise The following code should be considered bad form, regardless of language or desired functionality: while( true ) { } Supporting Arguments The while( true ) loop is poor form because it: Breaks the implied contract of a while loop. The while loop declaration should explicitly state the only exit condition. I...
1,420,044
1,428,407
Generically reading a well-formed binary file
I'm trying to read contents of a game's map/model files into a program for the purposes of writing a small model viewer and testing out some DirectX features. The model/map file formats are chunked in nature, and I know the format of these files. I can easily read the files by parsing through the individual chunks, usi...
These kind of rules are easily coded using a finite-state machine. Each chunk should change the state you are in. Each state waiting for specific chunks afterwards. If you encounter a chunk that you should not encounter in the current, that's an error.
1,420,145
1,420,740
visiting all free slots in a bitfield
I have an array of uint64 and for all unset bits (0s), I do some evaluations. The evaluations are not terribly expensive, but very few bits are unset. Profiling says that I spend a lot of time in the finding-the-next-unset-bit logic. Is there a faster way (on a Core2duo)? My current code can skip lots of high 1s: for...
Here's a quick micro-benchmark; please run it if you can to get stats for your system, and please add your own algorithms! The commandline: g++ -o bit_twiddle_mirco_opt bit_twiddle_mirco_opt.cpp -O9 -fomit-frame-pointer -DNDEBUG -march=native And the code: #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #...
1,420,234
1,420,248
Converting C++ function to Delphi: what to do with void* parameter?
I'm writing a DLL in Delphi using the below C++ example: USERDLL_API double process_message (const char* pmessage, const void* param) { if (pmessage==NULL) { return 0; } if (param==NULL) { return 0; } if (strcmp(pmessage,"state")==0) { current_state *state = (current_state*) param; r...
function process_message (const pmessage: PChar; const param: Pointer): Double; export; stdcall; begin If (pmessage = nil) Or (param = nil) Then Result := 0; Else If StrComp(pmessage, 'state') = 0 Then Result := process_state(current_state^(param)); // missing a return statement for cases wh...
1,420,280
1,420,285
Returning pointers in functions
Is the following code legal? char* randomMethod1() { char* ret = "hello"; return ret; } And this one? char* randomMethod2() { char* ret = new char[10]; for (int i = 0; i < 9; ++i) { ret[i] = (char)(65 + i); } ret[9] = '\0'; return ret; } I'd say the first one is legal, as you ar...
Both are legal. In the second one, you are not allocating memory from the stack. You are using new, and it allocates memory from the heap. If you don't free the pointer returned from the second method using delete, you'll have a memory leak. By the way, stack-allocated arrays are declared like this: char x[10]; // Note...
1,420,354
1,420,379
making a object equal to another object
i know you can make two objects equal to each other when one of them is being declared. i tested this in my program. but when i went to use a assignment statement it freaked out. Can you make two objects equal to each other with a assignment statement or can you only do that when one object is being declared?
You have provide operator= to a class so as copy the contents of another object. For example: class A { public: //Default constructor A(); //Copy constructor A(const A&); //Assignment operator A& operator=(const A& a); }; int main() { A a; //Invokes default constructor A b(a); //Invokes cop...
1,420,515
1,433,858
Causes for ILINK32 Error: Unresolved external '__fastcall System::TObject::NewInstance(System::TMetaClass *)' referenced from XXX.obj?
I am getting the following error from C++ Builder 2009's linker Unresolved external '__fastcall System::TObject::NewInstance(System::TMetaClass *)' referenced from XXX.obj? We have a set of Delphi files (.pas) and set of C++ Builder files (.hpp and .obj), which was generated from these .pas files. Set of files is copi...
OKay, I've found answer: the reason was some wrong IDE's or project's settings (I do not know for sure). I have several versions of C++ Builders and Delphis installed. And for some reason C++ Builder's 2009 linker picked up wrong obj files - the ones, which should be used for another version (possible 2007). The reaso...
1,420,546
1,420,554
Does C or C++ have a standard regex library?
Does it? If yes, where can I get the documentation for it... if not, then which would be the best alternative?
C++11 now finally does have a standard regex library - std::regex. If you do not have access to a C++11 implementation, a good alternative could be boost regex. It isn't completely equivalent to std::regex (e.g. the "empty()" method is not in the std::regex) but it's a very mature regex implementation for C++ none the...
1,420,552
1,420,564
What's the difference between virtual function instantiations in C++?
What's the difference between the following two declarations? virtual void calculateBase() = 0; virtual void calculateBase(); I read the first one (=0) is a "pure abstract function" but what does that make the second one?
First one is called a pure virtual function. Normally pure virtual functions will not have any implementation and you can not create a instance of a class containing a pure virtual function. Second one is a virtual function (i.e. a 'normal' virtual function). A class provides the implementation for this function, but i...
1,420,602
1,420,821
Compiling JVMTI agent (using GCC, on OSX Snow Leopard)
I am trying to build a JVMTI agent using the g++ command on Snow Leopard and I get the following error: $ g++ -o agent.so -I `/usr/libexec/java_home`/include agent.cpp Undefined symbols: "_main", referenced from: start in crt1.10.6.o ld: symbol(s) not found collect2: ld returned 1 exit status I am a total novice when...
The command line options you've supplied to g++ are telling it that you're trying to build an executable, not a shared library. g++ is complaining that you haven't defined a main function, as every executable requires one. Compile your shared library with the -c flag so that g++ knows to build a library, i.e. compile ...
1,420,825
1,420,967
Windows Mobile/C: Wait until variable changes
I'm currently writing a wrapper library for windows mobile in C/C++. I have to implement and export the following functions: void start_scanning(); int wait_for_scanning_result(); void stop_scanning(); start_scanning() is called to start the scanning process. wait_for_scanning_result() will wait until a result is avai...
You can use windows Synchronization Functions. Basically all you have to do is: * CreateEvent - create an event * WaitForSingleObject - wait for this event to become signaled * SetEvent - signal the event
1,420,972
1,421,025
Accessing an array with a negative number!
I am converting an extremely large and very old (25 years!) program from C to C++. In it there are many (very very many) places where I access a global one dimensional UBYTE array using a variety of integer indexes. Occasionally this index may be negative. I sometimes, but not always, trapped this case and made sure no...
Can you replace the global one-dimensional ubyte array with an object with overloaded operator[]? Using the absolute value of the int input might solve some of your issues. Edit: Depending on the usage pattern of your array (no pointer shenanigans), using an object with overloaded operator[] could actually be entirely...
1,421,277
1,421,522
How do you design a C++ application so that Mock Objects are easiest to use?
I've never developed using Test Driven Development, and I've never used Mock Objects for unit testing. I've always unit tested simple objects that don't incorporate other aspects of the application, and then moved on to less simple objects that only reference objects that have already been unit tested. This tends to p...
You could look to adapt your code to follow an (Abstract) Factory Design pattern, whereby a different factory could be used in a unit test environment that would create your mock objects.
1,421,367
1,431,430
Does the isSelect-method of QSqlQuery return true when a stored procedure is executed?
Will the isSelect-method of QSqlQuery return true when a stored procedure containing a SELECT-statment is executed on sqlserver?
The documentation states that isSelect: "Returns true if the current query is a SELECT statement; otherwise returns false" During my testing I found that it also returns true for an EXEC statement on sqlserver if there is a result-set to be fetched.
1,421,485
1,421,497
template class, implementation code causing linking issues
I currently have a program where my main code is in a file main.cpp. Main.cpp includes a header file "class.h" that declares a class that is used within main.cpp. Also in main.cpp I have function declarations that declare the functions I use within main.cpp. The code for these functions is in a separate .cpp file fucnt...
You could keep the template functions inside the template<> class what{/HERE/}; template<typename T> class MyTempClass{ void myFunctions{ // code here } } EDITED: I removed the code corrected by Glen
1,421,487
1,421,511
DirectX 9 or 10 Overlay
How is it possible to draw an overlay over an game with DirectX 9 or 10? I found code with deprecated DirectShow code, but it will not run.
If this is what you have already found then ignore it, but try this: Direct3D Hooking Example
1,421,658
30,828,487
Qt Creator: “XYZ does not name a type”
This is a very frustrating error message in Qt Creator: ’XYZ’ does not name a type. This usually means that there is an error in the class XYZ that prevents the compiler from generating the type, but there are no additional hints as to what went wrong. Any suggestions?
I found this problem on qtcreator 3.4.1 and QT 5.4, when I replace such as #include <QTextEdit> with class QTextEdit; this problem gone.
1,421,666
1,421,730
Qt Creator: “inline function used but never defined” – why?
Why am I getting this warning in Qt Creator: ` inline function ‘bool Lion::growl ()’ used but never defined? I double-checked my code, and have a declaration inline bool growl () in Lion (lion.h) and the corresponding implementation in lion.cpp: inline bool Lion::growl () What’s going on? EDIT: My assumption has been...
Well, I don't know the exact problem, but for starters: Inline methods are supposed to be implemented in the header file. The compiler needs to know the code to actually inline it. Also using the "inline" keyword in the class declaration doesn't have any effect. But it cannot hurt either. See also: c++ faq lite
1,421,668
1,421,678
C++ tutorial for experienced C programmer
I have been programming exclusively in C for 25 years but have never used C++. I now need to learn the basics of C++ programming. Can anyone recommend an online tutorial (or failing that a book) that would be most suitable for me. Thanks. Edit: I actually needed the C++ purely for the purposes of adding a couple of dir...
This might be of some use: C++ tutorial for C users. If you're looking for a book, check out "C++ for C Programmers" by Ira Pohl (Amazon).
1,421,671
1,421,780
When are static C++ class members initialized?
There appears to be no easy answer to this, but are there any assumptions that can be safely made about when a static class field can be accessed? EDIT: The only safe assumption seems to be that all statics are initialized before the program commences (call to main). So, as long as I don't reference statics from other...
The standard guarantees two things - that objects defined in the same translation unit (usually it means .cpp file) are initialized in order of their definitions (not declarations): 3.6.2 The storage for objects with static storage duration (basic.stc.static) shall be zero-initialized (dcl.init) before any other initi...
1,421,684
1,421,835
Converting float to double
How expensive is the conversion of a float to a double? Is it as trivial as an int to long conversion? EDIT: I'm assuming a platform where where float is 4 bytes and double is 8 bytes
Platform considerations This depends on platform used for float computation. With x87 FPU the conversion is free, as the register content is the same - the only price you may sometimes pay is the memory traffic, but in many cases there is even no traffic, as you can simply use the value without any conversion. x87 is a...
1,421,697
1,421,768
C# running faster than C++?
A friend and I have written an encryption module and we want to port it to multiple languages so that it's not platform specific encryption. Originally written in C#, I've ported it into C++ and Java. C# and Java will both encrypt at about 40 MB/s, but C++ will only encrypt at about 20 MB/s. Why is C++ running this muc...
Without source code it's difficult to say anything about the performance of your encryption algorithm/program. I reckon though that you made a "mistake" while porting it to C++, meaning that you used it in a inefficient way (e.g. lots of copying of objects happens). Maybe you also used VC 6, whereas VC 9 would/could pr...
1,422,056
1,422,184
Weird behaviour of Koenig Lookup
consider the following program: namespace NS2 { class base { }; template<typename T> int size(T& t) { std::cout << "size NS2 called!" << std::endl; return sizeof(t); } }; namespace NS1 { class X : NS2::base { }; } namespace NS3 { template<typen...
Template arguments and base classes both affect ADL, so I think GCC is correct, here: NS3 comes from the current scope, NS1 from the X template argument, and NS2 from the base class of the template argument. You have to disambiguate somehow; I'd suggest renaming one or more of the functions, if feasible, or perhaps use...
1,422,064
1,422,077
In C++, how can I hold a list of an abstract class?
I have two implemented classes: class DCCmd : public DCMessage class DCReply : public DCMessage Both are protocol messages that are sent and received both ways. Now in the protocol implementation I'd need to make a message queue, but with DCMessage being abstract it won't let me do something like this: class ...
You cannot instantiate the object because it is abstract as you said. You can however hold a vector of pointers to the DCMessage class which will work, you just need to add the memory address and not the object when pushing it on to the list. vector<DCMessage*> queue; DCCmd* commandObject = new DCCmd(...params...); qu...
1,422,144
1,428,607
Designing a better API?
What are the best practices and patterns to be followed for designing APIs? How to achieve implementation hiding the best way (C++/Java)? Designing APIs which are generic in nature? Any reference books/links which guide with neat examples to beginners?
This might be useful for you. The Little Manual of API Design (wayback machine) The Little Manual of API Design (original; dead)
1,422,145
1,422,255
How should I organize test cases in my project?
I have a project that looks like this: xdc/ hubactions/ hubconnection.cpp hubconnection.h uiinterface/ readme uiconnection.cpp uiconnection.h ... uiactions/ readme connectaction.cpp connectaction.h quitaction.cpp quitaction.h ... utils/ parser.cpp parser....
I like the code structure followed by the Apache Software Foundation (ASF) and its primary build tool, Maven. This structure is Java-centric, but can be applied to other languages. The best C++ plug-in for Maven, in my opinion, follows the ASF structure for C++ and looks like this: project/ /src /main /incl...
1,422,151
1,422,234
How to print a double with a comma
In C++ I've got a float/double variable. When I print this with for example cout the resulting string is period-delimited. cout << 3.1415 << endl $> 3.1415 Is there an easy way to force the double to be printed with a comma? cout << 3.1415 << endl $> 3,1415
imbue() cout with a locale whose numpunct facet's decimal_point() member function returns a comma. Obtaining such a locale can be done in several ways. You could use a named locale available on your system (std::locale("fr"), perhaps). Alternatively, you could derive your own numpuct, implement the do_decimal_point() m...
1,422,228
1,422,517
any good method to insert a control just like excel into MFC/c++ program?
I need a excel-like grid control in MFC, do anyone have good suggestion to implement that ?] with the control i can filter the data by clicking on the header, then it will display distinct data of current column for selection. Thanks!
Codeproject's MFC Grid control is very popular for this task. You will have to hack it to your own needs. For filtering and other more advanced features you might consider buying BCGSuite for MFC. Here is what they say about their Grid Control: MFC Document/View integration Integrated Field Chooser In-place cell edit...
1,422,402
1,425,974
What Are Binding Generators For?
A friend raised this on Twitter: @name_removed doesn't understand why binding generators seem to think writing pages of XML is vastly superior to writing pages of C++... Having never encountered binding generators before, I decided to look them up. Seems pretty self-explanatory, convert C++ classes to XML format. But n...
Several reasons: You focus in writing the protocol itself, not parsers. Writing parsing code is tedious, error prone work, and most of the code is boiler plate code anyway. If you have the protocol specified as XML, you can have the server written in one language and the client in another. In this way you can generate...
1,422,425
1,422,449
Need help allocating space for vector within class definition using boost
I am trying to allocate space for a boost vector type in a class definition. I am not a good c++ programmer, but shown below is my best attempt. There are no error messages, but when I try to access the vector from my main function it believes that the vector has zero elements. I know this is because I did not tell ...
In your constructor you are creating a local variable lam that shadows the class variable lam. You want to initialize the vector in the constructor's initialization list: Phase() : lam(2) { for(int i = 0; i < 2; i++) { lam(i) = 1.0; } } This calls the vector constructor you want as the class is being initialized,...
1,422,433
1,422,783
How do you set system time using C/C++?
I have an embedded system (ARM 9263) running an RTOS, IAR tools. The system supports the standard time() function which gives me the current time. I need the reverse call, that is I need to set the time - is there a "C" standard way to do this? I've googled around, sure thought it would be obvious, but perhaps it is pl...
Using the IAR toolset the time of day C runtime API (time()) can be overridden using the example in ARM\src\lib\time.c. The default routine always returns -1, an indication that the CRT has no idea what time it is. Once you provide your own implementation of time(), which will obtain the time of day from a source tha...
1,422,601
1,422,653
How do I turn on multi-CPU/Core C++ compiles in the Visual Studio IDE (2008)?
I have a Visual Studio 2008 C++ project that has support for using multiple CPUs/cores when compiling. In the VCPROJ file I see this: <Tool Name="VCCLCompilerTool" AdditionalOptions="/MP" ... I can't find where that was turned added via the IDE and I want to set up another project that uses all of my core...
To enable /MP option you could add it to Project Settings->C/C++->Command Line|Additional options. This is the only way to switch it on in vcproj.
1,422,817
1,422,854
How to read a float from binary file in C?
Everything I'm finding via google is garbage... Note that I want the answer in C, however if you supplement your answer with a C++ solution as well then you get bonus points! I just want to be able to read some floats into an array from a binary file EDIT: Yes I know about Endian-ness... and no I don't care how it was ...
How you have to read the floats from the file completely depends on how the values were saved there in the first place. One common way could be: void writefloat(float v, FILE *f) { fwrite((void*)(&v), sizeof(v), 1, f); } float readfloat(FILE *f) { float v; fread((void*)(&v), sizeof(v), 1, f); return v; }
1,423,031
1,423,044
How do I write to shared memory in C++?
I'd like to write to shared memory and then dump the contents to a file in the win32 api. Currently I have this code: HANDLE hFile, hMapFile; LPVOID lpMapAddress; hFile = CreateFile("input.map", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); hMapFile = CreateFile...
In the sprintf(MapViewOfFile, "<output 1>"); line, you wanted lpMapAddress, not MapViewOfFile. Or (char*)lpMapAddress to be precise.
1,423,251
1,424,893
talking between python tcp server and a c++ client
I am having an issue trying to communicate between a python TCP server and a c++ TCP client. After the first call, which works fine, the subsequent calls cause issues. As far as WinSock is concerned, the send() function worked properly, it returns the proper length and WSAGetLastError() does not return anything of sig...
client sends a PSH,ACK and then the server sends a PSH,ACK and a FIN,PSH,ACK There is a FIN, so could it be that the Python version of your server is closing the connection immediately after the initial read? If you are not explicitly closing the server's socket, it's probable that the server's remote socket vari...
1,423,297
1,423,387
Printing the contents of a file using the #include directive (preprocessor)
Say I have a file, t.txt, that contains the following two lines: one two Now, I would like to write a program which will #include that file somehow and print its contents, nothing more. That is, I want the contents of that file to appear in my code as a static text, at compile time. Any ideas? The reason im askin...
Alternative solution (since the original one won't work without limitations, as mentioned in the comments): As part of your build process, use a script (perl or python would do it easily) to generate staticstring.h from staticstring.txt, adding quotes and \n's as necessary, then use the other solution. This way your or...
1,423,357
1,423,382
Writing to shared memory
How can I write from a file to shared memory using the Win32 API? I have this code: hFile = CreateFile("input.map", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); hMapFile = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, TEXT("SharedObject"...
Is this the entire code sample? It looks to me like the call to sprintf places a null-terminated string at lpMapAddress, which effectively overwrites whatever you read from the file--at least for the purposes of your printf statement. If you want to replace the first part of what you read with the string "<output 1>", ...
1,423,489
1,423,546
Is there a caching penalty for mixing binary data and instructions within close proximity of each other?
I'm procedurally generating 128-byte blocks with some set n-byte header reserved for machine-language functions that I'm simply calling via in-line assembly. They aren't defined anywhere and are generated at run-time into pages allocated into memory with access for execution. However, I want to reserve the end (128 -...
There will be some penalty since the blocks will be loaded into both the L1 instruction and data caches, which will waste space. The amount of space wasted depends on the size of a cache block, but it probably won't be offset by the savings of a reduced instruction size. L2 caches and below are usually shared between i...
1,423,560
1,423,845
How do I use basic_filebuf with element type other than char?
Say I want to read the contents of a file using basic_filebuf. I have a type called boost::uintmax_t which has a size of 8 bytes. I am trying to write the following: typedef basic_filebuf<uintmax_t> file; typedef istreambuf_iterator<uintmax_t> ifile; file f; vector<uintmax_t> data, buf(2); f.open("test.txt", std::ios...
A basic_filebuf deals with an "internal" char type and an "external" one. The "external" one is the contents of the file, and is always bytes. The "internal" one is the template parameter, and is the one used in its interface with the program. To convert between the two, basic_filebuf uses the codecvt facet of its loca...
1,423,566
1,423,681
Template Type Conversion
I'm building a matrix template. There are operators, functions and all work fine. Except when I try to convert a double type matrix to int type matrix (or vice versa). = operator cannot be defined so its not possible to override it for basic_Matrix2D and basic_Matrix2D external to class. I know I can write in class = o...
Your question is very unclear, but theres nothing wrong with making the operator= something like this: // incomplete, but you get the idea template<class U> basic_Matrix2D<T> & operator=(const basic_Matrix2D<U> &x) { rows = x.rows; cols = x.cols; data = new T[rows * cols]; for (size_t i = 0; i < rows * ...
1,423,696
1,423,708
How to initialize a const field in constructor?
Imagine I have a C++ class Foo and a class Bar which has to be created with a constructor in which a Foo pointer is passed, and this pointer is meant to remain immutable in the Bar instance lifecycle. What is the correct way of doing it? In fact, I thought I could write like the code below but it does not compile.. c...
You need to do it in an initializer list: Bar(Foo* _foo) : foo(_foo) { } (Note that I renamed the incoming variable to avoid confusion.)
1,423,739
1,471,891
Waiting for a DBus service to be available in Qt
With a Qt DBus proxy built on QDbusAbstractInterface (via qdbusxml2cpp), what's the best way to handle the service/object you want to interface to not being available when you start? Note: I'm not interested in simply knowing it (you can use BlahService.isValid() to find that out); I want to be able to know if it's va...
Ok, since no one answered, I've found the answer in the meantime: You want to watch NameOwnerChanged: // subscribe to notifications about when a service is registered/unregistered connect(QDBusConnection::sessionBus().interface(), SIGNAL(serviceOwnerChanged(QString,QString,QString)), this,SLOT(...
1,423,786
1,423,808
What is the difference between declaring and defining a structure?
struct { char a; int b; } x; Why would one define a struct like that instead of just declaring it as: struct x { char a; int b; };
In the first case, only variable x can be of that type -- strictly, if you defined another structure y with the same body, it would be a different type. So you use it when you won't ever need any other variables of the same type. Note that you cannot cast things to that type, declare or define functions with prototyp...
1,424,177
1,424,346
Using GCC through Xcode to compile basic programs
So, I'm a brand new CS student, on a Mac, and I'm learning C++ for one of my classes. And I have a dumb question about how to compile my super basic C++ program. I installed Xcode, and I'm looking through the documentation to try and figure out how to use it (and I highly suspect it's extremely overpowered for what I'...
If XCode is installed then everything is set up correctly. If you typed gcc on the command line then you invoked the 'C' compiler (not the C++ compiler). Usually this does not matter as GCC compensates by looking at the file extension. But what does matter is that it does not invoke the linker with the correct C++ flag...
1,424,239
1,425,111
Static array of const pointers to overloaded, templatized member function
Static array initialization... with const pointers... to overloaded, templatized member functions. Is there a way it can be done (C++03 standard code)? I mean, if I have the template class template <class T1, class U1, typename R1> class Some_class { public: typedef T1 T; typedef U1 U; typedef R1 R; ...
To use BOOST_PP_ENUM in the way that you've shown, you would need a macro that takes a 'number' and yields an expression that is the address of an appropriate member of the appropriate class. I don't see a good way to do this without an explicit list unless the desired functions all have manufactured names (e.g. memfun...
1,424,261
1,424,314
Conditional operator can't resolve overloaded member function pointers
I'm having a minor issue dealing with pointers to overloaded member functions in C++. The following code compiles fine: class Foo { public: float X() const; void X(const float x); float Y() const; void Y(const float y); }; void (Foo::*func)(const float) = &Foo::X; But this doesn't compile (the compile...
From section 13.4/1 ("Address of overloaded function," [over.over]): A use of an overloaded function name without arguments is resolved in certain contexts to a function, a pointer to function or pointer to member function for a specific function from the overload set. A function template name is considered to name a ...
1,424,471
1,424,516
C++ Timer not working?
I'm trying to make a timer in c++. I'm new to c++. I found this code snippet UINT_PTR SetTimer(HWND hWnd, UINT_PTR nIDEvent, UINT uElapse, TIMERPROC lpTimerFunc); I put it in my global variables and it tells me Error 1 error C2373: 'SetTimer' : redefinition; different type modifiers I'm not sure what this mean...
You should call it like this: void CALLBACK TimerProc( HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime ) { //do something } SetTimer(NULL, NULL, 1000, TimerProc); This would set a timer for 1 second and will call TimerProc when it expires. Read TimerProc MSDN here: http://msdn.microsoft.com/en-us/library/ms...
1,424,510
1,424,535
My attempt at value initialization is interpreted as a function declaration, and why doesn't A a(()); solve it?
Among the many things Stack Overflow has taught me is what is known as the "most vexing parse", which is classically demonstrated with a line such as A a(B()); //declares a function While this, for most, intuitively appears to be the declaration of an object a of type A, taking a temporary B object as a constructor pa...
There is no enlightened answer, it's just because it's not defined as valid syntax by the C++ language... So it is so, by definition of the language. If you do have an expression within then it is valid. For example: ((0));//compiles Even simpler put: because (x) is a valid C++ expression, while () is not. To lear...
1,424,606
1,424,622
Lost Focus and GotFocus in c++
How do you add code to these events for native c++? I couldn't find a WM_LOSTFOCUS OR WM_GOTFOCUS; I only found WM_SETFOCUS. I need code to happen when my window loses focus, and regains it. Thanks.
JUST BEFORE your window loses focus it will be sent: WM_KILLFOCUS AFTER your window gains focus, it will be sent: WM_SETFOCUS Sending a WM_SETFOCUS message does not set the focus. You need to call SetFocus for that.
1,424,779
1,424,807
is there any good library for printing preview in MFC?
I need to print records in a grid view, and need to preview it before printing. I want to know whether or not there is a strong library for printing preview? And with the library I can change the position, layout of the data to print. More important: I need to change the data's layout, how can I do that?
MFC itself supports Print Preview, there shouldn't be a need for an additional library.
1,424,934
1,425,031
Question About CFile Seek
I am using MFC CFile Seek function. I have a problem about Seek out of file length. CFile cfile; BOOL bResult = cfile.Open( L"C:\\2.TXT", CFile::modeReadWrite | CFile::modeCreate | CFile::modeNoTruncate | CFile::typeBinary | CFile::shareDenyNone); cfile.Seek(10000, CFile::End); cfile.Close(); MSDN: Remarks The ...
I think MSDN misstated the matter slightly. When you call Seek the file pointer is adjusted, but the actual file on the disk doesn't change yet. If you call Write after that, then the actual file will become a sparse file (on NTFS) or a longer file (on FAT), with the expected length. There don't seem to be any definite...
1,424,948
1,424,964
C++ Console Progress Indicator
What would be an easy way of implementing a console-based progress indicator for a task that's being executed, but I can't anticipate how much time it would take? I used to do this back when I coded in Clipper, and it was only a matter of iterating through the chars '/', '-', '\', '|' and positioning them in the same p...
A very simple way to do it is to print out a string followed by a '\r' character. That is carriage return by itself and on most consoles, it returns the cursor to the beginning of the line without moving down. That allows you to overwrite the current line. If you are writing to stdout or cout or clog remember to fflush...
1,425,227
1,425,267
how to create files named with current time?
I want to create a series of files under "log" directory which every file named based on execution time. And in each of these files, I want to store some log info for my program like the function prototype that acts,etc. Usually I use the hard way of fopen("log/***","a") which is not for this purpose.And I just write a...
Declare a char array big enough to hold 16 + "log/" (so 20 characters total) and initialize it to "log/", then use strcat() or something related to add the time string returned by your function to the end of your array. And there you go! Note how the string addition works: Your char array is 16 characters, which means ...
1,425,256
1,425,308
How do I read a java object in C++?
I am implementing a log server in C++; that accepts log messages from a Java program (via log4j socket appender). How do I read these java logging objects in C++?
You should configure the log4j appender to send XML format messages. Then it is simply a matter of reading XML in C++.
1,425,349
1,425,683
How do I find an element position in std::vector?
I need to find an element position in an std::vector to use it for referencing an element in another vector: int find( const vector<type>& where, int searchParameter ) { for( int i = 0; i < where.size(); i++ ) { if( conditionMet( where[i], searchParameter ) ) { return i; } } return ...
You could use std::numeric_limits<size_t>::max() for elements that was not found. It is a valid value, but it is impossible to create container with such max index. If std::vector has size equal to std::numeric_limits<size_t>::max(), then maximum allowed index will be (std::numeric_limits<size_t>::max()-1), since eleme...
1,425,648
1,425,748
ListView Movement Problem
I am using Listview,the View selected is largeicon mode. The problem i am facing is selection.using the arrow-keys i am able to navigate only in the first row(suppose i have 3 images in a row,if i press right arrow key,it will move till the end of row and again it will comeback to the first image of the same row)But th...
If you are only handling keydown then it may be that the current keypress is still being processed (e.g. the move right), but you have already moved the focus to the item on the next row, and so when the key up happens it moves the focus on to the 2nd item. Try setting the Handled property to true of the KeyEventArgs o...
1,425,695
1,426,834
Safe way to initialize a derived class
I have a base class: class CBase { public: virtual void SomeChecks() {} CBase() { /* Do some checks */ SomeChecks(); /* Do some more checks */ } }; and a derived class: class CDerived : public CBase { public: virtual void SomeChecks() { /* Do some other checks *...
Calling virtual methods in the constructor/destructor is not allowed. The though processes behind this is that virtual methods are calling the most derived version of a method and if the constructor has not finished then the most derived data has not been correctly initialized and therefore doing so potentially provide...
1,425,905
1,425,910
C++: Performance impact of BIG classes (with a lot of code)
I wonder if and how writing "almighty" classes in c++ actually impacts performance. If I have for example, a class Point, with only uint x; uint y; as data, and have defined virtually everything that math can do to a point as methods. Some of those methods might be huge. (copy-)constructors do nothing more than initial...
You are right, methods only exist once in memory, they're just like normal functions with an extra hidden this parameter. And of course, only data members are taken in account for allocation, well, inheritance may introduce some extra ptrs for vptrs in the object size, but not a big deal