question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,737,193
1,737,401
Different implementation of a templated class method for a particular class template type
I have a templated class with a method for which I need a different implementation for a specific template type. How do i get it done?
You can specialise the method for that type. E.g. template<typename T> struct TemplatedClass { std::string methodA () {return "T methodA";} std::string methodB () {return "T methodB";} std::string methodC () {return "T methodC";} }; // Specialise methodA for int. template<> std::string TemplatedClass<int>::methodA () { return "int methodA"; }
1,737,324
1,756,489
Experiences using Wt C++ framework?
Has anyone seriously used Wt? Did it work well? Did you experience certain limitations? Or advantages? Wt is a C++ library for developing web applications. Please avoid the discussion of whether C++ is a good language for web development. I just want to give Wt a try because it seems like it could be a fun thing to do.
I have not personally used the framework, but have discussed it with a few people that have. They didn't really have any limitations, but I found it hard to believe they were compiling every time. Their main comment was that it was quite a light load on the server in terms of memory usage. Personally, I think the interpreted languages of php, python, ruby, etc work well with the nature of web development - but that's not the question you asked. Probably the biggest advantage is being able to use your existing skill set to work in a new medium. There are also a few good comments online discussing pros and cons. Here is one I found http://discuss.joelonsoftware.com/default.asp?biz.5.599655.33 However, I think the main answer here is that without a specific project requirement in mind, it is going to be difficult to evaluate any framework for suitability. If you think it will be fun to try coding a few things with it, then give it a go. That is going to be the best (if not only) way to determine if it suits your needs.
1,737,668
1,737,708
How do I integrate Boost into a Visual C++ project?
I'm trying to link up some of the boost stuff with a visual C++ project of mine and am not sure what the best way to do this is, I'm specifically interested in the singleton class.
I don't want to RTFM but Boost Getting Started on Windows is the first place to go. As you can see from the TOC, it is a very coherent walkthrough. Get Boost The Boost Distribution Header-Only Libraries Build a Simple Program Using Boost Build From the Visual Studio IDE Or, Build From the Command Prompt Errors and Warnings
1,737,955
1,738,371
C++ Data Structure for storing 3 dimensions of floats
I've implemented a 3D strange attractor explorer which gives float XYZ outputs in the range 0-100, I now want to implement a colouring function for it based upon the displacement between two successive outputs. I'm not sure of the data structure to use to store the colour values for each point, using a 3D array I'm limited to rounding to the nearest int which gives a very coarse colour scheme. I'm vaguely aware of octtrees, are they suitable in this siutation? EDIT: A little more explanation: to generate the points i'm repeatedly running this: (a,b,c,d are random floats in the range -3 to 3) x = x2; y = y2; z = z2; x2 = sin(a * y) - z * cos(b * x); y2 = z2 * sin(c * x) - cos(d * y); z2 = sin(x); parr[i][0]=x; parr[i][1]=y; parr[i][2]=z; which generates new positions for each axis each run, to colour the render I need to take the distance between two successive results, if I just do this with a distance calculation between each run then the colours fade back and forth in equilibrium so I need to take running average for each point and store it, using a 3dimenrsionl array is too coarse a colouring and I'm looking for advice on how to store the values at much smaller increments.
I'd probably think bout some kind of 3-d binary search tree. template <class KEY, class VALUE> class BinaryTree { // some implementation, probably available in libraries public: VALUE* Find(const KEY& key) const { // real implementation is needed here return NULL; } }; // this tree nodes wil actually hold color class BinaryTree1 : public BinaryTree<double, int> { }; class BinaryTree2 : public BinaryTree<double, BinaryTree1> { }; class BinaryTree3 : public BinaryTree<double, BinaryTree2> { }; And you function to retreive the color from this tree would look like that bool GetColor(const BinaryTree3& tree, double dX, double dY, double& dZ, int& color) { BinaryTree2* pYTree = tree.Find(dX); if( NULL == pYTree ) return false; BinaryTree1* pZTree = pYTree->Find(dY); if( NULL == pZTree ) return false; int* pCol = pZTree->Find(dZ); if( NULL == pCol ) return false; color = *pCol; return true; } Af course you will need to write the function that would add color to this tree, provided 3 coordinates X, Y and Z. std::map appears to be a good candidate for base class.
1,738,089
1,738,173
When trying to include '#include <boost/regex.hpp>' I get: 1>LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc100-mt-gd-1_39.lib'
Not sure why i get that, I downloaded libs from here and while I have a lib called 'libboost_regex-vc90-mt-gd-1_39.lib I don't have one which is called 'libboost_regex-vc100-mt-gd-1_39.lib', renaming the one with vc90 to vc100 works but I'm not sure if this is the ideal solution? #include "stdafx.h" #include <regex> #include <boost/array.hpp> #include <boost/regex.hpp> #define BOOST_ALL_NO_LIB int _tmain(int argc, _TCHAR* argv[]) { boost::array<int, 10> a; boost::smatch s; getchar(); return 0; }
You are probably using Visual Studio 2010 (this is where vc100 comes from), but the downloaded lib was built with 2008 (vc9) Visual Studio 2010 comes with TR1, include <regex> and enjoy.
1,738,401
1,738,489
libtiff.3.dylib: unknown required load command 0x80000022
Has anyone found a fix for this? I read that it has something to do with new dylib format in Snow Leopard... (This is the lib I get back from MacPorts.) Thanks, rui
What are you trying to use that library with? Chances are you have an old version of some build tool or app. Have you updated all of your MacPorts installation? sudo port selfupdate sudo port -u upgrade outdated EDIT: Based on your additional information, more questions: You have -I /sw/include and -L /sw/lib which are standard locations for Fink, not MacPorts (/opt/local/{include,lib}). In general, it's not a good idea to mix packages from Fink and MacPorts. Are you actually pulling in anything from Fink? If so, are all the Fink packages up-to-date? If that doesn't resolve the issue, are you building on 10.5 and, if so, which 10.5? Or are you building on 10.6 an app targeted for 10.5 and 10.6? Make sure you have the latest Xcode in either case. EDIT: It is very difficult to diagnose problems like this based on sketchy information. You say Leopard in your latest comment but then you say you are using the 10.6 SDK. At this point, all I can suggest is that you make sure you have the latest Xcode updates installed and, if you want more help, update the question with a more complete description of what you are trying to do and exactly how and where you are trying to do it, including versions of tools like gcc, et al. Good luck!
1,738,536
1,738,550
Abstract class in c++
Let's say I've got class: class Bad_Date { private: const char* _my_msg; public: const char* msg() const { return _my_msg; } }; And I would like to not be able to create any object of this class but I don't really want to put anything else there and make it pure virtual fnc. Is there any other way to make this class abstract or I have to create dummy fnc and declare it as a pure virtual? Thank you.
If you need a base class, you may need a virtual destructor. Make it pure virtual and you've got your abstract class. If you don't need a virtual destructor (ie the class is not used polymorphically), you can make the constructor protected (not private).
1,738,671
1,738,678
Pass enums by value or reference?
My general rule is to pass by value for primitive types and pass by reference for objects (obviously const'd if need be). However, I'm not sure what route to take with enumerated types. I'd assume that pass by value is preferred since they are seemingly small, but I'd like to hear others thoughts.
No other thoughts. An enum is just an integral value in a fancy dress (or suit, if you prefer). It has no internal structure and will travel in a register given a chance. If you'd pass an int by value, pass an enum that way, too.
1,738,673
1,873,172
Streaming the desktop
I want to create a C++ cross-platform (Windows and MacOS X) application that sends the screen as a video stream to a server. The application is needed in the context of lecture capture. The end result will be a Flash based web page that plays back the lecture (presenter video and audio + slides/desktop). I am currently exploring a few options: Bundle the VLC (the Video Player) binary with my app and use its desktop streaming features. Use the Qt Phonon library, but it doesn't seem to be powerful enough. Send individual screenshots plus a timestamp to the server instead of a video stream. The server then would have to create the video stream. Implement it in Java and use Xuggler (BigBlueButton uses it for their Desktop Sharing feature) ...? I would greatly appreciate your insights/comments on how to approach this problem.
My solution was to write a simple GUI application in Qt that invokes a VLC process in the background. This works really well.
1,738,790
1,740,919
Build management in C++ & good IDEs on Linux
I am starting to write a moderately sized project in C++ requiring a fairly large amount of files and dependencies on other projects. Do you think manually maintaining a Makefile for this project is the best approach? Are there other better alternatives for C++ that make build management and dependency management of files really easy to handle? Also, what IDE is good for C++ development on Linux? I am comfortable with Vim, but do you think there are good IDEs for C++ (like Eclipse for Java) that provide code-completion etc? Thanks! Ajay
Others have already recommended using CMake. To my mind you should manage your project with CMake then decide on your favourite IDE. CMake allows you to describe the project to be built, instead of how to build it. For example: I want to create a shared library called foo with source files a.cpp, b.cpp and c.h and it requires these link dependencies. Then on unix you get libfoo.so and on windows you get foo.dll and foo.lib. All common project settings can be abstracted up to higher levels in the build tree, this keeps most files very simple. More complicated requirments can be refactored into macros. Once your project is described like this CMake will generate makefiles and/or IDE projects. This means each developer can choose their own IDE, as well as allowing you to mandate an IDE if appropriate. My company use CMake to build the c++ in our product on windows and solaris. It contains 600 projects and 1.5 million lines of source code. We originally chose it as a cross platform build utility when porting to solaris, however for a large project like ours it is much easier to manage the build with CMake than with Visual Studio project files. I would recommend it as a build utility for any c++ project of any size We use the eclipse cdt on solaris and are very happy with it. Most of our development is with visual studio on windows. cmake also works well with other ides I use it with KDeveloper4 on linux at home without a hitch.
1,738,928
1,738,943
How to break into code when a file has been touched
I inherited an application using a large number of text based files for configuration. The file's names are constructed dynamically in the software, so I can't search directly for a file name in the source code. Is there any way to break into a program running in the debugger when it touches a particular text file?
If you know the place where the files are being open or if the dynamically created file names are assigned to some variable, create an conditional breakpoint that breaks the code execution only if the filename is matching the file that you're interested in.
1,739,102
1,739,115
Concatenating strings in macros - C++
What's the easiest way to concatenate strings defined in macros. i.e. The pseudo code I'm looking for would be like: #define ROOT_PATH "/home/david/" #define INPUT_FILE_A ROOT_PATH+"data/inputA.bin" #define INPUT_FILE_B ROOT_PATH+"data/inputB.bin" ... #define INPUT_FILE_Z ROOT_PATH+"data/inputZ.bin" The only way I know of is to use strcat in the code, or using the string class and then the c_str method, but it can get messy when I have lots of input files. I'd like to just use INPUT_FILE_A, etc. directly and not have lots of local variables. Is there a good way to do this? Thanks.
The compiler will automatically concatenate adjacent strings: #define ROOT_PATH "/home/david/" #define INPUT_FILE_A ROOT_PATH "data/inputA.bin" Or more generic: #define INPUT_FILE_DETAIL(root,x) root #x #define INPUT_FILE(x) INPUT_FILE_DETAIL(ROOT_PATH "data/", x)
1,739,134
1,739,148
Print text into a Windows input text box
Background I'm trying to write an application in C++ that will run on Vista. The application will take input from a the user (via input text box), perform some manipulation of that text, and will direct the user to click on an input box in another application. I'd like my application to print text into the second application's text box. Question What is the simplest way to print text into an input box without typing the text in by a keyboard?
You are proposing to violate very basic Windows user interface conventions. I strongly recommend that you push the manipulated text onto the clipboard, and let the user use Paste to put it in the target text box. If you insist on your original plan, you will have to use complex Win32 APIs to get a handle to the target window and then send it a WM_SETTEXT.
1,739,154
1,739,476
Any likely causes of a double-free in ncurses?
I have an ncurses app that does the following, sometimes instantly after launch, sometimes after some fiddling. malloc: *** error for object 0x100300400: double free Program received signal SIGABRT, Aborted (gdb) where #0 0x00007fff846a7426 in read () #1 0x00007fff83f3d775 in _nc_wgetch () #2 0x00007fff83f3de3f in wgetch () (and so on into my code) Does anyone have suggestions for likely things to pursue?
It looks like you are using glibc, likely on an x86_64 Linux system. The tool to use for any kind of heap corruption on Linux/x86_64 is Valgrind. It will just immediately give you the answer, so there is no point in guessing where the problem might be (and it could be anywhere).
1,739,184
1,739,210
How does one properly use the Unix exec C(++)-command?
Specifically, I need to call a version of exec that maintains the current working directory and sends standard out to the same terminal as the program calling exec. I also have a vector of string arguments I need to pass somehow, and I'm wondering how I would go about doing all of this. I've been told that all of this is possible exclusively with fork and exec, and given the terrible lack of documentation on the google, I've been unable to get the exec part working. What exec method am I looking for that can accomplish this, and how do I call it?
If you have a vector of strings then you need to convert it to an array of char* and call execvp #include <cstdio> #include <string> #include <vector> #include <sys/wait.h> #include <unistd.h> int main() { using namespace std; vector<string> args; args.push_back("Hello"); args.push_back("World"); char **argv = new char*[args.size() + 2]; argv[0] = "echo"; argv[args.size() + 1] = NULL; for(unsigned int c=0; c<args.size(); c++) argv[c+1] = (char*)args[c].c_str(); switch (fork()) { case -1: perror("fork"); return 1; case 0: execvp(argv[0], argv); // execvp only returns on error perror("execvp"); return 1; default: wait(0); } return 0; }
1,739,259
1,739,265
How to use QueryPerformanceCounter?
I recently decided that I needed to change from using milliseconds to microseconds for my Timer class, and after some research I've decided that QueryPerformanceCounter is probably my safest bet. (The warning on Boost::Posix that it may not works on Win32 API put me off a bit). However, I'm not really sure how to implement it. What I'm doing is calling whatever GetTicks() esque function I'm using and assigning it to Timer's startingTicks variable. Then to find the amount of time passed I just subtract the function's return value from the startingTicks, and when I reset the timer I just call the function again and assign startingTicks to it. Unfortunately, from the code I've seen it isn't as simple as just calling QueryPerformanceCounter(), and I'm not sure what I'm supposed to pass as its argument.
#include <windows.h> double PCFreq = 0.0; __int64 CounterStart = 0; void StartCounter() { LARGE_INTEGER li; if(!QueryPerformanceFrequency(&li)) cout << "QueryPerformanceFrequency failed!\n"; PCFreq = double(li.QuadPart)/1000.0; QueryPerformanceCounter(&li); CounterStart = li.QuadPart; } double GetCounter() { LARGE_INTEGER li; QueryPerformanceCounter(&li); return double(li.QuadPart-CounterStart)/PCFreq; } int main() { StartCounter(); Sleep(1000); cout << GetCounter() <<"\n"; return 0; } This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999). The StartCounter() function records the number of ticks the performance counter has in the CounterStart variable. The GetCounter() function returns the number of milliseconds since StartCounter() was last called as a double, so if GetCounter() returns 0.001 then it has been about 1 microsecond since StartCounter() was called. If you want to have the timer use seconds instead then change PCFreq = double(li.QuadPart)/1000.0; to PCFreq = double(li.QuadPart); or if you want microseconds then use PCFreq = double(li.QuadPart)/1000000.0; But really it's about convenience since it returns a double.
1,739,374
1,739,381
Does C++ have standard libraries for common File Utilities
I am looking for standard libraries in C++ that would allow me to do things like: Traverse a directory recursively search for files within a directory Check if file exists, folder exists or not and create it if not present. Check a folder hierarchy exists or create it if not found. Equivalent of mkdir -p Uncompressing / Compressing a file Checking the CRC / Hash of the file copy file, delete file, delete folder, copy folder recursively running a system command and reading its console output within the program. It seems that scripting languages and Java have good support for these kind of problems. But, I am not able to find out there are standard ways of doing this in C++.
No, but if you want a good library implementation, you might look into Boost.Filesystem; it has widely used, cross-platform facilities for doing most of those things.
1,739,614
1,739,685
What is the difference between Go's multithreading and pthread or Java Threads?
What is the difference between Go's multithreading approach and other approaches, such as pthread, boost::thread or Java Threads?
Quoted from Day 3 Tutorial <- read this for more information. Goroutines are multiplexed as needed onto system threads. When a goroutine executes a blocking system call, no other goroutine is blocked. We will do the same for CPU-bound goroutines at some point, but for now, if you want user-level parallelism you must set $GOMAXPROCS. or call runtime.GOMAXPROCS(n). A goroutine does not necessarily correspond to an OS thread. It can have smaller initial stack size and the stack will grow as needed. Multiple gorouitines may be multiplexed into a single thread when needed. More importantly, the concept is as outlined above, that a goroutine is a sequential program that may block itself but does not block other goroutines. Goroutines is implemented as pthreads in gccgo, so it can be identical to OS thread, too. It's separating the concept of OS thread and our thinking of multithreading when programming.
1,739,643
1,767,635
Easier way to find (visual) position of QModelIndex in QTreeView
I'm interested in calculating the physical position of a node in QTreeView and can't find a way to do this (other than calculating it myself, which is cumbersome and error prone given the robustness of QTreeView). Is there a standard way of finding the draw position of data associated with a QModelIndex (something similar to the way indexAt() maps a position to a QModelIndex)?
There's a method in QAbstractItemView that does exactly what I needed: The signature is: virtual QRect visualRect ( const QModelIndex & index ) const
1,739,777
1,739,788
C++ Classes - Pointers question
I had a quiz at school and there was this question that I wasn't sure if I answered correctly. I could not find the answer in the book so I just wanted to ask you. Point* array[10]; How many instances of class Point are created when the above code is called? I answered none because it only creates space for 10 instances, but doesn't create any. Then my friend said it was just one because when the compiler sees Point* it just creates one instance as a base.
It creates no Points. What it does is creates an array of ten pointers that can point to Point objects (it doesn't create space for ten instances). The pointers in the array are uninitialized, though, and no Point objects are actually created.
1,740,006
1,740,059
Custom C++ manipulator problem
I'm trying to implement my own stream manipulator inside my logging class. It's basically endline manipulator which changes state of a flag. However when I try to use it, I'll get: ftypes.cpp:57: error: no match for ‘operator<<’ in ‘log->Log::debug() << log->Log::endl’ /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc:67: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>] /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc:78: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ios<_CharT, _Traits>& (*)(std::basic_ios<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>] /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc:90: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>] ... Code: class Log { public: ... std::ostream& debug() { return log(logDEBUG); } std::ostream& endl(std::ostream& out); // manipulator ... private: ... std::ofstream m_logstream; bool m_newLine; ... } std::ostream& Log::endl(std::ostream& out) { out << std::endl; m_newLine = true; return out; } std::ostream& Log::log(const TLogLevel level) { if (level > m_logLevel) return m_nullstream; if (m_newLine) { m_logstream << timestamp() << "|" << logLevelString(level) << "|"; m_newLine = false; } return m_logstream; } I'm getting the error when I try to call it: log->debug() << "START - object created" << log->endl; (log is the pointer to Log object) Any ideas? I suspect it's somehow connected to the fact that the manipulator is actually inside the class but that's just my wild guess... Cheers, Tom EDIT: Putting this here instead of comment because of limiting formatting. I tried to implement my streambuf and it works great with one exception: when I try to open filebuf for append it fails. Output works nicely, just append doesn't for some unknown reason. If I try to use ofstream directly with append it works. Any idea why? – Works: std::ofstream test; test.open("somefile", std::ios_base::app); if (!test) throw LogIoEx("Cannon open file for logging"); test << "test" << std::endl; Appends "test" correctly . Doesn't work: std::filebuf *fbuf = new std::filebuf(); if (!fbuf->open("somefile", std::ios_base::app)) throw LogIoEx("Cannon open file for logging"); Throws exception, if I set openmode to out then it works.. Cheers
That's not how manipulators work - it's all about types. What you want is something like: class Log { ... struct endl_tag { /* tag struct; no members */ }; static const struct endl_tag endl; ... LogStream &debug() { /* somehow produce a LogStream type here */ } } LogStream &operator<<(LogStream &s, const struct endl_tag &) { s.m_newLine = true; } Note that: Since m_newLine is part of Log, we can't be working with generic std::ostreams. After all, what would std::cout << Log->endl() mean? So you need to create a new stream type derived from std::ostream (I've left it out here, but assumed it's named LogStream). endl doesn't actually do anything itself; all the work is in operator<<. The only purpose of it is to get the right operator<< overload to run. That said, you're not supposed to be defining new manipulators and stream classes if you can avoid it, because it gets complex :) Can you do what you need using just std::endl, and wrapping an ostream around your own custom streambuf? That is how the C++ IO library is meant to be used.
1,740,093
1,745,781
Unable to use SetTransform in D3D9
What might stop IDirect3DDevice9::SetTransform from working? I've looked at alot of tutorials for using transformation matrices in Direct3D9, including this one here. And as far as I can tell, they all do it the same way. I'm trying to write some code just to translate a texured polygon. I call SetTransform with a matrix initialized with D3DXMatrixTranslation, and it returns S_OK. However the actual polygons drawn to the screen do not get transformed. D3DXMATRIX m_Translation; D3DXMatrixTranslation(&m_Translation,100,100,0); d3dDevice->SetTransform(D3DTS_WORLD, &m_Translation); d3dDevice->SetFVF(D3DFVF_TLVERTEX); d3dDevice->SetStreamSource(0, vertexBuffer, 0, sizeof(TLVERTEX)); HRESULT hr = d3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2);
You set "D3DFVF_TLVERTEX" which means that you are supplying "Transform and Lit" vertices in the vertex buffer, therefore the device is not going to apply a transformation matrix to these vertices.
1,740,366
1,740,400
Programmatically parse and edit C++ Source Files
I want to programmatically parse and edit C++ source files. I need to change/add code in certain sections of code (i.e. in functions, class blocks, etc). I would also (preferably) be able to get comments as well. Part of what I want to do can be explained by the following piece of code: CPlusPlusSourceParser cp = new CPlusPlusSourceParser(“x.cpp”); // Create C++ Source Parser Object CPlusPlusSourceFunction[] funcs = cp.getFunctions(); // Get all the functions for (int i = 0; i &lt funcs.length; i++) { // Loop through all functions funcs[i].append(/* … code I want to append …*/); // Append some code to function } cp.save(); // Save new source cp.close(); // Close file How can I do that? I’d like to be able to do this preferably in Java, C++, Perl, Python or C#. However, I am open to other language API’s.
This is similar to AST from C code If your comfortable with Java antlr can easily parser your code into an abstract syntax tree, and then apply transformation to that tree. A default AST transform is to simply print out the original source.
1,740,449
1,740,469
String concatenation query c++
#include <stdio.h> #include <string.h> #include <conio.h> #include <iostream> using namespace std; char a[21]; // If this is put inside the function unter -> junk output char* b=""; void unter() { char *new_str = ""; strcpy(a, new_str); char str_temp[10]=""; int chnum =0, neighbor1=3, neighbor2=5, mynode=4; sprintf(str_temp,"%d",chnum); b = strcat(a, str_temp); b = strcat(b, "_from"); sprintf(str_temp,"%d",mynode); b = strcat(b, str_temp); b = strcat(b, "to"); sprintf(str_temp,"%d",neighbor1); b = strcat(b, str_temp); } int main() { unter(); cout << a; cout << b; std::cin.get(); } This is my code in C++. I'm not sure how the character array 'a' also has the same values as 'b'. And moreover, when I declare 'a' char a[21]; inside function unter(), I'm getting some junk value for 'b'(as output). Care to explain how?
a is a char array and b is a pointer that points to a, so when printing them, they always print the same thing. When you move the declaration for a into unter, it is destroyed when unter returns, leaving b a dnagling pointer, so you get garbage when you print it.
1,740,640
1,740,702
fcntl issues compiling C++
{net04:~/xxxx/wip} gcc -o write_test write_test.c In file included from write_test.c:4: global.h:10: warning: `b' initialized and declared `extern' This code uses fcntl.h and the file-handling functions defined - like open(), write(), close() etc.. The code compiles and works as intended. {net04:~/xxxx/wip} gcc -o write_test write_test.cpp In file included from write_test.cpp:4: global.h:10: warning: `b' initialized and declared `extern' write_test.cpp: In function `int main()': write_test.cpp:56: error: `exit' undeclared (first use this function) write_test.cpp:56: error: (Each undeclared identifier is reported only once for each function it appears in.) write_test.cpp:58: error: `write' undeclared (first use this function) write_test.cpp:62: error: `close' undeclared (first use this function) When I use it as a CPP source code, why does GCC complain? And curiously, why it doesn't complain for open()? What's even happening here?
C++ is more strict about headers - you need: #include <unistd.h> to properly get the functions indicated. global.h should not be defining b - headers shouldn't initialise variables. When compiling you should use -Wall -Werror and that will force you to fix all the dodgy bits of your code. To get exit() cleanly you'll need #include <cstdlib> (C++) or #include <stdlib.h> (C) Use g++ to link C++ code so that C++ libraries get included. Probably easiest to do the entire C++ compile with g++.
1,740,989
1,741,094
How do I extract the network protocol from the source code of the server?
I'm trying to write a chat client for a popular network. The original client is proprietary, and is about 15 GB larger than I would like. (To be fair, others call it a game.) There is absolutely no documentation available for the protocol on the internet, and most search results only come back with the client's scripting interface. I can understand that, since used in the wrong way, it could lead to ruining other people's experience. I've downloaded the source code of a couple of alternative servers, including the one I want to connect to, but those contain no documentation other than install instructions are poorly commented (I did a superficial browsing) are HUGE (the src folder of the target server contains 12 MB worth of .cpp and .h files), and grep didn't find anything related I've also tried searching their forums and contacting the maintainers of the server, but so far, no luck. Packet sniffing isn't likely to help, as the protocol relies heavily on encryption. At this point, all my hope is my ability to chew through an ungodly amount of code. How do I start? Edit: A related question.
If your original code is encrypted with some well known library like OpenSSL or Ctypto++ it might be useful to write your wrapper for the main entry points of these libraries, then delagating the call to the actual library. If you make such substitution and build the project successfully, you will be able to trace everything which goes out in the plain text way. If your project is not using third party encryption libs, hopefully it is still possible to substitute the encryption routines with some wrappers which trace their input and then delegate encryption to the actual code. Your bet is that usually enctyption is implemented in separate, relatively small number of source files so that should be easier for you to track input/output in these files. Good luck!
1,741,099
1,741,108
VC++ Error on template inheritance
This is child's play, but I'm a bit of a vc n00b. I get an error: error C2143: syntax error : missing ',' before '<'. on the second line of the following code: template<int i, int j> class B : public A<i, j> { } template<int i, int j> class A { } Thanks for the help!
You forgot the semi-colons and the declaration of A(just declare A before B to avoid writing the declaration): template<int i, int j> class A { }; template<int i, int j> class B : public A<i, j> { };
1,741,485
1,741,602
How to convert string from one charset to another in C++?
How to convert string from one charset to another in C++ in a portable way? For example I want to convert to wstring to UTF-8 character array or . How to do this? I am asking some standard way no chilkatsoft, wxWidgets, Qt. Its a plain C++ application. Though some simple class or methods will do the job.
The Boost Serialization library contains a UTF-8 codecvt facet.
1,741,720
1,741,761
c++ problem with polymorphism and vectors of pointers
Consider the following example code: class Foo { }; class Bar : public Foo { }; class FooCollection { protected: vector<shared_ptr<Foo> > d_foos; }; class BarCollection : public FooCollection { public: vector<shared_ptr<Bar> > &getBars() { // return d_foos won't do here... } }; I have a problem like this in my current project. The client code uses BarCollection, which stores pointers to Bars in d_foos which is declared in FooCollection. I'd now like to expose the collection of pointers to Bars to the client code. I could just give the client code access to the vector of pointers to Foos and cast these to pointers to Bars in the client code, but this feels wrong since the client doesn't have to know about Foo's existence. I could also define a get() member that retrieves objects from d_foos and casts them, but this feels quite clumsy. Preferably, I'd like to just return d_foos as a vector<shared_ptr<Bar> > &, but I cannot seem to do this. It could also be that my design is just plain wrong. It seemed to most natural solution though, as Bar is a specialization of Foo and BarCollection is a specialization of FooCollection and they share functionality. Could you suggest nice solutions to implement getBars in BarCollection or better design alternatives? Edit: Turns out my design was bad indeed. BarCollection is not a FooCollection, despite of requiring all of FooCollection's functionality. My current solution based on the answers below -- which is a lot cleaner -- is now: class Foo { }; class Bar : public Foo { }; template<class T> class Collection { vector<shared_ptr<T> > d_items; }; typedef Collection<Foo> FooCollection; class BarCollection : public Collection<Bar> { // Additional stuff here. }; Thanks for all the excellent suggestions and examples!
template<class T> class MyContainer { vector<shared_ptr<T> > d_foos; public: vector<shared_ptr<T> > & getVector(); }; class FooCollection : public MyContainer<Foo> { }; class BarCollection : public MyContainer<Bar> { };
1,741,775
1,741,948
How do I catch keyboard events in X11?
I'm writing an LCD controller, and one feature I want to add is the ability to catch keyboard strokes so that you can do stuff like instant messaging over the LCD. I found xsnoop.c but it's outdated. I'm using xorg-x11-server 1.6.4-0.1.fc11 on Fedora 11. I'm also using Qt. I didn't find anything in the docs that might help, but figured I'd mention it. Any hints?
I've just tried compiling xsnoop.c and there was a line #include <vroot.h> which needs to be just removed, but apart from that it works.
1,741,997
1,742,055
Separating Enums from Class Definitions using Namespaces in C++?
I'm working with a legacy class that looks like this: class A { enum Flags { One = 1, Two = 2 }; }; I'd like to pull out all the enums into a new namespace defined in a new header: // flags.h namespace flags { enum Flags { One = 1, Two = 2 }; }; Then pull these enums back into the class so that I can include just the flags.h in headers that only require these values (rather than the entire class definition): // a.h #include "flags.h" class A { using namespace flags; }; How should I be doing this?
A using directive is illegal at class scope. Instead of a namespace you could define a class and then inherit from it: struct flags { enum Flags { One=1, Two=2 }; }; class A : public flags { ... }; But this looks like a misuse of inheritance to me, to be honest. As an alternative you could bite the bullet and use a namespace without "importing" the names into class A.
1,742,273
1,782,435
Qt (Creator) with WinSocks (ws2_32)
I want to use an older code-fragment in my Qt-project, which is using WinSocks. I created my program with Qt Creator and I don't know, how I can link to the ws2_32-Library. I already added LIBS += -lws2_32 to my .pro, but nothing happened. So how can I link to this library? edit: Where can I find the ws2_32.lib to include it? Do I have to download it first? I know it comes with "Visual Studio", but I don't use it and I don't want to use it.
ok, when you know it, it's really simple.The Qt-SDK comes with a WinSock2-Library, called libws2_32.a.The only thing you have to do, is to enter this line in your .pro: LIBS += C:\Qt\2009.04\mingw\lib\libws2_32.a this includes the winsock2-library to your project and you have nothing else to do. You may do this slightly more simply by using this line in your .pro: LIBS += -lws2_32
1,742,282
1,742,685
Crash within CString
I am observing a crash within my application and the call stack shows below mfc42u!CString::AllocBeforeWrite+5 mfc42u!CString::operator=+22 No idea why this occuring. This does not occur frequently also. Any suggestions would help. I have the crash dump with me but not able to progress any further. The operation i am performing is something like this iParseErr += m_RawMessage[wMsgLen-32] != NC_SP; where m_RawMessage is a 512 length char array. wMsgLen is unsigned short and NC_SP is defined as #define NC_SP 0x20 // Space EDIT: Call Stack: 042afe3c 5f8090dd mfc42u!CString::AllocBeforeWrite+0x5 * WARNING: Unable to verify checksum for WP Communications Server.exe 042afe50 0045f0c0 mfc42u!CString::operator=+0x22 042aff10 5f814d6b WP_Communications_Server!CParserN1000::iCheckMessage(void)+0x665 [V:\CSAC\SourceCode\WP Communications Server\HW Parser N1000.cpp @ 1279] 042aff80 77c3a3b0 mfc42u!_AfxThreadEntry+0xe6 042affb4 7c80b729 msvcrt!_endthreadex+0xa9 042affec 00000000 kernel32!BaseThreadStart+0x37 Well this is complete call stack and i have posted the code snippet as in my original message Thanks
I have a suggestion that might be a little frustrating for you: CString::AllocBeforeWrite does implicate to me, that the system tries to allocate some memory. Could it be, that some other memory operation (specially freeing or resizing of memory) is corrupted before? A typical problem with C/C++ memory management is, that an error on freeing (or resizing) memory (for example two times freeing the same junk of memory) will not crash the system immediatly but can cause dumps much later -- specially when new memory is to be allocated. Your situation looks to me quite like that. The bad thing is: It can be very difficult to find the place where the real error occurs -- where the heap is corrupted in the first place. This also can be the reason, why your problem only occurs once in a while. It could depend on some complicated situation beforehand.
1,742,329
1,742,564
When implementing several COM interfaces at once how do I upcast to IUnknown?
Suppose my COM object implements two or more COM interfaces: class CMyClass : public IPersistFile, public IPersistStream { }; when implementing QueryInterface() I need to be able to return an IUnknown* pointer. Since both base interfaces are derived from IUnknown I cannot upcast implicitly - such upcast would be umbiguous. To upcast explicitly I need to use either of the two ways: if( iid == __uuidof( IUnknown ) ) { *ppv = static_cast<IPersistFile*>( this ); static_cast<IPersistFile*>( this )->AddRef(); return S_OK; } or if( iid == __uuidof( IUnknown ) ) { *ppv = static_cast<IPersistStream*>( this ); static_cast<IPersistStream*>( this )->AddRef(); return S_OK; } Looks like the only requirement is that whenever QI() is called on an object it returns the same pointer each time and I meet that requirement if I choose any of the casts and just stick to it. Which upcast should I choose and why?
Mark Ransom already gave the correct answer - any will do, as long as it's consistent - but picking the first one has one minor advantage. Due to layout rules, the IUnknown* of the first interface will point to the start of the object. Any other IUnknown* will point to subsequent vtable pointers elsewhere in the object. For debugging purposes, it's very useful to know where ano object begins in memory.
1,742,657
1,742,827
C# objects and C++ objects, the difference
When creating an object instance as such in C# Myclass mc = new Myclass(); This mc is now a reference to a Myclass object created in memory. It's like a 'pointer' to that memory. Is it the same or comparable to doing this in (Managed or Unmanaged) C++: MyCppClass *mcCppClass = new MyCppClass(); Because this actually creates a pointer to an object instance of the class. I'm just trying to find out what exactly the differences are?
An important difference, which no one seems to have mentioned yet, is this: Myclass mc = new Myclass(); in C#, this is the only correct way to create a new object. When you need an object, this is how you create it. MyCppClass *mcCppClass = new MyCppClass(); In C++, this is how you can create an object, and how you occasionally have to create an object. The problem with using this approach in C++ is that: new is extremely slow in C/C++, compared to a managed language. If used to allocate every object you need, it's going to hurt. The object has no fixed lifetime. It is allocated on the heap, and it is not destroyed until you call delete on it. If you forget to do so, it is never destroyed. If you call delete twice, your program blows up. In C++, you have two ways to create objects: The one you used above: // 1 MyCppClass *myobject = new MyCppClass(); delete myobject; but modified to include the delete call as well, because without it, you're leaking memory. Whenever you use new, you must also, sooner or later, call delete. One without the other is, in general, an error. And the second, more common, approach: // 2 MyCppClass myobject; The second one is, in some ways, more similar to your C# example. Its lifetime is automatically managed by the system (although the way it is managed is different. In C++, it lasts until it goes out of scope, where in C# it lasts until no one references it and it gets garbage collected - but in both cases, you don't have to do anything to ensure it is destroyed). It is also, in general, the correct way to create object instances, for the same reason. One of the most common mistakes made by new C++ programmers is to use new to allocate every object, store pointers to them, and then try to remember to delete them. A simpler, more robust and more efficent solution is to avoid new and avoid pointers as far as possible. Occasionally, you need an object whose lifetime is not limited to the declaring scope, (and where copying the object isn't an option for using it outside that scope). Then you use new, and most likely, wrap the resulting pointer in a smart pointer of some type.
1,742,700
1,742,905
Does a destructor always get called for a delete operator, even when it is overloaded?
I'm porting a bit of an old code from C to C++. The old code uses object-like semantics, and at one point separates object destruction from freeing the now-unused memory, with stuff happening in between: Object_Destructor(Object *me) { free(me->member1), free(me->member2) } ObjectManager_FreeObject(ObjectManager *me, Object *obj) { free(obj) } Is the above functionality possible in C++ using the standard destructor (~Object) and a subsequent call to delete obj? Or, as I fear, doing that would call the destructor twice? In the particular case, the operator delete of Object is overridden as well. Is the definition I've read elsewhere ("when operator delete is used, and the object has a destructor, the destructor is always called) correct in the overridden operator case?
You can separate destruction from deletion, but you probably don't really want to. If you allocate the memory with new char[] or malloc, and then call placement new, then you can separate destruction (which you do by directly calling the destructor) from deletion (or free). But then you're no longer calling the class's overloaded operator delete, instead you're calling delete[] on the char array (or free). If you call delete via a pointer to your class (the one you overloaded operator delete for), then that class's destructor will be called. So there is no way to separate them in the sense you ask for, of calling delete without the destructor.
1,742,750
1,742,776
How is a union different from a struct? Do other languages have similar constructs?
Possible Duplicate: Difference between a Structure and a Union in C I see this code for a union in C: union time { long simpleDate; double perciseDate; } mytime; What is the difference between a union and a structure in C? Where would you use a union, what are its benefits? Is there a similar construct in Java, C++ and/or Python?
So in your example, when I allocate time: int main() { time t; } The compiler can interpret the memory at &t as if it is either a long: t.simpleDate; or as if its a double: t.perciseDate; So if the raw hex of the memory at t looks like 0x12345678; That value can be "parsed" as either a double or long, depending on how its accessed. So for it to be useful you have to know how a long and a double are going to be packed & formatted exactly in memory. For example, a long is going to be a 2-s complement signed integer, which you can read about here. you can learn how a double is formatted in binary here. A struct, however, just groups separate variables, with distinct address spacing into one block of memory. (Note your example might be dangerous as sizeof(long) could be 32 bits whereas sizeof(double) is always 64 bits) Unions are commonly used when you want a "raw" representation (like a char array) and a "message" representation. For example a message that is to be sent over a socket: struct Msg { int msgType; double Val1; double Val2; }; // assuming packing on 32-bit boundary union { Msg msg; unsigned char msgAsBinary[20]; }; Hope that helps.
1,742,848
1,742,911
Why exactly do I need an explicit upcast when implementing QueryInterface() in an object with multiple interfaces()
Assume I have a class implementing two or more COM interfaces: class CMyClass : public IInterface1, public IInterface2 { }; Almost every document I saw suggests that when I implement QueryInterface() for IUnknown I explicitly upcast this pointer to one of the interfaces: if( iid == __uuidof( IUnknown ) ) { *ppv = static_cast<IInterface1>( this ); //call Addref(), return S_OK } The question is why can't I just copy this? if( iid == __uuidof( IUnknown ) ) { *ppv = this; //call Addref(), return S_OK } The documents usually say that if I do the latter I will violate the requirement that any call to QueryInterface() on the same object must return exactly the same value. I don't quite get that. Do they mean that if I QI() for IInterface2 and call QueryInterface() through that pointer C++ will pass this slightly different from if I QI() for IInterface2 because C++ will each time make this point to a subobject?
The problem is that *ppv is usually a void* - directly assigning this to it will simply take the existing this pointer and give *ppv the value of it (since all pointers can be cast to void*). This is not a problem with single inheritance because with single inheritance the base pointer is always the same for all classes (because the vtable is just extended for the derived classes). However - for multiple inheritance you actually end up with multiple base pointers, depending on which 'view' of the class you're talking about! The reason for this is that with multiple inheritance you can't just extend the vtable - you need multiple vtables depending on which branch you're talking about. So you need to cast the this pointer to make sure that the compiler puts the correct base pointer (for the correct vtable) into *ppv. Here's an example of single inheritance: class A { virtual void fa0(); virtual void fa1(); int a0; }; class B : public A { virtual void fb0(); virtual void fb1(); int b0; }; vtable for A: [0] fa0 [1] fa1 vtable for B: [0] fa0 [1] fa1 [2] fb0 [3] fb1 Note that if you have the B vtable and you treat it like an A vtable it just works - the offsets for the members of A are exactly what you would expect. Here's an example using multiple inheritance (using definitions of A and B from above) (note: just an example - implementations may vary): class C { virtual void fc0(); virtual void fc1(); int c0; }; class D : public B, public C { virtual void fd0(); virtual void fd1(); int d0; }; vtable for C: [0] fc0 [1] fc1 vtable for D: @A: [0] fa0 [1] fa1 [2] fb0 [3] fb1 [4] fd0 [5] fd1 @C: [0] fc0 [1] fc1 [2] fd0 [3] fd1 And the actual memory layout for D: [0] @A vtable [1] a0 [2] b0 [3] @C vtable [4] c0 [5] d0 Note that if you treat a D vtable as an A it will work (this is coincidence - you can't rely on it). However - if you treat a D vtable as a C when you call c0 (which the compiler expects in slot 0 of the vtable) you'll suddenly be calling a0! When you call c0 on a D what the compiler does is it actually passes a fake this pointer which has a vtable which looks the way it should for a C. So when you call a C function on D it needs to adjust the vtable to point to the middle of the D object (at the @C vtable) before calling the function.
1,742,859
1,742,961
std::vector::reserve performance penalty
inline void add(const DataStruct& rhs) { using namespace boost::assign; vec.reserve(vec.size() + 3); vec += rhs.a, rhs.b, rhs.c; } The above function was executed for about 17000 times and it performed (as far as I can see. There was some transformation involved) about 2 magnitudes worse with the call to vector::reserve. I always was under the impression that reserve can speed up push_back even for small values but this doesn't seem true and I can't find any obvious reasons why it shouldn't be this way. Does reserve prevent the inlining of the function? Is the call to size() too expensive? Does this depend on the platform? I'll try and code up some small benchmark to confirm this in a clean environment. Compiler: gcc (GCC) 4.4.2 with -g -O2
GCC implementation of reserve() will allocate exact number of elements, while push_back() will grow internal buffer exponentially by doubling it, so you are defeating the exponential growth and forcing reallocation/copy on each iteration. Run your test under ltrace or valgrind and see the number of malloc() calls.
1,743,053
1,743,112
Are there C/C++ compilers that do not require standard library includes?
All applicants to our company must pass a simple quiz using C as part of early screening process. It consists of a C source file that must be modified to provide the desired functionality. We clearly state that we will attempt to compile the file as-is, with no changes. Almost all applicants user "strlen" but half of them do not include "string.h", so it does not compile until I include it. Are they just lazy or are there compilers that do not require you to include standard library files, such as "string.h"?
GCC will happily compile the following code as is: main() { printf("%u\n",strlen("Hello world")); } It will complain about incompatible implicit declaration of built-in function ‘printf’ and strlen(), but it will still produce an executable. If you compile with -Werror it won't compile.
1,743,277
1,743,284
Is there a tool for Visual Studio to track (or break on) variable value?
Is there is a tool or a setting in the Visual Studio debugger to stop on breakpoints or when a variable is set to a particular value? I mean, if I know that value will be set to "HELLO," I want the debugger will stop the same way it would if it reached a breakpoint?
You're looking for a Conditional Breakpoint.
1,743,309
1,743,345
Displaying an EMF file
Got a quick question about Windows EMF/EMF+ files. Reading the documentation, I realize that an EMF/EMF+ file is just a bunch of GDI/GDI+ commands. So what's the supported way for reading in an EMF/EMF+ file and then displaying it in either MFC or WinForms? Thanks, Alex
Here is how it is done (for EMF) in MFC (or did I misunderstand the question?) Here is more elaborate article on the subject.
1,743,365
1,745,508
Is there a C or C++ embeddable library for reading email through pop?
I'm looking for a not too big C or C++ library that would allow to read email through pop on Windows. The smallest the better. It would be better if it could support SSL.
There is also this CPJNOPO3Connection which supports ssl. I have not used this library but the SMTP one with great success both on Windows and Windows CE
1,743,511
1,743,581
How to programmatically tell if two variables are on the same stack? (in Windows)
I'm in a thread. I have an address. Is that address from a variable on the same stack that I'm using? static int *address; void A() { int x; atomic::CAS(address, 0, &x); // ie address = &x // ... } void B() { int y; int * addr = atomic::read(address); // ie addr = address if (addr && on_same_stack(&y, addr)) { // B() called from A() } else { // B() called from different thread than A() } } I need to implement on_same_stack(addr1, addr2). I know that the stack(s) on Windows grow as needed, but I also know that there is a limit to the growth, and that (in debug at least) there is stack-overflow-checking code on every function call. So I think it can be done. Now, I also know that I could/should use thread IDs, etc. But I'm trying to implement some tricky lock-free coding here, and I don't really have the room to store the thread IDs, just a single pointer. (I'm hoping to avoid CMPXCH16). Please trust me that I somewhat know what I'm doing :-). This is for Windows-only for now. But the more portable the better. (NT/XP/7/CE?) P.S. this site is called "stackoverflow" so it should be the right place to ask, shouldn't it? :-) EDIT: adding context, since everyone is asking. I'm implementing a custom call_once similar to pthread_once or boost.threads call_once. I'm attempting to check for recursion. I am very limited with what I have to work with. I can't add function parameters. I can't make assumptions about what the rest of the program is doing, like how much TLS they are already using. Etc. I can only code inside my one function, and make no changes or assumptions about anything outside of that. Thanks for your questions/answers.
How about something crazy like (untested): declspec(__thread) void* stackBottom; void Thread1Routine(void* arg) { volatile int bottom; stackBottom = &bottom; ... (do stuff which ends up calling on_same_stack()) ... } bool on_same_stack(void* p) { volatile int top; return ((LONG_PTR)p >= (LONG_PTR)&top) && ((LONG_PTR)p <= (LONG_PTR)stackBottom); } (edited to remove theoretical register-based arg passing issues)
1,743,803
1,743,874
C++ linker - Lack of duplicate symbols
Why does the following code not give me a duplicate symbol linker error for Impl? I ran across this problem in some code I inherited and I'm recreating a shorter version here for simplicity. I have two classes, Foo and Bar, that each define a different version of the same struct (Impl) in each of their .cpp files. So Foo.cpp and Bar.cpp each have an identically named Impl definition, but each one has a different inline constructor implementation. Both Foo and Bar have a member variable of type Impl and each forward declares Impl in its .h file. Foo.cpp news an instance of Bar inside its constructor. What's interesting is what gets created depends on the order the files are linked. So this compilation command: g++ -o a.out main.cpp Bar.cpp Foo.cpp results in this output: ==> main() Bar.cpp's Impl::Impl() Bar.cpp's Impl::Impl() <== main() And this command: g++ -o a.out main.cpp Foo.cpp Bar.cpp results in this output: ==> main() Foo.cpp's Impl::Impl() Foo.cpp's Impl::Impl() <== main() I have tried this with gcc 4.1.2, Visual Studio 2008 and the Green Hills Multi 4.2.4 and they all produce the same result. Foo.h #ifndef FOO_H struct Impl; class Bar; class Foo { public: Foo(); ~Foo(); private: Impl* p; Bar* bar; }; #endif Foo.cpp #include <iostream> #include "Foo.h" #include "Bar.h" struct Impl { Impl() { std::cout << "Foo.cpp's Impl::Impl()" << std::endl; } }; Foo::Foo() : p(new Impl), bar(new Bar) { } Foo::~Foo() { delete p; delete bar; } Bar.h #ifndef BAR_H #define BAR_H struct Impl; class Bar { public: Bar(); ~Bar(); private: Impl* p; }; #endif Bar.cpp #include <iostream> #include "Bar.h" struct Impl { Impl() { std::cout << "Bar.cpp's Impl::Impl()" << std::endl; } }; Bar::Bar() : p(new Impl) { } Bar::~Bar() { delete p; } main.cpp #include <iostream> #include "Foo.h" int main (int argc, char const *argv[]) { std::cout << "==> main()" << std::endl; Foo* f = new Foo(); std::cout << "<== main()" << std::endl; return 0; }
You're violating the one definition rule, and the compiler/linker isn't required to tell you about it.
1,743,832
1,743,866
C++ Access to command line arguments outside main?
I have a couple command line apps that both end up calling into com objects. Rather than adding new interface to these com objects, can they access the parameters passed from the command line? Edit: Sort of how I can call GetModuleFileName to get the file name. Im wondering if there is an equivalent method to get the args.
The Win32 API that you're looking for is: GetCommandLine. Your COM object probably needs to run within your process though. To convert the command line to an argv style array of strings, call the CommandLineToArgvW function.
1,743,964
1,745,302
Determining value based on adjacent cells in matrix
Input: a maze represented by an arbitrarily sized matrix of bools. (Out of bounds counts as 0) 00100 00100 01110 11111 01110 00100 Output: a nice looking representation of the maze (neighbourhood gets mapped to a wchar_t): ┌─┐ │1│ ┌┘1└┐ ┌┘111└┐ |11111| └┐111┌┘ └┐1┌┘ └─┘ Edit: Basically each 0 gets mapped to a 4 bit value representing the wall layout. My approach and thoughts: I thought it would be simplest to look at each cell at a time. Then look at it's neighbours to determine what kind of value to put there. Turns out I have 8 boolean inputs (all neighbours), this generates 2^8=256 different scenarios. I don't feel like hard coding them all. Is there a more elegant way to map the values correctly?
Inspired by Doug T.'s solution I wrote the following myself. Basically I run through the matrix twice (poor performance :/). The first time I'll draw walls around every 1 in the matrix, I do this with bit-masks. The second time I clean up all the "inwards-pointing"-walls. Example setup: // Add padding to output-matrix int owidth = width+2; int oheight = height+2; // 4-bit value: 0bWSEN static char N = 0x1; // The dash that goes from the center to the north static char E = 0x2; // The dash that goes from the center to the east static char S = 0x4; // ... static char W = 0x8; // This is what I will draw around every tile char box[] = {S|E, E|W, W|S, N|S, 0 , N|S, N|E, E|W, W|N }; The walling loop: for(unsigned int y = 0; y < height; y++) for(unsigned int x = 0; x < width; x++) { // We ignore walls if (! isOne(x, y)) // isOne takes care of out-of-bounds continue; // Go through neighbourhood for(int dy = -1; dy <= 1; dy++) for(int dx = -1; dx <= 1; dx++) { if (dy == 0 && dx == 0) // Ignore self continue; if (! isOne(x+dx, y+dy)) { // Draw part of box int ox = x+1, oy = y+1; // output-x and y out[(oy+dy)*owidth+(ox+dx)] |= box[(dy+1)*3 + (dx+1)]; } } } The clean-up loop: // Clean up "pointing edges" for(unsigned int y = 0; y < height; y++) for(unsigned int x = 0; x < width; x++) { // We ignore zero's since we're only cleaning walls. if (isOne(x, y)) continue; int ox = x+1, oy = y+1; // output-x and y // Remove edges that points to 'zero'-cells. if (! isOne(x , y-1)) out[y*width+x] &= ~N; if (! isOne(x , y+1)) out[y*width+x] &= ~S; if (! isOne(x-1, y )) out[y*width+x] &= ~W; if (! isOne(x+1, y )) out[y*width+x] &= ~E; } I'll then have a 16 size (one for each symbol) look-up list with one entry for each character. map<unsigned int, wchar_t> p; p[0] = ' '; p[N] = '.'; // ... p[N|S] = L'\u2502'; // │ p[E|W] = L'\u2500'; // ─ // ... p[N|E|S|W] = L'\u253C'; // ┼ This algorithm is not efficient by any means, O(2*width*height) ain't good... It can be improved by generating a 256 size loop-up table as others suggested, this would give us O(1) on execution.
1,743,999
1,744,021
Function returning variable by reference?
In C++, function() = 10; Works if function returns a variable by reference, right? Would someone please elaborate on this in detail?
Consider this piece of code first int *function(); ... *function() = 10; Looks similar, isn't it? In this example, function returns a pointer to int, and you can use it in the above way by applying a unary * operator to it. Now, in this particular context you can think of references as "pointers in disguise". I.e. reference is a "pointer", except that you don't need to apply the * operator to it int &function(); ... function() = 10; In general, it is not a very good idea to equate references to pointers, but for this particular explanation it works very well.
1,744,016
1,744,061
The Price of DuplicateHandle
I'm writing a class library that provides convenient object-oriented frontends to the C API that is the Windows Registry. I'm curious, however, what the best course of action is for handling HREGs, for instances where my key class is copied. I can either Allocate a heap integer and use it as a reference count. Call RegCloseKey() on the handle and deallocate the integer when the refrence count equals zero. Use the builtin functionality of handles, and rather than maintaining a reference count, call DuplicateHandle() on the HREG when the registry key object is copied. Then always call RegCloseKey in destructors. The DuplicateHandle() design is much simpler, but I'm concerned if designing things that way is going to severely hamper performance of the application. Because my application recurses through hundreds of thousands of keys, speed of copying this object is a sensitive issue. What are the inherent overheads of the DuplicateHandle() function?
I suspect you'll find that DuplicateHandle has very little overhead. The kernel already manages a reference count for each open object, and DuplicateHandle adds a new entry to the kernel handle table for the destination process, and increments the object reference count. (DuplicateHandle also normally does security checks, although it may skip that if the source and destination processes are the same.) You may run into difficulties if you open hundreds of thousands of objects at the same time, depending on how many handles Windows feels like letting you open.
1,744,144
1,744,302
Adding an include guard breaks the build
I added #ifndef..#define..#endif to a file of my project and the compiler fails. As soon as I remove it or put any other name in the define it compiles fine. What could be the problem? Sounds like the file is already declared, but I do not know where. I'm fine just removing it, but I really want to know why this is happening. error: expected class-name before ‘{’ token error: ‘QDesignerFormEditorInterface’ has not been declared And a couple of other errors. I am actually using an example from Qt, "Custom Widget Plugin Example". The difference is I am using my own class for the custom widget (.h, .cpp and .ui file). It might have to do with the file that has 2 includes, though that is how the example did it.
Is this macro used as an include guard? If so, it sounds like you're duplicating a name used elsewhere. This is a common problem when people don't think about the scope an include guard must have—you should include much more information in it than just the file name. Include guard goals: generate once, when creating a header never have to think about again chance of duplicating is less than your chance of winning the lottery Bad include guard names (for file "config.h"): CONFIG_H much too general _CONFIG_H, CONFIG__H, CONFIG_H__, __CONFIG_H__, etc. all reserved, still much too general PROJECT_CONFIG_H better, much less likely to duplicate in unrelated projects but still no path information, easy to duplicate in large projects Good include guard names (for file "config.h"): PATE_20091116_142045 that's <last name>_<date>_<time> no project, path, filename information even needed easy to type if your editor has an insert-date feature, you can "type" it very fast easy to generate include a sequence number when generating, if you need to generate more than one per second strong guarantee of being universally unique INCLUDE_GUARD_726F6B522BAA40A0B7F73C380AD37E6B generated from an actual UUID strong guarantee of being universally unique if it turns up unexpectedly, "INCLUDE_GUARD" is a good hint about what it is, while serving to put it in a separate namespace (though by convention rather than recognized by the language) prepend a project name, if desired (which is often required by project guidelines for macros) easy to write your own sample program to generate
1,744,194
1,744,328
Visualizing C++ to help understanding it
I'm a student who's learning C++ at school now. We are using Dev-C++ to make little, short exercises. Sometimes I find it hard to know where I made a mistake or what's really happing in the program. Our teacher taught us to make drawings. They can be useful when working with Linked Lists and Pointers but sometimes my drawing itself is wrong. (example of a drawing that visualizes a linked list: nl.wikibooks.org/wiki/Bestand:GelinkteLijst.png ) Is there any software that could interpret my C++ code/program and visualize it (making the drawings for me)? I found this: link text other links: cs.ru.ac.za/research/g05v0090/images/screen1.png and cs.ru.ac.za/research/g05v0090/index.html That looks like what I need but is not available for any download. I tried to contact that person but got no answer. Does anybody know such software? Could be useful for other students also I guess... Kind regards, juFo
This is unrelated to the actual title but I'd like to make a simple suggestion concerning how to understand what's happening in the program. I don't know if you've looked at a debugger but it's a great tool that can definitely vastly improve your understanding of what's going on. Depending on your IDE, it'll have more or less features, some of them should include: seeing the current call stack (allows you to understand what function is calling what) seeing the current accessible variables along with their values allowing you to walk step by step and see how each value changes and many, many more. So I'd advise you to spend some time learning all about the particular debugger for your IDE, and start to use all of these features. There's sometimes a lot more stuff then simply clicking on Next. Some things may include dynamic code evaluation, going back in time, etc.
1,744,407
1,744,793
Cache Line Alignment (Need clarification on article)
I've recently encountered what I think is a false-sharing problem in my application, and I've looked up Sutter's article on how to align my data to cache lines. He suggests the following C++ code: // C++ (using C++0x alignment syntax) template<typename T> struct cache_line_storage { [[ align(CACHE_LINE_SIZE) ]] T data; char pad[ CACHE_LINE_SIZE > sizeof(T) ? CACHE_LINE_SIZE - sizeof(T) : 1 ]; }; I can see how this would work when CACHE_LINE_SIZE > sizeof(T) is true -- the struct cache_line_storage just ends up taking up one full cache line of memory. However, when the sizeof(T) is larger than a single cache line, I would think that we should pad the data by CACHE_LINE_SIZE - T % CACHE_LINE_SIZE bytes, so that the resulting struct has a size that is an integral multiple of the cache line size. What is wrong with my understanding? Why does padding with 1 byte suffice?
You can't have arrays of size 0, so 1 is required to make it compile. However, the current draft version of the spec says that such padding is unecessary; the compiler must pad up to the struct's alignment. Note also that this code is ill-formed if CACHE_LINE_SIZE is smaller than alignof(T). To fix this, you should probably use [[align(CACHE_LINE_SIZE), align(T)]], which will ensure that a smaller alignment is never picked.
1,744,513
1,745,413
SetupDiGetDeviceInterfaceDetail returns only "\" for the path of all USB HID objects
I can tell how many USB HID devices I have (7), but every time I try to get details on any device, the path returned for it is always "\", making it so that I can't access the device at all. I'm using code that is very similar in procedure to this code: HANDLE connectDeviceNumber(DWORD deviceIndex) { GUID hidGUID; HDEVINFO hardwareDeviceInfoSet; SP_DEVICE_INTERFACE_DATA deviceInterfaceData; PSP_INTERFACE_DEVICE_DETAIL_DATA deviceDetail; ULONG requiredSize; HANDLE deviceHandle = INVALID_HANDLE_VALUE; DWORD result; //Get the HID GUID value - used as mask to get list of devices HidD_GetHidGuid (&hidGUID); //Get a list of devices matching the criteria (hid interface, present) hardwareDeviceInfoSet = SetupDiGetClassDevs (&hidGUID, NULL, // Define no enumerator (global) NULL, // Define no (DIGCF_PRESENT | // Only Devices present DIGCF_DEVICEINTERFACE)); // Function class devices. deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); //Go through the list and get the interface data result = SetupDiEnumDeviceInterfaces (hardwareDeviceInfoSet, NULL, //infoData, &hidGUID, //interfaceClassGuid, deviceIndex, &deviceInterfaceData); /* Failed to get a device - possibly the index is larger than the number of devices */ if (result == FALSE) { SetupDiDestroyDeviceInfoList (hardwareDeviceInfoSet); Log("hidin: -- failed to get specified device number"); return INVALID_HANDLE_VALUE; } //Get the details with null values to get the required size of the buffer SetupDiGetDeviceInterfaceDetail (hardwareDeviceInfoSet, &deviceInterfaceData, NULL, //interfaceDetail, 0, //interfaceDetailSize, &requiredSize, 0); //infoData)) //Allocate the buffer deviceDetail = (PSP_INTERFACE_DEVICE_DETAIL_DATA)malloc(requiredSize); deviceDetail->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA); //Fill the buffer with the device details if (!SetupDiGetDeviceInterfaceDetail (hardwareDeviceInfoSet, &deviceInterfaceData, deviceDetail, requiredSize, &requiredSize, NULL)) { SetupDiDestroyDeviceInfoList (hardwareDeviceInfoSet); free (deviceDetail); Log("hidin: -- failed to get device info"); return INVALID_HANDLE_VALUE; } Log("Opening device with path: %s", deviceDetail->DevicePath);
Surely you are compiling with UNICODE defined? Then you Log() formatting string is wrong. Fix: Log("Opening device with path: %ls", deviceDetail->DevicePath);
1,744,523
1,745,377
SSL_accept with blocking socket
I made a server with SSL and blocking sockets. When I connect with telnet (so it does not do the handshake), the SSL_accept blocks indefinitely and blocks every new handshake/accept (and by definition new connections). How can I solve this awful problem ?
Why not just set the socket stream to non-blocking mode before calling SSL_accept(), and then block on something like select() with a timeout if SSL_accept() returns SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE? Alternatively, you can block on select() before calling SSL_accept(). Either should work. That way you can at least bound the time the connection is blocked due to the DoS like behavior/attack. Bear in mind that SSL/TLS is record-oriented, meaning you must loop until the full record is read. SSL_pending() can help in such cases.
1,744,888
1,744,917
Cannot Debug Unmanaged Dll from C#
I have a DLL that was written in C++ and called from a C# application. The DLL is unmanaged code. If I copy the DLL and its .pdb files with a post build event to the C# app's debug execution dir I still can't hit any break points I put into the DLL code. The break point has a message attached to it saying that "no symbols have been loaded for this document". What else do I have to do to get the debugging in the dll source? I have "Tools->Options->Debugging->General->Enable only my code" Disabled. The DLL is being compiled with "Runtime tracking and disable optimizations (/ASSEMBLYDEBUG)" and Generate Debug Info to "Yes (/DEBUG)"
To debug into your C++ DLL you need to enable mixed mode debugging on the startup application in your solution. Right click on project -> Properties Go to Debug Tab Check "Enable unmanaged code debugging" This will allow you to debug into native code for an F5 style scenario. If you want to enable it for attaching to the process then do the following in the "Attach to Process" Dialog Select the process to debug Click on the "Select ..." button above the process list Click "Debug these code types" Check both Managed and Native
1,744,902
1,839,629
How might I obtain the IContextMenu that is displayed in an IShellView context menu?
Building a file open dialog replacement. Much of it works now, but I would like to generate the view-mode drop-down for the toolbar directly from the shell view object. Looking at IShellView2, I can see IShellView2::GetView() will give me the FOLDERVIEWMODE's supported. However, that doesn't give me the names of these modes, nor format that popup menu for me, nor immediately give me a way to actually set one of those modes (it would appear it is necessary to destroy the shell view window and create a replacement one for the current folder and specify the new FOLDERVIEWMODE desired... yeesh). At any rate, if one right clicks on an IShellView window, one gets a context menu, the first submenu of which is exactly what I want to place in my drop-down toolbar button (ie. the "view" fly-out menu (e.g. Small Icons, Medium Icons, etc.)). It seems like there ought to be a way to grab that submenu directly from the IShellView, rather than having to hardcode my values (and that way, if a given instance of IShellView supports extra view modes, they'd be there. Similarly, those which should be disabled would be, since it would all be under the IShellView's control). I have read Raymond Chen's excellent How to host an IContextMenu. Unfortunately, that just gives me a very simplistic context menu - the one for the folder itself, or for a file in a given folder, but NOT the context menu for the IShellView's shell view window (from which I might obtain the view fly-out). I have tried the following, based on Chen's article: CComQIPtr<IContextMenu> pcm(m_shell_view); // <<-- FAIL resulting pointer is NULL <<< // create a blank menu CMenu menu; if (!menu.CreatePopupMenu()) throw CContextException("Unable to create an empty menu in which to store the context menu: "); // obtain the full popup menu we need if (FAILED(m_hresult = pcm->QueryContextMenu(menu, 0, SCRATCH_QCM_FIRST, SCRATCH_QCM_LAST, CMF_NORMAL))) throw CLabeledException("Unable to query the context menu for the current folder"); // display the menu to the user // menu.getsubmenu ::TrackPopupMenu(menu, ::GetSystemMetrics(SM_MENUDROPALIGNMENT)|TPM_TOPALIGN|TPM_LEFTBUTTON, pt.x, pt.y, 0, m_shell_view_hwnd, NULL); Unfortunately, the attempt to query the m_shell_view (which is an IShellView*) for its IContextMenu interface fails. This "works": // retrieve our current folder's PIDL PidlUtils::Pidl pidl(m_folder); // get the context menu for the current folder CComPtr<IContextMenu> pcm; if (FAILED(m_hresult = GetUIObjectOf(m_owner->m_hWnd, pidl, IID_PPV_ARGS(&pcm)))) throw CLabeledException("Unable to obtain the PIDL for the current folder"); But here I get only a very few options in the context menu (Open, Explore, ...). Not the detailed context menu that I get if I simply right click on the shell view itself. I'm out of ideas as to how to proceed. Help?! ;)
Try IShellView::GetItemObject with SVGIO_BACKGROUND as uItem to get a IContextMenu on the view object : http://msdn.microsoft.com/en-us/library/bb774832%28VS.85%29.aspx
1,745,045
29,316,214
std::locale breakage on MacOS 10.6 with LANG=en_US.UTF-8
I have a C++ application that I am porting to MacOSX (specifically, 10.6). The app makes heavy use of the C++ standard library and boost. I recently observed some breakage in the app that I'm having difficulty understanding. Basically, the boost filesystem library throws a runtime exception when the program runs. With a bit of debugging and googling, I've reduced the offending call to the following minimal program: #include <locale> int main ( int argc, char *argv [] ) { std::locale::global(std::locale("")); return 0; } This program fails when I run this through g++ and execute the resulting program in an environment where LANG=en_US.UTF-8 is set (which on my computer is part of the default bash session when I create a new console window). Clearing the environment variable (setenv LANG=) allows the program to run without issues. But I'm surprised I'm seeing this breakage in the default configuration. My questions are: Is this expected behavior for this code on MacOS 10.6? What would a proper workaround be? I can't really re-write the function because the version of the boost libraries we are using executes this statement internally as part of the filesystem library. For completeness, I should point out that the program from which this code was synthesized crashes when launched via the 'open' command (or from the Finder) but not when Xcode runs the program in Debug mode. edit The error given by the above code on 10.6.1 is: $ ./locale terminate called after throwing an instance of 'std::runtime_error' what(): locale::facet::_S_create_c_locale name not valid Abort trap
I have encountered this problem very recently on Ubuntu 14.04 LTS and on a Raspberry Pi running the latest Raspbian Wheezy. It has nothing to do with OS X, rather with a combination of G++ and Boost (at least up to V1.55) and the default locale settings on certain platforms. There are Boost bug tickets sort of related to this issue, see ticket #4688 and ticket #5928. My "solution" was first to do some extra locale setup, as suggested by this AskUbuntu posting: sudo locale-gen en_US en_US.UTF-8 sudo dpkg-reconfigure locales But then, I also had to make sure that the environment variable LC_ALL is set to the value of LANG (it is advisable to put this in your .profile): export LC_ALL=$LANG In my case I use the locale en_US.UTF-8. Final remark: the OP said "This program fails when I run this through g++". I understand that this thread was started in 2009, but today there is absolutely no need to use GCC or G++ on the Mac, the much better LLVM/Clang compiler suite is available from Apple free of charge, see the XCode home page.
1,745,349
1,745,403
Saving QList<T> to a file?
I've got a QList of QLineEdit*'s QList<QLineEdit*> example; Example will hold 100 items of lineEdits. When I try to save or load to a file, it fails to save or load the QList properly, if at all. I get a much lower than expected count of data. I see on QList<T>'s resource page here that there's the correct operator for << & >>, however I can't seem to get them to save to a file using QDataStream I've also tried copying all the "text()" values from the LineEdits into a seperate String List but I still can't save them to a file. Any help would be appreciated. EDIT: Looks like that did it. This is how I'm reading them back, is there a more simple approach to this, or have I pretty much covered it? //memoryAddresses for(int i = 0; i < 100; i++) { QString temp; loadFile >> temp; memAddr.at(i)->setText(temp); }
QList<QLineEdit*> is a list of pointers (basically ints so if you write that to a file you won't get much useful information. The text() method should do what you are looking for. foreach( const QLineEdit* le, example ) { if( le ) { ds << le->text(); } } Note the differences between displayText and text. To read back: If you are only working with strings, the QTextStream class is a little nicer to use (could also be used above rather than the QDataStream...to be consistent though you should use the same type of stream for reading and writing). I am not able to test this code at the moment but you can try something like this: QList<QLineEdit*> example; while(!stream.atEnd()) { QString str; stream >> str; if( stream.isNull() ) break; QLineEdit* le = new QLineEdit(); le->setText(str); example.append(le); }
1,745,487
1,745,667
What can be instantiated?
What types in C++ can be instantiated? I know that the following each directly create a single instance of Foo: Foo bar; Foo *bizz = new Foo(); However, what about with built-in types? Does the following create two instances of int, or is instance the wrong word to use and memory is just being allocated? int bar2; int *bizz2 = new int; What about pointers? Did the above example create an int * instance, or just allocate memory for an int *? Would using literals like 42 or 3.14 create an instance as well? I've seen the argument that if you cannot subclass a type, it is not a class, and if it is not a class, it cannot be instantiated. Is this true?
So long as we're talking about C++, the only authoritative source is the ISO standard. That doesn't ever use the word "instantiation" for anything but class and function templates. It does, however, use the word "instance". For example: An instance of each object with automatic storage duration (3.7.2) is associated with each entry into its block. Note that in C++ parlance, an int lvalue is also an "object": The constructs in a C++ program create, destroy, refer to, access, and manipulate objects. An object is a region of storage. Since new clearly creates regions of storage, anything thus created is an object, and, following the precedent of the specification, can be called an instance.
1,745,693
1,745,758
Get text width in MFC
I'm wanting to dynamically resize a CButton to the width of the text within it. Is there either a built-in way to do this in MFC, or a way of calculating the pixel width of some specified text (so that I can use CWnd::SetWindowPos)?
You can use CDC::GetTextExtent to calculate the width of text in a certain font. Use CWnd::GetDC to get the Device Context from the control displaying the text.
1,745,942
1,745,963
C++ template parameter in array dimension
I have have the following code using templates and array dimension as template non-type parameter template<int n> double f(double c[n]); ... double c[5]; f<5>(c); // compiles f(c); // does not compile should not the compiler to be able to instantiate the second f without explicit template parameter? I am using g++4.1
It works when using references: template<size_t n> double f(double (&c)[n]);
1,746,008
1,746,017
Casting UINT64 to float?
Is it safe to cast a UINT64 to a float? I realize that UINT64 does not hold decimals, so my float will be whole numbers. However, my function to return my delta-time returns a UINT64, which isn't a very useful type for the function I'm currently working with. I'm assuming a simple static_cast<float>(uint64value) will not work?
Large values of UINT64, (an 8 byte value) may be truncated if you cast them to a float, which is only 4 bytes.
1,746,136
1,750,710
How do I "normalize" a pathname using boost::filesystem?
We are using boost::filesystem in our application. I have a 'full' path that is constructed by concatenating several paths together: #include <boost/filesystem/operations.hpp> #include <iostream>   namespace bf = boost::filesystem; int main() { bf::path root("c:\\some\\deep\\application\\folder"); bf::path subdir("..\\configuration\\instance"); bf::path cfgfile("..\\instance\\myfile.cfg"); bf::path final ( root / subdir / cfgfile); cout << final.file_string(); } The final path is printed as: c:\some\deep\application\folder\..\configuration\instance\..\instance\myfile.cfg This is a valid path, but when I display it to the user I'd prefer it to be normalized. (Note: I'm not even sure if "normalized" is the correct word for this). Like this: c:\some\deep\application\configuration\instance\myfile.cfg Earlier versions of Boost had a normalize() function - but it seems to have been deprecated and removed (without any explanation). Is there a reason I should not use the BOOST_FILESYSTEM_NO_DEPRECATED macro? Is there an alternative way to do this with the Boost Filesystem library? Or should I write code to directly manipulating the path as a string?
Boost v1.48 and above You can use boost::filesystem::canonical: path canonical(const path& p, const path& base = current_path()); path canonical(const path& p, system::error_code& ec); path canonical(const path& p, const path& base, system::error_code& ec); http://www.boost.org/doc/libs/1_48_0/libs/filesystem/v3/doc/reference.html#canonical v1.48 and above also provide the boost::filesystem::read_symlink function for resolving symbolic links. Boost versions prior to v1.48 As mentioned in other answers, you can't normalise because boost::filesystem can't follow symbolic links. However, you can write a function that normalises "as much as possible" (assuming "." and ".." are treated normally) because boost offers the ability to determine whether or not a file is a symbolic link. That is to say, if the parent of the ".." is a symbolic link then you have to retain it, otherwise it is probably safe to drop it and it's probably always safe to remove ".". It's similar to manipulating the actual string, but slightly more elegant. boost::filesystem::path resolve( const boost::filesystem::path& p, const boost::filesystem::path& base = boost::filesystem::current_path()) { boost::filesystem::path abs_p = boost::filesystem::absolute(p,base); boost::filesystem::path result; for(boost::filesystem::path::iterator it=abs_p.begin(); it!=abs_p.end(); ++it) { if(*it == "..") { // /a/b/.. is not necessarily /a if b is a symbolic link if(boost::filesystem::is_symlink(result) ) result /= *it; // /a/b/../.. is not /a/b/.. under most circumstances // We can end up with ..s in our result because of symbolic links else if(result.filename() == "..") result /= *it; // Otherwise it should be safe to resolve the parent else result = result.parent_path(); } else if(*it == ".") { // Ignore } else { // Just cat other path entries result /= *it; } } return result; }
1,746,352
1,746,417
How to have templated function overloads accept derived classes from different base classes?
I want to be able to define template <class TX> void f(const TX &x){ ... } template <class TY> void f(const TY &x){ ... } where TX must be derived from BaseX and TY must be derived from BaseY (how do I specify this kind of thing?), and I want to be able to call it as f(DerivedX<T>()) It is most important that I can avoid specifying the template parameters. Is this possible, and if so how would I implement it? If it's not possible, is there a way I can make a templated function accept only certain types, but still have it be implicitly instantiated? I cannot just make the overloads of f accept the base class because I need the derived class' type.
You can use is_base_of from Boost.TypeTraits like so: #include <boost/type_traits.hpp> #include <boost/utility.hpp> class BaseX { }; class BaseY { }; class DerivedX : public BaseX { }; class DerivedY : public BaseY { }; template <typename TX> boost::enable_if<boost::is_base_of<BaseX, TX>, void>::type f(const TX& x) { } int main(int argc, char** argv) { DerivedX x; DerivedY y; f(x); // compiles f(y); // will cause a compilation error } The Boost.TypeTraits library is header-only, so you don't need to link anything in.
1,746,402
1,746,505
What's A QT Or Open Source C++ Template For Ordinal Sorting
I am looking for a special template class, hopefully either a QT template or a self-contained open source library. This template class is intended to act as a container for a set of objects. Each object in the set has an integer-valued weight function but the weight function itself is arbitrary. It could range uniformly from 10 to 100 or vary non-uniformly from 1000 to 10000 or be a constant value. The template would keep a list of objects sorted by this weight (resolving ties arbitrarily). It would allow me to quickly retrieve the object having nth highest weight from the list, by order, not value (random access using an integer, like QList). The template also allow me to quickly add and remove arbitrary elements while keeping the list ordered by weight (like a QMap). Just quickly finding objects within an order of magnitude would be enough for my purposes - IE, finding the 1st, the 10th, the 100th, the 1000th and so-forth elements in my ordered list would suffice. I could implement a data structure like this myself (as an array of lists of increasing size or as a modified a binary tree having a count of n elements below each node). But it seems better to use a standard, commonly available, well documented template to solve the problem. I would prefer to avoid STL but if there's an STL solution, I would be interested. Edit: I'm looking for, at the least, orders of magnitude - not just the first but the 1st, the 10th, the 100th ordered by weight on up to the end (the internal ordering of a heap data structure would be great but I don't see any functions that directly access this). I can see that STL provides a "random access iterator" but after paging through a fair amount of documentation, I still can't find if this iterator would give the nth value without needing to sort the list for each call - indeed, my vague impression is that it would. STL also provides an "nth element" function but it appears that this is relatively costly if you are calling it for each access to the list. Edit2: Reason one can't simply use a QMap iterator and do it2 = it.begin()+1000; (from QT's documentation): iterator iterator::operator+ ( int j ) const Returns an iterator to the item at j positions forward from this iterator. (If j is negative, the iterator goes backward.) This operation can be slow for large j values. See also operator-().
The data structure you're looking for is a heap. The stdlib has std::make_help, push_heap, and pop_heap. There is also std::priority_queue. (I'm not sure why you'd avoid these, unless there's some other requirement you haven't told us about.) A tree such as a map will also work, but it will sort every item. If you need, for example, only the 'best' three out of 1,000,000, then sorting all of them would be wasteful.
1,746,499
1,746,515
Iterator and 2d vector
vector< vector<int> >::iterator temp = mincost.end(); vector<int> a = *temp; if ( *temp != *(temp--) ) return 0; mincost is a 2d vector, I want to get the last vector<int> of this vector and last--. I don't really understand about iterator :) . Help me !! :D Thx ^^
minconst.end() points to the element one-past-the-end of the vector minconst; it doesn't point to the last element in the vector. Since you want the last two elements, you should first test to be sure the vector actually has two elements in it, otherwise inevitably you'll run into problems. Then, accessing the last elements in the vector is simply a matter of *(minconst.end() - 1) and so forth. The C++ Reference also has a description of iterators.
1,746,594
1,746,662
middle of linked list
how to find the middle of the linked list when we are not informed of its size and it must be performed using only one loop and only one pointer.
How about LinkedList * llist = getLList(); // the linked list Node * node = llist.head; while ( node ) { node = node.next; if ( node ) { node = node.next; llist.remove( llist.head ); } } // now llist.head is (er, um... was) the middle node. // hope you didn't need the rest of the list.
1,747,151
1,747,159
Need help on getArea() function
I'm trying to calculate the area of the circle and the rectangle by using the existing data (radius ,width, and height). But i have some errors, i hope you can help me fix it. #include <iostream> #include <vector> #include <string> using namespace std; class Shape { public: virtual void Draw () = 0; virtual void MoveTo (int newx, int newy) = 0; virtual int GetArea()const = 0; }; class Rectangle : public Shape { public: Rectangle (int x, int y, int w, int h); virtual void Draw (); virtual void MoveTo (int newx, int newy); int GetArea() {return height * width;} private: int x, y; int width; int height; }; void Rectangle::Draw () { cout << "Drawing a Rectangle at (" << x << "," << y << "), width " << width << ", height " << height << "\n"; }; void Rectangle::MoveTo (int newx, int newy) { x = newx; y = newy; } Rectangle::Rectangle (int initx, int inity, int initw, int inith) { x = initx; y = inity; width = initw; height = inith; } class Circle : public Shape { public: Circle (int initx, int inity, int initr); virtual void Draw (); virtual void MoveTo (int newx, int newy); int GetArea() {return 3.14 * radius * radius;} private: int x, y; int radius; }; void Circle::Draw () { cout << "Drawing a Circle at (" << x << "," << y << "), radius " << radius <<"\n"; } void Circle::MoveTo (int newx, int newy) { x = newx; y = newy; } Circle::Circle (int initx, int inity, int initr) { x = initx; y = inity; radius = initr; } int main () { Shape * shapes[2]; shapes[0] = new Rectangle (10, 20, 5, 6); shapes[1] = new Circle (15, 25, 8); for (int i=0; i<2; ++i) { shapes[i]->Draw(); shapes[i]->GetArea(); } return 0; }
Rectangle::GetArea method should be const. You declared it non-const, so it is not considered an override of Shape::GetArea, so Rectangle is considered abstract.
1,747,220
1,747,381
Why is this the same even when object pointers differ in multiple inheritance?
When using multiple inheritance C++ has to maintain several vtables which leads to having "several views" of common base classes. Here's a code snippet: #include "stdafx.h" #include <Windows.h> void dumpPointer( void* pointer ) { __int64 thisPointer = reinterpret_cast<__int64>( pointer ); char buffer[100]; _i64toa( thisPointer, buffer, 10 ); OutputDebugStringA( buffer ); OutputDebugStringA( "\n" ); } class ICommonBase { public: virtual void Common() = 0 {} }; class IDerived1 : public ICommonBase { }; class IDerived2 : public ICommonBase { }; class CClass : public IDerived1, public IDerived2 { public: virtual void Common() { dumpPointer( this ); } int stuff; }; int _tmain(int argc, _TCHAR* argv[]) { CClass* object = new CClass(); object->Common(); ICommonBase* casted1 = static_cast<ICommonBase*>( static_cast<IDerived1*>( object ) ); casted1->Common(); dumpPointer( casted1 ); ICommonBase* casted2 = static_cast<ICommonBase*>( static_cast<IDerived2*>( object ) ); casted2->Common(); dumpPointer( casted2 ); return 0; } it produces the following output: 206968 //CClass::Common this 206968 //(ICommonBase)IDerived1::Common this 206968 //(ICommonBase)IDerived1* casted1 206968 //(ICommonBase)IDerived2::Common this 206972 //(ICommonBase)IDerived2* casted2 here casted1 and casted2 have different values which is reasonable since they point to different subobjects. At the point when the virtual function is called the cast to the base class has been done and the compiler doesn't know that it was a most derived class originally. Still this is the same each time. How does it happen?
When multiple inheritance is used in a virtual function call, the call to the virtual function will often go to a 'thunk' that adjusts the this pointer. In your example, the casted1 pointer's vtbl entry doesn't need a thunk becuase the IDerived1 sub-object of the CClass happens to coincide with the start of the CClass object (which is why the casted1 pointer value is the same as the CClass object pointer). However, the casted2 pointer to the IDerived2 sub-object doesn't coincide with the start of the CClass object, so the vtbl function pointer actually points to a thunk instead of directly to the CClass::Common() function. The thunk adjusts the this pointer to point to the actual CClass object then jumps to the CClass::Common() function. So it will always get a pointer to the start of the CClass object, regardless of which type of sub-object pointer it might have been called from. There's a very good explanation of this in Stanley Lippman's "Inside the C++ Object Model" book, section 4.2 "Virtual Member Functions/Virtual Functions Under MI".
1,747,254
1,747,273
C-style Variable initialization in PHP
Is there such a thing as local, private, static and public variables in PHP? If so, can you give samples of each and how their scope is demonstrated inside and outside the class and inside functions?
I don't know about C++ but there's how PHP works about: For Function scopes: <?php $b = 6; function testFunc($a){ echo $a.'-'.$b; } function testFunc2($a){ global $b; echo $a.'-'.$b; } testFunc(3); testFunc2(3); ?> The output is 3- 3-6 Code inside functions can only be accessed variables outside functions using the global keyword. See http://php.net/manual/en/language.variables.scope.php As for classes: <?php class ExampleClass{ private $private_var = 40; public $public_var = 20; public static $static_var = 50; private function classFuncOne(){ echo $this->private_var.'-'.$this->public_var; // outputs class variables } public function classFuncTwo(){ $this->classFuncOne(); echo $private_var.'-'.$public_var; // outputs local variable, not class variable } } $myobj = new ExampleClass(); $myobj->classFuncTwo(); echo ExampleClass::$static_var; $myobj->classFuncOne(); // fatal error occurs because method is private ?> Output would be: 40-20 - 50 Fatal error: Call to private method ExampleClass::classFuncOne() from context '' in C:\xampp\htdocs\scope.php on line 22 One note to take: PHP does not have variable initialization, although variables are said to be set or not set. When a variable is set, it has been assigned with a value. You can use the unset to remove the variable and its value. A not set variable is equivalent to false, and if you use it with all errors output, you will see a E_NOTICE error.
1,747,494
1,747,561
Conjugate function for complex number
I am trying to create a function that conjugate a complex number for example A(2, 3) will turn into A(2,-3) by typing ~A i have done a little code below but i guess it's wrong, i hope you can help me slove this. i have quoted the part that i did wrong in the code below. #include <iostream> using namespace std; class Complex { private: double real; double imaginenary; public: Complex(); Complex(double r, double i = 0); // Declaration Complex operator~(const Complex & c) const; Complex operator+(const Complex & c) const; Complex operator-(const Complex & c) const; Complex operator*(const Complex & c) const; Complex operator*(double n) const; friend Complex operator*(double m, const Complex & c) { return c * m; } friend ostream & operator<<(ostream & os, const Complex & c); }; Complex::Complex() { real = imaginenary = 0; } Complex::Complex(double r, double i ) { real = r; imaginenary = i; } // Definition Complex Complex::operator~(const Complex & c) const { Complex conj; conj.imaginenary = -1 * imaginenary; conj.real = real; } Complex Complex::operator+(const Complex & c) const { Complex sum; sum.imaginenary = imaginenary + c.imaginenary; sum.real = real + c.real; return sum; } Complex Complex::operator-(const Complex & c) const { Complex diff; diff.imaginenary = imaginenary - c.imaginenary; diff.real = real - c.real; return diff; } Complex Complex::operator*(const Complex & c) const { Complex mult; mult.imaginenary = imaginenary * c.imaginenary; mult.real = real * c.real; return mult; } Complex Complex::operator*(double mult) const { Complex result; result.real = real * mult; result.imaginenary = imaginenary * mult; return result; } ostream & operator<<(ostream & os, const Complex & c) { os << "(" << c.real <<"," << c.imaginenary<<"i)"; return os; } int main() { Complex A; Complex B(5, 40); Complex C(2, 55); cout << "A, B, and C:\n"; cout << A <<"; " << B << ": " << C << endl; cout << " complex conjugate is" << ~C << endl; cout << "B + C: " << B+C << endl; cout << "B * C: " << B*C << endl; cout << "10 * B: " << 10*B << endl; cout << "B - C: " << B - C << endl; return 0; }
try Complex Complex::operator~() const { Complex conj; conj.imaginenary = -1 * imaginenary; conj.real = real; return conj; } But it might be wiser to remove the operators from the class definition and create (friend) functions instead. It works better with implicit type conversion.
1,747,660
1,747,775
strange std::vector problem with uint32_t on Visual Studio 2008
This works fine: std::vector<int> v; v.push_back(123); but this throws a std::length_error: std::vector<uint32_t> v;// or vector<unsigned __int32> v.push_back(123); It seems to be triggered by resizing, because std::vector<uint32_t> v; v.reserve(2); triggers a debug assertion "iterator not dereferencable". This occurs on Visual Studio 2008, but the same code works fine on Mac and Linux. Can anyone suggest a way to narrow down the search for an explanation? UPDATE: The rat's nest of static and dynamically linked dependencies in this project made it too time-consuming to find the offending library. I gave up and rebuilt every dependency from source. I lost two days of my life and still don't know exactly where the problem was, but the app runs! Thanks for your help.
This #include <iostream> #include <vector> int main() { std::vector<unsigned __int32> v; v.reserve(2); std::cout << v.capacity() << '\n'; return 0; } runs without any hiccups for me in VS 2008. It prints 2. What does this do for you? If it works, too, then my first few guesses are: You invoked undefined behavior somewhere before. By the time execution gets to the code you showed, all bets are off. This is across DLL boundaries and you linked together DLLs/EXE built with different settings. The way to find out about this is to distill it down to the smallest possible test case exhibiting the behavior. (That shouldn't contain more than 50LoC, ideally, it's 10.) If you don't find the problem while doing so, append the example to your question.
1,747,691
1,747,788
Handling a resource effectively using auto pointers
I have a code which looks like this: class Parent { auto_ptr<Resource> ptr2Resc; public: void parentMethod(int i ) { SomeOtherClass someOthrPtr = new SomeOtherClass(ptr2Resc); } }; The ctor of SomeOtherClass: SomeOtherClass(auto_ptr<Resource> ptrRes); So now when i call parentMethod, the auto_ptr gets swapped and the ptr2Resc is dellocated. My C++ code doesn't support TR1 or Boost. So whats the best way to have the ptr2Resc deallocated during the Parent Class destructor, and not when it is passed as a parameter. Can i pass it as a reference to auto_ptr to the SomeOtherClass ctor? Thanks
Following is the quote from Josuttis book regarding passing auto_ptr by reference: You might think about passing auto_ptrs by reference instead. However, passing auto_ptrs by reference confuses the concept of ownership. A function that gets an auto_ptr by reference might or might not transfer ownership. Allowing an auto_ptr to pass by reference is very bad design and you should always avoid it As I said in my comment, if you do not intend to transfer the ownnership, you can simply change the constructor of SomeClass to take a raw pointer.
1,747,744
1,750,443
How do I split a large MFC project into smaller projects
We have a large MFC/C++ Visual Studio 2005 solution which currently consists of two projects: Code (around 1500 .h/.cpp files, linked dynamically to MFC) Resource DLL (we translate the resources using an external tool) What options do we have (lib, dll, ...)? Where do we start? Is there a technical sample of this or a tutorial (I could not find anything)? PS: We have no experience with creating dlls and/or libs with C++/Visual Studio yet, so any tips how to get started are appreciated.
Clearly there is no universal answer to you question. First you need to create some simple program using DLL's or statically linked libs (simply as an exercise). Before you know how to create such application from scratch it is not advisable to attempt fragmenting real-life project. There are couple of MS tutorials here and here for static libraries and DLLs correspondingly. After that you can approach your application. First try to understand the structure of your project. Ideally you would be able to figure out GUI part, business logic and back end. The easiest usually is GUI (because business logic is often interwoven with backend, my prediction you are going to have hard time separating those two). Move all the files that drive GUI (dialogs, user event handlers and such) into separate DLL. Once GUI is separated look at the rest. From my experience next thing to do is to separate utilities, that are used everywhere in your application but do not really depend on the application state (or provided with relevant state on every call). While doing so you will learn a lot about the rest of the project, hopefully enough to fragment it even further. Process is incremental and there is no magic wand. Sorry.
1,747,976
1,748,053
C++ array delete operator syntax
After I do, say Foo* array = new Foo[N]; I've always deleted it this way delete[] array; However, sometimes I've seen it this way: delete[N] array; As it seems to compile and work (at least in msvc2005), I wonder: What is the right way to do it? Why does it compile the other way, then?
You can check this MSDN link: delete[N] operator. The value is ignored. EDIT I tried this sample code on VC9: int test() { std::cout<<"Test!!\n"; return 10; } int main() { int* p = new int[10]; delete[test()] p; return 0; }; Output is: Test!! So the expression is evaluated but the return value is ignored. I am surprised to say the least, I can't think of a scenario why this is required.
1,748,473
1,748,519
Character decoding Conversion Function Implementation
I need to implement a character encoding conversion function in C++ or C( Most desired ) from a custom encoding scheme( to support multiple languages in single encoding ) to UTF-8. Our encoding is pretty random , it looks like this Because of the randomness of this mapping, I am thinking to use std::map for mapping our encoding to UTF and vice versa in two different maps ,and use this maps for conversion. Is their any optimized data structure or way to do it.
If your code points are contiguous, just make a big char * array and translate using that. I don't really understand what you mean by UTF-8 codepoint. UTF-8 has representations, and Unicode has codepoints. If you want code points, use an array of ints. const int mycode_to_unicode [] = { 0x00ff, 0x0102, // etc. }; You could put a value like -1 if there are holes in your encoding to catch errors. Going the other way is just making an array of structs of the same size of something like struct { int mycode; int unicode; }; copying the keys of the array into mycode and the values into unicode, and running it through qsort with a function which compares the values of unicode, then using bsearch with the same function to go from code point to your encoding. This is assuming you want to use C.
1,748,624
1,748,645
Circular dependencies of declarations
I am trying to implement example of visitor pattern, but I have trouble with circular dependecies of declarations of classes. When I do forward declaration of class Visitor, classes Russia and England doesn't know that Visitor has method visit, but when I extend forward declaration of Visitor for method accept, I need to use classes England and Russia, but they need to know who Visitor is, because they are using this type in their code. I tried many variations of ordering the code, but I failed fully. Please, help me understand, what C++ needs to get this. Thanks. #include <cstdio> #include <vector> using namespace std; class Visitor; class Land { public: virtual void accept(const Visitor *v); }; class England : public Land { public: void accept(const Visitor *v) { v->visit(this); } }; class Russia : public Land { public: void accept(const Visitor *v) { v->visit(this); } }; class Visitor { public: void visit(const England *e) const { printf("Hey, it's England!\n"); } void visit(const Russia *r) const { printf("Hey, it's Russia!\n"); } }; class Trip { private: vector<Land> *l; public: explicit Trip(vector<Land> *_l):l(_l) {} void accept(Visitor *v) { for (unsigned i = 0; i < l->size(); i++) { l->at(i).accept(v); } } }; int main() { England england; Russia russia; vector<Land> trip_plan; trip_plan.push_back(england); trip_plan.push_back(russia); trip_plan.push_back(england); Trip my_trip(&trip_plan); Visitor me; my_trip.accept(&me); return 0; } And there is the g++ output c++ -ansi -Wall -Wextra -Wconversion -pedantic -Wno-unused-parameter -o vp vp.cc vp.cc: In member function ‘virtual void England::accept(const Visitor*)’: vp.cc:40: error: invalid use of incomplete type ‘const struct Visitor’ vp.cc:30: error: forward declaration of ‘const struct Visitor’ vp.cc: In member function ‘virtual void Russia::accept(const Visitor*)’: vp.cc:47: error: invalid use of incomplete type ‘const struct Visitor’ vp.cc:30: error: forward declaration of ‘const struct Visitor’
class Visitor; class England : public Land { public: void accept(const Visitor *v); // Only declaration }; // Define Visitor class Visitor { //... }; // Now implementation void England::accept(const Visitor *v) { v->visit(this); }
1,748,827
1,748,864
Virtual tables are undefined
I wrote some code but I am unable to compile it: #include <cstdio> #include <vector> using namespace std; class Visitor; class Land { public: virtual void accept(const Visitor *v); }; class England : public Land { public: void accept(const Visitor *v); }; class Russia : public Land { public: void accept(const Visitor *v); }; class Visitor { public: void visit(const England *e) const; void visit(const Russia *r) const; }; class Trip { private: vector<Land> *l; public: explicit Trip(vector<Land> *_l); void accept(Visitor *v); }; /**/ void Visitor::visit(const England *e) const { printf("Hey, it's England!\n"); } void Visitor::visit(const Russia *r) const { printf("Hey, it's Russia!\n"); } void Russia::accept(const Visitor *v) { v->visit(this); } void England::accept(const Visitor *v) { v->visit(this); } Trip::Trip(vector<Land> *_l):l(_l) {} void Trip::accept(Visitor *v) { for (unsigned i = 0; i < l->size(); i++) { l->at(i).accept(v); } } int main() { England england; Russia russia; vector<Land> trip_plan; trip_plan.push_back(england); trip_plan.push_back(russia); trip_plan.push_back(england); Trip my_trip(&trip_plan); Visitor me; my_trip.accept(&me); return 0; } This is what I got from g++: c++ -ansi -Wall -Wextra -Wconversion -pedantic -Wno-unused-parameter -o vp vp.cc /tmp/ccNanCPR.o: In function `Land::Land()': vp.cc:(.text._ZN4LandC2Ev[Land::Land()]+0xf): undefined reference to `vtable for Land' /tmp/ccNanCPR.o: In function `Land::Land(Land const&)': vp.cc:(.text._ZN4LandC1ERKS_[Land::Land(Land const&)]+0x13): undefined reference to `vtable for Land' /tmp/ccNanCPR.o: In function `Land::~Land()': vp.cc:(.text._ZN4LandD1Ev[Land::~Land()]+0xf): undefined reference to `vtable for Land' /tmp/ccNanCPR.o:(.rodata._ZTI6Russia[typeinfo for Russia]+0x10): undefined reference to `typeinfo for Land' /tmp/ccNanCPR.o:(.rodata._ZTI7England[typeinfo for England]+0x10): undefined reference to `typeinfo for Land' collect2: ld returned 1 exit status This question is based on Circular dependencies of declarations
I already answered it there. The rules for vtable instantiation are explained in your compiler documentation. Here, it is waiting to see the definition (body) of Land::accept, which you declared to be a non-pure virtual, but never defined. Either define it, or make it pure virtual.
1,748,856
1,748,886
Inconsistent results from printf with long long int?
struct DummyStruct{ unsigned long long std; int type; }; DummyStruct d; d.std = 100; d.type = 10; /// buggy printf, unsigned long long to int conversion is buggy. printf("%d,%d\n",d.std, d.type); // OUTPUT: 0,100 printf("%d,%d\n", d.type, d.std); // OUTPUT: 10,100 printf("%lld,%d\n",d.std, d.type); // OUTPUT: 100,10 Please tell me why unsigned long long to int conversion is not properly handled in printf. I am using glibc. Is this bug in printf ? why printf does not do internal type conversion ?
Its your usage that is the problem. Unless the types specified in the format string are exactly the same as the types in the parameters then things will not work correctly. This is because the compiler pushes the parameters as-is onto the stack. There is not type checking or conversion. At run-time the code is pulling the values of the stack and advancing to the next object based on the value in the format string. If the format string is wrong then the amount advanced is incorrect and you will get funny results.
1,748,902
1,749,086
Linux inter-process reentrant semaphore
I'm porting a Windows application to Linux and I have a synchronization problem. In Windows I'm using a system-level named mutex to sync access to a shared memory block. How do I emulate that in Linux? I've created a SystemV semaphore, using semget. The problem is that it is not reentrant, if I already hold it it will block, unlike on Windows. I could add a reference count to it, but then I would need to synchronize access to that, which means another (this time for the current process only) mutex. Is there a class somewhere which provides a reentrant interprocess lock (maybe in Boost)? BTW, using a file lock is not acceptable since it will probably be too slow (I need ultra-low latency communication between the two processes).
You can just use a shared (interprocess), recursive pthread_mutex_t. Create a normal pthread_mutex (stored in shared memory) and set its attributes using pthread_mutexattr_settype with the PTHREAD_MUTEX_RECURSIVE flag, and then call pthread_mutexattr_setpshared with the PTHREAD_MUTEX_SHARED flag. That will give you a reentrant, interprocess lock.
1,749,229
1,749,284
Direct-X in C++ Game Programming
I am reletively new to c++ programming can anyone please tell me how does Direct-X SDK is helpful and how does it works and how can we use it in game programming.I Downloaded it and I found lots of header files and documentation also tells something about game programming.
DirectX is a library (a large collection of classes, really) that allows you to "talk" to the video adapter, sound card, keyboard, mouse, joystick, etc. It allows you to do it much more efficiently then other "standard" Windows functions. This is important because games need all the performance gain you can get - and DirectX has plenty to offer in this regard. Especially when it comes to graphics programming, because it has functions that enable you to use the 3D acceleration features of your graphics card. Windows doesn't have such functions by default. The DirectX SDK contains: Documentation for all the features of DirectX; Tutorials in the C++ language to get you started if you don't know anything; Sample applications; The necessary .h and .lib files to add DirectX support to your program; The debug version of DirectX (I think, I'm not so sure about this one) The DirectX redist that you can include with your own programs. If you're not up to speed with C++ then starting with DirectX development will be quite difficult, as either of these things has a pretty big learning curve. Btw - you did download the latest version from Microsoft webpage, not a 5 years old copy from some web guy, right?
1,749,311
1,749,351
friend function within a namespace
When a friend function is included in the namespace, its definition needs to be prefixed with namespace to compile it, here is the sample code: test.h: #ifndef TEST_H #define TEST_H namespace TestNamespace { class TestClass { public: void setValue(int &aI); int value(); private: int i; friend void testFunc(TestClass &myObj); }; void testFunc(TestClass &myObj); } #endif test.cpp: #include "test.h" using namespace TestNamespace; void TestClass::setValue(int &aI) { i=aI; } int TestClass::value() { return i; } void testFunc(TestClass &myObj) { int j = myObj.i; } Compiling above code give the error : 1>c:\qtprojects\namesp\test.cpp(17) : error C2248: 'TestNamespace::TestClass::i' : cannot access private member declared in class 'TestNamespace::TestClass' 1> c:\qtprojects\namesp\test.h(11) : see declaration of 'TestNamespace::TestClass::i' 1> c:\qtprojects\namesp\test.h(6) : see declaration of 'TestNamespace::TestClass' However if i use void TestNamespace::testFunc(TestClass &myObj) { int j = myObj.i; } It compiles, Why the function needs to be prefixed with namespace TestNamespace::testFunc but not the class, Both the class TestClass and function testFunc are included in the namespace in header.
The TestClass is being used in the testFunc method. Since you have included the namespace "using namespace TestNamespace;" it works fine. For testFunc method you are defining the implementation, you need to tell compiler that testfunc belongs to namespace TestNamespace: you can do it either: in .cpp namespace TestNamespace { void testFunc(TestClass &myObj) { int j = myObj.i; } } OR void TestNamespace::testFunc(TestClass &myObj) { int j = myObj.i; }
1,749,519
1,749,605
C++ 64-bit std::ostream support
I am about to make the transition from using standard FILE pointers from some older code to using C++ streams but I need to have LARGEFILE seeking support (the compiler flags that activate this support are: -D_FILE_OFFSET_BITS=64 et al) which I am able to obtain by using the off64_t datatype. My original question was answered regarding this subject matter and the C API, and now I am hoping to be able to transition towards using C++ streams. Do the same flags trigger seeking ability on file streams in C++?
So I performed a quick test on a 16GB file and it seems to have worked. Here is the code that I used. // compiled with : g++ -o largefile -D_FILE_OFFSET_BITS=64 largefile.cpp #include "iostream" #include "fstream" int main (int argc, char * argv[]) { char line[4096]; std::ifstream stream ("/home/jbellone/largefile.csv"); // Seek forward to somewhere past 4GB stream.seekg (10294967296, std::ios_base::beg); stream.getline (line, 100); std::cout &lt&lt stream.tellg() &lt&lt " " &lt&lt line &lt&lt "\n"; }
1,749,531
1,749,556
help on typedefs - basic c/c++
i have been going through some code and came across a statement that somehow disturbed me. typedef GLfloat vec2_t[2]; typedef GLfloat vec3_t[3]; From my perspective, a statement such as typedef unsigned long ulong; Means that ulong is taken to mean unsigned long Now, can the statement below mean that vec2_t[2] is equivalent to GLfloat?? typedef GLfloat vec2_t[2]; Most likely, Probably its not the intended meaning. I would appreciate it if someone clears this up for me. Thanks
Basically a typedef has exactly the same format as a normal C declaration, but it introduces another name for the type instead of a variable of that type. In your example, without the typedef, vec2_t would be an array of two GLfloats. With the typedef it means the vec2_t is a new name for the type "array of two GLfloats". typedef GLfloat vec2_t[2]; This means that these two declarations are equivalent: vec2_t x; GLfloat x[2];
1,749,534
1,749,604
Multiple dispatch in C++
I am trying to understand what multiple dispatch is. I read a lot of various texts but I still have no idea what multiple dispatch is and what it is good for. Maybe the thing I am missing is piece of code using multiple dispatch. Please, can you write a little piece of code in C++ using multiple dispatch so that I can see it cannot be compiled/runned properly because C++ has only single dispatch? I need to see the difference. Thanks.
Multi-dispatch is the ability to choose which version of a function to call based on the runtime type of the arguments passed to the function call. Here's an example that won't work right in C++ (untested): class A { }; class B : public A { }; class C : public A { } class Foo { virtual void MyFn(A* arg1, A* arg2) { printf("A,A\n"); } virtual void MyFn(B* arg1, B* arg2) { printf("B,B\n"); } virtual void MyFn(C* arg1, B* arg2) { printf("C,B\n"); } virtual void MyFn(B* arg1, C* arg2) { printf("B,C\n"); } virtual void MyFn(C* arg1, C* arg2) { printf("C,C\n"); } }; void CallMyFn(A* arg1, A* arg2) { // ideally, with multi-dispatch, at this point the correct MyFn() // would be called, based on the RUNTIME type of arg1 and arg2 pFoo->MyFn(arg1, arg2); } ... A* arg1 = new B(); A* arg2 = new C(); // Using multi-dispatch this would print "B,C"... but because C++ only // uses single-dispatch it will print out "A,A" CallMyFn(arg1, arg2);
1,749,597
1,749,661
how do aim bots in fps games work?
I was curious if anyone had any experience/knowledge about aim bots in online FPS games such as Counter-Strike. I am curious and would like to learn more about how the cursor knows how to lock on to an opposing player. Obviously if I wanted to cheat I could go download some cheats so this is more of a learning thing. What all is involved in it? Do they hook the users mouse/keyboard in order to move the cursor to the correct location? How does the cheat application know where exactly to point the cursor? The cheat app must be able to access data within the game application, how is that accomplished? EDIT: to sids answer, how do people obtain those known memory locations to grab the data from? EDIT2: Lets say I find some values that I want at location 0xbbbbbbbb using a debug program or some other means. How do I now access and use the data stored at that location within the application since I don't own that memory, the game does. Or do I now have access to it since I have injected into the process and can just copy the memory at that address using memcpy or something? Anyone else have anything to add? Trying to learn as much about this as possible!
Somewhere in the game memory is the X,Y, and Z location of each player. The game needs to know this information so it knows where to render the player's model and so forth (although you can limit how much the game client can know by only sending it player information for players in view). An aimbot can scan known memory locations for this information and read it out, giving it access to two positions--the player's and the enemies. Subtracting the two positions (as vectors) gives the vector between the two and it's simple from there to calculate the angle from the player's current look vector to the desired angle vector. By sending input directly to the game (this is trivial) and fine-tuning with some constants you can get it to aim automatically pretty quickly. The hardest part of the process is nailing down where the positions are stored in memory and adjusting for any dynamic data structure moving players around on you (such as frustum culling). Note that these are harder to write when address randomization is used, although not impossible. Edit: If you're wondering how a program can access other programs memory, the typical way to do it is through DLL injection. Edit: Since this is still getting some hits there are more ways that aimbots work that are more popular now; namely overwriting (or patching in-place) the Direct3D or OpenGL DLL and examining the functions calls to draw geometry and inserting your own geometry (for things like wall-hacks) or getting the positions of the models for an aimbot.
1,749,650
1,749,969
Game programming for windows in C++ or C#
I just learned the basics of c++ and c#,just the simple basics of the language.And I want to pursue game programming can anyone please tell me where to start off I read somewhere that Direct-X is used for game programming and I downloaded it from Microsoft's website but I just didn't understood it.From where did you people started your game programming when you were just beginners or do I need to have a deep knowledge about the language or can I just start now, please suggest me.And I am in the first semester of my cs undergraduate degree.
From reading your comments to the original question, it would seem that you have fallen into the trap of setting your sights far too high. The game 'World of Goo' did not happen overnight. It took a long time using lots of third party libraries to do the video/audio/physics/gameplay elements and a very good working knowledge of programming in general and an understanding of the restrictions doing a game often imposes. Now, this may seem like a negative response but the point is it is better to achieve something small than to fail at something big. Failure generally puts people off doing what they really want to do. Byron Whitlock's advice of "start coding now" is the best advice. But, start off with something simple: a text based version of Guess the Colours for example, then some easy, non-realtime graphics like Othello / Reversi / Sliding puzzles then try something realtime like Tetris and then branch out into physics, audio, 3D and so on. The key to becoming a great programmer is to get code finished and working (shipping is a feature!), learn from the code - see if there are better ways to do stuff and so on. Start small, finish some programs, get a morale boost, firm up your foundations and gradually add complexity from there.
1,749,740
1,749,770
Are thread and process ids unique?
I am using a static library; it has a function which uses the current time and creates a unique id, which is then inserted into my database. This number should be unique in my database table. There are two processes running in parallel. Sometimes they simultaneously call this function, and the same number is generated. I get an integrity violation when this happens. I am thinking to use the process id, the thread id, and the current time. Is this combination unique? Platform: Windows XP
Use the database to generate them. How to do that depends on the database, but Postgres calls them sequences for an example.
1,749,767
1,750,005
Track handle creation / deletion
I have a large old program which has some rather complex graphical displays (all via standard API calls). The program appears to be working fine, but I recently looked at the "handles" field of Windows Task Manager when this program was running and noticed that the number of handles was gradually and relentlessly creeping upwards. Is there some software or strategy I can employ to trace this rogue handle creation? I Would expect the program to create a large number of handles, but I would also expect this to reach a limit. So what I really want to see is which part of the code was creating the most recent handles. EDIT: After some investigation with "Process Explorer" I have discovered that the thing that is creeping up is "Handles" rather then "GDI Handles". So I guess that means its nothing to do with the complex graphics.
Please try this link for advice. Problem is complex and somebody has written tutorial on how to tackle it. Update: here is one more link that can help.
1,749,951
1,750,199
C++ IntelliSense 'auto' feature? Where is it? How to get it 'on'?
I would like to enable the IntelliSense 'auto' feature (like the Visual Studio C# 2008 Express) but I am using Visual Studio C++ 2008 Express Edition and in the Tools > Options > Text Editor > C/C++ (there is no option 'IntelliSense' (like Visual C#). How do I get this feature enabled? I know I can get a shortcut in place (CTRL-space etc...)? But how do I get it automatically (the drop down menu)?
In C++, IntelliSense is turned on by default (and AFAIK there isn't even an official way to turn it off). However, when you're coming from C#, you might think it's turned off, because it's so much less powerful in C++. (The reason for this is that C++ is much, much harder to parse. You can find more information on the subject here and here.) Visual Assist improves C++ considerably (although it might not be all that considerably when you're used to C#), but I don't think you can install plugins in the express edition.
1,750,275
1,761,635
how to display IBitmapImage on CDC
What is the best way to display IBitmapImage on a device context. I am using Windows CE 6.0. void CImaginingTestView::OnDraw(CDC* pDC) { CImaginingTestDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); IBitmapImage* pBitmapImage = pDoc->GetBitmapImage(); if (pBitmapImage) { // how to draw my bitmap on a pDC ?? } }
Assuming you're talking about the Imaging API, take a look at the IImage interface an in particular its Draw Method.
1,750,442
1,750,454
Performance of 32-bit integers in a 64-bit environment (C++)
We've started compiling both 32- and 64-bit versions of some of our applications. One of the guys on my project is encouraging us to switch all of our 32-bit integers to their 64-bit equivalents, even if the values are guaranteed to fit in a 32-bit space. For example, I've got a value that is guaranteed to never exceed 10,000 which I'm storing in an unsigned int. His recommendation is to switch this to a size_t so that it expands to 64 bits in a 64-bit environment, even though we'll never need the extra space. He says that using 64-bit variables will speed up the application regardless of the values stored in each variable. Is he right? It's turning out to be a lot of work, and I'm not anxious to put in the effort if it doesn't actually make a difference. We're using Microsoft Visual C++ 2008. I'm kinda hoping for a more general, platform-independent answer though. So what do you think? Are we right to spend time changing our data types for performance reasons rather than range reasons?
I think you have a huge case of pre-mature optimization staring you in the face. Never make micro changes like this in your application until a profiler has definitively told you that it is a source of significant performance problems. Otherwise you'll spend a lot of time fixing non-problems.
1,750,514
1,750,661
Including commented Class declaration in implementation file
Everyone knows the advantages of a more readable code. So in order to make my code more readable what i do normally is include the commented class declaration in the implementation file of that class. This way i need not have to browse through various include directories to go to the definition. So, Is this a good practice or just over-documentation? If there is some standard technique, plz let me know. EDIT: Is there a way to migrate to class declaration from implementation in Vim ? Except opening it in new buffer. Thanks
This is actually counter-productive, because now you have to change three locations instead of two when modifying class declaration, and one of these locations won't be checked by compiler to catch any mismatches. Also, in large and quickly-evolving projects comments always get obsolete, so they cannot be trusted. All modern IDEs can help to access class declaration from class implementation in a number of ways, all of which are more convenient than scrolling to the top of file and then back. As an alternative, consider using an auto-documentation tool such as doxygen. Doxygen can be told to include entire class declarations in the documentation -- with syntax highlighting, line numbers and links to the source files. You can include a doxygen pass in your build process and always have an up-to-date code reference.
1,750,517
1,750,549
Import C++ classes in python?
so.. let's say i have this C function: PyObject* Foo(PyObject* pSelf, PyObject* pArgs) { MessageBox(NULL, "Foo was called!", "Info", MB_OK); return PyInt_FromLong(0); } and then, I have to do this: static PyMethodDef Methods[] = { {"Foo", Foo, METH_NOARGS, "Dummy function"}, {NULL, NULL, 0, NULL} }; Py_InitModule("bar", Methods); and I execute my python script.. but C functions are a little annoying, it's C++ and I use classes for almost everything. So, is there any way to import member functions from a class to my python script? oh btw, the python script looks something like this: import bar from bar import * Foo()
boost.python enables you to do that very effectively.
1,750,937
1,750,958
I need high performance. Will there be a difference if I use C or C++?
I need to write a program (a project for university) that solves (approx) an NP-hard problem. It is a variation of Linear ordering problems. In general, I will have very large inputs (as Graphs) and will try to find the best solution (based on a function that will 'rate' each solution) Will there be a difference if I write this in C-style code (one main, and functions) or build a Solver class, create an instance and invoke a 'run' method from a main (similar to Java) Also, there will be alot of floating point math going on in each iteration. Thanks!
No. The biggest performance gains/flaws will be on the algorithm you implement, and how much unneeded work you perform (Unneeded work could be everything from recalculating a previous value that could have been cached, to using too many malloc/free's vs using memory pools, passing large immutable data by value instead of reference)
1,751,330
1,752,457
ITaskbarList3 undeclared?
I'm trying to write some c++ code to use the ITaskbarList3, but I'm getting that error. I have confirmed that I am including shobjidl.h (but I checked and this file only defines up to ITaskbarList2). I have Visual Studios 2008 (SP1) and I have Microsoft Windows SDK for Windows Server 2008 installed. Does anyone know what I am missing?
You need to install the Windows 7 SDK. That has an update shobjidl.h with ITaskbarList3.
1,751,346
1,751,368
interpret signed as unsigned
I have a value like this: int64_t s_val = SOME_SIGNED_VALUE; How can I get a uint64_t u_val that has exactly the same bit pattern as s_val, but is treated as unsigned? This may be really simple, but after looking on Stackoverflow and elsewhere I haven't turned up the answer.
int64_t s_val = SOME_SIGNED_VALUE; uint64_t u_val = static_cast<uint64_t>(s_val); C++ Standard 4.7/2 states that: If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). ] From the other hand, Standard says that "The mapping performed by reinterpret_cast is implementation-defined. [Note: it might, or might not, produce a representation different from the original value. ]" (5.2.10/3). So, I'd recommend to use static_cast.
1,751,352
1,920,101
automake dependency tracking for nonstandard C++ suffix
how can i force automake to generate dependency tracking for nonstandard C++ suffix files? in particular I mean generating .deps directory file content. I am using libtool as well. Thanks
Take a look at this section in the automake manual regarading default _SOURCES. It looks like saying: bin_PROGRAMS = target AM_DEFAULT_SOURCE_EXT = .foo will get you past the first step. So, now automake knows where to look for the first dependency (target.foo), and it will ask GCC to compute the dependencies of target.foo based upon the header file names that are included in that file. GCC spits out the inferred object names, transforming the included stem.h -> stem.o. And here's where I hit a wall. To have your automake script be completely portable, you cannot use the % patterns. You must use the suffix stacking, as wallyk demonstrated in his answer. Depending upon your portability requirements, you could just ignore that and define the implicit rule in Makefile.in to be something like: %.o : %.foo $(CXX) -o $@ -c $(CPPFLAGS) $(CXXFLAGS) $< If portability is a strict requirement I'm afraid you're out of luck without a lot of hacking.
1,751,441
1,752,594
How to subtract one audio wave from another?
How to subtract one audio wave from another? In general and in C# (or if we cannot do it in C# in C/C++) I have sound wave A and sound wave B (BTW: they are in PCM) I want to subtract B from A What do I need? Open Source Libs (NOT GPL, but LGPL will be ok) Tutorials on how to do such operation (with or without using libs) Articles on this topic PS: it’s all about AEC…
If the samples are normalised to the same level, and are stored in a signed format such that the "zero level" is 0 or 0.0, the answer is fairly simple: S_C = (S_A / 2) - (S_B / 2); for each sample S_A and S_B in A and B. If you are using unsigned values for the samples then you will need to do more work: first, you need to convert them to a signed value with a zero centre (eg, if you have 16 bit unsigned samples, subtract 32768 from each), then apply the formula, then convert them back to the unsigned format. Be careful of overflow - here's an example of how to do the conversions for the aforementioned 16 bit samples: #define PCM_16U_ZERO 32768 short pcm_16u_to_16s(unsigned short u) { /* Ensure that we never overflow a signed integer value */ return (u < PCM_16U_ZERO) ? (short)u - PCM_16U_ZERO : (short)(u - PCM_16U_ZERO); } unsigned short pcm_16s_to_16u(short s) { /* As long as we convert to unsigned before the addition, unsigned arithmetic does the right thing */ return (unsigned short)s + PCM_16U_ZERO; }
1,751,671
1,751,702
boost::format - attempting to use HTML as formatter string - need some help
I'm attempting to use boost::format, where my formatting string is the HTML below. I intend to insert 3x std::strings at locations specified by %s placeholders. In other words - I'm opening the below *.html file for reading, read it's contents into a single std::string and use it as the formatter. Next I'm attempting to do the following : std::string output = (boost::format(formatter) % str1 % str2 % str3).str(); Where str1-3 are strings containing text which I'm attempting to insert - obviously. The format attempt throws an exception saying that the format string is ill-formed. I've been trying to analyze it for the better part of the last 2 hrs but I've failed and I need some help. What is wrong with the below HTML - why can't it become the proper formatter string? What are the limitations I should be aware of ? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>KP&D</title> <style type="text/css"> html, body { height: 100%; margin: 0; padding: 0; } img#bg { position:fixed; top:0; left:0; width:100%; height:100%; } #content { position:relative; z-index:1; } </style> </head> <body> <img src="Images/PageBackground.png" alt="background image" id="bg" /> <div id="content"> <br/>&nbsp; <img src="Images/MyLogoReflected.png" alt="logo image"/> <br />&nbsp; <img src="Images/PDC_StatusPage.png" alt="remote status page image" /> <br />&nbsp; <img src="Images/PDC_RemoteConfiguration.png" alt="remote config image" /> <br />&nbsp; %s <br />&nbsp; <img src="Images/PDC_RemoteSubsystemStatus.png" alt="remote status image" /> <br />&nbsp; %s <br />&nbsp; <img src="Images/PDC_RemoteConnectivityStatus.png" alt="remote status image" /> <br />&nbsp; %s <br />&nbsp; </div> </body> </html> Here's the code snippet responsible for loading the forementioned file : #include <string> #include <fstream> #include <boost/algorithm/string.hpp> #include <boost/format.hpp> int main() { std::ifstream ifs("welcome.html"); // the html is in that file if(!ifs.good()) return 1; std::string buffer = ""; while(!ifs.eof()) { char buf[256]; ifs.getline(buf, 256); buffer += buf; } buffer = boost::trim_right_copy(buffer); const std::string str1 = "aaa"; const std::string str2 = "bbb"; const std::string str3 = "ccc"; std::string Out = ""; try{ Out = (boost::format(buffer) % str1 % str2 % str3 ).str(); } catch(std::exception &e) { err = e.what(); return 1; } return 0; }
boost::format uses % to delimit format specifications; so the % characters in your CSS are confusing it; it is trying to evaluate them as format specifications. You'll need to replace those with %% to get just a literal % character in the output. If that doesn't help, then I would recommend trying to edit your template down into smaller pieces, until you find a piece as small as possible that demonstrates the problem. Once you do that, you may discover the problem yourself, but if not, edit your post to include that smaller snippet that still demonstrates the problem (preferably 1 or 2 lines of less than 80 characters each), as well as the exact error that you are getting from Boost. Likewise, it would help if you posted a snippet of the code you are using to read in the file, and invoke boost::format; a complete program with just a few lines of code for reading the template in, and printing the output of boost::format, would allow us to see if there's anything in your code that might be causing problems (and again, that may help you isolate the problem yourself). The code you posted (edited a bit so it actually works; you left out declarations of buffer and err), works just fine with the template you posted, if all of the % signs in the CSS are replaced by %%, as I originally suggested. Here's the edited code (including output to check that it works): #include <string> #include <fstream> #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <iostream> int main() { std::ifstream ifs("template.html"); // the html is in that file std::string buffer, err; if(!ifs.good()) return 1; while(!ifs.eof()) { char buf[256]; ifs.getline(buf, 256); buffer += buf; } buffer = boost::trim_right_copy(buffer); const std::string str1 = "aaa"; const std::string str2 = "bbb"; const std::string str3 = "ccc"; std::string Out = ""; try{ Out = (boost::format(buffer) % str1 % str2 % str3 ).str(); } catch(std::exception &e) { err = e.what(); std::cout << err << std::endl; return 1; } std::cout << Out; return 0; } And here's the edited template: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>KP&D</title> <style type="text/css"> html, body { height: 100%%; margin: 0; padding: 0; } img#bg { position:fixed; top:0; left:0; width:100%%; height:100%%; } #content { position:relative; z-index:1; } </style> </head> <body> <img src="Images/PageBackground.png" alt="background image" id="bg" /> <div id="content"> <br/>&nbsp; <img src="Images/MyLogoReflected.png" alt="logo image"/> <br />&nbsp; <img src="Images/PDC_StatusPage.png" alt="remote status page image" /> <br />&nbsp; <img src="Images/PDC_RemoteConfiguration.png" alt="remote config image" /> <br />&nbsp; %s <br />&nbsp; <img src="Images/PDC_RemoteSubsystemStatus.png" alt="remote status image" /> <br />&nbsp; %s <br />&nbsp; <img src="Images/PDC_RemoteConnectivityStatus.png" alt="remote status image" /> <br />&nbsp; %s <br />&nbsp; </div> </body> </html>