question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,468,811
2,468,961
Load NSImage into QPixmap or QImage
I have an NSImage pointer from a platform SDK, and I need to load it into Qt's QImage class. To make things easier, I can create a QImage from a CGImageRef by using QPixmap as an intermediate format, like this: CGImageRef myImage = // ... get a CGImageRef somehow. QImage img = QPixmap::fromMacCGImageRef(myImage).toImage(); However, I cannot find a way to convert from an NSImage to a CGImageRef. Several other people have had the same problem, but I have yet to find a solution. There is the CGImageForProposedRect method, but I can't seem to get it to work. I'm currently trying this (img is my NSImage ptr): CGImageRef ir = [img CGImageFirProposedRect:0:0:0]; Any ideas?
NSImage is a high level image wrapper that might contain more than one image (thumbnails, different resolutions, vector representations, ...) and does a lot of caching magic. A CGImage on the other hand is one plain bitmap image. Since NSImage is a so much richer object, there’s no easy way of converting in between the two. To get a CGImageRef from an NSImage you have some options: Manually select an NSBitmapImageRep from the NSImage (using [img representations]) and get the CGImage from that. Setup a graphics context (CGBitmapContextCreate), draw the image into that, and create a CGImage from this context. Use the new Snow Leopard API to create the CGImage directly from the NSImage: [img CGImageForProposedRect:NULL context:nil hints:nil]
2,468,853
2,468,913
Freeing memory twice
In C and C++, Freeing a NULL pointer will result in nothing done. Still, I see people saying that memory corruption can occur if you "free memory twice". Is this true? What is going on under the hood when you free memory twice?
int *p = malloc(sizeof(int)); //value of p is now lets say 0x12345678 *p = 2; free(p); //memory pointer is freed, but still value of p is 0x12345678 //now, if you free again, you get a crash or undefined behavior. So, after free ing the first time, you should do p = NULL , so if (by any chance), free(p) is called again, nothing will happen. Here is why freeing memory twice is undefined: Why free crashes when called twice
2,468,857
2,468,871
Are +=, |=, &= etc atomic?
Are the "modify" operators like +=, |=, &= etc atomic? I know ++ is atomic (if you perform x++; in two different threads "simultaneously", you will always end up with x increased by 2, as opposed to x=x+1 with optimization switched off.) What I wonder is whether variable |= constant, and the likes are thread-safe or do I have to protect them with a mutex? (...or is it CPU-dependent? In this case, how is it on ARM?)
You are wrong. There is no guarantee that ++ is atomic and neither is there for the compound assignment operators, or indeed for any C++ operation.
2,469,015
2,469,021
Copying pointers in C++
I have a class A containing two pointers to objects of another class B. I want to initialize one pointer or the other depending on which one is passed to init(), which also takes other parameters. My situation is thus the following: class A { public: A(); init(int parameter, int otherParameter, B* toBeInitialized); protected: B* myB; B* myOtherB; }; Now my point is that I want to call init() as: init(640, 480, this->myB); or init(640, 480, this->myOtherB); Now, my init is implemented as: void init( int parameter, int otherParameter, B* toBeInitialized ) { toBeInitialized = someConstructorFunction(parameter, otherParameter); } The problem is that the two pointers are not initialized, I suspect that toBeInitialized is overwritten, but the original parameter is not modified. I am doing something wrong? Should I use references to pointers? Thank you Tommaso
Yes, change to void init( int parameter, int otherParameter, B*& toBeInitialized ) { toBeInitialized = someConstructorFunction(parameter, otherParameter); } In your original code toBeInitialized is passed by value and only the local copy of the variable will be modified.
2,469,160
2,469,217
comparison between string literal
This very simple code: #include <iostream> using namespace std; void exec(char* option) { cout << "option is " << option << endl; if (option == "foo") cout << "option foo"; else if (option == "bar") cout << "opzion bar"; else cout << "???"; cout << endl; } int main() { char opt[] = "foo"; exec(opt); return 0; } generate two warning: comparison with string literal results in unspecified behaviour. Can you explain why exactly this code doesn't work, but if I change char opt[] to char *opt it works, but generates the warning? Is it related to the \0 termination? What is the difference between the two declaration of opt? What if I use const qualifier? The solution is to use std::string?
char arrays or char pointers aren't really the same thing as string class objects in C++, so this if (option == "foo") Doesn't compare the string option to the string literal "foo" it compares the address of option with the address of the string literal "foo". You need to use one of the many string comparison functions if you want to know if the option is the same as "foo". strcmp is the obvious way to do this, or you can use std::string instead of char*
2,469,303
2,469,338
How should platform specific lib files be named?
I'm working on a C++ project that produces a lib that other teams use. It's being produced in a few different flavours: Win32 Debug Dynamic Win32 Debug Static Win32 Release Dynamic Win32 Release Static x64 Debug Dynamic x64 Debug Static x64 Release Dynamic x64 Release Static I'm wondering what the best wisdom is on how to name the dlls and what arguments are for different naming conventions. Do I output the libs into different directories, or do I append some letters on the end of the lib to differentiate them, or something else? One concern is that if I use directories, but don't give all the libs different names, users of the library will have problems where they accidentally use the wrong lib. Are these concerns valid? Thanks very much.
I output all the different flavours into the same directory, using a naming convention to disambiguate. By having them in the same directory, the linker directories don't have to change between flavour. The libraries then get linked using a set preprocessor directives that select the #pragma (lib,...) directive for the flavour being compiled.
2,469,393
2,469,951
Problem with FtpFindFirstFile
I want to download all file from ftp directory i want use for that FtpFindFirstFile and FtpGetFile; LPWIN32_FIND_DATA FileData; TCHAR* APP_NAME = TEXT("ftpcli"); TCHAR* PATH_FTP = TEXT("ftp://127.0.01"); TCHAR* ADR_FTP = TEXT("127.0.0.1"); TCHAR* LC_FILE = TEXT("C:\\!"); TCHAR* PATH_FILE = TEXT("/Soft/DVD_Players/WinDVD6"); UINT a; HINTERNET opn; HINTERNET conn; a = InternetAttemptConnect(0); if (a == ERROR_SUCCESS ) { if(InternetCheckConnection(PATH_FTP,FLAG_ICC_FORCE_CONNECTION, NULL)) { opn = InternetOpen(APP_NAME, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, INTERNET_FLAG_ASYNC); conn = InternetConnect(opn, ADR_FTP, INTERNET_DEFAULT_FTP_PORT, NULL, NULL, INTERNET_SERVICE_FTP, NULL, NULL); FtpSetCurrentDirectory(conn, PATH_FILE); FtpFindFirstFile(conn, NULL, &FileData, INTERNET_FLAG_NEED_FILE, NULL); FtpGetFile(conn, FileData->cFileName, LC_FILE, FALSE, FILE_ATTRIBUTE_NORMAL, FTP_TRANSFER_TYPE_BINARY, NULL); } } That code return error i know that because i do not identified memory on LPWIN32_FIND_DATA. But i do not know how do it.
You've declared a pointer to WIN32_FIND_DATA, you need a concrete instance of that structure. Fix: WIN32_FIND_DATA FileData; // NOTE: not LP
2,469,531
2,469,697
Reading and writing C++ vector to a file
For some graphics work I need to read in a large amount of data as quickly as possible and would ideally like to directly read and write the data structures to disk. Basically I have a load of 3d models in various file formats which take too long to load so I want to write them out in their "prepared" format as a cache that will load much faster on subsequent runs of the program. Is it safe to do it like this? My worries are around directly reading into the data of the vector? I've removed error checking, hard coded 4 as the size of the int and so on so that i can give a short working example, I know it's bad code, my question really is if it is safe in c++ to read a whole array of structures directly into a vector like this? I believe it to be so, but c++ has so many traps and undefined behavour when you start going low level and dealing directly with raw memory like this. I realise that number formats and sizes may change across platforms and compilers but this will only even be read and written by the same compiler program to cache data that may be needed on a later run of the same program. #include <fstream> #include <vector> using namespace std; struct Vertex { float x, y, z; }; typedef vector<Vertex> VertexList; int main() { // Create a list for testing VertexList list; Vertex v1 = {1.0f, 2.0f, 3.0f}; list.push_back(v1); Vertex v2 = {2.0f, 100.0f, 3.0f}; list.push_back(v2); Vertex v3 = {3.0f, 200.0f, 3.0f}; list.push_back(v3); Vertex v4 = {4.0f, 300.0f, 3.0f}; list.push_back(v4); // Write out a list to a disk file ofstream os ("data.dat", ios::binary); int size1 = list.size(); os.write((const char*)&size1, 4); os.write((const char*)&list[0], size1 * sizeof(Vertex)); os.close(); // Read it back in VertexList list2; ifstream is("data.dat", ios::binary); int size2; is.read((char*)&size2, 4); list2.resize(size2); // Is it safe to read a whole array of structures directly into the vector? is.read((char*)&list2[0], size2 * sizeof(Vertex)); }
As Laurynas says, std::vector is guaranteed to be contiguous, so that should work, but it is potentially non-portable. On most systems, sizeof(Vertex) will be 12, but it's not uncommon for the struct to be padded, so that sizeof(Vertex) == 16. If you were to write the data on one system and then read that file in on another, there's no guarantee that it will work correctly.
2,469,858
2,469,930
How to access C arrays from assembler for Windows x64?
I've written an assembler function to speed up a few things for image processing (images are created with CreateDIBSection). For Win32 the assembler code works without problems, but for Win64 I get a crash as soon as I try to access my array data. I put the relevant info in a struct and my assembler function gets a pointer to this struct. The struct pointer is put into ebx/rbx and with indexing I read the data from the struct. Any idea what I am doing wrong? I use nasm together with Visual Studio 2008 and for Win64 I set "default rel". C++ code: struct myData { tUInt32 ulParam1; void* pData; }; CallMyAssemblerFunction(&myData); Assembler Code: Win32: ... push ebp; mov ebp,esp mov ebx, [ebp + 8]; pointer to our struct mov eax, [ebx]; ulParam1 mov esi, [ebx + 4]; pData, 4 byte pointer movd xmm0, [esi]; ... Win64: ... mov rbx, rcx; pointer to our struct mov eax, [rbx]; ulParam1 mov rsi, [rbx + 4]; pData, 8 byte pointer movd xmm0, [rsi]; CRASH! ...
Quite probably, the pData field is at [rbx + 8], not [rbx + 4]. The compiler inserts some extra space ("padding") between ulParam1 and pData so that pData is 8-byte aligned (which makes accesses faster).
2,469,861
2,477,451
Parsing string, with Boost Spirit 2, to fill data in user defined struct
I'm using Boost.Spirit which was distributed with Boost-1.42.0 with VS2005. My problem is like this. I've this string which was delimted with commas. The first 3 fields of it are strings and rest are numbers. like this. String1,String2,String3,12.0,12.1,13.0,13.1,12.4 My rule is like this qi::rule<string::iterator, qi::skip_type> stringrule = *(char_ - ',') qi::rule<string::iterator, qi::skip_type> myrule= repeat(3)[*(char_ - ',') >> ','] >> (double_ % ',') ; I'm trying to store the data in a structure like this. struct MyStruct { vector<string> stringVector ; vector<double> doubleVector ; } ; MyStruct var ; I've wrapped it in BOOST_FUSION_ADAPT_STRUCTURE to use it with spirit. BOOST_FUSION_ADAPT_STRUCT (MyStruct, (vector<string>, stringVector) (vector<double>, doubleVector)) My parse function parses the line and returns true and after qi::phrase_parse (iterBegin, iterEnd, myrule, boost::spirit::ascii::space, var) ; I'm expecting var.stringVector and var.doubleVector are properly filled. but it is not the case. What is going wrong ? The code sample is located here Thanks in advance, Surya
qi::skip_type is not something you could use a skipper. qi::skip_type is the type of the placeholder qi::skip, which is applicable for the skip[] directive only (to enable skipping inside a lexeme[] or to change skipper in use) and which is not a parser component matching any input on its own. You need to specify your specific skipper type instead (in your case that's boost::spirit::ascii:space_type). Moreover, in order for your rules to return the parsed attribute, you need to specify the type of the expected attribute while defining your rule. That leaves you with: qi::rule<string::iterator, std::string(), ascii:space_type> stringrule = *(char_ - ','); qi::rule<string::iterator, MyStruct(), ascii:space_type> myrule = repeat(3)[*(char_ - ',') >> ','] >> (double_ % ','); which should do exactly what you expect.
2,469,931
2,469,967
How to check if a pointer is null in C++ Visual 2010
I am having problems here if I want to check if eerste points to nothing I get Blockquote Unhandled exception at 0x003921c6 in Bank.exe: 0xC0000005: Access violation reading location 0xccccccd0. and I am kinda wondering why he justs skips the if statement or doens't stop when the object eerste points to nothing Bank::Bank() { LijstElement *eerste = NULL; LijstElement *laatste = NULL; } Rekening * Bank::getRekening(int rekNr) { if(NULL != eerste) { LijstElement *nummer = eerste; while(nummer->volgende!= NULL) { Rekening *een = nummer->getRekening(); if(een->getRekNr()==rekNr) { return een; } else { nummer = nummer->volgende; } } } return NULL; }
I think you have to change Bank::Bank() { eerste = NULL; laatste = NULL; } because they are probably declared in your class as member variables and you're declaring them as local variables. As Fred Larson proposed, you can also use initialization lists. Bank::Bank() : eerste(NULL), laatste(NULL) { //whatever else you are planning to do in your constructor }
2,470,255
2,470,834
C++ - Difference between (*). and ->?
Is there any difference in performance - or otherwise - between: ptr->a(); and (*ptr).a(); ?
Since you are asking for it in the comments. What you are probably looking for can be found in the Standard (5.2.5 Class member access): 3 If E1 has the type “pointer to class X,” then the expression E1->E2 is converted to the equivalent form (*(E1)).E2; The compiler will produce the exact same instructions and it will be just as efficient. Your machine will not know if you wrote "->" or "*.".
2,470,286
2,471,067
PHP's preg_match() equivalent in C++?
My question is simple. Is there a PHP's preg_match() function equivalent in the C++ STL? If not, can you tell me an alternative? Thanks.
preg_match() calls code from libPCRE. If you want the equivalent of preg_match(), then you must use that library. Alternatively, if you just need the feature of regular expression matching (PCRE or not), there is also the Boost::regex library mentioned in another answer. If your compiler supports the new versions of the standard (C++11 or later), then it probably also includes the new standard regular expression library. The Standard includes support for ECMAScript syntax (which is very similar to, and based on, PCRE) as well as a few others.
2,470,487
2,472,299
Call c++ function pointer from c#
Is it possible to call a c(++) static function pointer (not a delegate) like this typedef int (*MyCppFunc)(void* SomeObject); from c#? void CallFromCSharp(MyCppFunc funcptr, IntPtr param) { funcptr(param); } I need to be able to callback from c# into some old c++ classes. C++ is managed, but the classes are not ref classes (yet). So far I got no idea how to call a c++ function pointer from c#, is it possible?
dtb is right. Here a more detailed example for Marshal.GetDelegateForFunctionPointer. It should work for you. In C++: static int __stdcall SomeFunction(void* someObject, void* someParam) { CSomeClass* o = (CSomeClass*)someObject; return o->MemberFunction(someParam); } int main() { CSomeClass o; void* p = 0; CSharp::Function(System::IntPtr(SomeFunction), System::IntPtr(&o), System::IntPtr(p)); } In C#: public class CSharp { delegate int CFuncDelegate(IntPtr Obj, IntPtr Arg); public static void Function(IntPtr CFunc, IntPtr Obj, IntPtr Arg) { CFuncDelegate func = (CFuncDelegate)Marshal.GetDelegateForFunctionPointer(CFunc, typeof(CFuncDelegate)); int rc = func(Obj, Arg); } }
2,470,539
2,470,578
c++ simple conditional logging
Disclaimer: I'm not a c++ developer, I can only do basic things. (I understand pointers, just my knowledge is so rusty, I haven't touch c/c++ for about 20 years :) ) The setup: I have an Outlook addin, written in C#/.Net 1.1. It uses a c++ shim to load. Usually, this works pretty well, and I use in my c# code nlog for logging purposes. But sometimes, the addin fails to load, i.t. it does not hit the managed code at all for me to be able to investigate the problem from the log files. So, I need to hook some basic logging into the c++ shim - just writing in a file. I need to make it as simple as possible for our users to enable. Actually I would prefer not to ship it by default. I was thinking about something, which will check if a specific dll is present (the logging dll), and if so, to use it. Otherwise, it will just not log anything. That way, when I have a user with such a problems, I can send him only the logging dll, the user will save it in the runtime directory, and I'll have the file. I guess this have to be done with some form a factory solution, which returns either a dummy logger, or if the dll is found, a real one. Another option would be to make some simple logger, and rebuild the shim with or w/o using it, based on directives. This is not the desirable approach, because the shim needs to be signed, and I have to instruct the user to make a backup copy of the "real" one, then restore when done, etc., instead of just saving and deleting a dll. I'd appreciate any good suggestion how to approach it, together with links or sample code how to go after this. Cheers
The loading of the logging dll's seams like a complicated way of handling the configuration issue. Why not use the registry. If you use conditional loading on dlls you will be using LoadLibrary and GetProceAddress and as you said your not really a c++ coder so why introduce the complexity. Also there have to be n+1 c++ logging libraries available have you looked into any of those. Some I found after a Google search log4cpp rlog
2,470,737
2,470,840
Why can't initialize the static member in a class in the body or in the header file?
Could any body offer me any reason about that? If we do it like that, what's the outcome? Compile error?
The problem is that static initialization isnt just initialization, it is also definition. Take for example: hacks.h : class Foo { public: static std::string bar_; }; std::string Foo::bar_ = "Hello"; std::string GimmeFoo(); main.cpp : #include <string> #include <sstream> #include <iostream> #include "hacks.h" using std::string; using std::ostringstream; using std::cout; int main() { string s = GimmeFoo(); return 0; } foo.cpp : #include <string> #include <sstream> #include <iostream> #include "hacks.h" using std::string; using std::ostringstream; using std::cout; string GimmeFoo() { Foo foo; foo; string s = foo.bar_; return s; } In this case, you can't initialize Foo::bar_ in the header because it will be allocated in every file that #includes hacks.h. So there will be 2 instances of Foo.bar_ in memory - one in main.cpp, and one in foo.cpp. The solution is to allocate & initialize in just one place: foo.cpp : ... std::string Foo::bar_ = "Hello"; ...
2,471,001
2,471,076
LNK2001 error in code
I am getting LNK2001 error. The code has been included below. Can someone please help me out? Error 3 error LNK2001: unresolved external symbol "private: static class std::vector<struct _UpdateAction,class std::allocator<struct _UpdateAction> > InstrumentCache::actionTaken" (?actionTaken@InstrumentCache@@0V?$vector@U_UpdateAction@@V?$allocator@U_UpdateAction@@@std@@@std@@A) PerformanceTest.obj //UpdateAction.h typedef struct _UpdateAction { enum FIS_ACTION { ADDED, UPDATED, DELETED }; int id; int type; int legacyType; FIS_ACTION action; }UpdateAction; typedef std::vector<UpdateAction> ActionTakenVector; // InstrumentCache.h #include UpdateAction.h class InstrumentCache { public: static ActionTakenVector& GetApplicationUpdateVector () { return actionTaken; } static void ClearApplicationUpdateVector() { actionTaken.clear(); } private: static ActionTakenVector actionTaken; }; //fisClient.h #include "UpdateAction.h" #include "InstrumentCache.h" class FISClient { void FunctionOne() { ActionTakenVector& rV = InstrumentCache::GetApplicationUpdateVector(); InstrumentCache::ClearApplicationUpdateVector(); } } ; PerformanceTest.cpp #include "fisClient.h"
It seems that you are missing the definition of actionTaken (the declaration in the class is not enough). Does adding ActionTakenVector InstrumentCache::actionTaken; in PerformanceTest.cpp help?
2,471,249
2,471,424
Linux network programming. What can I start with?
I've recently got interested in Linux network programming and read quite a bit (Beej's Guide to Network Programming). But now I'm confused. I would like to write something to have some practice, but I don't know what exactly. Could please recommend me a couple of projects to start with? Thanks.
I'm not sure how in-depth you want to start your Linux Network Programming career, but if you want to just get started with dealing with sockets, probably the easiest examples are a Producer/Consumer pairing or an Echo Server. Another good source would be looking at some of the examples/assignments from any number of University/College courses on Distributed computing. Producer/Consumer This could be run in a pair of terminals on your computer to test. Create two applications: Producer program starts with a hostname and port, takes a line of input from the user, connects to the Consumer, sends it the input, asks for another line of input, and finishes when it reaches EOF (Ctrl-D). Consumer program starts with a listening port, waits for a connection from the Producer, reads the message sent by the Producer, outputs that message, closes the connection with the Producer, exits gracefully when sent an interrupt (Ctrl-C). Echo Server Similar idea to Producer/Consumer. Echo Server starts with a listening port, waits for a connection, reads a message from the Client, sends that same message back to the Client, and exits gracefully when sent an interrupt (Ctrl-C). Echo Client starts with a hostname and port, takes a line of input from the user, connects to the Server, sends the input, reads back the response, compares the two to verify it was an echo, asks for another line of input, and finishes when it reaches EOF.
2,471,251
2,471,402
Visual Studio C++ multi-project solution
I have created an C++ solution in VS2008. The first project contains the model. The second projects is the view. The problem is that i don't get make references to my model classes defined in the first project. The message error is : Error 1 fatal error C1083: Cannot open include file: 'utils/GeradorSistematicoDeAlturaDoPlanoDeCorteStrategy.h': No such file or directory c:\Users\user\Programação em C++\Simulacao\Simulacao_Testes\src\Teste1.cpp 3 Simulacao_Testes Is there any configuration in VS2008 that makes to be made in order to, from the my view (second project) project, i do make references to the first project, the model?
First of all I find this approach for the MVC pattern quite strange. But if you really want to do it like that you have to link the resulting DLL/LIB from your model project to your view project (go to the project properties, then Configuration Properties/Linker/Input/Additional Dependencies; you may need to set the right path too in Configuration Properties/Linker/General/Additional Library Directories)
2,471,339
2,475,757
Generic calls to OnResetDevice() and OnLostDevice()
This is kind of a COM question to do with DirectX. So, both ID3DXSprite and ID3DXFont and a bunch of the other ID3DX* objects require you to call OnLostDevice() when the d3d device is lost AND OnResetDevice() when the device is reset. What I want to do is maintain an array of all ID3DX* objects and simply call OnResetDevice() and OnLostDevice() on each whenever the device is lost or reset. However I can't seem to find a BASE CLASS for the ID3DX* classes... they all seem to COM-ually inherit from IUnknown. Is there a way to do this or do I have to maintain separate arrays of ID3DXFont* pointers, ID3DXSprite* pointers, etc?
There isn't a common base class, sorry. You could use multiple inheritance and templates to sort of achive what you want. Something like this (untested but hopefully you'll get the idea)... #include <d3dx9.h> #include <vector> using namespace std; class DeviceLostInterface { public: virtual void onLost() = 0; virtual void onReset() = 0; }; template <typename Base> class D3DXWrapper : public Base, public DeviceLostInterface { public: virtual void onLost() { Base::OnLostDevice(); } virtual void onReset() { Base::OnResetDevice(); } }; int main() { // Wouldn't be set to null in real program D3DXWrapper<ID3DXSprite>* sprite = 0; D3DXWrapper<ID3DXFont>* font = 0; vector<DeviceLostInterface*> things; things.push_back(sprite); things.push_back(font); // This would be a loop... things[0]->onLost(); things[1]->onLost(); } This sort of meets your requirements, but to be honest I don't really think it's very useful. You'd either need some way to know what to cast each item back to, or keep the pointers in a type specific list anyway and then you might as well just write separate code to reset each type anyway.
2,471,430
2,471,550
How to set maximum read length for a stream in C++?
I'm reading data from a stream into a char array of a given length, and I'd like to make the maximum width of read to be large enough to fit in that char array. The reason I use a char array is that part of my specification is that the length of any individual token cannot exceed a certain value, so I'm saving myself some constructor calls. I thought width() did what I wanted, but I was apparently wrong... EDIT: I'm using the stream extraction operators to perform the extraction, since these are flat text files with values separated by whitespace.
char x[4]; cin.width(4); cin >> x; cout << x; Input: "abcdef" Output: "abc" (x[3] is null terminating char) Width works fine in this case. Note: Empirical testing indicates that the cin.width call only lasts for one stream operation. It may be more convenient to use cin >> setw(4) >> x; instead, though this requires iomanip.
2,471,529
2,471,563
How to implement generic callbacks in C++
Forgive my ignorance in asking this basic question but I've become so used to using Python where this sort of thing is trivial that I've completely forgotten how I would attempt this in C++. I want to be able to pass a callback to a function that performs a slow process in the background, and have it called later when the process is complete. This callback could be a free function, a static function, or a member function. I'd also like to be able to inject some arbitrary arguments in there for context. (ie. Implementing a very poor man's coroutine, in a way.) On top of that, this function will always take a std::string, which is the output of the process. I don't mind if the position of this argument in the final callback parameter list is fixed. I get the feeling that the answer will involve boost::bind and boost::function but I can't work out the precise invocations that would be necessary in order to create arbitrary callables (while currying them to just take a single string), store them in the background process, and invoke the callable correctly with the string parameter.
The callback should be stored as a boost::function<void, std::string>. Then you can use boost::bind to "convert" any other function signature to such an object, by binding the other parameters. Example I've not tried to compile this, but it should show the general idea anyways void DoLongOperation(boost::function<void, const std::string&> callback) { std::string result = DoSomeLengthyStuff(); callback(result); } void CompleteRoutine1(const std::string&); void CompleteRoutine2(int param, const std::string&); // Calling examples DoLongOperation(&CompleteRoutine1); // Matches directly DoLongOperation(boost::bind(&CompleteRoutine2, 7, _1)); // int parameter is bound to constant. // This one is thanks to David Rodríguez comment below, but reformatted here: struct S { void f( std::string const & ); }; int main() { S s; DoLongOperation( boost::bind( &S::f, &s, _1 ) ); }
2,471,591
2,481,740
How can I detect message boxes popping up in another process?
I'd like to execute some code whenever a (any!) message box (as spawned by the MessageBox Function) is shown in another process. I didn't start the process I'm monitoring. I can think of three approaches: Install a global CBT Hook procedure which tells me whenever a window is created on the desktop. Then, check whether the window belongs to the process I'm monitoring and whether the class name is #32770 (which is the class name of dialogs according to the About Window Classes page at the MSDN). This would probably work, but it would pull the DLL which contains the hook procedure into virtually every process on the desktop, and the hook procedure gets called a lot. It smells like a potential perfomance problem. Try to subclass the #32770 system window class (is this possible at all?) and look for WM_CREATE messages in my custom window procedure. Intercept the MessageBox Function API call (even though the remote process is running already!) and call my code from the hook function. So far, I only know that the first idea is feasible, but it seems really inefficient. Can anybody think of a simpler solution than that to this problem?
I can't think of any efficient solution that doesn't involve injecting code into the other process (this is basically what many types of hooks do by the way). But if you are willing to go down that path, you can intercept calls to MessageBox. Spend some time stepping through into a call to MessageBox in the debugger in assembly language mode and you'll see that it's an indirect call through a lookup table (that's how exports work). so if you can get your code into the process, you can patch the table to jump to your code instead. See http://www.codeproject.com/KB/threads/completeinject.aspx for code showing how to inject a dll into another process.
2,471,892
2,472,442
Setting custom header values in an IIS ISAPI filter
I have an ISAPI filter that I am using to do URL rewriting for my CMS. I am processing SF_NOTIFY_PREPROC_HEADERS notifications, and trying to do this: DWORD ProcessHeader(HTTP_FILTER_CONTEXT *con, HTTP_FILTER_PREPROC_HEADERS *head) { head->SetHeader(con, "test1", "aaa"); con->AddResponseHeaders(con, "test2:bbb\r\n", 0); return SF_STATUS_REQ_NEXT_NOTIFICATION; } However, I can't seem to read these values using server variables or response headers in classic ASP or PHP. The values are missing. I'm expecting either my "test1" or "test2" header values to appear, but they are not. Am I doing something wrong here?
I finally figured it out, I was missing a ':' in the header name: DWORD ProcessHeader(HTTP_FILTER_CONTEXT *con, HTTP_FILTER_PREPROC_HEADERS *head) { head->SetHeader(con, "test1:", "aaa"); return SF_STATUS_REQ_NEXT_NOTIFICATION; } This now creates a server variable called "HTTP_TEST1".
2,472,568
2,472,974
Visual C++ 9.0 (2008) Static Lib + Boost Library = Large .lib File
I have a Visual Studio 2008 C++ project that outputs a static library and uses some functionality of the Boost Library. When I build the project in Debug configuration, the .lib file is 7.84 MB. When I build the project in Release configuration, the .lib file is 23.5 MB. !!!! The only Boost headers I include are: boost/function.hpp boost/exception/all.hpp Since this is a static library, I don't have any Boost library files specified to include, but somehow it's a ginormous output. When I use that static library in a test executable, the resulting .exe file is only 746 KB in Debug and 231 KB in Release. The problem is that I have to create a "release" of the library to check into a different repository to be used by other projects. And I would prefer not to have to add 30 MB of files each time I update it. And if nothing else it really confuses me as to why the Release build is 3 times the size of the Debug. Anyone have suggestions as to what I'm doing wrong? Thanks, Matt
Project + Properties, C/C++, Optimization, Whole Program Optimization = No. That at least ought to keep your Release build size from blowing up. I can't repro the debug library size, just the headers gives me a 111KB .lib.
2,472,601
2,472,725
Numerical precision of double type in Visual C++ 2008 Express debugger
I'm using Visual C++ 2008 Express Edition and when i debug code: double x = 0.2; I see in debugging tooltip on x 0.20000000000000001 but: typedef numeric_limits< double > double_limit; int a = double_limit::digits10 gives me: a = 15 Why results in debugger are longer than normal c++ precision? What is this strange precision based on? My CPU is Intel Core 2 Duo T7100
What you are seeing is caused by the fact that real numbers (read floating-point) cannot be expressed with perfect precision and accuracy in binary computers. This is a fact of life. Instead, computers approximate the value and store it in memory in a defined format. In the case of most modern machines (including any machine your'e running MSVC Express on), this format is IEEE 754. Long story short, this is how real numbers are stored in IEEE 754: there is one sign bit, 8 exponent bits and 23 fraction bits (for float data type -- doubles use more bits accordingly but the format is the same). Because of this, you can never achieve perfect precision and accuracy. Fortunately you can achieve plenty of accuracy and precision for almost any application including critical financial systems and scientific systems. You don't need to know everything there is to know about IEEE754 in order to be able to use floating-points in your code. But there are a few things you must know: 1) You can never compare 2 floating point values for equality because of the rounding error inherent in floating point calulation & storage. Instead, you must do something like this: double d = 0.2; double compare = 0.000000001; double d2 = something; if( (d - d2 < compare) && (d2 - d < compare) ) { // numbers are equal } 2) Rounding errors compound. The more times you perform operations on a floating point value, the greater the loss of precision. 3) You cannot add two floating points of vastly different magnitude. For example, you can't add 1.5x10^30 and 1.5x10^-30 and expect 60 digits of precision.
2,472,773
2,476,965
Instruction for installing an environment with Qt and Qt integration with Visual Studio 2008
I want to use Qt lib but I don't know how to install Visual Studio 2008+Qt+Qtintegration. I have read some forums, that step by step tell what to download, where to download from, and then what to do. But that was for old versions of mentiond products. I ask to Qt developers tell me the way to install these items on Windows. Any forum or site will be fine. Thanks.
To get QT working with dev studio you need to install two things. First, a copy of the QT Visual Studio Libraries. And the QT Visual Studio Addin. http://qt.nokia.com/downloads/windows-cpp-vs2008 http://qt.nokia.com/downloads/visual-studio-add-in Download the QT sdk, and install it. It usually installs into a folder like c:\qt\4.6.2 Then, install the visual studio addin. The addin should add (At least) two new things to Visual Sutdio. A new "Qt" project in the Create New Project Wizard, and a Qt menu. Qt supports building your project against multiple builds of Qt, so the first thing you need to do is go to the Qt menu, and point it to the directory you installed the Qt SDK to. It all went well it should auto populate with c:\qt\4.6.2 Then, use the Wizard to create a new Qt project in Visual Studio. If you are creating your first Qt project in Visual Studio this way, there is no need to fiddle with .pro files or doing any kind of "stuff" outside Visual Studio to get a project going. The Visual Studio addin sets up the workspace to do all the pre-compiles needed by the Qt build environment. -- Note: The Qt SDK at this URL http://qt.nokia.com/downloads/sdk-windows-cpp comes with the MinGW runtine for GCC, and Qt Creator embedded. This is no good for Visual Studio. This build installs to a folder like c:\Qt\2010.2
2,472,868
2,472,902
I just learned about C++ functions; can I use if statements on function return values?
What I am confused on is about the isNumPalindrome() function. It returns a boolean value of either true or false. How am I suppose to use that so I can display if it's a palindrome or not. For ex. if (isNumPalindrome == true) cout << "Your number is a palindrome"; else cout << "your number is not a palindrome."; #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } #include <iostream> #include <cmath> using namespace std; int askNumber(); bool isNumPalindrome(); int num, pwr; int main() { askNumber(); return 0; } bool isNumPalindrome() { int pwr = 0; if (num < 10) return true; else { while (num / static_cast<int>(pow(10.0, pwr)) >=10) pwr++; while (num >=10) { int tenTopwr = static_cast<int>(pow(10.0, pwr)); if ((num / tenTopwr) != (num% 10)) return false; else { num = num % tenTopwr; num = num / 10; pwr = pwr-2; } } return true; } } int askNumber() { cout << "Enter an integer in order to determine if it is a palindrome: " ; cin >> num; cout << endl; if(isNumPalindrome(num)) { cout << "It is a palindrome." ; cout << endl; } else { cout << "It is not a palindrome." ; cout << endl; } return num; }
The return value for a function can be used just like a variable of the same type. Your main program should look something like this: int main() { int num=askNumber(); bool isPal=isNumPalindrome(num); if (isPal) { //do something } else { //do something else } return 0; } or you could be even more succinct: int main() { if (isNumPalindrome(askNumber())) { //do something } else { //do something else } return 0; } What you don't want to do is use those global variables you defined. In more complicated programs that will be a recipe for disaster. Edit: you'll want to make sure you edit your isNumPalindrome function to accept the number it's working with: bool isNumPalindrom(int num) { ... }
2,472,924
2,473,242
Linking to MSVC DLL from MinGW
I'm trying to link the LizardTech GeoExpress DSDK into my own application. I use gcc so that we can compile on for platforms. On Linux and Mac this works easily: they provide a static library (libltidsdk.a) and headers and all that we have to do is use them. Compiling for windows isn't so easy. They've built the library using Microsoft Visual Studio, and we use MinGW. I've read the MinGW FAQ, and I'm running into the problems below. The library is all C++, so my first question: is this even possible? Just linking against the dll as provided yields "undefined reference" errors for all of the C++ calls (constructors, desctructors, methods, etc). Based on the MinGW Wiki: http://www.mingw.org/wiki/MSVC%5Fand%5FMinGW%5FDLLs I should be able to use the utility reimp to convert a .lib into something useable. I've tried all of the .lib files provided by LizardTech, and they all give "invalid or corrupt import library". I've tried both version 0.4 and 0.3 of the reimp utility. Using the second method described in the wiki, I've run pexport and dlltool over the dll to get a .a archive, but that produces the same undefined references. BTW: I have read the discussion below. It left some ambiguity as to whether this is possible, and given the MinGW Wiki page it seems like this should be doable. If it is impossible, that's all I need to know. If it can be done, I'd like to know how I can get this to happen. How to link to VS2008 generated .libs from g++ Thanks!
You can't do this. They have exported C++ classes from their dll, rather than C-functions. The difference is, c++ functions are always exported with names in a mangled form that is specific to a particular version of the compiler. Their dll is usable by msvc only in that form, and will probably not even work between different versions of msvc, as Microsoft have changed their mangling scheme before. If you have any leverage, you need to get them to change their evil ways. Otherwise you will need to use MSVC to write a shim dll, that will import all the classes, and re-export them via c functions that return interfaces.
2,472,944
2,472,968
Good C++ array class for dealing with large arrays of data in a fast and memory efficient way?
Following on from a previous question relating to heap usage restrictions, I'm looking for a good standard C++ class for dealing with big arrays of data in a way that is both memory efficient and speed efficient. I had been allocating the array using a single malloc/HealAlloc but after multiple trys using various calls, keep falling foul of heap fragmentation. So the conclusion I've come to, other than porting to 64 bit, is to use a mechanism that allows me to have a large array spanning multiple smaller memory fragments. I don't want an alloc per element as that is very memory inefficient, so the plan is to write a class that overrides the [] operator and select an appropriate element based on the index. Is there already a decent class out there to do this, or am I better off rolling my own? From my understanding, and some googling, a 32 bit Windows process should theoretically be able address up to 2GB. Now assuming I've 2GB installed, and various other processes and services are hogging about 400MB, how much usable memory do you think my program can reasonably expect to get from the heap? I'm currently using various flavours of Visual C++. Edit As per Poita's post, I've tried a std::deque, using the following test on VS2008; #include <deque> using namespace std; struct V { double data[11]; }; struct T { long data[8]; }; void dequeTest() { deque<V> VQ; deque<T> TQ; V defV; T defT; VQ.resize(4000000,defV); TQ.resize(8000000,defT); } The total memory for the above data comes out at 608MB, were I to use straight malloc or HeapAlloc, and takes < 1 second. The deque resizes took 950MB originally, and then slowly started dropping back. 15 minutes later, dequeTest() finished, using just 6MB of memory showing for the process which probably was more to do with the run-times. I also tried populating the deque using various push options, but performance was so bad, I had to break out early. I could possibly provide a better allocator than the defualt to get a much better response, but on the face of it deque is not the class for this job. Note this could also relate to the MS VS2008 implementation of deque, as there seems to be alot in this class that is very implementation dependant when it comes to performance. Time to write my own big array class, I reckon. Second Edit: Allocating smaller amounts yielded 1.875GB immediately using the following; #define TenMB 1024*1024*10 void SmallerAllocs() { size_t Total = 0; LPVOID p[200]; for (int i = 0; i < 200; i++) { p[i] = malloc(TenMB); if (p[i]) Total += TenMB; else break; } CString Msg; Msg.Format("Allocated %0.3lfGB",Total/(1024.0*1024.0*1024.0)); AfxMessageBox(Msg,MB_OK); } Final edit I have decided to accept Poita's post and the various comments following it, not because I'll be using the deque class directly, but more for the array as a deck of cards notion in the comments that followed. This should be straightforward to implement with O(1) random element access, based on a fixed number of elements per block, which is what i need. Thanks to all for the feedback!
Have you tried using an std::deque? Unlike a std::vector, which uses one huge heap allocation, deque usually allocates in small chunks, but still provides amortised constant time indexing via operator[].
2,473,087
2,473,143
I want to extend std::string, but not for the reason you might think
I have a method that effectively takes a string. However, there is a very limited subset of strings I want to use. I was thinking of typedef'ing std::string as some class, and call the functions explicit. I'm not sure that would work, however. Ideas?
The usual rule still applies: the class isn't designed to be inherited from, and its destructor isn't virtual, so if you ever upcast to the std::string base class, and let the object be destroyed, your derived class' destructor won't be called. If you can guarantee that this will never happen, go ahead. Otherwise, you could make the std::string a member of your class, rather than a base class. or you could use private inheritance. The problem with this approach is that you'd have to re-implement the string interface for the class to be usable as a string. Or you could just define your class to expose a getString() function which returns the internal std::string object. Then you can still pass your own class around, and the compiler will complain if you try to pass a std::string, but the internal string is accessible when you need it. That might be the best compromise.
2,473,300
2,473,395
Overloading the QDataStream << and >> operators for a user-defined type
I have a an object I'd like to be able to read and write to/from a QDataStream. The header is as follows: class Compound { public: Compound(QString, QPixmap*, Ui::MainWindow*); void saveCurrentInfo(); void restoreSavedInfo(QGraphicsScene*); void setImage(QPixmap*); QString getName(); private: QString name, homeNotes, addNotes, expText; Ui::MainWindow *gui; QPixmap *image; struct NMRdata { QString hnmrText, cnmrText, hn_nmrText, hn_nmrNucl, notes; int hnmrFreqIndex, cnmrFreqIndex, hn_nmrFreqIndex, hnmrSolvIndex, cnmrSolvIndex, hn_nmrSolvIndex; }*nmr_data; struct IRdata { QString uvConc, lowResMethod, irText, uvText, lowResText, highResText, highResCalc, highResFnd, highResFrmla, notes; int irSolvIndex, uvSolvIndex; }*ir_data; struct PhysicalData { QString mpEdit, bpEdit, mpParensEdit, bpParensEdit, rfEdit, phyText, optAlpha, optConc, elemText, elemFrmla, notes; int phySolvIndex, optSolvIndex; }*physical_data; }; For all intents and purposes, the class just serves as an abstraction for a handful of QStrings and a QPixmap. Ideally, I would be able to write a QList to a QDataStream but I'm not exactly sure how to go about doing this. If operator overloading is a suitable solution, would writing code like friend QDataStream& operator << (QDataStream&,Compound) { ... } be a potential solution? I'm very open to suggestions! Please let me know if any further clarification is needed.
I think you've answered your own question! The stream operator QDataStream& operator<<( QDataStream&, const Compound& ) will work fine. In the implementation you just use the existing stream operators on QDataStream to serialise the individual bits of your Compound. Some Qt classes define non-member QDataStream operators too. QString is one and so is QList so it looks like you're sorted!
2,473,538
2,473,606
C++ Macro Arithmetric
I have to do with Macros (it's macros calling macros; so templates are out of the question). Here's what I want: foo(3, a, b1, c1) --> foo1(a, b1, c1); foo(5, a, b1, c1, b2, c2) -> foo2(a, b1, c1, b2, c2); foo(7, a, b1, c1, b2, c2, b3, c3) -> foo3(a, b1, c1, b2, c2, b3, c3); So basically, what I want is to be able to execute the "function" n -> (n-1)/2 at macro expansion time. Is this possible? [PS, if you dislike my questions; I support your right to downvote; my worst question so far is only -17, so maybe we can break that record; however, please let me know why my question is technically invalid.] EDIT: Foo takes a variable # of arguments, of the form: foo(N, a1, b1, a2, b2, ... a_N, b_N) -> foo##N(a1, b1, a2, b2, ... a_N, b_N); EDIT: To all the closers. This is a very different question. The former is about "how do I count the # of arguments in a Macro." (to which there was a good response on the mailing list). This question is a matter of: given I've counted the # of arguments, how do I dispatch on it?
I haven't tested this, but should work: #define SUBSTFOO3( a, b1, c1 ) foo1(a, b1, c1) #define SUBSTFOO5( a, b1, c1, b2, c2 ) foo2(a, b1, c1, b2, c2) /* ad nauseam */ #define foo( N, ... ) SUBSTFOO ## N ( __VA_ARGS__ ) This might also work: #define SUBSTFOO3 foo1 /* no arguments needed */ #define SUBSTFOO5 foo2 /* "( __VA_ARGS__)" already the correct substitution */ #define foo( N, ... ) SUBSTFOO ## N ( __VA_ARGS__ )
2,473,628
2,473,648
C++: can't static_cast from double* to int*
When I try to use a static_cast to cast a double* to an int*, I get the following error: invalid static_cast from type ‘double*’ to type ‘int*’ Here is the code: #include <iostream> int main() { double* p = new double(2); int* r; r=static_cast<int*>(p); std::cout << *r << std::endl; } I understand that there would be problems converting between a double and an int, but why is there a problem converting between a double* and an int*?
Aside from being pointers, double* and int* have nothing in common. You could say the same thing for Foo* and Bar* pointer types to any dissimilar structures. static_cast means that a pointer of the source type can be used as a pointer of the destination type, which requires a subtype relationship.
2,473,665
2,473,722
window c++ : how to timeout receiveFrom function in a udp based conversation
I am trying to create a reliable service on top of UDP. Here i need to timeout receiveFrom function of window c++ if not packet arrives in specified time. In java i do this DatagramSocket.setSoTimeout but i dont know how to achieve this in windows c++. thanks
Take a look at setsockopt() specifically SO_RCVTIMEO.
2,473,799
2,473,857
GDI+ double buffering in C++
I haven't written anything with GDI for a while now (and never with GDI+), and I'm just working on a fun project, but for the life of me, I can't figure out how to double buffer GDI+ void DrawStuff(HWND hWnd) { HDC hdc; HDC hdcBuffer; PAINTSTRUCT ps; hdc = BeginPaint(hWnd, &ps); hdcBuffer = CreateCompatibleDC(hdc); Graphics graphics(hdc); graphics.Clear(Color::Black); // drawing stuff, i.e. bunnies: Image bunny(L"bunny.gif"); graphics.DrawImage(&bunny, 0, 0, bunny.GetWidth(), bunny.GetHeight()); BitBlt(hdc, 0,0, WIDTH , HEIGHT, hdcBuffer, 0,0, SRCCOPY); EndPaint(hWnd, &ps); } The above works (everything renders perfectly), but it flickers. If I change Graphics graphics(hdc); to Graphics graphics(hdcBuffer);, I see nothing (although I should be bitblt'ing the buffer->hWnd hdc at the bottom). My message pipeline is set up properly (WM_PAINT calls DrawStuff), and I'm forcing a WM_PAINT message every program loop by calling RedrawWindow(window, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW); I'm probably going about the wrong way to do this, any ideas? The MSDN documentation is cryptic at best.
CreateCompatibleDC(hdc) creates a DC with a 1x1 pixel monochrome bitmap as its drawing surface. You need to also CreateCompatibleBitmap and select that bitmap into the hdcBuffer if you want a drawing surface larger than that. Edit: the flickering is being caused by WM_ERASEBKGND, when you do this hdc = BeginPaint(hWnd, &ps); Inside the call to BeginPaint, Windows sends your WndProc a WM_ERASEBKGND message if it thinks the background needs to be redrawn, if you don't handle that message, then DefWindowProc handles it by filling the paint rectangle with your class brush, so to avoid the flickering, you should handle it and return TRUE. case WM_ERASEBKGND: return TRUE; // tell Windows that we handled it. (but don't actually draw anything) Windows thinks your background should be erased because you tell it that it should, that's what RDW_ERASE means, so you should probably leave that out of your RedrawWindow call
2,474,006
2,474,013
new[n] and delete every location with delete instead the whole chunk with delete[]
Is this valid C++ (e.g. not invoking UB) and does it achieve what I want without leaking memory? valgrinds complains about mismatching free and delete but says "no leaks are possible" in the end. int main() { int* a = new int[5]; for(int i = 0; i < 5; ++i) a[i] = i; for(int i = 0; i < 5; ++i) delete &a[i]; } The reason I'm asking: I have a class that uses boost::intrusive::list and I new every object that is added to that list. Sometimes I know how many objects I want to add to the list and was thinking about using new[] to allocate a chunk and still be able to delete every object on its own with the Disposer-style of boost::intrusive.
No way. You cannot call delete on what was not allocated by new or you get heap corruption. You see, that array created by new[] didn't allocate n individual objects, but one array. The second object of the array is in the middle of the allocation block.
2,474,018
2,474,021
When does invoking a member function on a null instance result in undefined behavior?
Consider the following code: #include <iostream> struct foo { // (a): void bar() { std::cout << "gman was here" << std::endl; } // (b): void baz() { x = 5; } int x; }; int main() { foo* f = 0; f->bar(); // (a) f->baz(); // (b) } We expect (b) to crash, because there is no corresponding member x for the null pointer. In practice, (a) doesn't crash because the this pointer is never used. Because (b) dereferences the this pointer ((*this).x = 5;), and this is null, the program enters undefined behavior, as dereferencing null is always said to be undefined behavior. Does (a) result in undefined behavior? What about if both functions (and x) are static?
Both (a) and (b) result in undefined behavior. It's always undefined behavior to call a member function through a null pointer. If the function is static, it's technically undefined as well, but there's some dispute. The first thing to understand is why it's undefined behavior to dereference a null pointer. In C++03, there's actually a bit of ambiguity here. Although "dereferencing a null pointer results in undefined behavior" is mentioned in notes in both §1.9/4 and §8.3.2/4, it's never explicitly stated. (Notes are non-normative.) However, one can try to deduced it from §3.10/2: An lvalue refers to an object or function. When dereferencing, the result is an lvalue. A null pointer does not refer to an object, therefore when we use the lvalue we have undefined behavior. The problem is that the previous sentence is never stated, so what does it mean to "use" the lvalue? Just even generate it at all, or to use it in the more formal sense of perform lvalue-to-rvalue conversion? Regardless, it definitely cannot be converted to an rvalue (§4.1/1): If the object to which the lvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior. Here it's definitely undefined behavior. The ambiguity comes from whether or not it's undefined behavior to deference but not use the value from an invalid pointer (that is, get an lvalue but not convert it to an rvalue). If not, then int *i = 0; *i; &(*i); is well-defined. This is an active issue. So we have a strict "dereference a null pointer, get undefined behavior" view and a weak "use a dereferenced null pointer, get undefined behavior" view. Now we consider the question. Yes, (a) results in undefined behavior. In fact, if this is null then regardless of the contents of the function the result is undefined. This follows from §5.2.5/3: If E1 has the type “pointer to class X,” then the expression E1->E2 is converted to the equivalent form (*(E1)).E2; *(E1) will result in undefined behavior with a strict interpretation, and .E2 converts it to an rvalue, making it undefined behavior for the weak interpretation. It also follows that it's undefined behavior directly from (§9.3.1/1): If a nonstatic member function of a class X is called for an object that is not of type X, or of a type derived from X, the behavior is undefined. With static functions, the strict versus weak interpretation makes the difference. Strictly speaking, it is undefined: A static member may be referred to using the class member access syntax, in which case the object-expression is evaluated. That is, it's evaluated just as if it were non-static and we once again dereference a null pointer with (*(E1)).E2. However, because E1 is not used in a static member-function call, if we use the weak interpretation the call is well-defined. *(E1) results in an lvalue, the static function is resolved, *(E1) is discarded, and the function is called. There is no lvalue-to-rvalue conversion, so there's no undefined behavior. In C++0x, as of n3126, the ambiguity remains. For now, be safe: use the strict interpretation.
2,474,091
2,474,113
Why can I set an anonymous enum equal to another in C but not C++?
I have the following code snippet: enum { one } x; enum { two } y; x = y; That will compile in C, but in C++, I get the following error: test.c:6: error: cannot convert ‘main()::<anonymous enum>’ to ‘main()::<anonymous enum>’ in assignment Can someone explain to me why this is happening? I would prefer an answer with some specifics about why the compiler behaves this way, rather than just "You can't do that"
Converting from one enum type to another goes via an integer type (probably the underlying type of the source, not sure). An implicit conversion from enum to an integer type is allowed in both C and C++. An implicit conversion from an integer type to enum is allowed in C, but not in C++. Basically, C++ is being more type safe. It's trying to stop you doing this: enum {zero, one, two} x; x = 143; // assigns a value outside the range of the enum If you want to perform this enum-enum conversion in C++, you could use typeof/declspec/boost typeof or equivalent. In GCC: int main() { enum {zero, one, two} x; enum {zero1, one1, two1} y = two1; typedef typeof(x) xtype; x = static_cast<typeof(x)>(y); } It doesn't normally make sense to do so, though. For most purposes, enums (and especially anonymous ones) are "enumerated types". They do just happen to be "implemented" by the C and C++ standards as integers wearing funny hats, but that doesn't mean that red is "equal to" hammer just because they each appear first in two different enums (colours and tools respectively). static_cast suggests that there's a relation between the two types involved. Any two enum types are "related" by the fact that both have an underlying integer type, and those are related, so the "relation" there really doesn't say much. If you write this code you're getting a pretty poor version of type safety.
2,474,121
2,474,142
Is it possible to use the .NET version of TeeChart with C++?
TeeChart .NET is a 100% managed C#.NET Charting Control. Would it still be possible to use the .NET version of the charting control with Visual C++? I'm contemplating changing IDEs from Codegear to Visual Studio, so the legacy C++ code is obviously not C++/CLI
Visual C++/CLI ? Create a DLL on VC++/CLI and link dynamically with your main VC++/non-CLI project
2,474,190
2,474,264
C++ find method is not const?
I've written a method that I'd like to declare as const, but the compiler complains. I traced through and found that this part of the method was causing the difficulty: bool ClassA::MethodA(int x) { bool y = false; if(find(myList.begin(), myList.end(), x) != myList.end()) { y = true; } return y; } There is more happening in the method than that, but with everything else stripped away, this was the part that didn't allow the method to be const. Why does the stl find algorithm prevent the method from being const? Does it change the list in any way?
If myList is an object of a custom container type, you could have a problem if its begin() and end() methods don't have a const overload. Also, assuming perhaps the type of x isn't really int in your code, are you sure there's an equality operator that can operate on a const member of that type?
2,474,282
2,474,299
C++ a class with an array of structs, without knowing how large an array I need
I have a class with fields like firstname, age, school etc. I need to be able to store other information like for instance, where they have travelled, and what year it was in. I cannot declare another class specifically to hold travelDestination and what year, so I think a struct might be best. This is just an example: struct travel { string travelDest; string year; }; The issue is people are likely to have travelled different amounts. I was thinking of just having an array of travel structs to hold the data. But how do I create a fixed sized array to hold them, without knowing how big I need it to be? Perhaps I am going about this the completely wrong way, so any suggestions as to a better way would be appreciated. I realise there is essentially no difference between a class and struct, but for the purposes of assignment criteria I am not allowed a "class", so yeah.
You could try associating a std::vector with each person, with each entry in the vector containing a struct: typedef struct travel { string travelDest; string year; } travelRecord; std::vector<travelRecord> travelInfo; You can then add items to the vector as you see fit: travelRecord newRecord1 = {"Jamaica", "2010"}; travelInfo.push_back(newRecord1); travelRecord newRecord2 = {"New York", "2011"}; travelInfo.push_back(newRecord2); Some more information about vector operations can be found here.
2,474,384
2,474,403
C++ typename of member variable
Is it possible to get typename of a member variable? For example: struct C { int value ; }; typedef typeof(C::value) type; // something like that? Thanks
Not in C++03. C++0x introduces decltype: typedef decltype(C::value) type; Some compilers have a typeof extension, though: typedef typeof(C::value) type; // gcc If you're okay with Boost, they have a library for it: typedef BOOST_TYPEOF(C::value) type;
2,474,429
2,474,436
Does throw inside a catch ellipsis (...) rethrow the original error in C++?
If in my code I have the following snippet: try { doSomething(); } catch (...) { doSomethingElse(); throw; } Will the throw rethrow the specific exception caught by the default ellipsis handler?
Yes. The exception is active until it's caught, where it becomes inactive. But it lives until the scope of the handler ends. From the standard, emphasis mine: §15.1/4: The memory for the temporary copy of the exception being thrown is allocated in an unspecified way, except as noted in 3.7.4.1. The temporary persists as long as there is a handler being executed for that exception. That is: catch(...) { // <-- /* ... */ } // <-- Between those arrows, you can re-throw the exception. Only when the handlers scope ends does the exception cease to exist. In fact, in §15.1/6 the example given is nearly the same as your code: try { // ... } catch (...) { // catch all exceptions // respond (partially) to exception <-- ! :D throw; //pass the exception to some // other handler } Keep in mind if you throw without an active exception, terminate will be called. This cannot be the case for you, being in a handler. If doSomethingElse() throws and the exception has no corresponding handler, because the original exception is considered handled the new exception will replace it. (As if it had just thrown, begins stack unwinding, etc.) That is: void doSomethingElse(void) { try { throw "this is fine"; } catch(...) { // the previous exception dies, back to // using the original exception } try { // rethrow the exception that was // active when doSomethingElse was called throw; } catch (...) { throw; // and let it go again } throw "this replaces the old exception"; // this new one takes over, begins stack unwinding // leaves the catch's scope, old exception is done living, // and now back to normal exception stuff } try { throw "original exception"; } catch (...) { doSomethingElse(); throw; // this won't actually be reached, // the new exception has begun propagating } Of course if nothing throws, throw; will be reached and you'll throw your caught exception as expected.
2,474,432
2,474,558
System of linear equations in C++?
I need to solve a system of linear equations in my program. Is there a simple linear algebra library for C++, preferably comprised of no more than a few headers? I've been looking for nearly an hour, and all the ones I found require messing around with Linux, compiling DLLs in MinGW, etc. etc. etc. (I'm using Visual Studio 2008.)
I think Eigen is what you're looking for. http://eigen.tuxfamily.org/index.php?title=Main_Page It is a headers only library and compiles on many compilers. It even uses exotic assembly for faster math. This is the page that shows off the linear solver api. http://eigen.tuxfamily.org/dox-2.0/TutorialAdvancedLinearAlgebra.html It has a few solvers with a simple api.
2,474,434
2,474,452
What are the main benefits of implementing a virtual machine as part of an application?
Several databases I've been looking at recently implement a virtual machine internally to perform the respective data reads and writes. For an example, check out this article on SQLite's virtual machine they call the 'VDBE'. I'm curious as to what the benefits of such an architecture are. I would assume performance is one but why would a virtual machine like this run faster? In fact, it seems to be that this extra layer could cause it to run slower. So perhaps it's for security? Or portability? Anyway, just curious about this.
They do their stuff at the "assembly-like" level, where you gain acceptable speed without losing portability. I think they provide a virtual machine so they get a balanced trade off. Either you execute the high level code(SQL code**) as a high level language and you lose speed but you gain convenience. The other way is to produce Platform-Specific(Native) code which is going to run much faster compared to the interpreted but it is a lot of hassle for a wide-spread library which runs where ANSI-C exists. ** It doesn't have to be SQL-code of course. I think that an imperative representation is much better suited for execution. Anyway, that representation still is a very high level representation compared to "opcode".
2,474,548
2,474,631
Why does my finite state machine take so long to execute?
I'm working on a state machine which is supposed to extract function calls of the form /* I am a comment */ //I am a comment pref("this.is.a.string.which\"can have QUOTES\"", 123456); where the extracted data would be pref("this.is.a.string.which\"can have QUOTES\"", 123456); from a file. Currently, to process a 41kb file, this process is taking close to a minute and a half. Is there something I'm seriously misunderstanding here about this finite state machine? #include <boost/algorithm/string.hpp> std::vector<std::string> Foo() { std::string fileData; //Fill filedata with the contents of a file std::vector<std::string> results; std::string::iterator begin = fileData.begin(); std::string::iterator end = fileData.end(); std::string::iterator stateZeroFoundLocation = fileData.begin(); std::size_t state = 0; for(; begin < end; begin++) { switch (state) { case 0: if (boost::starts_with(boost::make_iterator_range(begin, end), "pref(")) { stateZeroFoundLocation = begin; begin += 4; state = 2; } else if (*begin == '/') state = 1; break; case 1: state = 0; switch (*begin) { case '*': begin = boost::find_first(boost::make_iterator_range(begin, end), "*/").end(); break; case '/': begin = std::find(begin, end, L'\n'); } break; case 2: if (*begin == '"') state = 3; break; case 3: switch(*begin) { case '\\': state = 4; break; case '"': state = 5; } break; case 4: state = 3; break; case 5: if (*begin == ',') state = 6; break; case 6: if (*begin != ' ') state = 7; break; case 7: switch(*begin) { case '"': state = 8; break; default: state = 10; break; } break; case 8: switch(*begin) { case '\\': state = 9; break; case '"': state = 10; } break; case 9: state = 8; break; case 10: if (*begin == ')') state = 11; break; case 11: if (*begin == ';') state = 12; break; case 12: state = 0; results.push_back(std::string(stateZeroFoundLocation, begin)); }; } return results; } Billy3 EDIT: Well this is one of the strangest things I've ever seen. I just rebuilt the project and it's running reasonably again. Odd.
Unless your 41 kb file is mostly comments or prefs, it's going to spend most of its time in state 0. And for each character in state 0, you make a minimum of two function calls. if (boost::starts_with(boost::make_iterator_range(begin, end), "pref(")) { You can speed this up by pre-testing to see if the current character is 'p' if (*begin == 'p' && boost::starts_with(boost::make_iterator_range(begin, end), "pref(")) { If the character isn't 'p' then there is no need to make any function calls. In particular not creating a iterator, which is probably where the time is being spent.
2,474,608
2,474,649
Asynchronous Completion Routines I/O, Pointer to routine encapsulated in class
I was wondering if there was anyway to use functions like ReadFileEx that require a pointer to a function in a class WITHOUT marking the function as static? Thanks in advance. SBP.
No, non-static class functions have an implied first argument (this) which is incompatible with their use as a callback for ReadFileEx etc.
2,474,756
2,474,770
Is It Safe to Cast Away volatile?
Most of the time, I am doing this way. class a { public: ~ a() { i = 100; // OK delete (int *)j; // Compiler happy. But, is it safe? // The following code will lead compilation error : delete j; } private: volatile int i; volatile int *j; }; int main() { a aa; } However, I saw an article here: https://www.securecoding.cert.org/confluence/display/seccode/EXP32-C.+Do+not+access+a+volatile+object+through+a+non-volatile+reference Casting away volatile allows access to an object through a non-volatile reference. This can result in undefined and perhaps unintended program behavior. So, what will be the workaround for my above code example? Here is the error message I get if I use delete j Note that, this is output from VC6 (Don't ask why I am using VC6!) c:\projects\a\a.cpp(5) : error C2664: 'delete' : cannot convert parameter 1 from 'volatile int *' to 'void *' Conversion loses qualifiers
Nothing. If you don't access the volatile memory, the semantics of volatile are unaffected. If you accessed volatile memory through a casted non-volatile pointer, the compiler might optimize the reference away. If the value had changed, you'd have the wrong value. For some value of wrong. ;-) The delete doesn't access the volatile memory, it just frees it. Sort of an uncommon thing to do with volatile memory.
2,474,994
2,475,219
C++ in embedded software programming
Is there significant problem, if I write the code for embedded linux system using C++ language programming ?. Actually, I have intention to port some code to arm linux, with arm-uclibc compiler. Thanks
Are you asking about plain C++ or embedded C++? As I understand it, embedded C++ is pretty much dead. You can program in C++, but, depending on your requirements, there may be some constructs that you will want to avoid using. For example, if you don't have much space, you may want to avoid templates as much as possible (or to explicitly instantiate templates) to keep your template instantiations to a minimum. You might also want to avoid exceptions or RTTI to reduce the amount of generated type information (to save space) and also to avoid having to deal with exception safety (to keep potential pitfalls to a minimum) as well as the high cost of exception propagation (to shorten the longest execution path, for real time systems). Virtual functions should be OK (they don't introduce that much overhead), but if you have very strict requirements, you may also need to limit your use of those. If you do use exceptions, you should also be sure that the compiler supports them (as many cross-compilers for embedded systems do not).
2,475,138
2,475,621
right usage of std::uncaught_exception in a destructor
There are some articles concluding "never throw an exception from a destructor", and "std::uncaught_exception() is not useful", for example: http://www.gotw.ca/gotw/047.htm (written by Herb Sutter) But it seems that I am not getting the point. So I wrote a small testing example (see below). Since everything is fine with the testing example I would very appreciate some comments regarding what might be wrong with it ? testing results: ./main Foo::~Foo(): caught exception - but have pending exception - ignoring int main(int, char**): caught exception: from int Foo::bar(int) ./main 1 Foo::~Foo(): caught exception - but *no* exception is pending - rethrowing int main(int, char**): caught exception: from Foo::~Foo() example: // file main.cpp // build with e.g. "make main" // tested successfully on Ubuntu-Karmic with g++ v4.4.1 #include <iostream> class Foo { public: int bar(int i) { if (0 == i) throw(std::string("from ") + __PRETTY_FUNCTION__); else return i+1; } ~Foo() { bool exc_pending=std::uncaught_exception(); try { bar(0); } catch (const std::string &e) { // ensure that no new exception has been created in the meantime if (std::uncaught_exception()) exc_pending = true; if (exc_pending) { std::cerr << __PRETTY_FUNCTION__ << ": caught exception - but have pending exception - ignoring" << std::endl; } else { std::cerr << __PRETTY_FUNCTION__ << ": caught exception - but *no* exception is pending - rethrowing" << std::endl; throw(std::string("from ") + __PRETTY_FUNCTION__); } } } }; int main(int argc, char** argv) { try { Foo f; // will throw an exception in Foo::bar() if no arguments given. Otherwise // an exception from Foo::~Foo() is thrown. f.bar(argc-1); } catch (const std::string &e) { std::cerr << __PRETTY_FUNCTION__ << ": caught exception: " << e << std::endl; } return 0; } ADDED: In other words: despite of the warnings in some articles it works as expected - so what might be wrong with it?
There's nothing technically wrong with your code. It's perfectly safe in that you will never accidentally terminate because you threw an exception when it was not safe to. The issue is that it also is not useful, in that it will occasionally also not throw an exception when it is safe to. Your destructor's documentation basically has to say "this might or might not throw an exception." If it occasionally won't throw an exception, you might as well never throw an exception. That way, you're at least consistent.
2,475,614
2,477,203
VC++ libcurl .lib size
I'm having an issue with the size of the .lib when I compile libcurl. It's 1.6 MB and the sample program they have is alround 300 KB. I downloaded the latest version (curl-7.20.0) and opened the project file from the lib directory in visual studio 2008. In the project properties I set /MT and compiled a release build. I even tried adding HTTP_ONLY to the processor which didn't seem to affect anything. What's going on?
Turn off Whole Program Optimization to keep the size reasonable. Project + Properties, C/C++, Optimization.
2,475,642
2,475,677
How to achieve the following C++ output formatting?
I wish to print out double as the following rules : 1) No scietific notation 2) Maximum decimal point is 3 3) No trailing 0. For example : 0.01 formated to "0.01" 2.123411 formatted to "2.123" 2.11 formatted to "2.11" 2.1 formatted to "2.1" 0 formatted to "0" By using .precision(3) and std::fixed, I can only achieve rule 1) and rule 2), but not rule 3) 0.01 formated to "0.010" 2.123411 formatted to "2.123" 2.11 formatted to "2.110" 2.1 formatted to "2.100" 0 formatted to "0" Code example is as bellow : #include <iostream> int main() { std::cout.precision(3); std::cout << std::fixed << 0.01 << std::endl; std::cout << std::fixed << 2.123411 << std::endl; std::cout << std::fixed << 2.11 << std::endl; std::cout << std::fixed << 2.1 << std::endl; std::cout << std::fixed << 0 << std::endl; getchar(); } any idea?
You cannot do this with the iostream library's built-in formatting. Additionally, you don't need to apply fixed on every output because it is not reset. You can write your own manipulator to do it: struct MyFormatter { int precision; double value; MyFormatter(int precision, double value) : precision(precision), value(value) {} friend std::ostream& operator<<(std::ostream& s, MyFormatter const& v) { std::stringstream ss; ss << std::set_precision(v.precision) << std::fixed << v.value; std::string str; ss.str().swap(str); str.resize(str.find_last_not_of("0") + 1); if (str[str.length() - 1] == '.') str.resize(str.length() - 1); s << str; return s; } }; struct MyFormat { int precision; MyFormat(int precision) : precision(precision) {} MyFormatter operator()(double value) const { return MyFormatter(precision, value); } }; int main() { MyFormat f(3); std::cout << f(0) << ' ' << f(0.1) << ' ' << f(0.12345) << '\n'; return 0; }
2,475,657
2,475,688
Overloaded function called with one parameter, but I thought I'd passed two
I recently refactored code like this (MyClass to MyClassR). #include <iostream> class SomeMember { public: double m_value; SomeMember() : m_value(0) {} SomeMember(int a) : m_value(a) {} SomeMember(int a, int b) : m_value(static_cast<double>(a) / 3.14159 + static_cast<double>(b) / 2.71828) {} }; class MyClass { public: SomeMember m_first, m_second, m_third; MyClass(const bool isUp, const int x, const int y) { if (isUp) { m_first = SomeMember(x); m_second = SomeMember(y); m_third = SomeMember(x, y); } else { m_first = SomeMember(y); m_second = SomeMember(x); m_third = SomeMember(y, x); } } }; class MyClassR { public: SomeMember m_first, m_second, m_third; MyClassR(const bool isUp, const int x, const int y) : m_first(isUp ? x : y) , m_second(isUp ? y : x) , m_third(isUp ? x, y : y, x) { } }; int main() { MyClass a(true, 1, 2); MyClassR b(true, 1, 2); using namespace std; cout.precision(10); cout << "a:" << endl << "\tfirst: " << a.m_first.m_value << "\tsecond: " << a.m_second.m_value << "\tthird: " << a.m_third.m_value << endl; cout << "b:" << endl << "\tfirst: " << b.m_first.m_value << "\tsecond: " << b.m_second.m_value << "\tthird: " << b.m_third.m_value << endl; return 0; } What is the error, why does it compile (tested with VC6 as well as VC9 warning level 4: no complaints) and what is the right way of doing it? I (assume) I already have all these answers but I think it's and interesting problem to share. Update Extended code so it's "copy & paste & execute"-able. VC9 gave me no complaints either so VC6 is not the problem here. For completeness, the output is: a: first: 1 second: 2 third: 1.054069532 b: first: 1 second: 2 third: 1.004499999
I’m not sure what exactly you expect but let’s start … First off, ditch VC6. Seriously. Using it is a huge problem since it’s just not standards conforming and precludes a lot of options. Using it correctly is like playing Russian roulette. Your constructor of m_third doesn’t do what you think it does. You cannot write a conditional expression like this: “several parameters” is not a valid expression in C++, and the conditional operator works on expressions. The code compiles because it’s still correct, it just doesn’t do what you want it to. Instead of using “several parameters”, it evaluates the sequence point operator (,) which just takes the last value of the expression, so your conditional is effectively equivalent to: isUp ? y : x The right way is to use two conditionals: m_third(isUp ? x : y, isUp ? y : x) The third constructor of SomeMember is wrong, the value may overflow, yielding a negative value – I highly doubt that that’s what you want.
2,475,686
2,475,724
Accessing program information that gdb sees in C++
I have a program written in C++, on Linux, compiled with -g. When I run it under gdb, I can 1) set breakpoints 2) at those breakpoints, print out variables 3) see the stackframe 4) given a variable that's a structure, print out parts of the structure (i.e. how ddd displays information). Now, given that my program is compiled with "-g" -- is there anyway that I can access this power within my program itself? I.e. given that my program is compiled with "-g", is there some std::vector<string> getStackFrame(); function I can call to get the current stackframe at the current point of execution? Given a pointer to an object and it's type ... can I do std::vector getClassMember(class_name); ? I realize the default answer is "no, C++ doesn't support that level of introspection" -- however, recall I'm on linux, my program is compiled with "-g", and gdb can do it, so clearly the inforamtion is there. Question is: is there some API for accessing it? EDIT: PS Naysers, I'd love to see a reason for closing this question.
The debugging format is called dwarf. This should give you hint where to search further. Library to read ELF file DWARF debug information
2,475,794
2,476,875
Symbol exporting problem using __declspec(dllexport)
I use __declspec(dllexport) with several methods in a library. But one of the symbols do not get exported properly. The value in question is called "restart". I've given the output from dumpbin.exe, below: 1 0 0002DB27 ev_err = @ILT+2850(_ev_err) 2 1 0002DADC m_foutput = @ILT+2775(_m_foutput) 3 2 0002D361 m_free = @ILT+860(_m_free) 4 3 0002D505 m_free_vars = @ILT+1280(_m_free_vars) 5 4 0002D055 m_get = @ILT+80(_m_get) 6 5 0002D95B m_ident = @ILT+2390(_m_ident) 7 6 0002D80C m_inverse = @ILT+2055(_m_inverse) 8 7 0002D0F5 m_mlt = @ILT+240(_m_mlt) 9 8 0002D339 m_ones = @ILT+820(_m_ones) 10 9 0002D43D m_rand = @ILT+1080(_m_rand) 11 A 0002DC3F m_resize = @ILT+3130(_m_resize) 12 B 0002D465 m_zero = @ILT+1120(_m_zero) 13 C 0002D3A7 px_foutput = @ILT+930(_px_foutput) 14 D 0002DA2D px_free = @ILT+2600(_px_free) 15 E 00092DE0 restart = _restart 16 F 0002DB45 set_err_flag = @ILT+2880(_set_err_flag) 17 10 0002D550 v_foutput = @ILT+1355(_v_foutput) 18 11 0002D839 v_free = @ILT+2100(_v_free) This seems to indicate that restart did not get exported properly but I can't figure out why. I use the following line to export the variable: extern __declspec(dllexport) jmp_buf restart; What is the reason for this anomaly and how can I resolve it?
It is because your "restart" identifier is data, not code. It probably should have been named "restart_state". Exporting data from a DLL is a supported scenario but a good way to blow your foot off. The client code has to have strict binary compatibility with the DLL code. That's a very questionable proposition for setjmp(), the saved state is highly implementation dependent. You are much better off exporting functions that make the setjmp() and longjmp() calls and keep the jmp_buf private.
2,475,818
2,476,176
How to generate boost uuid from string at compile time
is there a way to generate a boost uuid from a string like 988A00C4-79F3-46f9-98CD-D5AD4AA2A0FE at compile time?
No, because there is no processing of string literals at compile time in C++. Depending on what you need and where you get the string from, you could use a pre-build-step that directly puts it into some aggregate initializer form or something that you can process at compile time (i.e. compile-time lists of characters).
2,475,870
2,475,905
Misunderstanding function pointer - passing it as an argument
I want to pass a member function of class A to class B via a function pointer as argument. Please advise whether this road is leading somewhere and help me fill the pothole. #include <iostream> using namespace std; class A{ public: int dosomeA(int x){ cout<< "doing some A to "<<x <<endl; return(0); } }; class B{ public: B(int (*ptr)(int)){ptr(0);}; }; int main() { A a; int (*APtr)(int)=&A::dosomeA; B b(APtr); return 0; } This brilliant piece of code leaves me with the compiler error: cannot convert int (A::*)(int)' toint (*)(int)' in initialization Firstly I want it to compile. Secondly I don't want dosomeA to be STATIC.
Pointers to members are different from normal function pointers. As the compiler error indicates the type of &A::dosomeA is actually int (A::*)(int) and not int (*)(int). Inside B's constructor you need an instance of A to call the member on using one the .* or ->* operators. E.g' B(int(A::*ptr)(int)) { A atmp; (atmp.*ptr)(int); }
2,475,938
4,639,714
Accessing Firefox tab element in nsIWebProgressListener::OnStateChange using C++
I am developing extension for Firefox 3.0-3.5 versions using VS2008. I want to set attribute to a tab once the document load request completes within that tab window. So in OnStateChange method, I am checking for document load. I have used STATE_STOP & STATE_IS_DOCUMENT for it. I want to determine which tab window has been associated with particular document request. I have valid DOM Document pointer got from nsIWebProgress *aWebProgress which is 1st input parameter of OnStateChange. if ((aStateFlags & STATE_STOP) && (aStateFlags & STATE_IS_DOCUMENT)) { nsCOMPtr<nsIDOMWindow> domwin; nsCOMPtr<nsIDOMDocument> domDoc; aWebProgress->GetDOMWindow(getter_AddRefs(domwin)); domwin->GetDocument(getter_AddRefs(domDoc)); } I have tried to get nsIDOMDocumentXBL pointer by QIing nsIDOMDocument pointer(domDoc in my example) but it fails with Error code 0x80004002 (2147500034) i.e.NS_ERROR_NO_INTERFACE. How do I get the tab element corresponding to document load request. Could any one please help me? Thanks in Advance, Vaibhav D. Gade.
IF I understood the question correctly and you want a for a content window, you probably need https://developer.mozilla.org/en/Working_with_windows_in_chrome_code#Accessing_the_elements_of_the_top-level_document_from_a_child_window to get the chrome window, then run the implementation of gBrowser.getBrowserForDocument in the chrome window. You'd save yourself a lot of time if you stopped writing C++ and switched to JS for such things.
2,475,973
2,476,001
how to implement code completion in qt
i am writing an ide using qt (on c++) and i need to add auto completion feature to it so i want to know : how to do that (i am using qtPlainTextEdit) ? what the data structure i should use ?
I think you should take a look at this: http://qt-project.org/doc/qt-4.8/tools-customcompleter.html I used this example to understand CodeCompletion and I think it is fine :) [edit] Qt has a own class for such purpose called QCompleter: http://qt-project.org/doc/qt-4.8/qcompleter.html
2,476,031
2,476,517
How to test COM object integrity automatically?
Every COM object must have integrity. In simplified terms this means that if an object implements 3 interfaces - A, B and C and I have A* pointer to the object I must be able to successfully QueryInterface() both B and C and having B I must be able to retrieve A and C and having C I must be able to retrieve A and B. Now my object implements 5 interfaces and I want to test its integrity. Writing checks for all of the above myself will require a substantial effort. Is there a tool or some easily tweakable code or a code pattern that would do it?
I don't see the problem. If you implement A, B and C then interface A must QI properly for A, B, C and IUnknown. Including itself. The test is the same for all interfaces, you need only one small function that takes an IUnknown* argument.
2,476,205
2,476,222
Will the Windows service be 64-bit if installed from 64-bit process?
Just wondering, if I install a Windows service from 64-bit process (service code embedded in the process), is the service itself Win32 service or can services be 64-bit as well? I need to know this since my service would inject code (DLL-injection) to Win32-process, so due to WOW64 restrictions the service-process itself cannot be 64-bit.
64 bit. See... if the exe of the service is 32 bit, the service is 32 bit. if the exe of the service is 64 bit, the service runs 64 bit.
2,476,235
2,476,820
What are common uses of condition variables in C++?
I'm trying to learn about condition variables. I would like to know what are the common situations where condition variables are used. One example is in a blocking queue, where two threads access the queue - the producer thread pushes an item into the queue, while the consumer thread pops an item from the queue. If the queue is empty, the consumer thread is waiting until a signal is sent by the producer thread. What are other design situations where you need a condition variable to be used? I'd prefer examples based from experience though, such as those in real live applications.
One use of condition variables that's a bit more complicated than just a message queue, is to "share a lock", where different threads are waiting for subtly different conditions of the same basic nature. For instance, you have a (very shonky, simplified) web cache. Each entry in the cache has three possible states: not present, IN_PROGRESS, COMPLETE. getURL: lock the cache three cases for the key: not present: add it (IN_PROGRESS) release the lock fetch the URL take the lock update to COMPLETE and store the data broadcast the condition variable goto COMPLETE COMPLETE: release the lock and return the data IN_PROGRESS: while (still IN_PROGRESS): wait on the condition variable goto COMPLETE I have in practice used the pattern to implement a variant of the POSIX function pthread_once without any help from the scheduler. The reason I couldn't use a semaphore or lock per once_control, and just do the initialization under the lock, is that the function wasn't allowed to fail, and the once_control had only trivial initialization. For that matter, pthread_once itself has no defined error codes, so implementing it to possibly fail doesn't leave your caller with any good options... Of course with this pattern you have to be careful about scaling. Each time any initialization is completed, every waiting thread wakes up to grab the lock. So when you design the system you think very carefully about sharding, and then decide you can't be bothered doing anything to actually implement it until you see proven performance problems.
2,476,381
2,476,426
C++ Constructor initialization list strangeness
I have always been a good boy when writing my classes, prefixing all member variables with m_: class Test { int m_int1; int m_int2; public: Test(int int1, int int2) : m_int1(int1), m_int2(int2) {} }; int main() { Test t(10, 20); // Just an example } However, recently I forgot to do that and ended up writing: class Test { int int1; int int2; public: // Very questionable, but of course I meant to assign ::int1 to this->int1! Test(int int1, int int2) : int1(int1), int2(int2) {} }; Believe it or not, the code compiled with no errors/warnings and the assignments took place correctly! It was only when doing the final check before checking in my code when I realised what I had done. My question is: why did my code compile? Is something like that allowed in the C++ standard, or is it simply a case of the compiler being clever? In case you were wondering, I was using Visual Studio 2008
Yes, it's valid. The names in the member initializer list are looked up in the context of the constructor's class so int1 finds the name of member variable. The initializer expression is looked up in the context of the constructor itself so int1 finds the parameter which masks the member variables.
2,476,425
2,477,023
C++/STL: std::transform with given stride?
I have a 1d array containing Nd data, I would like to effectively traverse on it with std::transform or std::for_each. unigned int nelems; unsigned int stride=3;// we are going to have 3D points float *pP;// this will keep xyzxyzxyz... Load(pP); std::transform(pP, pP+nelems, strMover<float>(pP, stride));//How to define the strMover??
Well, I have decided to use for_each instead of transform any other decisions are welcome: generator<unsigned int> gen(0, 1); vector<unsigned int> idx(m_nelem);//make an index std::generate(idx.begin(), idx.end(),gen); std::for_each(idx.begin(), idx.end(), strMover<float>(&pPOS[0],&m_COM[0],stride)); where template<class T> T op_sum (T i, T j) { return i+j; } template<class T> class strMover { T *pP_; T *pMove_; unsigned int stride_; public: strMover(T *pP,T *pMove, unsigned int stride):pP_(pP), pMove_(pMove),stride_(stride) {} void operator() ( const unsigned int ip ) { std::transform(&pP_[ip*stride_], &pP_[ip*stride_]+stride_, pMove_, &pP_[ip*stride_], op_sum<T>); } }; From first look this is a thread safe solution.
2,476,432
2,477,389
Storing expression template functors
at the moment I'm really interested in expression templates and want to code a library for writing and differentiating mathematical functions with a lambda-style syntax. At the moment, I'm able to write (_x * _x)(2); and get the correct result 4. But I would really like to do something like MathFunction f = _x * _x; f(2);, but I don't have any ideas on how to cope with the recursive expression templates on the right side. Is it possible to achieve this without using the 'auto'-Keyword instead of MathFunction or having to make the operator() virtual? Thanks for your help!
As I'm a newbie to this site, I have found this not until I submitted this question. Thanks for your answers, but this is what I was really looking for.
2,476,724
2,476,777
Any implementations of C++0x out there?
Other than Microsoft's upcoming VC10?
here is a good breakdown of c++0x support in several major compilers
2,476,748
2,476,806
Writing 'bits' to C++ file streams
How can I write 'one bit' into a file stream or file structure each time? Is it possible to write to a queue and then flush it? Is it possible with C# or Java? This was needed when trying to implement an instance of Huffman coding. I can't write bits into files, so write them to a bitset and then (when compression was completed) write 8-bit piece of it each time (exclude last one).
Buffering the individual bits until you've accumulated a whole byte seems like a good idea: byte b; int s; void WriteBit(bool x) { b |= (x ? 1 : 0) << s; s++; if (s == 8) { WriteByte(b); b = 0; s = 0; } } You just have to deal with the case when the number of bits to be written is not a multiple of eight.
2,477,053
2,477,116
How do I get an Iterator over a vector of objects from a Template?
I'm busy implementing a Graph ADT in C++. I have templates for the Edges and the Vertices. At each Vertex I have a vector containing pointers to the Edges that are incident to it. Now I'm trying to get an iterator over those edges. These are the lines of code: vector<Edge<edgeDecor, vertexDecor, dir>*> edges = this->incidentEdges(); vector<Edge<edgeDecor, vertexDecor, dir>*>::const_iterator i; for (i = edges.begin(); i != edges.end(); ++i) { However, the compiler won't accept the middle line. I'm pretty new to C++. Am I missing something? Why can't I declare an iterator over objects from the Edge template? The compiler isn't giving any useful feedback. Much thanks niel
If that snippet comes from a template, you have probably run into the problem of dependent names - use typename: typename vector<Edge<edgeDecor, vertexDecor, dir>*>::const_iterator i; typename tells the compiler that you are referring to a type. Without it, dependent names are assumed to not be types or templates. For more details have a look at e.g. Comeaus template FAQ.
2,477,160
2,477,189
storing an integer constant other than zero in a pointer variable
int main() { int *d=0; printf("%d\n",*d); return 0; } this works fine. >cc legal.c > ./a.out 0 if i change the statement int *d=0; to int *d=1; i see the error. cc: "legal.c", line 6: error 1522: Cannot initialize a pointer with an integer constant other than zero. so its obvious that it will allow only zero.i want to know what happens inside the memory when we do this int *d=0 which is making it valid syntax. I am just asking this out of curiosity!
I'm surprised that you didn't get a SEGFAULT when you ran your code. The *d in the printf statement is dereferencing the pointer. To answer your question, though, C++ allows 0 to be given as a default initializer for any object, which is why it can be used to initialize the pointer to null (0 and null are identical). With the value of 1, you are asking the compiler to convert an integer to a pointer, which requires an explicit cast.
2,477,162
2,477,175
std::map and behavior of already inserted data
Does std::map move around already inserted values when inserting new data ?
The map is implemented as a tree, and when you insert a new element, the tree may need to be rebalanced. This does not invalidate any iterators or references to elements in the tree. This balancing is done via the manipulation of pointers, so you have nothing to worry about; the nodes themselves stay put. Balancing involves changing the structure of the tree by telling nodes who their children, parents, and siblings are via re-assigning pointers, but this is an implementation detail. Logically nothing has changed.
2,477,459
2,477,474
Segmentation fault before return
Why does the following code seg fault before returning: int main() { char iD[20]; memset (iD, 0, 20); char* prefix; srand (time(NULL) ); int iPrefix = rand()%1000000; sprintf(prefix, "%i", iPrefix); int len = strlen(prefix); char* staticChar = "123456789"; //set prefix into ID memcpy(iD, prefix, len); // append static value memcpy(iD+len, staticChar, 20-len); cout << "END " << endl; return 0; } At the minute, the cout will display, but I get a segmentation fault.
You need to allocate memory for prefix before calling this: sprintf(prefix, "%i", iPrefix); or you could refactor the code e.g., snprintf(iD, sizeof(iD), "%i%s", iPrefix, staticChar);
2,477,461
2,477,487
is const (c++) optional?
according to some tutorials i read a while back, the "const" declaration makes a variable "constant" ie it cannot change later. But i find this const declaration abit inconveniencing since the compiler sometimes gives errors like "cannot convert const int to int" or something like that. and i find myself cheating by removing it anyway. question: assuming that i am careful about not changing a variable in my source code, can i happily forget about this const stuff? Thanks in advance
Are you serious? Why would you want to give up on such a useful feature just because you make a mistake sometimes? Better try and learn to avoid mistakes with const and you benefit from the great assistance it adds to ensure correctnes with your code. Of course, you can say goodbye to all the help the language provides, and tell the compiler thereby not tell you about mistakes in your code anymore. Instead, you will have to ask the debugger later on where your bugs are. Not sure whether that's better.
2,477,486
2,492,813
How to manipulate a header and then continue with it in C#?
I want to replace an old ISAPI filter that ran on IIS6. This filter checks if the request is of a special kind, then manipulates the header and continues with the request. Two headers are added in the manipulating method that I need for calling another special ISAPI module. So I have ISAPI C++ code like: DWORD OnPreProc(HTTP_FILTER_CONTEXT *pfc, HTTP_FILTER_PREPROC_HEADERS *pHeaders) { if (ManipulateHeaderInSomeWay(pfc, pHeaders)) { return SF_STATUS_REQ_NEXT_NOTIFICATION; } return SF_STATUS_REQ_FINISHED; } I now want to rewrite this ISAPI filter as a managed module for the IIS7. So I have something like this: private void OnMapRequestHandler(HttpContext context) { ManipulateHeaderInSomeWay(context); } And now what? The request seems not to do what it should? I already wrote an IIS7 native module that implements the same method. But this method has a return value with which I can tell what to do next: REQUEST_NOTIFICATION_STATUS CMyModule::OnMapRequestHandler(IN IHttpContext *pHttpContext, OUT IMapHandlerProvider *pProvider) { if (DoSomething(pHttpContext)) { return RQ_NOTIFICATION_CONTINUE; } return RQ_NOTIFICATION_FINISH_REQUEST; } So is there a way to send my manipulated context again?
I finally found it. As I stated in the comments I add two headers to the request that are needed by my DLL that finally handles the request. The url header contains the path to the DLL. So I have to do a redirect to that DLL. This is done with the following code: private void OnMapRequestHandler(HttpContext context) { ManipulateHeaderInSomeWay(context); string url = context.Request.Header["url"]; // path of the DLL // now this is the important call! context.Server.TransferRequest(url, true); }
2,477,570
2,477,702
How to load an RSA key from binary data to an RSA structure using the OpenSSL C Library?
Currently I have my private key saved in a file, private.key, and I use the following function to load it: RSA *r = PEM_read_RSAPrivateKey("private.key", NULL, NULL, NULL); This works perfectly but I'm not happy with the file-based format; I want to save my key in pure binary form (ie, no base64 or similar) in a char* variable and load/save the key from/to it. This way I have much more freedom: I'll be able to store the key directly into the application const char key[] { 0x01, 0x02, ... };, send it over a network socket, etc. Unfortunately though I haven't found a way to do that. The only way to save and load a key I know of reads/saves it to a file directly.
Use d2i_RSAPrivateKey to load directly from a buffer containing binary DER format: const unsigned char *p = key; RSA *r = d2i_RSAPrivateKey(NULL, &p, keylen);
2,477,850
2,477,864
How to use string.substr() function?
I want to make a program that will read some number in string format and output it like this: if the number is 12345 it should then output 12 23 34 45 . I tried using the substr() function from the c++ string library, but it gives me strange results - it outputs 1 23 345 45 instead of the expected result. Why ? #include <iostream> #include <string> #include <cstdlib> using namespace std; int main(void) { string a; cin >> a; string b; int c; for(int i=0;i<a.size()-1;++i) { b = a.substr(i,i+1); c = atoi(b.c_str()); cout << c << " "; } cout << endl; return 0; }
If I am correct, the second parameter of substr() should be the length of the substring. How about b = a.substr(i,2); ?
2,477,951
2,478,045
Win32 API - Create Button help
I try to create 2 buttons inside my app case WM_CREATE:{ hWnd =CreateWindowEx(NULL, L"BUTTON", L"Giai PTB2", WS_TABSTOP|WS_VISIBLE| WS_CHILD|BS_DEFPUSHBUTTON, 100, 100, 100, 24, hWnd, (HMENU)IDC_PTB2_BUTTON, hInst, NULL); HWND hWndNew =CreateWindowEx(NULL, L"BUTTON", L"Tim max", WS_TABSTOP|WS_VISIBLE| WS_CHILD|BS_DEFPUSHBUTTON, 200, 200, 100, 100, hWnd, (HMENU)IDC_PTB2_BUTTON2, hInst, NULL); break; } The problem is , only "Giai PTB2" button shows :) Thanks first :)
check hWnd .. you are changing is value by the first create the side effect is that you are passing the first button as parent of the second ...
2,478,143
2,478,364
How can I find out how much memory an instance of a C++ class consumes?
I am developing a Graph-class, based on boost-graph-library. A Graph-object contains a boost-graph, so to say an adjacency_list, and a map. When monitoring the total memory usage of my program, it consumes quite a lot (checked with pmap). Now, I would like to know, how much of the memory is exactly consumed by a filled object of this Graph-class? With filled I mean when the adjacency_list is full of vertices and edges. I found out, that using sizeof() doesn't bring me far. Using valgrind is also not an alternative as there is quite some memory allocation done previously and this makes the usage of valgrind impractical for this purpose. I'm also not interested in what other parts of the program cost in memory, I want to focus on one single object. Thank you.
I have never used adjacency_list so this is just an idea which although works with STL containers. So using adjacency_list says BGL uses containers from the STL such as std::vector, std::list, and std::set to represent the set of vertices and the adjacency structure. OK, then you just have to give your adjacent list std::vector, std::list, and std::set which have their own allocator type. Adding your own allocator to STL containers is an easy task. Having done all this you just have to get from your allocators the size of memory that has been allocated while filling the adjacency_list. So the idea is to build the adjacent list out of STL containers (which seems possible after a quick look at the BGL documentaiton) which have own allocator types. Update 1 Actually you haven't told why you need to know how much bytes your graph consumes. If you just need to get this number only once you probably have to write you program with and without filling the graph. Then run for example UNIX95= ps -u $USER -o vsz,args and find out the difference. Roughly you will get the size of you graph. If you need to get this values regularly in your application and if you are not able to implement the whole solution using allocators you need to start with a few small steps. Read about allocators: C++ Standard Allocator, An Introduction and Implementation Allocators(STL) Try to implement std::vector with your own allocator as an exercise Try to add counting bytes to your allocator Try to build the Boost graph with allocator Customizing the Adjacency List Storage Do something to count bytes in std::string members of your containers. By default they will not use the allocator of their container. So either instead use fixed-size strings or manage somehow insert a container's allocator in this string members. Again, take a look at Adding your own allocator to STL containers By the way if you don't want to reinvent the C++ allocator you can just use something like that: template <typename T> class your_allocator { public: // here you need to put everything that is required by C++ standard // and calls finally send to std_allocator_ private: std::allocator<T> std_allocator_; };
2,478,151
2,478,167
Why is 'volatile' parasitic in C++?
Consider the following code: int main() { int i; volatile int* p = &i; int *v = p; return 0; } This gives an error in g++: $ g++ -o volatile volatile.cpp volatile.cpp: In function ‘int main()’: volatile.cpp:6: error: invalid conversion from ‘volatile int*’ to ‘int*’ My intention was that I want to make p volatile. However, once I've read the value of p, I don't care if accessing v is volatile. Why is it required that v be declared volatile? This is hypothetical code of course. In a real situation you could imagine that p points to a memory location, but is modified externally and I want v to point to the location that p pointed to at the time of v = p, even if later p is externally modified. Therefore p is volatile, but v is not. By the way I am interested in the behaviour both when this is considered C and C++, but in C this only generates a warning, not an error.
If you mean that the pointer should be volatile, rather than the object it points to, then declare it as int* volatile p;
2,478,397
2,478,746
Atomic swap in GNU C++
I want to verify that my understanding is correct. This kind of thing is tricky so I'm almost sure I am missing something. I have a program consisting of a real-time thread and a non-real-time thread. I want the non-RT thread to be able to swap a pointer to memory that is used by the RT thread. From the docs, my understanding is that this can be accomplished in g++ with: // global Data *rt_data; Data *swap_data(Data *new_data) { #ifdef __GNUC__ // Atomic pointer swap. Data *old_d = __sync_lock_test_and_set(&rt_data, new_data); #else // Non-atomic, cross your fingers. Data *old_d = rt_data; rt_data = new_data; #endif return old_d; } This is the only place in the program (other than initial setup) where rt_data is modified. When rt_data is used in the real-time context, it is copied to a local pointer. For old_d, later on when it is sure that the old memory is not used, it will be freed in the non-RT thread. Is this correct? Do I need volatile anywhere? Are there other synchronization primitives I should be calling? By the way I am doing this in C++, although I'm interested in whether the answer differs for C. Thanks ahead of time.
Generally don't use volatile when writing concurrent code in C/C++. The semantics of volatile are so close to what you want that it is tempting but in the end volatile is not enough. Unfortunately Java/C# volatile != C/C++ volatile. Herb Sutter has a great article explaining the confusing mess. What you really want is a memory fence. __sync_lock_test_and_set provides the fencing for you. You will also need a memory fence when you copy (load) the rt_data pointer to your local copy. Lock free programming is tricky. If you're willing to use Gcc's c++0x extensions, it's a bit easier: #include <cstdatomic> std::atomic<Data*> rt_data; Data* swap_data( Data* new_data ) { Data* old_data = rt_data.exchange(new_data); assert( old_data != new_data ); return old_data; } void use_data( ) { Data* local = rt_data.load(); /* ... */ }
2,478,717
2,478,732
Is it good practice to generally make heavyweight classes non-copyable?
I have a Shape class containing potentially many vertices, and I was contemplating making copy-constructor/copy-assignment private to prevent accidental needless copying of my heavyweight class (for example, passing by value instead of by reference). To make a copy of Shape, one would have to deliberately call a "clone" or "duplicate" method. Is this good practice? I wonder why STL containers don't use this approach, as I rarely want to pass them by value.
Restricting your users isn't always a good idea. Just documenting that copying may be expensive is enough. If a user really wants to copy, then using the native syntax of C++ by providing a copy constructor is a much cleaner approach. Therefore, I think the real answer depends on the context. Perhaps the real class you're writing (not the imaginary Shape) shouldn't be copied, perhaps it should. But as a general approach, I certainly can't say that one should discourage users from copying large objects by forcing them to use explicit method calls.
2,478,881
2,478,898
reading a file of unknown length with a function
I'm trying to write a short function that will let me quickly read in a file of unknown size and return pointer to the array of data and the length of that array but it seems my code isn't working. What am i doing wrong? int readIn(int* pointer, param parameters, string description) { string fileName = parameters.fileName + " " + description + ".bin"; ifstream readFile; readFile.open(fileName.c_str(), ios::in|ios::binary|ios::ate); int size = readFile.tellg(); int length = size / 4; int* output = new int [length]; readFile.seekg (0, ios::beg); readFile.read(reinterpret_cast<char*>(output), (size)); readFile.close(); pointer = output; // link new array with the pointer return length; } and in the main function: int* testList; int numEntries = readIn(testList, parameters, "test"); I end up with an error saying that my testList variable was used and not initialized. What am i doing wrong?
You aren't returning anything in your pointer variable after the function call. You can fill a variable so it's value remains changed after the function call by dereferencing it's address. Example: void fillX(int *p) { //p holds a memory address, go to that memory address and change its value *p = 4; } void main(int argc, char **argv) { int x; fillX(&x); return 0; assert(x == 4); } To change what a pointer points to you need to pass in a pointer to a pointer. I.e. you'd need to pass in the address of your pointer, and then you'd need the parameter type to be an int** pointer. When you set it you'd say *pointer = buffer; Example: void fillPointer(int **pp) { //p holds a memory address to a pointer //Go to that memory address and change its value *pp = new int[10]; } void main(int argc, char **argv) { int *x; fillPointer(&x); //x now points to the first element of an array delete[] x; return 0; } The key point here: When you want to change values via a parameter, you need to pass in it's address, then dereference it to set what's at that address.
2,478,928
2,479,000
RAII: Initializing data member in const method
In RAII, resources are not initialized until they are accessed. However, many access methods are declared constant. I need to call a mutable (non-const) function to initialize a data member. Example: Loading from a data base struct MyClass { int get_value(void) const; private: void load_from_database(void); // Loads the data member from database. int m_value; }; int MyClass :: get_value(void) const { static bool value_initialized(false); if (!value_initialized) { // The compiler complains about this call because // the method is non-const and called from a const // method. load_from_database(); } return m_value; } My primitive solution is to declare the data member as mutable. I would rather not do this, because it suggests that other methods can change the member. How would I cast the load_from_database() statement to get rid of the compiler errors?
This is not RAII. In RAII you would initialize it in the constructor, which would solve your problems. So, what you are using here is Lazy. Be it lazy initialization or lazy computation. If you don't use mutable, you are in for a world of hurt. Of course you could use a const_cast, but what if someone does: static const MyClass Examplar; And the compiler decides it is a good candidate for Read-Only memory ? Well, in this case the effects of the const_cast are undefined. At best, nothing happens. If you still wish to pursue the const_cast route, do it as R Samuel Klatchko do. If you thought over and think there is likely a better alternative, you can decide to wrap your variable. If it was in class of its own, with only 3 methods: get, set and load_from_database, then you would not worry about it being mutable.
2,478,933
2,478,951
Compilation failing - no #include - boost
I'm trying to compile a third-party library, but g++ is complaining about the following line: typedef boost::shared_ptr<MessageConsumer> MessageConsumerPtr; The strange thing is, there is no #include directive in the file - and it is clearly supposed to be this way; there are about 60 files with the same (or very similar) issues. Clearly if there was an #include directive referencing the relevant boost header this would compile cleanly. My question is: how can I get g++ to somehow automagically find the relevant symbol (in all instances of this issue, it is a namespace that can't be found - usually std:: or boost::) by either automatically processing the relevant header (or some other mechanism). Thanks. Edit My current g++ call looks like: g++ -fPIC -O3 -DUSING_PCH -D_REENTRANT -I/usr/include/boost -I./ -c MessageInterpreter.cpp -o MessageInterpreter.o
You can use the -include command line option: g++ -include boost/shared_ptr.hpp ... From the man page: -include file Process file as if "#include "file"" appeared as the first line of the primary source file. However, the first directory searched for file is the preprocessor's working directory instead of the directory containing the main source file. If not found there, it is searched for in the remainder of the "#include "..."" search chain as normal.
2,479,067
2,479,202
Why is the volatile qualifier used through out std::atomic?
From what I've read from Herb Sutter and others you would think that volatile and concurrent programming were completely orthogonal concepts, at least as far as C/C++ are concerned. However, in GCC implementation all of std::atomic's member functions have the volatile qualifier. The same is true in Anthony Williams's implementation of std::atomic. So what's deal, do my atomic<> variables need be volatile or not?
Why is the volatile qualifier used throughout std::atomic? So that volatile objects can also be atomic. See here: The relevant quote is The functions and operations are defined to work with volatile objects, so that variables that should be volatile can also be atomic. The volatile qualifier, however, is not required for atomicity. Do my atomic<> variables need to be volatile or not? No, atomic objects don't have to be volatile.
2,479,253
2,479,269
Which namespace does operator<< (stream) go to?
If I have have some overloaded ostream operators, defined for library local objects, is its okay for them to go to std namespace? If I do not declare them in std namespace, then I must use using ns:: operator <<. As a possible follow-up question, are there any operators which should go to standard or global namespace?
According to Koenig Lookup (C++ Standard 3.4.2) operator<< will be searched in namespaces of arguments. No need to declare it in std namespace.
2,479,393
2,495,733
MAPI_E_NOT_FOUND on OpenMsgStore
I'm trying to open the MessageStore of a user using MAPI. The weird thing is, when I run this a console application, while I'm logged with the user, everything works fine. But when I run this as a Windows Service I get MAPI_E_NOT_FOUND when trying to open the MessageStore. I already configured the service to run as the user. MapiLogonEx seems to work fine and GetMsgStoreTables also gives me the correct results (I verfied that the EntryID of the MessageStore is correct). Here's my code: LPMAPITABLE pStoresTbl = NULL; m_lpMAPISession->GetMsgStoresTable(0, &pStoresTbl); // Query Collumns LPSPropTagArray pTags = NULL; LPSRowSet pRows = NULL; pStoresTbl->SeekRow(BOOKMARK_BEGINNING,0,NULL); pStoresTbl->QueryRows( LONG_MAX, NULL, &pRows); LPSBinary lpEntryID = NULL; ULONG iprops; for (iprops = 0; iprops < pRows->aRow[0].cValues; iprops++) { SPropValue sProp = pRows->aRow[0].lpProps[iprops]; if (PROP_ID(sProp.ulPropTag) == PROP_ID(PR_ENTRYID)) { lpEntryID = &sProp.Value.bin; break; } } lpMDB = NULL; HRESULT hres = m_lpMAPISession->OpenMsgStore(NULL, lpEntryID->cb, (LPENTRYID) lpEntryID->lpb, NULL, MDB_NO_DIALOG | MDB_NO_MAIL | // spooler not notified of our presence MDB_TEMPORARY | // message store not added to MAPI profile MAPI_BEST_ACCESS, &lpMDB);
Is that an Exchange profile? Are you sure you are opening the primary mailbox rather than the PF store? Dmitry Streblechenko (MVP) http://www.dimastr.com/ OutlookSpy - Outlook, CDO and MAPI Developer Tool
2,479,459
2,587,331
Maximum length of a std::basic_string<_CharT> string
I was wondering how one can fix an upper limit for the length of a string (in C++) for a given platform. I scrutinized a lot of libraries, and most of them define it arbitrarily. The GNU C++ STL (the one with experimental C++0x features) has quite a definition: size_t npos = size_t(-1); /*!< The maximum value that can be stored in a variable of type size_t */ size_t _S_max_len = ((npos - sizeof(_Rep_base))/sizeof(_CharT) - 1) / 4; /*!< Where _CharT is a template parameter; _Rep_base is a structure which encapsulates the allocated memory */ Here's how I understand the formula: The size_t type must hold the count of units allocated to the string (where each unit is of type _CharT) Theoretically, the maximum value that a variable of type size_t can take on is the total number of units of 1 byte (ie, of type char) that may be allocated The previous value minus the overhead required to keep track of the allocated memory (_Rep_base) is therefore the maximum number of units in a string. Divide this value by sizeof(_CharT) as _CharT may require more than a byte Subtract 1 from the previous value to account for a terminating character Finally, that leave the division by 4. I have absolutely no idea why! I looked at a lot of places for an explanation, but couldn't find a satisfactory one anywhere (that's why I've been trying to make up something for it! Please correct me if I'm wrong!!).
The comments in basic_string.h from GCC 4.3.4 state: // The maximum number of individual char_type elements of an // individual string is determined by _S_max_size. This is the // value that will be returned by max_size(). (Whereas npos // is the maximum number of bytes the allocator can allocate.) // If one was to divvy up the theoretical largest size string, // with a terminating character and m _CharT elements, it'd // look like this: // npos = sizeof(_Rep) + (m * sizeof(_CharT)) + sizeof(_CharT) // Solving for m: // m = ((npos - sizeof(_Rep))/sizeof(CharT)) - 1 // In addition, this implementation quarters this amount. In particular, note the last line, "In addition, this implementation quarters this amount." I take that to mean that the division by four is in fact entirely arbitrary. I tried to find more information in the checkin log for basic_string.h, but it only goes back to October 5, 2000, and this comment was already present as shown in that revision, and I'm not familiar enough with that code base to know where the file might have lived in the source tree before it was moved to its current location.
2,479,576
2,479,618
What kind of bad things would happen if you write the whole class in a single file in C++?
In C# or Java, classes are declared and defined at the same time. In C++, the norm is to do that separately. What if we write the whole class in one , say .cpp, file and include that in files that references to it, what kinds of bad thing technically would happen besides a lengthened compilation process?
If your implementation of MyClass is all in the header file MyClass.h then any file you needed to implement MyClass will be included whenever someone includes MyClass.h. If you change any part of MyClass.h, even if it's trivial (such as adding a comment or even a space) then all files that include it will have to recompile, even if the interface hasn't changed. Neither of these matters for toy projects, but as you noted, when you have a program that consists of hundreds (or thousands, etc.) of class files, the added compilation time alone makes it worthwhile to separate out implementation from interface. For instance, if I have the following: // MyClass.h #include <iostream> #include <iomanip> #include <sstream> #include <string> #include "Inventory.h" class MyClass { public: MyClass(); void processInventory(Inventory& inventory) { // Do something with each item in the inventory here // that uses iostream, iomanip, sstream, and string } private: // ... }; It would more ideomatically be written as: // MyClass.h class Inventory; class MyClass { public: MyClass(); void processInventory(Inventory& inventory); private: // ... }; // MyClass.cc #include "MyClass.h" #include <iostream> #include <iomanip> #include <sstream> #include <string> #include "Inventory.h" MyClass()::MyClass() { } void MyClass()::processInventory(Inventory& inventory) { // Do something with each item in the inventory here // that uses iostream, iomanip, sstream, and string } Notice: Including MyClass.h doesn't mean iostream, iomanip, sstream, string, or Inventory.h have to be parsed. Changing how processInventory works doesn't mean all files using MyClass.h have to be recompiled. Notice how much easier it can be to figure out how to use MyClass now. Header files serve an important purpose: they show people how to use your class. With the modified MyClass.h it's easy to see the list of functions. If each function is defined in the header, then you can't look at just the list of functions. That makes it harder to figure out how to use the class.
2,479,591
2,487,915
What's the recommended implementation for hashing OLE Variants?
OLE Variants, as used by older versions of Visual Basic and pervasively in COM Automation, can store lots of different types: basic types like integers and floats, more complicated types like strings and arrays, and all the way up to IDispatch implementations and pointers in the form of ByRef variants. Variants are also weakly typed: they convert the value to another type without warning depending on which operator you apply and what the current types are of the values passed to the operator. For example, comparing two variants, one containing the integer 1 and another containing the string "1", for equality will return True. So assuming that I'm working with variants at the underlying data level (e.g. VARIANT in C++ or TVarData in Delphi - i.e. the big union of different possible values), how should I hash variants consistently so that they obey the right rules? Rules: Variants that hash unequally should compare as unequal, both in sorting and direct equality Variants that compare as equal for both sorting and direct equality should hash as equal It's OK if I have to use different sorting and direct comparison rules in order to make the hashing fit. The way I'm currently working is I'm normalizing the variants to strings (if they fit), and treating them as strings, otherwise I'm working with the variant data as if it was an opaque blob, and hashing and comparing its raw bytes. That has some limitations, of course: numbers 1..10 sort as [1, 10, 2, ... 9] etc. This is mildly annoying, but it is consistent and it is very little work. However, I do wonder if there is an accepted practice for this problem.
Hash codes of VARIANTS that are equal should be equal. Without knowing the equality and coercion rules that are used for testing equality, it is hard to come up with a proper implementation.
2,479,746
2,479,762
Loop on enumeration values
How awful is it - or is it perfectly acceptable - to index a loop on an enumeration? I have an enumeration defined. The values of the literals are default values. The assigned values do not have any significance, will not have any significance, and the values of any literals added in the future will also not have any significance. It's just defined to limit the allowed values and to make things easier to follow. Therefore the values will always start at 0 and increase by 1. Can I set up a loop like so: enum MyEnum { value1, value2, value3, maxValue } for(MyEnum i = value1; i < maxValue; i = static_cast<MyEnum>(i+1)){}
As far as I'm concerned, that's just fine. I'm sure some purist out there somewhere will freak out, but as far as the language spec is concerned, that code will work correctly, so you should feel free to go for it if it makes your life easier.
2,479,784
2,479,944
Exporting static data in a DLL
I have a DLL which contains a class with static members. I use __declspec(dllexport) in order to make use of this class's methods. But when I link it to another project and try to compile it, I get "unresolved external symbol" errors for the static data. e.g. In DLL, Test.h class __declspec(dllexport) Test{ protected: static int d; public: static void m(){int x = a;} } In DLL, Test.cpp #include "Test.h" int Test::d; In the application which uses Test, I call m(). I also tried using __declspec(dllexport) for each method separately but I still get the same link errors for the static members. If I check the DLL (the .lib) using dumpbin, I could see that the symbols have been exported. For instance, the app gives the following error at link time: 1>Main.obj : error LNK2001: unresolved external symbol "protected: static int CalcEngine::i_MatrixRow" (?i_MatrixRow@CalcEngine@@1HA) But the dumpbin of the .lib contains: Version : 0 Machine : 14C (x86) TimeDateStamp: 4BA3611A Fri Mar 19 17:03:46 2010 SizeOfData : 0000002C DLL name : CalcEngine.dll Symbol name : ?i_MatrixRow@CalcEngine@@1HA (protected: static int CalcEngine::i_MatrixRow) Type : data Name type : name Hint : 31 Name : ?i_MatrixRow@CalcEngine@@1HA I can't figure out how to solve this. What am I doing wrong? How can I get over these errors? P.S. The code was originally developed for Linux and the .so/binary combination works without a problem EDIT: In the given case, the static variables are not directly referred by the application but the method is inlined since it's in the header. I was able to resolve the link errors by moving the methods to the .cpp file.
In this thread at cprogramming.com it is suggested that a static variable is local to the dll and not exported. Summary of discussion below The static member is not accessed directly by code in the calling application, only through member functions of the class in the dll. However there are several inline functions accessing the static member. Those functions will be inline expanded into the calling applications code makeing the calling application access the static member directly. That will violate the finding referenced above that static variables are local to the dll and cannot be referenced from the calling application.
2,479,846
2,479,899
No "redefinition of default parameter error" for class template member function?
Why does the following give no compilation error?: // T.h template<class T> class X { public: void foo(int a = 42); }; // Main.cpp #include "T.h" #include <iostream> template<class T> void X<T>::foo(int a = 13) { std::cout << a << std::endl; } int main() { X<int> x; x.foo(); // prints 42 } It seems as though the 13 is just silently ignored by the compiler. Why is this? The cooky thing is that if the class template definition is in Main.cpp instead of a header file, I do indeed get the default parameter redefinition error. Now I know the compiler will complain about this if it were just an ordinary (non-template) function. What does the standard have to say about default parameters in class template member functions or function templates?
8.3.6 §6 The default arguments in a member function definition that appears outside of the class definition are added to the set of default arguments provided by the member function declaration in the class definition. [Example: class C { void f(int i = 3); void g(int i, int j = 99); }; void C::f(int i = 3) // error: default argument already { } // specified in class scope void C::g(int i = 88, int j) // in this translation unit, { } // C::g can be called with no argument --end example] According to the standard, it should give you an error.
2,479,983
2,480,027
What elegant solution exists for this pattern? Multi-Level Searching
Assume that we have multiple arrays of integers. You can consider each array as a level. We try to find a sequence of elements, exactly one element from each array, and proceed to the next array with the same predicate. For example, we have v1, v2, v3 as the arrays: v1 | v2 | v3 ----------------- 1 | 4 | 16 2 | 5 | 81 3 | 16 | 100 4 | 64 | 121 I could say that the predicate is: next_element == previous_element^2 A valid sequence from the above example is: 2 -> 4 -> 16 Actually, in this example there isn't another valid sequence. I could write three loops to brute-force the mentioned example, but what if the number of arrays is variable, but with know order of course, how would you solve this problem? Hints, or references to design patters are very appreciated. I shall do it in C++, but I just need the idea. Thanks,
If you order your arrays beforehand, the search can be done much faster. You could start on your smaller array, then binary-search for expected numbers on each of them. This would be O(nklogM), n being the size of the smallest array, k being the numbers of arrays, M being the size of larger array This could be done even faster if you use Hashmaps instead of arrays. This would let you search in O(n*k). If using reverse functions (to search in earlier arrays) is not an option, then you should start on first array, and n = size of first array. For simplicity, I'll start from first array //note the 1-based arrays for (i : 1 until allArrays[1].size()) { baseNumber = allArrays[1][i]; for (j: 2 until allArrays.size()) { expectedNumber = function(baseNumber); if (!find(expectedNumber, allArrays[j])) break; baseNumber = expectedNumber; } } You can probably do some null checks and add some booleans in there to know if the sequence exist or not
2,480,074
2,480,089
What's the boost way to create a functor that binds out an argument
I have need for a function pointer that takes two arguments and returns a string. I would like to pass an adapter that wraps a function that takes one argument, and returns the string (i.e. discard one of the arguments). I can trivially build my own adapter, that takes the 2 arguments, calls the wrapped function passing just the one argument through. But I'd much rather have a simple way to create an adapter on the fly, if there is an easy way to do so in C++/boost? Here's some details to make this a bit more concrete: typedef boost::function<CString (int,int)> TooltipTextFn; class MyCtrl { public: MyCtrl(TooltipTextFn callback = boost::bind(&MyCtrl::GetCellText, this, _1, _2)) : m_callback(callback) { } // QUESTION: how to trivially wrapper GetRowText to conform to TooltipTextFn by just discarding _2 ?! void UseRowText() { m_callback = boost::bind(&MyCtrl::GetRowText, this, _1, ??); } private: CString GetCellText(int row, int column); CString GetRowText(int row); TooltipTextFn m_callback; } Obviously, I can supply a member that adapts GetRowText to take two arguments and only passes the first to GetRowText() itself. But is there already a boost binder / adapter that lets me do that?
By only providing _1, it will ignore the 2nd parameter given to m_callback and call MyCtrl::GetRowText with one int parameter. void UseRowText() { m_callback = boost::bind(&MyCtrl::GetRowText, this, _1); } On the other hand, void UseRowText() { m_callback = boost::bind(&MyCtrl::GetRowText, this, _2); } is also valid, where we send the 2nd parameter passed to m_callback into the 1st parameter of MyCtrl::GetRowText.
2,480,322
2,480,582
nasm/yasm arguments, linkage to C++
I've got a question concerning nasm and its linkage to C++. I declare a litte test function as extern "C" void __cdecl myTest( byte i1, byte i2, int stride, int *width ); and I call it like this: byte i1 = 1, i2 = 2; int stride = 3, width = 4; myTest( i1, i2, stride, &width ); the method only serves to debug assembly and have a look at how the stack pointer is used to get the arguments. beyond that, the pointer arguments value shall be set to 7, to figure out how that works. This is implemented like this: global _myTest _myTest: mov eax, [esp+4] ; 1 mov ebx, [esp+8] ; 2 mov ecx, dword [esp+16] ; width mov edx, dword [esp+12] ; stride mov eax, dword [esp+16] mov dword [eax], 7 ret and compiled via yasm -f win32 -g cv8 -m x86 -o "$(IntDir)\$(InputName).obj" "$(InputPath)" , then linked to the c++ app. In debug mode, everything works fine. the function is called a couple of times and works as expected, whereas in release mode the function works once, but subsequent programm operations fail. It seems to me that something's wrong with stack/frame pointers, near/far, but I'm quite new to this subject and need a little help. thanks in advance! a.
Well, it seems that I have to preserve ebx via push/pop.
2,480,338
2,480,353
Purpose of front() and back() in assigning values in a Queue? (C++)
I have declared: queue<int, list<int> > Q After a series of calls: Q.push(37); Q.pop(); Q.push(19); Q.push(3); Q.push(13); Q.front(); Q.push(22); Q.push(8); Q.back(); I get: 19->3->13->22->8->NULL What I don't get is what the calls to Q.front() and Q.back() do. From what I understand, they return a reference to the first or last elements respectively, but I dont see how my list would be any different had those calls not been made. Do they have any effect? Sorry if this seems trivial, but I'm trying to figure out of those calls have a purpose, or of my professor is just trying to screw with me.
They give you a reference but if you want to do something with it then you have to use that reference. e.g. Q.push(37); Q.push(19); Q.front() = 8; Then you should have... 8,19 Merely calling Q.front() or Q.back() on their own line has no effect. These are generally referred to as accessor functions, they give you access to a value (which you can sometimes modify if you want) but don't themselves modify the underlying data structure.
2,480,502
2,480,515
C++ read registry string value in char*
I'm reading a registry value like this: char mydata[2048]; DWORD dataLength = sizeof(mydata); DWORD dwType = REG_SZ; ..... open key, etc ReqQueryValueEx(hKey, keyName, 0, &dwType, (BYTE*)mydata, &dataLength); My problem is, that after this, mydata content looks like: [63, 00, 3A, 00, 5C, 00...], i.e. this looks like a unicode?!?!. I need to convert this somehow to be a normal char array, without these [00], as they fail a simple logging function I have. I.e. if I call like this: WriteMessage(mydata), it outputs only "c", which is the first char in the registry. I have calls to this logging function all over the place, so I'd better of not modify it, but somehow "fix" the registry value. Here is the log function: void Logger::WriteMessage(const char *msg) { time_t now = time(0); struct tm* tm = localtime(&now); std::ofstream logFile; logFile.open(filename, std::ios::out | std::ios::app); if ( logFile.is_open() ) { logFile << tm->tm_mon << '/' << tm->tm_mday << '/' << tm->tm_year << ' '; logFile << tm->tm_hour << ':' << tm->tm_min << ':' << tm->tm_sec << "> "; logFile << msg << "\n"; logFile.close(); } }
Look at WideCharToMultiByte().
2,480,632
2,480,640
When virtual destructor is not needed even there is a virtual function, Why?
It says that if there is a virtual function, it is a good practice to have a virtual destructor. However, if the object is created on the stack but not on heap, do we still need to do that? Regards,
Strictly speaking no - the virtual destructor is only necessary if the object will be destroyed via a pointer to reference to a base object. If the static type at destruction time is the actual type of the object, then the correct dtor will be called regardless of whether it's virtual or not. But if a class has virtual functions, the reason for that is generally so that it can be accessed through a pointer or reference to one of the objects bases. If the object is going to be destroyed through that mechanism, then having a virtual dtor will ensure the correct one is called. And if you have a virtual function, making the dtor virtual comes at next to no cost.
2,480,659
2,480,694
Why does defined(X) not work in a preprocessor definition without a space?
A preprocessor definition that includes defined(X) will never evaluate to true, but (defined X) will. This occurs in MSVC9; I have not tested other preprocessors. A simple example: #define FEATURE0 1 #define FEATURE1 0 #define FEATURE2 1 #define FEATURE3 (FEATURE0 && !FEATURE1 && (defined(FEATURE2))) #define FEATURE4 (FEATURE0 && !FEATURE1 && (defined FEATURE2)) #define FEATURE5 (FEATURE0 && !FEATURE1 && (defined (FEATURE2))) #if FEATURE3 #pragma message("FEATURE3 Enabled") #elif (FEATURE0 && !FEATURE1 && (defined(FEATURE2))) #pragma message("FEATURE3 Enabled (Fallback)") #endif #if FEATURE4 #pragma message("FEATURE4 Enabled") #elif (FEATURE0 && !FEATURE1 && (defined FEATURE2)) #pragma message("FEATURE4 Enabled (Fallback)") #endif #if FEATURE5 #pragma message("FEATURE5 Enabled") #elif (FEATURE0 && !FEATURE1 && (defined (FEATURE2))) #pragma message("FEATURE5 Enabled (Fallback)") #endif The output from the compiler is: 1>FEATURE3 Enabled (Fallback) 1>FEATURE4 Enabled 1>FEATURE5 Enabled Working cases: defined (X), defined( X ), and defined X. Broken case: defined(X) Why is defined evaluated differently when part of a definition, as in the #if cases in the example, compared to direct evaluation, as in the #elif cases in the example?
defined is specific to #if and #elif. When using it through macro expansion the behavior is undefined.