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
3,482,178
3,482,274
How do you read the 128-bit NTFS FILE_ID for a directory and/or file?
So NTFS uses a 128-bit Guid to identify files and directories, you can view this information easily enough: C:\Temp>C:\Windows\System32\fsutil.exe objectid query . Object ID : ab3ffba83c67df118130e0cb4e9d4076 BirthVolume ID : ca38ec6abfe0ca4baa9b54a543fdd84f BirthObjectId ID : ab3ffba83c67df118130e0cb4e9d4076...
A bit of searching took me to DeviceIoControl and there lies the answer to your question: FSCTL_GET_OBJECT_ID returns exactly the same IDs as in your output from fsutil. Anyhow, the docs for BY_HANDLE_FILE_INFORMATION say that the 64-bit file ID already uniquely identifies a file on a given volume. According to Wikiped...
3,482,303
3,482,317
What does the '&' means in a Unary Operator of a Class?
class CDate { // some declarations public: CDate& operator ++ () { // increment function; return *this; } }; Does the '&' mean a reference that is being a return? Thanks SpecC
Yes, you answered your own question. CDate & simply means that the operator returns a reference to a CDate object. It has no special meaning because it's an operator, it means the same in any other function.
3,482,592
3,482,732
fatal error C1083: Cannot open include file: 'boost/config.hpp': No such file or directory
I think I did all the necessary configuration but I am still getting this: Error 1 fatal error C1083: Cannot open include file: 'boost/config.hpp': No such file or directory File:c:\documents and settings\administrator\my documents\visual studio 2008\libs\boost_1_43_0\boost\smart_ptr\shared_ptr.hpp Line:17 Here are...
I finally found the answer :) and I will write it here to help. Project>"YOURPROJECT" Properties>C/C++>General>Additional Include Directories then select where you downloaded your library . This worked and all the above didn't, so make sure not to forget it .
3,482,672
3,482,764
How to access multiple levels of overridden elements?
How do I access overridden members of base classes of base classes? #include <iostream> using namespace std; class A {public: char x; A(){x='A';};}; class B1 : public A {public: char x; B1(){x='B';};}; class B2 : public A {public: char x; B2(){x='B';};}; class C : public B1, public B2 {public: char x; C(){x='C';};}; ...
You can access both version of A via reference casts plus the scoping operator, likes this: ((B1&) c).A::x and ((B2&) c).A::x. cout << ((A&) c).x << endl; fails on my compiler because the compiler doesn't know which copy of A's data you want to operate on.
3,482,718
3,482,798
QFile open file for writing fails
I'm trying to open file and write some text data into it. QFile out(":/test.txt"); if (!out.open(QIODevice::ReadWrite)) { QMessageBox msgBox; msgBox.setText(out.errorString()); msgBox.exec(); return; } But it fails with "Unknown error". (Qt 4.6, Wnidows XP SP3)
":/test.txt" is a name of a resource file embedded to the executable and you can't write to it. Change the file name for example to "C:/test.txt".
3,482,763
3,572,668
How to create IPP (Intel Performace primitives) C++ wrapper functions?
IPP is a C library, with hundreds of functions like this: IppStatus ippiTranspose_8u_C1R(const Ipp8u* pSrc, int srcStep, Ipp8u* pDst, int dstStep, IppiSize roiSize)); To be able to call these functions in a more convenient, safe and consistent way, we need ...
There are some kind of wrappers, provided by Intel, which are well hidden in ipp-samples for windows only. I'm using the latest 7.0 beta version. They provide C++ headers, generated by a perl script, which are supposed to be used as a C++ wrappers. The "wrapper" for the ippiTranspose_8u_C1R function in the question is ...
3,482,854
3,483,075
detecting memory leaks in C++ / windows
For debugging purposes, when I'm writing an app, the first thing I do is put the following into the stdafx.h: // -- leak detection ---------------------------------------------------------- #ifdef _DEBUG // http://msdn.microsoft.com/en-us/library/e5ewb1h3(v=VS.80).aspx #define _CRTDBG_MAP_ALLOC #include <stdlib.h...
Visual Leak Detector - pretty easy to use and there'e no overhead for the app built in release.
3,482,941
3,483,026
How do you 'realloc' in C++?
How can I realloc in C++? It seems to be missing from the language - there is new and delete but not resize! I need it because as my program reads more data, I need to reallocate the buffer to hold it. I don't think deleteing the old pointer and newing a new, bigger one, is the right option.
Use ::std::vector! Type* t = (Type*)malloc(sizeof(Type)*n) memset(t, 0, sizeof(Type)*m) becomes ::std::vector<Type> t(n, 0); Then t = (Type*)realloc(t, sizeof(Type) * n2); becomes t.resize(n2); If you want to pass pointer into function, instead of Foo(t) use Foo(&t[0]) It is absolutely correct C++ code, because...
3,483,085
3,483,087
What is the right way to put a smart pointer in class data (as class member) in C++?
Suppose I have a class Boda: class Boda { ... }; And I have a member cydo in this class that I want to be a smart pointer (that is, I want it to get deallocated automatically as soon as the class gets destroyed). I am using Boost's smart pointers, so I write: class Boda { boost::shared_ptr<int> cydo; publi...
class Boda { boost::shared_ptr<int> cydo; public: Boda () : cydo(new int(5)) {} }; Though, I can't think why you'd want to wrap an int ... :)
3,483,292
3,483,378
QGraphicsView noobie question
Trying to add text to QGraphicsView: Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); QGraphicsScene scene; scene.addText("Hello, world!"); ui->graphicsView->setScene(&scene); } But when the project running, there is nothing on the QGraphicsView.
Your QGraphicsScene scene is a local variable and it is deleted immeadiately after the Widget's constructor has been executed. Change the scene to a private member variable of the Widget class.
3,483,327
3,483,863
Deleting char array returned by getenv()
Should I free the memory allocated for the char array, pointer to which is returned by the char * getenv( char * ) function? And which way - C free() or C+ delete []? If no - why? I mean: char * ptr = getenv( "LS_COLORS" ); cout << ptr << endl; delete [] ptr; //Is this or free() call needed? Thank you.
The original data is stored in the environ variable (which is an array of char* and contains all environment variables with their values), getenv() only search for the corresponding variable name and returns the position of its value from the environ variable, so you don't have to free it, otherwise undefined behavior ...
3,483,407
3,484,112
looking for scripting language for automated build & deploy
I'll start to write a automated build/deploy script for our software team, and I'm not sure which scripting language or tool to use. I'm always eager to learn something new and improve my value on the current software market, so what language do you propose? In the past, I used windows batch files, which are kind of u...
It was briefly mentioned, I like PERL for these sorts of things. On an absolutely humongous project I worked on, we had perl scripts practically running the entire build process. It even built classes based upon messaging templates. It was pretty cool, and this was a Windows project to boot. CPAN provides an enormous r...
3,483,455
3,483,556
What should be the right file permissions for program executables and logs files?
I have written a Linux system wide C++ program /usr/bin/PROG_X that uses a configuration file /etc/PROG_X.conf and log file /var/PROG_X.log. Now I need to call this program, after strong authentication, from the web using apache web server and php. Calling the program may involve changing configuration files and will c...
For the most locked-down approach (assuming the log and config are sensitive): Apache runs as user 'www', 'progx' user and group exists for the sole purpose of running /usr/bin/PROG_X. /etc/PROG_X.conf is owned by root:progx, and has permissions 640 /var/PROG_X.log is owned by root:progx, and has permissions 660 /usr/b...
3,483,588
3,483,596
Why does VS require constant for array size, and MinGW does not? And is there a way around it?
I have ported some code from Mingw which i wrote using code::blocks, to visual studio and their compiler, it has picked up many errors that my array sizes must be constant! Why does VS need a constant size and mingw does not? e.g. const int len = (strlen(szPath)-20); char szModiPath[len]; the len variable is underlin...
Why does VS need a constant size and mingw does not? Because Variable Length Arrays are not a part of C++ although MinGW(g++) supports them as extension. Array size has to be a constant expression in C++. In C++ it is always recommended to use std::vector instead of C-style arrays. :)
3,483,639
3,483,658
Problem with conversion
I have a class: template<class T> class MyClass { public: class Iterator { public: Iterator(MyClass<T>&){/*some code*/}; }; operator Iterator(); Iterator& begin(); }; template<class T> MyClass<T>::operator typename MyClass<T>::Iterator()...
begin() cannot return a reference to an Iterator; it needs to return an Iterator by value. When the user-declared conversion to Iterator is called, it yields a temporary Iterator object. A non-const reference cannot be bound to a temporary, hence the error you get when begin() returns a reference. That said, having a ...
3,483,776
3,483,857
C++: Files, encodings and datatypes
---- PLEASE CLOSE ---- ------ Edit --------- I found where the problem is. I'm going to start a new question for the real problem .... ----------------------   Hi, My Situation: Linux (Ubuntu 10.04) gcc But it has to be platform independent I have a text file (UTF-8) with special characters like ¥ © ® Ỳ È Ð. I ha...
use while( !in ) instead of the eof variant, it's better, see this question I'm assuming you're using Windows (as Linux and Mac normally have native UTF-8 platform encoding, which allows you to ignore most of this stuff). What I would do is read the whole file as chars and convert it to wchar_t's using the handy func...
3,483,910
3,484,023
Is there a place where we can see PHP <=> C++ equilavent libraries/function for a php developer starting with C++?
Is there a place where we can see PHP <=> C++ equilavent libraries/function for a php developer starting with C++? As a PHP developer starting with C++, I often ask myself: what is the equivalent of such-and-such PHP function in C++? The advantage of php, is that we have a very nice site which documents about everythin...
There is no direct mapping for all php functionality to C++. The languages are just too different and are designed for completely different purposes. All C++ standard libraries are documented here: http://www.sgi.com/tech/stl http://www.boost.org http://www.cplusplus.com/reference/iostream/ Here is a link to Stack ov...
3,483,932
3,484,028
When the virtual member functions of a template class instantiated?
I know that the normal member function of a template class will be instantiated whenever it is used for the first time. But this cannot be done for the virtual member function as it can be accessed through a base class pointer. Does this mean that virtual member functions will be instantiated as soon as the template cl...
14.7.1/9 in C++03: An implementation shall not implicitly instantiate a function template, a member template, a non-virtual member function, a member class or a static data member of a class template that does not require instantiation. It is unspecified whether or not an implementation implicitly instantiates a virtu...
3,483,965
3,483,991
C++: std::string problem
I have this simple code: #include <iostream> #include <fstream> using namespace std; int main(void) { ifstream in("file.txt"); string line; while (getline(in, line)) { cout << line << " starts with char: " << line.at(0) << " " << (int) line.at(0) << endl; } in.close(); return 0;...
You are getting the first character in the string. But it looks like the string is a UTF-8 string (or possibly some other multibyte character format). This means each symbol (glyph) that os printed is made of 1 (or more characters). If it is UTF-8 then any character that is outside the ASCII (0-127) range is actually m...
3,484,123
3,484,155
How to use C++ Smart Pointers?
I've been using C++ for some time now and I still don't feel very comfortable about using smart pointers and I've only been using them when editing some code that uses them, never in my own code (it might be worth to say that I'm a student). Can you explain what are the types of smart pointers, how do they work and whe...
C++98 does not provide any smart pointers except auto_ptr which is fraught with its own issues. C++0X tries to fix this by bringing in a few more varieties (shared_ptr, unique_ptr etc.). In the meantime the best bet is to use Boost. Take a look at the various flavors available to you here. Boost is community driven, ex...
3,484,221
3,567,791
algorithm to match prefix and name to a list of names
I have a std::vector<std::string> of all the files in a directory: // fileList folder/file1 folder/file2 file3 file4.ext and a std::set<std::string> of filenames and the same for all used folder prefixes: // set1 file2 file4.ext // set2 folder I need to generate the full (relative) paths to the ALL files in set1, bu...
One area which you are not clear about is this: Given set1 & set2 as described above, what if fileList had "file4.ext" and "folder\file4.ext". Would you want both? Or is the list of file in set1 guaranteed to be unique? Assuming that you'd want both, pseudo-code: foreach(pathname in fileList) separate pathna...
3,484,371
3,487,099
What's the difference between type(myVar) and (type)myVar?
I'm going through the full tutorial at cplusplus.com, coding and compiling each example manually. Regularly, I stumble upon something that leaves me perplexed. I am currently learning this section: http://www.cplusplus.com/doc/tutorial/structures/ . There are some subtleties that could easily be overlooked by only read...
There is no difference between type(x) and (type)x. These two are completely equivalent. Most people prefer type(x) for classes and (type)x for non-class types, but that's purely up to one's own choice. Both call constructors for classes with one argument x. The preferred way for classes is type(x), because this allow...
3,484,434
3,484,541
What does "#pragma comment" mean?
What does #pragma comment mean in the following? #pragma comment(lib, "kernel32") #pragma comment(lib, "user32")
#pragma comment is a compiler directive which indicates Visual C++ to leave a comment in the generated object file. The comment can then be read by the linker when it processes object files. #pragma comment(lib, libname) tells the linker to add the 'libname' library to the list of library dependencies, as if you had ad...
3,484,517
3,484,767
Find if point lies within a rectangle
How can a find if a point lies within a 2D rectangle given 4 points?
Transform the point to a coordinate frame aligned with the rectangle, then the problem becomes axis-aligned and trivial. If the rectangle consists of the following 4 points: a b c d Then get the "x-axis" and "y-axis" of the rectangle as: x = Normalize(d-c) y = Normalize(a-c) Then construct a rotation matrix using x...
3,485,034
3,485,172
Convert triangle strips to triangles?
I'm using the GPC tessellation library and it outputs triangle strips. The example shows rendering like this: for (s = 0; s < tri.num_strips; s++) { glBegin(GL_TRIANGLE_STRIP); for (v = 0; v < tri.strip[s].num_vertices; v++) glVertex2d(tri.strip[s].vertex[v].x, tri.strip[s].vertex[v].y); glEnd(); } ...
perticularly 1 VBO for 1 polygon Whoa. 1 VBO per polygon won't be efficient. Kills the whole reason for vertex buffer. The idea for vertex buffer is to cram as many vertices into it as you can. You can put multiple triangle strip into one vertex buffer, or render separate primitives that are stored in one buffer. I...
3,485,064
3,485,068
C++0x auto, decltype and template functions
I've been reading this CodeProject article on C++0x and have given it a quick try in VC2010. However I've run into a compile error and I'm at a bit of a loss as to what the problem is. #include < iostream> template <typename FirstType, typename SecondType> auto AddThem(FirstType t1, SecondType t1) -> decltype(t1 + t2...
It’s because you named both of your parameters t1. You probably meant to call the second one t2.
3,485,150
3,485,161
File and Line number for Debugging
Possible Duplicate: C/C++ line number Hi, I have a simple error manager class that other classes use to report errors which are then printed out to a log file for later examination. I can print out the description and give it error codes. What I would also like, is for it to record the file name and line number wher...
Yes, you can use the __FILE__ and __LINE__ macros, which expand to the file name and line number, respectively.
3,485,166
3,485,200
Change the current working directory in C++
How can I change my current working directory in C++ in a platform-agnostic way? I found the direct.h header file, which is Windows compatible, and the unistd.h, which is UNIX/POSIX compatible.
The chdir function works on both POSIX (manpage) and Windows (called _chdir there but an alias chdir exists). Both implementations return zero on success and -1 on error. As you can see in the manpage, more distinguished errno values are possible in the POSIX variant, but that shouldn't really make a difference for mos...
3,485,227
3,486,065
Execute data as code?
My client asked me to write an custom encrypted executable to prevent easy cracking of the licensing system. Now, I understand that this is a false sense of security, but despite this he insisted on it. So, I dug up my knowledge of portable executables and came up with this idea: Encrypt the executable Stick this to...
As others have mentioned, simply loading the entire EXE up into a data section and linking it at runtime is a difficult task; however, here's another option. Take your input EXE; find its code and initialized data (including constant) sections. Rename these sections and convert them all to read-write initialized data s...
3,485,230
3,485,242
C++ Iterator do what?
Code: vector<weight *> &res; vector<weight>::iterator it = lower_bound(w.begin(), w.end(), queryweight); while(it != w.end()) { weight *w = &(*it); if(w->weight >= 60) break; res.push_back(w); it++; } I think the lower_bound do a binary search (?), so in the end, does the C++ code inte...
lower_bound returns the lowest iterator (i.e. position in the vector) of an element that is not less than the third parameter - here, queryweight. The while loop then goes through the remaining elements and, until it reaches an element that has a wight of greater than or equal to 60 adds them to the vector res. I assum...
3,485,472
3,487,847
Using enum as template type argument in C++
are there any restrictions / problems using an enum as template (type) argument in C++? Example: enum MyEnum { A, B, C, D, E }; template <typename _t> class MyTemplate { public: _t value; void func(const _t& param) { /* .... */ } }; // .... MyTemplate<MyEnum> MyInstance; My actual problem using MSVC++ v...
Referring to the original question: are there any restrictions / problems using an enum as template (type) argument in C++? I didn't find any - and I don't think there are any. It might turn out to be a bad idea because this technique it is not used that often, so there might be a few (more) compiler bugs relating to...
3,485,650
3,487,488
WS_EX_LAYERED window does not receive mouse events
I'm coding a custom background non rectangular window with buttons such as minimize and close in bitmaps. Here is my code just for now The problem is the custom window does not receive mouse messages while hovering over non zero alpha regions.
Since minimize and close buttons are outside window client area, you need to capture WM_NCLBUTTONUP in addition to WM_LBUTTONUP
3,485,652
3,485,668
problems with global variable shared between sourcefiles (I'm using include guards)
I'm trying to share the same variable between two .cpp files, they include the same .h file. But I'm getting linking errors, telling me that I have multiple definitions. Which I find awkward, since I'm using include guards //main.cpp #include <cstdio> #include "shared.h" int main(){ shared_int = 5; printVal(); r...
The declaration in your header file needs an extern: extern int shared_int; Then, you will need an actual instance of the definition in one C++ file (such as in shared.cpp): int shared_int; The include guards you're using here are good practice, but they won't have any effect in this situation. The include guard prev...
3,486,048
3,486,091
C++ interface between raw pointers and shared_ptr
I have code that uses raw pointers throughout. It needs to call a method that takes the raw pointer into a shared_ptr. This method is not under my control, belonging to an external api. I cannot just pass the pointer to the shared_ptr because when it will be deleted when the shared_ptr goes out of scope in the method (...
This sounds somewhat unusual and potentially quite dangerous, but you can accomplish this by using a no-op deleter when constructing the shared_ptr: struct no_op_delete { void operator()(void*) { } }; int* p = 0; // your pointer std::shared_ptr<int> sp(p, no_op_delete()); When sp and all copies that were made of ...
3,486,141
3,486,150
How to create a new data structure in C++ with object orientation?
This semester in university I have a class called Data Structures, and the professor allowed the students to choose their favourite language. As I want to be a game programmer, and I can't take Java anymore, I chose C++ ... but now I'm stuck with lack of knowledge in this language. I have to do the following: create a ...
Unlike Java, in C++ you don't need to use the new keyword to create objects. In Java, all objects are stored on the heap (free store) and can only be accessed via references. In C++, objects can be value types. You can declare them directly on the stack, e.g. SuperArray array(start, end); And you can call methods like...
3,486,260
3,511,375
Hooking and controlling a background process's input events
I'm currently researching ways to hook a process and take control of it using mouse/keyboard events whilst it is in the background (Ala, not the active window). I guess you could think of it as a more advanced macro that doesn't require the targeted window/process to be active. Now I know the process hooking code is ab...
Use PostThreadMessage and remember that the thread to which the message is posted must have a message queue created, or else the call fails.
3,486,424
3,486,427
Receiving an entire UDP packet
I am programming a UDP proxy application for Windows in C++ that sends and receives UDP packets with Winsock. The problem is that I need to work with the ENTIRE packet, not just the data and UDP and/or IP header. I have tried raw sockets with IP_HDRINCL (might be misspelled), but it still chops off some information fro...
For receiving packets, WinPCAP will let you do all of this and more, and there's sample code here which shows how to capture all of the packets arriving on an interface.
3,486,524
3,486,544
Memory deallocation and exceptions
I have a question regarding memory deallocation and exceptions. when I use delete to delete an object created on the heap . If an exception occurs before this delete is the memory going to leak or this delete is going to execute ?
This depends on where that delete is. If it's inside the catch that catches the exception, it might invoke. try { f(); // throws } catch( ... ) { delete p; // will delete } If it's after the catch that catches the exception and that catch doesn't return from the function (i.e. allows execution flow to procee...
3,486,595
3,486,621
Php script that responds to my qt application
I want to create a Qt application that takes a random integer and sends to the server to a specific file (say to process.php) in order to that file to answer to that Qt application if the number is odd or even. And when the Qt application gets the answer from the process.php, it gives a message box that tells the serve...
Take a look at Qt how can I get content of a page web for some examples of how to perform a fetch in QT
3,486,854
3,486,867
Size of structure with a char, a double, an int and a t
When I run only the code fragment int *t; std::cout << sizeof(char) << std::endl; std::cout << sizeof(double) << std::endl; std::cout << sizeof(int) << std::endl; std::cout << sizeof(t) << std::endl; it gives me a result like this: 1 8 4 4 Total: 17. But when I test sizeof struct which contains these data t...
There is some unused bytes between some members to keep the alignments correct. For example, a pointer by default reside on 4-byte boundaries for efficiency, i.e. its address must be a multiple of 4. If the struct contains only a char and a pointer struct { char a; void* b; }; then b cannot use the adderss #1 — it...
3,486,929
3,488,012
Boost.Test application debugging
When debugging a C++ Boost.Test application inside VS2010 (VS2008), how to make the debugger stop at Boost.Test assertion failure points?
I haven't tried this myself, but in theory you'd want to set a breakpoint somewhere in the check_impl function (in the boost_unit_test_library source), probably in the non-PASS cases of its final case statement. In practice I always just find myself just running the tests again (or the specific problem test, selected ...
3,486,963
3,487,777
asynchronous Inter thread communication
I'm making a cross plateform program that embbed a small RARP server (implemented with winpcap/pcap) and runs 2 TCP IP servers. I have to use C++. So i will have at least 4 threads, the main one wich countain the controller, 2 TCP/IP async socket, and the RARP server. I planned to use c++ BOOST Asio and Thread, because...
There's no generic solution to this, you can't just interrupt a thread and deliver a notification to be processed. That causes horrible re-entrancy problems and large servings of deadlock. A notification can only be processed when the thread is in a quiescent state. An operating system usually has services availabl...
3,486,968
3,487,013
C++: Union vs Bitwise operators
I have two char's and I want to "stitch" them bitwise together. For example: char c1 = 11; // 0000 1011 char c2 = 5; // 0000 0101 short int si = stitch(c1, c2); // 0000 1011 0000 0101 So, what I first tried was with bitwise operators: short int stitch(char c1, char c2) { return (c1 << 8) | c2; } But this doesn't...
The union method is implementation-defined at best (in practice, it will pretty reliably work but the format of si depends on the endianness of the platform). The problem with the bitwise way is, as you suspect, the negative numbers. A negative number is represented by a chain of leading 1's. So -5 for example is 1111...
3,487,042
3,487,066
Question about CoCreateInstance() method's implementation
I have a question about how CoCreateInstnace() method locate and create an instance of a CoClass contained in a COM DLL. Accroding to MSDN: The CoCreateInstance function provides a convenient shortcut by connecting to the class object associated with the specified CLSID, creating an uninitialized instance, and...
Please check it by debugging with debug version of MSVCRT libraries within the Visual Studio IDE. Alternatively, you can scan the VC++ include header files
3,487,068
3,487,084
How to fit a structure in an int64?
I need to fit the following structure into int64. day 9 bit (0 to 372) year 8 bit (2266-2010 = 256 y) seconds 17 bit (24*60*60=86400 s) hostname 12 bit (2^12=4096) random 18 bit (2^18=262144) How do I make such a structure fit in an int64? All items are numberic, and of the specified bit size
Just bitwise-or the components together with appropriate shifts. int64 combined = random | (hostname << 18) | (seconds << (18+12)) ... etc. Get things out by shifting and and-ing them. random = combined & 0x3FFFF hostname = (combined >> 18) & 0xFFF; etc.
3,487,087
3,487,108
How to implement an end in a map?
I'm implementing a map for an exercise and I'm at the point where I would have to iterate over it (done and working) but the problem is that I don't know how to implement a last element (presumably an empty link). I was thinking that I would attach some special kind of link (descendant of base link) which would then be...
If your iterator isn't bidirectional then you don't really need end to point to anything (just use NULL in that case). end() only needs to have a real value in the case of a bidirectional iterator, because in that case you'll need to be able to move backwards from end() towards the beginning of the list. The GNU C++ L...
3,487,117
3,487,370
Create static library in Visual C++ Express 2010
how to create static library in Visual C++ Express 2010? When creating project, I cant find static library option. Thanks.
You can create a new one: New project -> Win32 Console Application -> Static Library (the generated project will be empty) Or configure an existing C++ project to become a static library: Project property Pages -> Configuration Properties -> General -> Configuration Type, select 'Static library'
3,487,174
3,487,217
Initializing a char array in C. Which way is better?
The following are the two ways of initializing a char array: char charArray1[] = "foo"; char charArray2[] = {'f','o','o','\0'}; If both are equivalent, one would expect everyone to use the first option above (since it requires fewer key strokes). But I've seen code where the author takes the pain to always use the sec...
What about another possibility: char charArray3[] = {102, 111, 111, 0}; You shouldn't forget the C char type is a numeric type, it just happens the value is often used as a char code. But if I use an array for something not related to text at all, I would would definitely prefer initialize it with the above syntax tha...
3,487,221
3,487,264
Change local time by C++ program
Now in my country the local time is: 3:43 PM Can I write program in C++ to change the time on a Windows 7 system to another time? For example set it to 5:00 PM (increase) or decrease it?
In VC++ you can try. Include the Windows.h header file. SetSystemTime Function SYSTEMTIME st; st.wYear = 2010; st.wMonth = 5; st.wDay = 2; st.wHour = 7; st.wMinute = 46; st.wSecond = 31; st.wMilliseconds = 345; ::SetSystemTime(&st);
3,487,256
3,487,385
Nested templates and constructor
Edit: Note that my final purpose here is not having the class working, is just learning more about templates :-) Suppose you have a template class which implements a vector: template <typename T> class Vector { public: Vector(size_t dim) { dimension = dim; elements = new T[dim]; ...
This isn't what you asked, but there's a good chance the matrix would be better of implemented as a single linear vector where you provide high-level access methods that do the indexing (e.g. elmLoc=row*ncols+col). This way you don't need to create and initialize a vector of vectors. You also don't need to worry abou...
3,487,293
3,487,323
Is a C++ program really slower than a similar C program?
Assume that i have written a program in C++ without using RTTI and run-time polymorphism (no virtual function, no virtual inheritance) and classes don't have private/protected members, also the C++ specific header files are not used (i.e. C header files are used: cstring, cstdio, ... instead of string, iostream, ...). ...
C++ doesn't use RAII. You CAN use RAII in your c++ program. As long as you are doing exactly the same thing in C++ and in C, both program should be exactly as fast. Writing fast programs in C or C++ is not a matter of programming language but of what kind of feature you use.
3,487,532
3,487,560
Cocktail Sort code segfaults - not sure why
I wrote a Cocktail Sort algorithm, and am testing it by generating random vectors of size 500 up to 10,000 - running it 10 times per vector. After about the 2000-3000 length vector mark, the code segfaults. I expect it isn't the test code as the same test is used for multiple sorting algorithms and it runs fine for eve...
If you use A.at(i) instead of A[i], bounds checking will be done, and out-of-range exceptions thrown. That may be helpful for debugging. It appears to me that the access here... for(int i = firstIndex-1; i < lastIndex; i++) { if(A[i] > A[i+1]) { will be out-of-bounds when firstIndex is zero (the first iter...
3,487,537
3,487,988
Difficulty getting GDB to load debugging symbols
I use GDB to debug C/C++ programs very often, and I'm reasonably knowledgeable with how it works and what it can do. However, every so often I run into problems where mysteriously I can't seem to get GDB to properly load symbols from a core file. Currently, I have a binary executable in a shared NFS directory. The e...
Check your ulimits. It's quite a common source of confusion. Truncated core files can make any form of gdb inspection useless, well you can read the name of the binary in most cases, and if the core file is at least 8k you can get a stack trace.
3,487,655
3,487,834
Ensure all key events get sent to main window?
Is there a way to ensure that all WM_KEYDOWN events find their way into my main window regardless of who has focus? this is mainly for global things such as Delete, and hotkeys such as CTRL A and CTRL S. The problem is if another control has focus, all of these stop working. Is there maybe a better way of doing this th...
Yes, you do it in your message loop. At the exact location where a traditional message loop has the TranslateAccelerator() call. Which performs the same kind of operation, catching short-cut keystrokes and turning them into WM_COMMAND messages. A typical class library implements this with a "PreProcessMessage" metho...
3,487,717
3,487,736
Erasing multiple objects from a std::vector?
Here is my issue, lets say I have a std::vector with ints in it. let's say it has 50,90,40,90,80,60,80. I know I need to remove the second, fifth and third elements. I don't necessarily always know the order of elements to remove, nor how many. The issue is by erasing an element, this changes the index of the other ele...
I am offering several methods: 1. A fast method that does not retain the original order of the elements: Assign the current last element of the vector to the element to erase, then erase the last element. This will avoid big moves and all indexes except the last will remain constant. If you start erasing from the back,...
3,487,866
3,487,934
making a SingletonMixin class in c++
I have four classes, let's call S1, S2, S3 and S4. These class are singletons; each one have a getInstance and a finalize method - and an instance private variable-. Now, to avoid repeting the finalize and getInstance methods I'm trying to make a SingletonMixin class, something like: template<class T> class SingletonMi...
The problem: If you make (de)constructors private, the Singleton base class cannot generate an instance. However: friend class SingletonMixin<Foo>; is your friend.
3,487,870
3,488,857
error: pointer being freed was not allocated
I am trying to overload the assignment operator to do a deep copy of a polygon object, the program compiles but I am getting an error toward the end that I want to clear up. Below is the relevant code, if you think I need to add more please just post a comment. Assume the proper #include's and that the << operator is o...
I can't see the constructor for the PolygonNode class. Is the link_ pointer initialized to null on creation? If not, that may be the problem manifesting itself in the error you get. You have to make sure, the link_ pointers in the PolygonNode instances get initialized to null. Define appropriate constructors. Do you ha...
3,487,959
3,488,014
Drawing text with C++ directx
I'm creating an application overlay via Direct3D hooking, however I can't draw any text. I've started with this sample. The library itself seems to replace all D3D calls with own functions (and in the end it calls the original ones). I've tried all variations of DrawText without any result visible result. On the other ...
You're using the wrong DrawText function (GDI). Try using the one from ID3DXFont. (after creating the font,etc..)
3,488,048
3,495,830
Pointer to the start of an object (C++)
I need a way to get a pointer to the start of an object in C++. This object is used inside a template so it can be any type (polymorphic or not) and could potentially be an object that uses multiple inheritance. I found this article which describes a way to do it (see the section called "Dynamic Casts") using typeid an...
I've found a solution from another question that lets me work out at compile time if a type is polymorphic and I can then use this with template specialisation to use the correct type of cast. Apparently this method might break if the compiler adds padding between sub-objects, but I can hopefully add some compile time ...
3,488,108
3,489,067
How to compile for 32bit with Eclipse
I'm currently writing a little program in c++ on my 64bit Ubuntu Pc. By default eclipse compiles the program for a 64bit architecture. Since I want to use my little program on my server which is still 32bit, I need to be able to compile my program for 32bit. How could can I do that in eclipse? I've been fiddling for a ...
I found the answer myself, after lots of searching and trying things out. This is a solution that works if you happen to have the same problem. For this to work the following packages have to be installed: gcc/g++ with multilib ia32-libs Then right click on your project, and select "properties". Go to "C/C++ Build" a...
3,488,145
3,488,156
Integer vs floating division -> Who is responsible for providing the result?
I've been programming for a while in C++, but suddenly had a doubt and wanted to clarify with the Stackoverflow community. When an integer is divided by another integer, we all know the result is an integer and like wise, a float divided by float is also a float. But who is responsible for providing this result? Is it ...
The compiler will decide at compile time what form of division is required based on the types of the variables being used - at the end of the day a DIV (or FDIV) instruction of one form or another will get involved.
3,488,226
3,488,246
Mergesort - std::bad_alloc thrown when trying to assign vector
Good afternoon ladies and gents. So, it is not my day for errors. Implementing Mergesort (not in-place) in C++, and I'm having real trouble with the code, with no idea why. The second-to-last line of the mergeSort() function assigns the result of the merge() to a vector of ints, result. This line (the actual allocation...
In the Merge function, vector<int> result is not being returned.
3,488,233
3,488,452
Borland c++ inline asm problem with WORD PTR and string
I am writing small kernel for the 8086 processor (Working in BC3.1, on Windows XP as host operating system). Kernel is multithreaded, so I have problems when I use printf or cout for debugging (somewhere in code, printf sets InterruptEnable flag to 1, and my timer interrupt routine calls dispatch and my code breaks dow...
First of all, at least in my opinion, you've chosen a rather poor name -- what you have is pretty much a puts, not a printf. Second, for what you're trying to accomplish, you might want to try using Borland's cprintf, cputs, and such -- they use the DOS console output routines, and there's a pretty decent chance they d...
3,488,438
3,488,508
need advice for type of TCP server to cater for this type of application
The requirement of the TCP server: receive from each client and send result back to same client (the server only do this) require to cater for 100 clients speed is an important factor, ie: even at 100 client connections, it should not be laggy. For now I have been using C# async method, but I find that I always e...
You must be doing it wrong. I personally wrote C# based servers that could handle 1000+ connections, sending more than 1 message per second, with <10ms response time, on commodity hardware. If you have such high response times it must be your server process that is causing blocking. Perhaps contention on locks, perhaps...
3,488,509
3,488,525
Overriding a templated class function
I'm trying to create some kind of callback for a class template. The code is like this: template <typename t> class Foo { void add(T *t) { prinf('do some template stuff'); on_added(t); } void on_added(T *t) { } } struct aaa {} class Bar : Foo<aaa> { void on_added(aaa *object) { ...
Use 'virtual'... template <typename t> class Foo { void add(T *t) { prinf('do some template stuff'); on_added(t); } virtual void on_added(T *t) { } } struct aaa {} class Bar : Foo<aaa> { void on_added(aaa *object) { printf("on added called on Bar"); } }
3,488,571
3,488,974
Does insertion of elements in a vector damages a pointer to the vector?
In a program to simulate logic gates I switched from using arrays node N[1000]; to vectors vector<node> N; And my program did work perfectly before using vectors but now it prints wrong results, so I tried debugging and I found out that the bug happens here: node* Simulator::FindNode(string h) { int i; for(...
A few things. First, as far as I can tell NNodes is just tracking the size. But you have std::vector::size() for that. You then use it to get the last inserted element, but you can just use std::vector::back() for that: return &N.back();. Also your parameter is being passed by value, when it should probably be passed b...
3,488,910
3,597,261
2D Collision Detection Code
Does anyone know a very simple physics engine, or just a set of basic functions that could complete these tasks: Simple point, line, and rectangle collision detection? I looked at Box2D but it is way too advanced for what I am making. I just need some simple code. Thanks in advance!
Here's my shot at point/line collision detection. The important thing is to avoid trig functions, divisions, and other expensive operations so as not to slow things down too much. As GMan's comment notes, you need to bear in mind that the point will be moving. So you'll have the current position of the point (let's cal...
3,488,915
3,488,987
Do I need a virtual destructor for boost::ublas matrix?
Do I need virtual destructor when I am using boost::ublas matrix ? By the way, my class is a template class.
Do you mean you have this? template <typename Whatever> struct my_class { // ... boost::ublas::matrix m; }; There's nothing here that dictates you have a virtual destructor. You want a virtual destructor when you intend on having users publically derive from your class. So that question should be "Users will...
3,489,056
3,493,578
Compile other external libraries (without CMakeLists.txt) with CMake
short -- Is it possible to build a external binary/library out of a project with CMake, when the binary/library only has a makefile given? So you have your own project, a bunch of CMakeLists.txt in your src-tree and this external library with its source-files. Your sources depend on this library and some binaries/libra...
It sounds like you want CMake's external project. I have worked with it quite extensively when developing the Titan build system, and it provides a way of managing multiple out of source builds. You can include ExternalProject, and then something like the following would build the project: ExternalProject_Add(Qt DOW...
3,489,104
3,489,152
What is the regular expression to get a token of a URL?
Say I have strings like these: bunch of other html<a href="http://domain.com/133742/The_Token_I_Want.zip" more html and stuff bunch of other html<a href="http://domain.com/12345/another_token.zip" more html and stuff bunch of other html<a href="http://domain.com/0981723/YET_ANOTHER_TOKEN.zip" more html and stuff What i...
Appendix B of RFC 2396 gives a doozy of a regular expression for splitting a URI into its components, and we can adapt it for your case ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*/([^.]+)[^?#]*)(\?([^#]*))?(#(.*))? ####### This leaves The_Token_I_Want in $6, which is the “hashderlined” su...
3,489,138
3,489,248
C++: How do I prevent a function from accepting a pointer that is allocated in-line?
Couldn't figure out how to word the question accurately, so here's an example: Given this function prototype: void Foo(myClass* bar); I want to prevent this usage: Foo(new myClass()); and instead require a previously created object: myClass* bar = NULL; bar = new myClass(); Foo(bar); or myClass bar; Foo(&bar); Than...
Your design needs to make a choice. Either take ownership and delete it, or don't take ownership. Either way, it's up to the user to know how to use your function. They either need to know that your function will destroy the image (and maybe pass their own copy as needed), or they need to be smart enough to manage thei...
3,489,405
38,544,022
Qt - accessing the bundle path
The Qt documentation "Mac Differences" page provides the following code for accessing an application's bundle path: CFURLRef appUrlRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef macPath = CFURLCopyFileSystemPath(appUrlRef, kCFURLPOSIXPathStyle); const char *pathPtr = CFStringGetCStringPtr(macPath,CFS...
The modern way with Qt 5 and OS X 10.9 or greater is: CFURLRef url = (CFURLRef)CFAutorelease((CFURLRef)CFBundleCopyBundleURL(CFBundleGetMainBundle())); QString path = QUrl::fromCFURL(url).path();
3,489,498
3,489,562
Is coding in native c++ still popular?
I want to go into native c++ programming after University, but it seems like languages that compile with JIT (like .Net) are overtaking c++. What does the future hold for Native code?
C++ is the seventh programming language I have been professionally paid to program in, and I'm sure won't be the last. My advice is not to think of yourself as a specific language programmer. Even if JIT takes over the world, it has to get down to native machine code eventually, and someone has to write that software...
3,489,774
3,489,786
Why isn't this function caught by the compiler, and what does it do?
I found in some legacy code I'm dealing with this function (in C++) Vec3d Minimum() { if(this->valid) { return minBB; } else { return NULL; } } where Vec3d is a object that is basically a struct with x,y,z and some operators overloaded (code below). AFAIK, you can't return a 0 f...
0 can be used in the context of pointers to be the null pointer constant. That is, it's going into here: Vec3d(Vec3d* v); Note the comment is incorrect, as that is not a copy-constructor. The code is a bit shoddy. There doesn't need to be a set function, and typically non-mutating operators should be free-functions. ...
3,489,992
3,490,027
How can I prevent storing an intrusive_ptr-based class in other smart pointers
At work we have a base class, let's call it IntrusiveBase, that acts something like a mixin to allow a class to be stored in a boost:intrusive_ptr. That is, it provides its subclasses with a ref count and defines intrusive_ptr_add_ref and intrusive_ptr_release overloads. The problem is that it is too easy for someone t...
Even if I have to do something repetitively for each of the major smart pointer classes, it would be worth it. In that case, you can specialize them on your InstrusiveBase inheriting types. namespace boost { template<> class scoped_ptr<InstrusiveBaseSubclass> { }; // scoped_ptr<InstrusiveBaseSubClass> p(n...
3,490,040
3,490,150
C++ Pointer Arithmetic and Concatenation Question
How does this code concatenate the data from the string buffer? What is the * 10 doing? I know that by subtracting '0' you are subtracting the ASCII so turn into an integer. char *buf; // assume that buf is assigned a value such as 01234567891234567 long key_num = 0; someFunction(&key_num); ... void someFunction(long ...
It's basically an atoi-type (or atol-type) function for creating an integral value from a string. Consider the string "123". Before starting, key_num is set to zero. On the first iteration, that's multiplied by 10 to give you 0, then it has the character value '1' added and '0' subtracted, effectively adding 1 to give...
3,490,153
3,490,174
To throw or not to throw exceptions?
I was talking to a friend of mine that through my new code I didn't treat exceptions, just because I didn't know how to do it in C++. His answer surprised me: "why in the hell would you want to throw excetions?". I asked him why, but he didn't have a satisfying answer, so I googled it. One of the first pages I found wa...
The C++ iostreams classes do not, by default, use exception handling. Generally one should use exceptions for situations where an error can occur, but such errors are "unusual" and "infrequent" (such as a disk failing, the network being down, etc.). For error conditions that you do expect (such as the user providing in...
3,490,157
3,528,661
The SDL library I built from source crashes!
I've successfully built SDL from source using bcc 5.5.1 but any SDL test application using it crashes right away at startup. I'm looking for some help and/or guidance on how to resolve this issue. Just to fill in some info, SDL-1.2.14 was used. The project's compiled as a dll with multithreading enabled and linked to C...
Alright, I finally found out what the issue was a couple days ago. The reason for the crash was because the wrong source file was compiled for the given platform. The project file I used kept compiling SDL_sysmutex.c from threads\generic. The correct SDL_sysmutex.c to use under win32 should have been from threads\win3...
3,490,461
3,490,514
How to generate random 64 bit ints with boost random
I'm trying to generate a random 64bit unsigned integer using boost random, but I'm getting an assertion failure with uniform_int. struct timeval tv; boost::mt19937 randGen(tval.tv_usec); boost::uniform_int<> uInt64Dist(0, std::numeric_limits<uint64_t>::max()); boost::variate_generator<boost::mt19937&, boost::uniform_in...
uniform_int defaults to int as the value type. Use the following instead: boost::uniform_int<uint64_t> ... The same goes for the following line: boost::variate_generator<boost::mt19937&, boost::uniform_int<uint64_t> > ...
3,490,483
3,490,533
Floodfill replace with GDI?
My application has a static control which inside has a tab control. It looks like this: alt text http://img834.imageshack.us/img834/5645/topbar.png and I want to handle the topbar's paint event so that after it has drawn itself (and its children), have it floodfill to look more like this: alt text http://img230.imagesh...
The first thing I'd try would be to fill it in response to WM_ERASEBKGND (and I'd use FillRect, not FloodFill).
3,490,845
3,490,993
Rotated 2d rectangle intersecting points or area
Moving ahead from previous question.I have two rectangle and they look like this: struct Rect { NSPoint topLeft; NSPoint topRight; NSPoint bottomLeft; NSPoint bottomRight; } I use something similar code to check whether rectangles intersects(or collision) . In case If 2 rectangles intersects I want to calcula...
You can determine the points of intersection by doing this: foreach line in rectangle 1: line1 foreach line in rectangle 2: line2 find point of intersection for line1, line2 to find the intersection point of two lines: http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/ You can find the area of intersecti...
3,490,856
3,564,116
Get resolution of DirectX device
Where should I be looking for resolution of DirectX (3D) device? getViewport seems to have Width and Height, yet as far as I know viewport is supposed to be an area, not 2D "canvas" with these attributes. (I hope "resolution" applies to the device, not D3D directly. Please correct me if this part is wrong.) Simple MSDN...
If for some reason you only have the d3d interface, you can use getcreationparameters to get the original hwnd and then you can use GetWindowRect or GetClientRect as suggested before. D3DDEVICE_CREATION_PARAMETERS cparams; RECT rect; device->GetCreationParameters(&cparams); GetWindowRect(cparams.hFocusWindow, &rect); ...
3,490,898
3,492,638
Implement Drag and Drop without using Context Menu using Shell extension in C++
HI, I want to implement Drag and Drop without using Context Menu using Shell extension in C++ Currently I am refering to Shell extension article: http://www.codeproject.com/KB/shell/shellextguide6.aspx But this article in turn is using Cookies and all .. I am not able to understand that. My requirement is just when I w...
I think this OLE Drag and Drop article is pretty good for beginners. Also a good source is Drag and Drop How-to Topics on MSDN. Good luck.
3,491,204
3,491,241
Static data members of class templates
"A definition for a static data member may be provided in a namespace scope enclosing the definition of the static member's class template." It means ... Is this correct..... namespace N{ template<typename T>class A{ public: static int x; static int fun(); }; } namespace N1{ template<class T>int A<T>::x=10; ...
If you check the standard you should see the example. A definition for a static data member may be provided in a namespace scope enclosing the definition of the static member’s class template. [Example: template<class T> class X { static T s; }; template<class T> T X<T>::s = 0; —end example] Your program is not ...
3,491,489
3,958,698
Running boost unit test console applications as part of Teamcity build
In our application, there are a bunch of unit test console applications that have been written using the boost unit test framework. These test applications form part of the Visual Studio Solution (we are using VS2008 Professional). Is it possible to run these as part of a Teamcity build? So far I have configured Teamc...
Yes, it is possible to have boost unit tests reports and stats as part of a TeamCity build. Here is how I have done it, for a single unit tests project: Download and add to the unit tests project the TeamCity files for boost from http://confluence.jetbrains.net/display/TW/Cpp+Unit+Test+Reporting Create a batch file th...
3,491,499
3,491,541
SHFileOperation creates empty directory instead of file
I'm trying to copy a file from one location to another using SHFileOperation: SHFILEOPSTRUCT fileop; fileop.hwnd = 0; fileop.wFunc = FO_COPY; fileop.pFrom = L"C:\\SomeDirectory\\SomeName.jpg\0"; fileop.pTo = L"C:\\SomeOtherDirectory\\SomeName.jpg\0"; fileop.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT; file...
For FO_COPY and FO_MOVE operations the pTo member of the SHFILEOPSTRUCT must be a location, i.e. a directory, and not a destination filename. The directory is allowed not to exist, in which case it is created even if it looks like a filename. You should either just specify "C:\\SomeOtherDiretory\0" or use FO_RENAME. As...
3,491,848
3,492,182
enable_if + disable_if combination provokes an ambiguous call
While trying to answer this question I wanted to suggest the use of enable_if + disable_if to allow the overload of a method based on the fact that a type was (or not) polymorphic. So I created a small test file: template <class T> void* address_of(T* p, boost::enable_if< boost::is_polymorphic<T> >* du...
The compiler choked because you forgot the trailing ::type on enable_if and disable_if. The templates are always defined; it is just that the member type is present if and only if the expression is true (for enable_if) or false (for disable_if). template <class T> void* address_of(T* p, typename boost:...
3,491,868
3,491,901
GENERAL: Programming Code Guidelines & Styles
I know that each programming language has certain guideline and styles. My question is about two languages that I write code in, that isn't very popular or documented. I know this topic is very broad, and everyone has their own unique way of doing things. What I would like is to hear advantage, disadvantages to certai...
These are all really subjective issues - people mostly disagree about these sorts of things, and to be honest it really doesn't matter that much! :-) I'd say that the only thing that you can actually do wrong is to be inconsistent about whatever pattern you do use.
3,491,990
3,492,124
C++ definition of dllimport static data member
I do have a class which looks like below: //.h file class __declspec(dllimport) MyClass { public: //stuff private: static int myInt; }; // .cpp file int MyClass::myInt = 0; I get the following compile error: error C2491: 'MyClass::myInt' : definition of dllimport static data member not allowed what ...
__declspec(dllimport) means that the current code is using the DLL that implements your class. The member functions and static data members are thus defined in the DLL, and defining them again in your program is an error. If you are trying to write the code for the DLL that implements this class (and thus defines the m...
3,492,037
3,492,265
Global keyboard hook with C++
I've already saw many tutorials and articles about hooking, yet I don't quite understand it. Mainly because every single example uses different solution. I know I will have to implement something that will keep the hook alive. Usually it's some kind of while cycle. Q1: If this loop was in some class with callbacks, wil...
I know I will have to implement something that will keep the hook alive No, that's not a concern. A global hook requires a DLL with the callback. That DLL gets injected in all running processes. It will stay loaded in the process until you call UnHookWindowsHookEx() or the process terminates, whichever comes first...
3,492,742
3,496,688
Compile-time 'String' Manipulation with Variadic Templates
Hey all, I'm currently trying to write a compile-time string encryption (using the words 'string' and 'encryption' quite loosely) lib. What I have so far is as follows: // Cacluate narrow string length at compile-time template <char... ArgsT> struct CountArgs { template <char... ArgsInnerT> struct Counter; template ...
If you just want to operate on one character at a time its easy: template<char c> struct add_three { enum { value = c+3 }; }; template <char... Chars> struct EncryptCharsA { static const char value[sizeof...(Chars) + 1]; }; template<char... Chars> char const EncryptCharsA<Chars...>::value[sizeof...(Chars) + 1...
3,492,762
3,492,809
double dealloc problem while cleaning up a C++ STL list of pointers
Problem: I try to deallocate memory pointed by pointer items of an STL list. This should work fine but in my case, there can be duplicate pointers in the list and I get a double dealloc exception even though I test whether the pointer is NULL or not (see source code below). How can I solve this problem ? Environment: ...
Can you use smart pointers rather than raw pointers? I would try using boost shared_ptrs, like so: #include <boost/shared_ptr.hpp> list< boost::shared_ptr< Line > > l; boost::shared_ptr< Line > line( new Line( 10, 10, 10, 10 ) ); l.push_back( line ); l.push_back( line ); When the list is destroyed, the boost::shared_...
3,492,843
3,492,887
Need a tool to get C++ Inheritance Hierarchy of existing project?
I am trying to understand WebKit (2 Million lines of C++ code). I want a tool which takes a class name as input and tell me the names of all classes which inherit from it. For example, if I pass in "RenderObject" it should return RenderInline, RenderBox. I am using Fedora 13 and for debugging purpose I am using QtCreat...
I'd use doxygen to generate hierarchy graphs and class listings. The output is similar to javadoc's. GraphViz can be used with Doxygen to generate beautiful graphs, but is optional. By the way, isn't there already a documentation for Webkit ?
3,492,899
11,149,801
gdb cannot watch variables declared inside for-loop
I am using gcc 4.1.2 20080704 (Red Hat 4.1.2-48) GNU gdb (GDB) Red Hat Enterprise Linux (7.0.1-23.el5_5.1) and I cannot watch variables declared inside for-loop. I tried to recreate this behavior on a smaller example but it worked fine. Seems like this problem shows up only inside complex class member functions. Please...
I have not been able to solve it exactly but this work around might help you. Let us say want to access loop variable in for(int i=0;i<x;i++){...} You could do the following print &i $1 = (int *) 0x7fffffffdfa8 watch *0x7fffffffdfa8 This one has the definite disadvantage of having to wait as it may get reassigned ...
3,492,979
3,493,639
Overloading overloaded operator=?
What can I do when I need different job done, depending on the rval and lval type? Defining several overloads pop out with error 'operator = is ambiguous'. Any ideas, or tips (links to tutorials), are much appreciated, since I've just today found out about operator overloading. Thanks in advance! EDIT: Yes, I'd use C++...
For wrapint = wrapint situation: wrapint& wrapint::operator=(const wrapint& rhs) { // test for equality of objects by equality of address in memory // other options should be considered depending on specific requirements if (this == &rhs) return *this; m_iCurrentNumber = rhs.m_iCurrentNumber; retu...
3,492,987
3,498,056
Basic DirectX11 problem, code crashes as soon as I begin drawing anything to the screen. Also help with Netbeans configuration
So, I started programming in DirectX11 today, I've had a lot experience with coding, but not specifically DirectX, so I went and look at some tutorials. All was going swell, I could initialize a window, set a background color, but then as soon as I tried to define a shader and draw an object, it just crashes on load. T...
It works for me :) I had to remove L prefix of some strings for compiling code: "shaders.hlsl", "WindowClass", "Our First Direct3D Program" Do you have .hlsl file in the same path than your executable? Also you can't start the program from VS. You will need to launch the .exe from the explorer. But you can set an absol...
3,493,210
3,493,260
Macros as default param for function argument
I'm writing logger file. I'd prefer to use macros __FUNCTION__ there. I don't like the way like: Logger.write("Message", __FUNCTION__); Maybe, it's possible to make something like: void write(const string &message, string functionName = __FUNCTION__) { // ... } If not, are there any ways to do that stuff not by ha...
You could do something like that by wrapping it all in a macro: #define log(msg) Logger.write(msg, __FUNCTION__) The downside is that you will need to have Logger in scope when using this macro.
3,493,246
3,493,347
measuring code coverage of an unit test using aqtime
I want to measure the code coverage of an unit test with aqtime. The application to test uses a lot of boost functionality. Now these boost methods appear in the test report. With these methods in the report, it is nearly impossible to interpret it since I did not test boost but the classes using boost. Is there a fast...
I found a way: run with everything create a filter that includes everything you don't want select all elements of the filter create an excluding area for all those elements run again and refine.
3,493,332
3,493,634
Using declaration that refers to member templates of the base class.
Can any one explain this "A using-declaration in a derived class cannot refer to a specialization of a template conversion function in a base class." it is from ISO C++ Standard ..14.5.2 ,point 7
This means that this is ill-formed: struct A { template<typename T> operator T(); }; struct B : A { using A::operator int; }; // ill-formed: refers to specialization Likewise for other function template specializations (not only conversion functions) struct A { template<typename T> void f(); }; struct B : A { using A:...
3,493,344
3,494,468
Difference between GetModuleHandle and including header
maybe stupid question, but i dont know answer. What is difference between using GetModuleHandle or LoadLibrary to load dll(and then to use function of that dll) and to include directly desired header. For example, with using GetModuleHandle: typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO); // Call GetNativeSystemInfo if s...
First, make sure you understand that GetModuleHandle and LoadLibrary are not exactly equivalent. But since that's not directly part of your question, I'll leave off a big explanation and just suggest you make sure to understand the documentation in those two links. To use a dll function directly as if it were like any...