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,532,697
1,715,054
Converting from HBITMAP to Jpeg or Png in C++
Does anyone know how I can use an HBITMAP variable to write a png or jpeg file? I first looked into doing this with GDI+ but it gives me errors telling me min/max haven't been defined (defining them just brings more problems), I then looked into libpng's C++ bindings (png++) and couldn't get the examples to compile. thanks, Mikey
HBITMAP bmp; CImage image; image.Attach(bmp); image.Save("filename.jpg"); // change extension to save to png
1,533,017
1,533,123
Dropping privileges in C++ on Windows
Is it possible for a C++ application running on Windows to drop privileges at runtime? For instance, if a user starts my application as Administrator, but there's no reason to run my application as administrator, can I in some way give up the Administrator-privileges? In short, I would like to write code in the main() function which drops privileges I don't need (for instance, Write access on the Windows directory).
Yes, you can use AdjustTokenPrivileges to remove unneeded and dangerous privileges from your token. You can either disable if not immediately needed (the privilege can be enabled later) or remove a privilege from your token altogether. You can also create a restricted token via CreateRestrictedToken and relaunch your application running with that restricted token. CreateRestrictedToken can be used to disable privileges and remove groups (like Administrators Group) from a token. You may be able to use AdjustTokenGroups to remove the administrator group from the token of your running process, but I've never tried this on an already running process. Note that write-access to the Windows directory is not covered by a privilege. Resources in the system have ACL's which govern who has access. System and administrators have write-access to the Windows directory.
1,533,134
1,894,918
Use gSOAP for VS 2003/C++ access to SOAP Web Service with WS-Security?
We have an upcoming project to allow an old platform that's only extensible with C++ / VS 2003 to call a SOAP-based web service that uses WS-Security. My Google research indicates that gSOAP could be the best way to go. I'm looking for validation and/or alternative suggestions.
I've been using gSoap with the wsse plugin for WS-Security using signatures on both the client and server side for both Windows and Linux. It took some doing, but it works well. It is extremely fast too. It will require you to link OpenSSL with your project. I actually found a bug in the wsse plugin a few releases back that involved direct calls to OpenSSL for signature generation and validation. All of the bugs involved leaking OpenSSL structures. (The fixes were accepted into the source tree and are part of the current release.) Overall, it really wasn't that difficult to get going. I used SoapUI (http://www.soapui.org/) to troubleshoot the signature generation when trying to validate if I was doing something wrong or the remote end was having issues. If you're doing server side WS-Security under Apache2, you'll have to stick with the mod_gsoap 0.6 that comes with gSoap. I had to modify it a bit because it won't deal with WS-Security by default. I believe, but didn't do a lot of investigation, that someone broke mod_gsoap 0.7 that is the current release available at SourceForge. It took me a while to figure out that 0.7 was segfaulting apache2, so maybe this will save you some pain.
1,533,361
1,533,489
XP Visual Style in wxWidgets?
I'd like to know whether it is possible to enable XP Visual Style in wxWidgets, as it is not enabled by default. All of the controls were drawn in classic Windows style. I'm using wxMSW packed with wxPack, but without wxFormBuilder (http://wxpack.sourceforge.net/), and MSVC++ 2008 EE as the ide. So, is it possible to enable the XP Visual Style in wxWidgets applications?
Assuming that wxWidgets are - on windows - simple wrappers around the corresponding windows controls, to get the new XP theming enabled you need to add a manifest to your project that lists the common control dll version 6 as a dependent assembly. Visual Studio has a #pragma directive to allow programmers to easilly insert dependencies in their manifests. Place the following in a cpp or header file. #pragma comment(linker,"/manifestdependency:\"type='win32' "\ "name='Microsoft.Windows.Common-Controls' "\ "version='6.0.0.0' "\ "processorArchitecture='x86' "\ "publicKeyToken='6595b64144ccf1df' "\ "language='*' "\ "\"") If you are using a different build environment, then you need to follow that environments rules for creating a manifest file, and adding it as a resource to the exe file.
1,533,378
1,533,575
JNI Freeing Memory to Avoid Memory Leak
So i have this C++ program that is called via JNI from my Java program, the code follows: JNIEXPORT jstring JNICALL Java_com_entrust_adminservices_urs_examples_authn_LdapAuthenticator2_takeInfo(JNIEnv *env, jobject obj, jstring domain, jstring id, jstring idca, jstring password) { const char *nt_domain; const char *nt_id; const char *nt_password; HANDLE hToken = 0; bool aut = false; nt_domain = env->GetStringUTFChars(domain, NULL); nt_id = env->GetStringUTFChars(id, NULL); nt_password = env->GetStringUTFChars(password, NULL); aut = LogonUser(nt_id, nt_domain, nt_password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &hToken ); /* release buffers */ env->ReleaseStringUTFChars(domain, nt_domain); env->ReleaseStringUTFChars(id, nt_id); env->ReleaseStringUTFChars(password, nt_password); /* release the login handle */ CloseHandle(hToken); if(aut) { return env->NewStringUTF("true"); } DWORD dwError = GetLastError(); LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPTSTR) &lpMsgBuf, 0, NULL ); return env->NewStringUTF((const char*)lpMsgBuf); //returns the contents of lpMsgBuf (error) } in that second to last line jstring newString = env->NewStringUTF((const char*)otherString); is never released, but returned, will it cause an eventual memory leak? is there anyway to get around this? Also is it possible that instead of returning a string i return a boolean (as returned by the LogonUser function), instead of a jstring, and instead add an "errormessage" refrence to be passed in the method, and update that? will my Java program be able to see an update to "errormessage"? Thanks.
NewStringUTF() creates a new java.lang.String -- in other words, an object on the Java heap, which will get collected when there are no more references to it. Or are you asking about otherString? I don't know what FormatMessage does, but it looks like it's allocating memory on the C heap. If that's the case, then yes, you have to explicitly free that memory. You make your life harder by sometimes setting otherString to a constant string. Don't do that. Instead, call NewStringUTF() within the blocks of your if/else, and in the second case free the native C string.
1,533,380
1,533,532
c++ opengl converting model coordinates to world coordinates for collision detection
(This is all in ortho mode, origin is in the top left corner, x is positive to the right, y is positive down the y axis) I have a rectangle in world space, which can have a rotation m_rotation (in degrees). I can work with the rectangle fine, it rotates, scales, everything you could want it to do. The part that I am getting really confused on is calculating the rectangles world coordinates from its local coordinates. I've been trying to use the formula: x' = x*cos(t) - y*sin(t) y' = x*sin(t) + y*cos(t) where (x, y) are the original points, (x', y') are the rotated coordinates, and t is the angle measured in radians from the x-axis. The rotation is counter-clockwise as written. -credits duffymo I tried implementing the formula like this: //GLfloat Ax = getLocalVertices()[BOTTOM_LEFT].x * cosf(DEG_TO_RAD( m_orientation )) - getLocalVertices()[BOTTOM_LEFT].y * sinf(DEG_TO_RAD( m_orientation )); //GLfloat Ay = getLocalVertices()[BOTTOM_LEFT].x * sinf(DEG_TO_RAD( m_orientation )) + getLocalVertices()[BOTTOM_LEFT].y * cosf(DEG_TO_RAD( m_orientation )); //Vector3D BL = Vector3D(Ax,Ay,0); I create a vector to the translated point, store it in the rectangles world_vertice member variable. That's fine. However, in my main draw loop, I draw a line from (0,0,0) to the vector BL, and it seems as if the line is going in a circle from the point on the rectangle (the rectangles bottom left corner) around the origin of the world coordinates. Basically, as m_orientation gets bigger it draws a huge circle around the (0,0,0) world coordinate system origin. edit: when m_orientation = 360, it gets set back to 0. I feel like I am doing this part wrong: and t is the angle measured in radians from the x-axis. Possibly I am not supposed to use m_orientation (the rectangles rotation angle) in this formula? Thanks! edit: the reason I am doing this is for collision detection. I need to know where the coordinates of the rectangles (soon to be rigid bodies) lie in the world coordinate place for collision detection.
What you do is rotation [ special linear transformation] of a vector with angle Q on 2d.It keeps vector length and change its direction around the origin. [linear transformation : additive L(m + n) = L(m) + L(n) where {m, n} € vector , homogeneous L(k.m) = k.L(m) where m € vector and k € scalar ] So: You divide your vector into two pieces. Like m[1, 0] + n[0, 1] = your vector. Then as you see in the image, rotation is made on these two pieces, after that your vector take the form: m[cosQ, sinQ] + n[-sinQ, cosQ] = [mcosQ - nsinQ, msinQ + ncosQ] you can also look at Wiki Rotation If you try to obtain eye coordinates corresponding to your object coordinates, you should multiply your object coordinates by model-view matrix in opengl. For M => model view matrix and transpose of [x y z w] is your object coordinates you do: M[x y z w]T = Eye Coordinate of [x y z w]T
1,533,687
1,533,715
Write a class using a two-dimensional dynamic array
I have a homework assignment. I'm not looking for anyone to do the work for me, I'm just having trouble with one little aspect, although I'd accept advice on other bits as well. The assignment is: Write a class using a two-dimensional dynamic array. The constructor passes in the dimensions of the array. The constructor also intializes all values in the dynamic array to the row index multiplied by the column index. Swap two columns of the two-dimensional array, where the column indexes are passed in as parameters. Do this just by copying addresses, not values of column elemnets. Delete a column of the two-dimensional array, where the column index is passed in as a parameter. Do not just use the delete operator on the column array and set the horizontal array element to NULL. Shrink the size of the horizontal array by 1. Create a print function for the class to print out the values of the two-dimensional array and make sure that your functions are working correctly. After you know that they are working correctly, delete the print function. I need help understanding how to declare the 2D array in the private section. And, as mentioned, if anyone could give me other hints on how to do it, that would be appreciated.
It's been awhile since I've done C++ development, but if I remember correctly, you'd do something like th efollowing: int rows = 5; int cols = 10; int** array = new int*[rows]; for (int i = 0; i < rows; i++) { array[i] = new int[cols]; } I might be mistaken; I see posts to the contrary online where you have to fake 2D arrays with a single dimensional array and change your subscripting: http://en.allexperts.com/q/C-1040/creating-2D-array-dynamically.htm
1,533,916
1,533,956
How to set up a C++ function so that it can be used by p/invoke?
Hopefully this is a brainlessly easy question, but it shows my lack of expertise with C++. I'm a C# programmer, and I've done extensive work with P/Invoke in the past with other people's C++/C dlls. However, this time I've decided to write a wrapper C++ dll (unmanaged) myself, and am then calling my wrapper dll from C#. The problem I am immediately running into is that I am unable to define a C++ function that can be found by p/invoke. I don't know what the syntax for this is, but here's what I'm trying so far: extern bool __cdecl TestFunc() { return true; } Originally I simply had this, but it did not work either: bool TestFunc() { return true; } And then on the C# side, I have: public const string InterfaceLibrary = @"Plugins\TestDLL.dll"; [DllImport( InterfaceLibrary, CallingConvention = CallingConvention.Cdecl, EntryPoint = "TestFunc" ), SuppressUnmanagedCodeSecurity] internal static extern bool TestFunc(); Everything compiles, but when I execute this C# p/invoke call, I get a System.EntryPointNotFoundException: Unable to find an entry point named 'TestFunc' in DLL 'Plugins\TestDLL.dll'. Surely this must be something incredibly simple on the C++ end that I just don't know the syntax for.
You'll want to use extern "C" as well as __declspec(export), like so: extern "C" _declspec(dllexport) bool TestFunc() { return true; } For full details, see MSDN on Marshalling Types.
1,533,917
1,533,990
C++ template macro shortcut
Often when working with templates, you end up with something like: template <T> class the_class { public: // types typedef T value_type; typedef const value_type const_value_type; typedef value_type& reference; typedef const_value_type& const_reference; typedef value_type* pointer; typedef const_value_type* const_pointer; ... }; This is lot's of the same stuff, though, copied to lots of different templated classes. Is it worthwhile to create something like: // template_types.h #define TEMPLATE_TYPES(T) \ typedef T value_type; \ typedef const value_type const_value_type; \ typedef value_type& reference; \ typedef const_value_type& const_reference; \ typedef value_type* pointer; \ typedef const_value_type* const_pointer; So my class just becomes: #include "template_types.h" template <typename T> class the_class { public: TEMPLATE_TYPES(T) ... }; This seems cleaner, and avoids duplication when I make other template classes. Is this a good thing? Or should I avoid this and just copy-paste typedefs?
Sure, what you're doing would work, but it's kind of old-school. Have you tried to put that stuff into another template class that you could derive from? template <typename T> class template_defs { public: // types typedef T value_type; typedef const value_type const_value_type; typedef value_type& reference; typedef const_value_type& const_reference; typedef value_type* pointer; typedef const_value_type* const_pointer; }; template <typename T> class the_class : public template_defs<T> ...
1,534,324
1,534,349
What does (int **array;) create?
I want to know what is happening in memory when you declare: int **array;
The compiler reserves four bytes (on a 32bit system, eight bytes on 64bit) to store a pointer (that would point to another pointer, that would point to an int). No further memory allocation is done, it is left to the programmer to actually set the pointer to point to some other memory location where the int*/array/... is stored.
1,534,335
1,534,369
std::string equivalent for data with null characters?
I'd like to read a binary file and use something like std::string that automatically resizes the buffer and such. I'm using Visual C++. What are my options?
std::string should be safe to do so... you only have to be careful using .c_str() method. Use .data().
1,534,399
1,534,415
What's the difference between std::string::c_str and std::string::data?
Why would I ever want to call std::string::data() over std::string::c_str()? Surely there is some method to the standard's madness here...
c_str() guarantees NUL termination. data() does not.
1,534,437
1,534,566
I'm starting my C++ learning, using CodeBlocks and windows, what compiler should I use?
I'm under the impression certain compilers only work for making windows applications.
If you care about portability to Unix, use the mingw compilers which are based on gcc. Gcc is widely available on a lot of architectures and OS. If you only work for Windows, Visual Studio Express might be a better choice in comparison to Codeblocks.
1,534,450
1,534,729
C++ or Python for C# programmer?
I am a corporate C# programmer. I found some time to invest into myself and stumbed upon a dilemma. Where to go from now? C#/.NET is easy to learn, develop for, etc. In future I would want to apply to Microsoft or Google, and want to invest spare time wisely, so what I will learn will flourish in future. So: Python or C++ for a C# programmer? I am a little scared of C++ because developing anything in it takes ages. Python is easy, but I take it as a child-play language, which still need lots of patching to be some mature development tool/language. Any C# developers having same dilemma?
C# is a little closer to Java and C++ than it is to Python, so learn Python first out of the two. However, my advice would be: Stick with your current language and learn more techniques, such as a wider range of algorithms, functional programming, design by contract, unit testing, OOAD, etc. learn C (focus on figuring out pointers, multi-dimensional arrays, data structures like linked lists, and resource management like memory allocation/deallocation, file handles, etc) learn Assembly (on a modern platform with a flat memory architecture, but doing low-level stuff like talking to hardware or drawing on a canvas) learn Python or Ruby. Chances are, you'll stick with one of these for a while, knowing all of the above, unless some hot new language has come along by then.
1,534,473
1,534,496
In a header file for other programm to use, can I only declare the templates?
I was wondering about using or not templates, in other thread I found out that templates must be implement in the header file because of some reasons. Thats ok, my question is if the source will be need if other programm use it? from the logic of the other thread's answer, it seems that even other programm would need the full implementation so the compiler can say if a line can or not use the templated function. if yes, I guess templates are not a good thing for the developer who wants others to use his library? if no, then we are good and templates will be used. or if at least there is anyway to save my hard, hours spent, code from others? (I will use stl vectors and such, but I am asking for my own code... Templates seem to be nice, save you a lot of hardcoded lines or macro abusing, but if others can read your source than it makes almost no sense[lot of sense to open projects xD]) Thanks, Joe
If you want users of your library to be able to use your templates, their source code needs to be available to those users. However you can sometimes design your template classes so that most of the logic happens in non-template classes which don't have the full source code in the headers.
1,534,555
1,537,322
C++, boost asio, receive null terminated string
How can I retrieve null-terminated string from a socket using the boost::asio library?
m_socket = boost::asio::ip::tcp::socket(io_service); boost::asio::streambuf replyBuf; ... ... boost::asio::read_until(m_socket, replyBuf, '\0'); And if you want to transform the streambuf to a string: std::string retVal((std::istreambuf_iterator<char>(&replyBuf)), std::istreambuf_iterator<char>());
1,534,600
1,534,610
Are there any numeric suffixes for specifying a double?
void Foo(float a){} //1 void Foo(double a){} //2 overloaded Foo(1.0f); //calls function 1 Foo(1.0 /*double numeric suffix?*/); //calls function 2 If not, is a cast the only way this can be achieved? I am mainly interested in ensuring double precision math during certain operations, etc: ulong j; double v; j = /*some value*/; if(j>0UL) v = 1.0 / j; //if 1.0 is set as a float by the compiler then //could it be likely we lose some precision here //if a double would allow for more precision? Is //a cast the only means of ensuring double precision? Other tips on allowing the compiler to auto-determine the types during an operation would be helpful.
A suffix is unnecessary in C++. Any floating point value which lacks the 'f' suffix will be typed to the compiler type double by default. Reference: http://en.wikipedia.org/wiki/C_0x
1,534,659
1,535,608
How to dereference a pointer passed by reference in c++?
I'm doing (something like) this: void insert(Node*& node, string val, Node* parent) { if (node == NULL) instantiateNode(node, val, parent); else insert(node->child, val, node); } The thing is, that instantiateNode(..., parent) seems to modify the original *&node passed into the function when setting the *parent. instantiateNode() is supposed to alter the node, but if it alters the parent than you have a node that is set to its parent, which doesn't make sense, and also doesn't work. At all. The reason I'm bothering with pointer references at all is because it eliminates special cases and significantly reduces the amount of error checking I have to do. Since I'm doing it to reduce line count and trivial algorithm-ish duplication, I can get around this by approximately doubling the code line count. But I'd rather not, and I feel like there should be a way to dereference a pointer reference to get a new pointer that points to the same object. And, really, I thought that pass of *&node through *parent should have done it, but apparently gcc is optimizing it out.
there should be a way to dereference a pointer reference to get a new pointer that points to the same object. Well, how about this? Node* n = node; Now you've got a non-reference pointer that points to the same object as node, exactly what you asked for. I am 95% sure the problem you are facing has nothing to do with references, and everything to do with faulty logic in instantiateNode or your use of it. That's why it would be useful if you gave us more information about what the code is supposed to do, or even posted the code to instantiateNode.
1,534,713
1,535,325
Software or tools recommended to improve fast your C++ programming skills
List anything you think is great to improve c++ knowledge... Please be concrete when giving solutions.
1) Daily Read c++ , stl and related tagged question on stackoverflow , Try analyze the problems , think of solution , and understand solution given by others 2) :) Start working on C++ in you work , If you have good senior people who do a strict code/design review and give valid comments , you will learn c++. 3) Participate on open source projects , Download source and analyze it. 4 Regarding tool : Use source code analyzer like coverity , Lean window debugging tools package or something equivalent in unix,
1,534,734
1,534,811
Fast (in means of developer time) way to use a lot of C++ code from Java
Background: We are designing a physics app, that will do a lot of data analysis, but our focus is integrating physical electronic equipement. Basically I would like to be able to call root (it's a big data analysis library from CERN written in C++) library written in C++ library from Java. Basically ability to use ROOT classes from Java (and doing it without losing much time to code JNI wrappers) is a showstopper to us (if it will be hard, most probably we will be using Qt). I can think of following methods JNI - as I said - we dont want to write wrappers for every class. . . JNA - JNA doesnt provide C++ mappings, but only C. SWIG - I didn't use it, but heard it's hard to use. Other things that may be revelant: we have access to root source code, but we dont want to change it. We want results to be portable. We would like to stick to free libraries. And as I said - we would be able to use much of the ROOT code from the beginning, without fuss.
With any choice, you're going to need to do some wrapping. While you don't want to write JNI wrappers for every class, you could write higher level C++ classes that encompass groups of methods. Then you only need to write wrappers for the higher level classes (this approach works for other methods too, not just JNI).
1,534,752
1,534,849
How to make C++ code draw on Java components
We are designing physics app, and we would like to have it written in Java, and also we want to use root (root is writen in C++). Root has some nice graphical features -- it is able to draw very nice 3D charts, and I'm thinking whether it's possible to embedd those charts in Java app. Is there any way to make C++ code draw on for example JPanel? Is there a way to pass back mouse/keyboard events? - we would like to have some interactivity, like rotating a 3d chart. I asked similar question about embedding a lot of C++ code (that is not related to drawing anything) in Java app (also about root) it's here.
Since SWT is built to be a fairly thin wrapper around native widgets, it may be easier to work with than Swing/AWT for your particular task. I realize this particular link is a bit old, but it does show how to quickly wrap a native widget.
1,534,826
1,534,842
Learning to create animations in C++
does anyone know where I can learn to create and manipulate animations in c++ for the purpose of game development?
GameDev.net would probably be a good place to start, they have links to plenty of tutorials for both DirectX and OpenGL. The NeHe OpenGL tutorials are a pretty good introduction. Microsoft alos has quite a few tutorials and sample applications that come with the DirectX SDK.
1,534,912
1,534,929
How to build in release mode with optimizations in GCC?
What are the specific options I would need to build in "release mode" with full optimizations in GCC? If there are more than one option, please list them all. Thanks.
http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html There is no 'one size fits all' - you need to understand your application, your requirements and the optimisation flags to determine the correct subset for your binary. Or the answer you want: -O3
1,535,004
1,535,031
How to divide two doubles accurately
I have two double a, b; I know that the following is true -1 <= a/b <= 1 however b can be arbitrarily small. When I do this naively and just compute the value a/b the condition specified above does not hold in some cases and I get values like much greater than 1 in absolute value (like 13 or 14.) How can I ensure that when I divide by b, I get a value such that the condition mentioned above can be enforced. In the case where I can not guarantee this I am happy to set the computed value a/b to 0.
What you need to enforce is abs(a)≤abs(b). If that condition holds, then -1≤a/b≤1, regardless of floating-point precision used. Your logic error is occurring before the division, since at the division point abs(a)>abs(b) which violates your a-priori requirement.
1,535,105
1,535,309
code blocks 8.02 console program not outputting cout statements with SDL
im currently using the SDL-devel-1.2.13-mingw32 library in code blocks 8.02. with the mingw 5.1.6 installed separately on C:\ this program compiles and runs with no errors but i can't see the last system("pause"); on the screen. When i press any key, it of course skips over the system("pause"); then code blocks tells me that it successful ran. It also doesn'w show the cout << " SDL \n"; WTF? #include <iostream> #include <SDL.h> using namespace std; int main(int argc, char *argv[]) { cout << " SDL \n"; cout << endl; if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) == -1) { cerr << "Failed to initialize SDL: " << SDL_GetError() << endl; exit(1); } atexit(SDL_Quit); system("pause");` return 0; }
Depending on the options used to compile SDL, console output may be redirected to files called stdout.txt and stderr.txt -- this is the default for most Windows builds. See this wiki article for a solution: http://www.libsdl.org/cgi/docwiki.cgi/FAQ_Console
1,535,207
1,535,248
Memory leak caused by a wrong usage of scoped_lock?
I have a memory leak, and I guess it's caused by a wrong usage of scoped_lock (Boost). I however don't manage to find the exact problem, and I do believe that the way the code has been written is not completely right neither. The code is in this class there: http://taf.codeplex.com/SourceControl/changeset/view/31767#511225 The main important method is ThreadedLoop(). Basically, this method is started within a thread, and checks regularly for market data to be downloaded for Yahoo. For each stock (or else), a new thread will be created (for the ExecuteNextRequest() method), passing as a parameter a pointer to string containing the stock name. This is the only memory allocation I do, but it's released at the end of the thread execution. I would be also interested in how this code could be enhanced (of course I could use a threadpool, but that's not the point yet). Many thanks!
I suggest that, instead of using a "raw" pointer to std::string, you use a boost::shared_ptr<std::string>, and pass that around. When you're done, call its reset() function; it will decrement the usage count, and free the string automatically when the count is 0. As a bonus, you can attach boost::weak_ptr objects to those strings (you can stick them into a vector maybe), and monitor how many of them are still "live". This way you'll know if something's causing the strings to not be decremented to 0 for any reason. To be clear: if (_tickersQueue.size() > 0) { boost::shared_ptr<std::string> ticker(new std::string(PopNextTicker())); if (!ticker->empty()) _threads.create_thread(boost::bind(&TAFYahooFinanceParadigm::ExecuteNextRequest, this, ticker)); else ticker.reset(); // optional; ticker will drop out of scope anyway } Yes, you have to adjust the function type of ExecuteNextRequest appropriately. :-)
1,535,249
1,535,294
C++ Read File Into hash_map
I'm trying to read in a list of words and save them in a C++ STL hash_map along with their position in the alphabetically sorted file. The idea is later I'll need to be able to tell if a string is a word and whether it comes before or after a different word. ifstream f_dict ("dictionary.txt"); __gnu_cxx::hash_map <const char*, int> dictionary; string temp_str; int counter = 0; while (!f_dict.eof()) { f_dict >> temp_str; dictionary.insert(make_pair(temp_str.c_str(), counter++)); } The problem I'm having is that it isn't saving the actual word. The for loop below prints out a selection of the words, but iter->first is always empty. What am I missing? __gnu_cxx::hash_map<const char*, int>::iterator iter; int i = 0; for (iter = dictionary.begin(); iter != dictionary.end() && i < 150; iter++) { cout << "word: " << iter->first << " index: " << iter->second << "\n"; i++; }
You are trying to store the same const char * for each word because your never creating any new memory for the word pulled from the file. If you print out the pointer being returned from temp_str.c_str(), it will be the same for every call within your first loop. In your second loop you're printing out the same char * for every record in your map (note there is only 1 b/c map does not allow dups) which has been set to empty string either within the 1st loop or between that and your for loop. Here is example code that demonstrates the problem and a solution. #include <fstream> #include <iostream> #include <map> using namespace std; int main (int argc, char **argv) { ifstream file("test.txt"); map<const char *, int> dictionary; map<string, int> strDictionary; string temp_str; int counter = 0; while (!file.eof()) { file >> temp_str; cout << "PARSED: " << temp_str << "\n"; cout << "INSERTING: " << (unsigned long) temp_str.c_str() << "\n"; dictionary.insert(make_pair(temp_str.c_str(), counter)); strDictionary.insert(make_pair(temp_str, counter)); counter++; } cout << "Dictionary Size: " << dictionary.size() << "\n"; cout << "Str Dictionary Size: " << strDictionary.size() << "\n"; for (map<const char*, int>::const_iterator iter = dictionary.begin(); iter != dictionary.end(); ++iter) { cout << "CHAR * DICTINARY: " << iter->first << " -> " << iter->second << "\n"; } for (map<string, int>::const_iterator iter = strDictionary.begin(); iter != strDictionary.end(); ++iter) { cout << "STR DICTIONARY: " << iter->first << " -> " << iter->second << "\n"; } return 1; }
1,535,368
1,535,718
Resource for learning Lua to use with C++?
So I have heard that Lua is a good scripting language that ties into C++. Does anyone know some good resources for picking it up, for someone with lots of C++ experience?
You may want to look at toLua++ or Luabind for C++ integration. As far as learning lua itself goes, the Programming in Lua book or even the Lua Reference Manual shouldn't be out of your league at all; see the documentation section of the lua website. The usual rule applies: read lots of other code when you're getting started. If it's your cup of tea, you could e.g. go dig though World of Warcraft addons for some (admittedly specialized) real-world examples. And listen to the community: subscribe to some mailing lists, take a look at the lua-users resources (especially the wiki), et cetera. I work at a game development company, and we use primarily C++ and lua together. We don't actually use Luabind or toLua++ yet (mostly just a lack of time to test and integrate them), but a few things we've learned: you'll want to make a choice between creating and destroying lua environments (lua_State instances) on demand and keeping one or more around; getting rid of them can alleviate memory issues and provide nice unpolluted execution environments take advantage of lua_pcall's ability to register a debug function, see discussion on Gamedev.net if you're on a memory budget, consider using lua_setallocf to change allocator behavior -- constrain it to its own area of memory to prevent fragmentation, and take advantage of a more efficient small object allocator (perhaps boost::pool) to reduce overhead (other ideas in an earlier answer) get a good lua-aware editor; we use SciTE and Crimson Editor a lot where I work pay some attention to your garbage collector, call gc with various arguments and see what works best for your performance and memory requirements; we've had games where full gc each frame was the right choice, and others where 10% per frame was the right choice when you get comfortable, reach out to metatables; altering index and newindex has proved especially useful for us oh, and coroutines are sexy
1,535,619
1,763,393
Google Geolocation API library
Is there a library out there that will get you your approximate location using the google service (https://www.google.com/loc/json)? Google Gears has support for it as described here http://code.google.com/p/gears/wiki/GeolocationAPI There is also good doco on the web service request/response schema. Firefox and iPhone Safari use the service as well and they have their own implementations. I would like to use the service in my own C# application so I would like a library that I can use (either one of C/C++/C#). Currently the only way my colleague got it working is using a gears plugin for IE and hosting the embedded IE window in our WPF app. This is a bit cumbersome and poorly re-distributable. Any ideas? Edit This is a comment from the above page: Comment by steveblock@google.com, Dec 02, 2008 Thanks for all the comments. A few responses ... Answers to many of the questions about use of the API can be found in the Geolocation >API documentation at http://code.google.com/apis/gears/api_geolocation.html. This Wiki page is intended to document work in progress for those developing Gears, not to serve as definitive documentation of the API. Regarding the JSON protocol, I've updated this document to reflect the current behaviour in Gears. Note that official documentation of the protocol will soon be added to the Geolocation API documentation. The Gears Terms of Service prohibits direct use of the Google location server (http://www.google.com/loc/json) via HTTP requests. This service may only be accessed through the Geolocation API. This kinda sucks. So how does Firefox gets away using this service directly via a HTTP request.
please take a look at Sony PlaceEngine, it will get you the location based on the WiFi signals it can access. The down side is that users have to install the PE client. The up side is that it can be accessed by web sites and/or local apps. There is an online server DB you can query for detailed information, and a local DB option you can query for location estimates when there is no internet. This is used for a bunch of Navigation software, including as a back-up to GPS in Sony's Nav-U units. Also, you can update the placeEngine data yourself (i.e. add new access points). Option 2 is Apple's CoreLocation - which currently uses a service known as SkyHook. I am sure you can use SkyHook on non-Apple platforms if you wish. Google's Latitude service uses Gears somehow, and it must be using WiFi, because it's much too accurate to be based only on IP Address. They are probably using the PlaceEngine or Skyhook databases themselves on the back-end...
1,535,816
1,535,845
C++ partial method specialization
Is there a partial specialization for template class method? template <class A, class B> class C { void foo(); } it doesn't work to specialize it like this: template <class A> void C<A, CObject>::foo() {}; Any help?
If you are already have specialized class you could give different implementation of foo in specialized class: template<typename A, typename B> class C { public: void foo() { cout << "default" << endl; }; }; template<typename A> class C<A, CObject> { public: void foo() { cout << "CObject" << endl; }; }; To specialize member function in Visual C++ 2008 you could make it template too: template<typename A, typename B> class C { template<typename T> void foo(); template<> void foo<CObject>(); }; The solution above seems to will be available only in future C++ Standard (according to draft n2914 14.6.5.3/2).
1,535,988
1,536,011
Swapping Nodes on a single linked list
I am trying to make a swapNode function that can take any two nodes and swap them. I've made an algorithm that works if they're at least 2 nodes away, but I can't seem to come up with an algorithm that will work if they are closer to each other. Here's what I wrote so far: void swapNode(call * &head, call * &first, call * &second){ call * firstPrev = NULL; call * secPrev = NULL; call * current = head; //set previous for first while((current->next != first) ){ current = current->next; } firstPrev = current; current = head; //set previous for second while((current->next != second) ){ current = current->next; } secPrev = current; current = second->next; //set firstPrev-> next to second firstPrev->next = second; //set secPrev->next to first secPrev->next = first; //set second->next = first->next second->next = first->next; //set first->next to current first->next = current; current = head; while(current->next != NULL){ cout << current->number << endl; current = current->next; } cout << current->number << endl; } EDIT: I now have this as my swap part, but it still doesn't seem to work correctly //swap firstPrev-> next with second->next tmp = firstPrev->next; second->next = firstPrev->next; second->next = tmp; //swap swap first->next with second->next tmp = first->next; second->next = first->next; second->next = tmp; EDIT2: This one doesn't seem to work either, I get a seg fault. //swap previous's->next tmp =firstPrev->next; secPrev->next = firstPrev->next; secPrev->next = tmp; //swap swap first->next with second->next tmp = first->next; second->next = first->next; second->next = tmp;
Say we have: Node1 -> Node2 -> Node3 -> Node4 -> Node5 To swap two nodes, you need to swap the next values of the ones before each of them, and also the next values of the nodes you want to swap. So to swap, say, Node2 and Node3, you effectively have to swap Node1->next with Node2->next, and Node2->next with Node3->next. That will work, even if they're right next to each other (or even if it's the same node). For example: Swap Node1->next and Node2->next Node1->next = Node3 Node2->next = Node2 Swap Node2->next with Node3->next Node2->next = Node4 Node3->next = Node2 This comes out as: Node1 -> Node3 -> Node2 -> Node4 -> Node5 Swapped! As unwind noted in the comments section, if swapping Node1 with anything, you'll have to set a new head for the linked list. In response to the edit of the question: Your code for swapping almost right. However, you need to swap the firstPrev with secPrev. It just so happened in my example that we were swapping one of the node's next values twice, because they were next to each other. But logically, we want to swap the nexts of the two previous ones, and then swap the nexts of the actual nodes. Try this: //swap firstPrev-> next with secPrev->next tmp = firstPrev->next; secPrev->next = firstPrev->next; secPrev->next = tmp; //swap swap first->next with second->next tmp = first->next; second->next = first->next; second->next = tmp; If you're getting a segfault, check the tmp variable - it could be an error of allocation or deletion somewhere. Where do you get the segfault?
1,536,026
1,536,312
Touch friendly GUI in Windows Mobile
I'm porting an audio processing application written in C++ from Windows to Windows Mobile (version 5+). Basically what I need to port is the GUI. The application is quite complicated and the GUI will need to be able to offer a lot of functionality. I would like to create a touch friendly user interface that also looks good. Which basically means that standard WinMo controls are out the window. I've looked at libraries such as Fluid and they look like something I would like to use. However, as I said I'm developing i C++. Even though it would be possible to only write the GUI part i some .NET language I rather not. My experience with .NET on Windows Mobile is that it doesn't work very well... Can anyone either suggest a C/C++ touch friendly GUI library for Windows Mobile or some kind of "best practices" document/how-to on how to use the standard Windows Mobile controls in order to make the touch friendly and also work and look well in later versions of Windows Mobile (in particular version 6.5)?
There are two aspects to your question: Libraries. For this I would take a look at Qt for CE/WinMo. The C++ alternative is MFC. GUI Design. About Face and Designing Interfaces (J. Tidwell) are a couple of good books. Also: make sure that your UI is finger-friendly, I hate it when I have to use a stylus. keep in mind that on touch screens you can't have tooltips (no mouse over) and you don't have a mouse pointer. WinMo uses click and long click, but the latter is not easily discoverable. add joystick UI navigation don't try to cram too many controls on the tiny screen, use tabs or drill-down menus
1,536,319
1,554,644
Does C# have an equivalent to #pragma pack in C++?
C# provides StructLayoutAttribute.Pack, but its behaviour is "every member gets at least the specified alignment whether it wants it or not", whereas the behaviour of #pragma pack in C++ is "every member gets the alignment it wants, unless it wants more than the specified alignment, in which case it's not guaranteed to get more than that". Is there a way to cause the layout of a struct in C# to be the same as the layout of a similar struct in C++ with a specific #pragma pack, other than using StructLayout( LayoutKind.Explicit ) and FieldOffset on each member, or inserting unused padding members?
After experimenting with StructLayout.Pack, it appears that it does indeed do exactly the same thing as #pragma pack in C++. Believing the MSDN documentation for StructLayout.Pack (which claimed the behaviour described in my original post) was a mistake.
1,536,566
1,540,203
ValidateUser instead of LogonUser?
We're trying to "lock down" a computer such that we have a generic login account for Windows XP that has very few permissions. Our software is then launched via a launcher that runs it as more privileged user, allowing it to access the file system. Then, an operator will login to our software and we were hoping to authenticate their credentials by using the win32 LogonUser() function. The problem that we're seeing though, is that we want to set the software operators with a "Deny logon locally" group policy but setting this prevents the LogonUser() function from working. I understand that we could work around this by passing LOGON32_LOGON_NETWORK instead of LOGON32_LOGON_NETWORK to LogonUser() but I didn't really want to do as it creates other problems. Instead, I was wondering if there is anything like C#'s ValidateUser() function in C++? (Btw we're compiling with VS2003 if that's relevant)
If you want more control over the login process, you can replace the built-in login with your own, using a Gina dll. Writing your own will probably mean more work then just finding the right arguments for some API calls, but if you're looking for full customization, this might be the solution for you.
1,536,753
1,536,779
Does std::vector.pop_back() change vector's capacity?
If I allocated an std::vector to a certain size and capacity using resize() and reserve() at the beginning of my program, is it possible that pop_back() may "break" the reserved capacity and cause reallocations?
No. The only way to shrink a vector's capacity is the swap trick template< typename T, class Allocator > void shrink_capacity(std::vector<T,Allocator>& v) { std::vector<T,Allocator>(v.begin(),v.end()).swap(v); } and even that isn't guaranteed to work according to the standard. (Although it's hard to imagine an implementation where it wouldn't work.) As far as I know, the next version of the C++ standard (what used to be C++0x, but now became C++1x) will have std::vector<>::shrink_to_fit().
1,536,830
1,536,881
List processes for specific user
Would someone be able to point me to the C++ API's that I can use to display a list of processes and the user name in Windows? My current code uses the CreateToolhelp32Snapshot Function which shows all the processes running for all users, but I do not know what API's to use to retreieve the user name so I can filter it by user. I do not need to use CreateToolhelp32Snapshot, and I have seen other methods to retrieve the process list, but none seem to get me the user name that is running the process. Thanks for any help.
I know that using GetTokenInformation with TokenUser gets you the SID, and a quick serach reveals that LookupAccountSid should get you the corresponding account. Havent't tried that last one myself though.
1,536,837
1,536,939
Creating generic hashtables - C++
.NET framework has got a Dictionary<TKey,TValue> class which is implemented as hash tables and provides data retrieval in constant time (O(1)). I am looking for a similar implementation in C++. I know about std::map but in this data retrieval takes logarithmic time. Is there any good hash table implementation in C++ which will retrieve data in constant time? If I am writing my own, how will I calculate hash code for the key? Like .NET, I thought of having GetHashCode() method on types. template<typename TKey,typename TVal> class Dictionary { public: void Add(TKey key, TVal val){ int hashCode = key.GetHashCode(); /* .... */ } } If I did like the above and the given key type doesn't have GetHashCode() method, compiler will throw error. But this method won't work when key is primitive types like int. I may need to write a wrapper for int by providing GetHashCode. I wonder what is the C++ way of implementing this? Any thoughts?
Also, check out C++ Technical Report 1 for std::tr1::unordered_map if a strict adherence to C++ standard is required. Actually std::hash_map is not C++ standard but widely used anyway.
1,537,151
1,538,026
How to get rid of C4800 warning produced by boost::flyweight in VS2008
I get a warning when compiling below code in VS2008 with MFC turned on. Boost version 1.39 include "boost/flyweight.hpp" include "boost/flyweight/key_value.hpp" class Foo { public: Foo(const CString& item) : mfoo(item) {} const CString& getkeyvalue() const {return mfoo;} private: const CString mfoo; }; struct Conversion { const CString& operator() (const Foo& item) const {return item.getkeyvalue();} }; using namespace boost::flyweights; flyweight<key_value<CString, Foo, Conversion>, tag<Foo> > flyweight_test; The last line in the above code produces a warning d:\work\sourcecode\boost1390\boost\functional\hash\extensions.hpp(72) : warning C4800: 'const wchar_t *' : forcing value to bool 'true' or 'false' (performance warning) d:\work\sourcecode\boost1390\boost\functional\hash\extensions.hpp(71) : while compiling class template member function size_t boost::hash<T>::operator ()(const T &) const with [ T=ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t>> ] d:\work\sourcecode\boost1390\boost\multi_index\hashedindex.hpp(1159) : see reference to class template instantiation 'boost::hash<T>' being compiled with [ T=ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t>> ] This warning goes on and on, through hashed factory, MPL, etc. Why is the warning there and how do I correct the code so no warning is produced? Edit: To fix, add below implementation of hash_value template<typename CharType, typename TraitsType> std::size_t hash_value(const ATL::CStringT<CharType, TraitsType>& s) { return CStringElementTraits<typename TraitsType>::Hash(s); }
One of the classes in flyweight probably uses the hash_value functions (or the wrapper class hash) to calculate a hash value from a ATL::CString. This is not defined in boost directly, so you'll need to provide an implementation: std::size_t hash_value(const ATL::CString& s) { // ... } Just looking at your compiler output, it seems that CString itself is templated, so you would implement template<typename CharType, typename TraitsType> std::size_t hash_value(const ATL::CString<CharType, TraitsType>& s) { // calculate hash e.g. by calling hash_value(const std::string&) }
1,537,164
1,537,196
How to use std::string in a QLineEdit?
I have the following problem. I am trying to integrate a large code written by me with a Qt interface. Some of my functions return std::string. I did not succeed in making QLineEdit::setText accept them (other functions returning char do not give me problems). What should I do? Thanks! Giuseppe
Try this: std::string a = "aaa"; lineEdit->setText(QString::fromStdString(a)); You will need Qt with STL support.
1,537,271
1,537,292
why do we need both const and non-const getters in this example
I came across this example here: #include <vector> #include <cstddef> template<typename Tag> class Ref_t { std::size_t value; friend Tag& element(Ref_t r, std::vector<Tag>& v) { return v[r.value]; } friend const Tag& element(Ref_t r, const std::vector<Tag>& v) { return v[r.value]; } public: // C'tors, arithmetic operators, assignment }; struct A{}; struct B{}; typedef Ref_t<A> ARef_t; typedef Ref_t<B> BRef_t; int main() { std::vector<A> va; ARef_t ar; A& a = element(ar, va); } So the question is why do we need -two friend element functions in Ref_t class?
The difference between the two functions is that an element() of a non-const vector is itself non-const, but if the entire vector is const, then each element() is also const. i.e. int main() { std::vector<A> const cva = foo(); ARef_t ar; A const& a = element(ar, cva); }
1,537,402
1,539,020
Retrieve revision number in VS with qmake
My current workflow: hg update (or whatever one uses to check out a revision) MyProject.pro → qmake → MyProject.vcproj Open Visual Studio, edit files Build project During the build step, how can I update my config.h header file with information from version control system (e.g. hg id)? MyProject.vcproj is generated by qmake, so I shouldn't edit it by hand.
You can execute external commands from inside qmake. The easiest way to make the information available in your sources would be to use a define: HGID = $$system(hg id) DEFINES += HGID=\\\"$$HGID\\\" I'm not sure if you can edit an external file from qmake. You could use an external tool, but on Windows you normally don't have things like sed, so it might be a little more problematic.
1,537,518
1,537,534
C++ Initialization list and memory alloc
Is the following valid? class myClass { private: ... int m_nDataLength; boost::shared_array<int> m_pData; ... public: myClass(): ..., m_nDataLength(10), m_pData(new int[m_nDataLength]), ... { } } Am I right in assuming that the initialization will happen exactly in the order I've given in the ctor? If not, what if m_nDataLength's initialization happens after m_pData's?
While the initialization in your example does happen in the order you want, it's not for the reason you assume: Initialization happens in the order of the data members declaration in the class definition. The reason for this is that the destructor must destroy the members in backward order not matter which constructor was used to create the object. For that, a constructor-independent way of defining the construction order must be used. That means that, if instead of class myClass { private: ... int m_nDataLength; boost::shared_array<int> m_pData; someone would change your code to class myClass { private: ... boost::shared_array<int> m_pData; int m_nDataLength; then the code would have a bug. My advice is: Write your constructors so that the initialiszation order doesn't matter. If you cannot do this (note: to me this happened less than 5 times in the last decade), make it completely clear at the point the data members are declared. Something like this should do: class myClass { private: ... int m_nDataLength; // Note: Declaration order boost::shared_array<int> m_pData; // matters here!
1,537,578
1,537,837
How to unit test an email client
I'm working on a desktop email client right now, and I want to unit test my backend. However, I can't see a way to make that work. In order for my code to work, it has to connect to a working mail server. Unless I tie my unit tests to an email account, and make sure that account matches the state my tests expect, I don't see how I can manage this. Does anyone have any ideas on how to test this sort of application, where it relies on external factors by design? EDIT: To add some details: I'm working on a C++ higher level mail client library for my application, which uses libEtPan, a C library, to actually handle the details of connecting to the mail server and interacting with it.
I'm going to assume by testing the back end you are referring to the bit of code that actually talks to the Email server and to test the rest of your software you have mocked this layer. Now this may or may not be integration tests depending on your definition unit. Frankly I don't care what you decide to call it but if you write some automated tests that are quick to run and are executed often then they might as well use the same platform as your unit tests. I'd try to write this so it can work in at lest the following two ways - The first would be that it connects to an process-local email server that you can set up and configure as you need. In Java I use Dumpster but I'm sure alikes exist for C++. The second would be to connect to at least one local email server that you can script. One that you can splatter as much as you like (so NOT real or shared between developers¹) and run the same set of tests against that. The reason being that the developers of SMTP servers hate everyone and you will want to check that your stub works the same as a real thing. This I see as the equivalent to One Database Per Developer. Now if you have not written your own SMTP client and just have a facade around an existing 3rd party API I less likely to "integration test" this on the assumption that the 3rd party API has been battered enough that bugs have already fallen out. I would look at mocking the 3rd party API and validating that the facade works as expected. 1) Maybe you could do this just during the CI cycle, so then share one set of email servers between all developers and the local run just uses a C++ Dumpster alike.
1,537,583
1,621,656
Qt linguist & google translate
I'm looking for a way to cheat and create some very rough translations of my Qt application using Qt linguist and an already-existing translation service such as google translate. There's a public API for google translate, so I'm hoping someone has already tried this, but I can't seem to find it. Has anyone seen anything like this before? I'm not expecting brilliant translations - at this point it's just to show as a proof of concept.
I've written an open source app to do this with gettext .po files, it wouldn't be hard to modify for Qt Linguist files. Demo and php source available at http://pepipopum.dixo.net
1,537,618
1,537,642
What are map files generated during compilation
What info map file contain generated during compilation of project and how i enable /map option in makefile. Language : c++ compiler : vc6
From Microsoft's documentation for the /MAP linker option: A mapfile is a text file that contains the following information about the program being linked: The module name, which is the base name of the file The timestamp from the program file header (not from the file system) A list of groups in the program, with each group's start address (as section:offset), length, group name, and class A list of public symbols, with each address (as section:offset), symbol name, flat address, and .obj file where the symbol is defined The entry point (as section:offset)
1,537,823
1,537,860
How can I ask Windows to print a document?
I want to (programmatically) print documents of various types, by asking Windows to do it (using the default associated application). How can I do this (in .NET or C++/Win32 API)? For example, if I have MS Office and Acrobat Reader installed on the machine, PDF files should be printed by Acrobat Reader, and DOC files should be printed by MS Word. But if I don't have MS Office installed, DOC files should be printed using Wordpad, or OpenOffice.org Writer if the latter is installed, or whatever application is currently the default association for that type of files.
Try using the ShellExecute function. For example, in C: ShellExecute(my_window_handle, "print", path_to_file, NULL, NULL, SW_SHOW);
1,537,964
3,312,896
Visual C++ equivalent of GCC's __attribute__ ((__packed__))
For some compilers, there is a packing specifier for structs, for example :: RealView ARM compiler has "__packed" Gnu C Compiler has "__attribute__ ((__packed__))" Visual C++ has no equivalent, it only has the "#pragma pack(1)" I need something that I can put into the struct definition. Any info/hack/suggestion ? TIA...
You can define PACK like as follows for GNU GCC and MSVC: #ifdef __GNUC__ #define PACK( __Declaration__ ) __Declaration__ __attribute__((__packed__)) #endif #ifdef _MSC_VER #define PACK( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop)) #endif And use it like this: PACK(struct myStruct { int a; int b; });
1,538,137
1,538,193
C++ static global non-POD: theory and practice
I was reading the Qt coding conventions docs and came upon the following paragraph: Anything that has a constructor or needs to run code to be initialized cannot be used as global object in library code, since it is undefined when that constructor/code will be run (on first usage, on library load, before main() or not at all). Even if the execution time of the initializer is defined for shared libraries, you’ll get into trouble when moving that code in a plugin or if the library is compiled statically. I know what the theory says, but I don't understand the "not at all" part. Sometimes I use non-POD global const statics (e.g: QString) and it never occured to me that they might not be initialized... Is this specific to shared objects / DLLs? Does this happen for broken compilers only? What do you think about this rule?
The "not at all" part simply says that the C++ standard is silent about this issue. It doesn't know about shared libraries and thus doesn't says anything about the interaction of certain C++ features with these. In practice, I have seen global non-POD static globals used on Windows, OSX, and many versions of Linux and other Unices, both in GUI and command line programs, as plugins and as standalone applications. At least one project (which used non-POD static globals) had versions for the full set of all combinations of these. The only problem I have ever seen was that some very old GCC version generated code that called the dtors of such objects in dynamic libraries when the executable stopped, not when the library was unloaded. Of course, that was fatal (the library code was called when the library was already gone), but that has been almost a decade ago. But of course, this still doesn't guarantee anything.
1,538,332
1,539,432
How should I name my class, functions, member variables and static variables?
Some may feel this question is subjective. But, I feel this is among the most important things to be told to a programmer. Is this a good function name to check for null values. 1. checkNull() 2. notNull() 3. isNull() What if I write checkIfNull() I do not know how many people share the same feeling as I do, I have spent more time in thinking good names for my functions than writing one. How do people think of good names? Can the naming be consistent across languages (mainly C++ and Java) Update: As I go by the number of updates till now, Most people prefer isNull(). How do you decide upon this that isNull() is the perfect name. checkNotNull() // throw exception if Null Is this a good name? Does everyone depend upon their intuition for deciding a name? The question is about choosing a perfect name!!!
I found this article. Felt like sharing with you guys!
1,538,441
1,539,067
How good is this representation of a context free grammar for a parser?
i have shared the header file containing class definition of a Context Free grammar for a parser. Could you comment on the design. this code is for my lab assignment. may be we could get some good programming tips out of this code. is the class hierarchy good or too complicated. #ifndef CFG_H #define CFG_H #include <iostream> #include <set> #include <list> using namespace std; class Terminal; class CfgSymbol { protected: char ch; set<Terminal*> first; set<Terminal*> follow; public: CfgSymbol() { ch = '\0'; } CfgSymbol(char c) : ch(c) { } virtual void computeFirst() = 0; }; class Terminal: public CfgSymbol { private: public: Terminal(): CfgSymbol() { } Terminal(char c) : CfgSymbol(c) { computeFirst(); } virtual void computeFirst() { first->insert(this); } }; class NonTerminal: public CfgSymbol { private: public: virtual void computeFirst(); virtual void computeFollow(); }; class SymbolString { public: CfgProduction* prd; list<CfgSymbol*> symstr; void computeFirst(); void computeFollow(); }; class CfgProduction { private: NonTerminal lhs; SymbolString rhs; public: int add_terminal(char t); int add_nonterminal(char n); int set_lhs(char c); }; class Cfg { public: vector<CfgProduction*> prdList; void addProduction(const CfgProduction& cfg); void computeFirst(); void computeFollow(); void computeFirstFollow(); }; #endif
Spirit's documentation should give you a nice intro for grammar implementation (with templates). Don't know your level, maybe that's too simple, but its quite interesting : As a grammar becomes complicated, it is a good idea to group parts into logical modules. For instance, when writing a language, it might be wise to put expressions and statements into separate grammar capsules. The grammar takes advantage of the encapsulation properties of C++ classes. The declarative nature of classes makes it a perfect fit for the definition of grammars. Since the grammar is nothing more than a class declaration, we can conveniently publish it in header files. The idea is that once written and fully tested, a grammar can be reused in many contexts. We now have the notion of grammar libraries.
1,539,003
1,539,042
Why is it a linker error to #include this file more than once?
This question isn't so much a 'how to solve' question as its a question about why doesn't this work? In C++ I can define a bunch of variables that I want to use across multiple files in a few ways. I can do it like this: int superGlobal; #include "filethatUsesSuperglobal1.h" int main() { // go. } That way ONLY works if "filethatUsesSuperglobal1.h" has its entire implementation there in the header and no attached .cpp file. Another way (the "morer correcter" way) is to use extern: externvardef.h #ifndef externvardef_h #define externvardef_h // Defines globals used across multiple files. // The only way this works is if these are declared // as "extern" variables extern int superGlobal; #endif externvardef.cpp #include "externvardef.h" int superGlobal; filethatUsesSuperglobal1.h #include "externvardef.h" #include <stdio.h> void go(); filethatUsesSuperglobal1.cpp #include "filethatUsesSuperglobal1.h" void go() { printf("%d\n", superGlobal ); } main.cpp #include <stdio.h> #include "externvardef.h" #include "filethatUsesSuperglobal1.h" int main() { printf( "%d\n", superGlobal ) ; go() ; } This is a small point and a somewhat nit picky question, but Why do I need to declare it extern - should not the #include guards on "externvardef.h" avoid redefinition? Its a linker error, even though that header file has #include guards around it. So its not a compiler error, its a linker error, but why.
Think about if from the code perspective - there is this symbol superGlobal that points at an integer. You have a bunch of .o files to link together into a single executable. Each of the .o files has it's own superGlobal symbol. Which should the linker use? The extern declaration says: another of the compilations units (.o files) is going to declare this symbol, so I can use it. Thus there is only one copy so the linker knows what to do.
1,539,333
1,539,443
Using a class in a namespace with the same name?
I have to use an API provided by a DLL with a header like this namespace ALongNameToType { class ALongNameToType { static void Foo(); } } Is there a way to use ALongNameToType::ALongNameToType::Foo without having to type ALongNameToType::ALongNameToType each time? I tried using using namespace ALongNameToType but got ambiguous symbol errors in Visual Studio. Changing the namespace name or removing it gives me linker errors.
I don't know what's ambiguous, but you can avoid all conflicts with other Foo functions like this: namespace ALongNameToType { struct ALongNameToType { static void Foo(); }; } typedef ALongNameToType::ALongNameToType Shortname; int main() { Shortname::Foo(); }
1,539,385
1,539,430
main() in C, C++, Java, C#
Is main() (or Main()) in C, C++, Java or C#, a user-defined function or a built-in function?
It's a user-defined function that is necessary for a program to execute. When you go to run your program in the compiled language, the main function is what is executed. For instance, in Java, if you have a function of the signature public static void main(String ... args) in a class then that class can be executed, as the JVM will execute the contents of that main method. Example in Java: public class Test { public static void main(String ... args) { System.out.println("Hello World"); } } ... javac Test.java ... java Test Results in "Hello World" being printed to the console.
1,539,396
1,539,431
apple's property list (plist) implementation in c++
I'm tasked with reading Apple's property list files within a c++ application. Focusing primarily on the xml-type plist files specified in OS X, which mimic a xml-type implementation.. Apple's implementation of their property list is described here: http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man5/plist.5.html I'm wondering if there are classes or libraries available that already can read this type of implementation within standard c++ (not Objective-C); hoping to find something rather than rolling our own. Are there any open-source implementations of this available?
PList files are not only mimicing XML, they are XML, including valid XML headers. Any XML reader should be able to parse these files as a result. If you're looking for a logical class that abstracts the files, I'm not aware of any existing ones. Given Apple's documentation, you should be able to write one yourself with an XML reader, although it would take some work for full compatibility.
1,539,619
1,540,029
Does #include affect program size?
When my cpp file uses #include to add some header, does my final program's size gets bigger? Header aren't considered as compilation units, but the content of the header file is added to the actual source file by the preprocessor, so will the size of the output file (either exe or dll) be affected by this? Edit: I forgot to mention that the question is not about templates/inline functions. I meant what will happen if I place an #include to a header that doesn't have any implementation detail of functions. Thanks.
You clarified that: [The header has no] templates/inline functions... doesn't have any implementation detail of functions. Generally speaking, no, adding a header file won't affect program size. You could test this. Take a program that already builds, and check the executable size. Then go into each .cpp file and include a standard C or C++ header file that isn't actually needed in that file. Build the program and check the executable size again - it should be the same size as before. By and large, the only things that affect executable size are those that cause the compiler to either generate different amounts of code, global/static variable initializations, or DLLs/shared library usages. And even then, if any such items aren't needed for the program to operate, most modern linkers will toss those things out. So including header files that only contain things like function prototypes, class/struct definitions without inlines, and definitions of enums shouldn't change anything. However, there are certainly exceptions. Here are a few. One is if you have an unsophisticated linker. Then, if you add a header file that generates things the program doesn't actually need, and the linker doesn't toss them out, the executable size will bloat. (Some people deliberately build linkers this way because the link time can become insanely fast.) Many times, adding a header file that adds or changes a preprocessor symbol definition will change what the compiler generates. For instance, assert.h (or cassert) defines the assert() macro. If you include a header file in a .c/.cpp file that changes the definition of the NDEBUG preprocessor symbol, it will change whether assert() usages generate any code, and thus change the executable size. Also, adding a header file that changes compiler options will change the executable size. For instance, many compilers let you change the default "packing" of structs via something like a #pragma pack line. So if you add a header file that changes structure packing in a .c/.cpp file, the compiler will generate different code for dealing with structs, and hence change the executable size. And as someone else pointed out, when you're dealing with Visual C++/Visual Studio, all bets are off. Microsoft has, shall we say, a unique perspective around their development tools which is not shared by people writing compiler systems on other platforms.
1,539,861
1,539,889
what is the good gvim guifont for C/C++ programming
I am trying to find an optimal font for gvim to program in C/C++. I currently have the following in ~/.gvimrc and I don't like it: if has("gui_gtk2") set guifont=MiscFixed\ 11 else set guifont=-misc-fixed-medium-r-normal--10-100-75-75-c-60-iso8859-1 endif set columns=80 lines=50 set guioptions-=T "hide toolbar "Try to load happy hacking teal colour scheme "I copy this to ~/.vim/colors/hhteal.vim silent! colorscheme hhteal if exists("colors_name") == 0 "Otherwise modify the defaults appropriately "background set to dark in .vimrc "So pick appropriate defaults. hi Normal guifg=gray guibg=black hi Visual gui=none guifg=black guibg=yellow "The following removes bold from all highlighting "as this is usually rendered badly for me. Note this "is not done in .vimrc because bold usually makes "the colour brighter on terminals and most terminals "allow one to keep the new colour while turning off "the actual bolding. " Steve Hall wrote this function for me on vim@vim.org " See :help attr-list for possible attrs to pass function! Highlight_remove_attr(attr) " save selection registers new silent! put " get current highlight configuration redir @x silent! highlight redir END
You can use :set guifont=* to bring up a font chooser dialog. Once you've chosen a font use :echo &guifont to see what to put in your .gvimrc. (remember to \-escape spaces) Personally, I like Inconsolata. From my .gvimrc: set guifont=Inconsolata\ 13
1,539,951
1,539,967
How can I create a macro for getting the library name a class is compiled into?
How can I create a macro for getting the library name a class is compiled into? Is there some way of getting this information from make? Essentially I'd like to do something like: # define LIBRARY_NAME (get info from make maybe?) ... # ifdef LIBRARY_NAME static const char* s_lib_name = STRINGIZE(LIBRARY_NAME); Thank you!
g++ allows you to use -DMACRO_NAME=MACRO_VALUE to supply macro values on the command line. Presumably other compilers have similar features. This is equivalent to having #define MACRO_NAME MACRO_VALUE at the top of each file being processed. Leaving out the =MACRO_VALUE part is equivalent to a plain #define MACRO_NAME. So now all you have to do is get make to keep track of the final destination for each file you're compiling (which may or may not be trivial, depends on exactly what you're doing...). You might also look into the # stringization and ## tokenization operators in the c preprocessor. They could save you a little work here...
1,540,182
1,540,244
Using a std::map as an associative array
So, I'm using a std::map as an associative array. The map is declared as such: std::map<int, CustomClass*> CustomContainer; Later on, I use the CustomContainer object as an associative array, e.g., CustomClass* pClass = CustomContainer[ID] Josuttis states: If you use a key as the index, for which no element yet exists, a new element get inserted into the map automatically. The value of the new element is initialized by the default constructor of its type. Thus, to use this feature you can't use a value type that has no default constructor The value of the map is of type CustomClass*. Will the value default to NULL, or is it undefined? (I think that it wouldn't, as "pointer" isn't a fundamental data type). I would think it would also rely somewhat on the constructor and the behavior there as well.... thoughts??? The only constructor of CustomClass looks like this: CustomClass::CustomClass(ClassA param1, ClassB param2, ClassC param3, ClassD param4) :privateClassA(param1), privateClassB(param2), privateClassC(param3), privateClassD(param4) { } Thanks much!
An uninitialized local pointer variable or field will have undefined value, just like uninitialized int (or, in general, POD-type) local variable or field would. However, this has nothing to do with question at hand. When you use operator[] on map, and it creates a new entry, it is default-initialized. This means null pointer value for pointers (and 0 for ints, and so on). It would never be undefined. If you actually need to check if there is an item with such key in the map or not, and do not want new entries, use find() member function, and compare the returned iterator to end().
1,540,515
1,540,525
Why is the output of cout << 7/9*9; is zero?
Why is the output of the following code equals to 0 or serven? cout << 7/9*9; //output 0 (zero) why? float nine = 9; float seven = 7; float i = seven/nine*nine; cout << i //output 7 Why? Thanks for the help.
7/9*9 evaluates those numbers as integers, so 7/9 evaluates to 0, and 0*9 = 0. When you made them floats, you were performing the intended calculation. Try 7.0/9*9 to get 7, and then you'll be doing a floating point operation.
1,540,659
1,540,668
How do dynamically allocated arrays get freed in C++?
I know that you have to do it like this: int * p; p = new int[10]; //use array delete [] p; Now my question is: Since it's not explicitly stated, how is it possible that the correct amount of memory is freed? Do the OS keep track of the allocated memory and its starting address?
The runtime library will keep track of allocated blocks of memory. It's guaranteed to deallocate the block correctly, given the initial pointer returned by new. While this can be implemented in the OS itself (theoretically), it normally isn't. What the OS keeps track of is the pages allocated to a process as a whole, not individual blocks allocated at this level of abstraction.
1,540,729
1,581,173
Undefined symbol _main when trying to build logstalgia on mac
I have been trying to build the logstalgia project (http://code.google.com/p/logstalgia/) on my Mac (10.5). Rather than having to link it to the system libraries correctly, I have built and added all of the dependencies to the project. I am new at this, but I do think I have done this correctly, mostly because I have had two of my friends who are much more experienced say so. Adding the frameworks removed all of the compile errors, but I still get a linker error. It seems to not be able to find the main() function. I have verified I included main.cpp in the sources to be compiled (using XCode) and that there are no accidental double declarations. I have also verified that the main function is correctly declared (no missing brackets, etc). It is as though XCode does not link in the correct order. Any help would be really appreciated, I am really excited to be down to a single error! (Hope fixing this does not open a floodgate). Thanks, Hamilton PS - I can definitely provide a zip of the Xcode project if anyone is willing to look! Checking Dependencies Ld "/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/build/Debug/Untitled" normal i386 cd "/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled" setenv MACOSX_DEPLOYMENT_TARGET 10.5 /developer/usr/bin/g++-4.0 -arch i386 -isysroot /developer/SDKs/MacOSX10.5.sdk "-L/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/build/Debug" -L/sw/lib "-L/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/../../pcre-7.9/.libs" -L/opt/local/lib -L/sw/lib "-F/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/build/Debug" -F/Users/hamiltont/Downloads/logstalgia-0.9.2 -F2/src/SDL.framework "-F/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled" -filelist "/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/build/Untitled.build/Debug/Untitled.build/Objects-normal/i386/Untitled.LinkFileList" -mmacosx-version-min=10.5 -framework OpenGL -lpcre -lSDL -lSDL_image-1.2.0 -prebind -o "/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/build/Debug/Untitled" Undefined symbols: "_main", referenced from: start in crt1.10.5.o ld: symbol(s) not found collect2: ld returned 1 exit status
I got this error to go away. If I understand, essentially SDL re-names the main function, so that it can do some stuff, then run your application, then clean up. Turns out that if you are building in Xcode, you must use ObjectiveC to compile your application. In Xcode, telling the linker to try and use SDL_main(), rather than just main() does not work (for some technical reasons that are a bit beyond me). So, you include a few Objective C files. In Oc, you get the benefit of being able to say explicitely what the name of your main class is. Hence, the Objective C files you include seem to do nothing more than let Xcode know to look for SDL_main(). In summary, this really had nothing to do with Logstalgia, but was entirely a problem with getting SDL to link correctly in Xcode. This link is talking about this problem exactly. The SDLMain.h and SDLMain.m are Objective C files. If you can't find them, try googleing "Setting up SDL templates in Xcode." I installed the templates in Xcode, used one of them to create an empty project that would compile, link, and run (and promptly do nothing!) and then I added the project files I wanted to the pre-configured project. Thanks!
1,540,831
1,545,235
stringstream temporary ostream return problem
I'm creating a logger with the following sections: // #define LOG(x) // for release mode #define LOG(x) log(x) log(const string& str); log(const ostream& str); With the idea to do: LOG("Test"); LOG(string("Testing") + " 123"); stringstream s; LOG(s << "Testing" << 1 << "two" << 3); This all works as intended, but when I do: LOG(stringstream() << "Testing" << 1 << "two" << 3); It does not work: void log(const ostream& os) { std::streambuf* buf = os.rdbuf(); if( buf && typeid(*buf) == typeid(std::stringbuf) ) { const std::string& format = dynamic_cast<std::stringbuf&>(*buf).str(); cout << format << endl; } } results in 'format' containing junk data instead of the usual correct string. I think this is because the temporary ostream returned by the << operator outlives the stringstream it comes from. Or am I wrong? (Why does string() work in this way? Is it because it returns a reference to itself? I'm assuming yes.) I would really like to do it this way as I would be eliminating an additional allocation when logging in release mode. Any pointers or tricks to get it done this way would be welcomed. In my actual solution I have many different log functions and they are all more complex than this. So I would prefer to have this implemented somehow in the calling code. (And not by modifying my #define if possible) Just to give an idea, an example of one of my actual #defines: #define LOG_DEBUG_MSG(format, ...) \ LogMessage(DEBUG_TYPE, const char* filepos, sizeof( __QUOTE__( @__VA_ARGS__ )), \ format, __VA_ARGS__) which matches varargs printf-like log functions taking char*, string() and ostream() as well as non-vararg functions taking string(), exception() and HRESULT.
I think I see what's happening. This produces the expected output: log(std::stringstream() << 1 << "hello"); while this does not: log(std::stringstream() << "hello" << 1); (it writes a hex number, followed by the "1" digit) A few elements for the explanation: An rvalue cannot be bound to a non-const reference It is OK to invoke member functions on a temporary std::ostream has a member operator<<(void*) std::ostream has a member operator<<(int) For char* the operator is not a member, it is operator<<(std::ostream&, const char*) In the code above, std::stringstream() creates a temporary (an rvalue). Its lifetime is not problematic, as it must last for the whole full expression it is declared into (i.e, until the call to log() returns). In the first example, everything works ok because the member operator<<(int) is first called, and then the reference returned can be passed to operator<<(ostream&, const char*) In the second example, operator<<(cannot be called with "std::stringstream()" as a 1st argument, as this would require it to be bound to a non-const reference. However, the member operator<<(void*) is ok, as it is a member. By the way: Why not define the log() function as: void log(const std::ostream& os) { std::cout << os.rdbuf() << std::endl; }
1,540,859
1,540,884
C2664 error in an attempt to do some OpenGl in c++
Here is an abstract of my code. I'm trying to use glutSpecialFunc to tell glut to use my KeyPress function class Car : public WorldObject { public: void KeyPress(int key, int x, int y) { } Car() { glutSpecialFunc(&Car::KeyPress); // C2664 error } } The error message I get is: Error 1 error C2664: 'glutSpecialFunc' : cannot convert parameter 1 from 'void (__thiscall Car::* )(int,int,int)' to 'void (__cdecl *)(int,int,int)' c:\users\thorgeir\desktop\programmingproject1\quickness\quickness\car.cpp 18 Quickness
Your function is a member of a class. When you do something like Car c; c.drive(), that drive() function needs a car to work with. That is the this pointer. So glut can't call that function if it doesn't have a car to work on, it's expecting a free function. You could make your function static, which would mean the function does not operate on a car. glut will then be able to call it, however I assume you want to manipulate a car. The solution is to make the function pass it's call onto an object, like this: void key_press(int key, int x, int y) { activeCar->KeyPress(key, x, y); } Where activeCar is some globally accessible pointer to car. You can do this with some sort of CarManager singleton. CarManager keeps track of the active car being controlled, so when a key is pressed you can pass it on: CarManager::reference().active_car().KeyPress(key, x, y). A singleton is an object that has only one globally accessible instance. It is outside the scope of the answer, but you can Google for various resources on creating one. Look up Meyers Singleton for a simple singleton solution. A different approach is to have a sort of InputManager singleton, and this manager will keep track of a list of objects it should notify of key presses. This can be done in a few ways, the easiest would be something like this: class InputListener; class InputManager { public: // ... void register_listener(InputListener *listener) { _listeners.push_back(listener); } void unregister_listener(InputListener *listener) { _listeners.erase(std::find(_listeners.begin(), _listeners.end(), listener)); } // ... private: // types typedef std::vector<InputListener*> container; // global KeyPress function, you can register this in the constructor // of InputManager, by calling glutSpecialFunc static void KeyPress(int key, int x, int y) { // singleton method to get a reference to the instance reference().handle_key_press(key, x, y); } void handle_key_press(int key, int x, int y) const { for (container::const_iterator iter = _listeners.begin(); iter != _listenders.end(), ++iter) { iter->KeyPress(key, x, y); } } container _listeners; }; class InputListener { public: // creation InputListener(void) { // automatically add to manager InputManager::reference().register_listener(this); } virtual ~InputListener(void) { // unregister InputManager::reference().unregister_listener(this); } // this will be implemented to handle input virtual void KeyPress(int key, int x, int y) = 0; }; class Car : public InputListener { // implement input handler void KeyPress(int key, int x, int y) { // ... } }; Of course feel free to ask more questions if this doesn't make sense.
1,540,960
1,541,370
How to write good Unit Tests?
Could anyone suggest books or materials to learn unit test? Some people consider codes without unit tests as legacy codes. Nowadays, Test Driven Development is the approach for managing big software projects with ease. I like C++ a lot, I learnt it on my own without any formal education. I never looked into Unit Test before, so feel left out. I think Unit Tests are important and would be helpful in the long run. I would appreciate any help on this topic. My main points of concern are: What is a Unit Test? Is it a comprehensive list of test cases which should be analyzed? So lets us a say i have a class called "Complex Numbers" with some methods in it (lets says finding conjugate, an overloaded assignment operator and an overloaded multiplication operator. What should be typical test cases for such a class? Is there any methodology for selecting test cases? Are there any frameworks which can create unit tests for me or i have to write my own class for tests? I see an option of "Test" in Visual Studio 2008, but never got it working. What is the criteria for Units tests? Should there be a unit test for each and every function in a class? Does it make sense to have Unit Tests for each and every class?
An important point (that I didn't realise in the beginning) is that Unit Testing is a testing technique that can be used by itself, without the need to apply the full Test Driven methodology. For example, you have a legacy application that you want to improve by adding unit tests to problem areas, or you want to find bugs in an existing app. Now you write a unit test to expose the problem code and then fix it. These are semi test-driven, but can completely fit in with your current (non-TDD) development process. Two books I've found useful are: Test Driven Development in Microsoft .NET A very hands on look at Test Driven development, following on from Kent Becks' original TDD book. Pragmatic Unit Testing with C# and nUnit It comes straight to the point what unit testing is, and how to apply it. In response to your points: A Unit test, in practical terms is a single method in a class that contains just enough code to test one aspect / behaviour of your application. Therefore you will often have many very simple unit tests, each testing a small part of your application code. In nUnit for example, you create a TestFixture class that contains any number of test methods. The key point is that the tests "test a unit" of your code, ie a smallest (sensible) unit as possible. You don't test the underlying API's you use, just the code you have written. There are frameworks that can take some of the grunt work out of creating test classes, however I don't recommmend them. To create useful unit tests that actually provide a safety net for refactoring, there is no alternative but for a developer to put thought into what and how to test their code. If you start becoming dependent on generating unit tests, it is all too easy to see them as just another task that has to be done. If you find yourself in this situation you're doing it completely wrong. There are no simple rules as to how many unit tests per class, per method etc. You need to look at your application code and make an educated assessment of where the complexity exists and write more tests for these areas. Most people start by testing public methods only because these in turn usually exercise the remainder of the private methods. However this is not always the case and sometimes it is necessary to test private methods. In short, even experienced unit testers start by writing obvious unit tests, then look for more subtle tests that become clearer once they have written the obvious tests. They don't expect to get every test up-front, but instead add them as they come to their mind.
1,541,031
1,541,067
Is it possible for slicing to occur with Smart Pointers?
If I understand slicing correctly I don't think this could happen with pointers or smart pointers. For example, if you had: class A { int something; }; class B : public A { int stuff; int morestuff; }; int main() { std::shared_ptr<B> b(new B()); std::shared_ptr<A> a; a = b; } My understanding is that the block of memory allocated to the object pointed to by "b" is still the same and doesn't change when assigned to the smart pointer "a". Please confirm or reject my understanding, or let me know of any pitfalls associated with this.
A smart pointer is still a pointer, so such an assignment won't cause slicing. Slicing happens only when dealing with values, not pointers. Note, however, templates don't know about the relationships between the items the point at, so even though B derives from A, shared_pointer<B> doesn't derived from shared_pointer<A>, so an assignment doesn't (automatically) get an automatic up-cast like it would with native pointers. Edit: elaborating on final point. Slicing happens with values, not pointers, so (given your definitions of A and B), something like: A ax = b; would work, but would "slice" the B object to become an A object. If, however, you have some sort of template that holds an instance of the item: template <class T> class holder { T t_; public: holder &operator=(T const &t) { t_ = t; return *this; } holder &operator=(holder const &t) { t_ = t; return *this; } }; Now, if we try to assign one value to another, like would cause slicing: holder<A> ha; holder<B> hb; A a; B b; ha = a; hb = b; ha = hb; we will NOT get slicing. Instead, the compiler will simply give us an error, telling us that holder<A> and holder<B> are not related types, so the assignment can't happen -- without adding an explicit cast, it simply won't compile.
1,541,275
1,541,297
C++ stringstream returning extra character?
I've been attempting to use the C++ stringstream class to do some relatively simple string manipulations, but I'm having a problem with the get() method. For some reason whenever I extract the output character by character it appends a second copy of the final letter. #include <iostream> #include <sstream> #include <string> using namespace std; int main() { stringstream ss("hello"); char c; while(!ss.eof()) { ss.get(c); cout << "char: " << c << endl; } return 0; } The output from the program is: char: h char: e char: l char: l char: o char: o Any help you can give me on this would be appreciated.
At the end of the stream ss.eof() doesn't know yet that the end of the stream will be reached soon, but the following extraction of a character fails. Since the extraction failed because the end of the stream was reached, c is not changed. Your program doesn't recognize that ss.get(c) failed and prints that old value of c again. A better way to check if there still is a character that can be read from the stream would be a loop like this: while (ss.get(c)) { cout << "char: " << c << endl; }
1,541,560
1,541,651
STL Priority Queue on custom class
I'm having a lot of trouble getting my priority queue to recognize which parameter it should sort by. I've overloaded the less than operator in my custom class but it doesn't seem to use it. Here's the relevant code: Node.h class Node { public: Node(...); ~Node(); bool operator<(Node &aNode); ... } Node.cpp #include "Node.h" bool Node::operator<(Node &aNode) { return (this->getTotalCost() < aNode.getTotalCost()); } getTotalCost() returns an int main.cpp priority_queue<Node*, vector<Node*>,less<vector<Node*>::value_type> > nodesToCheck; What am I missing and/or doing wrong?
less<vector<Node*>::value_type> Means that your comparator compares the pointers to each other, meaning your vector will be sorted by the layout in memory of the nodes. You want to do something like this: #include <functional> struct DereferenceCompareNode : public std::binary_function<Node*, Node*, bool> { bool operator()(const Node* lhs, const Node* rhs) const { return lhs->getTotalCost() < rhs->getTotalCost(); } }; // later... priority_queue<Node*, vector<Node*>, DereferenceCompareNode> nodesToCheck; Note that you need to be const-correct in your definition of totalCost. EDIT: Now that C++11 is here, you don't need to inherit from std::binary_function anymore (which means you don't need to #include functional)
1,541,676
1,542,120
fread terminating mid-read at null values. Also reading in garbage past expected data
I am reading in pieces of a binary file using a FILE object in C++. Here is the fseek and corresponding fread call: fseek(fp, startLocation, SEEK_SET); fread(data, m_sizeOfData, 1, fp); m_sizeOfData ends up being an integer greater than 400 thousand. This appears that it should read all 400 thousand+ bytes from the binary file into data (which is a char[m_sizeOfData], by the way), however it stops after about 6 or 7 characters at a unicode character that simply looks like a box. I'm thinking it might represent a null termination? I'm not positive on this. This isn't the case with every piece of the file that I am reading in. Most seem to work (generally) correctly. Why might this be and is there a way to correctly read all of the data? Edit: fp is defined as such: FILE* fp; _wfopen_s(&fp, L"C://somedata.dat", L"rb"); This box character, in hex, is 0x06 followed by 0x00. The data is defined by: char *data = new char[m_sizeOfData]; edit 2: I've also noticed that another file is having some garbage loaded onto the end of it. The garbage looks like: ýýýý««««««««îþ Is this because it is trying to complete a certain round number of bytes?
You are using the count/size parameters of fread the wrong way around. Since you are reading bytes, the second parameter should be 1 and the third parameter the count: fread(data, 1, m_sizeOfData, fp); You can then use the return value of fread to determine how many bytes were read. If you are getting the expected count returned, then you can be comfortable that you are reading all the data you wanted. In this case, you are probably outputting the data incorrectly - if you are treating it as a NUL-terminated string, then the 0x00 you are seeing will be the end of what is printed. The 0x06 is probably the box glyph.
1,541,763
1,541,798
Reading in an ascii 'maze' into a 2d array
I'm writing code to read in a 7x15 block of text in a file that will represent a 'maze'. #include <iostream> #include <fstream> #include <string> #include "board.h" int main() { char charBoard[7][15]; //the array we will use to scan the maze and modify it ifstream loadMaze("maze"); //the fstream we will use to take in a maze char temp; //our temperary holder of each char we read in for(int i = 0;i < 7; i++) { for(int j = 0; j < 15; j++) { temp= loadMaze.get(); charBoard[i][j] = temp; cout << charBoard[i][j]; //testing } cout << endl; } return 0; } this was my original draft but this didnt work as it kept returning ? for each char it read. This is the maze im testing with: ############# # ############ # # ######### #### # ! # ############ EDIT: The cout is printing this: ############# # ############ # # ######### #### # ! # ######### Am I not escaping \n's? I've been coding for a few hours so I think its a simple mistake I'm not catching that's tripping me up right now. Thanks!
Try an absolute path like "c:\MyMazes\maze". Throw in a system("cd") to see where the current directory is. If you're having trouble finding the current directory, check out this SO discussion Here's the complete code - this should display your entire maze (if possible) and the current directory. char charBoard[7][15]; //the array we will use to scan the maze and modify it system("cd"); ifstream loadMaze("c:\\MyMazes\\maze"); //the fstream we will use to take in a maze if(!loadMaze.fail()) { for(int i = 0;i < 7; i++) { // Display a new line cout<<endl; for(int j = 0; j < 15; j++) { //Read the maze character loadMaze.get(charBoard[i][j]); cout << charBoard[i][j]; //testing } // Read the newline loadMaze.get(); } return 0; } return 1;
1,541,771
1,541,966
Using Maven for C/C++ projects
I'm putting Maven build around cluster of amateur, poorly written and frankly - primitive C/C++ code (meaning some C, some C++). Problem is - there's lots of it in circulation currently and cannot be easily replaced. Building it requires a lot of tribal knowledge (you have to go from cube to cube just to find out how to compile/build various parts) and releasing is total nightmare. (No - I'm not going to rewrite it, plz don't ask) My question is - should I use maven-native-plugin to replace multitude of short makefiles or use exec-maven-plugin to simply execute these? I had pretty good experience so far with the latter doing .NET and don't know if I should invest into native plugin or stay with exec? If you had experience with "Mavenizing" C/C++ I would love to get some advice.
I highly recommend the maven-nar-plugin. I find it superior in many ways to the alternatives. It doesn't require listing out source files, handles multiple OSes and architectures, handles unit and integration tests, and generally follows "the maven way". It introduces a new kind of packaging - the NAR, or "native archive", that contains the artifact you care about (.dll, .so, .a, .exe, etc.) but also metadata, headers, etc. in a way that makes sense. It does require a bit of up front work to package third-party software up into NARs, but its pretty straightforward. Once they are NARs, you simply use the normal Maven dependency mechanism to link with them, for example: <dependency> <groupId>cppunit</groupId> <artifactId>cppunit</artifactId> <scope>test</scope> </dependency> One drawback is that it does not appear to be actively maintained, but it is full-featured and is a rather impressive example of Maven plugin authoring.
1,541,817
1,541,909
sort function C++ segmentation fault
In this code, for vector size, n >=32767, it gives segmentation fault, but upto 32766, it runs fine. What could be the error? This is full code. #include<cstdio> #include<cstring> #include<cmath> #include<queue> #include<utility> #include<algorithm> #include<sys/time.h> using namespace std; #define MAX 100000 bool compare(pair<int,int> p1,pair<int,int> p2) { if(p1.second < p2.second) return 1; else if(p1.second > p2.second) return 0; if(p1.first <= p2.first) return 1; else return 0; } int main() { freopen("randomin.txt","r",stdin); int n; scanf("%d",&n); vector< pair<int,int> > p(n); for(int i=0;i<n;i++) scanf("%d%d",&p[i].first,&p[i].second); **printf("%d\n",(int)p.max_size()); // prints 536870911** sort(p.begin(),p.begin()+n,compare); //for(int i=0;i<n;i++) //printf("%d %d\n",p[i].first,p[i].second); printf("%.6f\n",(p[n-1].second+p[n-2].second)/(20.0+p[n-1].first+p[n-2].first)); return 0; }
In C++, your compare predicate must be a strict weak ordering. In particular, compare(X,X) must return "false" for any X. In your compare function, if both pairs are identical, you hit the test (p1.first <= p2.first) , and return true. Therefore, this compare predicate does not impose a strict weak ordering, and the result of passing it to sort is undefined.
1,541,901
1,541,934
WinAPI function to start help file
when you open help in e.g. Windows Notepad (Help->Help Topics) no child process is started (such as hh.exe), which IMO means there is a WinAPI function called to do the job. I searched MSDN for a while but came up with nothing. what is this function?
Would this help? How can I open a help file (chm or so) from my GUI developed in VC++ 2008? There are several useful solutions in that discussion.
1,542,001
1,542,474
C code - need to clarify the effectiveness
Hi I have written a code based upon a requirement. (field1_6)(field2_30)(field3_16)(field4_16)(field5_1)(field6_6)(field7_2)(field8_1)..... this is one bucket(8 fields) of data. we will receive 20 buckets at a time means totally 160 fields. i need to take the values of field3,field7 & fields8 based upon predefined condition. if teh input argument is N then take the three fields from 1st bucket and if it is Y i need to take the three fields from any other bucket other than 1st one. if argumnet is Y then i need to scan all the 20 buckets one after other and check the first field of the bucket is not equal to 0 and if it is true then fetch the three fields of that bucket and exit. i have written the code and its also working fine ..but not so confident that it is effctive. i am afraid of a crash some time.please suggest below is the code. int CMI9_auxc_parse_balance_info(char *i_balance_info,char *i_use_balance_ind,char *o_balance,char *o_balance_change,char *o_balance_sign ) { char *pch = NULL; char *balance_id[MAX_BUCKETS] = {NULL}; char balance_info[BALANCE_INFO_FIELD_MAX_LENTH] = {0}; char *str[160] = {NULL}; int i=0,j=0,b_id=0,b_ind=0,bc_ind=0,bs_ind=0,rc; int total_bukets ; memset(balance_info,' ',BALANCE_INFO_FIELD_MAX_LENTH); memcpy(balance_info,i_balance_info,BALANCE_INFO_FIELD_MAX_LENTH); //balance_info[BALANCE_INFO_FIELD_MAX_LENTH]='\0'; pch = strtok (balance_info,"*"); while (pch != NULL && i < 160) { str[i]=(char*)malloc(strlen(pch) + 1); strcpy(str[i],pch); pch = strtok (NULL, "*"); i++; } total_bukets = i/8 ; for (j=0;str[b_id]!=NULL,j<total_bukets;j++) { balance_id[j]=str[b_id]; b_id=b_id+8; } if (!memcmp(i_use_balance_ind,"Y",1)) { if (atoi(balance_id[0])==1) { memcpy(o_balance,str[2],16); memcpy(o_balance_change,str[3],16); memcpy(o_balance_sign,str[7],1); for(i=0;i<160;i++) free(str[i]); return 1; } else { for(i=0;i<160;i++) free(str[i]); return 0; } } else if (!memcmp(i_use_balance_ind,"N",1)) { for (j=1;balance_id[j]!=NULL,j<MAX_BUCKETS;j++) { b_ind=(j*8)+2; bc_ind=(j*8)+3; bs_ind=(j*8)+7; if (atoi(balance_id[j])!=1 && atoi( str[bc_ind] )!=0) { memcpy(o_balance,str[b_ind],16); memcpy(o_balance_change,str[bc_ind],16); memcpy(o_balance_sign,str[bs_ind],1); for(i=0;i<160;i++) free(str[i]); return 1; } } for(i=0;i<160;i++) free(str[i]); return 0; } for(i=0;i<160;i++) free(str[i]); return 0; }
I had a hard time reading your code but FWIW I've added some comments, HTH: // do shorter functions, long functions are harder to follow and make errors harder to spot // document all your variables, at the very least your function parameters // also what the function is suppose to do and what it expects as input int CMI9_auxc_parse_balance_info ( char *i_balance_info, char *i_use_balance_ind, char *o_balance, char *o_balance_change, char *o_balance_sign ) { char *balance_id[MAX_BUCKETS] = {NULL}; char balance_info[BALANCE_INFO_FIELD_MAX_LENTH] = {0}; char *str[160] = {NULL}; int i=0,j=0,b_id=0,b_ind=0,bc_ind=0,bs_ind=0,rc; int total_bukets=0; // good practice to initialize all variables // // check for null pointers in your arguments, and do sanity checks for any // calculations // also move variable declarations to just before they are needed // memset(balance_info,' ',BALANCE_INFO_FIELD_MAX_LENTH); memcpy(balance_info,i_balance_info,BALANCE_INFO_FIELD_MAX_LENTH); //balance_info[BALANCE_INFO_FIELD_MAX_LENTH]='\0'; // should be BALANCE_INFO_FIELD_MAX_LENTH-1 char *pch = strtok (balance_info,"*"); // this will potentially crash since no ending \0 while (pch != NULL && i < 160) { str[i]=(char*)malloc(strlen(pch) + 1); strcpy(str[i],pch); pch = strtok (NULL, "*"); i++; } total_bukets = i/8 ; // you have declared char*str[160] check if enough b_id < 160 // asserts are helpful if nothing else assert( b_id < 160 ); for (j=0;str[b_id]!=NULL,j<total_bukets;j++) { balance_id[j]=str[b_id]; b_id=b_id+8; } // don't use memcmp, if ('y'==i_use_balance_ind[0]) is better if (!memcmp(i_use_balance_ind,"Y",1)) { // atoi needs balance_id str to end with \0 has it? if (atoi(balance_id[0])==1) { // length assumptions and memcpy when its only one byte memcpy(o_balance,str[2],16); memcpy(o_balance_change,str[3],16); memcpy(o_balance_sign,str[7],1); for(i=0;i<160;i++) free(str[i]); return 1; } else { for(i=0;i<160;i++) free(str[i]); return 0; } } // if ('N'==i_use_balance_ind[0]) else if (!memcmp(i_use_balance_ind,"N",1)) { // here I get a headache, this looks just at first glance risky. for (j=1;balance_id[j]!=NULL,j<MAX_BUCKETS;j++) { b_ind=(j*8)+2; bc_ind=(j*8)+3; bs_ind=(j*8)+7; if (atoi(balance_id[j])!=1 && atoi( str[bc_ind] )!=0) { // length assumptions and memcpy when its only one byte // here u assume strlen(str[b_ind])>15 including \0 memcpy(o_balance,str[b_ind],16); // here u assume strlen(str[bc_ind])>15 including \0 memcpy(o_balance_change,str[bc_ind],16); // here, besides length assumption you could use a simple assignment // since its one byte memcpy(o_balance_sign,str[bs_ind],1); // a common practice is to set pointers that are freed to NULL. // maybe not necessary here since u return for(i=0;i<160;i++) free(str[i]); return 1; } } // suggestion do one function that frees your pointers to avoid dupl for(i=0;i<160;i++) free(str[i]); return 0; } for(i=0;i<160;i++) free(str[i]); return 0; } A helpful technique when you want to access offsets in an array is to create a struct that maps the memory layout. Then you cast your pointer to a pointer of the struct and use the struct members to extract information instead of your various memcpy's I would also suggest you reconsider your parameters to the function in general, if you place every of them in a struct you have better control and makes the function more readable e.g. int foo( input* inbalance, output* outbalance ) (or whatever it is you are trying to do)
1,542,084
1,543,484
What's the most commonly used XML library for C++?
I saw a few libraries through a quick Google search. What's generally the most commonly used XML implementation for C++? I'm planning on using XML as a means for program configuration. I liked XML because I'll be making use of its tree-like structure. If you think you have a more suitable solution for this, feel free to mention it. I want something lightweight and simple. Maybe XML is too much? Edit: Cross-platform would be preferable, but to answer a question, I'm programming this in Linux.
I would recommend not using XML. I know this is a matter of opinion but XML really clutters the information with a lot of tags. Also, even though it is human-readable, the clutter actually hampers readability (and I say it from experience since we have some 134 XML configuration files at the moment...). Furthermore, it is quite difficult to read because of the mix between attributes and plain-text. You never know which one you are going to need. I would recommend using JSON, if you want a language that already has well-defined parsers. For parsing, a simple look at json.org and you have a long list of C++ libraries.
1,542,108
1,542,206
How to hack the virtual table?
I would like to know how to change the address of Test which is in the virtual table with that of HackedVTable. void HackedVtable() { cout << "Hacked V-Table" << endl; } class Base { public: virtual Test() { cout <<"base"; } virtual Test1() { cout << "Test 1"; } void *prt; Base(){} }; class Derived : public Base { public: Test() { cout <<"derived"; } }; int main() { Base b1; b1.Test(); // how to change this so that `HackedVtable` should be called instead of `Test`? return 0; }
This works for 32-bit MSVC builds (it's a very simplified version of some production code that's been in use for well over a year). Note that your replacement method must explicitly specify the this parameter (pointer). // you can get the VTable location either by dereferencing the // first pointer in the object or by analyzing the compiled binary. unsigned long VTableLocation = 0U; // then you have to figure out which slot the function is in. this is easy // since they're in the same order as they are declared in the class definition. // just make sure to update the index if 1) the function declarations are // re-ordered and/or 2) virtual methods are added/removed from any base type. unsigned VTableOffset = 0U; typedef void (__thiscall Base::*FunctionType)(const Base*); FunctionType* vtable = reinterpret_cast<FunctionType*>(VTableLocation); bool hooked = false; HANDLE process = ::GetCurrentProcess(); DWORD protection = PAGE_READWRITE; DWORD oldProtection; if ( ::VirtualProtectEx( process, &vtable[VTableOffset], sizeof(int), protection, &oldProtection ) ) { vtable[VTableOffset] = static_cast<FunctionType>(&ReplacementMethod); if ( ::VirtualProtectEx( process, &vtable[VTableOffset], sizeof(int), oldProtection, &oldProtection ) ) hooked = true; }
1,542,200
1,542,272
Is using const_cast for read-only access to a const object allowed?
In C++ I have a function that only requires read-only access to an array but is mistakenly declared as receiving a non-const pointer: size_t countZeroes( int* array, size_t count ) { size_t result = 0; for( size_t i = 0; i < count; i++ ) { if( array[i] == 0 ) { ++result; } } return result; } and I need to call it for a const array: static const int Array[] = { 10, 20, 0, 2}; countZeroes( const_cast<int*>( Array ), sizeof( Array ) / sizeof( Array[0] ) ); will this be undefined behaviour? If so - when will the program run into UB - when doing the const_cast and calling the functon or when accessing the array?
Yes, it is allowed (if dangerous!). It's the actual write to a const object that incurs undefined behaviour, not the cast itself (7.1.5.1/4 [dcl.type.cv]). As the standard notes in 5.2.11/7 [expr.const.cast], depending on the type of the object an attempt to write through a pointer that is the result of casting away const may produce undefined behaviour.
1,542,220
1,542,347
ASCII "graphics" library?
Is there a platform-independent C/C++ library that can draw simple "graphics" in pure ASCII in a console program? For example (VERY roughly) I could call a function in the library like rectangle(3, 6); to get the following output: ****** * * ****** Ultimately, I would love to be able to plot simple graphs based on input data tables like: | |* | | * | * | * | * | * +--------------------------------- And does anyone know if there is a way to specifically render data plots/graphs in ASCII or UTF8?
From what you have said, you don't need ASCII graphics library as they purpose is to render bitmap into ASCII characters so the look of ASCII data will become 'similar' to the bitmap. For the task you have mentioned consider writing your own library, because: Your task is not really bitmap rendering It is not so complicated If you really want to use ASCII art lib, you may choose a library for graph bitmap rendering and then pass that generated bitmap data to ASCII lib so you will get the output.
1,542,339
1,542,413
C++ non null terminated char array outputting
I was trying to output a not null terminated char array to a file. Actual thing is, I am receiving packets and then printing their fields. Now as these fields are not null terminated, for example, a data segment which has size of 512 but may or may not be completely occupied. When I write this data to a file I am using simple << overloaded function which does not know any thing about actual data and only looks for termination of data segment. So, how can I tell the output function to write only this much specific number of bytes? Instead of using something like this which is expensive to call each time: enter code here bytescopied = strncpy(dest, src, maxbytes); if (bytescopied < 0) { // indicates no bytes copied, parameter error throw(fit); // error handler stuff here } else if (bytescopied == maxbytes) { dest[maxbytes-1] = '\0'; // force null terminator }
If you want to put exactly maxbytes bytes, use write method stream.write(buffer, maxbytes); If you can have less bytes in buffer, how do you know how many of them your buffer contains? If '\0' marks buffer end, you can write: stream.write(buffer, std::find(buffer, buffer+maxbytes, '\0') - buffer);
1,542,361
1,542,458
Why do we need an inserter function call when doing a set_union for a set?
i need to make the call to the set_union function of STL like this: set<int> a1, a2; set_union(a1.begin(), a1.end(), a2.begin(), a2.end(), inserter(a1, a1.begin()); and not set_union(a1.begin(), a1.end(), a2.begin(), a2.end(), a1.begin()); why is that so?
a1.begin() is simply not an output iterator. inserter(a1,a1.begin()) returns an output iterator which will invoke the set's insert function for each element. But I'm not even sure whether the first version is even correct. You iterate over the same set you insert new elements into. (!) Since you deal with set<> objects already, why don't you simply write a1.insert(a2.begin(),a2.end()); ?
1,542,623
1,542,643
Syntax error missing ; before *
I have a header file like so: #pragma once #include "gamestate.h" #include "ExitListener.h" class InitialGameState : public GameState { public: InitialGameState(Ogre::Camera *cam, Ogre::SceneManager *sceneMgr, OIS::Keyboard *keyboard, OIS::Mouse *mouse, Ogre::Root *root); ~InitialGameState(void); virtual bool update(Ogre::Real time); virtual void pause(void); virtual void start(void); void keyPressed(const OIS::KeyEvent &e); void keyReleased(const OIS::KeyEvent &e); //private: ExitListener *mFrameListener; }; The problem with this is that I get the following errors from VC 8: InitialGameState.h(16) : error C2143: syntax error : missing ';' before '*' InitialGameState.h(16) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int InitialGameState.h(16) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int (they all refer to the last line) I have a class ExitListener.h which is why I don't get the errors Edit: ExitListener.h: #pragma once #include <Ogre.h> #include <OIS/OIS.h> #include <CEGUI/CEGUI.h> #include <OgreCEGUIRenderer.h> #include "Thing.h" #include "InitialGameState.h" using namespace Ogre; class ExitListener : public FrameListener, public OIS::KeyListener, public OIS::MouseListener { public: ExitListener(OIS::Keyboard *keyboard, OIS::Mouse *mouse, Camera *cam, std::vector<Thing*> &vec): mKeyboard(keyboard), r(0.09), mContinue(true), mRunningAnimation(false), mMouse(mouse), mYaw(0), mPitch(0), things(vec), mCamera(cam), mWDown(false), mSDown(false), mADown(false), mDDown(false) { things = vec; mKeyboard->setEventCallback(this); mMouse->setEventCallback(this); } bool frameStarted(const FrameEvent& evt); bool keyPressed(const OIS::KeyEvent &e); bool keyReleased(const OIS::KeyEvent &e); bool mouseMoved(const OIS::MouseEvent &e); bool mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id); bool mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id); void setOwner(GameState *g); private: AnimationState *mSwim; Radian r; Radian mYaw; Radian mPitch; OIS::Keyboard *mKeyboard; OIS::Mouse *mMouse; Camera *mCamera; bool mContinue; bool mRunningAnimation; std::vector<Thing*> &things; bool mWDown; bool mADown; bool mDDown; bool mSDown; GameState *mOwner; }; Edit 2: It turned out that the problem could be solved by a forward declaration and then including the other header directly in my .cpp file. Thanks.
My guess is that ExitListener.h is including InitialGameState.h header file either directly or indirectly. So there is a circular dependency between the header file and compiler is unable to find the declaration for ExitListener. If you just need to store the pointer of ExitListener in this class then there is no need to include the ExitListener.h header file. Instead you can just use the forward declaration as class ExitListener; EDIT: You can use the forward declaration as suggested above, or remove the InitialGameState.h include from ExitListener.h . You need to include GameState.h (the base class header file) only. But I prefer to use the forward declarations in header file and include the header file only in cpp.
1,542,675
1,564,841
Access to external window handles
I am having a problem with the program I am currently working on. It is caused by the increased security in vista/Windows 7, specifically the UIPI which prevents a window with a lower integrity level 'talking' to a higher one. In my case, i am wanting to tell the window with a high Integrity level to move into our application, It works flawlessly on XP or windows 7 with the security off. I have tried setting the HWND of the higher IL window directly, rather than using the findwindow() function, this works fine but the program then fails when trying to move it or generally interact with it. The windowhandle is saved by the app to be embedded and read by the app running at a lower IL. I have also tried setting UIaccess in the manifest to TRUE and digitally signing the program but no luck. Any ideas on how to solve this problem? thanks.
Just thought i would follow this up for anyone who also struggled as I have finally found a way to do this. IL = Integrity Level. I had 2 apps, highIL.exe and lowIL.exe, the highIL wanted to find the lowIL.exe window, set it as a child window and move it into a zone created for it on the highIL.exe. This was blocked by the UIPI in vista+. In the end i used the ChangeWindowMessageFilter method in vista and the ChangeWindowMessageFilterEx in Windows7, both found in the user32.dll. These functions allow you to poke a hole in the UIPI to allow messages that you want through. I created a few custom messages using RegisterWindowMessage function, I used this function to register the method in both highIL and lowIL applications, the line looked a little like this: const UINT MY_MOVEINTWINDOW_MSG = RegisterWindowMessage(_T("MyMsg.MoveWindow")); The lowIL.exe is then able to send these messages to the highIL.exe window without them being blocked. Then it was a case of just simply adding and writing message handlers. This method will only work if you have access to both the high and low IL. The MSDN also has a working example of the ChangeWindowMessageFilterEx function on there Website
1,542,774
1,542,974
C++ reference to a shared_ptr vs reference
All, I recently posted this question on DAL design. From that it would seem that passing a reference to an object into a function, with the function then populating that object, would be a good interface for a C++ Data Access Layer, e.g. bool DAL::loadCar(int id, Car& car) {} I'm now wondering if using a reference to a boost::shared_ptr would be better, e.g. bool DAL::loadCar(int id, boost::shared_ptr<Car> &car) Any thoughts? Does one offer advantages over the other? What would be the implications of applying const correctness to both calls? Thanks in advance.
As sbi says, "It depends on what the function does. " However, I think the most important aspect of the above is not whether NULL is allowed or not, but whether the function stores a pointer to the object for later use. If the function just fills in some data then I would use reference for the following reasons: the function can still be used by clients who do not use shared_ptr, used for stack objects, etc. using the function with shared_ptr is still trivial - shared_ptr has dereferencing operator that returns a reference passing NULL is not possible less typing I don't like using "stuff" when I don't have to If the function needs to store pointer for later use or you anticipate the function might change in such a way that will require storing a pointer, then use shared_ptr.
1,542,799
1,542,901
Logging facilities and Qt
What logging facilities do you use whit Qt ? Do you choose qDebug(), qWarning(), qCritical(), qFatal() methods, or maybe something like Log4cpp (Log4cplus etc.), or maybe some custom-maked code ?
Existing C++ logging libraries are too heavy for my tastes, so I have created a custom front-end based on ideas from Logging in C++ for the Qt qInstallMsgHandlerq back-end. It's cross-platform and thread-safe. Someday I'll clean up the code and release it to the world :) An interesting alternative for Qt is QxtLogger.
1,542,892
1,542,900
Two ways of calling default constructor
I have the following code: struct B { //B() {} int x; int y; }; void print(const B &b) { std::cout<<"x:"<<b.x<<std::endl; std::cout<<"y:"<<b.y<<std::endl; std::cout<<"--------"<<std::endl; } int main() { B b1 = B(); //init1 B b2; //init2 print(b1); print(b2); return 0; } When I start program (vs2008, debug) I have the following output: x:0 y:0 -------- x:-858993460 y:-858993460 -------- As you can see b1.x and b1.y have 0 value. why? What's difference between init1 and init2? When I uncomment B constructor I have the following output: x:-858993460 y:-858993460 -------- x:-858993460 y:-858993460 -------- Can somebody explain the reason of this behaviour? Tnx in advance.
Default constructor for POD types fills it with zeros. When you explicitly define your own constructor you are not initialize x and y and you'll get random values (in VS debug they are filled with exact values, but in release they will be random). It is according to C++03 Standard 8.5/5: <...>To value-initialize an object of type T means: — if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); — if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized; — if T is an array type, then each element is value-initialized; — otherwise, the object is zero-initialized. B() is a value-initialization of temporary which will be used in copy-initialization of b1. In B b2 there is no initializer specified for an object, so according to C++03 Standard 8.5/9: If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor. Otherwise, if no initializer is specified for a non-static object, the object and its subobjects, if any, have an indeterminate initial value; if the object or any of its subobjects are of const-qualified type, the program is ill-formed. To get zeros for b2 you could write B b2 = {};.
1,542,960
1,543,716
A Better Boost reference?
The thing that really turns me off about Boost is their documentation. What I need is a good reference, and instead of explaining what a good reference is to me I would give example: java.sun.com/javase/6/docs/api/ Yes I love it. It is also this: cppreference.com/wiki/stl/vector/start On the other hand what I find about boost is something like this: http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/shared_ptr.htm Basically some long page of text. Almost no formatting, some bold text here and there and hopefully some links between elements. Not to mention that smart_ptr is one of the better documented libraries. If you do not find the difference between this and the above examples please stop reading and ignore this post. Do not get me wrong, I write C++ and I use Boost. At my firm we use at least 4 of their libraries, still each and every time I need to check a method prototype for instance it gets me out of my nerves scrolling through their essays. And yes I know that Boost is a collaborative project and that different libraries are developed by different teams. So does any of you share my disappointment with Boost's reference and do you know some better site documenting the Boost libraries?
In general, I don't find the documentation is that bad. In general again, the information is "somewhere" in there. The main problem I see is a lack of uniformity, making it difficult to find that "somewhere". As you write in your question, the docs were written by different people, and a different times, and that's probably the cause for this lack of a common structure. From the java and cppreference links you cite in example, I infer that you are more interested in the synopsis of the interface than in "tutorial" or "motivation" stuff. For shared_ptr, does http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/shared_ptr.htm#Synopsis provide what you're after? For some libs, the "test" and "example" directories under libs/<library_name> are useful. You may post your questions, comments and suggestions on the boost users and/or documentation mailing lists. From what I see there, specific documentation improvement suggestions are normally welcomed by the library maintainers.
1,543,098
1,543,121
I need a C++ Compiler
If possible I want one that's free, popular (so support on forums will be faster) and.... just good. I don't really know much about compilers so I don't know what exactly is good.
Please note that I have taken the below stuff from Link :http://cplus.about.com/od/glossary/a/compilers.htm I have coped relevant things here for more detail you can visit link directly Microsoft Visual C++ 2008 Express. Linkfrm. Turbo Explorer for C++. GCC (GNU Compiler Collection) Digital Mars C/C++ Compiler
1,543,156
1,543,482
time table / datebook as in Sunbird for Qt?
I would like to implement a calendar in my Qt-based program as it is already implement in Mozilla Sunbird (different colors and categories are important). Is there any "simple" possibility to realize that or do I have to create it all by myself, beginning at zero? Is there a good tutorial to create such a calendar with standards, so that I could import it in Mozilla Sunbird for example?
Take a look at what KOrganizer implements. You would probably have to strip some KDE-specific functionality though.
1,543,157
1,545,961
How can I find out how much memory my c++ app is using on the Mac
Certain operations in my app are using more memory than I think they should, and I would like to log the current memory usage to help identify which they are. Is there a system call that will return the amount of memory currently in use?
The following C function returns the CPU time and resident memory of process pid. To get the resources of other processes, you need root permission. You may also try getrusage(), but I never get it work properly for memory usage. Getting CPU time with getrusage() always works to me. The function is adapted from the source codes of the ps and top commands. It is part of my program that monitors the memory of other processes. #ifdef __APPLE__ #include <sys/types.h> #include <sys/sysctl.h> #include <sys/vmmeter.h> #include <mach/mach_init.h> #include <mach/mach_host.h> #include <mach/mach_port.h> #include <mach/mach_traps.h> #include <mach/task_info.h> #include <mach/thread_info.h> #include <mach/thread_act.h> #include <mach/vm_region.h> #include <mach/vm_map.h> #include <mach/task.h> #include <mach/shared_memory_server.h> typedef struct vmtotal vmtotal_t; typedef struct { /* dynamic process information */ size_t rss, vsize; double utime, stime; } RunProcDyn; /* On Mac OS X, the only way to get enough information is to become root. Pretty frustrating!*/ int run_get_dynamic_proc_info(pid_t pid, RunProcDyn *rpd) { task_t task; kern_return_t error; mach_msg_type_number_t count; thread_array_t thread_table; thread_basic_info_t thi; thread_basic_info_data_t thi_data; unsigned table_size; struct task_basic_info ti; error = task_for_pid(mach_task_self(), pid, &task); if (error != KERN_SUCCESS) { /* fprintf(stderr, "++ Probably you have to set suid or become root.\n"); */ rpd->rss = rpd->vsize = 0; rpd->utime = rpd->stime = 0; return 0; } count = TASK_BASIC_INFO_COUNT; error = task_info(task, TASK_BASIC_INFO, (task_info_t)&ti, &count); assert(error == KERN_SUCCESS); { /* adapted from ps/tasks.c */ vm_region_basic_info_data_64_t b_info; vm_address_t address = GLOBAL_SHARED_TEXT_SEGMENT; vm_size_t size; mach_port_t object_name; count = VM_REGION_BASIC_INFO_COUNT_64; error = vm_region_64(task, &address, &size, VM_REGION_BASIC_INFO, (vm_region_info_t)&b_info, &count, &object_name); if (error == KERN_SUCCESS) { if (b_info.reserved && size == (SHARED_TEXT_REGION_SIZE) && ti.virtual_size > (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE)) { ti.virtual_size -= (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE); } } rpd->rss = ti.resident_size; rpd->vsize = ti.virtual_size; } { /* calculate CPU times, adapted from top/libtop.c */ unsigned i; rpd->utime = ti.user_time.seconds + ti.user_time.microseconds * 1e-6; rpd->stime = ti.system_time.seconds + ti.system_time.microseconds * 1e-6; error = task_threads(task, &thread_table, &table_size); assert(error == KERN_SUCCESS); thi = &thi_data; for (i = 0; i != table_size; ++i) { count = THREAD_BASIC_INFO_COUNT; error = thread_info(thread_table[i], THREAD_BASIC_INFO, (thread_info_t)thi, &count); assert(error == KERN_SUCCESS); if ((thi->flags & TH_FLAGS_IDLE) == 0) { rpd->utime += thi->user_time.seconds + thi->user_time.microseconds * 1e-6; rpd->stime += thi->system_time.seconds + thi->system_time.microseconds * 1e-6; } if (task != mach_task_self()) { error = mach_port_deallocate(mach_task_self(), thread_table[i]); assert(error == KERN_SUCCESS); } } error = vm_deallocate(mach_task_self(), (vm_offset_t)thread_table, table_size * sizeof(thread_array_t)); assert(error == KERN_SUCCESS); } mach_port_deallocate(mach_task_self(), task); return 0; } #endif /* __APPLE__ */
1,543,193
1,543,221
Why Can't I store references in a `std::map` in C++?
I understand that references are not pointers, but an alias to an object. However, I still don't understand what exactly this means to me as a programmer, i.e. what are references under the hood? I think the best way to understand this would be to understand why it is I can't store a reference in a map. I know I need to stop thinking of references as syntactic suger over pointers, just not sure how to :/
They way I understand it, references are implemented as pointers under the hood. The reason why you can't store them in a map is purely semantic; you have to initialize a reference when it's created and you can't change it afterward anymore. This doesn't mesh with the way a map works.
1,543,305
1,543,429
Swap 2D Double Arrays in c++
I have the following method to swap two double arrays (double**) in c++. Profiling the code, the method is accounting for 7% of the runtime... I was thinking that this should be a low cost operation, any suggestions? I am new with c++, but i was hoping to just swap the references to the arrays. 62 void Solver::Swap(double** &v1, double** &v2) 63 { 64 double** vswap = NULL; 65 vswap = v2; 66 v2 = v1; 67 v1 = vswap; 68 }
1) Make sure your function is inlined. 2) You can inplace swap, using a XOR for instance 3) Try to force the compiler to pass arguments using register instead of the stack (even though there's lot of register stress on x86, it's worth trying) - you can use the standard register keyword or play with fastcall on MS' compiler. typedef double** TwoDimArray; class Solver { inline void Swap( register TwoDimArray& a, register TwoDimArray& b ) { a ^= b ^= a ^= b; } }; 4) Don't bother giving default values for temporaries like vswap.
1,543,736
1,545,079
How do I temporarily disable a macro expansion in C/C++?
For some reason I need to temporarily disable some macros in a header file and the #undef MACRONAME will make the code compile but it will undef the existing macro. Is there a way of just disabling it? I should mention that you do not really know the values of the macros and that I'm looking for a cross compiler solution (should work at least in GCC and MSVC).
In MSVC you could use push_macro pragma, GCC supports it for compatibility with Microsoft Windows compilers. #pragma push_macro("MACRONAME") #undef MACRONAME // some actions #pragma pop_macro("MACRONAME")
1,543,761
1,544,432
pointers and references question
#ifndef DELETE #define DELETE(var) delete var, var = NULL #endif using namespace std; class Teste { private: Teste *_Z; public: Teste(){ AnyNum = 5; _Z = NULL; } ~Teste(){ if (_Z != NULL) DELETE(_Z); } Teste *Z(){ _Z = new Teste; return _Z; } void Z(Teste *value){ value->AnyNum = 100; *_Z = *value; } int AnyNum; }; int main(int argc, char *argv[]){ Teste *b = new Teste, *a; a = b->Z(); cout << "a->AnyNum: " << a->AnyNum << "\n"; b->Z(new Teste); cout << "a->AnyNum: " << a->AnyNum << "\n"; //wdDELETE(a); DELETE(b); return 0; } I would like to know if there is a memory leak in this code it works ok, the *a is set twice and the AnyNum prints different numbers on each cout << but I wonder what happened to the _Z after the setter(new Teste), I don't have much knowledge in pointers/references yet, but for the logic I guess it is being swapped for the new variable if it is leaking, is there anyway to accomplish this without having to set a to _Z again? because the address didn't change, just the direct memory allocated I was going to use *& instead of just pointers, but would it make difference?
There is a memory leak on this line: b->Z(new Teste); because of the definition of the function: void Z(Teste *value){ value->AnyNum = 100; *_Z = *value; } It looks like Z without arguments was supposed to be a getter and with arguments a setter. I suspect you meant to do: void Z(Teste *value){ value->AnyNum = 100; _Z = value; } (note the third line) That is, assign the pointer "value" to the pointer "_Z" instead of copy what value pointed at over what Z pointed at. With that, the first memory leak would be resolved, but the code would still have one since _Z could have been holding a pointer. So you'd have to do: void Z(Teste *value){ value->AnyNum = 100; delete _Z; // you don't have to check for null _Z = value; } As mentioned in another comment, the real solution is to use smart pointers. Here's a more modern approach to the same code: using namespace std; class Teste { private: boost::shared_ptr<Teste> Z_; public: Teste() : AnyNum(5), Z_(NULL) { } boost::shared_ptr<Teste> Z() { Z_.reset(new Teste); return Z_; } void Z(boost::shared_ptr<Teste> value) { value->AnyNum = 100; Z_ = value; } int AnyNum; }; int main(int argc, char *argv[]){ boost::shared_ptr<Teste> b = new Teste, a; a = b->Z(); cout << "a->AnyNum: " << a->AnyNum << "\n"; b->Z(boost::shared_ptr<Teste>(new Teste)); cout << "a->AnyNum: " << a->AnyNum << "\n"; return 0; }
1,543,790
1,543,834
simple c++, opengl game engine for linux?
I was wondering if anyone knew of a simple opengl game engine for linux where the source is available to read. I basically want to read the source to get a better idea of how things are put together without worrying about the code being cross platform or having fancy particle effects or anything.
You may be interested in Irrlicht
1,543,830
1,543,915
send the enter button input through pipe
how to send return(enter button) character through program in windows c/c++? I want to send an external program "user name" with enter button through pipe but "\n" and "\r" and EOF are not working. consider if pPipe is the pipe stream for sending the data to the remote process stdin... fprintf(pPipe,"username\n");
You can use escape sequences.
1,544,225
1,544,259
static method with polymorphism in c++
I have a weird issue using polymorphism. I have a base class that implements a static method. This method must be static for various reasons. The base class also has a pure virtual method run() that gets implemented by all the extended classes. I need to be able to call run() from the static class. The problem, of course, is that the static class doesn't have a this pointer. This method can be passed in a void * parameter. I have been trying to come up with a clever way to pass the run method into it, but nothing has worked so far. have also tried passing this into it. The problem with this is that I would then have to instantiate it, which requires knowledge of the extended class. This defeats the whole purpose of the polymorphism. Any ideas on how to go about this?
Don't pass it as a void* pointer, pass it as a pointer (or reference) to the base class: class BaseClass { public: static void something(BaseClass* self) { self->foo(); } virtual void foo() = 0; };
1,544,274
1,544,287
Class dependency tool
I'm looking for a (preferably open source) tool that, given a large body of C/C++ code, will generate a visual or maybe XML graph of dependencies between classes (C++) and/or files (C). The idea would be that, if you had to convert the code to another language, you'd like to be able to get the lowest level classes compiling first, and build up from there. So, you'd first need to identify which classes those are. As far as I can tell, Doxygen doesn't have quite this capability, but I could be wrong.
Doxygen will do some pretty neat graphs.
1,544,351
1,553,534
Handling a SAFEARRAY returned from C# server
I need to return an array of structure (classes) from a C# library to an unmanaged C++ client. This is the function in the C# library: [ComVisible(true)] [Serializable] public sealed class RetrieverProxy : IRetrieverProxy { public IMyRecord[] RetrieveMyRecords(long[] ids) { IList<IMyRecord> result = new List<IMyRecord>(); for (int i = 0; i < ids.Count(); i++) { result.Add(new MyRecord() { // some test data }); } return result.ToArray(); } } MyRecord itself contains an array of structures, which are also COM visible and contain a double and a DateTime field. I get the follow wrapper from regasm: inline SAFEARRAY * IRetrieverProxy::RetrieveMyRecords (SAFEARRAY * ids) { SAFEARRAY * _result = 0; HRESULT _hr = raw_RetrieveMyRecords(ids, &_result); if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this)); return _result; } From the client code, I invoke the library like the following: SAFEARRAY *pMyRecordsSA; SAFEARRAY *pIds; // omitting pIds initialization, because from the library I can see // that they are ok pMyRecordsSA = pIRetrieverProxy->RetrieveMyRecords(pIds); The problem I have is how to retrieve the results which are now stored in pMyRecordsSA. I have tried the following but I it's not working: IMyRecordPtr pIMyRecords(__uuidof(MyRecord)); HRESULT hr = SafeArrayAccessData(pMyRecordsSA, (void**)&pIMyRecords); but then trying to use the pIMyRecords pointer gives an access violation (hr is 0K). Any ideas? I am really stuck on this.
It turned out that I just needed "another level of indirection". That is, a pointer to pointer vs a simple pointer. IMyRecords** pIMyRecords; HRESULT hr = SafeArrayAccessData(pMyRecordsSA, (void**)&pIMyRecords); This did the trick.
1,544,850
1,599,270
Open source RTP mixer/translator exe or sdk
Hi I need opens source (win 32) sdk or free server with signaling protocol, which implements RTP translator or mixer. e.g receives RTP traffic from one connection and transmits it on the other. Does not have to have conferencing capabilities. Server should implement some kind of protocol which opens, bridges, and closes connections. Ready made server is much preferable than just common RTP SDK.
I haven't found nothing real. RtpProxy approaches the goal but I wasn't able to use it because it is for linux only. I tweaked Rtp Relay test program included in Live555
1,544,991
1,545,018
C++: How can a public static member function access private instance member variables?
I'm writing a C++ class to read input from a file into preallocated buffers called "chunks". I want the caller to be able to call a public static Chunk class method called GetNextFilledChunk(), which Grabs a Chunk from an inactive chunk pool Fills the Chunk instance from the input stream using the Chunk's private member variables/functions Returns a pointer to the Chunk to the caller But step 2 is giving me fits. No matter what I've tried, trying to get to the Chunk instance's private member variables/functions causes g++ 4.2.1 to emit errors. Here's a piece of the class definition from the header file: class Chunk { public: Chunk(); ... static Chunk* GetNextFilledChunk(); ... private: ... ssize_t m_ActualTextSize; }; And here's part of the source file that shows the problem: #include "Chunk.h" Chunk:: Chunk* GetNextFilledChunk() { ... theChunk = sInactiveChunks.top(); sInactiveChunks.pop(); ... theChunk->m_ActualTextSize = TextSize(); // PROBLEM IS HERE ... return theChunk; } As shown, g++ complains that GetNextFilledChunk() is trying to access a private member of Chunk. Then I thought, maybe it needs to be a "friend". But everything I've tried to do in header file to make GetNextFilledChunk() a friend results in an error. For instance: friend static Chunk* GetNextFilledChunk(); results in "Chunk.h:23: warning: ‘Chunk* GetNextFilledChunk()’ declared ‘static’ but never defined" What I find truly bizarre is that if I simply make GetNextFilledChunk() a plain old function, not a static member function, I can "friend" it and everybody is happy. But that seems silly - why should one be able to do something in a class from a non-class function that can't be done from a static member function? So... How can Chunk's s GetNextFilledChunk() function access private member variables of a Chunk instance? And if it can't be done, is it an inherent part of C++, or simply a bug in g++?
This looks a little bizarre: Chunk:: Chunk* GetNextFilledChunk() { Is that a typo? Should it be: Chunk* Chunk::GetNextFilledChunk() { ? It looks like you're accidentally defining GetNextFilledChunk to be a plain function rather than a member of Chunk.
1,545,080
1,545,085
C++ code file extension? What is the difference between .cc and .cpp
I have seen C++ code saved as both .cc and .cpp files. Is there a difference between the two? The Google style guide seems to suggest .cc, but provides no explanation. I am mainly concerned with programs on Linux systems.
At the end of the day it doesn't matter because C++ compilers can deal with the files in either format. If it's a real issue within your team, flip a coin and move on to the actual work.