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
2,221,065
2,221,563
How to read in a data file of unknown dimensions in C/C++
I have a data file which contains data in row/colum form. I would like a way to read this data in to a 2D array in C or C++ (whichever is easier) but I don't know how many rows or columns the file might have before I start reading it in. At the top of the file is a commented line giving a series of numbers relating to what each column holds. Each row is holding the data for each number at a point in time, so an example data file (a small one - the ones i'm using are much bigger!) could be like: # 1 4 6 28 21.2 492.1 58201.5 586.2 182.4 1284.2 12059. 28195.2 ..... I am currently using Python to read in the data using numpy.loadtxt which conveniently splits the data in row/column form whatever the data array size, but this is getting quite slow. I want to be able to do this reliably in C or C++. I can see some options: Add a header tag with the dimensions from my extraction program # 1 4 6 28 # xdim, ydim 21.2 492.1 58201.5 586.2 182.4 1284.2 12059. 28195.2 ..... but this requires rewriting my extraction programs and programs which use the extracted data, which is quite intensive. Store the data in a database file eg. MySQL, SQLite etc. Then the data could be extracted on demand. This might be a requirement further along in the development process so it might be good to look into anyway. Use Python to read in the data and wrap C code for the analysis. This might be easiest in the short run. Use wc on linux to find the number of lines and number of words in the header to find the dimensions. echo $((`cat FILE | wc -l` - 1)) # get number of rows (-1 for header line) echo $((`cat FILE | head -n 1 | wc -w` - 1)) # get number of columns (-1 for '#' character) Use C/C++ code This question is mostly related to point 5 - if there is an easy and reliable way to do this in C/C++. Otherwise any other suggestions would be welcome Thanks
Figured out a way to do this. Thanks go mostly to Manuel as it was the most informative answer. std::vector< std::vector<double> > readIn2dData(const char* filename) { /* Function takes a char* filename argument and returns a * 2d dynamic array containing the data */ std::vector< std::vector<double> > table; std::fstream ifs; /* open file */ ifs.open(filename); while (true) { std::string line; double buf; getline(ifs, line); std::stringstream ss(line, std::ios_base::out|std::ios_base::in|std::ios_base::binary); if (!ifs) // mainly catch EOF break; if (line[0] == '#' || line.empty()) // catch empty lines or comment lines continue; std::vector<double> row; while (ss >> buf) row.push_back(buf); table.push_back(row); } ifs.close(); return table; } Basically create a vector of vectors. The only difficulty was splitting by whitespace which is taken care of with the stringstream object. This may not be the most effective way of doing it but it certainly works in the short term! Also I'm looking for a replacement for the deprecated atof function, but nevermind. Just needs some memory leak checking (it shouldn't have any since most of the objects are std objects) and I'm done. Thanks for all your help
2,221,132
2,221,177
Creating registry keys in Windows 7
In attempting to upgrade some C++ software to run in Windows 7 I have experienced some problems in being able to create registry keys from scratch. This is my code: // // Create a brand new registry key // LONG Registry::CreateRegister( std::string path ) { HKEY hKey; DWORD dwDisposition; LONG openRes = RegCreateKeyEx( HKEY_CLASSES_ROOT, path.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition ); RegCloseKey( hKey ); return openRes; } In Windows XP, the RegCreateKeyEx function successfully creates the registry key, returning a success (0) value. In Windows 7 I am getting a return value of 5 (access denied) from the same function. I used the regedit tool to ensure that my account has the necessary full permissions, but without success. Can anyone see where I might be going wrong, or if there are other gotchas and known issues I need to be aware of when using Visual Studio within Windows 7? The software is currently written in Visual Studio 2003. Thanks in anticipation.
Since Vista, access to certain areas of the registry has been locked down. The user must have "elevated" permissions. Try running your program with "Run as administrator" (right click it in Explorer).
2,221,291
2,221,347
Direct3D Sprite->SetTransform usage?
I draw textures using the D3DXSprite. I want to transform them(rotate, scale etc..) so I use the SetTransfrom method. Should I, store the old transformation -> set a new one -> draw -> set the old one? I have a sprite class whice take care of the Draw and the Update methods. I mean something like this: D3DXMatrix oldMatrix; sprite->GetTransfrom(&oldMatrix); D3DXMatrix newMatrix; D3DXMatrixScaling(&newMatrix, 2.0f, 2.0f, 0.0f); sprite->SetTransform(&newMatrix); sprite->Draw(...); sprite->SetTransform(&oldMatrix); Good/Bad?
What would be bad is to retrieve the oldMatrix and use it for computing a newMatrix (precision issues). It's better to recompute a fresh matrix at each new draw. What you probably want to store for each of your sprites is a position, rotation and scale factor.
2,221,296
2,221,332
C/C++ Pointer Question
tl;dr - Could you please expand on the 4 comments in the first code snippet below? Specifically what is meant be deref I'm a long time Java developer looking to learn C++. I came across this website aimed at developers in my situation. int x, *p, *q; p = new int; cin >> x; if (x > 0) q = &x; *q = 3; // 1. deref of possibly uninitialized ptr q q = p; p = new int; // 2. potential storage leak (if x != 0 this // memory will not be returned to free storage) *p = 5; delete q; *q = 1; // 3. deref of deleted ptr q q = p; if (x == 0) delete q; (*p)++; // 4. deref of possibly dangling ptr p (if x is zero) Although I thought I understood how pointers work, I am finding the comments difficult to understand. My take; We are either assigning x (& *q of course) to be 3 OR if q != &x then q has a just value as it was uninitialized and we have just assigned a random piece of memory to the value 3. I'm not sure how you can dereference something that isn't initialized? This is fine What's wrong with dereferencing a deleted pointer? After 'delete q' is *q meaningless? What's wrong with dangling pointers? Is the memory viable for reallocation now that we have deleted it even though we still have a pointer to it? I think my basic misunderstanding is about just declaring an int pointer, does this allocate memory too? Is it on the stack or the heap? Also does dereference just mean 'read the value at the address of the pointer'? I think my confusion is that I interpret it as loosing a reference to some data as in; int *x; x = new int; *x = 5; x = new int; // Dereferencing the first bit of memory allocated. Thanks for you patience I hope that this makes some sense as a question, Gav
Simply put: A pointer is an address of a variable whose values you may be interested in. Dereferencing is the act of accessing that value -- by prepending the * (dereferencing operator) to the pointer variable. The access may be for reading, writing or both. If you do not initialize a pointer to a valid address (or the special value NULL) -- you do not know what that variable contains. Dereferencing will try to take whatever is there and treat it as an address. This is undefined behavior -- all bets are off, anything might happen, though if you are lucky you'll end up with a trap/hardware exception. Exactly. Because, p was holding the address of some memory you allocated. Not freeing up system resources causes a leak. Dereferencing a deleted pointer is the same as dereferencing an uninitialized pointer -- you don't know what value it may contain. Again, UB. True. You have UB for x == 0. Dangling pointers are dangerous because they creep up at the most inopportune time, format your hard disk and are never seen again. It becomes impossible to reasonably justify how your program will behave.
2,221,628
2,221,655
c++ allocating memory problem
i'm having a weird problem with allocating memory in c++ i'm creating a buffer and read file content into it. problem is the allocating is incorrect and at the end of the printing there are weird chars... the content of the file is "Hello"... i'm sitting on it for hours... what can be the problem ? :( void main() { FILE *fp; char *buffer; long file_size; size_t result; fp = fopen("input.txt","r"); if (fp == NULL) { fputs("File Error",stderr); exit(1); } //get file size fseek(fp, 0, SEEK_END); file_size = ftell(fp); rewind(fp); //allocate memory to contain the whole file size buffer = new char[file_size]; if (buffer == NULL) { fputs("Cannot allocate memory space",stderr); exit(2); } //copy the file into the buffer result = fread(buffer, 1, file_size, fp); if (result != file_size) { fputs("Reading error",stderr); exit(3); } cout<<buffer; fclose(fp); delete buffer; }
Allocate one more place for termination character. And put it at the end of your buffer. This will probably solve your problem. buffer = new char[file_size + 1]; buffer[file_size] ='\0';
2,221,671
2,221,700
C++ Templates queries
HI, I started learning C++ STL's i am just trying some small programs.one of them is below: inline int const& max (int const& a, int const& b) { return a < b ? b : a; } template <typename T> inline T const& max (T const& a, T const& b) { return a < b ? b : a; } int main() { ::max(7, 42); // calls the nontemplate for two ints ::max<>(7, 42); // calls max<int> (by argument deduction) ::max('a', 42.7); // calls the nontemplate for two ints } I have some basic questions!! why is the scope resolution operator used here? why/how is that calling ::max<>(7, 42) will assume that the parameter passed are integers?
1) why is the scope resolution operator used here? Probably to differentiate the max declared here from the one in (for example) the std:: namespace. 2) why/how is that calling ::max<>(7, 42) will assume that the parameter passed are integers? It doesn't have to assume anything - integer literals have the type int. And to answer the question you didn't ask: max('a', 42.7); matches the non-template version because type conversions are not performed on templated parameters, but are performed on non-template ones.
2,221,832
2,221,871
boost::trim each string in std::vector<std::string>
I'm currently stuck finding the correct syntax for trimming each string in a std::vector. I tried std::vector<std::string> v; std::for_each(v.begin(), v.end(), &boost::trim); which gave me the following error messages in MSVC7.1. error C2784: '_Fn1 std::for_each(_InIt,_InIt,_Fn1)' : could not deduce template argument for 'T1' from 'std::vector<_Ty>::iterator' with [_Ty=std::string] : see declaration of 'std::for_each' error C2896: '_Fn1 std::for_each(_InIt,_InIt,_Fn1)' : cannot use function template 'void boost::algorithm::trim(SequenceT &,const std::locale &)' as a function argument : see declaration of 'boost::algorithm::trim' If I explicitly give the template parameter trims second parameter can not be found by the compiler, though its set by default. std::for_each(v.begin(), v.end(), &boost::trim<std::string>); error C2198: 'void (__cdecl *)(std::string &,const std::locale &)' : too few arguments for call through pointer-to-function I was wondering how the correct syntax to call trim for each element in v would look like.
You need to bind as well the second parameter of trim (the locale): std::vector<std::string> v; std::for_each(v.begin(), v.end(), boost::bind(&boost::trim<std::string>, _1, std::locale() ));
2,221,842
2,221,876
C++ - String input with a pointer-to-structure?
How do you use a pointer-to-struct to get input that will be stored in a string variable? I thought simply passing pz->szCompany to getline() would behave the same as if I had used the . operator on a normal instance of Pizza (instead of a pointer-to), but when I run this program it skips over the company name prompt completely. // Parts of the program omitted. struct Pizza { string szCompany; float diameter; float weight; }; Pizza* pz = new Pizza; cout << "Enter the weight: "; cin >> pz->weight; cout << "Enter the company name: "; // use getline because the company name can have spaces in it. getline(cin, pz->szCompany); cout << "Enter the diameter: "; cin >> pz->diameter; cout << "\nCompany name: " << pz->szCompany; cout << "\nWeight: " << pz->weight; cout << "\nDiameter: " << pz->diameter; // cannot forget this step. delete pz; return 0;
When you use >> to read input, it will leave unread characters in the stream (those, that couldn't be converted to integer, at least the return character you type to enter input), which the following getline will consume thinking it has already read an (empty) line. #include <limits> //... cin >> pz->diameter; cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); cout << "Enter the company name: "; // use getline because the company name can have spaces in it. getline(cin, pz->szCompany); Your problem has nothing to do with the struct or pointers, just the normal behavior of input streams. You may also have to deal with incorrect input. For example, entering a non-number where a number is expected would put the stream in an error state, so that all subsequent attempts to read would fail unless you deal with it. Better take Neil's advice, but for getting input from the user, it might also make sense to use a function for formatted input that prompts you until you get valid input: template <class T> T input(const std::string& prompt, const std::string& error_prompt) { std::cout << prompt; T result; while (!(std::cin >> result)) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << error_prompt; } std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); return result; } //... pz->weight = input<float>("Enter the weight: ", "Please enter a numeric value: ");
2,222,192
2,222,282
Absolute positioning in printout with cout in C++?
How do you get "absolutely positioned" columns with cout, that leftaligns text and right-aligns numbers? #include <iostream> #include <iomanip> using namespace std; struct Human { char name[20]; char name2[20]; char name3[20]; double pts; }; int main() { int i; Human myHumen[3] = { {"Mr", "Alan", "Turing", 12.25}, {"Ms", "Ada", "Lovelace", 15.25}, {"Sir", "Edgar Allan", "Poe", 45.25} }; cout << "Name1" << setw(22) << "Name2" << setw(22) << "Name3" << setw(22) << "Rating" <<endl; cout << "-----------------------------------------------------------------------\n"; for(i = 0; i < 3; i++) { cout << myHumen[i].name << setw(22) << myHumen[i].name2 << setw(22) << myHumen[i].name3 << setw(20) << myHumen[i].pts << endl; }//this didn't do nice printouts, with leftalign for text and rightalign with numbers }
You use the "left" and "right" manipulators: cout << std::left << std::setw(30) << "This is left aligned" << std::right << std::setw(30) << "This is right aligned"; An example with text + numbers: typedef std::vector<std::pair<std::string, int> > Vec; std::vector<std::pair<std::string, int> > data; data.push_back(std::make_pair("Alan Turing", 125)); data.push_back(std::make_pair("Ada Lovelace", 2115)); for(Vec::iterator it = data.begin(), e = data.end(); it != e; ++it) { cout << std::left << std::setw(20) << it->first << std::right << std::setw(20) << it->second << "\n"; } Which prints: Alan Turing 125 Ada Lovelace 2115
2,222,293
2,222,318
Vector, Size_type, and Encapsulation
I have a class with a private data member of type vector< A*>. The class has two public methods that actually use vector<A*>::size_type: Method returning number of elements in the vector Method returning element in the vector by index I can add to public section of the class the following typedef: typedef vector::size_type SIZE_t; but IMHO it exposes too many details about class implementation. Another approach is to use size_t. What do you think?
Use plain old size_t for both member functions.
2,222,549
2,222,983
Best C++ Matrix Library for sparse unitary matrices
I am looking for a good (in the best case actively maintained) C++ matrix library. Thereby it should be templated, because I want to use a complex of rationals as numerical type. The matrices what I am dealing with are mainly sparse and unitary. Can you please suggest libraries and also give a small explaination why to use them, because I know how to find them, but I cannot really decide what is suitable for me because I am missing the experience with them. EDIT: The main operations I am dealing with are matrix multiplication, scalar multiplication with a vector and kronecker product. The size of the matrices is exponential and I wanna at least be able to deal with matrices up to 1024x1024 entries.
Many people doing "serious" matrix stuff, rely on BLAS, adding LAPACK / ATLAS (normal matrices) or UMFPACK (sparse matrices) for more advanced math. The reason is that this code is well-tested, stable, reliable, and quite fast. Furthermore, you can buy them directly from a vendor (e.g. Intel MKL) tuned towards your architecture, but also get them for free. uBLAS mentioned in Manuel's answer is probably the standard C++ BLAS implementation. And if you need something like LAPACK later on, there are bindings to do so. However, none of these standard libraries (BLAS / LAPACK / ATLAS or uBLAS + bindings + LAPACK / ATLAS) ticks your box for being templated and easy to use (unless uBLAS is all you'll ever need). Actually, I must admit, that I tend to call the C / Fortran interface directly when I use a BLAS / LAPACK implementation, since I often don't see much additional advantage in the uBLAS + bindings combination. If I a need a simple-to-use, general-purpose C++ matrix library, I tend to use Eigen (I used to use NewMat in the past). Advantages: quite fast on Intel architecture, probably the fastest for smaller matrices nice interface almost everything you expect from a matrix library you can easily add new types Disadvantages (IMO): single-processor [Edit: partly fixed in Eigen 3.0] slower for larger matrices and some advanced math than ATLAS or Intel MKL (e.g. LU decomposition) [Edit: also improved in Eigen 3.0] only experimental support for sparse matrices [Edit: improved in upcoming version 3.1]. Edit: The upcoming Eigen 3.1 allows some functions to use the Intel MKL (or any other BLAS / LAPACK implementation).
2,222,631
2,222,670
Understanding C++ Template Error
#include <iostream> #include <cstring> #include <string> template <typename T> inline T const& max (T const& a, T const& b) { return a < b ? b : a; } inline char const* max (char const* a, char const* b) { return std::strcmp(a,b) < 0 ? b : a; } template <typename T> inline T const& max (T const& a, T const& b, T const& c) { return max (max(a,b), c); // error } int main () { ::max(7, 42, 68); // OK const char* s1 = "frederic"; const char* s2 = "anica"; const char* s3 = "lucas"; ::max(s1, s2, s3); // ERROR } Could anybody please tell me why this is an error?
When you say: max (max(a,b), c) max(char*,char*) returns a pointer BY VALUE. You then return a reference to this value. To make this work, you should make all your max() functions return values rather than references, as I think was suggested in an answer to your previous question, or make the char* overload take and return references to pointers.
2,222,641
2,222,797
Using Java JAR libraries with C++
I'm developing a win32 C++ application that needs to export data to excel spreadsheets. There isn't a mature C++ library for this, but exists for Java. How I can integrate a C++ application with Java code, in such way that I can call Java functions from my C++ application?
You can also generate a simple html file, save it as .xls and excel will know to read it. e.g: <table><tr><td>cell a</td><td>cell b</td></table> And then no need for executing Java and external programs.
2,222,939
2,222,954
What does the "incomplete type is not allowed" error mean?
I am trying to declare a callback routine in C++ as follows: void register_rename (int (*function) (const char *current, const char *new)); /*------------------------------------------------------------*/ /* WHEN: The callback is called once each time a file is received and * accepted. (Renames the temporary file to its permanent name) * WHAT: Renames a file from the given current name to the specified new name. */ However, I get the following error: line 204: error #70: incomplete type is not allowed void register_rename (int (*function) (const char *current, const char *new)); I'm not sure how to correct this. I have other similar callback routines declared in the same header file, and I do not get this error. Please help! :)
You cannot use new because it is a keyword. Try to pick a valid identifier for your second argument.
2,223,245
2,223,288
Overloading global swap for user-defined type
The C++ standard prohibits declaring types or defining anything in namespace std, but it does allow you to specialize standard STL templates for user-defined types. Usually, when I want to specialize std::swap for my own custom templated type, I just do: namespace std { template <class T> void swap(MyType<T>& t1, MyType<T>& t2) { t1.swap(t2); } } ...and that works out fine. But I'm not entirely sure if my usual practice is standard compliant. Am I doing this correctly?
What you have is not a specialization, it is overloading and exactly what the standard prohibits. (However, it will almost always currently work in practice, and may be acceptable to you.) Here is how you provide your own swap for your class template: template<class T> struct Ex { friend void swap(Ex& a, Ex& b) { using std::swap; swap(a.n, b.n); } T n; } And here is how you call swap, which you'll notice is used in Ex's swap too: void f() { using std::swap; // std::swap is the default or fallback Ex<int> a, b; swap(a, b); // invokes ADL } Related: Function template specialization importance and necessity
2,223,374
2,238,574
C++ library works in vb6 but not in c#
I'm writing a C# application that has to consume a C++ api provided by my customer. The library works fine when it's referenced by a vb6 application, but when I reference it in my c# application and try to call the same methods, I get a different (wrong) behavior. The methods I'm calling take a couple of string arguments. Provided that I don't have the library's source code, I can only guess what could be wrong and this leads me to the following thought: Is it possible that the library could have been designed to be called from vb6 only? I mean for example, that it could be expecting the string parameters to be encoded in a certain way different from the one c# uses. If so, is there any workaround for this? So far the best I could do was to create a vb6 wrapper ocx, but it's not any elegant and least of all easy to deploy solution. I'm posting the code which initializes the object: ApiPrnClass apiprn; // this is the class imported form the com reference for (int j = 0; j < 10; j++) { apiprn = new ApiPrnClass(); apiprn.FMGetModel(_TIPODISPOSITIVO.iDocument); apiprn.FMPRNFormat(_TIPODISPOSITIVO.iDocument, _TIPOFORMATO.DEL_CONDENSED, ""); apiprn.PRNBeforePrint(_TIPODISPOSITIVO.iDocument, ""); for (int i = 0; i < 10; i++) { string linea = "TEST C/ BUFF XXX-----------------------".Replace("XXX", (10 * j + i).ToString().PadLeft(3, '0')); apiprn.FMPrint(_TIPODISPOSITIVO.iDocument, linea); } apiprn.PRNAfterPrint(_TIPODISPOSITIVO.iDocument); System.Threading.Thread.Sleep(1000); } I would appreciate any help, Thanks, Bernabé
I can't believe the cause of the problem, I found it myself. I realized that the library was doing fine when called from a c# console application but wrong when used from a winforms (didn't mention it before, it was a library intended to print a ticket). The only difference i knew there could be between the two types of application is that the console application runs a thread dedicated to the runing code while the winforms goes to check the event qeue. It seems the library was so twisted-code that it couldn't support that switching. So I tryied calling the library from the windows application but in another thread....and it worked! Thanks for all the answers anyway, Bernabé
2,223,464
2,223,490
Using C++\C# .Net assemblies\DLL's in win32 C++ (unmanaged) application
There is any way to use C++\C# .Net assemblies\DLL's in win32 C++ (unmanaged) applications?
Is it possible to use .Net, from any language, in C++ in a 100% pure unmanaged application? No it is not. Using managed code requires the CLR to be in the process. Is it possible to use .Net, from any language, in C++ in an unmanaged application that does not specifically start up the CLR? Yes. It is possible to use the managed code via COM Interop. In this case the native code need not know that the CLR is even in process. It would create the COM objects as it would if they were defined in C++ and not know the difference.
2,223,670
2,223,707
fwrite with structs containing an array
How do I fwrite a struct containing an array #include <iostream> #include <cstdio> typedef struct { int ref; double* ary; } refAry; void fillit(double *a,int len){ for (int i=0;i<len;i++) a[i]=i; } int main(){ refAry a; a.ref =10; a.ary = new double[10]; fillit(a.ary,10); FILE *of; if(NULL==(of=fopen("test.bin","w"))) perror("Error opening file"); fwrite(&a,sizeof(refAry),1,of); fclose(of); return 0; } The filesize of test.bin is 16 bytes, which I guess is (4+8) (int + double*). The filesize should be 4+10*8 (im on 64bit) ~$ cat test.bin |wc -c 16 ~$ od -I test.bin 0000000 10 29425680 0000020 ~$ od -fD test.bin -j4 0000004 0,000000e+00 7,089709e-38 0,000000e+00 0 29425680 0 0000020 thanks
You are writing the pointer (a memory address) into the file, which is not what you want. You want to write the content of the block of memory referenced by the pointer (the array). This can't be done with a single call to fwrite. I suggest you define a new function: void write_my_struct(FILE * pf, refAry * x) { fwrite(&x->ref, sizeof(x->ref), 1, pf); fwrite(x->ary, sizeof(x->ary[0]), x->ref, pf); } You'll need a similar substitute for fread.
2,223,729
2,223,761
Using a singleton to store global application parameters
i'm developing a simple simulation with OpenGL and this simulation has some global constants that are changed by the user during the simulation execution. I would like to know if the Singleton design pattern is the best way to work as a temporary, execution time, "configuration repository"
A singleton is probably the best option if you need to keep these settings truly "global". However, for simulation purposes, I'd consider whether you can design your algorithms to pass a reference to a configuration instance, instead. This would make it much easier to store configurations per simulation, and eventually allow you to process multiple simulations with separate configurations concurrently, if requirements change. Often, trying to avoid global state is a better, long term approach.
2,223,804
2,223,832
Formatting a hard disk in c++ on Windows 7
I am wondering how to format a hard disk in Windows 7 through c++? I currently have an application that is successful at this using a function in a dll. Unfortunately I don't have the code for the dll so there is no way for me to see what its doing. It doesn't actually format the drive itself but it launches the format utility built into windows and starts the formatting. What I mean by format utility is the dialog you get when you right click on a drive and select format. Somehow the dll opens this dialog and starts the format. The dialog is almost identical in Windows XP and 7 but for some reason it does not work properly in 7. I have tried running the application in admin as well with no luck.
If memory serves, you're looking for SHFormatDrive().
2,223,835
2,223,848
stl insertion iterators
Maybe I am missing something completely obvious, but I can't figure out why one would use back_inserter/front_inserter/inserter, instead of just providing the appropriate iterator from the container interface. And thats my question.
Because those call push_back, push_front, and insert which the container's "normal" iterators can't (or, at least, don't). Example: int main() { using namespace std; vector<int> a (3, 42), b; copy(a.begin(), a.end(), back_inserter(b)); copy(b.rbegin(), b.rend(), ostream_iterator<int>(cout, ", ")); return 0; }
2,223,942
2,223,999
Write file without system and hdd cache
How can I write something to a file in C++ without using system cache and drive cache? I just want to write exactly on the hdd regardless all the system cache settings.
Unless you are writing a disk device driver, you can't guarantee that there won't be any cache or processing done with your write. The C runtime library exposes fflush(FILE *) to do this. Windows has FlushFileBuffers as well as a flag you can pass to CreateFile (FILE_FLAG_NO_BUFFERING) (which itself adds restrictions on what you can do). An alternative to trying to bypass write caching is to make your data structures resilient to partial failure. For files, one popular technique is to write out the header of the file after the rest of the file is written. Assuming Murphy and not Machiavellian behavior, that should be enough. Or use the OS provided file replacement or transaction functions (See ReplaceFile and Transactional NTFS for Windows).
2,224,019
2,224,257
Why doesn't boost::serialization check for tag names in XML archives?
I'm starting to use boost::serialization on XML archives. I can produce and read data, but when I hand-modify the XML and interchange two tags, it "fails to fail" (i.e. it proceeds happily). Here's a small, self-complete example showing what I see: #include <iostream> #include <fstream> #include <boost/archive/xml_oarchive.hpp> #include <boost/archive/xml_iarchive.hpp> #include <boost/serialization/nvp.hpp> #include <boost/serialization/split_member.hpp> using namespace std; int main (void) { boost::archive::xml_oarchive oa (cout); static const string producer = "XXX", version = "0.0.1"; oa << boost::serialization::make_nvp ("producer", producer); oa << boost::serialization::make_nvp ("producer_version", version); } This writes XML to standard output, which contains: <producer>XXX</producer> <producer_version>0.0.1</producer_version> Now, I replace all the code in the main function with a reader: boost::archive::xml_iarchive ia (cin); string producer, version; ia >> boost::serialization::make_nvp ("producer", producer); ia >> boost::serialization::make_nvp ("producer_version", version); cout << producer << " " << version << endl; which works as expected when fed the previous output (outputs "XXX 0.0.1"). If, however, I feed it XML in which I changed the order of the two lines "producer" and "producer_version", it still runs and outputs "0.0.1 XXX". Thus, it fails to recognize that the tags don't have the expected names, and just proceed. I would have expected it to thrown a xml_archive_parsing_error exception, as indicated in the doc. Does someone here have experience with that? What I am doing wrong?
Just changing the order of the two lines won't cause an xml_archive_parsing_error exception. The doc you've linked says that itself: (...)This might be possible if only the data is changed and not the XML attributes and nesting structure is left unaltered.(...) You haven't changed attributes and the order change has kept the structure (still two fields on the first level of your XML). No exception will ever be thrown this way. Also, when reading a XML using the make_nvp function, the name parameter won't put any restriction on what is being read. It will just tell arbitrarily the name to be used with the new name-value pair. So, you can change the name of your XML tags on your input, as long you don't change your expected order i.e. you could rename producer and producer_version on your XML to foo and bar and still would read the serialized data correctly i.e.: <foo>XXX</foo> <bar>0.0.1</bar> And your printed answer would still be "XXX 0.0.1". Since this only formatting your serialized data as a XML, there is no interest in checking the tag names. They are only used for making your serialized output more readable.
2,224,155
2,224,274
Game development with Qt: where to look first?
So, I'm going to develop a Pac-Man clone with Qt. The problem is that I do not really know where to start. I quickly take a look at the documentation and some demo. I also downloaded some game sources on qt-apps.org. And it seems that there is a lot of ways to develop a game with Qt! In your experience, which part of Qt should I consider to develop a Pac-Mac clone ? The Animation Framework The Graphics View Framework The Paint System Qt Declarative Any help would be appreciated.
I think that QGraphicsView framework is the best way. Create a QGraphicsScene, some QGraphicsItems for the elements of the game. You have collision detection for free. Most of KDE games are based on the QGraphicsView framework. It is a good fit for simple game development.
2,224,159
2,224,170
default initialization in C++
I have a question about the default initialization in C++. I was told the non-POD object will be initialized automatically. But I am confused by the code below. Why when I use a pointer, the variable i is initialized to 0, however, when I declare a local variable, it's not. I am using g++ as the compiler. class INT { public: int i; }; int main () { INT* myint1 = new INT; INT myint2; cout<<"myint1.i is "<<myint1->i<<endl; cout<<"myint2.i is "<<myint2.i<<endl; return 0; } The output is myint1.i is 0 myint2.i is -1078649848
You need to declare a c'tor in INT and force 'i' to a well-defined value. class INT { public: INT() : i(0) {} ... }; i is still a POD, and is thus not initialized by default. It doesn't make a difference whether you allocate on the stack or from the heap - in both cases, the value if i is undefined.
2,224,164
2,224,194
Help me convert C++ structure into C#
I am completely new to C#, and need help converting a C++ structure to C#. The C++ structure is given as: #define QUE_ADDR_BUF_LENGTH 50 #define QUE_POST_BUF_LENGTH 11 typedef struct { const WCHAR *streetAddress; const WCHAR *city; const WCHAR *state; const WCHAR *country; const WCHAR *postalCode; } QueSelectAddressType; typedef struct { WCHAR streetAddress[QUE_ADDR_BUF_LENGTH + 1]; WCHAR city[QUE_ADDR_BUF_LENGTH + 1]; WCHAR state[QUE_ADDR_BUF_LENGTH + 1]; WCHAR country[QUE_ADDR_BUF_LENGTH + 1]; WCHAR postalCode[QUE_POST_BUF_LENGTH + 1]; } QueAddressType; I cannot make changes to the C++ structure as they are defined by the API I am attempting to interface with. Any help would be appreciated. EDIT: Here is more information, the function in the dll I am attempting to call is declared the as follows: #ifdef QUEAPI_EXPORTS #define QueAPIExport __declspec(dllexport) #elif defined QUEAPI_SERVER #define QueAPIExport #else #define QueAPIExport __declspec(dllimport) #endif #ifdef __cplusplus extern "C" { #endif typedef uint32 QuePointHandle; QueAPIExport QueErrT16 QueCreatePointFromAddress ( QueSelectAddressType* addr, // in: Address data to search on. QuePointHandle* point // out: Handle to selected point. Must be closed with QueClosePoint. ); Here is how I have defined the DllImport: [DllImport("QueAPI.DLL", EntryPoint = "QueCreatePointFromAddress")] public static unsafe extern QueTypesnConst.QueErrT16 QueCreatePointFromAddress(QueTypesnConst.QueSelectAddressType *address, uint *point); EDIT2: The following code blocks were the solution to the problem: For the Structures: [StructLayout(LayoutKind.Sequential)] public struct QueSelectAddressType { [MarshalAsAttribute(UnmanagedType.LPWStr)] public string streetAddress; [MarshalAsAttribute(UnmanagedType.LPWStr)] public string city; [MarshalAsAttribute(UnmanagedType.LPWStr)] public string state; [MarshalAsAttribute(UnmanagedType.LPWStr)] public string country; [MarshalAsAttribute(UnmanagedType.LPWStr)] public string postalCode; }; [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)] public struct QueAddressType { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst=51)] public string streetAddress; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 51)] public string city; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 51)] public string state; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 51)] public string country; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 12)] public string postalCode; }; For the DllImport: [DllImport("QueAPI.DLL", EntryPoint = "QueCreatePointFromAddress")] public static extern QueTypesnConst.QueErrT16 QueCreatePointFromAddress(ref QueTypesnConst.QueSelectAddressType address, ref uint point);
Try the following definition public partial class NativeConstants { /// QUE_ADDR_BUF_LENGTH -> 50 public const int QUE_ADDR_BUF_LENGTH = 50; /// QUE_POST_BUF_LENGTH -> 11 public const int QUE_POST_BUF_LENGTH = 11; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct QueSelectAddressType { /// WCHAR* [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string streetAddress; /// WCHAR* [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string city; /// WCHAR* [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string state; /// WCHAR* [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string country; /// WCHAR* [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string postalCode; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Unicode)] public struct QueAddressType { /// WCHAR[51] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=51)] public string streetAddress; /// WCHAR[51] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=51)] public string city; /// WCHAR[51] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=51)] public string state; /// WCHAR[51] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=51)] public string country; /// WCHAR[12] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=12)] public string postalCode; }
2,224,677
2,225,125
What does "vtable fixup" mean?
I have heard this term, "vtable fixup", used. What does it mean? I had no success asking Google. I already know what a vtable is so that does not need to be defined.
The simple answer: It's a hack to allow code generated by different compilers / languages to coexist. It allows the runtime to find the locations of virtual functions without knowing the details of the implementation.
2,224,733
2,224,784
Using regular expressions with C++ on Unix
I'm familiar with Regex itself, but whenever I try to find any examples or documentation to use regex with Unix computers, I just get tutorials on how to write regex or how to use the .NET specific libraries available for Windows. I've been searching for a while and I can't find any good tutorials on C++ regex on Unix machines. What I'm trying to do: Parse a string using regex by breaking it up and then reading the different subgroups. To make a PHP analogy, something like preg_match that returns all $matches.
Consider using Boost.Regex. An example (from the website): bool validate_card_format(const std::string& s) { static const boost::regex e("(\\d{4}[- ]){3}\\d{4}"); return regex_match(s, e); } Another example: // match any format with the regular expression: const boost::regex e("\\A(\\d{3,4})[- ]?(\\d{4})[- ]?(\\d{4})[- ]?(\\d{4})\\z"); const std::string machine_format("\\1\\2\\3\\4"); const std::string human_format("\\1-\\2-\\3-\\4"); std::string machine_readable_card_number(const std::string s) { return regex_replace(s, e, machine_format, boost::match_default | boost::format_sed); } std::string human_readable_card_number(const std::string s) { return regex_replace(s, e, human_format, boost::match_default | boost::format_sed); }
2,225,162
2,225,181
Observer design pattern in C++
Is the observer design pattern already defined in STL (Like the java.util.Observer and java.util.Observable in Java) ?
Here is a reference implementation (from Wikipedia). #include <iostream> #include <string> #include <map> #include <boost/foreach.hpp> class SupervisedString; class IObserver{ public: virtual void handleEvent(const SupervisedString&) = 0; }; class SupervisedString{ // Observable class std::string _str; std::map<IObserver* const, IObserver* const> _observers; typedef std::map<IObserver* const, IObserver* const>::value_type item; void _Notify(){ BOOST_FOREACH(item iter, _observers){ iter.second->handleEvent(*this); } } public: void add(IObserver& ref){ _observers.insert(item(&ref, &ref)); } void remove(IObserver& ref){ _observers.erase(&ref); } const std::string& get() const{ return _str; } void reset(std::string str){ _str = str; _Notify(); } }; class Reflector: public IObserver{ // Prints the observed string into std::cout public: virtual void handleEvent(const SupervisedString& ref){ std::cout<<ref.get()<<std::endl; } }; class Counter: public IObserver{ // Prints the length of observed string into std::cout virtual void handleEvent(const SupervisedString& ref){ std::cout<<"length = "<<ref.get().length()<<std::endl; } }; int main(){ SupervisedString str; Reflector refl; Counter cnt; str.add(refl); str.reset("Hello, World!"); std::cout<<std::endl; str.remove(refl); str.add (cnt); str.reset("World, Hello!"); std::cout<<std::endl; return 0; }
2,225,330
2,225,426
Member-Function Pointers With Default Arguments
I am trying to create a pointer to a member function which has default arguments. When I call through this function pointer, I do not want to specify an argument for the defaulted argument. This is disallowed according to the standard, but I have never before found anything that the standard disallowed that I could not do in some other conformant way. So far, I have not found a way to do this. Here is code illustrating the problem I'm trying to solve: class MyObj { public: int foo(const char* val) { return 1; } int bar(int val = 42) { return 2; } }; int main() { MyObj o; typedef int(MyObj::*fooptr)(const char*); fooptr fp = &MyObj::foo; int r1 = (o.*fp)("Hello, foo."); typedef int(MyObj::*barptr)(int); barptr bp1 = &MyObj::bar; int r2 = (o.*bp1)(); // <-- ERROR: too few arguments for call typedef int (MyObj::*barptr2)(); barptr2 bp2 = &MyObj::bar; // <-- ERROR: Can't convert from int(MyObj::*)(int) to int(MyObj::*)(void) int r3 = (o.*bp2)(); return 0; } Any ideas on how to do this in conformant C++ if I do not want to specify any values for the defaulted arguments? EDIT: To clarify the restrictions a bit. I do not want to specify any default arguments either in the call or in any typedef. For example, I do not want to do this: typedef int(MyObj::*barptr)(int = 5); ...nor do I want to do this: typedef int(MyObj::*barptr)(int); ... (o.barptr)(5);
It would be rather strange to expect the function pointers to work the way you expect them to work in your example. "Default argument" is a purely compile-time concept, it is a form of syntactic sugar. Despite the fact that default arguments are specified in the function declaration or definition, they really have nothing to do with the function itself. In reality default arguments are substituted at the point of the call, i.e. they are handled in the context of the caller. From the function's point of view there's no difference between an explicit argument supplied by the user or a default one implicitly supplied by the compiler. Function pointers, on the other hand, are run-time entities. They are initialized at run time. At run-time default arguments simply don't exist. There's no such concept as "run-time default arguments" in C++. Some compilers will allow you to specify default arguments in function pointer declaration, as in void foo(int); int main() { void (*pfoo)(int = 42) = foo; pfoo(); // same as 'pfoo(42)' } but this is not standard C++ and this does not appear to be what you are looking for, since you want the "default argument " value to change at run time depending on the function the pointer is pointing to. As long as you want to stick with genuine function pointers (as opposed to function objects, aka functors) the immediate workaround would be for you to provide a parameter-less version of your function under a different name, as in class MyObj { public: ... int bar(int val = 42) { return 2; } int bar_default() { return bar(); } }; int main() { MyObj o; typedef int (MyObj::*barptr2)(); barptr2 bp2 = &MyObj::bar_default; int r3 = (o.*bp2)(); return 0; } This is, of course, far from elegant. One can actually argue that what I did above with bar_default could have been implicitly done by the compiler, as a language feature. E.g. given the class definition class MyObj { public: ... int bar(int val = 42) { return 2; } ... }; one might expect the compiler to allow the following int main() { MyObj o; typedef int (MyObj::*barptr2)(); barptr2 bp2 = &MyObj::bar; int r3 = (o.*bp2)(); return 0; } where the pointer initialization would actually force the compiler to implicitly generate an "adapter" function for MyObj::bar (same as bar_default in my previous example), and set bp2 to point to that adaptor instead. However, there's no such feature in C++ language at this time. And to introduce something like that would require more effort than it might seem at the first sight. Also note that in the last two examples the pointer type is int (MyObj::*)(), which is different from int (MyObj::*)(int). This is actually a question to you (since you tried both in your example): how would you want it to work? With an int (MyObj::*)() pointer? Or with a int (MyObj::*)(int) pointer?
2,225,331
2,228,467
Recordset Update errors when updating sql_variant field
I'm using C++ and ADO to add data to a SQL Server 2005 database. When calling the Recordset Update method for a sql_variant column I'm getting the error DB_E_ERRORSOCCURRED and the error message Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done. If the value I'm adding is NULL all works fine and all values going to the fields that are not sql_variant types work. Does anyone know what I might be doing wrong? Thanks [Edit] I have some more information. The value we are storing is the empty string - ADO appears to want to store this in the sql_variant as a nchar(0), which of course is not a valid SQL data type. Is there a way to get an empty string in a sql_variant using the ADO batch commands?
You are only being shown the outer-most error there and as the error suggest you need to check the inner errors to find out the problem. Apologies, I'm a VB developer but if you loop through the errors on your connection object you should be able to pinpoint the actual error. From my classic ADO days multiple-step errors usually pointed at trying to stuff something to big into your column, e.g a string thats too big or a number with too high precision. Hope this helps. Ed
2,225,435
2,225,444
How do I create a header-only library?
I'd like to package a library I'm working on as a header-only library to make it easier for clients to use. (It's small and there's really no reason to put it into a separate translation unit) However, I cannot simply put my code in headers because this violates C++'s one definition rule. (Assuming that the library header is included in multiple translation units of a client project) How does one modify a library to make it header-only?
You can use the inline keyword: // header.hpp (included into multiple translation units) void foo_bad() {} // multiple definitions, one in every translation unit :( inline void foo_good() {} // ok :) inline allows the linker to simply pick one definition and discard the rest. (As such, if those definitions don't actually match, you get a good dose of undefined behavior...!) As an aside, member functions defined within a class-type, are implicitly marked inline: struct myclass { void i_am_inline_implicitly() { // because my definition is here } void but_i_am_not(); void neither_am_i(); }; inline void myclass::but_i_am_not() { // but that doesn't mean my definition cannot be explicitly inline } void myclass::neither_am_i() { // but in this case, no inline for me :( }
2,225,600
2,225,612
What's the difference between opening a file with ios::binary or ios::out or both?
I'm trying to figure out the difference between opening a file like: fstream *fileName*("FILE.dat",ios::binary); or fstream *fileName*("FILE.dat",ios::out); or fstream *fileName*("FILE.dat",ios::binary | ios::out); I found that all of these forms are identical: in all cases, the same output on the file is produced using either *fileName*<< or *fileName*.write().
ios::out opens the file for writing. ios::binary makes sure the data is read or written without translating new line characters to and from \r\n on the fly. In other words, exactly what you give the stream is exactly what's written.
2,225,602
2,225,647
SystemTimeToTzSpecificLocalTime crash on windows xp
The time function in the same code crashes on xp but runs fine on windows 2003 machine. Any ideas? TIME_ZONE_INFORMATION tzi; SYSTEMTIME stStartUTC; SYSTEMTIME stStart; LPCSTR lpszZone; BOOL bStatus; FILETIME* pFT; DWORD dReturn; pFT = new FILETIME; if (pFT) { pFT->dwHighDateTime = 4294967295ul; pFT->dwLowDateTime = 4294962295ul; if (pFT) { FileTimeToSystemTime (pFT, &stStartUTC); } else { GetSystemTime (&stStartUTC); } dReturn = GetTimeZoneInformation (&tzi); bStatus = SystemTimeToTzSpecificLocalTime (&tzi, &stStartUTC, &stStart); } Stack from the crash dump is : 0816e968 7c85a6f2 00000000 00000024 7c85a6f8 kernel32!__report_gsfailure+0xda 0816ebf8 7c85a788 0816ec10 0816ec70 0000a8f0 kernel32!FindRegTziForCurrentYear+0x1a5 0816ec3c 7c85a7bd 0816ec70 0000a8f0 0816eec4 kernel32!CheckDynamicTimeZoneInformation+0x29 0816ec54 7c85a834 0816ec70 0000a8f0 0816eec4 kernel32!GetDynamicTimeZoneInfoForTimeZone+0x17 0816ee7c 7c83b11c 0000a8f0 00000000 0816eec4 kernel32!GetTimeZoneInformationForYear+0x58 0816f020 14f27e38 0816f05c 0816f03c 0816f04c kernel32!SystemTimeToTzSpecificLocalTime+0x3c Thanks, Mithuna
Try adding a GetLastError call to check if every function upto the SystemTimeToTzSpecificLocalTime succeeds or not. That should give you some hint.
2,225,643
2,225,697
In C++ what does it mean for a compiler to "inline" a function object?
In the wikipedia article about function objects it says such objects have performance advantages when used with for_each because the compiler can "inline" them. I'm a bit foggy on exactly what this means in this context... or any context I'm embarrassed to say. Thanks for any help!
The last parameter of for_each template is a functor. Functor is something that can be "called" using the () operator (possibly with arguments). By defintion, there are two distinctive kinds of functors: Ordinary non-member functions are functors. Objects of class type with overloaded () operator (so called function objects) are also functors. Now, if you wanted to use an ordinary function as a functor for for_each, it would look something like the following inline void do_something(int &i) { /* do something */ } int main() { int array[10]; std::for_each(array, array + 10, &do_something); } In this case the for_each template is instantiated with [deduced] arguments <int *, void (*)(int &)>. Note that the actual functor value in this case is the function pointer &do_something passed as the function argument. From the point of view of for_each function this is a run-time value. And since it is a run-time value, the calls to the functor cannot be inlined. (Just like it is in general case impossible to inline any call made through a function pointer). But if we use a function object instead, the code might look as follows struct do_something { void operator()(int &i) { /* do something */ } }; int main() { int array[10]; std::for_each(array, array + 10, do_something()); } In this case the for_each template is instantiated with [deduced] arguments <int *, do_something>. The calls to the functor from inside for_each will be directed to do_something::operator(). The target for the call is known and fixed at compile-time. Since the target function is known at compile-time, the call can easily be inlined. In the latter case we, of course, also have a run-time value passed as an argument to for_each. It is a [possibly "dummy" temporary] instance of do_something class we create when we call for_each. But this run-time value has no effect on the target for the call (unless the operator () is virtual), so it doesn't affect inlining.
2,225,672
2,225,681
C++ need for Assembly in embedded systems
I hear of a need to call assembly functions/calls when programming embedded systems in C. Is this necessary in C++ or not?
C++ does not provide any more low-level constructs than C does. Hence, if you need to fiddle around with control registers and ISRs in C, you will need to do it in C++.
2,225,746
2,225,773
System-wide ShellExecute hooks?
is there any way I can install a system-wide ShellExecute hook using C++ without having to inject a hooking module into every active process. I am using Windows 7. My purpose for this is because, I want to be able to select which browser a link is opened in when a link is opened with the default browser using ShellExecute, like this: ShellExecute(NULL, "open", "http://stackoverflow.com", NULL, NULL, SW_SHOWNORMAL);
The last parameter of SetWindowsHookEx takes a thread id -- if this is NULL the procedure will be associated with all threads in the same desktop as the calling thread or with a particular thread otherwise. Read more: Using Hooks
2,225,768
2,225,866
Where to get custom Visual Studio 2008 syntax highlighting (complex one)
Ok, im used to see some more syntax highlighting, and the default syntax highlighting is really limited in VS 2008, so i was thinking, is there such highlighting somewhere: defined variables would have own color. defined functions would have own color. predefined functions would have own color (from libs etc, would have own list for these perhaps). constants/enums would have own color. typedefs/defs would have own color. strings (stuff between quotes) would have own color. floats/doubles would be colored differently (would check for 1.0f or 1.0 etc) Because this would be totally awesome, i havent seen 1,2,4,5 in any syntax highlighting systems before, it would be nice to have such. This would speed up programming a lot since if i make a mistake i would see it instantly before compiling. I watched some MSDN site and it was pretty complicated to do it, so im hoping if theres already existing stuff so i could just download it and so on.
Take a look at the Visual Assist X plug-in from Whole Tomato software: http://www.wholetomato.com/ I think it takes care of most of the items on your list.
2,225,786
2,225,875
How are game event lengths handled in 2D games
I have an idea of how I want to approach this but i'm not sure if it is ideal. By event I mean for example, if the player wins, a bunch of sparks fly for 1 second. I was thinking of creating my game engine class, then creating a game event base class that has 3 void functions, update, draw, render. There could be for example fireforks for collecting 100 coins for 3 seconds. The way I want to implement it is by having an event vector in my game engine where I can push the fireforks animation in. once something is pushed in the vector, the game does event[i].render() etc... For removing it I thought that each event could have an event length in frames, and each frame a uint is increased, if the uint matches the length, it is popped from the vector. I just wasnt sure if doing it like this was the best way. Thanks
I would have each event instance have a method called isDone, or something like that. Then, for each frame, iterate through your events and: if (event.isDone()) { //remove the event } else { event.update(); } Doing it this way allows for easier changes in the future. Not all events will last for a fixed amount of time (this might not be true for your game), some might even depend on things other than the current frame. But in your eventBaseClass, you could define isDone as: return this.endFrame >= game.currentFrame; and override it in any events that you need to.
2,225,956
2,226,601
What is the sprintf() pattern to output floats without ending zeros?
I want to output my floats without the ending zeros. Example: float 3.570000 should be outputted as 3.57 and float 3.00000 should be outputted as 3.0 (so here would be the exception!)
A more efficient and (in my opinion) clearer form of paxdiablo's morphNumericString(). Sorry not compiled or tested. void morphNumericString( char *s ) { char *p, *end, *decimal, *nonzero; // Find the last decimal point and non zero character end = p = strchr(s,'\0'); decimal = nonzero = NULL; while( p > s ) { p--; if( !nonzero && *p!='0' ) { nonzero = p; } if( !decimal && *p=='.' ) { decimal = p; break; // nonzero must also be non NULL, so stop early } } // eg "4.3000" -> "4.3" if( decimal && nonzero && nonzero>decimal ) *(nonzero+1) = '\0'; // eg if(decimal) "4.0000" -> "4.0" // if(!decimal) "4" -> "4.0" else strcpy( decimal?decimal:end, ".0" ); }
2,225,980
2,225,996
Why does the following class have a virtual table?
Suppose I have a diamond inheritance situation as follows: class A{ public: virtual void foo(){}; }; class B: public virtual A{ public: virtual void foo(){}; }; class C: public virtual A{ public: virtual void foo(){}; }; class D: B, C{}; The last line yields a compilation error citing ambiguity. As I understand it, the problem is that the compiler doesn't know which foo to place in D's vtbl, but why would there even be a vtbl for D if it doesn't define any virtual functions of its own?
You're inheriting classes that contain virtual functions. Therefore, your class has virtual functions. It's as simple as that.
2,226,045
2,226,077
C++ decimal output formatting
i'm writing a double value to a file. The numeric value is written with a point as a decimal separator. I would like to use a comma. How i can do that?
The usual way is to use a locale with the decimal separator set to the comma. If your machine is configured for that generally, you can probably just use the nameless locale for it: std::cout.imbue(std::locale("")); std::cout << 12345.67;
2,226,052
2,226,100
How to allow derived class to call methods on other derived class? OO-design
Say I have something like -- this is just an example mind you. class Car { void accelerate(); void stop(); } class Person { void drive(Car car); } class Toyota : public Car { void accelerateUncontrollably(); } class ToyotaDriver : public Person { void drive(Car car) { // How to accelerateUncontrollably without dynamic cast? } } A couple things, Toyotas and ToyotaDriver go together, i.e. I can have a ToyotaFactory class which will return the driver and the car. So the pieces are interchangeable and used in different parts of the code but a Toyota and a ToyotaDriver go together.
My impression is that using a dynamic_cast is absolutely fine here. No need to avoid it.
2,226,118
2,226,179
One Valid Case of Exception leaving a Destructor
I'm working on a simple class to manage the lifetime of a HKEY. class Key { HKEY hWin32; public: Key(HKEY root, const std::wstring& subKey, REGSAM samDesired); Key(const Key& other); ~Key(); Key& operator=(const Key& other); Key& swap(Key& other); HKEY getRawHandle() { return hWin32; }; }; //Other Methods.... Key::~Key() { LONG errorCheck = RegCloseKey(hWin32); /* * I know it's generally bad to allow exceptions to leave destructors, * but I feel that if RegCloseKey() is going to fail, the application * should be terminated. (Because it should never fail.) */ if (errorCheck != ERROR_SUCCESS) WindowsApiException::Throw(errorCheck); } Is this valid reasoning? I don't see how else a failure of RegCloseKey() can be communicated to the callee.
The failure of RegCloseKey is more of an assert situation than an error that needs to be passed up the call chain. You want to sit up and take notice right away in debug builds, But what good is that failure information going to do the caller? What is he supposed to do about it?
2,226,147
2,226,182
How to know if the the value of an array is composed by zeros?
Hey, if you can get a more descriptive tittle please edit it. I'm writing a little algorithm that involves checking values in a matrix. Let's say: char matrix[100][100]; char *ptr = &matrix[0][0]; imagine i populate the matrix with a couple of values (5 or 6) of 1, like: matrix[20][35]=1; matrix[67][34]=1; How can I know if the binary value of an interval of the matrix is zero, for example (in pseudo code) if((the value from ptr+100 to ptr+200)==0){ ... // do something I'm trying to pick up on c/c++ again. There should be a way of picking those one hundred bytes (which are all next to each other) and check if their value is all zeros without having to check on by one.(considering char is one byte)
You can use std::find_if. bool not_0(char c) { return c != 0; } char *next = std::find_if(ptr + 100, ptr + 200, not_0); if (next == ptr + 200) // all 0's You can also use binders to remove the free function (although I think binders are hard to read): char *next = std::find_if(ptr + 100, ptr + 200, std::bind2nd(std::not_equal_to<char>(), 0)); Dang, I just notice request not to do this byte by byte. find_if will still do byte by byte although it's hidden. You will have to do this 1 by 1 although using a larger type will help. Here's my final version. template <class T> bool all_0(const char *begin, const char *end, ssize_t cutoff = 10) { if (end - begin < cutoff) { const char *next = std::find_if(begin, end, std::bind2nd(std::not_equal_to<char>(), 0)); return (next == end); } else { while ((begin < end) && ((reinterpret_cast<uintptr_t>(begin) % sizeof(T)) != 0)) { if (*begin != '\0') return false; ++begin; } while ((end > begin) && ((reinterpret_cast<uintptr_t>(end) % sizeof(T)) != 0)) { --end; if (*end != '\0') return false; } const T *nbegin = reinterpret_cast<const T *>(begin); const T *nend = reinterpret_cast<const T *>(end); const T *next = std::find_if(nbegin, nend, std::bind2nd(std::not_equal_to<T>(), 0)); return (next == nend); } } What this does is first checks to see if the data is long enough to make it worth the more complex algorithm. I'm not 100% sure this is necessary but you can tune what is the minimum necessary. Assuming the data is long enough it first aligns the begin and end pointers to match the alignment of the type used to do the comparisons. It then uses the new type to check the bulk of the data. I would recommend using: all_0<int>(); // 32 bit platforms all_0<long>(); // 64 bit LP64 platforms (most (all?) Unix platforms) all_0<long long>() // 64 bit LLP64 platforms (Windows)
2,226,227
2,226,262
Embedded C++ : to use exceptions or not?
I realize this may be subjective, so will ask a concrete question, but first, background: I have always been an embedded software engineer, but usually at Layer 3 or 2 of the OSI stack. I am not really a hardware guy. I have generally always done telecoms products, usually hand/cell-phones, which generally means something like an ARM 7 processor. Now I find myself in a more generic embedded world, in a small start-up, where I might move to "not so powerful" processors (there's the subjective bit) - I cannot predict which. I have read quite a bit about debate about exception handling in C++ in embedded systems and there is no clear cut answer. There are some small worries about portability and a few about run-time, but it mostly seems to come down to code size (or am i reading the wrong debates?). Now I have to make the decision whether to use or forego exception handling - for the whole company, for ever (it's going into some very core s/w). That may sound like "how long is a piece of string", but someone might reply "if your piece of string is an 8051, then don't. If, OTOH, it is ...". Which way do I jump? Super-safe & lose a good feature, or exceptional code and maybe run into problems later?
In terms of performance, my understanding is that exceptions actually reduce the size and increase the performance of the normal execution paths of code, but make the exceptional/error paths more expensive. (often a lot more expensive). So if your only concern is performance, I would say don't worry about later. If today's CPU can handle it, then tomorrows will as well. However. In my opinion, exceptions are one of those features that require programmers to be smarter all of the time than programmers can be reasonably be expected to be. So I say - if you can stay away from exception based code. Stay away. Have a look at Raymond Chen's Cleaner, more elegant, and harder to recognize. He says it better than I could.
2,226,252
2,226,336
Embedded C++ : to use STL or not?
I have always been an embedded software engineer, but usually at Layer 3 or 2 of the OSI stack. I am not really a hardware guy. I have generally always done telecoms products, usually hand/cell-phones, which generally means something like an ARM 7 processor. Now I find myself in a more generic embedded world, in a small start-up, where I might move to "not so powerful" processors (there's the subjective bit) - I cannot predict which. I have read quite a bit about debate about using STL in C++ in embedded systems and there is no clear cut answer. There are some small worries about portability, and a few about code size or run-time, but I have two major concerns: 1 - exception handling; I am still not sure whether to use it (see Embedded C++ : to use exceptions or not?) 2 - I strongly dislike dynamic memory allocation in embedded systems, because of the problems it can introduce. I generally have a buffer pool which is statically allocated at compile time and which serves up only fixed size buffers (if no buffers, system reset). The STL, of course, does a lot of dynamic allocation. Now I have to make the decision whether to use or forego the STL - for the whole company, for ever (it's going into some very core s/w). Which way do I jump? Super-safe & lose much of what constitutes C++ (imo, it's more than just the language definition) and maybe run into problems later or have to add lots of exception handling & maybe some other code now? I am tempted to just go with Boost, but 1) I am not sure if it will port to every embedded processor I might want to use and 2) on their website, they say that they doesn't guarantee/recommend certain parts of it for embedded systems (especially FSMs, which seems weird). If I go for Boost & we find a problem later ....
Super-safe & lose much of what constitutes C++ (imo, it's more than just the language definition) and maybe run into problems later or have to add lots of exception handling & maybe some other code now? We have a similar debate in the game world and people come down on both sides. Regarding the quoted part, why would you be concerned about losing "much of what constitutes C++"? If it's not pragmatic, don't use it. It shouldn't matter if it's "C++" or not. Run some tests. Can you get around STL's memory management in ways that satisfy you? If so, was it worth the effort? A lot of problems STL and boost are designed to solve just plain don't come up if you design to avoid haphazard dynamic memory allocation... does STL solve a specific problem you face? Lots of people have tackled STL in tight environments and been happy with it. Lots of people just avoid it. Some people propose entirely new standards. I don't think there's one right answer.
2,226,291
2,228,298
Is it possible to create and initialize an array of values using template metaprogramming?
I want to be able to create an array of calculated values (let's say for simplicity's sake that I want each value to be the square of it's index) at compile time using template metaprogramming. Is this possible? How does each location in the array get initialized? (Yes, there are easier ways to do this without resorting to template metaprogramming, just wondering if it's possible to do this with an array.)
Although you can't initialise an array in-place like that, you can do almost the same thing by creating a recursive struct: template <int I> struct squared { squared<I - 1> rest; int x; squared() : x((I - 1) * (I - 1)) {} }; template <> struct squared<1> { int x; squared() : x(0) {} }; Then later in your code you can declare: squared<5> s; and the compiler will indeed create a struct containing 5 ints: 0, 1, 4, 9, 16. A couple of notes: My interpretation of the C++ standard is that it stops short of guaranteeing that this struct will be laid out identically to an array. While it is a POD type, and POD types are guaranteed to be laid out "contiguously" in memory (1.8/5) with the first member at offset 0 (9.2/17) and later members at higher addresses (9.2/12), and arrays are also laid out "contiguously" (8.3.4/1), the standard doesn't say that arrays are layout-compatible with such structs. However, any sane compiler will lay these objects out identically. [EDIT: As ildjarn points out, the presence of a user-defined constructor actually makes this class non-aggregate and therefore non-POD. Again, any sane compiler will not allow this to affect its layout.] C++ requires that even an empty struct be at least 1 byte long. If it did not, we could go with a slightly cleaner formulation in which the base case of the recursion was I == 0 and we didn't subtract 1 from I for the calculations. It would be nice if we could place this struct inside a union with an array of the appropriate size, to make it easy to access the members. Unfortunately, C++ bans you from including an object in a union if that object has a non-trivial constructor. So the easiest way to get at the ith element is with a good old-fashioned cast: squared<5> s; cout << "3 squared is " << reinterpret_cast<int*>(&s)[3] << endl; If you wanted, you could write an overloaded operator[]() function template to make this prettier.
2,226,412
2,226,420
Not Able To Use STL's string class
Encountered this problem before but forgot how I solved it. I want to use the STL string class but the complier is complaining about not finding it. Here is the complete .h file. #ifndef MODEL_H #define MODEL_H #include "../shared/gltools.h" // OpenGL toolkit #include <math.h> #include <stdio.h> #include <string> #include <iostream> #include "Types.h" class Model { public: obj_type_ptr p_object; char Load3DS (char *p_filename); int LoadBitmap(char *filename); int num_texture; string fun("alex"); Model(char* modelName, char* textureFileName); }; #endif
You want to be using std::string, yes? You're just using string. Which works if you have a using namespace ... declaration, but isn't really a good idea in a header file.
2,226,675
2,226,708
How do you use sets and gets in C++?
I've used them in java and didn't seem to have too many issues, but I'm not grasping them very well in C++. The assignment is: Write a class named Car that has the following member variables: year. An int that holds the car's model year. make. A string that holds the make of the car. speed. An int that holds the car's current speed. In addition, the class should have the following member functions. Constructor. The constructor should accept the car's year and make as arguments and assign these values to the object's year and make member variables. The constructor should initialize the speed member variable to 0. Accessors. Appropriate accessor functions should be created to allow values to be retrieved from an object's year, make, and speed member variables. accelerate. The accelerate function should add 5 to the speed member variable each time it is called. brake. The brake function should subtract 5 from the speed member variable each time it is called. Demonstrate the class in a program that creates a Car object, and then calls the accelerate function five times. After each call to the accelerate function, get the current speed of the car and display it. Then, call the brake function five times. After each call to the brake function, get the current speed of the car and display it. So far this is what I have but I'm reasonably certain I'm completely wrong. If anyone has any advice I'd really appreciate it, thanks! #include<iostream> #include<string> using namespace std; class Car { public: int year; string make; int speed; Car() { setYear(newYear); setMake(newMake); setSpeed(0); } void setYear(int newYear) { year = newYear; } void setMake(string newMake) { make = newMake; } int getYear() { return year; } string getMake() { return make; } int accelerate(int speed) { return (speed+5); } int brake(int speed) { return (speed-5); } }; int main() { return 0; } PS: The main has return 0; purely as a place holder just trying to understand the whole "get and set" thing.
Generally your get/set functions should work fine. Some other comments: The year, make and speed variables should probably be private, else there wouldn't really be any need to have get/set functions for them since the variables could as well be changed directly. Probably there shouldn't be any set-functions at all. I don't think it is intended to be possible change the year or make or set the speed directly. The constructor should take newYear and newMake as parameters. accelerate() and break() should change the speed saved in the car object, not just return a value different from speed. using namespace std; can import lots of unexpected names to the global namespace and it is often preferable to use explicitly qualified names like std::string instead.
2,226,691
2,226,905
Creating multicast events with std::tr1::function (or boost::function)
I'm attempting to create C#-like multicast delegates and events using features from TR1. Or Boost, since boost::function is (mostly) the same as std::tr1::function. As a proof of concept I tried this: template<typename T1> class Event { private: typedef std::tr1::function<void (T1)> action; std::list<action> callbacks; public: inline void operator += (action func) { callbacks.push_back(func); } inline void operator -= (action func) { callbacks.remove(func); } void operator ()(T1 arg1) { for(std::list<action>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++) { (*iter)(arg1); } } }; Which works, sort of. The line callbacks.remove(func) does not. When I compile it, I get the following error: error C2451: conditional expression of type 'void' is illegal Which is caused by line 1194 of the list header, which is in the remove function. What is causing this?
I think this is exactly same problem: comparing-stdtr1function-objects (basically you can't compare functors, that's why erase or anything using operator== won't work)
2,226,859
2,226,873
Is there a way in windows to know if a process is not responding?
Is there a way to know when a process is hung? is there a win32 call for this?
You send it a WM_NULL with SendMessageTimeout(). If that times out after something like a second or three, it's not responding (though it might eventually, of course).
2,226,912
2,227,013
Can I separate C++ main function and classes from Objective-C and/or C routines at compile and link?
I have a small C++ application which I imported Objective-C classes. It works as Objective-C++ files, .mm, but any C++ file that includes a header which may end up including some Objective-C header must be renamed to a .mm extension for the proper GCC drivers. Is there a way to write either a purely C++ wrapper for Objective-C classes or can I separate the Objective-C objects out somehow and just link them separately? Maybe even if the Objective-C classes became a small library I could statically re-link at compile time? The problem is that this code is cross-platform, and it is more difficult to compile on systems that normally do not use Objective-C (i.e. not Macs). Even though preprocessor commands restrict any implementation of Objective-C code on Windows or Linux, the original code still has .mm extensions and GCC still treats the code as Objective-C++.
Usually you simply wrap your Objective-C classes with C++ classes by e.g. using opaque pointers and forwarding calls to C++ methods to Objective-C methods. That way your portable C++ sources never have to see any Objective-C includes and ideally you only have to swap out the implementation files for the wrappers on different platforms. Example: // c++ header: class Wrapper { struct Opaque; Opaque* opaque; // ... public: void f(); }; // Objective-C++ source on Mac: struct Wrapper::Opaque { id contained; // ... }; void Wrapper::f() { [opaque->contained f]; } // ...
2,226,927
2,227,022
Should I use a single header to include all static library headers?
I have a static library that I am building in C++. I have separated it into many header and source files. I am wondering if it's better to include all of the headers that a client of the library might need in one header file that they in turn can include in their source code or just have them include only the headers they need? Will that cause the code to be unecessary bloated? I wasn't sure if the classes or functions that don't get used will still be compiled into their products. Thanks for any help.
In general, when linking the final executable, only the symbols and functions that are actually used by the program will be incorporated. You pay only for what you use. At least that's how the GCC toolchain appears to work for me. I can't speak for all toolchains. If the client will always have to include the same set of header files, then it's okay to provide a "convience" header file that includes others. This is common practice in open-source libraries. If you decide to provide a convenience header, make it so that the client can also choose to include specifically what is needed. To reduce compile times in large projects, it's common practice to include the least amount of headers as possible to make a unit compile.
2,226,962
2,226,976
Mixed I/O operations on single socket
I am thinking to write a simple wrapper class for socket in C++. I wonder if there is a need to have concrete class specific to I/O type, such as TcpSyncSocket and TcpAsyncSocket. Thus I would like to know how often do you guys find yourself in need to have mixture of both kind I/O operations on single socket. While I do not have extensive experience in doing socket programming, probably I will drop the idea if this is simply the norm. Thanks.
I've never written nor seen mixed use sync vs. async sockets. Ordinarily the usage is dependent on the program's organization, and that doesn't normally change throughout the lifetime of a socket..
2,226,968
2,226,990
Is C++ built on top of C?
Does C++ code gets converted to C before compilation ?
A few C++ compilers (the original cfront, Comeau C++) use C as an intermediate language during compilation. Most C++ compilers use other intermediate langauges (e.g. llvm). Edit: Since there seems to be some misunderstanding about the history: "C with classes" started out using a preprocessor called "Cpre". At that time, it was seen strictly as a dialect of C, not a separate language in itself. In December 1983, people were starting to view it as a separate language, and the name C++ was invented. As it happens, development of cfront started in April 1983, so a reasonably usable version became available (to a select few) just about the same time as the name "C++" came into use. This appears to be mostly coincidence though. As far as producing C as its output, that was really quite common on Unix. Just for example, the Berkeley Pascal compiler and at least a couple of Fortran compilers also produced C as their output. There is, however, a huge difference between Cpre and Cfront. Although both produced C as their output, Cpre did virtually no syntax checking of its own -- it looked for a few specific things, and did a relatively mechanical translation on them. It wasn't until the C compiler looked at the result that real syntactical analysis was done. If your code contained a syntax error, it was almost certain that it wouldn't be caught until the C compiler parsed the output from Cpre. Cfront, however, did full syntactical analysis of the source code itself, so (short of a bug in its code generator) you'd never see a syntax error from the C compiler. The C compiler was simply used as a code generator so nobody needed to rewrite CFront to accommodate different processors, object file formats, etc. If you want to get into more detail, chapter 2 of The Design and Evolution of C++ is devoted almost entirely to the "C with Classes" time frame (and there are various other details about it spread throughout the book).
2,227,029
2,238,919
#pragma once equivalent for c++builder
Is there anything equivalent to #pragma once for Codegear RAD Studio 2009? I am using the precompiled header wizard and I would like to know if it is still necessary to use include guards when including header files?
Support for #pragma once was added in C++Builder 2010 In C++Builder 2009 and earlier, the unknown pragma will simply be ignored. I would suggest using #ifndef X #define X //code #endif style header guards in the versions of C++Builder that do not support #pragma once.
2,227,038
2,227,089
Using 7-zip via system() in c++
I'm trying to use 7-Zip to zip up a file via the system() function in C++ on a windows XP machine. I tried: (formatted to be what system() would have received) "C:\Program Files\7-Zip\7z.exe" a -tzip "bleh.zip" "addedFile.txt" which spat the error 'C:\Program' is not recognized as an internal or external command, operable program or batch file. I've tried several similar alternatives but have not yet found a solution. I want to try to run it straight from its install directory so that as long as a user has 7-Zip installed it will be able to function. This is for an in house utility application. EDIT: as requested these are the actual lines of code: std::string systemString = "\"C:\\Program Files\\7-Zip\\7z.exe\" a -tzip \"" + outDir + projectName + ".zip" + "\" \""; //... std::string finalSystemString = systemString + *i + "\""; system( finalSystemString.c_str() ); *i is an iterator to a particular file that is getting added.
it looks like something is stripping the quotes around the first argument. You could play around with extra quotes to try and fix this, or you can get the MS-DOS compatible short path name for 7z.exe with the Win32 API GetShortPathName The short path will not have spaces in it, it will be something like "C:\PROGRA~1\7-ZIP\7Z.EXE"
2,227,065
2,227,284
Need insight into how manifest is being generated for C++ program
When I run an executable that I built, I get the following error: The system cannot execute the specified program My immediate thought was that it was a dependency problem with one of the VC8.0 re-distributable DLLs (msvcr80d.dll et al.). We have had a few problems with patched versions of these DLLs affecting our programs. When I opened my executable under Dependency Walker, the following errors are displayed: Error: The Side-by-Side configuration information in "w:\MYPROGRAM.EXE.manifest" contains errors. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem (14001). Warning: At least one delay-load dependency module was not found. Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module. If I open up the manifest file for my executable, it has the following in it: <?xml version='1.0' encoding='UTF-8' standalone='yes'?> <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50727.762' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50727.4053' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> </assembly> It seems to have 2 copies of the Microsoft.VC80.DebugCRT dependent assembly in it. The 8.0.50727.4053 version of the assembly is not in my side-by-side configuration (I believe this version comes with a Visual Studio patch which is not installed). If I remove this assembly from the manifest file, the executable runs fine. However, when I re-build my application, the manifest is re-generated and the extra dependency is added again. What causes this dependency to be added to the manifest? I'm guessing it has something to do with another DLL which my application depends on being built on another PC with a different set of re-distributable DLLs, but I want to confirm this. Update: I have tried a lot of the suggestions in this blog post, without a lot of luck. One thing that is strange is that the manifest generated when I do a Release build doesn't include the 8.0.50727.4053 entry, but the Debug build does.
You are right. Security update for Visual C++ 2005 SP1 forces your app to use a newer version of CRT and MFC (8.0.50727.4053 instead of 8.0.50727.762). As it maybe compatible, it's better to use the new one. You should distribute with your app also the vcredist_x86.exe. As I now, VS C++ does not scan for dependency, so the manifest is generated from the core VS (you can manualy control it by project settings). I thing the VS update was installed on the development PC, so VS reflect it in the manifest.
2,227,124
2,227,394
Texturing Not Working
I am using code from this site: http://www.spacesimulator.net/tut4_3dsloader.html It works in their example project but when I placed the code into a class for easier and more modular use, the texture fails to appear on the object. I've double checked to make sure the texture ID is correct by debugging them side by side. On my project I get a blank white object while the example works fine. Are there ANY ways to tell what is going on under the hood? Any error functions I can call that can give me some hint to what's going on? Right now I am just guessing. (Yes I have enabled 2D textures. Thanks SO!
glGetLastError() or glGetError() what ever it is... make sure glEnable(GL_TEXTURE_2D); and make sure your texture is bound using glBindTexture make sure there are texture coords being rendered and that they are right (if they are all the same, or all the same uninitialized value you will get one colour across the whole thing) ummm.... make sure your texture matrix isn't screwed... glMatrixMode(GL_TEXTURE); glLoadIdentity(); if your not using it... then ummm.... make sure the data getting loaded in when you load the texture is right. make sure if you have mipmapping on that you are loading in the mip maps, otherwise if you have the object at a different zoom you might not get any texture... umm... thats all I can think of off the top of my head. EDIT: ooo, I just remembered one that caught me up once: by changing the structure, you may have changed the initialization order of the app. MAKE SURE you aren't trying to load textures BEFORE you initialize opengl (with the device contexts or whatever, I was under windows)
2,227,173
2,227,212
Is it okay to use "delete this;" on an object that inherits from a Thread class?
In general, if you have a class that inherits from a Thread class, and you want instances of that class to automatically deallocate after they are finished running, is it okay to delete this? Specific Example: In my application I have a Timer class with one static method called schedule. Users call it like so: Timer::schedule((void*)obj, &callbackFunction, 15); // call callbackFunction(obj) in 15 seconds The schedule method creates a Task object (which is similar in purpose to a Java TimerTask object). The Task class is private to the Timer class and inherits from the Thread class (which is implemented with pthreads). So the schedule method does this: Task *task = new Task(obj, callback, seconds); task->start(); // fork a thread, and call the task's run method The Task constructor saves the arguments for use in the new thread. In the new thread, the task's run method is called, which looks like this: void Timer::Task::run() { Thread::sleep(this->seconds); this->callback(this->obj); delete this; } Note that I can't make the task object a stack allocated object because the new thread needs it. Also, I've made the Task class private to the Timer class to prevent others from using it. I am particularly worried because deleting the Task object means deleting the underlying Thread object. The only state in the Thread object is a pthread_t variable. Is there any way this could come back to bite me? Keep in mind that I do not use the pthread_t variable after the run method finishes. I could bypass calling delete this by introducing some sort of state (either through an argument to the Thread::start method or something in the Thread constructor) signifying that the method that is forked to should delete the object that it is calling the run method on. However, the code seems to work as is. Any thoughts?
I think the 'delete this' is safe, as long as you don't do anything else afterwards in the run() method (because all of the Task's object's member variables, etc, will be freed memory at that point). I do wonder about your design though... do you really want to be spawning a new thread every time someone schedules a timer callback? That seems rather inefficient to me. You might look into using a thread pool (or even just a single persistent timer thread, which is really just a thread pool of size one), at least as an optimization for later. (or better yet, implement the timer functionality without spawning extra threads at all... if you're using an event loop with a timeout feature (like select() or WaitForMultipleObjects()) it is possible to multiplex an arbitrary number of independent timer events inside a single thread's event loop)
2,227,185
2,227,259
Threadsafe logging inside C++ Shared library
I have implemented multithreaded shared library in C++ (For Linux and Windows). I would like to add logging mechanism inside the library itself. The caller of the library is not aware of that. The log file would be same so I am wondering how could I design the thread safe logging if multiple process is using my library and trying to open and log into the same log file. Any suggestions?
Use file locking. I believe fcntl is POSIX compliant so should work on Windows too. Does your code use Posix calls? With fcntl, you should be able to lock a specific range of bytes. So if you seek to end and try to lock out the amount of bytes you are about to write, it should be pretty fast. To obtain the lock, you can probably spin, relinquishing the CPU for a small amount of time, if you don't obtain the lock.
2,227,221
2,232,149
How do you have a window that has no icon in the tasktray?
I found the windows style WS_EX_TOOLWINDOW but this changes the title bar. Is there a way to not have the tasktray icon but keep the normal window titlebar?
You usually do want to do this if you have added an alternate means to restore the window - for example placing an icon in the notification tray. The usual way of ensuring the taskbar does not display your window is to create it with a hidden parent window. Whenever a window has a parent, the parent window is used to create the button - hidden windows are not shown on the taskbar. Also, WS_EX_APPWINDOW should be removed as that performs the opposite hint to the shell and forces the window onto the taskbar even if it would otherwise not have been shown.
2,227,589
2,228,435
How can I dump a MySQL database from mysql c library
I want to archive my database of mysql. Kindly give me some guide lines how I can make it possible, I am using mysql c library for insertion and selection etc. I dont know how to use dump command.
Use SHOW TABLES and DESCRIBE tbl_name queries to obtain structure of database and tables. Then, use SELECT to fetch data and proceed it to your output according to the structure.
2,227,594
2,227,710
Ncurses User Pointer
I'm trying to learn ncurses, and I'm reading the terrific guide here, but the example at user pointers does not compile. I get this error when I try to compile. menu.cpp: In function 'int main()': menu.cpp:44: error: invalid conversion from 'void (*)(char*)' to 'void*' menu.cpp:44: error: initializing argument 2 of 'int set_item_userptr(ITEM*, void*)' menu.cpp:70: error: invalid conversion from 'void*' to 'void (*)(char*)' Also, you probably need to add cstdlib and cstring for that to compile with strlen and calloc. I don't know much about void pointers, so some help fixing the example would be very appreciated. Thanks
From reading the manual page: #include <menu.h> int set_item_userptr(ITEM *item, void *userptr); void *item_userptr(const ITEM *item); DESCRIPTION Every menu item has a field that can be used to hold application-specific data (that is, the menu-driver code leaves it alone). These functions get and set that field. userptr is user-specific data that you should supply to set_item_userptr(). If you don't want to supply any data, you should supply NULL. Looks like you are calling set_item_userptr() with a pointer to a function as its second argument. It is not guaranteed that you can convert a function-pointer to void * and back portably, either in C or in C++ (C++ requires a cast when converting a void * to any other pointer type). Without knowing what you are trying to do, if you really need to pass a function pointer, you should cast it to the appropriate type: int ret = set_item_userptr(item, reinterpret_cast<void *>(ptr)); void (*pf)(char*); pf = reinterpret_cast<void (*)(char *)>(item_userptr(item)); but it's not guaranteed to work. You should do something else, like having a struct that contains the function pointer, and passing a pointer to the struct to set_item_userptr().
2,227,727
2,227,746
How to use Loki's Pimpl implementation?
Link to source code of Loki Pimpl header. I am not able to find any documentation on how to use the same, can any one explain how to use. And what does the following function in the header do. PimplOwner ImplOf PimplOf RimplOf
This page has most of the information you need
2,227,811
2,227,831
C++ templates problem
I am new to templates in c++. i was trying some small programs. CPP [80]> cat 000001.cpp 000001.hpp #include <iostream> #include <string> #include "000001.hpp" int main() { int i = 42; std::cout << "max(7,i): " << ::max(7,i) << std::endl; double f1 = 3.4; double f2 = -6.7; std::cout << "max(f1,f2): " << ::max(f1,f2) << std::endl; std::string s1 = "mathematics"; std::string s2 = "math"; std::cout << "max(s1,s2): " << ::max(s1,s2) << std::endl; } template <typename T> inline T const& max (T const& a, T const& b) { return a < b ? b : a; } when i compile this program: i get an error below: CPP [78]> /opt/aCC/bin/aCC -AA 000001.cpp Error (future) 229: "/opt/aCC/include_std/string.cc", line 164 # "Ambiguous overloaded function call; a function match was not found that was strictly best for ALL arguments. Two functions that matched best for some arguments (but not all) were "const unsigned long &max<unsigned long>(const unsigned long &,const unsigned long &)" ["000001.hpp", line 2] and "const unsigned long &std::max<unsigned long>(const unsigned long &,const unsigned long &)" ["/opt/aCC/include_std/algorithm", line 1762]." Choosing "const unsigned long &max<unsigned long>(const unsigned long &,const unsigned long &)" ["000001.hpp", line 2] for resolving ambiguity. _C_data = _C_getRep (max (_RW::__rw_new_capacity (0, this), ^^^ Warning: 1 future errors were detected and ignored. Add a '+p' option to detect and fix them before they become fatal errors in a future release. Behavior of this ill-formed program is not guaranteed to match that of a well-formed program Could nybody please tell me what exactly the error is?
The code you've posted compiles just fine, there must be something else that is wrong inside "000001.hpp". Can you post the contents of that file too? Edit: If you do as avakar says but the problem persists, that must be due to some problem with your compiler. There are two obvious workarounds I can think of: rename your max function to something else, or put it in a namespace: namespace Foo { template <typename T> inline T const& max (T const& a, T const& b) { return a < b ? b : a; } } int main() { int i = 42; std::cout << "max(7,i): " << Foo::max(7,i) << std::endl; double f1 = 3.4; double f2 = -6.7; std::cout << "max(f1,f2): " << Foo::max(f1,f2) << std::endl; std::string s1 = "mathematics"; std::string s2 = "math"; std::cout << "max(s1,s2): " << Foo::max(s1,s2) << std::endl; }
2,227,926
2,228,030
What technique would you recommend when reviewing C++ for an interview?
I've got about 2/3 years C++ experience but I've spent most of my career doing Java. I'm about to go for an interview for a C++ programming role and I've been thinking about the best way to brush up my C++ to make sure I don't get caught out by any awkward questions. What would you recommend?
If you have enough time try to write an application using C++ - go over the basics so when you'll be asked to show coding skills you'll be able to write code fluently. I've noticed that during C++ centric interviews it is common practice to ask question about how it works: How virtual methods are implemented? What happens when you call new - how memory is allocated? What is the difference between struct and class? Why should you mark your class d'tor as virtual? I guess a good way to learn all those is to read a good C++ book - if you have the stomach for it you can read Stroustrup book - but there bound to be other books just as good (with less pages in them). Have a look at the C++ Style and Technique FAQ
2,227,939
2,228,092
Using a vector data structure - design and syntax questions
I have some basic C++ design/syntax questions and would appreciate your reply. I have N number of regions Each region needs to store information about an object "element" i.e. I want to achieve something like this: region[i].elements = list of all the elements for region i. Question 1: Does the following syntax (see code below) / design look correct. Am I missing anything here? EDIT The instances of struct elem are created by some other class and its memory deallocation is handles by that class only I just want to access that object and its members using reg[i].elements list (vector) ... so, how should I add these element objects to the vector "elements" in class Region? //Already have this stucture that I need to use struct elemt { int* vertex; int foo1; double foo2; }; class Region{ public: // I am not sure what should be the syntax here! // is it correct? std::vector <elemt*> elements; } // Following is the constructor of "class A" A::A(){ // --header file defines: Region *reg; // Let numOfRegions be a class variable. ( changes based on "Mac"'s suggestion) numOfRegions = 100; //allocate memory: reg = new Region[numOfRegions]; } A::~A(){ delete [] reg; reg = NULL; } A::doSomething(){ // here I want to append the elements to the vector // Let i be region 10. // Let e1 be an element of "struct elemt" that needs to be added reg[i].elements.push_back(e1); } Question 2: Is the syntax in doSomething() correct? Later I want to run an iterator over all the elements in reg[i] and want to access, e1->foo1, e1->foo2 and like that. Question 3: In do something method, how do I ensure that e1 is not already in the "elements" UPDATE Corrected some syntax errors, and hopefully fixed memory leak noticed by user 'Mac. '
First of all get rid of the memory leak from the code. A::A(int numOfRegions = 100){ m_reg = new Region[numOfRegions]; // define Region *m_reg in the class } A::~A(){ delete [] m_reg; m_reg = NULL; } You are allocating memory in the constructor and storing return address in local variable and it ll get destroyed when its scope is over . You should store the base address so that you can delete it .
2,228,211
2,228,595
Problem with SQLBindParameter on IN/OUT parameter
I have the following parameter being bound for calling a SQL procedure: TCHAR str[41]; SQLINTEGER cb; SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT_OUTPUT, SQL_C_TCHAR, SQL_C_TCHAR, 40, 0, str, 0, &cb); When I loop through str after calling the query I can see the result is there, but it's not quite right: std::stringstream ss; ss<<"{"; for(int i=0;i<41;++i) { ss<<(int)str[i]; if(i<40)ss<<','; } ss<<"}"<<endl<<"{"; for(int i=0;i<41;++i) { if(str[i]) ss<<"'"<<str[i]<<"'"; else ss<<"null"; if(i<40)ss<<','; } ss<<"}"<<endl; cout<<ss.str(); {53,55,56,49,53,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,0} {'5','7','8','1','5',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',null} For whatever reason, str is being padded with spaces. I know the SQL procedure is actually returning "57815" from testing it in isolation. Any ideas what's going on and how to resolve it? The cb value is set to 40 after the SQL call is executed.
If the SQL database field is of type CHAR, it will be space padded (and if it isn't a CHAR, what type is it?). This is expected behaviour. If it isn't are you sure that SQL_C_TCHAR is the type you really want - it isn't listed on this MSDN page.
2,228,275
2,228,309
Java generics and JNI
Is it possible to call a native CPP function using JNI which takes generic arguments? Something like the following: public static native <T, U, V> T foo(U u, V v); And then call it like: //class Foo, class Bar, class Baz are already defined; Foo f = foo(new Bar(), new Baz()); Can anyone please provide me with a sample which is actually doing this or some tutorial on the net which does this? I am asking because in my CPP JNI function (called by JVM), I get unsatisfied link error. CPP Code follows: JNIEXPORT jobject JNICALL Java_Processor_process (JNIEnv *env, jclass processor_class, jobject obj1, jobject obj2) { jclass bar_class = env->FindClass("Bar"); jmethodID getFooMethod = env->GetMethodID(bar_class, "getFoo", "()Ljava/lang/Object;"); //getFoo() is defined as `public Foo getFoo();` in Bar.java return env->CallObjectMethod(obj1, getFooMethod); } EDIT: I have tried by modifying the code but now I am getting NoSuchMethodError: Java code: public static native <U, V> String foo(U u, V v); //... String str = foo(new Bar(), new Baz()); CPP code: JNIEXPORT jstring JNICALL Java_Processor_process (JNIEnv *env, jclass processor_class, jobject obj1, jobject obj2) { jclass bar_class = env->FindClass("Bar"); jmethodID getFooMethod = env->GetMethodID(bar_class, "getFoo", "()Ljava/lang/String;"); //getFoo() is now defined as `public String getFoo();` in Bar.java return env->CallObjectMethod(obj1, getFooMethod); } Does this mean that JNI has no support for generics or am I missing something?
There are numerous questions regarding type erasure on stack overflow (e.g. Get generic type of java.util.List), what you're looking to do is neither possible with JNI nor Java itself. The runtime type signature of foo is (in both worlds, or actually, there is only one world) Object foo(Object u, Object v), which will do an implicit class cast on the return value to whatever type you call it with. As you might notice (and as mentioned in the comment to your question), there's no way for you to know what type T is. EDIT: By the way, the getFoo method is supposed to return 'Foo', so shouldn't you be doing jmethodID getFooMethod = env->GetMethodID(bar_class, "getFoo", "()LFoo;"); Come to think of it, your entire call sequence seems out of place... you've got a foo which is native, returning string. Now foo looks for getFoo in Bar, which returns 'Foo', and returns the result of that call directly, effectively trying to return a Foo (Foo getFoo() according to the comment) where string is expected.
2,228,354
2,228,371
Binary .dat file question in c++
I wanted to shrink the size of a large text file with float values into a binary .dat file, so I used (in c++): // the text stream std::ifstream fin(sourceFile); // the binary output stream std::ofstream out(destinationFile, std::ios::binary); float val; while(!fin.eof()) { fin >> val; out.write((char *)&val,sizeof(float)); } fin.close(); out.close(); Then, I wanted to read all the float values from the rpeviously created binary file into a array of float values. But when I try to read from this file I get an exception at the last line of code (the reading process): // test read std::ifstream fstream(destinationFile, std::ios::binary); __int64 fileSize = 0; struct __stat64 fileStat; if(0 == _tstat64(destinationFile, &fileStat)) { fileSize = fileStat.st_size; } //get the number of float tokens in the file size_t tokensCount = fileSize / sizeof(float); float* pBuff = new float[tokensCount]; fstream.read((char*)&pBuff, tokensCount * sizeof(float)); What am I doing wrong?
float* pBuff = new float[tokensCount]; fstream.read((char*)&pBuff, tokensCount * sizeof(float)); You are reading into the pBuff variable, not the buffer it points to. You mean: fstream.read((char*)pBuff, tokensCount * sizeof(float));
2,228,424
2,228,452
Objects of a class share same code segment for methods?
For example we have code class MyClass { private: int data; public: int getData() { return data; } }; int main() { MyClass A, B, C; return 0; } Since A, B and C are objects of MyClass, all have their own memory. My question is that, are all of these objects share same memory for methods of class ( getData() in this case) or all objects have separate code segment for each object.? Tnahks in advance....
Same. You could be interested in knowledge of how things in C++ are implemented under the hood.
2,228,492
2,228,530
vector declaration and size allocation
This is related to my other post. One of the suggestions here was to use vector for class Region.. as illustrated in the following code. I have a few more beginner questions -- a) How to allocate this vector a size = numOfRegions? Or do I really need to allocate a size to a vector? b) How do I insert objects of class Region to this vector<Region>? All these Region objects need to be managed by class A c) I am assuming I don't need to delete this vector in class A's distructor .. correct? struct elemt { int* vertex; int foo1; double foo2; }; class Region{ public: std::vector <elemt*> elements; int info; } class A{ public: std::vector<Region> reg; const int numOfRegions = 100; } A::A(){ // how to create and append Region object to vector std::vector<Region> reg ?? // Do I need to allocate size for this region vector? } A::~A(){ //do nothing // Do I need to delete vector<Region> reg here ?? } A::doSomething(){ // here I want to append the elements to the vector // Let i be region 10. // Let e1 be an element of "struct elemt" that needs to be added reg[i].elements.push_back(e1); }
Call vector.reserve if you know the size of your vector up front. This isn't required because push_back will resize the vector when needed vector.push_back(Region()); You don't have to delete member vector
2,228,533
2,228,694
Estimate the size of outputted dll/exe upfront?
currently I'm fixing some issues regarding to small outputted dll (I'm using Ribosome build system on Windows) so I'm wondering this: suppose project (C++) include source files whose total size is i.e. 100 KB and project also depends on i.e. 3 libraries, each about 100KB, what binary size should I expect after compiling and linking? Can I estimate this up front? p.s. assuming that this is release build with turned off any kind of optimization and source files contain pure code without any comments or similar Thanks
I don't think you can do an upfront estimation of the generated size. There is no correlation between the number of lines of code and size of the generated binary. Even in Release mode, the compiler can convert hude amount lines of codes into a small block of execution and the reverse is true.
2,228,612
2,228,653
Is null terminate() handler allowed?
In VC++7 if I do the following: void myTerminate() { cout << "In myTerminate()"; abort(); } int main( int, char** ) { set_terminate( &myTerminate ); set_terminate( 0 ); terminate(); return 0; } the program behaves exactly as if abort() was called directly which is exactly what default terminate() handler does. If I omit the set_terminate( 0 ); statement my terminate handler is being called. So calling set_terminate( 0 ) seems to have the effect of resetting the terminate() handler to default. Is this behavior specific to VC++7 only? Won't the program run into undefined behavior if I call set_terminate( 0 ) on some other implementation?
Looking into the standard reveals the following: terminate_handler set_terminate(terminate_handler f) throw(); 1 Effects: Establishes the function designated by f as the current handler function ... cut 2 Requires: f shall not be a null pointer. 3 Returns: The previous terminate_handler. Seems to be non-standard.
2,229,353
2,229,393
Function pointer with extra data
I have class which handles packages: typedef void (*FCPackageHandlerFunction)(FCPackage*); class FCPackageHandlers{ ... void registerHandler(FCPackage::Type type, FCPackageHandlerFunction handler); void handle(FCPackage* package); ... QHash<FCPackage::Type, FCPackageHandlerFunction> _handlers; }; Then I have a server class who receive packages. Now I want to register a function who handles the packages. But this function must have a instance of the server for other variables. So i try this: struct FCLoginHandler{ FCServer* server; FCLoginHandler(FCServer* server){ this->server = server; } void operator()(FCPackage* package){ std::cout << "Received package: " << package->toString().data() << "\n"; } }; ... FCServer::FCServer(){ _handlers.registerHandle(FCPackage::Login, FCLoginHandler(this)); } But then I get this error: error: no matching function for call to 'FCPackageHandlers::registerHandler(FCPackage::Type, FCLoginHandler)' note: candidates are: void FCPackageHandlers::registerHandler(FCPackage::Type, void (*)(FCPackage*)) Does anybody know the right solution?
You are trying to store a function object in a function pointer, and that's not possible. You should store a std::tr1::function instead: #include <functional> typedef std::tr1::function<void(FCPackage*)> FCPackageHandlerFunction; class FCPackageHandlers{ ... void registerHandler(FCPackage::Type type, FCPackageHandlerFunction handler); void handle(FCPackage* package); ... QHash<FCPackage::Type, FCPackageHandlerFunction> _handlers; }; There's a similar function class in Boost in case you don't have access to std::tr1 yet. Also, consider using boost::bind and a regular function to avoid the boilerplate of having to create your own function objects such as FCLoginHandler: void handle_FC_login(FCServer* server, FCPackage* package) { std::cout << "Received package: " << package->toString().data() << "\n"; // You can use server if you need it } FCServer::FCServer() { _handlers.registerHandle(FCPackage::Login, std::tr1::bind(&handle_FC_login, this, _1)); } std::tr1::bind is also available in Boost, and if you don't have access to that either you can always use std::bind2nd. EDIT: Since you can't modify the type of FCPackageHandlerFunction, your best shot might be to add another hash that stores data associated to each function pointer: typedef void (*FCPackageHandlerFunction)(FCPackage*); class FCPackageHandlers{ ... void registerHandler(FCPackage::Type type, FCPackageHandlerFunction handler, FCServer * func_data); void handle(FCPackage* package); ... QHash<FCPackage::Type, FCPackageHandlerFunction> _handlers; QHash<FCPackageHandlerFunction, FCServer*> _handler_func_data; }; // The server will be passed by the package handler which will // extract it from the _handler_func_data hash void handle_FC_login(FCServer* server, FCPackage* package) { std::cout << "Received package: " << package->toString().data() << "\n"; } FCServer::FCServer(){ _handlers.registerHandle(FCPackage::Login, &handle_FC_login, this ); } Presumably this is how you'll have to implement FCPackageHandlers::handle: void FCPackageHandlers::handle(FCPackage * package) { // Query function FCPackageHandlerFunction func = _handlers[package->GetType()]; // Query associated data FCServer * server = _handler_func_data[func]; // Call handler func(server, package); }
2,229,368
2,229,549
tr1::function WINAPI
How can I use tr1::function with WINAPI calling convention ? (at least in windows). I can use visual c++ 9 SP1 TR1 or BOOST's one... typedef void (WINAPI *GetNativeSystemInfoPtr)(LPSYSTEM_INFO); HMODULE h = LoadLibrary (_T("Kernel32.dll")); GetNativeSystemInfoPtr fp = (GetNativeSystemInfoPtr) GetProcAddress (h,"GetNativeSystemInfo"); SYSTEM_INFO info; fp(&info); //works! // This doesn't compile function< void WINAPI (LPSYSTEM_INFO) > fb = (GetNativeSystemInfoPtr) GetProcAddress (h,"GetNativeSystemInfo");
This compiles: #include <boost/function.hpp> #include <windows.h> int main(void) { typedef void (WINAPI *GetNativeSystemInfoPtr)(LPSYSTEM_INFO); HMODULE h = LoadLibrary (("Kernel32.dll")); GetNativeSystemInfoPtr fp = (GetNativeSystemInfoPtr) GetProcAddress (h,"GetNativeSystemInfo"); SYSTEM_INFO info; fp(&info); //works! boost::function< void (LPSYSTEM_INFO) > fb = (GetNativeSystemInfoPtr) GetProcAddress (h,"GetNativeSystemInfo"); SYSTEM_INFO info2; fb(&info2); return 0; } and the contents on "info" is the same that the one of "info2", so it seems to work. My understanding is that the parameter used to instantiate a boost::function is the signature of its operator(). It is not strictly related to the signature of the function of function object that it wraps. Otherwise, its benefits would be lost, since boost::function's utility is precisely to be able to wrap anything that is callable behind a uniform interface, regardless of the details of the final target's type.
2,229,381
2,229,413
Why does dynamic cast from class to subclass requires the class to be polymorphic?
As I understand it, what makes dynamic cast different from a static cast is its use of RTTI, and the fact that it fails if the dynamic type of a variable- when casting from base to derived- does not fit. But why does the class have to be polymorphic for that to be done if we have the RTTI anyway? EDIT: Since there was some confusion about the use of the word "polymorphic", here's the entry in cplusplus.com that prompted me to ask this: dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class. Therefore, dynamic_cast is always successful when we cast a class to one of its base classes: class CBase { }; class CDerived: public CBase { }; CBase b; CBase* pb; CDerived d; CDerived* pd; pb = dynamic_cast<CBase*>(&d); //ok: derived-to-base pd = dynamic_cast<CDerived*>(&b); //wrong: base-to-derived The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic. http://www.cplusplus.com/doc/tutorial/typecasting/
What sort of pointer could you use if there was no inheritance relationship? The only legal and sensible casts that can be performed between pointers to objects of different types (ignoring const casts) are within the same inheritance hierarchy. Edit: To quote BS from the D&E book on dynamic_cast, section 14.2.2.2: Further, a class with virtual functions is often called a polymorphic class and polymorphic classes are the only ones that can be safely manipulated via a base class ... From a programming point of view, it therefore seems natural to provide RTTI for polymorphic types only. My emphasis.
2,229,495
2,233,147
Cannot get a proper Vista / 7 theme for toolbar with wxWidgets
I cannot get a proper theme for toolbars in Vista / 7 with wxWidgets (c++). For some unknown reason, I get gray bar now (as you can see here). I want it to get this look instead. I've linked against comctl32.lib (=> 5.82) and UXTHEME is on. Here's the code: #include <wx/wx.h> class TestAppFrame: public wxFrame { public: TestAppFrame(wxWindow *parent, wxWindowID id = wxID_ANY, const wxString &title = wxT("Test"), const wxPoint &position = wxDefaultPosition, const wxSize &size = wxSize(373, 206), long style = wxDEFAULT_FRAME_STYLE | wxTAB_TRAVERSAL) : wxFrame(parent, id, title, position, size, style) { wxToolBar *tb = CreateToolBar(wxNO_BORDER | wxHORIZONTAL | wxTB_FLAT); tb->Realize(); SetToolBar(tb); } }; class TestApp: public wxApp { public: bool OnInit() { if (!wxApp::OnInit()) return false; wxInitAllImageHandlers(); TestAppFrame *frame = new TestAppFrame(NULL); frame->Show(true); return true; } }; IMPLEMENT_APP(TestApp) What am I doing wrong here? Best regards, nhaa123
The gradient rebar-like background is actually inappropriate for toolbars under Vista/7, if you look at any native applications using toolbars and not rebars or ribbons (which are, admittedly, a bit hard to find nowadays) you can see that they have the same grey background so we decided that this was the correct thing to do. You should be able to paint the background of the toolbar on your own in EVT_ERASE_BACKGROUND event but by default wx tries to behave conforming to the platform standards and in this case this means not using any gradients.
2,229,544
2,229,746
Implementing file locks to make a copy a file
Develop a C program for file-copy where two processes work together to complete the task: Parent process receives source filename and destination filename from command line. It opens the source file in read mode. Use shared lock on the source file in both the processes. Use exclusive lock on the destination file. Do read/write operations in 256 byte blocks. You should lock as small portion of the file as possible at one time. How do i got about when to check locks and when to put locks? I am not able to find a good resource which contains example. I tried reading it from "Beej's guide to IPC", but it doesnt have a complete example. I know that I have to use fcntl() but how and when? Pls someone give a pseudocode of the program..
See my answer How can I copy a file on unix using C on StackOverflow. It uses a rudimentary locking and read the comments that caf has mentioned by using lockf, there is a more robust way to do this using fcntl. There is a detailed document about this on GNU's website here. Here is the code on the opengroup that demonstrates the usage of fcntl to do the locking. Hope this helps, Best regards, Tom.
2,229,965
2,230,009
In C++, is it possible to reconcile stack-based memory management and polymorphism?
I love declaring variables on the stack, especially when using the standard container. Each time you avoid a new, you avoid a potential memory leak. I also like using polymorphism, ie class hierarchies with virtual functions. However, it seems these features are a bit incompatible: you can't do: std::vector<BaseType> vec; vec.push_back(DerivedType()) or at least it seems you would lose the polymorphic nature of the object you push in. So, is there any way to reconcile stack-based memory management and the use of virtual functions?
Well the obvious answer: std::vector<BaseType*> vec; DerivedType d; vec.push_back(&d); But probably not what you intended. d and vec better die at the same time; if vec outlives d you've got a bad pointer. I think what you really want is something like Boost pointer containers: boost::ptr_vector<BaseType> vec; vec.push_back(new DerivedType()); So you don't have to worry about leaks. The pointer containers were made specifically for the task of easing use and storage of polymorphic objects.
2,230,089
2,230,125
C++ Confusion. Reading Integer From Text File. Convert to ASCII
I am learning C++ for the first time. I have no previous programming background. In the book I have I saw this example. #include <iostream> using::cout; using::endl; int main() { int x = 5; char y = char(x); cout << x << endl; cout << y << endl; return 0; } The example makes sense: print an integer and the ASCII representation of it. Now, I created a text file with these values. 48 49 50 51 55 56 75 I am writing a program to read this text file -- "theFile.txt" -- and want to convert these numbers to the ASCII value. Here is the code I wrote. #include <iostream> #include <fstream> using std::cout; using std::endl; using std::ifstream; int main() { ifstream thestream; thestream.open("theFile.txt"); char thecharacter; while (thestream.get(thecharacter)) { int theinteger = int(thecharacter); char thechar = char(theinteger); cout << theinteger << "\t" << thechar << endl; } system ("PAUSE"); return 0; } This is my understanding about the second program shown. The compiler does not know the exact data type that is contained in "theFile.txt". As a result, I need to specify it so I choose to read the data as a char. I read the each digit in the file as a char and converted it to an integer value and stored it in "theinteger". Since I have an integer in "theinteger" I want to print it out as a character but char thechar = char(theinteger); does not work as intended. What am I doing incorrect?
You are reading one char at a time from the file. Hence, if your file contains: 2424 You will first read the char "2" from the file, convert it to an int, and then back to a char, which will print "2" on cout. Next round will print "4", and so on. If you want to read the numbers as full numbers, you need to do something like: int theinteger; thestream >> theinteger; cout << char(theinteger) << endl;
2,230,309
2,230,360
Pointer to QList - at() vs. [] operator
I'm having problem with understanding some of QList behavior. #include <QList> #include <iostream> using namespace std; int main() { QList<double> *myList; myList = new QList<double>; double myNumber; double ABC; for (int i=0; i<1000000; i++) { myNumber = i; myList->append(myNumber); ABC = myList[i]; //<----------!!!!!!!!!!!!!!!!!!! cout << ABC << endl; } cout << "Done!" << endl; return 0; } I get compilation error cannot convert ‘QList’ to ‘double’ in assignment at marked line. It works when I use ABC = myList.at(i), but QT reference seems to say that at() and [] operator is same thing. Does anybody know what makes the difference? Thanks
That's because operator[] should be applied to a QList object, but myList is a pointer to QList. Try ABC = (*myList)[i]; instead. (Also, the correct syntax should be myList->at(i) instead of myList.at(i).)
2,230,338
2,231,473
bool function problem - always returns true?
#include <iostream> #include <string> #include <algorithm> #include <cstdlib> #include <cstdio> using namespace std; static bool isanagram(string a, string b); int main(void) { int i,n,j,s; cin >> n; string a, b; cin >> a >> b; if(!isanagram(a,b)) cout << "False" << endl; else cout << "True" << endl; return 0; } static bool isanagram(string a, string b) { int i, j, size, s=0; size = a.size(); bool k; for(i=0;i<size;i++) { k=false; for(j=0;j<size;j++) { if(a[i] == b[j]) { k = true; break; } } if(k==true) s+=1; } cout << a[2] << b[2] << endl; if(s == size) return true; else return false; } I don't know where exactly is the problem so i just pasted the whole code. It should be a simple program capable for finding if two strings are anagrams, but it's not working and i don't know why. I used pointers in the program so thought the might be the problem and removed them, i removed other things additionally but still it's not working. If you can give it a look-see and tell me some idea where i might've gone wrong with my code ? Thank you in advance.
First things first: don't declare the method static. It's a confusing keyword at the best of times given all the roles it can fulfill... so reserve for times when you really have to (method or attribute of a class that is not tied to any instance for example). Regarding the algorithm: you're nearly there, but presence only is not sufficient, you need to take the number of characters in account too. Let's do it simply: bool anagram(std::string const& lhs, std::string const& rhs) { if (lhs.size() != rhs.size()) return false; // does not cost much... std::vector<int> count(256, 0); // count of characters for (size_t i = 0, max = lhs.size(); i != max; ++i) { ++count[lhs[i]]; --count[rhs[i]]; } for (size_t i = 0, max = count.size(); i != max; ++i) if (count[i] != 0) return false; return true; } // anagram Let's see it at work: anagram("abc","cab") Initialization: count = [0, 0, ...., 0] First loop i == 0 > ['a': 1, 'c': -1] First loop i == 1 > ['a': 0, 'b': 1, 'c': -1] First loop i == 2 > ['a': 0, 'b': 0, 'c': 0 ] And the second loop will pass without any problem. Variants include maintaining 2 counts arrays (one for each strings) and then comparing them. It's slightly less efficient... does not really matter though. int main(int argc, char* argv[]) { if (argc != 3) std::cout << "Usage: Program Word1 Word2" << std::endl; else std::cout << argv[1] << " and " << argv[2] << " are " << (anagram(argv[1], argv[2]) ? "" : "not ") << "anagrams" << std::endl; }
2,230,367
2,230,543
C++ in mobile apps. How does it works
Tell me. How is executed binaries (written in c++ ForExample) in mobiles?? Is it only possible as mixed with J2ME or is it possible to execute "RAW" (like exe file) binary. (In old and new mobiles)
Running a program on a mobile phone is like running it on a normal computer. You have to take two things into consideration the processor that is running the phone and the OS that is running on top of the processor. Certain phone OS's are very restrictive on what they let run on the phone so you need to read up on the restrictions imposed by the OS. Secondly the processors are usually very limited and completely different to a normal PC so you need a compiler that will generate code for that processor. But RAW object files are not enough C++ is dependent on a whole set of standard libraries functions and framework to start up the application. For this you will need to have the appropriate SDK for the your phone so that you can link your program with the appropriate framework that your phone OS will understand. The last problem is getting the binaries onto the phone. Detailed instructions will usually come with the SDK.
2,230,508
2,230,540
Using virtual function in child after casting operation in C++
I have the following code: class A { }; class B : public A { public: virtual void f() {} }; int main() { A* a = new A(); B* b = static_cast<B*>(a); b->f(); } This program fails with a segmentation fault. There are two solutions to make this program work: declare f non-virtual do not call b->f() (i.e. it fails not because of the cast) However, both are not an option. I assume that this does not work because of a lookup in the vtable. (In the real program, A does also have virtual functions. Also, the virtual function is not called in the constructor.) Is there a way to make this program work?
You can't do that because the object you create is A, not B. Your cast is invalid-- an object of A (created with new) cannot magically become an object of B. Did you mean the A* a = new A() to actually be A* a = new B()? In that case, I would expect it to work.
2,230,758
2,230,778
What does LPCWSTR stand for and how should it be handled?
First of all, what is it exactly? I guess it is a pointer (LPC means long pointer constant), but what does "W" mean? Is it a specific pointer to a string or a pointer to a specific string? For example I want to close a Window named "TestWindow". HWND g_hTest; LPCWSTR a; *a = ("TestWindow"); g_hTest = FindWindowEx(NULL, NULL, NULL, a); DestroyWindow(g_hTest); The code is illegal and it doesn't work since const char[6] cannot be converted to CONST WCHAR. I don't get it at all. I want to get a clear understanding of all these LPCWSTR, LPCSTR, LPSTR. I tried to find something , however I got confused even more. At msdn site FindWindowEx is declared as HWND FindWindowEx( HWND hwndParent, HWND hwndChildAfter, LPCTSTR lpszClass, LPCTSTR lpszWindow ); So the last parameter is LPCSTR, and the compiler demands on LPCWSTR. Please help.
LPCWSTR stands for "Long Pointer to Constant Wide String". The W stands for Wide and means that the string is stored in a 2 byte character vs. the normal char. Common for any C/C++ code that has to deal with non-ASCII only strings.= To get a normal C literal string to assign to a LPCWSTR, you need to prefix it with L LPCWSTR a = L"TestWindow";
2,230,765
2,230,783
Setting a breakpoint on a member function called on a specific object
In gdb, is it possible to set a breakpoint on a member function called on a specific object? To be more specific, imagine class A has a member function Foo(). I'd like the program to stop when Foo is called on a specific object of type A (0xFF11DEADBEAF for example). Is this at all possible?
Use: b <Classname>::<functionname> if this==0xDEADBEEF (btw: all instances share member function addresses.)
2,231,038
2,236,111
How to store the Visual C++ debug settings?
The debug settings are stored in a .user file which should not be added to source control. However this file does contain useful information. Now I need to set each time I trying to build a fresh checkout. Is there some workaround to make this less cumbersome? Edit: It contains the debug launch parameters. This is often not really a per-user setting. The default is $(TargetPath), but I often set it to something like $(SolutionDir)TestApp\test.exe with a few command line arguments. So it isn't a local machine setting per se.
Set the debug launch parameters in a batch file, add the batch file to source control. Set the startup path in VS to startup.bat $(TargetPath).
2,231,041
2,231,071
Where/how to define a template
What is the best pratice in regards to defining a template in C++? template <class T> class A { private: // stuff public: T DoMagic() { //method body } } Or: template <class T> class A { private: // stuff public: T DoMagic(); } template <class T> A::T DoMagic() { // magic } Another way? I seem to stumble over some controversy regarding this subject. So; What path to choose?
This is completely a matter of style. That said however: choose a way and stick to it -- either all inline, or all out, or mixed based on some rule personally I use a 3 line rule. If the method body in the template is longer than 3 lines I move it outside. There's no real reason not to include all definitions inline (they are inline from the compilers POV anyway), however, many people argue that keeping them separate is more clean, and allows the class definition to be more readable.
2,231,111
2,231,157
Why are string::append operations behaving strangely?
look at the following simple code: #include <iostream> #include <string> using namespace std; int main() { string s("1234567890"); string::iterator i1 = s.begin(); string::iterator i2 = s.begin(); string s1, s2; s1.append(i1, ++i1); s2.append(++i2, s.end()); cout << s1 << endl; cout << s2 << endl; } what would you expect the output to be? would you, like me, expect it to be: 1 234567890 wrong! it is: 234567890 i.e. the first string is empty. seams that prefix increment operator is problematic with iterators. or am I missing something?
Not a bug. The order in which the arguments to s1.append(i1, ++i1); are evaluated is not specified by the standard. The compiler is free to use any order it chooses. In this case, it evaluates the second argument (++i1) before the first (i1) and you specify a null range to copy.
2,231,124
2,231,182
How to get the object type from a collection (vector) of parent objects using RTTI
I have a base class which has two child classes derived from it. class A {}; class B : public A {}; class C : public A {}; I have another class that has a pointer to collection of class A members using a vector, something like this: vector<A*> *m_collection; And what I do is to create objects of class B or C and add them to the collection using push_back: B *myb = new B(); m_collection->push_back(myb); Then I loop through the collection and try to check using 'typeid', but it always returns the base class (A). Is it not possible to know the exact type? Thank you!
Firstly, there is unlikely to be a reason to create your vector dynamically using new. Simply say: vector<A*> m_collection; Then you need to give your base class a virtual function or two. A virtual destructor would be a good start: class A { public: virtual ~A() {} }; without it you cannot safely write code like: m_collection.push_back( new B ); delete m_collection[0]; Doing this will also enable run-time type information. Howver, switching on typeid is not how C++ likes you to use RTTI - you should use dynamic_cast: m_collection.push_back( new B ); // or new A or new C if ( C * c = dynamic_cast<C *>( m_collection[0] ) ) { c->CFunc(): // function in C } else if ( B * b = dynamic_cast<B *>( m_collection[0] ) ) { b->BFunc(): // function in B } else if ( A * a = dynamic_cast<A *>( m_collection[0] ) ) { a->AFunc(): // function in A } else { throw "unknown type"; } In general however, it is better to use the virtual function mechanism for dispatch, rather than RTTI.
2,231,138
2,231,509
in C++ files: what a file opened as an ios::binary differs from one opened as ios::binary | ios::out?
if i opened a file like: ofstream file("file.dat",ios::binary); or ofstream file("file.dat",ios::binary | ios::out); what can i do with a file opened in the latter form that i can't do with the former form and vice versa thank you
thanks for all people who answered me: i now tested several codes depending on what i have been answered and came up with this summary: using ofstream: ios::out is the default even if nothing is specified, but if you used only ios::in with ofstream, no compilation errors (unless you use read() or >> or some ifstream object) but no files would be written. using ifstream: ios::in is the default even if nothing is specified, but if you used only ios::out with ifstream, no compilation errors (unless you use write() or << or some ofstream object) but you can't read any information from the file. using fstream: no defaults, you have to explicitly determine what you are going to do. Otherwise, no compilation error but you don't get what you want simply. as for the original question , both work exactly the same!
2,231,414
2,231,543
Does a type require a default constructor in order to declare an array of it?
I noticed that when you declare an array, the default constructor must be needed. Is that right? Is there any exception? For example, struct Foo{ Foo(int i ) {} }; int main () { Foo f[5]; return 0; } The code above does not compile.
Other answers are all right but, for completeness: You could also use the array initialization syntax: Foo f[5] = {1,2,3,4,5}; This works if Foo's ctor is not explicit. If it was, you'd have to be.... explicit: Foo f[5] = {Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)}; Note1: There is a difference between the two cases that may not be obvious and is thus worth noting: In the first, the array elements are directly constructed from the ints in the initialization list, by invoking the Foo(int) ctor. In the second, the initialization list is made of Foos constructed with the explicit Foo(int) ctor, and the array elements are copy constructed from the elements in the initialization list. A copy ctor for Foo is thus required in the latter case. [1] Thanks to MSalters for the comment.
2,231,504
2,232,328
Why and when should one call _fpreset( )?
The only documentation I can find (on MSDN or otherwise) is that a call to _fpreset() "resets the floating-point package." What is the "floating point package?" Does this also clear the FPU status word? I see documentation that says to call _fpreset() when recovering from a SIGFPE, but doesn't _clearfp() do this as well? Do I need to call both? I am working on an application that unmasks some FP exceptions (using _controlfp()). When I want to reset the FPU to the default state (say, when calling to .NET code), should I just call _clearfp(), _fpreset(), or both. This is performance critical code, so I don't want to call both if I don't have to...
_fpreset() resets the state of the floating-point unit. It resets the FPU precision to its default and clears the FPU status word. The two occasitions I see to use it are when recovering from an FPE (as you said) and when getting control back from library code (e.g. a DLL that you have no control about) that has screwed the FPU in any way, like changing the precision.
2,231,525
2,231,542
Storing and printing 10+ digit integer in c++
I'm using cout to print digits to the console. I am also storing values of up to 13+billion as a digit and doing computations on it. What data type should I use? When I do the following: int a = 6800000000; cout << a; It prints -1789934592. thanks.
long long can hold up to 9223372036854775807. Use something like gmp if you need larger.
2,231,720
2,231,813
TCHAR[], LPWSTR, LPTSTR and GetWindow Text function
So the GetWindowText is declared on MSDN as follows: int GetWindowText( HWND hWnd, LPTSTR lpString, int nMaxCount ); However for the code to work we have to declare the second parameter as TCHAR[255] WTitle; and then call the function GetWindowText(hWnd,Wtitle,255); The LPTSTR is a pointer to an array of tchar, so declaring LPTSTR is similar to declaring TCHAR[]? It doesn't work this way though. When using TCHAR[] the program returns valid GetWindowText result (it is an integer equal to the number of symbols in the title). The question is : how can I get the exact title out of TCHAR[] ? Code like TCHAR[255] WTitle; cout<< WTitle; or cout<< *Wtitle; returns numbers. How can I compare this with a given string? TCHAR[4] Test= __T("TEST") if (WTitle == Test) do smth doesn't work also.
OK, a few definitions first. The 'T' types are definitions that will evaluate to either CHAR (single byte) or WCHAR (double-byte), depending upon whether you've got the _UNICODE symbol defined in your build settings. The intent is to let you target both ANSI and UNICODE with a single set of source code. The definitions: TCHAR title[100]; TCHAR * pszTitle; ...are not equivalent. The first defines a buffer of 100 TCHARs. The second defines a pointer to one or more TCHARs, but doesn't point it at a buffer. Further, sizeof(title) == 100 (or 200, if _UNICODE symbol is defined) sizeof(pszTitle) == 4 (size of a pointer in Win32) If you have a function like this: void foo(LPCTSTR str); ...you can pass either of the above two variables in: foo(title); // passes in the address of title[0] foo(pszTitle); // passes in a copy of the pointer value OK, so the reason you're getting numbers is probably because you do have UNICODE defined (so characters are wide), and you're using cout, which is specific to single-byte characters. Use wcout instead: wcout << title; Finally, these won't work: TCHAR[4] Test == __T("TEST") ("==" is equality comparison, not assignment) if (WTitle == Test) do smth (you're comparing pointers, use wcscmp or similar)
2,231,899
2,231,937
throwing an exception causes segmentation fault
Collection CollectionFactory::createFromMap(const std::string& name, const DataMap& dm) const { if (!Collection::isNameValid(name)) { const std::string error = "invalid collection name"; throw std::invalid_argument(error); } Collection c(name, dm); dm.initDataCollection(&c, true); return c; } Whenever the throw statement is executed, I'm getting a segmentation fault. Here is the cause from Valgrind output. I've no idea what's going on. ==21124== Invalid read of size 1 ==21124== at 0x41D2190: parse_lsda_header(_Unwind_Context*, unsigned char const*, lsda_header_info*) (eh_personality.cc:62) ==21124== by 0x41D24A9: __gxx_personality_v0 (eh_personality.cc:228) ==21124== by 0x4200220: _Unwind_RaiseException (unwind.inc:109) ==21124== by 0x41D2C9C: __cxa_throw (eh_throw.cc:75) ==21124== by 0x4079BFB: corestore::CollectionFactory::createFromMap(std::string const&, corestore::DataMap const&) const (CollectionFactory.C:43) ==21124== by 0x8188F86: CollectionFactoryTest::testCreateNewFromMap_InvalidName() (CollectionFactoryTest.C:91) ==21124== by 0x81895D3: CppUnit::TestCaller<CollectionFactoryTest>::runTest() (TestCaller.h:166) ==21124== by 0x40D1BB5: CppUnit::TestCaseMethodFunctor::operator()() const (TestCase.cpp:34) ==21124== by 0x40C18E3: CppUnit::DefaultProtector::protect(CppUnit::Functor const&, CppUnit::ProtectorContext const&) (DefaultProtector.cpp:15) ==21124== by 0x40CD0FC: CppUnit::ProtectorChain::ProtectFunctor::operator()() const (ProtectorChain.cpp:20) ==21124== by 0x40CCA65: CppUnit::ProtectorChain::protect(CppUnit::Functor const&, CppUnit::ProtectorContext const&) (ProtectorChain.cpp:77) ==21124== by 0x40DC6C4: CppUnit::TestResult::protect(CppUnit::Functor const&, CppUnit::Test*, std::string const&) (TestResult.cpp:178) ==21124== Address 0xc82f is not stack'd, malloc'd or (recently) free'd I've had several iterations of the unit test that's bombing, but here is the current one that exhibits the same bug as all the others: void CollectionFactoryTest::testCreateNewFromMap_InvalidName() { const char* MAP_FILE = "smallMapWithThreeSets.xml"; const char* NAME1 = "name/invalidname"; const char* NAME2 = "name/invalidname"; DataMapReader dmr; DataMap dm = dmr.getDataMapFromFile(MAP_FILE); CollectionFactory cf; try { cf.createFromMap(NAME1, dm); } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } /*CPPUNIT_ASSERT_THROW(cf.createFromMap(NAME1, dm), std::invalid_argument); CPPUNIT_ASSERT_THROW(cf.createFromMap(NAME2, dm), std::invalid_argument);*/ } Per request, the contents of isNameValid: bool Collection::isNameValid(const std::string& name) { /* can't be blank */ if(name.length() == 0) { return false; } /* Can't contain '/' */ if(name.find('/') != std::string::npos) { return false; } return true; }
Is that the very first Valgrind error or are there previous ones? My guess is that there are previous ones and one of those is corrupting memory and causing throw to break.
2,231,981
2,272,555
Socket programming Xp > Vista, Vista > XP
I am developing a program which sends images from one computer to another (similar to remote assistance without mouse/keyboard input). The two computers I use to test this are one Windows XP machine and one Windows Vista. I have the stationary XP machine directly connected to a router, and a laptop which is connected through wireless. The transmission from XP to Vista works great, I am able to get a constant flow of images that are displayed on Vista. However, when I flip it and send images from Vista to XP it does not work. I also tried a local "copy", that is, without the network get a flow of images and this works on Vista as well as XP. It is the exact same program on both machines. I don't think it matters but I am using GDI+ for the images. So I send a .jpg through a stream on the network and rebuild it on the other side. My Network Message class is called NetMsg. it consists of a char* type and a char* data. the types determine how I interpret the data, no issues here. Let's call the computers #1 and #2. When connection is created and I marked the area on #1 that I want to send: 001>#1 sends type RESIZE // to get the window on #2 the same size as the area I have marked on #1 002>#1 sends type PICTURE_DATA // this is the actual imagedata 003>#2 after received the two above messages, sends type REQUEST_MORE // #2 wants more imagedata 004>#go to step 1 I haven't even bothered to debug it when sending image data from XP to Vista, since it works great, exactly like I want it. However when Vista sends to XP I have noticed the following: Data received can actually be two NetMsgs. I have support for this by splitting the data into several NetMsgs Data received can be incomplete, that is I have to wait for more data. I have support for this by marking a NetMsg as incomplete and on the next datatransmission complete it. (as well as a combination of the first step) This almost did the trick because I got some images transferred correctly, however then it suddenly stopped. I have not debugged this thoroughly so I do not know why the data suddently stopped.. However: What I do not understand is that this works great when sending from XP to Vista but not the other way around. What am I missing? Do let me know if you need extracts of code, however, it is pretty huge... roughly 500 rows.. Otherwise I am looking for known issues when sending data from Vista to XP. Any help and/or feedback appreciated!
It was actually blocking on both computers and both were waiting for the other to respond.