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 ...
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>...
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 = ...
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 oldMa...
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; ...
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 t...
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() { FI...
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); // cal...
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 ...
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...
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 c...
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.ign...
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] = { {"M...
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_bac...
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::si...
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...
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 arc...
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 ...
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...
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 te...
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, M...
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) { ...
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 argume...
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 o...
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 us...
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=fo...
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) { fw...
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 eventuall...
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...
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 o...
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_oarc...
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...
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 Q...
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 {...
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 *postalC...
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....
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 ...
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})[- ]?(\\...
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; s...
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 n...
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 noth...
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 val...
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 erro...
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 hea...
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 act...
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 u...
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* pF...
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 functi...
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 ShellExec...
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 ha...
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 e...
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...
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; whil...
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 unde...
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 accelerateUnco...
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; }; }; ...
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 ...
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, ...
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 some...
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 t...
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 smal...
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...
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 resor...
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 ...
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> #in...
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 ho...
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...
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> callback...
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 Ob...
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 dif...
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...
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 ...
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 ...
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 tim...
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, opera...
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...
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 pr...
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, s...
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 sid...
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 who...
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::s...
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 ti...
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...
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 c...
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 c...
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 '...
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 fi...
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(...
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 yo...
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 hap...
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 synta...
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 dest...
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::stringstr...
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 sampl...
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 ...
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 *)&...
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 ...
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...
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 compilin...
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 terminat...
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-standar...
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; }; T...
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, FCPackage...
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,"GetNati...
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; ...
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 ...
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: ...
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 { ...
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 ...
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 r...
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 demons...
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> v...
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.pus...
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 in...
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 somethi...
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(myN...
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" ...
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 ...
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...
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->...
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(NUL...
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 ...
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 ofte...
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 } Anoth...
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 ...
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 <<...
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 ...
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 cod...
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 o...
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 tha...
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 ...
_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 screwe...
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 arr...
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...
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, t...
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 t...
It was actually blocking on both computers and both were waiting for the other to respond.