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,959,476
2,964,279
C++ Adding 2 arrays together quickly
Given the arrays: int canvas[10][10]; int addon[10][10]; Where all the values range from 0 - 100, what is the fastest way in C++ to add those two arrays so each cell in canvas equals itself plus the corresponding cell value in addon? IE, I want to achieve something like: canvas += another; So if canvas[0][0] =3 and a...
Here is an SSE4 implementation that should perform pretty well on Nehalem (Core i7): #include <limits.h> #include <emmintrin.h> #include <smmintrin.h> static inline int canvas_add(int canvas[10][10], int addon[10][10]) { __m128i * cp = (__m128i *)&canvas[0][0]; const __m128i * ap = (__m128i *)&addon[0][0]; ...
2,959,502
2,960,065
Linking Error Building 64bit Qt app on 32bit XP machine
I'm trying to build a 64 bit version of my application (and yes I really do need the memory) on my 32bit xp dev box for production testing on our Vista64 server. Previously, I have built w/o any errors the Qt 4.6.2 DLL's in 64 bit mode. That step went vary smooth. Just to get started in building production, I'm tryi...
qt application 64 bit windows Edit: Nevermind, you found it. You need to link against qtmain if you are not using CMake or qmake as stated here: http://doc.qt.io/archives/4.6/modules.html. You don't need to accept this as I didn't find it, but just so future people see the answer and don't get confused.
2,959,535
2,959,838
c++ Function pointer inlining
I know I can pass a function pointer as a template parameter and get a call to it inlined but I wondered if any compilers these days can inline an 'obvious' inline-able function like: inline static void Print() { std::cout << "Hello\n"; } .... void (*func)() = Print; func(); Under Visual Studio 2008 its clever eno...
GNU's g++ 4.5 inlines it for me starting at optimization level -O1 main: subq $8, %rsp movl $6, %edx movl $.LC0, %esi movl $_ZSt4cout, %edi call _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_E movl $0, %eax addq $8, %rsp ret where .LC0 is the .s...
2,959,631
2,959,846
Can an out-of-process COM object determine its parent process?
From an out-of-process COM object (LocalServer32) can I determine the client process that requested the creation of the object? - to be specific I need to get hold of the client processes command line. This question arrises because (due to poor standardisation, implementation and support) the potential 3rd party client...
Having looked into this further I suspect the answer is going to be "NO", but by all means tell me I'm wrong. Using Process Explorer I can see that the parent process for my COM object is an instance of "svchost.exe", and not the client application.
2,960,176
2,960,383
MFC: Best way to get text from a CRichEdit?
I've got a CRichEdit that I need to get the text from. What is the best way to do that? GETTEXTEX? StreamOut? If I go the StreamOut approach, what would my callback look like?
It's inherited from CWnd so you should just be able to use GetWindowText(). CString returnText; yourRichEdit.GetWindowText(returnText);
2,960,193
2,960,216
What is the difference between NULL in C++ and null in Java?
I've been trying to figure out why C++ is making me crazy typing NULL. Suddenly it hits me the other day; I've been typing null (lower case) in Java for years. Now suddenly I'm programming in C++ and that little chunk of muscle memory is making me crazy. Wikiperipatetic defines C++ NULL as part of the stddef: A macr...
Java's null is more like C++0x's nullptr. NULL in C++ is just 0 and can end up resolving to int rather than a pointer like you'd want. Consider: void f(int); void f(char*); ... f(NULL); // which f()? C++0x has nullptr, which fixes that problem but it's still not going to be totally equivalent to Java's null. The...
2,960,434
2,960,540
C Population Count of unsigned 64-bit integer with a maximum value of 15
I use a population count (hamming weight) function intensively in a windows c application and have to optimize it as much as possible in order to boost performance. More than half the cases where I use the function I only need to know the value to a maximum of 15. The software will run on a wide range of processors, bo...
It is indeed possible to optimise your function for the "maximum 15" case. The following shaves off a few operations: inline int population_count64_max15(unsigned __int64 w) { w -= (w >> 1) & 0x5555555555555555ULL; w = (w & 0x3333333333333333ULL) + ((w >> 2) & 0x3333333333333333ULL); return int((w * 0x11111111...
2,960,496
2,960,543
Why is NULL/0 an illegal memory location for an object?
I understand the purpose of the NULL constant in C/C++, and I understand that it needs to be represented some way internally. My question is: Is there some fundamental reason why the 0-address would be an invalid memory-location for an object in C/C++? Or are we in theory "wasting" one byte of memory due to this reserv...
The null pointer does not actually have to be 0. It's guaranteed in the C spec that when a constant 0 value is given in the context of a pointer it is treated as null by the compiler, however if you do char *foo = (void *)1; --foo; // do something with foo You will access the 0-address, not necessarily the null pointe...
2,960,554
2,960,580
correct way to store an exception in a variable
I have an API which internally has some exceptions for error reporting. The basic structure is that it has a root exception object which inherits from std::exception, then it will throw some subclass of that. Since catching an exception thrown in one library or thread and catching it in another can lead to undefined be...
You have what would be what I think is your best, only answer. You can't keep a reference to the original exception because it's going to leave scope. You simply have to make a copy of it and the only generic way to do that is with a prototype function like clone(). Sorry.
2,960,682
2,960,701
Explicit type conversion
I have read in a book that specifies this : //: C03:SimpleCast.cpp int main() { int b = 200; unsigned long a = (unsigned long int)b; } ///:~ "Casting is powerful, but it can cause headaches because in some situations it forces the compiler to treat data as if it were (for instance) larger than it really is, so it will...
int main(void) { short int a = 5; short int b = 7; *(long int*)&a = 0; } Assuming sizeof(long) > sizeof(short), and assuming the compiler puts a on the stack before b, b will be trashed.
2,960,775
2,960,817
Proper way to handle issue when porting 32 to 64 bit. Conversion from DT1 to DT2 of greater size
So I am trying to port 32 bit to 64 bit. I have turned on the VS2008 flag for detecting problems with 64 bit. I am trying following: char * pList = (char *)uiTmp); warning C4312: 'type cast' : conversion from 'unsigned int' to 'char *' of greater size Disregard the code itself. This is also true for any pointer, becau...
This is not a warning you can ignore, it will bomb in 64-bit code. An unsigned int cannot store a pointer. There's no magic cast that will make this work. Review your code and rethink storing pointer values in an unsigned int. It should probably be a void*. If you #include <windows.h> then you can use UINT_PTR.
2,960,869
3,010,570
DUMP in unhandled C++ exception
In MSVC, how can I make any unhandled C++ exception (std::runtime_error, for instance) crash my release-compiled program so that it generates a dump with the full stack from the exception throw location? I have installed NTSD in the AeDebug registry and can generate good dumps for things like memory access violation, s...
I finally cracked it down. Use the set_terminate() function to register a handler for every thread In you main function(), make it impossible for external DLLs (event Windows') to successfully call SetUnhandledExceptionFilter(). A great article on how to do that here: http://www.debuginfo.com/articles/debugfilters.ht...
2,961,115
2,961,249
How to populate wxListCtrl?
I'm trying to populate a wxListCtrl but after trying various methods can't seem to be able to populate it with items. Basically, I want a list control that would have three columns with headings and will show values in rows. But I've tried InsertItem, SetItem, or InsertColumn methods but am only able to show the column...
You can add columns like this: int column_width = 90; my_list_ctrl->InsertColumn(0, L"ColumnText", wxLIST_FORMAT_LEFT, column_width); You can add items like this: int image_index = 0; long list_index = my_list_ctrl->InsertItem(0, L"My Item text", image_index); You can set the text of the subitems like this: int colum...
2,961,127
2,961,434
Casting a byte array to a struct pointer depends on endianness or memory alignment?
Suppose this code: unsigned char list[3] = { 1, 2, 3 }; struct _struct{ unsigned char a; unsigned char b; unsigned char c; } *s; s = ( _struct * ) list; Can I assume that always s->a == 1, s->b == 2, s->c == 3 ? Or it will depend on the system's endianness or memory alignment?
Let's dissect this. In all cases, sizeof(char) == 1, and the list array will have its three members at memory locations list, list + 1, and list + 2. The situation with the struct is not quite as clear. The Standard guarantees that the members will be allocated in increasing memory locations, but not that they will be...
2,961,207
2,961,258
And now for a complete change of direction from C++ function pointers
I am building a part of a simulator. We are building off of a legacy simulator, but going in different direction, incorporating live bits along side of the simulated bits. The piece I am working on has to, effectively route commands from the central controller to the various bits. In the legacy code, there is a const...
Can't be done. However, you could do something sort of like it with a functor. I'd put example code but as I was writing it I realized such a construct would necessarily be quite complicated. You might look at boost::bind for some ideas.
2,961,407
2,961,446
Can you explicitly set a structure layout/alignment in C++ as you can in C#?
In C# you have nice alignment attributes such as this: [StructLayout(LayoutKind.Explicit)] public struct Message { [FieldOffset(0)] public int a; [FieldOffset(4)] public short b; [FieldOffset(6)] public int c; [FieldOffset(22)] //Leave some empty space just for the heck of it. public Dat...
Compilers typically support that via a #pragma but it's not something that is included in the C++ standard and, thus, is not portable. For an example with the Microsoft compiler, see: http://msdn.microsoft.com/en-us/library/2e70t5y1(VS.80).aspx
2,961,431
2,961,464
Which design pattern is most appropriate?
I want to create a class that can use one of four algorithms (and the algorithm to use is only known at run-time). I was thinking that the Strategy design pattern sounds appropriate, but my problem is that each algorithm requires slightly different parameters. Would it be a bad design to use strategy, but pass in the r...
It would be a valid design because the Strategy pattern asks for an interface to be defined and any class that implements it is a valid candidate to run the strategy code, regardless how it is constructed.
2,961,488
2,961,514
Can I use a switch to hold a function?
I have a 3 file program, basically teaching myself c++. I have an issue. I made a switch to use the math function. I need and put it in a variable, but for some reason I get a zero as a result. Also another issue, when I select 4 (divide) it crashes... Is there a reason? Main file: #include <iostream> #include "math.h...
You're calling your functions with a and b before you get the data from the user. Try saving the math function that they selected when they enter it, and move your switch to after you have asked them for a and b. #include <iostream> #include "math.h" #include <string> using namespace std; int opersel; int c; int a; i...
2,961,504
2,961,764
Help with Assembly/SSE Multiplication
I've been trying to figure out how to gain some improvement in my code at a very crucial couple lines: float x = a*b; float y = c*d; float z = e*f; float w = g*h; all a, b, c... are floats. I decided to look into using SSE, but can't seem to find any improvement, in fact it turns out to be twice as slow. My SSE code i...
As you've found out, just replacing a couple of instructions with SSE is not going to work because you need to shuffle the data around in memory in order to load the SSE registers correctly, and this moving data around in memory (the bit that constructs the arrays) is going to kill your performance as memory is very sl...
2,961,725
2,961,776
How to debug properly and find causes for crashes?
I dont know what to do anymore... its hopeless. I'm getting tired of guessing whats causing the crashes. Recently i noticed some opengl calls crashes programs randomly on some gfx cards. so i am getting really paranoid what can cause crashes now. The bad thing on this crash is that it crashes only after a long time of ...
A "random" crash that occurs sometime after a complex operation is almost certainly the result of heap corruption. Heap corruption bugs are a bitch, since they usually manifest themselves very far away from the place that actually caused the bug. My suggestion, since you're on Windows, is to use Application Verifier, w...
2,961,765
2,963,172
C++ code parser/processor library
is there any library that parse a source code of C++ to produce lets say, call graph, class inheritance tree, flow control, class member list or anything as a ready to use graph or structure in code (not in diagram image). to make it more clear, suppose to generate call graph image, there will be a process like this: ...
It depends on how precise you want the parsing to be. If you want it to be absolutely accurate (i.e. shouldn't miss a class because of some overcomplicated macro or template metaprogramming that it couldn't handle), then you need a proper C++ front end for this, and I'm not aware of any that are both free and easily re...
2,961,980
2,962,013
C++ for small, individual projects (i.e. hobby programming)
I recently started C++. I am using PHP right now and decided to take a look at C++. Web programming had me working with a couple of languages, with a couple of people. I wanted to do programming where I only had to bother with one language and create small utility apps (mostly not web-based). I wanted a compiled, stron...
You can certainly use C++ in all the areas you mention, though whether it is best of breed for any of them is open to debate. C++ is very large and complex language, and requires a fair bit of effort to get up to speed on. If I were you, I would pick one of the areas you mention that you are most interested in, and th...
2,962,085
2,962,105
how to do trig functions to data in Windows textboxes
must you convert from strings to double? if so. how? Are there functions for trig that will accept textbox string data as is? Is there a way to pull the data from the textbox as a numeric value, not as a string?
must you convert from strings to double? Yes. if so. how? The C++ way is to use the string streams; in particular, you'll probably want to use istringstream. A viable alternative is to follow the C way, i.e. use sscanf with the appropriate format specifier ("%f"). Another C++ option is to use the boost lexical_cast, b...
2,962,153
2,962,169
How can I find if an arbitrary process is running under wow64?
I need a tool which will discover whether an arbitrary process is running in x86 or x64 mode on a machine. I need to do this programatically from C++, based on a process ID. There has to be some way to do this (as you can clearly see it from the task manager). Does anyone know of a windows api that will tell you, giv...
There is a WinAPI function, IsWow64Process.
2,962,210
3,093,154
Compile JavaScript to Native Code with V8
Is it really possible, with Google's V8 Engine, to compile JavaScript into Native Code, save it as a binary file, and execute it whenever I want through my software envorinment, on any machine?
You can use the V8 snapshot functionality to precompile the code. This still means that you have to have a full version of V8 running to load the snapshot (i.e., you don't get stand-alone native code, it needs to run inside the V8 VM), so all you save is the compilation time. Also, the quality of snapshot code isn't n...
2,962,223
2,962,298
How do you hook a C++ compiled dll function to a sql database?
I want to do something like: lastName SIMILARTO(lastName, 'Schwarseneger', 2) where lastName is the field in the database, 'Schwarseneger' is the value that lastName field is being compared to and 2 is the maximum number of characters (edit distance) that can differ between the lastName field, and the entered value. I ...
See MySQL 5.1 Reference Manual :: 22.3.2 Adding a New User-Defined Function This blog post also have detailed instructions for building User Defined Function DLLs on Windows.
2,962,233
2,962,465
how can we avoid allocation done by Marshal::StringToHGlobalAnsi?
My wrapper from managed to unmanaged is handling a lot of data and this function Marshal::StringToHGlobalAnsi would call new for each of them, which is a big hit for me. So my question is: Can I allocate a chunk of unmanaged memory and use it to convert the managed data types to unmanaged by hand?
Assuming all of the characters in the System::String are in the ASCII range, the most basic implementation would be something like: void ConvertAndCopy(System::String^ ms, char* us) { for (int i(0); i < ms->Length; ++i) us[i] = static_cast<char>(ms[i]); us[ms->Length] = '\0'; } // usage example: Syste...
2,962,287
2,962,310
How would I instruct extconf.rb to use additional g++ optimization flags, and which are advisable?
I'm using Rice to write a C++ extension for a Ruby gem. The extension is in the form of a shared object (.so) file. This requires 'mkmf-rice' instead of 'mkmf', but the two (AFAIK) are pretty similar. By default, the compiler uses the flags -g -O2. Personally, I find this kind of silly, since it's hard to debug with an...
The quick and dirty way is to append -O0 to CXXFLAGS, which will turn off optimization. Later options will override earlier ones. As far as safety for a plugin, you should be able to do anything that doesn't affect the ABI. Without testing, I don't see why -funroll would. Of course, safe does not imply better. As ...
2,962,553
2,962,570
Real World strtod(); for use with WINAPI textbox
ResultBox1->Text = (sin(TextBox1->Text)) * TextBox2->Text That is what i would like to work, but im dealing with Strings I cant seem to convert the strings, do the trig, and convert back to string for displaying properly... anyone with an example?
System::Convert::ToDouble(TextBox1->Text) You said you're trying to convert a System::String^ so this should work for you.
2,962,589
2,963,843
What do I name this class whose sole purpose is to report failure?
In our system, we have a number of classes whose construction must happen asynchronously. We wrap the construction process in another class that derives from an IConstructor class: class IConstructor { public: virtual void Update() = 0; virtual Status GetStatus() = 0; virtual int GetLastErro...
I'd name it NullConstructor in line with the null object pattern, which is the pattern you're using. See http://en.wikipedia.org/wiki/Null_Object_pattern
2,962,767
2,962,801
When did C++ get nested classes?
Somehow I never noticed until today that C++ supports nested classes. This surprised me because when I was learning C++ back in the '90s, I specifically remember nested classes being something that Object Pascal and Java had, but which C++ did not. I asked an old programmer friend about it and he concurred that he re...
Nested classes were added in CFront 3.0, released in 1993. EDIT It goes back even earlier, as you can see in the table of contents to The Annotated C++ Reference Manual (1990).
2,962,852
2,962,861
debug error : max must have union class struct types
this is my code: #include <iostream> using namespace std; class Sp { private : int a; int b; public: Sp(int x = 0,int y = 0) : a(x), b(y) { }; int max(int x,int y); }; int Sp::max(int a,int b) { return (a > b ? a : b); }; int main() { int q,q1; cin >> q >>q1; Sp *mm = new Sp(q,q1)...
Instead of: mm.max(q,q1); you need to use: mm->max(q,q1); mm is a pointer and needs to be addressed as such. Alternately, you could just say: Sp mm(q,q1); cout<< mm.max(q,q1); and avoid pointers all together.
2,962,959
2,962,997
understanding the anatomy of file formats and image formats
I am trying to do some research on file formats especially image formats. Information such as header layouts for particular types of image formats and how to parse them using C++. If anyone can point me in the right direction of some good tutorials or books. that would be helpful. thanks [edit] If there are any resourc...
An indispensible source of information in this regard http://www.wotsit.org . You can also find some good info at the Amiga File Formats page (don't get misled by the "Amiga" in the title -- many of those formats are still used, and it's a great source of information). Also, a good source of information is magicdb.org...
2,963,283
2,963,308
sigwait in Linux (Fedora 13) vs OS X
So I'm trying to create a signal handler using pthreads which works on both OS X and Linux. The code below works on OS X but doesn't work on Fedora 13. The application is fairly simple. It spawns a pthread, registers SIGHUP and waits for a signal. After spawning the signal handler I block SIGHUP in the main thread so t...
The POSIX spec for sigwait() says: The signals defined by set shall have been blocked at the time of the call to sigwait(); otherwise, the behavior is undefined. You're not doing this. If you add: pthread_sigmask(SIG_BLOCK, &set, NULL); to your signal_handler() function immediately after the sigaddset(), then...
2,963,356
2,963,381
C++ forward declaration problem
I have a header file that has some forward declarations but when I include the header file in the implementation file it gets included after the includes for the previous forward declarations and this results in an error like this. error: using typedef-name ‘std::ifstream’ after ‘class’ /usr/include/c++/4.2.1/iosfwd:14...
Don't forward declare std:ifstream - just import <iosfwd> instead. ifstream is a typedef. See here for further details: http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.2/group__s27__2__iosfwd.html
2,963,396
2,963,451
GCC doesn't like C++ style casts with spaces
I am porting some C++ code to GCC, and apperantly it isn't happy with C++ style casting when sapces are involved, as in unsigned int(-1), long long(ShortVar) etc... It gives an error: expected primary-expression before 'long'. Is there any way to make peace with GCC without going over each one of those and rewrite in ...
GCC is correctly crying -- unsigned int(-1) is a notation that is not conformant with the C++03 standard (5.4.2): An explicit type conversion can be expressed using functional notation (5.2.3), a type conversion operator (dynamic_cast, static_cast, reinterpret_cast, const_cast), or the cast notation: cast-expression:...
2,963,539
2,963,554
Guidelines to an Iterator Class
I have a Red Black tree implemented in c++. It supports the functionality of a STL map. Tree nodes contain keys and the values mapped. I want to write an iterator class for this, but I'm stuck with how to do it. Should I make it an inner class of the Tree class? Can anyone give me some guidelines on how to write it + s...
Sure, read this nice article on writing STL iterators, it might give you the needed overview: http://www.drdobbs.com/184401417 In general, yes, an inner class is good, because the iterator needs access to your implementation specific tree nodes: struct container { ... public: struct iterator { // these typedefs a...
2,963,842
2,963,869
Friends, templates, overloading <<
I'm trying to use friend functions to overload << and templates to get familiar with templates. I do not know what these compile errors are: Point.cpp:11: error: shadows template parm 'class T' Point.cpp:12: error: declaration of 'const Point<T>& T' for this file #include "Point.h" template <class T> Point<T>::Poin...
Both the template parameter and the function parameter have the same name. Change it to something like: template <class T> std::ostream &operator<<(std::ostream &out, const Point<T> &point) { std::cout << "(" << point.xCoordinate << ", " << point.yCoordinate << ")"; return out; } The declaration of the friend ...
2,963,965
2,964,003
Why is 'virtual' optional for overridden methods in derived classes?
When a method is declared as virtual in a class, its overrides in derived classes are automatically considered virtual as well, and the C++ language makes this keyword virtual optional in this case: class Base { virtual void f(); }; class Derived : public Base { void f(); // 'virtual' is optional but implied. }...
Yeah, it would really be nicer to make the compiler enforce the virtual in this case, and I agree that this is a error in design that is maintained for backwards compatibility. However there's one trick that would be impossible without it: class NonVirtualBase { void func() {}; }; class VirtualBase { virtual void ...
2,964,266
2,964,371
display 25 randomnumbers from an array
I have in C++ an array of 100 elements, so v[1], ... ,v[100] contains numbers. How can i display, 25 random numbers from this array? So i wanna select 25 random positions from this array and display the values.. How can i do this in C++? Thanks! #include <cstdlib> #include <iostream> #include <math.h> #include <std...
I modified the version of Mehdi a little in order to make it choose differnet indexes NOTE: This makes the algorithm not deterministic - it relies on the RNG. int indexes[100]={0}; srand ( time (0) ); for (int i=0;i<25;i++) { int index = rand() % 100; if (indexes[index] != 0) { // try again ...
2,964,391
2,970,128
Preventing multiple process instances on Linux
What is the best way on Linux platform for the process (C++ application) to check its instance is not already running?
The standard way to do this is to create a pidfile somewhere, typically containing the pid of your program. You don't need to put the pid in there, you could just put an exclusive lock on it. If you open it for reading/writing and flock it with LOCK_EX | LOCK_NB, it will fail if the file is already locked. This is race...
2,964,516
2,964,777
Using pointers, references, handles to generic datatypes, as generic and flexible as possible
In my application I have lots of different data types, e.g. Car, Bicycle, Person, ... (they're actually other data types, but this is just for the example). Since I also have quite some 'generic' code in my application, and the application was originally written in C, pointers to Car, Bicycle, Person, ... are often pas...
If you don't want a full class, you should read up on FlyWeight pattern. It's designed to save up memory. EDIT: sorry, lunch-time pause ;) The typical FlyWeight approach is to separate properties that are common to a great number of objects from properties that are typical of a given instance. Generally, it means: stru...
2,964,654
3,549,297
Member is inaccessible from friend class
I have a declaration like this #include "Output/PtPathWriter.h" // class PtPathWriter // I've also tried forward declaring the friend class // leg data is a class designed to hold data for a single leg. class PtPathLeg { friend class PtPathWriter; // doesn't work //friend void PTPathWriter::writeToFile(string ...
Your little t should be a capital T in P**t**PathWriter.
2,964,702
2,964,723
C++ program crashes at runtime
I have this simple c++ program #include <cstdlib> #include <iostream> #include <math.h> #include <stdlib.h> #include <time.h> #include <vector> using namespace std; int aleator(int n) { return (rand()%n)+1; } int main() { int r; int indexes[100]={0}; // const int size=100; //int a[size]; std:...
aleator() returns a number between 1 and n, inclusive. However, this means it may return 100, which is outside the bounds of indexes[]. So get rid of the +1 in aleator(). Also, your vector v is of size zero. You can't ask for v[index] unless v[index] exists...
2,965,010
2,965,031
What does static linking against a library actually do?
Say I had a library called libfoo which contained a class, a few static variables, possibly something with 'C' linkage, and a few other functions. Now I have a main program which looks like this: int main() { return 5+5; } When I compile and link this, I link against libfoo. Will this have any effect? Will my execu...
It won't do anything in a modern linker, because it knows the executable doesn't actually use libfoo's symbols. With gcc 4.4.1 and ld 2.20 on my system: g++ linker_test.cpp -static -liberty -lm -lz -lXp -lXpm -o linker_test_unnecessary g++ linker_test.cpp -static -o linker_test_none ls -l linker_test_unnecessary linke...
2,965,011
2,965,082
Using static variable in function vs passing variable from caller
I have a function which spawns various types of threads, one of the thread types needs to be spawned every x seconds. I currently have it like this: bool isTime( Time t ) { return t >= now(); } void spawner() { Time t = now(); while( 1 ) { if( isTime( t ) )//is time is called in more than one...
Apart from the problem I cited in the comments to the question, you should avoid clever tricks like the plague. The first form (after fixing the bug) is cleaner and easier to understand. The second form, OTOH, confuses the reader by giving the impression that the assignment to t and the test t >= now() happen immediate...
2,965,018
2,965,071
C++ Add this pointer to a container by calling it in base class constructor
class Base { public: Base (int a, int b); private: int a,b; }; class Derived1 { public: Derived1():base(1,2){} }; similarly Derived2, Derived 3 which doesnt contain any data members on its own Now i need to contain these derived objects in a singleton, so i was thinking to call this in base constructor like Base::Bas...
If all the derived class call this base class constructor, yes, you should be fine. Just beware of the copy constructor which, if not overloaded, will not add this to your global vector. I suppose you want as well remove the instances that were destroyed, from the global vector ? If so, don't forget to declare Base::~B...
2,965,487
3,024,500
How can I hash a password and store it for later verification with another digest?
I am using gsoap's wsseapi plugin and would like to store hashed sha1 passwords rather than plain text. I have spent a ridiculous amount of time experimenting with various methods of hashing the plain text password for storage. Can anyone suggest a way to hash a password so it can be later verified against a username t...
Seems that the plain text password is required at both sides. This is so that on the server, the password stored is hashed using the nonce created at the client side and then the password hashes are compared. I thought there may have been a way for the client to enter a normal alphanumeric password and for the server ...
2,965,495
2,965,546
Constructor is being invoked twice
In code: //file main.cpp LINT a = "12"; LINT b = 3; a = "3";//WHY THIS LINE INVOKES CTOR? std::string t = "1"; //LINT a = t;//Err NO SUITABLE CONV FROM STRING TO LINT. Shouldn't ctor do it? //file LINT.h #pragma once #include "LINT_rep.h" class LINT { private: typedef LINT_rep value_type; const value_type* m...
You don't have an = operator which takes a RHS of std::string (or char*), so, the literal '3' is being constructed to a LINT, and then assigned using your = operator. EDIT: As for the 2nd question in your code, you need to call c_str() on the std::string to get the char* buffer of the string, then the same thing will h...
2,965,555
2,965,745
Equivalence of boolean expressions
I have a problem that consist in comparing boolean expressions ( OR is +, AND is * ). To be more precise here is an example: I have the following expression: "A+B+C" and I want to compare it with "B+A+C". Comparing it like string is not a solution - it will tell me that the expressions don't match which is of course fa...
I think the competing approach to exhaustive (and possibly exhausting) creation of truth tables would be to reduce all your expressions to a canonical form and compare those. For example, rewrite everything into conjunctive normal form with some rule about the ordering of symbols (eg alphabetical order within terms) a...
2,965,684
2,965,711
C++ - Error: expected unqualified-id before ‘using’
I have a C++ program and when I try to compile it it gives an error: calor.h|6|error: expected unqualified-id before ‘using’| Here's the header file for the calor class: #ifndef _CALOR_ #define _CALOR_ #include "gradiente.h" using namespace std; class Calor : public Gradiente { public: Calor(); Calor(int a)...
There is a semicolon missing at the end of this class: class Gradiente : public Sensor { protected: int vActual, vMin; public: Gradiente(); ~Gradiente(); } // <-- semicolon needed after the right curly brace. Also, the names of your include guards are illegal. Names that begin with an...
2,965,819
2,965,833
can i add .h and .cpp files in a c# project?
I want to add some .h and .cpp files to a C# project to get the C++ functionality in C#. I want to use the code directly without making a dll. Can i do so? How?
No you cannot. If the amount of code is small, you can write a C# class and paste pieces of the C++ code into it so that you essentially ported that class into C#. Obviously this won't work if you're using a language feature or library function that is not in C#. Alternatively you need to compile your C++ code into som...
2,965,864
3,584,680
What is your favorite/recommended project structure and file structure for Unit Testing using Boost?
I have not used Unit Testing so far, and I intend to adopt this procedure. I was impressed by TDD and certainly want to give it a try - I'm almost sure it's the way to go. Boost looks like a good choice, mainly because it's being maintained. With that said, how should I go about implementing a working and elegant file-...
Our Boost based Testing structure looks like this: ProjectRoot/ Library1/ lib1.vcproj lib1.cpp classX.cpp ... Library2/ lib2.vcproj lib2.cpp toolB.cpp classY.cpp ... MainExecutable/ main.cpp toolA.cpp toolB.cpp classZ.cpp ... Tests/ unittests.sln u...
2,965,927
2,965,986
C++ new & delete and functions
This is a bit unclear to me... So, if I have a function: char *test(int ran){ char *ret = new char[ran]; // process... return ret; } and then call it multiple times: for(int i = 0; i < 100000000; i++){ char *str = test(rand()%10000000+10000000); // process... // delete[] str; // do i have to del...
You don't have to. But if you don't delete memory you reserved with 'new' you will start running out of memory eventually (memory leak).
2,966,207
2,966,304
C++ macro definition unclear
Is this a macro defintion for a class or what exactly is it? #define EXCEPTIONCLASS_IMPLEMENTATION(name, base, string) : public base \ { \ public: \ name() : base(string) {} ...
It is a macro definition for an exception class. It looks somebody wants you to write code like this: class my_exception EXCEPTIONCLASS_IMPLEMENTATION(my_exception, std::exception, "What a mess!") The pre-processor will spit out: class my_exception : public std::exception { public: my_exception() : std::exception("Wha...
2,966,323
2,968,774
boost::asio and socket ownership
I've two classes (Negotiator, Client), both has their own boost::asio::ip::tcp::socket. Is there a way to transfer socket object to Client after negotiation is finished. I'm looking forward to do something like that: boost::asio::ip::tcp::socket sock1(io); //... boost::asio::ip::tcp::socket sock2; sock2.assign(sock...
I think that you could: obtain sock1's native handle with the native() member function dup() (or WSADuplicateSocket()) sock1's native handle pass the dup()-ed handle to sock2 with the assing() member function However: I'm not sure as I never tried that If you want to transfer (instead of sharing) the socket from Neg...
2,966,413
2,966,484
Windows/C++: detect when focus has changed between windows (globally)
I'm trying to find a way to detect when focus is changed to another window (without having to poll every X ms). I've already figured out a way to detect when focus is switched between applications using WH_SHELL and HSHELL_ACTIVATESHELLWINDOW. The problem is I want to detect when focus is switched between dialog/window...
You can use SetWindowsHookEx with a WH_CBT hook type. If you just want to detect focus changes within an application, pass GetCurrentThreadId() as the last parameter, otherwise the hook will be for all threads on the current desktop. Note that using windows hooks can have an adverse effect on system performance, so th...
2,966,493
2,966,522
C++ new & delete and string & functions
Okay the previous question was answered clearly, but i found out another problem. What if I do: char *test(int ran){ char *ret = new char[ran]; // process... return ret; } And then run it: for(int i = 0; i < 100000000; i++){ string str = test(rand()%10000000+10000000); // process... // no...
Here you are not converting the char* to a [std::]string, but copying the char* to a [std::]string. As a rule of thumb, for every new there should be a delete. In this case, you'll need to store a copy of the pointer and delete it when you're done: char* temp = test(rand()%10000000+10000000); string str = temp; delete[...
2,966,510
2,968,497
How to install and run the examples of QtOpenCl, i.e. Qt in OpenCl?
The thing is I have to run the OpenCl examples, as given here:http://labs.trolltech.com/blogs/2010/04/07/using-opencl-with-qt/. The problem is that I have no clue where to start. I downloaded the source for QtOpenCl but it needs a valid OpenCl installation. I have Qt installed already. How do I install OpenCl? I don't ...
The ATI Stream SDK contains a CPU OpenCL implementation that you can use: http://ati.amd.com/technology/streamcomputing/sdkdwnld.html Installing it will give you a working OpenCL CPU Implementation.
2,966,764
2,967,501
Porting a project to OpenGL3
I'm working on a C++ cross-platform OpenGL application (Windows, Linux and MacOS) and I am wondering if some of you could share some advices on porting a large application to OpenGL 3. The reason I am looking into OpenGL 3 is because I think we could benefit a lot from using the new "Sync objects". Nvidia has supported...
The last update to glut was version 3.7, roughly 10 years ago. Taking that into account, I doubt that it'll ever support OpenGL 3.x (or 4.x). The people working on OpenGlut seem to be considering the possibility of OpenGL 3.x support, but haven't done anything with it yet. FLTK has a (partial) glut simulation, but it's...
2,966,952
2,966,964
How to set QWidget width?
How to set QWidget width? I know setGeometry(QRect& rect) function to do that, but in that case I should use geometry() function to get former parameters of my QWidget, then I should increment the width and use setGeometry(..). Is there any direct way to that, say: QWidget aa; aa.setWidth(165); //something like this? ...
resize() might be better to use. Example usage: widget->resize(165, widget->height());
2,966,992
2,978,894
Where is iTunes SDK/API documentation?
I downloaded a zipped archive from Apple that consists of a C++ header file and source. Included in this was a help file. For some reason this help file opens but I cannot read the content. Is there any other documentation outside of a help file for this? For c++ or c#?
Solved.. The problem was a Windows Security feature was blocking the compiled help file from opening. I found the solution here: http://weblog.helpware.net/?p=36
2,966,993
2,967,255
Why does my Application not run using the x64 Version of Windows Server 2008?
I have a Win32 C++ Application using a handful of third-Party DLLs that is installed at some hundred costumer machines. I recently tested the x86 Version of the installation successfully on Windows XP, Windows Vista x64, Windows 7 x86 as well as Windows Server 2008 x86. No Problems. The Installer (nullsoft) installs th...
It doesn't look like a side-by-side error. The exception code is STATUS_INVALID_PARAMETER, "An invalid parameter was passed to a service or function." That doesn't help. You'll need a debugger, probably with the Windows debugging symbols. Make it stop on the first-chance exception.
2,966,997
2,967,011
C equivalent of C++ delete[] (char *)
What is the C equivalent of C++ delete[] (char *) foo->bar; Edit: I'm converting some C++ code to ANSI C. And it had: typedef struct keyvalue { char *key; void *value; struct keyvalue *next; } keyvalue_rec; // ... for ( ptr = this->_properties->next, last = this->_properties; ptr!=NULL; last = pt...
In C, you don't have new; you just have malloc(); to free memory obtained by a call to malloc(), free() is called. That said, why would you cast a pointer to (char*) before passing it to delete? That's almost certainly wrong: the pointer passed to delete must be of the same type as created with new (or, if it has cla...
2,967,015
2,967,070
Set a C++ bitset from a binary input steam
I have an input stream from a binary file. I want to create a bitset for the first 5 bits of the stream. Here is the code I have so far: ifstream is; is.open ("bin_file.out", ios::binary ); bitset<5> first_five_bits; is >> first_five_bits; // always is set to default 00000
char c; if( ! cin.get(c) ) throw ROFL(); // return error, flip bit, call mom bitset<5> first_five_bits(c >> (CHAR_BIT-5)); // CHAR_BIT in <climits>
2,967,062
2,967,089
c++ try catch practices
Is this considered good programming practice in C++: try { // some code } catch(someException) { // do something } catch (...) { // left empty <-- Good Practice??? }
No! That is a terrible practice! Just about the only time you should catch (...) and not rethrow the exception would be in main() to catch any otherwise unhandled exceptions and to display or log an error before exiting. If you catch (...), you have absolutely no idea what exception was thrown, and thus you can't know...
2,967,128
2,979,380
Seeking suggestions on redesigning the interface
As a part of maintaining large piece of legacy code, we need to change part of the design mainly to make it more testable (unit testing). One of the issues we need to resolve is the existing interface between components. The interface between two components is a class that contains static methods only. Simplified exam...
The simplest answer is to wrap the old library that has the static interface in a facade, then refactor the code to call the new facade instead of the old library. This new wedge should permit substitution of the library for unit testing purposes. Test it out on a single method first, just to see how to implement it....
2,967,818
2,967,846
Can C++ memory leaks negatively affect CPU usage?
I have a C++ program that has a pretty terrible memory leak, about 4MB / second. I know where it's coming from and can fix it, but that's not my main problem. My program is taking up a very large amount of CPU usage and it isn't running as fast as I want it to. I have two different threads in the program. One by itself...
Regardless of whether or not your memory leak is causing the problem it needs to be fixed. Once you fix the memory leak see if you're still having the problem. You should be able to answer your own question at that point.
2,967,854
2,967,926
Working on a cross platform library
What are the best practices on writing a cross platform library in C++? My development environment is Eclipse CDT on Linux, but my library should have the possibility to compile natively on Windows either (from Visual C++ for example). Thanks.
To some extent, this is going to depend on exactly what your library is meant to accomplish. If you were developing a GUI application, for instance, you would want to focus on using a well-tested cross-platform framework such as wxWidgets. If your library depends primarily on File IO, you would want to make sure you us...
2,968,067
2,968,203
VS2008 Link Error Using SafeInt3.hpp in 64bit mode
I have the below code that links and runs fine in 32bit mode - #include "safeint3.hpp" typedef SafeInt<SIZE_T> SAFE_SIZE_T; SAFE_SIZE_T sizeOfCache; SAFE_SIZE_T _allocateAmt; Where safeint3.hpp is current version that can be found on Codeplex SafeInt. For those who are unaware of it, safeint is a template class that ...
The problem is that inside safeint3.hpp, the code looks like this: bool IntrinsicMultiplyUint64( const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet ) { .... } This means every translation unit that includes safeint3.hpp will get a definition of IntrinsicMultiplyUint64. If you are willing...
2,968,158
2,968,413
How to check value of defined symbols (Eclipse->Paths & Symbols) in a makefile?
We have a project that used to be an Eclipse-managed CDT project. However, I am trying to change it to a standard makefile project. One of them has a couple of symbols defined in Project Properties->C/C++ General->Paths & Symbols->Symbols. The makefiles generated by Eclipse used to automatically get the value when it...
Use environment variables and conditionals to tell your options to make. Something like: DEFINES = -DFOO ifeq ($(COMPILE_FOR_A),1) DEFINES += -DBAR else DEFINES += -DBAZ endif Then invoke make with/without the variable in the environment: ~$ COMPILE_FOR_A=1 make
2,968,172
2,968,271
How to share an array in Python with a C++ Program?
I two programs running, one in Python and one in C++, and I need to share a two-dimensional array (just of decimal numbers) between them. I am currently looking into serialization, but pickle is python-specific, unfortunately. What is the best way to do this? Thanks Edit: It is likely that the array will only have 50 e...
I suggest Google's protobuf
2,968,336
3,022,562
Qt - Password field, warn about Caps-Lock
Is there any Qt-built-in method to warn user (with pop-up window) that CapsLock is switched on while password field is active? I am currently using QLineEdit (is it good?) with setEchoMode(QLineEdit::Password).
I have soved this problem already. I have used QToolTip QT - How to apply a QToolTip on a QLineEdit as a way to inform user about caps lock stat, and used, of course, a function that gets current state ( GetKeyState(VK_CAPITAL)). Disadvantage: this works on Windows only.
2,968,365
3,007,880
Qt - Disabling QDialog's "?" button
I create an instance of QDialog and on the left of 'x' (close) button i have also '?' button. How I can disable that '?' ?
Change the window flags, for example in the constructor: this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
2,968,380
2,968,654
Simplest way to provide template specialization for derived classes
I have the following scenario: class my_base { ... } class my_derived : public my_base { ... }; template<typename X> struct my_traits; I want to specialize my_traits for all classes derived from my_base including, e.g.: template<typename Y> // Y is derived form my_base. struct my_traits { ... }; I have no problems...
Well, you don't need to write your own isbaseof. You can use boost's or c++0x's. #include <boost/utility/enable_if.hpp> struct base {}; struct derived : base {}; template < typename T, typename Enable = void > struct traits; template < typename T > struct traits< T, typename boost::enable_if<std::is_base_of<base, T...
2,968,814
2,968,838
extend php with java/c++?
i only know php and i wonder if you can extend a php web application with c++ or java when needed? i dont want to convert my code with quercus, cause that is very error prone. is there another way to extend it? cause from what i have read python can extend it with c++ without converting the python code and use java wit...
Most of PHP is written in modular C code. You can create your own PHP extensions in C. See http://php.net/internals, the PHP wiki and the book "Extending and Embedding PHP" by Sara Golemon.
2,968,915
2,968,954
C++: How to use types that have not been defined?
C++ requires all types to be defined before they can be used, which makes it important to include header files in the right order. Fine. But what about my situation: Bunny.h: class Bunny { ... private: Reference<Bunny> parent; } The compiler complains, because technically Bunny has not been...
The answer to your question depends on what Reference<> looks like. If it has an instance variable of type Bunny in it then of course it won't work (how would it, you have a recursive definition that never ends). If it has only references and pointers in it then it should work fine. The Bunny type in the template in...
2,969,033
2,969,079
Recursive breadth-first travel function in Java or C++?
Here is a java code for breadth-first travel: void breadthFirstNonRecursive(){ Queue<Node> queue = new java.util.LinkedList<Node>(); queue.offer(root); while(!queue.isEmpty()){ Node node = queue.poll(); visit(node); if (node.left != null) queue.offer(node.left); i...
I can't imagine why you'd want to, when you have a perfectly good iterative solution, but here you go ;) void breadth_first(Node root): Queue q; q.push(root); breadth_first_recursive(q) void breadth_first_recursive(Queue q): if q.empty() return; Node n = q.pop() print "Node: ", n if (n.left) q.push(n.le...
2,969,034
2,998,222
Best way to access nested data structures?
I would like to know what the best way (performance wise) to access a large data structure is. There are about hundred ways to do it but what is the most accessible for the compiler to optimize? One can access a value by foo[someindex].bar[indexlist[i].subelement[j]].baz[0] or create some pointer aliases like sometype...
As a personal preference, I generally find it easier to read and understadn if there are fewer nested levels to traverse. Thus, I tend to use the ... SomeType *pSomeType = &asManyLevelsAsItMakesSense[someIndex]; pSomeType->subSomeNestedLevels = ...; I find this particularly useful when dealing with deep nested struc...
2,969,222
2,969,244
Make GNU make use a different compiler
How can I make GNU Make use a different compiler without manually editing the makefile?
You should be able to do something like this: make CC=my_compiler This is assuming whoever wrote the Makefile used the variable CC.
2,969,271
2,969,380
Strange error: cannot convert from 'int' to 'ios_base::openmode'
I am using g++ to compile some code. I wrote the following snippet: bool WriteAccess = true; string Name = "my_file.txt"; ofstream File; ios_base::open_mode Mode = std::ios_base::in | std::ios_base::binary; if(WriteAccess) Mode |= std::ios_base::out | std::ios_base::trunc; File.open(Name.data(), Mode); And I receive...
openmode is the correct type, not open_mode.
2,969,312
2,970,663
Create an instance from a static method
let's say I want my users to use only one class, say SpecialData. Now, this data class would have many methods, and depending on the type of data, the methods do different things, internally, but return externally similar results. Therefore my wanting to have one "public" class and other "private", child classes that ...
Well, you've got three choices: a) You want to have only one instance of SuperMatrix anyway. Then go for the static function member route as has already been suggested. b) You want to create multiple instances. Then you have to return a pointer instead of references and create the objects with with new (i.e. return new...
2,969,383
2,969,432
Virtual destructors for interfaces
Do interfaces need a virtual destructor, or is the auto-generated one fine? For example, which of the following two code snippets is best, and why? Please note that these are the WHOLE class. There are no other methods, variables, etc. In Java-speak, this is an "interface". class Base { public: virtual void foo() =...
Consider the following case: Base *Var = new Derived(); delete Var; You need the virtual destructor, otherwise when you delete Var, the derived class' destructor will never be called.
2,969,387
2,969,417
Why operator= returns reference not const reference
The original question is related to overloading operator= and I like to share my findings as it was nontrivial for me to find them. I cannot imagine reasonable example to use (a=b) as lvalue. With the help of IRC and google I've found the next article: http://msdn.microsoft.com/en-us/magazine/cc301415.aspx it provid...
One good reason is that one of the requirements in the standard for a class X to be useable in the standard containers is that the expression a = b must have type X& (where a is an lvalue of type X and b is an rvalue of type X).
2,969,596
2,969,621
Passing variables to functions
A quick question: When i pass a variable to a function, does the program make a copy of that variable to use in the function? If it does and I knew that the function would only read the variable and never write to it, is it possible to pass a variable to the function without creating a copy of that variable or should...
Yes, parameters passed by value are copied. However, you can also pass variables by reference. A reference is an alias, so this makes the parameter an alias to a variable, rather than a copy. For example: void foo(int x) {} void bar(int& x) {} int i; foo(i); // copies i, foo works with a copy bar(i); // aliases i, ba...
2,969,616
2,969,704
Writing a windows web service and not sure what language to use?
So I am required to write a fairly basic Windows service and have never done so before. Of C#, C++ (the Visual Studio suite), what is the best language to develop in? I am a student, and am most familiar with OO languages such as Java. Additionally, if anyone can recommend any books, articles, or google searches that w...
As others have stated, C# is a lot closer to java than C++. With respect to Web services, which I take to be your focus based on the title and tags of your question, there are two options in .NET, ASMX or WCF. ASMX web services are the older technology, basically ASP.NET intercepts and processes requests using the ASP....
2,969,691
2,969,722
How do I get the length of a VBO to render all vertices when using glDrawArrays()?
I create a VBO in a function and I only want to return the VBO id. I use glDrawArrays in another function and I want it to draw all the vertices in the VBO without needing to also pass the number of vertices. The VBO also contains texture coordinate data. Thank you.
You need to return it, sorry. Data about the VBO might live somewhere far away from your CPU and be slow to access, so you need to keep locally whatever data you need.
2,969,709
2,969,751
const object and const constructor
Is there any way to know if an object is a const object or regular object, for instance consider the following class class String { String(const char* str); }; if user create a const object from String then there is no reason to copy the passed native string and that because he will not make any manipulation on it,...
There is a very good reason for copying - you can't know that the lifetime of the const char * is the same as that of the String object. And no, there is no way of knowing that you are constructing a const object.
2,969,843
2,977,559
Validate Unicode String and Escape if Unicode is Invalid (C/C++)
I have a program that reads arbitrary data from a file system and outputs results in Unicode. The problem I am having is that sometimes filenames are valid Unicode and sometimes they aren't. So I want a function that can validate a string (in C or C++) and tell me if it is a valid UTF-8 encoding. If it is not, I want t...
The following code is based on an IRI library I have been working on for awhile. Section 3.2 ("Converting URIs to IRIs") of RFC 3987 deals with converting invalid UTF-8 octets to valid UTF-8. #define IS_IN_RANGE(c, f, l) (((c) >= (f)) && ((c) <= (l))) int UTF8BufferToUTF32Buffer(char *Data, int DataLen, unsigned l...
2,970,007
2,970,022
Friends, templates, overloading << linker errors
I had some good insight to an earlier post regarding this, but I have no idea what these compile errors mean that I could use some assistant on. Templates, friends, and overloading are all new, so 3 in 1 is giving me some problems... 1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Point<doub...
With most compilers, you need to put templates in headers, so they're visible to the compiler where they're used. If you really want to avoid that, you can use explicit instantiation of the template(s) over the necessary types, but putting them in a header is much more common.
2,970,170
2,975,877
Network time out when trying to connect ipod touch to my server
I have an ipod touch program that should receive messages from a server program on my mac. To make sure that the touch can receive messages from a computer other than a mac, I programmed the server in C++. If I run both the server and the ipod app on the same computer (the app running on the simulator), the connection ...
The iPod was connected to a different network than my Mac, and that's why it got blocked. When I connected to the same network, it works perfectly fine.
2,970,209
2,970,230
Do dll's ever turn into machine code?
Just curious, I was told that with dll files, you can make modifications to the dll without recompiling the whole application that uses it. On the other hand .lib files need to be compiled so the code can linked to the application as one. So I know that the .lib files are turned into machine code. but what about the d...
The dlls are still machine code. They're just dynamically linked in at run time (hence then name) so (if you don't change the function signatures) you don't have to recompile your main program to use a dll after it's been changed. A static library is physically part of your executable, that's why changes there requir...
2,970,253
2,970,261
Confused with implicit and explicit template declarations
I'm getting confused with implicit and explicit declarations. I don't know why you need to explicitly say or at certain times. For example, In my main.cpp #include <iostream> #include "Point.h" int main() { Point<int> i(5, 4); Point<double> *j = new Point<double> (5.2, 3.3); std::cout << i << *j; ...
For a class template, the template arguments must be specified explicitly. For a function template, the template arguments can be inferred implicitly. Point is a class, so explicit declaration is required.
2,970,436
2,970,528
How to determine the name of the DLL (string) that loaded my DLL?
I'm writing a device driver that is loaded by a 3rd-party driver. I need a way to determine the name of the 3rd-party driver that is loading my device driver (for debug purposes). For example, GetModuleFileName will provide me the name of the executable. I'd like instead to be able to get the DLL names. The stack t...
I assume you've got a process handle, or id of the process your my.dll is loaded in. See an MSDN example at http://msdn.microsoft.com/en-us/library/ms686701(v=VS.85).aspx which will take a snapshot of a process and give all information. The interesting method is at BOOL ListProcessModules( DWORD dwPID ): MODULEENTRY32 ...
2,970,455
2,970,483
What would be the best way to implement a constant object?
First of all I should probably say that the term 'constant object' is probably not quite right and might already mean something completely different from what I am thinking of, but it is the best term I can think of to describe what I am talking about. So basically I am designing an application and I have come across s...
If you want the values to be constant, then you will not need setters, otherwise code can simply change the values in your constants, making them not very constant. In C++, you can just declare the instances const, although I'd still get rid of the setters, since someone could always cast away the const. The pattern lo...
2,970,490
3,013,794
Most Lite-Weight XML Parser with XPath and Wide-char Support
I want a lite-weight C++ XML parser/DOM that: Can take UTF-8 as input, and parse into UTF-16. Maybe it does this directly (ideal!), or perhaps it provides a hook for the conversion (such as taking a custom stream object that does the conversion before parsing). Offers some XPath support. I've been looking at RapidXM...
pugixml has an UNICODE branch. I guess UNICODE will be officially supported in the next version (0.6)
2,970,607
2,970,611
isdigit() c++, probably simple question, but stuck
I'm having trouble with isdigit. I read the documentation, but when I cout << isdigit(9), I get a 0. Shouldn't I get a 1? #include <iostream> #include <cctype> #include "Point.h" int main() { std::cout << isdigit(9) << isdigit(1.2) << isdigit('c'); // create <int>i and <double>j Points Point<int> i(5, ...
isdigit() is for testing whether a character is a digit character. If you called it as isdigit('9'), it would return nonzero. In the ASCII character set (which you are likely using), 9 represents the horizontal tab, which is not a digit. Since you are using the I/O streams for input, you don't need to use isdigit() to...
2,971,040
2,971,049
Global - Local difference in the init of an array in c
Why this dont work: int size = 2; int array[size]; int main() { return 0; } It says the error: array bound is not an integer constant And this work: int size = 2; int main() { int array[size]; return 0; } Anyone knows the reason? thanks
In C++ or C89/90 neither works. These languages require that array size is an Integral Constant Expression (ICE). In your examples size is not an ICE. If your C++ or C89/90 compiler allows it, it is nothing else than a non-standard compiler extension. In C99 the second works because this is how Variable Array Length (V...
2,971,103
2,971,116
Can't push vector of vector of GlDouble?
I have a vector which accepts vectors of GlDouble vectors. But when I try to push one it says: Error 1 error C2664: 'std::vector<_Ty>::push_back' : cannot convert parameter 1 from 'std::vector<_Ty>' to 'const std::vector<_Ty> &' c:\Users\Josh\Documents\Visual Studio 2008\Projects\Vectorizer Project\Vectorizer Project\V...
Edit: After new additions, the problem is not const - the problem is that you're trying to push the wrong type. std::vector<std::vector<GLdouble> > v; v.push_back(std::vector<GLdouble>()); // works; pushing contained type v.push_back(std::vector<std::vector<GLdouble> >()); // <-- error: trying to push type of containe...
2,971,254
2,971,274
c++, sleep, and loops
Ok, this is just out of curiousity, but why does the sleep function NOT work in a loop, or how can I Get it to work in a loop? for(int i = 0; i < 5; i++) { cout << i << endl; sleep(2); }
cout is buffered, meaning its contents aren't always written to the console right away. Try adding cout.flush() right before sleep(2);