question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,079,411
3,079,491
Creating a custom context menu Window (WinAPI)
I'm wondering how to create windows like these alt text http://img824.imageshack.us/img824/997/this.jpg I'm refering to the one that says Marquee selection tool... these ones. I'm also not referring to the skin. I know how to do my own drawing and what not, this is not the issue. It's because windows usually need a parent which means it should not be possible for these windows to overlap into the tools. The only windows that can do this are context menus and menus. How can I create this style of window? Thanks
I think you are confusing the concept of owner windows and parent windows. Only dialog controls have parent windows, and these are automatically clipped by the parent's client area. Other windows have owner windows. This is a weaker relationship. There's nothing stopping a window from overlapping its owner. Also, I wouldn't assume that just because the toolbar launches the context menu that the toolbar window has a relationship with the menu window. It might or might not, depending on how things are coded behind the scenes. In any case, just try it out. Use the TrackPopupMenu() to create a popup. You can have it overlap the owner window without difficulty. Any window without the WS_CHILD style will exhibit the same behaviour.
3,079,525
3,079,541
RegOpenKeyEx return ERROR_SUCCESS but it shouldn't (windows 7)
I've got a problem about RegOpenKeyEx, the code: #include <tchar.h> #include <stdio.h> #include <windows.h> #pragma comment (lib, "Advapi32.lib") int main () { TCHAR *keyName = _T("SOFTWARE\\foobar2000\\capabilities"); HKEY key = NULL; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) { printf("open key failed!\n"); return -1; } else { printf("open key success!\n"); } TCHAR *value = _T("123"); if (RegSetValueEx(key, _T("xxx"), 0, REG_SZ, (const BYTE *)value, sizeof(TCHAR) * (_tcslen(value) + 1)) != ERROR_SUCCESS) { printf("set value failed!\n"); } RegCloseKey(key); return 0; } Save the code in such as reg.cpp, and in command mode: cl reg.cpp and I got reg.exe, run it: D:\tmp>reg.exe open key success! But the value hasn't been written in the registry. Another strange thing is that if I use the visual studio to create a CLI project, and paste the code into main(), the RegOpenKeyEx() will return false. The platform is windows 7, and UAC is enabled.
Sounds like you're running into virtualization. IF the app has no manifest, when you try to write to HKLM\Software it actually writes to HKEY_USERS\<User SID>_Classes\VirtualStore\Machine\Software. To prevent this, you can run the app elevated. You might want to add a manifest forcing it to run elevated every time. Alternatively, stop writing to HKLM and use HKCU instead. As for the C++/CLI part, my guess would be you are given an asInvoker manifest for that one, which suppresses virtualization and results in the attempt to get to HKLM failing.
3,079,619
3,083,500
Dialog of my Word add-in not using visual styles
I have written a Word add-in in C++ using plain Win32 API. It opens some dialogs but these are always shown without commctl6 visual styles on Vista+. The manifest is in place as RT_MANIFEST and resource ID - 2 (as shown below). When I invoke the same functionality/dialogs from my own test app, visual styles are OK. Any idea how Word is preventing my add-in from using visual styles despite the manifest? <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel> </requestedPrivileges> </security> </trustInfo> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="x86" publicKeyToken="6595b64144ccf1df" language="*"></assemblyIdentity> </dependentAssembly> </dependency> </assembly>
Are you using ISOLATION_AWARE_ENABLED?
3,079,704
3,081,290
Is it possible to map an address to the result of a function?
I'm writing a NES emulator in C/C++ for Mac OS (I've already written one, so I know the basics). Since many hardware registers are mapped to memory locations, I was wondering if there was some syscall I could use to map an address to the result of a function: when it would be accessed, the function would be called. (I'm pretty sure I can't, but hey, it's worth asking.) Here is what I'd like to do: int getStatusRegisterValue() { return 0xCAFEBABE; } // obviously, more parameters than just this would be involved I suppose int* statusRegister = syscall_to_map_function_to_address(getStatusRegisterValue); // from here on, doing (*statusRegister) should call getStatusRegisterValue and // return its value *statusRegister == 0xCAFEBABE; This project is going to be my try at LLVM, and my goal is to recompile the ROM to LLVM bytecode. That's why it would be convenient if the simple memory access could trigger the function (just like on real NES hardware). The two other obvious possibilities to solve my problem are to either cache the register values and store them in actual memory, or call a function from the recompiled code to map the memory locations to whatever they really are. Thanks!
Maybe you could try installing a SEGV handler and checking the faulting address there. As I don't use Mac OS I can't help you more.
3,079,742
4,063,550
boost::asio handshake through http proxy?
Quite new to boost and asio, need help: connect to proxy asio::ip::tcp::socket socket_; send CONNECT host: ssl server to the proxy receive response 200 asio::ssl::context ctx(io_service, asio::ssl::context::sslv23); sslsocket_(socket_,context) try handshake sslsocket_.async_handshake(asio::ssl::stream_base::client, boost::bind(&client::handle_handshake, this, asio::placeholders::error)); and get asio.ssl error Wireshark: host sends FIN after 1st message of handshake Direct async connection to ssl server works fine, same through Proxifier
Forgot to mention that was running the application in VMplayer with NAT network; bridged removed the problem with initial handshake but sometimes after reconnect saw the same message; using the method in Sam's link got to "unexpected record" during handshake - google said on this error about renegotiations but that was not the case; digging into sources of OpenSSL: the new connection used the same BIO for reading and recevied application data from previous connection Don't know how to reset the SSL structure with asio, so made dynamic socket allocation with new|delete
3,079,836
3,079,848
c++ static won't link
Can you help? The following code: class MT { public: static int ms_number; }; int MT::ms_number; yields: Error 8 error LNK2005: "public: static int MT::ms_number" (?ms_number@MT@@2HA) already defined in ProjName.obj Why?
You need to move this line: int MT::ms_number; out of your .h file and into a single .cpp file.
3,079,978
4,002,502
Making Vista / 7 User Frame control? (WinAPI)
I notice Vista/7 uses this type of control as well as Windows Live Messenger. This is the control: How can this control be programably added to a WinAPI application? Thanks
This resource is Bitmap 7016 in explorer.exe's resources. It is a 32 bit bitmap, so it has an extra alpha channel. This is how it is done.
3,079,980
3,080,108
Calling a function from a derived template class
My base class: //Element.h class Element { public: Element(); virtual ~Element(){}; // not sure if I need this virtual Element& plus(const Element&); virtual Element& minus(const Element&); }; Derived template class: //Vector.h #include "Element.h" template <class T> class Vector: public Element { T x, y, z; public: //constructors Vector(); Vector(const T& x, const T& y = 0, const T& z =0); Vector(const Vector& u); ... //operations Element& plus(const Element&) const; Element& minus(const Element&) const; ... }; ... //summation template <class T> Element& Vector<T>::plus(const Element& v) const { const Vector<T>& w = static_cast<const Vector<T>&>(v); Vector<T>* ret = new Vector<T>((x + w.x), (y + w.y), (z + w.z)); return *ret; } //difference template <class T> Element& Vector<T>::minus(const Element& v) const { const Vector<T>& w = static_cast<const Vector<T>&>(v); Vector<T>* ret = new Vector<T>((x - w.x), (y - w.y), (z - w.z)); return *ret; } I had another issue with this code (answered in another post), but currently I'm wrestling with the fact that if I try to run this, I get Undefined symbols: "Element::plus(Element const&)", referenced from: vtable for Vectorin main.o "Element::Element()", referenced from: Vector::Vector()in main.o Vector::Vector(double const&, double const&, double const&)in main.o "Element::minus(Element const&)", referenced from: vtable for Vectorin main.o "typeinfo for Element", referenced from: typeinfo for Vectorin main.o ld: symbol(s) not found collect2: ld returned 1 exit status Is this because the derived template class isn't housed in the same file as the base class, and that's causing compiler issues (similar to how I had to define the entire Vector class in the header file)? I'm fairly new to C++, and still reading up on what vtables are and how they work, but I can't quite figure this out yet.
I think the compiler/linker means it when it tells you Undefined symbols: "Element::plus(Element const&)" . These symbols (plus and minus for Element) have been declared but they have not been defined.
3,080,049
3,080,209
Should i always use GL_ARGB format for all textures in OpenGL?
This has been bothering me a while... and it's really hard to really see any difference in performance, so i ask here: If my images doesnt use alpha channel, should i use 'GL_RGB' for saving them in GFX card memory, or 'GL_ARGB' as if that would be faster in processing since its full 32 bit block? Or does GFX cards automatically convert 24 bit images into 32 bit images to boost their rendering times? Edit: I have no performance issues, but i just want to do it the best way! I also want to ensure that the program renders good on old graphics cards that doesnt necessary optimize things as good as new cards.
Choose the formats appropriate for your texture data, and let the video card driver worry about the details. Don't try to outsmart it. OpenGL implementations are quite well-optimized and will make all of the necessary decisions for you for the best performance, whether that means converting all textures to 32bpp or some other internal format. If you find that you're having performance issues, use a tool like gDEBugger to work out your performance bottlenecks. It's highly unlikely that your texture format is such a bottleneck. Edit: If the problem is simply memory pressure, then you have too many textures that are too large. Simple as that. Use compression, use lower-quality (fewer bits per channel) textures, or use smaller textures.
3,080,137
3,080,155
What is wrong with this code?
int main() { char *name = new char[7]; name = "Dolphin"; cout << "Your name is : " << name <<endl; delete [] name; } Why doesn't the VC++ compiler complain?
You've got two questions here: First, What's wrong with code? Well ... When you assign "Dolphin" to name you are not copying into the allocated array you are adjusting the pointer to point to a string literal. Later you try to delete what the pointer points to. I'd expect this to crash horribly in some environments. If you really want a copy of the "Dolphin" characters, have a look at strncpy(), but as already been observed, you need a space for the null too. Second, why that particular compiler doesn't warn you that the assignment is potentially: that's a bit harder. [It's been observed that other compilers will give a warning.] The question is whether this compiler treats a string literal as a "Pointer to const char" or a "Pointer to char". If it was the former case then I'd expect an error. Until about 2004 C++ was consistent with C in treating literals as pointer to char, and hence the assignment would be permitted. So I guess the question for you is to determine what version of the specs you are working against, and that might depend upon the version of VC++ you are using and also any compiler options you have chosen. A MSDN C++ reference indicates that VC++ treats string literals as non const. I'll leave it to VC++ gurus to comment further.
3,080,156
3,080,176
How do I link in functions from a .cpp source file that also has a 'main'?
I want to use some functions from a .cpp source file that has a main function in my .cpp source file. (I'm building with make and gcc.) Here's the rule from my Makefile: $(CXX) $(CXXFLAGS) $(INCLUDES) $(SRCS) $(LIBS) -o $@ And here's the output (with some names changed to prevent distraction): $ make foo g++ -g -Wall -m32 -Ilinux/include foo.cpp bar.cpp -o foo /tmp/ccJvCgT3.o: In function `main': /home/dspitzer/stuff/bar.cpp:758: multiple definition of `main' /tmp/ccUBab2r.o:/home/dspitzer/stuff/foo.cpp:68: first defined here collect2: ld returned 1 exit status make: *** [foo] Error 1 How do I indicate to gcc that I want to use the main from foo.cpp? Update: I should have added that "bar.cpp" is "someone else's" code, and has it's own reason for a main. (It sounds like I should work with that someone else to have him split the shared functions into a separate file.)
what you could do is wrap each main() function in an #ifdef block, then use the command line to define the symbol which will cause the relevant main to be used. #ifdef USE_MAIN1 int main(void) { } #endif Then ensure the gcc command line gets something like this added to it -DUSE_MAIN1 Or just restructure your code!
3,080,191
3,080,258
Window Style for shading?
When a menu item or context menu is made, it has a shadow, if I create a window with WS_POPUP instead of WS_CHILD it has no shadow. How can I get the shadow? Thanks
It is enabled with WNDCLASSEX.style. Turn on the CS_DROPSHADOW style. I think this only works on top-level windows.
3,080,224
3,080,246
Ways to parse XML in C++ (Win32)
I'm looking for a way to parse XML in C++ in Windows and I've found a few such as MSXML, Xerces, TinyXml etc but I'm wondering which is best in terms of performance and features. My requirements are that it must be able to be static linked or have the source included in the project itself and must not require any additional toolits such as boost. MSXML would be the obvious choice as it's an MS library but it seems to be a COM library and rather convoluted to actually get any use out of it. Does anyone have any suggestions as to something quick and simple to use? Thanks, J
I used libxml with success. The API is a bit confusing and complicated, but once you get it it works pretty good. Besides it is stuffed with functionality, so if you need that, go with libxml. You dont have to worry about bloated binaries since you can only link the parts you need. You dont need to include the complete libxml if you only need to parse xml and dont use the xpath stuff for example
3,080,298
3,080,324
Nesting of Structs and Classes
#include<iostream> using namespace std; struct My_Class{ class My_struct{ int am_i_in_class_or_struct; }; }; int main(){ cout<<sizeof(My_Class)<<endl; cout<<sizeof(My_struct)<<endl; cout<<sizeof(int); } Please Explain: when i executed the above program on Turbo C i got output: 1 2 2 Now shouldn't the size be same in each case, or at least My_Class should have the same or larger size than My_struct!! If there are errors in the program please fix them if you can, or else ignore it and concentrate on the question at hand! I dont trust Turbo C as such... but currently my VS 2008 keeps crashing due to my Ram going bad!
You are nesting the declarations, but not the data. Declaring one class inside another class does not magically make the data members of the inner class also members of the outer class. Your code is virtually equivalent to a mere struct My_Class{ }; class My_struct{ int am_i_in_class_or_struct; }; with only one difference. In your code the name of the struct is My_Class::My_struct. In my version it is just My_struct. Only the names change. Nothing else. (Actually, there are some other differences with regard to access rights, but it is not immediately relevant to the question as stated.)
3,080,377
3,080,917
How do I use DrawPrimitiveUP so it uses the color value from my defined struct?
I need to draw lines using DrawPrimitiveUP and I need it to use the color value from my defined structure. Important snippets from the code: struct PointVertexColor { float x, y, z; // Position DWORD color; //Colour }; #define D3DFVF_PointVertexColor ( D3DFVF_XYZ | D3DFVF_DIFFUSE ) PointVertexColor myLines[1024]; device->DrawPrimitiveUP( D3DPT_LINELIST, myLinesCount, myLines, sizeof( PointVertexColor ) ); I have a pointlight set, lighting enabled and ambient lighting also. Problem is that if I set up a material it uses the materials color and not the one from my data struct. How do I set it up so it uses the DWORD color and then set it back to use material for later code ?
The problem was obvious if you know it - you can't use vertex color and lighting at the same time. The solution is to disable lighting for that part of the code and then re-enable it later. Hope it helps someone with the same question.
3,080,439
3,080,448
C++ reference variable across files
I have a project where I need to reference a variable declared in one CPP file in another, is that possible? If so, how?
It is possible, if you declare it as global (top-level, above any function definition) and use "extern ;" in other files to make it known to the compiler. // Main.cpp #include <...> int myNum; int main(int argc, char** argv) { // MAGIC BE HERE return 0; } and // Second.cpp #include <...> extern int myNum; int f() { return myNum * 2; } extern prevents the compiler from allocating memory again when a variable was allocated in another file.
3,080,560
3,080,649
C++ TLS, somethings wrong
I'm learning about Thread Local Storage... (TLS) Here is my TLS Alloc code: //global variable DWORD g_dwTlsIndex; //inside DLLMain: int val= 5; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: g_dwTlsIndex = TlsAlloc(); if ((g_dwTlsIndex = TlsAlloc()) == TLS_OUT_OF_INDEXES) { printf("No more indexes available"); } void *pint; memcpy(&pint, &val, sizeof val); TlsSetValue(g_dwTlsIndex, pint); break; Now I try to get the value from the TLS: (in another CPP file) // declare index value... extern DWORD g_dwTlsIndex; int data; LPVOID d; d = TlsGetValue(g_dwTlsIndex); memcpy(&data, &d, sizeof d); printf("Data: %d", data); But data contains 0, where I put 5 in it.... What have I done wrong?
A few notes: Your error checking statement should read: if (g_dwTLSIndex == TLS_OUT_OF_INDEXES). As it stands, you're assigning g_dwTlsIndex twice (and thus losing the reference with the first assignment.) Do some basic debugging: Call TlsGetValue in the line immiediately after TlsSetValue. Does that work at least? Check the return codes. TlsGetValue and TlsSetValue both return a function telling you whether the assignment was successful. Was it? Keep track of your index. You're using a global variable to store g_dwTlsIndex, so it could easily be getting altered. What is the value after alloc (use a printf to see). What is the value when you make the Get call? Do these values match? These steps should help you find the problem.
3,080,579
3,087,910
Ampersand accelerators cause a beep in a Win32 dialog
I have a dynamically created toolbar on a plain Win32 dialog. My buttons are added with & shortcuts which correctly puts underscore to characters following ampersand but pressing Alt+(char) causes a beep and the button is not clicked. It has been a while since I have done Win32 API development. Is there something that needs to be done to a dynamically created child window (toolbar) in order for the accelerator keys to work? This could be something really obvious that I am missing...
Well... You have to write code to handle these keypresses and convert them into WM_COMMAND messages. The traditional way to do this is to define an accelerator table and process them using TranslateAccelerator() - but of course, you're free to do it however you like... Just make sure the keys you handle jibe with the keys you underline! You might also find this KB article helpful: How to use accelerator keys within a modal dialog box in Visual C++... Or, for a more in-depth (and MFC-free) look at implementing custom message processing in dialogs, check out Raymond Chen's articles on the dialog manager, specifically part 4: The dialog loop and part 9: Custom accelerators in dialog boxes (but seriously, read the whole thing, you know you want to...)
3,080,632
3,506,819
NetBeans6.9 C++ runtime error
In NetBeans 6.9 in windows version I use CygWin for C++ programming.I can compile my simple program and BUILD SUCCESSFUL message show by output window in NetBeans but when run my project this message show in external terminal : /cygdrive/c/Users/SjB/Documents/NetBeansProjects/CppApplication_3/dist/Debug/Cyg win-Windows/cppapplication_3.exe: error while loading shared libraries: ?: canno t open shared object file: No such file or directory Press [Enter] to close the terminal ... after that I go manually to this folder (/cygdrive/c/Users/SjB/Documents/NetBeansProjects/CppApplication_3/dist/Debug/Cygwin-Windows/) and run it manually (./cppapplication_3.exe) and work ! what should I do to run it in NetBeans IDE ???!!!
You should add the environment variable to your path. Go to Control Panel -> Systems-> Advanced -> Environment variables and edit the $PATH variable by adding C:\cygwin\bin Then, reload your project in NetBeans and it should work.
3,080,764
3,081,038
'this' pointer in macro and function
I have some code which use 'this' pointer of class which calls this code. For example: Some::staticFunction<templateType>(bind(FuncPointer, this, _1)); Here is I'm calling bind function from boost. But it doesn't matter. Now I have to wrap this code. I made a macro: #define DO(Type, Func) Some::staticFunction<Type>(bind(FuncPointer, this, _1)); And compiler insert this code into class which calls this macro, so 'this' takes from caller. But I don't want to use macro and prefer function (inline). But how to resolve 'this' passing. Could I use it in inline function like in macro or I have to pass it manually?
The this keyword can be put by the function you call class MyClass { // ... template<typename Type, typename Func> void doit(Func f) { Some::staticFunction<Type>(bind(f, this, _1)); } }; After which you can call doit<templateType>(FuncPointer); If you like you can inherit the function // T must be a derived class of MyRegister<T> template<typename T> class MyRegister { protected: template<typename Type, typename Func> void doit(Func f) { Some::staticFunction<Type>(bind(f, (T*)this, _1)); } }; class MyClass : MyRegister<MyClass> { // ... }; That way you can just use doit and not first write it, just like with the macro. Useful if you have a wide range of classes that you use the function in. Edit: Notice that the C-Style cast is required here (can't use static_cast), because of the private inheritance. It's a safe cast if T is derived from MyRegister<T> Personally i would prefer this over the macro. Notice that your macro can't cope with commas in the type-name DO(std::pair<A, B>, g); This tries to pass 3 arguments to the macro instead of 2. You could reverse the order of the type and the function and use variadic macros (which are a C++0x feature, but available in some compiler in C++03 mode) or you could use a typedef and pass the alias name.
3,081,033
3,081,145
Number of arguments in macro definition
I have some templated function which has different number of arguments due to the template-type. This function is wrapped with macro definition. #define SomeTemplate(TemplateType, Arguments) someFunc<TemplateType>(Arguments); Everything is okay when I'm using only one argument for function calling, but I need in more. I looked at boost it does such things through definition of different macros, like this: #define TEMP_1(Arg1) someFunc<Template>(Arg1); #define TEMP_2(Arg1, Arg2) someFunc<Template>(Arg1, Arg2); #define TEMP_3(Arg1, Arg2, Arg3) someFunc<Template>(Arg1, Arg2, Arg3); But this code marked as portable for compilers. There is way to use some defines with any number of arguments. How can I do that?
the only way to do that us using __VA__ARGS__ in the macro definations, however, its not as portable, beacuse older compilers like VC6 doesn't support var arg'ed macros, see: MSVC GCC
3,081,052
3,081,072
Correct data structure to use for (this specific) expiring cache?
I need to read from a dataset which is very large, highly interlinked, the data is fairly localized, and reads are fairly expensive. Specifically: The data sets are 2gigs - 30gigs in size, so I have to map sections of the file into memory to read. This is very expensive compared to the rest of the work I do in the algorithm. From profiling I've found roughly 60% of the time is spent reading the memory, so this is the right place to start optimizing. When operating on a piece of this dataset, I have to follow links inside of it (imagine it like being similar to a linked list), and while those reads aren't guaranteed to anywhere near sequential, they are fairly localized. This means: Let's say, for example, we operate on 2 megs of memory at a time. If you read 2 megs of data into memory, roughly 40% of the reads I will have to subsequently do will be in that same 2 megs of memory. Roughly 20% of the reads will be purely random access in the rest of the data, and the other 40% very likely links back into the 2meg segment which pointed to this one. From knowledge of the problem and from profiling, I believe that introducing a cache to the program will help greatly. What I want to do is create a cache which holds N chunks of X megs of memory (N and X configurable so I can tune it) which I can check first, before having to map another section of memory. Additionally, the longer something has been in the cache, the less likely it is that we will request that memory in the short term, and so the oldest data will need to be expired. After all that, my question is very simple: What data structure would be best to implement a cache of this nature? I need to have very fast lookups to see if a given address is in the cache. With every "miss" of the cache, I'll want to expire the oldest member of it, and add a new member. However, I plan to try to tune it (by changing the amount that's cached) such that 70% or more of reads are hits. My current thinking is to use either an AVL tree (LOG2 n for search/insert/delete) would be the safest (no degenerate cases). My other option is a sparse hashtable such that lookups would be O(1) in the best case. In theory this could degenerate into O(n), but in practice I could keep collisions low. The concern here would be how long it takes to find and remove the oldest entry in the hashtable. Does anyone have any thoughts or suggestions on what data structure would be best here, and why?
Seems like you are looking for an LRU (Least Recently Used) cache: LRU cache design
3,081,108
3,081,168
Custom iterator: how do I keep track of it?
I have this situation: I have a class which keeps track of an array of pointers. I built a custom iterator which loops through this array. My problem is on how to make it threadsafe, especially while incrementing/decrementing? Here is a draft of the relevant parts of what I have: typedef fruit * iterator; class fruits { private: fruit ** flist; int n; //keeps track of position in flist int count; //number of fruits public: iterator begin() {n=0; return fruit[n];} iterator end() {n=count; return fruit[n];} iterator operator++ () { return fruit[++n]; } } The problem i see is that if two parts of the program create an iterator things won't work. How does C++ STL deal with it? UPDATE: I have found the error of my ways. The iterator should keep track of where it is by itself. For that I created an iterator class embedded in my main class. Life is now good.
The standard containers maintain their iteration state in iterator objects separately from the container, so there can be multiple iterations over the container at the same time. So begin() and end() return iterators, but don't change the state of the container; operator++ acts on iterators, not the container. For a simple array like this, a pointer (to a fruit*, not a fruit) works perfectly well as an iterator, so you can just define begin() and end(): iterator begin() {return flist;} iterator end() {return flist + count;} and use it like this: for (iterator i = my_fruit.begin(); i != my_fruit.end(); ++i) do_something_with(*i); // *i is a fruit* There's no problem with multiple threads doing this at the same time, as long as none of them try to modify the container. On the other hand, unless this is a learning exercise to better understand how containers and iterators work, you're much better off using std::vector than implementing your own version of it.
3,081,246
3,081,269
Why aren't (C++) virtual destructors enforced for a base class
Destructors aren't virtual by default to not hurt when its not needed, which is fine. But in case of a base class derived class scenario, is there any use case for not having a virtual destructor? If not could it be possible (does it make sense) for the compiler to complain if a class derives from a base class which has a public non virtual destructor (or no destructor) defined. And not just warn about it.
The problem with your idea is that it's conceivable that someone is using a non-virtual base class destructor as an optimization (if you're never going to destroy via a base-class pointer, then the missing virtual won't hurt you, and still avoids the vtable entry). Since it COULD be used, it's allowed. I'd think an optional compiler warning might be a good idea, but not something in the language spec.
3,081,289
3,081,405
How to read a line from a text file in c/c++?
After exhaustive googling and visiting many forums, I am yet to find a good comprehensive answer for this question. A lot of the forums suggest using the get line istream& getline (char* s, streamsize n ) function. My question is what if I don't know what the length of each line is and cannot predict what the size may be? Also what is it's equivalent in C? Is there any specific function in c /c++ to read one single line each time from a text file ? Explanation , with Code snippets will help me a lot.
In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines. If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it. #include <stdio.h> #include <stdlib.h> void handle_line(char *line) { printf("%s", line); } int main(int argc, char *argv[]) { int size = 1024, pos; int c; char *buffer = (char *)malloc(size); FILE *f = fopen("myfile.txt", "r"); if(f) { do { // read all lines in file pos = 0; do{ // read one line c = fgetc(f); if(c != EOF) buffer[pos++] = (char)c; if(pos >= size - 1) { // increase buffer length - leave room for 0 size *=2; buffer = (char*)realloc(buffer, size); } }while(c != EOF && c != '\n'); buffer[pos] = 0; // line is now in buffer handle_line(buffer); } while(c != EOF); fclose(f); } free(buffer); return 0; }
3,081,305
3,081,334
What is the difference between r-value references and l-value references? (CodeGen)
What does an r-value reference look like from a lower-level perspective. I just can't seem to wrap my head around it! Can I see an example of generated code (either equivalent C or x86/x64) from a r-value reference vs. a l-value reference? For example, what would this construct look like? Let's assume no copy elision for now. vector<SomethingHUUGE> myFunc(); void foo(vector<SomethingHUUGE>&&); int main() { foo(myFunc()); return 0; }
There is no difference for the purposes of code generation. The only semantic difference between the two is that you know an RValue reference is about to be destroyed, while an lvalue reference will not.
3,081,340
3,082,115
QTableView sorting signal?
I use QTableView + QStandardItemModel to show some data (data stored in some other data structure), and this table view is sortable. Since it is sortable, when sorting this model, I also need to sort the order of stored data. I try to implement a slot for the sorting signal, but I don't know what signal is emitted when clicking the header to start the sorting action. I tried the clicked signal, but it's only emitted for data row, not for the headerData. what should I do if I want to do something else while sorting the QtableView + QStandardItemModel ?
The Header of the View can be obtained by QHeaderView * QTableView::horizontalHeader () const Now with the obtained QHeaderView, you can connect a slot to the signal, void QHeaderView::sectionClicked ( int logicalIndex ) [signal]. From the Qt 4.5 documentation, This signal is emitted when a section is clicked. The section's logical index is specified by logicalIndex.Note that the sectionPressed signal will also be emitted. Hope it helps.
3,081,446
3,085,256
Drawing list of points in SDL?
If i have an array of coordinates for a path(Such as in a paint program), what is the best way to render the entire path with SDL? I looked at setting pixels individually, but from what i've seen that's a bad idea. I also thought about drawing all the coordinates as SDL_Rect's, but rendering a large list of rect's each frame sounds slow. Is there a simple way of achieving this effect?
You can implement yourself the Bresenham line algorithm directly accessing the framebuffer but I think you'll be doing much better using OpenGL...
3,081,505
3,081,553
Is there an equivalent of str_replace in C++?
In PHP, there is a str_replace function that basically does a find and replace. Is there an equivalent of this function in C++?
Not exactly, but take a look at the Boost String Algorithms Library - in this case the replace functions: std::string str("aabbaadd"); boost::algorithm::replace_all(str, "aa", "xx"); str now contains "xxbbxxdd".
3,081,537
3,081,651
How can I make a variable of the same type as another using templates?
I'd like to create a variable which matches the type of another variable by way of a template such that if the other variable ever changes type to match, the one derived from it via a template also changes its type. How can I do this with templates in C++? The purpose is to ensure that when I read from disk into a temporary variable that the number of bytes read from disk exactly matches the actual variable. In this case, I am going to ignore the value so don't want to read to the actual variable, but need to make sure I read the right number of bytes before moving on to keep things in sync.
If you don't have decltype available in your compiler, you can write a template function to accomplish this. It's kind of ugly but it will get the job done. template<typename T> T read_alike(int fd, T const &unusedVar) { T realVar; if (::read(fd, &realVar, sizeof(realVar)) != sizeof(realVar) throw std::runtime_error("read failed or incomplete"); return realVar; } You'd call it like: MyClass myObj; MyClass newObj = read_alike(fd, myobj);
3,081,539
3,081,558
Why is my operator<< overloading not working?
Error: ..\Record.cpp: In function `std::ostream& operator<<(std::ostream&, Record&)': ..\Record.cpp:83: error: no match for 'operator<<' in 'out << Record::date()()' Record.cpp: /* * Record.cpp * * Created on: Jun 13, 2010 * Author: DJ */ #include <iostream> #include "Record.h" using std::string; using std::istream; using std::ostream; Record::Record() { } Record::Record(Date inDate) { _date = inDate; } Record::Record(Date inDate, Time inTime) { _date = inDate; _time = inTime; } Record::Record(Date inDate, Time inTime, string inDescription) { _date = inDate; _time = inTime; _description = inDescription; } Record::~Record() { } Time Record::time() { return _time; } void Record::time(Time inTime) { _time = inTime; } Date Record::date() { return _date; } void Record::date(Date inDate) { _date = inDate; } string Record::description() { return _description; } void Record::description(string inDescription) { _description = inDescription; } void Record::operator=(Record record) { _date = record.date(); _time = record.time(); _description = record.description(); } istream &operator>>(istream &in, Record &record) { Time inTime; Date inDate; string inDescription; in >> inDate >> inTime >> inDescription; record.date(inDate); record.time(inTime); record.description(inDescription); return in; } ostream &operator<<(ostream &out, Record &record) { out << record.date() << " " << record.time() << " " << record.description(); return out; } Date.cpp: /* * Date.cpp * * Created on: Jun 13, 2010 * Author: DJ */ #include "Date.h" #include <iostream> using std::istream; using std::ostream; Date::Date() { _day = 1; _month = 1; _year = 1999; } Date::Date(unsigned int inDay) { day(inDay); _month = 1; _year = 1999; } Date::Date(unsigned int inDay, unsigned int inMonth) { day(inDay); month(inMonth); _year = 1999; } Date::Date(unsigned int inDay, unsigned int inMonth, unsigned int inYear) { day(inDay); month(inMonth); year(inYear); } Date::~Date() { } void Date::day(unsigned int inDay) { assert(inDay <= daysInMonth()); _day = inDay; } unsigned int Date::day() { return _day; } void Date::month(unsigned int inMonth) { assert(inMonth <= 12); _month = inMonth; } unsigned int Date::month() { return _month; } void Date::year(unsigned int inYear) { _year = inYear; } unsigned int Date::year() { return _year; } void Date::operator=(Date date) { day(date.day()); month(date.month()); year(date.year()); } istream &operator>>(istream &in, Date &date) { char dummy; unsigned int day, month, year; in >> month >> dummy >> day >> dummy >> year; date.day(day); date.month(month); date.year(year); return in; } ostream &operator<<(ostream &out, Date &date) { out << date.month() << "/" << date.day() << "/" << date.year(); return out; } unsigned int Date::daysInMonth() { if(_month == 1 || _month == 3 || _month == 5 || _month == 7 || _month == 8 || _month == 10 || _month == 12) return 31; else return 30; } Time is basically the same as date.
Your operator<< should take const references (const Date &). If your operators take non-const references, they won't work with temporary objects (such as the one returned from Record::date). This is what's causing the error. Note that changing to const references means you will need to change any member functions called (e.g. Date::month) to be const. This is good practice anyway. Another option is to pass the parameter by value, which will invoke the copy constructor. const references are usually preferred because they are generally faster, and you shouldn't need to invoke non-const members anyway.
3,081,669
3,081,693
How to call a C++ function pointer from C?
I was successfully to finally be able to use TUI header from PDcurses library in my C++ project in a previous post here. now in my class I am including the C header: #include "tui.h" tui is in C and has this definition for menu: typedef struct { char *name; /* item label */ FUNC func; /* (pointer to) function */ char *desc; /* function description */ } menu; so in MainView.cpp I have: void sub0() { //domenu(SubMenu0); } void sub1() { //domenu(SubMenu1); } void MainView::showMainMenu() { menu MainMenu[] = { { "Users", sub0, "Manage Users" }, { "Accounts", sub1, "Manage Accounts" }, { "Items", sub1, "Manage Items" }, { "Staff", sub1, "Manage Staff" }, { "", (FUNC)0, "" } }; startmenu(MainMenu, "Library System 1.0"); } this is working as expected. The problem is that i need to make calls on my class methods in sub0() and sub1(). I tried to define C++ methods for my class to try and replace sub0 and sub1 with: void MainView::sub0() { //domenu(SubMenu0); } void MainView::sub1() { //domenu(SubMenu1); } the compiler is throwing this error: error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'FUNC' None of the functions with this name in scope match the target type what is the best way of passing those function pointers to the C code and get rid of that error? thanks
C++ class objects have a "this" pointer, which is sort of invisibly passed as the first argument to a class member function. That means you can't use a non-static member function for a C-style function pointer that takes 0 arguments. So solve this, you have a few choices. I'd need more detail before telling you which one to go with. Make the functions you want to use in the C code static. Use boost or tr1 or some other C++ library that allows binding member functions with their this pointer. With boost, this would look like: { "Users", boost::bind(&MainView::sub0, this), "Manage Users" }, You might be able to modify your code to pass around a reference to the class object along with these function pointers. If so, you can then invoke your callbacks directly on the object you want. It looks like you're dealing with a window manager though, and so you probably won't be able to make the changes needed for this approach to work. Probably what you will end up doing is some sort of work around, involving storing the pointer to the object you're using somewhere and then writing small stub functions which access this pointer and then call a member function on it. Some (dare I say, most) window managers allow you to include a pointer to arbitrary data with the callback for this purpose.
3,081,697
3,081,714
Should you format operator<< for classes?
As in, should the operator>> match the operator<< ? Database Example: If the operator>> reads in something of the following format: 2 Joe 500 20 1 Bob 250 30 0 should the operator<< output that? Or something like this: Record: 1/2 Name: Joe Balance: 500 Transactions: 20 Premium Account: Yes And then have a separate writeFile() function? I know either would work, but what is the "accepted standard"?
If you have an istream operator>> overload for a type that reads data in a particular format, then if you implement an ostream operator<< overload for the same type, it should output in the same format (otherwise, it could get quite confusing).
3,081,717
3,086,104
24 Bit Toolbar Button Images? (WinAPI)
I'm using pure win32. How can I use 24 bit images instead of 8 bit? Thanks
You can set the imagelist for the toolbar with the TB_SETIMAGELIST message.
3,081,765
3,081,805
Problem with using getline and strtok together in a program
In the below program , I intend to read each line in a file into a string , break down the string and display the individual words.The problem I am facing is , the program now outputs only the first line in the file. I do not understand why this is happening ? #include<iostream> #include<string> #include<fstream> #include<cstdio> using namespace std; int main() { ifstream InputFile("hello.txt") ; string store ; char * token; while(getline(InputFile,store)) { cout<<as<<endl; token = strtok(&store[0]," "); cout<<token; while(token!=NULL) { token = strtok(NULL," "); cout<<token<<" "; } } }
I'm new to C++, but I think an alternative approach could be: while(getline(InputFile, store)) { stringstream line(store); // include <sstream> string token; while (line >> token) { cout << "Token: " << token << endl; } } This will parse your file line-by-line and tokenise each line based on whitespace separation (so this includes more than just spaces, such as tabs, and new lines).
3,081,815
3,081,883
C++ errors while compiling
I am trying to compile a game, but getting 100+ errors like: C:\Users\AppData\Local\Temp\cctQCagR.o: In function `load_image(std::string)': main.cpp:(.text+0x4bd4): undefined reference to `std::string::c_str() const' C:\Users\Bill\AppData\Local\Temp\cctQCagR.o: In function `createShip(float, float)': main.cpp:(.text+0x4da4): undefined reference to `std::allocator<char>::allocator()' main.cpp:(.text+0x4dbc): undefined reference to `std::basic_string<char, std::char_tra its<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> cons t&)' main.cpp:(.text+0x4de4): undefined reference to `std::basic_string<char, std::char_tra its<char>, std::allocator<char> >::~basic_string()' main.cpp:(.text+0x4e04): undefined reference to `std::basic_string<char, std::char_tra its<char>, std::allocator<char> >::~basic_string()' main.cpp:(.text+0x4e1c): undefined reference to `std::allocator<char>::~allocator()' main.cpp:(.text+0x4e28): undefined reference to `std::allocator<char>::allocator()' main.cpp:(.text+0x4e40): undefined reference to `std::basic_string<char, std::char_tra its<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> cons t&)' main.cpp:(.text+0x4e60): undefined reference to `std::allocator<char>::~allocator()' main.cpp:(.text+0x4e70): undefined reference to `__cxa_end_cleanup' main.cpp:(.text+0x4e98): undefined reference to `std::basic_string<char, std::char_tra its<char>, std::allocator<char> >::~basic_string()' main.cpp:(.text+0x4eb8): undefined reference to `std::basic_string<char, std::char_tra its<char>, std::allocator<char> >::~basic_string()' main.cpp:(.text+0x4ed0): undefined reference to `std::allocator<char>::~allocator()' main.cpp:(.text+0x4ef4): undefined reference to `std::allocator<char>::~allocator()' main.cpp:(.text+0x4f04): undefined reference to `__cxa_end_cleanup' C:\Users\Bill\AppData\Local\Temp\cctQCagR.o: In function `load_files()': main.cpp:(.text+0x5164): undefined reference to `std::allocator<char>::allocator()' main.cpp:(.text+0x517c): undefined reference to `std::basic_string<char, std::char_tra its<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> cons t&)'
I believe you're trying to compile main.cpp with gcc instead of g++. #include <string> #include <stdio.h> int main() { std::string bla; bla = "BLA BLA"; printf("%s\n",bla.c_str()); return 0; } If you build the above code snippet with gcc you get the errors you mention. If you use g++ it build ok, this makes sense since g++ will make sure all the proper stuff it put together when build C++.
3,081,924
3,082,019
Finding the smallest window
Given two arrays A[n] and B[m], how can I find the smallest window in A that contains all the elements of B. I am trying to solve this problem in O(n) time but I am having problem doing it. Is there any well know algorithm or procedure for solving it.
countLet's call window 'minimal' if it can't be reduced. I.e., after increasing its left border or decreasing its right border it's no longer valid window (doesn't contain all elements from B). There three in your example: [0, 2], [2, 6], [6, 7] Let's assume say that you already found leftmost minimal window [left, right]. ([0, 2] in your example) Now we'll just slide it to the right. // count[x] tells how many times number 'x' // happens between 'left' and 'right' in 'A' while (right < N - 1) { // move right border by 1 ++right; if (A[right] is in B) { ++count[A[right]]; } // check if we can move left border now while (count[A[left]] > 1) { --count[A[left]]; ++left; } // check if current window is optimal if (right - left + 1 < currentMin) { currentMin = right - left + 1; } } This sliding works because different 'minimal' windows can't contain one another.
3,081,965
3,082,008
using C# DLL from C++: problem with functions with strings as parameters
Starting from this example: http://support.microsoft.com/kb/828736 I have tried to add a test function in my C# DLL which takes strings as parameters. My C# DLL code is as follows: namespace CSharpEmailSender { // Interface declaration. public interface ICalculator { int Add(int Number1, int Number2); int StringTest(string test1, string test2); }; // Interface implementation. public class ManagedClass : ICalculator { public int Add(int Number1, int Number2) { return Number1 + Number2; } public int StringTest(string test1, string test2) { if (test1 == "hello") return(1); if (test2 == "world") return(2); return(3); } } I then register this DLL using regasm. I use it in my C++ app like so: using namespace CSharpEmailSender; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { // Initialize COM. HRESULT hr = CoInitialize(NULL); // Create the interface pointer. ICalculatorPtr pICalc(__uuidof(ManagedClass)); long lResult = 0; long lResult2 = 0; pICalc->Add(115, 110, &lResult); wprintf(L"The result is %d", lResult); pICalc->StringTest(L"hello", L"world", &lResult2); wprintf(L"The result is %d", lResult2); // Uninitialize COM. CoUninitialize(); return 0; } After running this, lResult is correct (with value of 225), but lResult2 is zero. Any idea what I'm doing wrong?
Without trying to compile this, perhaps the interop expects the string to be of BSTR type. Can you try the following? pICalc->StringTest(CComBSTR(L"hello"), CComBSTR(L"world"), &lResult2); OR pICalc->StringTest(::SysAllocString(L"hello"), ::SysAllocString(L"world"), &lResult2);
3,082,045
3,084,252
How to use for_each with the function as the overloaded operator()
I have a std::vector of function objects. Each object can take an int, so I can say obj(4) and get an int result. How can I use the algorithm for_each to work on each element of the vector?
You would have to create a functor 'calling' each object: struct Caller { int value; void operator()( const YourFunctorHere& f ) const { f( value ); } } caller; std::for_each( functors.begin(), functors.end(), caller );
3,082,113
3,082,186
calculating factorial using template meta-programming
I do not understand how this piece of code (from Wikipedia) works: template <int N> struct Factorial { enum { value = N * Factorial<N - 1>::value }; }; template <> struct Factorial<0> { enum { value = 1 }; }; // Factorial<4>::value == 24 // Factorial<0>::value == 1 void foo() { int x = Factorial<4>::value; // == 24 int y = Factorial<0>::value; // == 1 } What is this weird template that takes <int N>? What is this second weird template <>? What are the enumerations for? What is the advantage of using this rather than normal runtime factorial calculation? How often do you people use this? I have been using C++ for a while now, but never used this before. How big a part of C++ was I missing out on? Thanks!
What is this weird template that takes <int N>? In C++, template arguments can either be types (prefixed with class or typename) or integers (prefixed with int or unsigned int). Here we are in the second case. What is this second weird template <>? template<> struct Factorial<0> is a complete specialization of Factorial class template, which means that 0 is considered a special value to which corresponds its own version of Factorial. What are the enums for? enums are the way to compute values in metaprogramming C++ What is the advantage of using this rather than normal runtime factorial calculation? The reason why this code was created in the first place is to create a proof of concept that calculus can be done using metaprogramming. The advantage is that generated code is extremely efficient (calling Factorial<4>::value is equivalent to simply writing "24" in your code. How often do you people use this? I have been using C++ for a while now, but never used this before. How big a part of C++ was I missing out on? Such functionality is rarely achieved using this method, but metaprogramming is used more and more nowadays. See Boost meta-programming library to get a hint of what can be done.
3,082,291
3,082,442
Virtual function calling using dereference object
I have a base class pointer pointing to a derived class object. I am calling foo() function by using two different ways in the code below. Why does Derived::foo() get called in the first case? Shouldn't (*obj).foo() call Base::foo() function as it has already been dereferenced? class Base { public: Base() {} virtual void foo() { std::cout << "Base::foo() called" << std::endl; } virtual ~Base() {}; }; class Derived: public Base { public: Derived() : Base() {} virtual void foo() { std::cout << "Derived::foo() called" << std::endl; } virtual ~Derived() {}; }; int main() { Base* obj = new Derived(); // SCENARIO 1 (*obj).foo(); // SCENARIO 2 Base obj1 = *obj; obj1.foo(); return 0; }
// SCENARIO 1 (*obj).foo(); Note that obj is a misnomer here, since it doesn't refer to an object, but to a pointer, (*ptr).foo() is just a roundabout way to do ptr->foo(). *ptr doesn't result in an object, but in a reference Base& to the object. And a virtual function call through a reference is subject to dynamic dispatch, just as such a call through a pointer. // SCENARIO 2 Base obj1 = *ptr; obj1.foo(); What you do here is you create a totally new object through slicing: it just has the base class parts of *ptr. What you want instead is this: Base& ref = *ptr; ref.foo();
3,082,397
3,082,459
IsDirty name for member function of CField class
What was the raionale behind having a function by the name IsDirty() in CField Class in MFC.
The terms "clean" and "dirty" are quite commonly used in data processing. When you receive a copy of some data structure from a persistent storage like a data base or file system, it is said to be "clean", unmodified, not touched. Once you are done with the data, the backing storage does not need to be updated for clean data. Once you edit your copy, it gets "dirty" and the changes you made must be saved back to the persistent storage after you're done, otherwise they would be lost.
3,082,700
3,084,434
Is there a way to 'expand' the #define directive?
I have a lot of "stupid" #define in a project and I want to remove them. Unfortunately, I can't do a simple search and replace, since the #define is parameterized. For example: #define FHEADGRP( x ) bool _process_grp##x( grp_id_t , unsigned char ) This is used to generate headers of a couple of functions. I would like to somehow do the same thing as the preprocessor does - replace each call of the macro by its result (with correct parameters inserted. I hope you understand what I want to do. I found out that with Visual Studio, one can get the preprocessed intermediate files with the /P option. Unfortunately, this does not help me, since the file is "polluted" with thousands of other lines and with all #defines expanded. I do not want to do this, I just want to expand some of the macros and preferably do it in my IDE (which is Visual Studio). Is there any way how to achieve this?
Yes, there is - since you're using Visual Studio. The Visual Studio IDE has a powerful search & replace mechanism. You seem to assume it can only handle literal strings. It can do more. Hit Ctrl-Shift-H for a global search and replace. In the "Find options", select "Use: Wildcards". Now replace FHEADGRP(*) by bool _process_grp\1( grp_id_t , unsigned char ) The wildcard is *, and \1 is the backreference. [edit] Macros work on the tokenized source, but Search&Replace works on characters. This can cause a slight problem. Consider the cases FHEADGRP(Foo) and FHEADGRP( Foo ). For a C macro, they're equivalent, but in the second case the backreference will expand to Foo - with spaces. The workaround is to use regexes, in particular replace FHEADGRP\(:b*(.*):b*\) with bool _process_grp\0( grp_id_t , unsigned char ). I find that the VS2005 implementation is a bit buggy; for instance the simple ? expression fails to match a single space. But the example above should work.
3,082,751
3,082,759
when returning by address, doesnt this go out of scope? ( SDL)
this is a code example from lazyfoo's SDL tutorials. SDL_Surface *load_image( std::string filename ) { //Temporary storage for the image that's loaded SDL_Surface* loadedImage = NULL; //The optimized image that will be used SDL_Surface* optimizedImage = NULL; //Load the image loadedImage = SDL_LoadBMP( filename.c_str() ); //If nothing went wrong in loading the image if( loadedImage != NULL ) { //Create an optimized image optimizedImage = SDL_DisplayFormat( loadedImage ); //Free the old image SDL_FreeSurface( loadedImage ); } //Return the optimized image return optimizedImage; } Here shouldn't optimizedImage go out of scope when it returns? seeing as it is local.
It does, but not the allocated memory pointed by it. It is a merely 4 byte pointer variable, the only thing needed from it is to retain its value. The value is the address. The address is something allocated in manually controlled fashion, and deallocating it requires calling functions the compiler does not know about.
3,082,800
3,082,810
Only implement copy constructor, no assignment constructor
When the class with a member which is a pointer, we need implement a copy constructor for it. I have a question, if we have implemented a copy constructor, should we implement an assignment constructor too? Best Regards,
It is not called an assign constructor but rather an assignment operator, and yes you should. The rule of thumb is: if you need to write a destructor then you should also provide a copy constructor and assignment operator (or block the compiler from generating one)
3,082,900
3,082,917
Preventing compilers from defining copy constructors and operator = overload for C++ Classes
Is there a way by which we can prevent compilers from defining copy constructors, operator = overload for C++ classes.
You can declare these functions as private which prevents people from using them when working with your class and at the same time prevents the compiler from generating them.
3,082,950
3,083,011
When are global static const variables being initialized?
I tried to search the site for this question but didn't find this exactly, although this subject is being discussed a lot... I have this declaration in a cpp file, not within any function: static const char* gText = "xxxxxxxxxxx"; Although it has a fixed size, I get a warning from a static analysis tool (Klocwork) when I'm trying to copy it to another char* variable - about possible out of bounds violation: char xText[32]; SecureZeroMemory(xText, 32); memcpy(xText, gText, strlen(gText)); Is it a false positive or is the global variable being initialized later? Thanks!
It is a false positive. strlen is probably abstracted as returning an unknown positive number, so that when analyzing the pattern memcpy(dest,src,strlen(src)); the analyzer does not realize that the reading part of the copy is safe as soon as src is a well-formed string. If you were using strcpy, the analyzer would probably conclude that it's okay in this case. Do you have a reason not to? The function strcpy is considered "unsafe" but your memcpy(..,src,strlen(src)) is quite unsafe too. EDIT: Also, sellibitze raises a very good point in the comments: the const attribute in the original code only applies to the chars pointed by gText and not to gText itself.
3,082,995
3,083,057
Return-type polymorphism for pass-by-value
I'm not sure if the question title is accurate... Let me start by explaining my original simple scenario, and then move on to explain what would I like to do, but can't. Originally, I had something like: class Operand; Operand genOperandA() { ...; return Operand(); } Operand genOperandB() { ...; return Operand(); } ... // more operand-generation functions typedef Operand (*OpGen)(); // Table of function pointers static const OpGen generators[] = { genOperandA, genOperandB, ... }; // Function to do some operation on the operand void operate(Operand& op); ... // Example call operate(generators[1]()); So far so good (I think). However, there are now several derived operand types, e.g. class RegisterOperand : public Operand. I have new, dedicated genOperand functions that ideally would return instances of the derived types. But I can't do this: Operand genOperandC() { ...; return RegisterOperand(); } and I can't do this: RegisterOperand genOperandC() { ...; return RegisterOperand(); } static const OpGen generators[] = { ... genOperandC, }; However, I know this would work if I were to return reference or pointer types, so the only option I currently have is something like: Operand *genOperandC() { ...; return new RegisterOperand(); } which now requires explicit cleanup which wasn't necessary originally. Any alternatives I haven't considered?
There might be other designs that doesn't require you to use pointers, but if you need or want to go this way, this might interest you. If returning a pointer is a problem (because of the need to "clean-up" things), you definitely should consider using smart pointers as return type. Here is an example of your factory method with smart pointers: boost::shared_ptr<Operand> genOperandC() { return boost::shared_ptr<Operand>(new RegisterOperand()); } This way, you won't have to call delete manually: it will be done by the destructor of boost::shared_ptr<Operand> for you when required. If afterwards you need to cast the resulting pointer, boost provides casting functions as well: boost::shared_ptr<Operand> op = genOperandC(); boost::shared_ptr<RegisterOperand> rop = boost::dynamic_pointer_cast<RegisterOperand>(op);
3,083,016
3,083,035
int to string conversion
I would like to save files with different names in a loop. I use a library that needs a char as a parameter of the file... for(int i=0;i<nodes;i++){ for(int j=0;j<nodes;j++){ char a[20]="test"; char c[20]="xout.dat"; Lib::SaveFile(_T(a), _T(c)); }} The above code works, but I would like to change the name of the xout.mid to the corresponding integer so I would get i*j files with different names.i and j go from 0 to about 30. I would like to get a char with the name i_j_xout.dat
char name[30]; sprintf(name, "%d-%d-%s", i, j, c);
3,083,280
3,083,603
A good repartition algorithm
I am implementing a memcached client library. I want it to support several servers and so I wish to add some load-balancing system. Basically, you can do two operations on a server: Store a value given its key. Get a value given its key. Let us say I have N servers (from 0 to N - 1), I'd like to have a repartition function which, from a given key and server number N, would give me an index in the [0, N[ range. unsigned int getServerIndex(const std::string& key, unsigned int serverCount); The function should be as fast and simple as possible and must respect the following constraint: getServerIndex(key, N) == getServerIndex(key, N); //aka. No random return. I wish I could do this without using an external library (like OpenSSL and its hashing functions). What are my options here? Side notes: Obviously, the basic implementation: unsigned int getServerIndex(const std::string& key, unsigned int serverCount) { return 0; } Is not a valid answer as this is not exactly a good repartition function :D Additional information: Keys will usually be any possible string, within the ANSI charset (mostly [a-zA-Z0-9_-]). The size may be anything from a one-char-key to whatever-size-you-want. A good repartition algorithm is an algorithm for which the probability of returning a is equal (or not too far) from the probability of returning b, for two different keys. The number of servers might change (rarely though) and if it does, it is acceptable that the returned index for a given key changes as well.
You're probably looking for something that implements consistent hashing. The easiest way to do this is to assign a random ID to each memcache server, and allocate each item to the memcache server which has the closest ID to the item's hash, by some metric. A common choice for this - and the one taken by distributed systems such as Kademlia - would be to use the SHA1 hash function (though the hash is not important), and compare distances by XORing the hash of the item with the hash of the server and interpreting the result as a magnitude. All you need, then, is a way of making each client aware of the list of memcache servers and their IDs. When a memcache server joins or leaves, it need only generate its own random ID, then ask its new neighbours to send it any items that are closer to its hash than to their own.
3,083,355
3,083,425
Why and when is worth using pointer to pointer?
Possible Duplicate: How do pointer to pointers work in C? Hello, Altough I think I passed the newbie phase in programming I still have some questions that somehow I can't find them explained. Yes, there are plenty of "how to"s overthere but almost always nobody explains why and/or when one technique is useful. In my case I have discovered that in some cases a pointer to a pointer is used in C++. Is not a pointer to an object enough? Which are the benefits? Where or when should be used a pointer to a pointer? I feel little bit desorientated in this matter. I hope time experienced expert could respond to this concerns that hopefully is shared by other no so experienced programers. ;-) Thank you everyone. Julen.
Well, it is somehow hard to answer to such a general question. First answer of a C++ programmer will certainly be : Do not use pointers in C++ ! As you have a lot of safer ways to handle problems than pointers, one of your goal will be to avoid them in the first place :) So pointers to pointers are seldom used in C++. They are mainly used in C. First, because in C, strings are "char*" so when you need a "pointer to a C string" you end with a "char**". Second, as you do not have references in C, when you need to have a function that modify a pointer or that give a pointer as an output value, you need to give a pointer to a pointer parameter. You typically find that in functions that allocate memory, as they give you a pointer to the allocated memory. If you go the C++ way, try to avoid pointers, you usually have better ways. my2c
3,083,458
3,084,359
Looking for any good(and free) cross-platform CLI parsing library for a command line utility
I am currently working on a CLI utility which I feel can be improved a lot by adding a framework. Basically the utility revolves around lots of command line syntax AND parsing the output. Currently the code is scattered all around with lots of individual inhouse run() and readFromRunOutput() calls with hardcoded CLI arguments. For example: op=run("command -args"); while(readFromRunOutPUr(op)) { // Process and take result from output if(op=="result-one") dothis(); else if(op=="result-two") dothat(); } I would like to create a generic framework out of this wherein the the following are fed in from outside the code through a XML file. 1) Test Name 2) Command Line invocation 3) Required Output for Success So assumming a simple XML invocation... <Test name=FirstTest> <CLI="command -args"> <Success Output= "value" > </Success> </CLI> </Test> Yes. There are some few chinks to worry about in the above example but I think I have given the gist of it. Basically I would like to move all the different CLI invocations to outside the code and then feed them in(with the criteria for success and failure). For lot of other reasons I cannot go for any scripting languages like perl or python and have to maintain the product in C/C++. From what I gather the requirements are Defined XML syntax Parser for the above XML spec to memory Get CLI -----> and invoke Read Output and compare with the fed in values (Preferably cross platform support) An implementation like this would not only standardize on all the different individual function calls but also make it easy to extend without any code changes. Now my question is , are there any readymade free libraries(for C++) available which already provide similar or basic template framework on which I can extend. Preferably first hand experience. Any other guidance ?
I don't understand what exactly you are looking for, but have a look at Boost Program Options. It can handle most CL Parsing out of the box and is easily extendible for the rest.
3,083,532
3,083,763
Dividing large integer by large integer
Guys I'm working on class called LINT (large int) for learning purposes, and everything went ok till know. I'm stuck on implementing operator/(const LINT&). The problem here is that in when I want to divide LINT by LINT I'm getting into recursive fnc invocation i.e: //unfinished LINT_rep LINT_rep::divide_(const LINT_rep& bottom)const { typedef LINT_rep::Iterator iter; iter topBeg = begin(); iter topEnd = end(); iter bottomBeg = bottom.begin(); iter bottomEnd = bottom.end(); LINT_rep topTmp;//for storing smallest number (dividend) which can be used to divide by divisor while (topBeg != topEnd) { topTmp.insert_(*topBeg);//Number not large enough add another digit if (topTmp >= bottom) {//ok number >= we can divide LINT_rep topShelf = topTmp / bottom;//HERE I'M RUNNING INTO TROUBLE } else { } ++topBeg; } return LINT_rep("-1");//DUMMY } What I'm trying to do is to implement this as if I would divide those numbers by hand, so for example having for a dividend 1589 and for divisor 27 I would go like so: check if first digit is >= divisor and if so divide if not add to the first digit another digit and check if a > b At some point it will be bigger (in simplified scenario) and if so I have to divide but in this case I'm running into recursive call and I have no idea how to break it. One note: as a tmp I have to use LINT instead of int for example because those numbers my not fit into int. So generally what I'm asking for is there any other way to do division? Or maybe there is false logic in my thinking (quite possible). Thank you.
When doing your part (1) you can't divide; you have to repeatedly subtract, or guess to subtract a multiple, just like when you do it by hand. You can 'guess' more effectively by setting upper and lower bounds for the multiple required and doing a binary-chop through the range. I've done a similar thing myself; it's a handy exercise to practice operator overloading. I can supply a snippet of code if you like, although it uses arrays and half-baked exceptions so I hesitate to offer it up before the expert readers of this site.
3,083,649
3,083,879
best practice for implementing a Search-Function via prepared statements
I'm trying to implement a Search-Function using c++ and libpqxx. But I've got the following problem: The user is able to specify 4 different search patterns (each of them optional): from date till date document type document id Each of them is optional. So if I want to use prepared statements I would need 2^4 = 16 different prepared statements. Well, it's possible, but I want to avoid this. Here as an example what a prepared statement in libpqxx looks like: _connection->prepare("ExampleStmnt", "SELECT * FROM foo WHERE title=$1 AND id=$2 AND date=$3") ("text", pqxx::prepare::treat_string) ("smallint", pqxx::prepare::treat_direct) ("timestamp", pqxx::prepare::treat_direct); Therefore I also have no idea how I would piece such a prepared statement together. Is there any other 'nice' way that I didn't think of?
The best you can do is to have four different ->prepare clauses, depending on how many search criteria are actually used, concatenate the criteria into your String, and then branch to one of the four prepare code blocks. (That will probably spook your style checker into thinking you are creating an injection vulnerability, but of course you aren't, as long as you insert only elements of the closed set os column names.) Note that this isn't a very nice solution, but even Stephane Faroult (in The Art of SQL) says it's the best one possible, so who am I to argue?
3,083,758
3,123,425
How do I diagnose problems in loading a gstreamer plugin?
I have created a gstreamer plugin with an element inside that would generate some data when put in a pipeline (by following the GStreamer Plugin Writer's Guide). My problem is that I cannot load my plugin in a test application. When I call gst_element_factory_make("myextractor", NULL) the result is always NULL. More data (I'm not sure this is related): When I run gst-inspect on my dll I get incomplete output (output generated using cygwin): beq11049@beqleuleu1nb028 /cygdrive/c/work $ /cygdrive/c/OSSBuild/GStreamer/v0.10.6/bin/gst-inspect.exe MyProject/Release/gstxyzlibrary.dll Plugin Details: Name: myextractor Description: XYZ Library Filename: MyProject/Release/gstxyzlibrary.dll Version: 1.0 License: LGPL Source module: myextractor Binary package: MyProject Origin URL: http://www.example.com/ myextractor: XYZExtractor 1 features: +-- 1 elements If I compare this with the avisubtitle addon (from the GStreamer Good Plug-ins package) I get a lot less information for mine. For example, my plugin says: 1 features: +-- 1 elements The avisubtitle plugin says (generated using $ /cygdrive/c/OSSBuild/GStreamer/v0.10.6/bin/gst-inspect.exe avisubtitle): GObject +----GstObject +----GstElement +----GstAviSubtitle My question: I need advice on how to debug this / determine what I am missing (enabling debugging output, settings and paths to check and so on). My test code (the call to gst_element_factory_make) is written in a Songbird adon, but I get the same results if I put my code in a separate executable.
It might be because the loader can't find your plugin, you should check that your plugin is in the shared library path: Make sure you've set the LD_LIBRARY_PATH environment variable to the directory containing your compiled plugin. In cygwin, add this to your .profile, or run it before you run your program: export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/cygdrive/c/path/to/your/plugin/" You could also use the -L linker option to specify a search path at compile time.
3,083,808
3,083,824
strange catch clause... C++
What is this catch clause?? STD_CATCH_ALL_with_kMETHODID(...) Its used in a python interpreter extension...
How about right-click and select Go To Declaration (using Visual Studio). You may try Go To Definition as well. If you cannot find it, it means you need to include a header where this macro is defined.
3,083,903
3,084,189
PostThreadMessage to another process
I want to post a message to a thread that is running as another process (in particular as a windows service). I've read the documentation for PostThreadMessage but there are some things unclear for me. How do I get a handle for my service's thread? The system only does marshalling for system messages (those in the range 0 to (WM_USER-1)). To send other messages (those >= WM_USER) to another process, you must do custom marshalling. I want to send my own messages, so how do I do this marshalling?
PostThreadMessage is less than ideal here. Getting the thread ID is indeed a problem since your service will have to run more than one thread. One to implement the service, another to pump a message loop that's required to read the messages. CreateToolHelp32Snapshot() can enumerate the threads but you will still not know which of those two threads is the one that's pumping. Use a named pipe instead. Call CreateNamedPipe() in your service, use message mode and give the pipe a name prefixed with "Global\" so that it is visible in the user session. The user code can connect to the pipe using the well-known pipe name. You can send whatever you want across the pipe but you will have to avoid pointers since they won't be valid in the service process. Same kind of problem as the message marshaling. Other possibilities are a socket, very similar to a pipe but using a well-known port number instead of a name, and out-of-process COM. Using COM is an advantage if you have complex objects that need to be marshaled across the process boundary. Avoid it if you don't have COM skillz though.
3,083,932
3,084,015
Modify in place the elements of a vector
The following doesn't work as desired (print 2) because, I guess, the nodes are passed by value even though the vector is passed by reference. How could I fix it? #include <iostream> using std::cout; using std::endl; #include <vector> using std::vector; class Node{ public: int value; Node(int); void createChildren(vector<Node> &); }; //! constructor of a single node Node::Node(int value) { this->value = value; } void Node::createChildren(vector<Node> &nodes) { for (int i = 0; i < 5; i++) { Node n(0); nodes.push_back(n); if (i == 0) { value = nodes.size(); } } } int main(void) { Node a(0); vector<Node> asdf; asdf.push_back(a); asdf[0].createChildren(asdf); cout << asdf[0].value << endl; return 0; }
When you execute the line nodes.push_back(n);, the vector is resized, invalidating previously held references as it copies the existing members to a newly allocated memory block. In your case, *this inside createChildren is such a reference (to asdf[0]). Changing value in it is no longer defined behavior because the destructor for this object has been executed (try defining ~Node() and see when it is called)
3,083,956
3,083,962
Simple question about #import
Is #import or #include a job that is handled by the complier or by the linker?
Anything that starts with # is a preprocessor directive and is expanded by the preprocessor, which is a step that happens before compilation.
3,083,987
3,085,097
calling class-specific operator new
The expression operator new(sizeof(T)) allocates T bytes via ::operator new, correct? Is there any way to call the class-specific version of operator new if it exists, exactly the way how new T() allocates memory (before calling the constructor)? T::operator new(sizeof(T)) gives a compile-time error if T does not define operator new, even if T inherits from a base class that defines it. What I would like to call is: Foo::operator new if Foo defines operator new Base::operator new if Foo derives from Base that defines operator new (what do I do about multiple inheritance?) ::operator new otherwise
The standard library solves this problem using an allocator object whose type is set as a template parameter of the class that needs a customizable allocation algorithm. I don't think there's any complete way to do what you asked, as already evidenced by your second bullet. There's no way for the compiler to know which parent's operator new to use if they both defined one. If you're trying to implement for example a small object allocator pool that picks an appropriate size/pool at compile time, what about using a standalone template allocator function: It would be called something like object_allocator<T>::allocate() and the template type would let you figure out the size automatically. You still can't inherit operator new because of the multiple inheritance issue but it makes it easy to figure out how to allocate memory within any class.
3,084,109
3,084,418
Caching the end iterator - Good idea or Bad Idea?
Generally speaking is it a good idea to cache an end iterator (specifically STL containers) for efficiency and speed purposes? such as in the following bit of code: std::vector<int> vint; const std::vector<int>::const_iterator end = vint.end(); std::vector<int>::iterator it = vint.begin(); while (it != end) { .... ++it; } Under what conditions would the end value be invalidated? would erasing from the container cause end to be invalidated in all STL containers or just some?
In the simple case of a vector, the end iterator will change when you add or remove elements from the container; though, it's usually safest to assume that if you mutate the container while iterating over it, all iterators to it become invalid. Iterators may be implemented differently in any given STL implementation. With regard to caching the end iterator -- it's certainly valid to cache it, but to find out if it is actually faster in your case, the best bet is for you to profile your code and see. While retrieving the end iterator from a vector is likely a fast implementation with a recent STL library and compiler, I have worked on past projects where caching the end iterator gave us a significant speed boost. (This was on the PlayStation 2, so do take with a grain of salt.)
3,084,689
3,084,788
How to create Handler
Add next changes: Emily::oSeMac^ Terminal; Emily::AsyncSocketController^ _socketManager; delegate void DataArrival(String^, array<unsigned char, 1>^, System::Net::IPEndPoint^); void _socketManager_onDataArrival(String^ SocketID, array<unsigned char, 1>^ SocketData, System::Net::IPEndPoint^ RemoteIP) { System::Object^ retData = Terminal->WhoCame (SocketID, SocketData, RemoteIP, _socketManager, 0); } Form1(void) { InitializeComponent(); _socketManager = gcnew Emily::AsyncSocketController(2000); _socketManager->onDataArrival += gcnew DataArrival(this, &AC_WebPassManager::Form1::_socketManager_onDataArrival); _socketManager->Start(); Terminal = gcnew Emily::oSeMac(); } Error error C2664: 'Emily::AsyncSocketController::onDataArrival::add' : cannot convert parameter 1 from 'AC_WebPassManager::Form1::DataArrival ^' to 'Emily::AsyncSocketController::onDataArrivalEventHandler ^' 1> No user-defined-conversion operator available, or 1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast 1>
_socketManager->onDataArrival += gcnew DataArrival(this, &Test::Form1::_socketManager_onDataArrival_); DataArrival is delegate: public delegate DataArrival(String^, array<unsigned char, 1>^, System::Net::IPEndPoint^); Possibly it is already defined somewhere, with other name - look this delegate definition in Emily namespace.
3,084,917
3,084,956
Access private variable in global scope
In this below code, the foo function in the global scope tries to access the private variables of a Box, which ofcourse doesn't work. I have to make the foo function work with one line of code at the place show code for a school assignment. #include <iostream> using namespace std; class Box { int x,y; public: Box(int xi,int yi) {x=xi;y=yi;} // One line of code to make foo(Box, Box) work }; bool foo(Box l,Box r) {return (l.x*l.y)>(r.x*r.y);} int main(int argc, char* argv[]) { Box b1(3,4),b2(1,2); if (foo(b1,b2)) cout << "b1>b2\n"; return cin.get(); }
Declare foo as a friend function inside Box #include<iostream> class Box { int x,y; public: Box(int xi,int yi) :x(xi),y(yi){}// Always use initializer list for initializing data members, i.e. prefer initialization over assignment friend bool foo(Box,Box);// friend functions can access private members }; bool foo(Box l,Box r) // friend keyword not to be written while defining the function {return (l.x*l.y)>(r.x*r.y);} int main(int argc, char* argv[]) { Box b1(3,4),b2(1,2); if (foo(b1,b2)) std::cout << "b1>b2\n"; return std::cin.get(); }
3,084,945
3,086,667
Build a Cross Compiler
I'm trying to compile a c++ file and generate an asm or s file to be disassembled and run in PSIM. Whenever I try to do this I get errors. I am attempting to compile to mipsI-linux. I think I've determined that my cross compiler that was given to me is not working correctly for some reason. Can anyone give me some help building a new cross compiler that will generate the correct instruction format? I'm working on a MAC.
You probably want to take a look at crosstool-NG (based on crosstool) which seems to make building a cross-compiler toolchain relatively easy.
3,085,070
3,085,141
Finite State Machine parser
I would like to parse a self-designed file format with a FSM-like parser in C++ (this is a teach-myself-c++-the-hard-way-by-doing-something-big-and-difficult kind of project :)). I have a tokenized string with newlines signifying the end of a euh... line. See here for an input example. All the comments will and junk is filtered out, so I have a std::string like this: global \n { \n SOURCE_DIRS src \n HEADER_DIRS include \n SOURCES bitwise.c framing.c \n HEADERS ogg/os_types.h ogg/ogg.h \n } \n ... Syntax explanation: { } are scopes, and capitalized words signify that a list of options/files is to follow. \n are only important in a list of options/files, signifying the end of the list. So I thought that a FSM would be simple/extensible enough for my needs/knowledge. As far as I can tell (and want my file design to be), I don't need concurrent states or anything fancy like that. Some design/implementation questions: Should I use an enum or an abstract class + derivatives for my states? The first is probably better for small syntax, but could get ugly later, and the second is the exact opposite. I'm leaning to the first, for its simplicity. enum example and class example. EDIT: what about this suggestion for goto, I thought they were evil in C++? When reading a list, I need to NOT ignore \n. My preferred way of using the string via stringstream, will ignore \n by default. So I need simple way of telling (the same!) stringstream to not ignore newlines when a certain state is enabled. Will the simple enum states suffice for multi-level parsing (scopes within scopes {...{...}...}) or would that need hacky implementations? Here's the draft states I have in mind: upper: reads global, exe, lib+ target names... normal: inside a scope, can read SOURCES..., create user variables... list: adds items to a list until a newline is encountered. Each scope will have a kind of conditional (e.g. win32:global { gcc:CFLAGS = ... }) and will need to be handled in the exact same fashion eveywhere (even in the list state, per item). Thanks for any input.
If you have nesting scopes, then a Finite State Machine is not the right way to go, and you should look at a Context Free Grammar parser. An LL(1) parser can be written as a set of recursive funcitons, or an LALR(1) parser can be written using a parser generator such as Bison. If you add a stack to an FSM, then you're getting into pushdown automaton territory. A nondeterministic pushdown automaton is equivalent to a context free grammar (though a deterministic pushdown automaton is strictly less powerful.) LALR(1) parser generators actually generate a deterministic pushdown automaton internally. A good compiler design textbook will cover the exact algorithm by which the pushdown automaton is constructed from the grammar. (In this way, adding a stack isn't "hacky".) This Wikipedia article also describes how to construct the LR(1) pushdown automaton from your grammar, but IMO, the article is not as clear as it could be. If your scopes nest only finitely deep (i.e. you have the upper, normal and list levels but you don't have nested lists or nested normals), then you can use a FSM without a stack.
3,085,257
3,085,600
Why disable CObject's copy constructor and assignment
The MFC's root object CObject's copy constructor and assignment are disabled by default. In MSDN, there is a description The standard C++ default class copy constructor does a member-by-member copy. The presence of the private CObject copy constructor guarantees a compiler error message if the copy constructor of your class is needed but not available. You must therefore provide a copy constructor if your class requires this capability. In CObject's source code, there is a comment: Disable the copy constructor and assignment by default so you will get compiler errors instead of unexpected behaviour if you pass objects by value or assign objects. My question is, what is the problem with the default bit-by-bit copy constructor for this CObject class? In my opinion, it would be better to give us the default copy constructor, and we could provide one if necessary (deep copy)
The default copy constructor is member-by-member, not bitwise. Most CObject-derived classes contain - and manage directly - some system resources, that have no reference counting or similar mechanism, so the choice was probably made with the default use case in mind. e.g. CGDIObject is roughly: class CGDIObject : public CObject { HGDIOBJ m_handle; CGDIObject() : m_handle(0) {} // derived classes provide a create, attach etc. ~CGDIObject() { DeleteObject(m_handle); } } The default copy constructor here would be dangerous (leading to double destruction), providing a "correct" copy constructor is surprisingly hard and expensive. Another reason may be that most CObject-derived classes are intended to be mutated, and thus passed by reference. A missing copy constructor will catch unintended copies that mutate a copy rather than the object passed: class CMyObject : public CObject { public: AttachFoo(FooHandle foo) { ... } AddBar() { ... } }; bool InitMySession(CMyObject & obj) { obj.AttachFoo(CreateRawFoo()); obj.AddBar(); obj.AddBar(); } // ... CMyObj mo; InitMySession(mo); Omitting the "&" gives you code that compiles well, but creates a temporary copy, modifies that, and then drops it, while mo remains unmodified. Quite many API's follow that pattern, as MFC doesn't rely on exceptions for error handling (for historic reasons: not all targeted compilers did support them well, and MFC requires a lot of extra resource handling that becomes painful with exceptions). I don't think these choices are good, e.g. derived classes should be allowed to use the default copy constructor if their members permit (and most members should permit). The decision fits the "mindset" of MFC, though, and the requriements / restrictions of the time MFC was created.
3,085,315
3,085,353
memory footprint issue
I was just curious I have a binary executable file in unix around 9MB. is that considered a large memory footprint? the client will be calling this to generate some values and subsequently queue messages elsewhere. I am just curious who is one suppose to know how when is it too big a memory footprint for a program and then having to provide like a static library instead of an executable?
Everything is relative. It's large footprint if the app is running on a machine with 8MB of RAM. It's not large if the app is running on a machine with 64GB RAM. Then again, it might be large even on a 64GB RAM machine if most of the RAM has been gobbled up by some huge Oracle instance (for example). You should also take into account that only a part of those 9MB is actually loaded into RAM -- readelf or objdump utilities can show you how much exactly.
3,085,349
3,085,368
Function Should Return Value Question
Given a function like so bool RequestStatus() { ... if (code == myCode) { return true; } else { return false; } } Why would the compiler complain that "Function should return value". Unless I am missing something, how else could it not return true or false? Is it because the value of myCode is runtime dependent so the compiler is not sure on the logical paths?
if you write return (code == myCode); you will save lines, make the compiler happy, and generally be writing in a more C++-ish style.
3,086,147
3,086,281
error in one line Xerces program
The following application gives me an access violation on its first line, whats with that? // test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <xercesc/util/XMLString.hpp> using namespace xercesc; int main() { XMLCh* path= XMLString::transcode("test.xml"); return 0; } [edit] The following code gives me an exception on the XMLFormatTarget line, but if i change the string from "C:/test.xml" to "test.xml" it works fine. // test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <xercesc/util/XMLString.hpp> #include <xercesc/framework/LocalFileFormatTarget.hpp> using namespace xercesc; int main() { XMLPlatformUtils::Initialize(); XMLFormatTarget *formatTarget = new LocalFileFormatTarget("C:/test.xml"); return 0; }
The obvious error in your program is that you are not initializing xerces-c before using it. http://xerces.apache.org/xerces-c/program-2.html You must call XMLPlatformUtils::Initialize() before making any other calls to xerces-c.
3,086,308
3,086,464
function templates with class template typedef arguments
the following code is an example of something I'm trying to do in a large project: #include <iostream> #include <vector> // standard template typedef workaround template<typename T> struct myvar {typedef std::vector<T> Type;}; template<typename T> T max(typename myvar<T>::Type& x) // T max(std::vector<T>& x) { T y; y=*x.begin(); for( typename myvar<T>::Type::iterator it=x.begin(); it!=x.end(); ++it ) if( *it>y ) y=*it; return y; } int main(int argc, char **argv) { myvar<int>::Type var(3); var[0]=3; var[1]=2; var[2]=4; std::cout << max(var) << std::endl; return 0; } When I try to compile it I get: >g++ delme.cpp -o delme delme.cpp: In function ‘int main(int, char**)’: delme.cpp:25: error: no matching function for call to ‘max(std::vector<int, std::allocator<int> >&)’ However, if I comment out line 8 and uncomment line 9 it compiles properly and gives: >g++ delme.cpp -o delme >./delme 4 Can someone please explain why the function template definition of max() using typename myvar<T>::Type& isn't considered as a match for ‘max(std::vector<int, std::allocator<int> >&)’ and is there a way to get it to match without using the underlying std::vector<T>& type?
Deducing the enclosing type (or any attributes of the enclosing type) from its the nested type is impossible. It is one of the examples of so called non-deduced context in C++. While the template function declaration itself is legal, you won't be able to call your function as mere max(var) since the template argument deduction cannot be carried out. In your case, the compiler will not be able to figure out that parameter x of type std::vector<int> implies that T is myvar<int>. You'll always have to specify template arguments for max explicitly, as in std::cout << max<int>(var) << std::endl; How to work around this problem depends on what you were trying to achieve by introducing that enclosing myvar template.
3,086,408
3,086,433
Search a std::string
I'm looking to search a string for example: std::string str = "_Data_End__Begin_Data_End"; |_________| |_____________| data data section1 section2 If i'm searching for "Begin" in str i want to make sure that it does look in "data section2" if it wasn't found in "data section1" if i knew the length of "data section1" would it be possible?
std::string::find() has an optional argument to indicate where to begin searching: str.find("Begin", length_of_data_section1);
3,086,656
3,086,992
Help with WinAPI Toolbar
I'm trying to create a toolbar where my bitmaps will be 40x40 and I'm trying to make the toolbar 40 pixels in width. I want it to be a vertical toobar. I'm getting nothing but horizontal results from this code: HWND OGLTOOLBAR::create(HWND parent,HINSTANCE hInst,WNDPROC prc, int *toolWidthPtr) { if (toolhWnd != NULL) { return toolhWnd; } int iCBHeight; // Height of the command bar DWORD dwStyle; // Style of the toolbar HWND hwndTB = NULL; // Handle to the command bar control RECT rect, // Contains the coordinates of the main // window client area rectTB; // Contains the dimensions of the bounding // rectangle of the toolbar control INITCOMMONCONTROLSEX iccex; // The INITCOMMONCONTROLSEX structure TBBUTTON tbButton[8]; wchar_t *txt = L"wii"; for(int i = 0; i < 8; i += 2) { tbButton[i].iBitmap = 0; tbButton[i].fsStyle = BTNS_BUTTON; tbButton[i].fsState = TBSTATE_ENABLED; tbButton[i].iString = (INT_PTR)txt; tbButton->idCommand = 0; } for(int i = 1; i < 8; i += 2) { tbButton[i].iBitmap = 0; tbButton[i].fsStyle = BTNS_BUTTON; //tbButton[i].fsState = TBSTATE_ENABLED; tbButton[i].iString = (INT_PTR)txt;\ tbButton->idCommand = 0; } iccex.dwSize = sizeof (INITCOMMONCONTROLSEX); iccex.dwICC = ICC_BAR_CLASSES; // Register toolbar control classes from the DLL for the common // control. InitCommonControlsEx (&iccex); // Create the toolbar control. dwStyle = WS_VISIBLE | WS_CHILD | TBSTYLE_TOOLTIPS | TBSTYLE_WRAPABLE | TBSTYLE_TRANSPARENT | CCS_VERT ; if (!(hwndTB = CreateToolbarEx ( parent, // Parent window handle dwStyle, // Toolbar window styles (UINT) 666, // Toolbar control identifier 8, // Number of button images hInst, // Module instance (UINT)LoadImage(hInst,MAKEINTRESOURCE(IDB_BRUSH),0,0,0,LR_VGACOLOR), // Bitmap resource identifier tbButton, // Array of TBBUTTON structure // contains button data sizeof(tbButton) / sizeof(TBBUTTON), // Number of buttons in toolbar 40, // Width of the button in pixels 40, // Height of the button in pixels 40, // Button image width in pixels 40, // Button image height in pixels sizeof (TBBUTTON))))// Size of a TBBUTTON structure { return NULL; } // Add ToolTips to the toolbar. SendMessage (hwndTB, TB_SETTOOLTIPS, (WPARAM) NUM_TOOLS, (LPARAM) 8); // Reposition the toolbar. GetClientRect (parent, &rect); GetWindowRect (hwndTB, &rectTB); iCBHeight = 40; mainWindow = parent; toolhWnd = hwndTB; return hwndTB; } I was sure that CCS_VERT was supposed to make it vertical. How can I make this toobar ~40 pixels wide and have 8 squares going downward instead of horizontal. Thanks I don't really want separators, I just thought this would help but it didn't...
From the SDK docs: Creating a Vertical Toolbar The key to creating a vertical toolbar is to include CCS_VERT in the window style, and to set the TBSTATE_WRAP style for each button Emphasis added.
3,086,691
3,087,606
C++ Partial Ordering Fails with 2 Template Parameters
So given the following template functions with partial specialization template<typename T> void foo(vector<T> &in) { cout << "vector" << endl; } template<typename T> void foo(T &in) { cout << "scalar" << endl; } int main(int arc, char *argv[]) { vector<double> a; double b; foo(a); foo(b); return 0; } I have no problem compiling with g++ 3.4.6 and get the expected output: vector scalar Now, if I add a second template parameter: template<class U, typename T> void foo2(vector<T> &in) { U a; cout << "vector" << endl; } template<class U, typename T> void foo2(T &in) { U a; cout << "scalar" << endl; } and call it with the following: int main(int arc, char *argv[]) { vector<double> a; double b; foo2<double>(a); foo2<double>(b); return 0; } When I try to compile it GCC 3.4.6 gives me an ambiguous overload error. error: call of overloaded `foo2(std::vector<double, std::allocator<double> >&)' is ambiguous note: candidates are: void foo2(std::vector<T, std::allocator<_T2> >&) [with U = double, T = double] note: void foo2(T&) [with U = double, T = std::vector<double, std::allocator<double> >] I fail to see how the second template parameter now makes the overload ambiguous. As far as I can tell the vector version should still be more specialized. Is this just a bug in 3.4? Is there a workaround? For the record the code works in gcc 4.1 without issue. Unfortunately some of our tools are still tied to 3.4 so that upgrading isn't the solution. Thanks.
This seems to be related to this defect which is fixed in the latest version of the compiler. Workarounds are to explicitly set all arguments of the template or to use functor instead: template<typename U> struct foo2 { template<typename T> void operator()( std::vector<T> &in ) { U a; cout << "vector" << endl; } template<typename T> void operator()( T& in ) { U a; cout << "scalar" << endl; } }; int main(int arc, char *argv[]) { vector<double> a; double b; foo2<double>()(a); foo2<double>()(b); return 0; }
3,086,770
3,089,632
What algorithms to use for image downsizing?
What algorithms to use for image downsizing? What is faster? What algorithm is performed for image resizing ( specially downsizing from big 600x600 to super small 6x6 for example) by such giants as flash and silver player, and html5?
Bilinear is the most widely used method and can be made to run about as fast as the nearest neighbor down-sampling algorithm, which is the fastest but least accurate. The trouble with a naive implementation of bilinear sampling is that if you use it to reduce an image by more than half, then you can run into aliasing artifacts similar to what you would encounter with nearest neighbor. The solution to this is to use an pyramid based approach. Basically if you want to reduce 600x600 to 30x30, you first reduce to 300x300, then 150x150, then 75x75, then 38x38, and only then use bilinear to reduce to 30x30. When reducing an image by half, the bilinear sampling algorithm becomes much simpler. Basically for each alternating row and column of pixels: y[i/2][j/2] = (x[i][j] + x[i+1][j] + x[i][j+1] + x[i+1][j+1]) / 4;
3,086,805
3,086,871
What I am doing wrong with c++ maps? (scary memory errors)
I am new to C++ and I'm having trouble using a map correctly in class that I'm writing. Basically, when I make a new Block object in a test program and call its write method, the program totally shits itself and gives me a double free or corruption error. What is weird is that everything works fine if I uncomment that one line in the Block constructor. I'm guessing I'm missing some basic c++ knowledge but I'm not finding anything useful on google. Block.h (includes not shown but they are there): namespace SSDSim{ class Block{ public: Block(uint block_num); ~Block(void); void read(uint page_num); void write(uint page_num, void *data); void erase(void); private: uint block_num; std::map<uint, void *> page_data; }; } Block.cpp: #include "Block.h" using namespace std; using namespace SSDSim; Block::Block(uint block){ //page_data[4]= (void *) 0xfeedface; block_num= block; } ... void Block::write(uint page_num, void *data){ if (page_data.find(page_num) == page_data.end()){ page_data[page_num]= data; } else{ cerr<<"Invalid write\n"; exit(1); } } test.cpp: #include <iostream> #include "../Block.h" using namespace std; using namespace SSDSim; int main(void){ Block b= Block(0); b.write(0, (void *) 0xdeadbeef); b.read(0); // b.read(4); return 0; }
Are you sure the error isn't when you call read()? After all, your constructor assigns page[4] to 0xfeedface, an arbitrary place in memory that could point to anything. If you try to then read that location in memory, bad things may happen. I would try to avoid creating pointers out of arbitrary addresses. Instead, test your program by making some object and passing its address to page[4]. The error could also be in your destructor. Since you are allocating a Block on the stack, its destructor is called when it goes out of scope.
3,086,949
3,086,979
stringstream was not declared in this scope
I'm having problem with stringstream.my visual studio nor linux g++ can understand stingstream. I've added sstream but it does'nt solve anything. I've worked with it before and really don't know what's up with it now? #include <sstream> #include <stdlib.h> #include "SymbolTable.cpp" #include "setjmp.h" using namespace std; jmp_buf *bfj; int TOP , SP=3 ; struct types{int int_val;float float_val;char char_val;bool bool_val;}; types DS[6400]; int main(){ ...//some code here label38 : stringstream s; label39 : bfj = (jmp_buf *)"label65"; label40 : longjmp(*bfj,1);; label41 : goto label43; label42 : TOP=SP; //some code here } I'm writing a compiler so the code is the output,that's why it may seams a bit odd.
If you include #include <sstream> then you must also reference the class by: std::stringstream or declare using namespace std; before using it. If you post more information we could provide more detailed help.
3,087,025
3,087,676
Need help designing an inter-process comm layer
I have several process in my system that need to communicate with each other. Some of the processes need to pass chunks of data 60 times per second continuously, and some are very sporadic. Most of the processes are in C#, one is C++. All running on the same windows 7 machine. Right now each process has it's own different comm implentation (pipes, events and sockets). I'm looking to unify into one communication layer. How would you implement this? Maybe some kind of broadcast with the intended receiver as header? What method of process communication would you choose? Thanks, SW
I would suggest using ICE, which supports remote objects and message passing. It will have no problem meeting your rates and bandwidth needs. It's also cross platform and supports languages other then just C# or C++, giving you more languages choices for other components.
3,087,223
3,087,251
Having trouble understanding this error creating a thread
HANDLE hThread; DWORD dwThreadId; hThread = CreateThread( NULL, // default security attributes 0, // use default stack size MyThreadFunction, // thread function name 0, // argument to thread function 0, // use default creation flags &dwThreadId); // returns the thread identifier <--Debugger takes me to this line? The error specifies the 3rd parameter but when i double click on the error it takes me to the last parameter? Trying to run the msdn CreateThread example http://msdn.microsoft.com/en-us/library/ms682453%28VS.85%29.aspx error C2664: 'CreateThread' : cannot convert parameter 3 from 'void (void)' to 'unsigned long (__stdcall *)(void *)' None of the functions with this name in scope match the target type
Clicking on the error takes you to the last parameter because the go-to-error function can only go by statements, and the entire function call is one statement. Basically, your problem is that MyThreadFunction has the wrong signature. It should be unsigned long __stdcall MyThreadFunction(void*) (or the equivalent thereof), but you wrote void MyThreadFunction(void) (or the equivalent thereof).
3,087,268
3,088,193
question with longjmp
I want to use longjmp to simulate goto instruction.I have an array DS containing elements of struct types (int , float, bool ,char). I want to jump to the place labled "lablex" where x is DS[TOP].int_val. how can I handle this? sample code : ... jmp_buf *bfj; ... stringstream s;s<<"label"<<DS[TOP].int_val; bfj = (jmp_buf *) s.str(); longjmp(*bfj,1); but as I thought it's having problem what should I do? error: output.cpp: In function ‘int main()’: output.cpp:101: error: invalid cast from type ‘std::basic_string, std::allocator >’ to type ‘__jmp_buf_tag (*)[1]’
You probably don't want to use longjmp at all but I hate it when people answer a question with "Why would you want to do that?" As has been pointed out your longjmp() usage is wrong. Here is a simple example of how to use it correctly: #include <setjmp.h> #include <iostream> using namespace std; jmp_buf jumpBuffer; // Declared globally but could also be in a class. void a(int count) { // . . . cout << "In a(" << count << ") before jump" << endl; // Calling longjmp() here is OK because it is above setjmp() on the call // stack. longjmp(jumpBuffer, count); // setjump() will return count // . . . } void b() { int count = 0; cout << "Setting jump point" << endl; if (setjmp(jumpBuffer) == 9) return; cout << "After jump point" << endl; a(count++); // This will loop 10 times. } int main(int argc, char *argv[]) { b(); // Note: You cannot call longjmp() here because it is below the setjmp() call // on the call stack. return 0; } The problems with your usage of longjmp() are as follows: You don't call setjmp() You haven't allocated the jmp_buf either on the stack or dynamically. jmp_buf *bfj is just a pointer. You cannot cast a char * to jmp_buf * and expect it to work. C++ not a dynamic language it is statically compiled. But really, it is very unlikely that you should be using longjmp() at all.
3,087,274
3,087,417
Is int guaranteed to be 32 bits on each platform supported by Qt, or only qint32?
I remember reading somewhere that Qt guarantees the size of some data types on supported platforms. Is it that int will be at least 32 bits everywhere, and qint32 will be exactly 32 bits everywhere? Or something else? C++ guarantees that int will be at least 16 bits, and some Qt structures like QRect and QPoint use int internally. I'm developing an application where 32 bits is needed with those types, and I don't want to have to duplicate their functionality so I can use a larger type.
The size of an integer type is up to the compiler. I don't think there's a guarantee that plain int will be of a precise size. But you can make sure you know it's not what you want by adding this line to the beginning of your main(): if(sizeof(int) != 4) { throw std::runtime_error("int is not 32-bit"); }
3,087,364
3,087,378
Iterating std::string elements
does it take constant time to move the iterator to elements of string in following: std::string str // string of size 100 MB std::string::iterator iter = str.begin(); std::advance(iter, str.size()-1); would it take constant time as in searching by index? char c = str[str.size()-1];
Yes, that's correct. This is guaranteed by the C++ standard (§24.3, Iterator operations): Since only random access iterators provide + and - operators, the library provides two function templates advance and distance. These function templates use + and - for random access iterators (and are, therefore, constant time for them);
3,087,422
3,087,833
How do the variable length fields in the windows EVENTLOGRECORD structure work?
I've tried, with little success, to identify how the variable length portion of the EVENTLOGRECORD data works. Winnt.h defines the structure, and the following data, as follows: typedef struct _EVENTLOGRECORD { DWORD Length; // Length of full record DWORD Reserved; // Used by the service DWORD RecordNumber; // Absolute record number DWORD TimeGenerated; // Seconds since 1-1-1970 DWORD TimeWritten; // Seconds since 1-1-1970 DWORD EventID; WORD EventType; WORD NumStrings; WORD EventCategory; WORD ReservedFlags; // For use with paired events (auditing) DWORD ClosingRecordNumber; // For use with paired events (auditing) DWORD StringOffset; // Offset from beginning of record DWORD UserSidLength; DWORD UserSidOffset; DWORD DataLength; DWORD DataOffset; // Offset from beginning of record // // Then follow: // // WCHAR SourceName[] // WCHAR Computername[] // SID UserSid // WCHAR Strings[] // BYTE Data[] // CHAR Pad[] // DWORD Length; // } EVENTLOGRECORD, *PEVENTLOGRECORD; I can pull out the first chunk which appears to be the source with the following code, but its certainly not the intended method: memcpy(&strings, pRecord+sizeof(EVENTLOGRECORD), tmpLog->UserSidOffset); But from the comments in Winnt.h, I'm also getting the computer name. So can someone explain how to determine the "SourceName" length from the EVENTLOGRECORD structure, and explain what StringOffset, DataLength and DataOffset are? Thanks.
So can someone explain how to determine the "SourceName" length from the EVENTLOGRECORD structure, From what I can see, SourceName[] and Computername[] are one behind each other, separated by a '\0', with the first starting right behind DataOffset, and the second starting right behind the '\0' of the first, and going up to two bytes before UserSidOffset, with a '\0' trailing. and explain what StringLength, DataLength and DataOffset are? StringLength I cannot find (and StringOffset is where Strings[] starts), DataLength is the number of bytes in Data[], and DataOffset is where Data[] starts. To read the strings, you could do something like this: // Beware, brain-compiled code ahead! void f(EVENTLOGRECORD* rec) { std::wstring source_name( reinterpret_cast<const wchar_t*>( reinterpret_cast<const unsigned char*>( rec + sizeof(EVENTLOGRECORD ) ) ) ); std::wstring computer_name( reinterpret_cast<const wchar_t*>( reinterpret_cast<const unsigned char*>( rec + sizeof(EVENTLOGRECORD ) + source_name.length()+1 ) ) ); // ... }
3,087,499
3,087,531
preventing memory leak (case-specific)
Consider the following situation: SomeType *sptr = someFunction(); // do sth with sptr I am unaware of the internals of someFunction(). Its pretty obvious that the pointer to the object which someFunction() is returning must be either malloc'ed or be a static variable. Now, I do something with sptr, and quit. clearly the object be still on the heap which is possibly a source of leak. How do I avoid this? EDIT: Are references more safer than pointers. Do the destructor for SomeType would be called if I do : { SomeType &sref = *sptr; } Any insights.
You need to read the documentation on someFunction. someFunction needs to clearly define the ownership of the returned pointer (does the caller own it and need to call delete or does someFunction own it and will make sure the the object is destructed sometime in the future). If the code does not document it's behavior, there is no safe way to use it.
3,087,634
3,087,659
How do I find the number of bytes used by a pointer?
I have a pointer (uint8_t *myPointer), that I pass as parameter to a method, and then this method sets a value to this pointer, but I want to know how many bytes are used (pointed at ?) by the myPointer variable. Thanks in advance.
The size of the pointer: sizeof(myPointer) (Equal to sizeof(uint8_t*)) The size of the pointee: sizeof(*myPointer) (Equal to sizeof(uint8_t)) If you meant that this points to an array, there is no way to know that. A pointer just points, and cares not where the value is from. To pass an array via a pointer, you'll need to also pass the size: void foo(uint8_t* pStart, size_t pCount); uint8_t arr[10] = { /* ... */ }; foo(arr, 10); You can use a template to make passing an entire array easier: template <size_t N> void foo(uint8_t (&pArray)[N]) { foo(pArray, N); // call other foo, fill in size. // could also just write your function in there, using N as the size } uint8_t arr[10] = { /* ... */ }; foo(arr); // N is deduced
3,087,822
3,087,858
Passing row of static 2-d array to function in C++
This is a really elementary question. Nonetheless, I haven't found a solution after studying dozens of semi-relevant examples online. I have a two-dimensional array of doubles whose size is known at compile time: double demPMFs[ NUM_DEM_PARAMS ][ NUM_AGE_CATEGORIES ]. Array entries are populated by input files early in the program. I'd like to pass individual rows as one-dimensional arrays to functions later in the program. I'd ideally like to maintain separate names for each row: #define LSPAN_PMF demPMFs[0][] #define FLEDGE_PMF demPMFs[1][] #define PAIR_PMF demPMFs[2][] #define BIRTH_AGE_PMF demPMFs[3][] #define SPLIT_AGE_PMF demPMFs[4][] (Here, NUM_DEM_PARAMS = 5;). Below is a failed attempt to pass a row to a function: int calcDeath( double demPMFs[][ NUM_AGE_CATEGORIES ] ) { int age_death = rmultinom( LSPAN_PMF, NUM_AGE_CATEGORIES ); return age_death; } int rmultinom( const double p_trans[], int numTrans ) // ...[code snipped]... } I'm getting compiler errors about the prototypes now; I expect to run into problems with the const declaration too. I can go into the details of the errors if people think they're relevant, but I suspect there's a lot to set straight already.
Instead of using array[index][], use array[index]: #define LSPAN_PMF demPMFs[0] // ... etc. But why obfuscate working with arrays so much? Using named indices would be much clearer: enum { IndexLspan, IndexFledge, // ... }; int calcDeath( double demPMFs[][ NUM_AGE_CATEGORIES ] ) { int age_death = rmultinom( demPMFs[IndexLspan], NUM_AGE_CATEGORIES ); Continuing, why not use the containers from the C++ standard library in the first place?
3,088,058
3,088,306
What's the point of using boost::mem_fn if we have boost::bind?
I'm having a look at the Boost libraries that were included in C++'s Technical Report 1 and trying to understand what each does. I've just finished running an example for boost::mem_fn and now I'm wondering what's the point of using it instead of the better boost::bind. As far as I understand, both of them return a function object pointing to a member function. I find mem_fn so limited that I can't find a scenario where using it would be better than bind. Am I missing something? Is there any case in which bind cannot replace mem_fn?
mem_fn is much smaller than bind, so if you only need the functionality of mem_fn it's a lot less code to pull in.
3,088,198
3,088,320
How to handle state transitions and yet replace "if" statements with polymorphic types?
Recently I was listening to a tech talk on clean coding. The speaker was a test engineer, who emphasized on avoiding the "if" statements in the code and use polymorphism as much as possible. Also he advocated against global states. I quite agree with him, yet i need a clarification on replacing the global state and "if" statement using polymorphism for the below scenario, I have 3 states in my document. I want to change the state of the UI components based on the document state. Right now, i use "if" blocks and an enumeration type holding the current state of document to transition the states of UI components. eg: enum DOC_STATE { DOC_STATE_A = 0, DOC_STATE_B, DOC_STATE_C }; void QMainWindow::handleUi(_docState) { switch(_docState) { case (DOC_STATE_A): { menu.disable(); .... } case (DOC_STATE_B): { menu.enable(); ... } case (DOC_STATE_C): { ... } } I think i can have separate child classes for each state and have the handleUI() method in each class. Calling handleUi() method calls the right method call. But say i maintain these objects in my doc, how do i switch from one object to other each time there is a transition in state? In other words, how to handle UI transition by tracking the change in state of document without using a global state and "if" or Switch statements? I use Qt. Thanks.
If you are using Qt, take a look at The Qt State Machine Framework and the State Machine Examples. No need to re-invent the wheel when your framework already provides a sports car :)
3,088,231
3,088,886
How to achieve better efficiency re-inserting into sets in C++
I need to modify an object that has already been inserted into a set. This isn't trivial because the iterator in the pair returned from an insertion of a single object is a const iterator and does not allow modifications. So, my plan was that if an insert failed I could copy that object into a temporary variable, erase it from the set, modify it locally and then insert my modified version. insertResult = mySet.insert(newPep); if( insertResult.second == false ) modifySet(insertResult.first, newPep); void modifySet(set<Peptide>::iterator someIter, Peptide::Peptide newPep) { Peptide tempPep = (*someIter); someSet.erase(someIter); // Modify tempPep - this does not modify the key someSet.insert(tempPep); } This works, but I want to make my insert more efficient. I tried making another iterator and setting it equal to someIter in modifySet. Then after deleting someIter I would still have an iterator to that location in the set and I could use that as the insertion location. void modifySet(set<Peptide>::iterator someIter, Peptide::Peptide newPep) { Peptide tempPep = (*someIter); anotherIter = someIter; someSet.erase(someIter); // Modify tempPep - this does not modify the key someSet.insert(anotherIter, tempPep); } However, this results in a seg fault. I am hoping that someone can tell me why this insertion fails or suggest another way to modify an object that has already been inserted into a set. The full source code can be viewed at github.
I hope it isn't bad form to answer my own question, but I would like it to be here in case someone else ever has this problem. The answer of why my attempt seg faulted was given my academicRobot, but here is the solution to make this work with a set. While I do appreciate the other answers and plan to learn about maps, this question was about efficiently re-inserting into a set. void modifySet(set<Peptide>::iterator someIter, Peptide::Peptide newPep) { if( someIter == someSet.begin() ) { Peptide tempPep = (*someIter); someSet.erase(someIter); // Modify tempPep - this does not modify the key someSet.insert(tempPep); } else { Peptide tempPep = (*someIter); anotherIter = someIter; --anotherIter; someSet.erase(someIter); // Modify tempPep - this does not modify the key someSet.insert(anotherIter, tempPep); } } In my program this change dropped my run time by about 15%, from 32 seconds down to 27 seconds. My larger data set is currently running and I have my fingers crossed that the 15% improvement scales.
3,088,236
3,088,477
Duplicate symbol error associated with const char * [] declaration
I'd love help diagnosing the source of a duplicate symbol error that I'm receiving when I try to compile with g++ 4.2.1. The specific error is ld: duplicate symbol _SOCIODEM_FILENAMES in /var/folders/c+/c+eq1Qz1Feye7vxs5mQOUE+++TI/-Tmp-//ccP3yVgF.o and /var/folders/c+/c+eq1Qz1Feye7vxs5mQOUE+++TI/-Tmp-//cc1NqtRL.o collect2: ld returned 1 exit status The error occurs only when I include this declaration in a file called Parameters.h: // Parameters.h #ifndef PARAMETERS_H #define PARAMETERS_H // ...[code snipped]... const int NUM_SOCIODEM_FILES = 5; const char * SOCIODEM_FILENAMES[ NUM_SOCIODEM_FILES ] = { "LSPAN_PDF.txt", "FLEDGE_PDF.txt", "PAIR_PDF.txt", "BIRTH_AGE_PDF.txt", "SPLIT_PDF.txt" }; // ...[code snipped]... #endif I've searched all my files, and this is the only place where SOCIODEM_FILENAMES is declared. When I comment out the declaration, the 'duplicate symbol' error goes away. I'm unfamiliar with linker errors (if that's what this is) and would appreciate help troubleshooting the problem. All my header files have #ifndef...#define...#endif wrappers. My compile command is g++ -o a.out -I /Applications/boost_1_42_0/ Host.cpp Simulation.cpp main.cpp Rdraws.cpp Thanks in advance. Solution summary I now have in Parameters.h: const char * const SOCIODEM_FILENAMES[ NUM_SOCIODEM_FILES ] = { "LSPAN_PDF.txt", "FLEDGE_PDF.txt", "PAIR_PDF.txt", "BIRTH_AGE_PDF.txt", "SPLIT_PDF.txt" }; All other definitions and declarations in Parameters.h are unchanged. Andrey and other commenters summarize an alternative approach using extern, which is overkill for my purposes.
For some reason none of the answers so far cared to explain the difference between your integer NUM_SOCIODEM_FILES object and array SOCIODEM_FILENAMES object. The latter triggers the linker error for the reasons already explained: because you include you header file into multiple implementation files. Yet, the former would link without any problems (because there are indeed no problems with NUM_SOCIODEM_FILES declaration). Why? The reason for this is that your NUM_SOCIODEM_FILES object is declared const. In C++ const objects have internal linkage by default, meaning that they do not cause linking problems even if they are defined in multiple implementation files. In other words, in C++ your NUM_SOCIODEM_FILES is equivalent to static const int NUM_SOCIODEM_FILES = 5; /* internal linkage */ which is why it does not lead to any linking problems. At the same time your SOCIODEM_FILENAMES is not declared constant, which is why it gets external linkage by default and eventually leads to linker errors. But if you declare your SOCIODEM_FILENAMES as const as well, the problem will go away const char * const SOCIODEM_FILENAMES[ NUM_SOCIODEM_FILES ] = { ... Note where the extra const is placed in the declaration. If you just add that extra const and leave everything else as is (i.e. keep the definition if SOCIODEM_FILENAMES in the header file), the linker will not report the error even if you include your header file into multiple translation units. This is not a recommended approach though, since that way you will give your SOCIODEM_FILENAMES internal linkage and end up with a standalone copy of SOCIODEM_FILENAMES array in each translation unit - something that might work fine but still makes very little sense. So, for your array, it is normally better to use the extern approach recommended in other answers. However, note that you shouldn't normally do it for NUM_SOCIODEM_FILES declaration!!! It is fine as it is, defined in the header file. Unless you are trying to do something unusual, scalar constants should normally be defined with initializer in the header files - that way they can be seen as compile-time constants in all translation units, which is a rather valuable thing to have. So, beware of the strange advice present in some other answers to move the definition of NUM_SOCIODEM_FILES into .cpp file as well - this actually makes no sense and is a totally wrong thing to do.
3,088,395
3,088,413
How do I set the windows system clock to the right local time using C++?
Right now I do something like this: SYSTEMTIME st; st.wHour = 6; st.wMinute = 23; BOOL result = SetSystemTime(&st); The goal is to get it to show that exact time on my local machine. When I run the program it changes it to 8:23 instead of 6:23. How can I get it to show the correct local time?
SetSystemTime() expects the provided time to be in UTC. If you want to set the time using the local time, use SetLocalTime().
3,088,464
3,088,474
Can C++ assignment operators be free functions?
I'm trying something like this: Foo & operator=(Foo & to, const Bar &from); But I'm getting this error: E2239 'operator =(Foo &, const Bar &)' must be a member function Are there limitations on which operators can/cannot be defined as Free Functions, and if so, why?
The assignment operator must be a non-static member function and must have exactly one parameter: An assignment operator shall be implemented by a non-static member function with exactly one parameter (C++03 13.5.3/1). operator(), operator[], and operator-> must also be implemented as non-static member functions. Class-specific operator new and operator delete (and variants thereof) must be implemented as static member functions (note that these are implicitly static, even if they are not declared with the static keyword).
3,088,555
3,088,615
How do I set the date to the next weekday of my choice using c++?
I would like to determine the next date that has a day of the week value equal to something I specify. For example, today is 6/21/2010 and the day of week value is 1 b/c today is a Monday. How do I find the next date with let's say a day of week value of 3. I would like to consider all cases that come close to the end of something including month and year. Is there any easy way to do this or do I have to manually check to see if it's close to the end of the month or year and make adjustments accordingly? I feel there is an easily and better solution than doing that.
You can stuff your values into a struct tm, and then normalize them with a call to mktime. This will ignore the day of week and day of year on input, and normalize the other values. For example, you can feed it an input of February 31st, and it'll convert that to March 3rd (or March 2nd for a leap year). To use this, the normal sequence would be to call time to get the current time as a time_t. Then convert that to a struct tm with a call to localtime. Adjust the time in the struct tm as needed (e.g., if it says today is Tuesday, and you want Friday, add three to the day of the month). Then call mktime to normalize the values, in case you've (for example) overflowed from one week/month/year to the next.
3,088,557
3,088,731
Are you aware of any lexical analyzer or lexer in Qt?
Are you aware of any lexical analyzer or lexer in Qt? I need it for parsing text files.
It is kinda interesting how Qt has evolved into an all-compassing framework that makes the programmer that uses it believe that anything that is useful has to start with the letter Q. Very dot-netty. Qt is just a class library that runs on top of the language, it doesn't preclude using everyday libraries that get a job done. Especially when that's a library that has little to do with presenting a user interface, the job that Qt does so well. There are many libraries that get lexical analysis and parsing done well. That starts with Lex and Yacc, Flex and Bison next, etcetera. You only have to Qt enable it for error messages, they readily support that.
3,088,581
3,088,889
segfault when trying to access a string member of a class
I have a class Message that has a std::string as a data member, defined like this: class Message { // Member Variables private: std::string text; (...) // Member Functions public: Message(const std::string& t) : text(t) {} std::string getText() const {return text;} (...) }; This class is used in a vector in another class, like this: class Console { // Member Variables private: std::vector<Message> messageLog; (...) // Member Functions public: Console() { messageLog.push_back(Message("Hello World!")); } void draw() const; }; In draw(), there's an iterator that calls getText(). When it does, the program segfaults. I've determined that text is valid inside the Message constructor. However, I can't tell if it's valid from inside Console. I'm assuming it is, but if I try to inspect indices of Console's messageLog, gdb tells me this: (gdb) p messageLog[0] One of the arguments you tried to pass to operator[] could not be converted to what the function wants. Anyone know what's going on? EDIT: here's draw(). TCODConsole is part of a curses library I'm using, and so this function prints each message in Console to a part of the curses screen. TL and BR are Point member objects (two ints) that tell where on the screen to draw Console. I left out parts of Message and Console in the original question to hopefully make things clearer, but if you need me to post the entire classes then I can. They aren't too long. void Console::draw() const { int x = TL.getX(), y = TL.getY(); int width = BR.getX() - TL.getX(); int height = BR.getY() - TL.getY(); // draw the Console frame TCODConsole::root->printFrame(x, y, width, height, true); // print the Console's messages vector<Message>::const_iterator it; for(it=messageLog.begin(); it<messageLog.begin()+height-1; ++it) { string message = "%c" + it->getText(); TCODConsole::setColorControl(TCOD_COLCTRL_1, it->getForeColor(), it->getBackColor()); y += TCODConsole::root->printRectEx(x, y, width, height, TCOD_BKGND_NONE, TCOD_LEFT, message.c_str(), TCOD_COLCTRL_1); } }
My guess is that by the point you use it->getText(), the iterator is NULL. Add a check it != messageLog.end() when you walk the array, and before calling it->getText().
3,088,607
3,088,678
How do I concurrently download and convert a binary file using threads?
I have a program that downloads a binary file, from another PC. I also have a another standalone program that can convert this binary file to a human readable CSV. I would like to bring the conversion tool "into" the download tool, creating a thread in the download tool that kicks off the conversion code (so it can start converting while it is downloading, reducing the total time of download and convert independently). I believe I can successfully kick off another thread but how do I synchronize the conversion thread with the main download? i.e. The conversion catches up with the download, needs to wait for more to download, then start converting again, etc. Is this similar to the Synchronizing Execution of Multiple Threads ? If so does this mean the downloaded binary needs to be a resource accessed by semaphores? Am I on the right path or should i be pointed in another direction before I start? Any advice is appreciated. Thank You.
This is a classic case of the producer-consumer problem with the download thread as the producer and the conversion thread as the consumer. Google around and you'll find an implementation for your language of choice. Here are some from MSDN: How to: Implement Various Producer-Consumer Patterns.
3,088,725
3,088,913
(C++)Code:: blocks does not recognize QT4 classes
So far I have worked in the console and a few days ago decided to try the QT GUI. I downloaded the QT SDK , install it, adjust the location of QT and set up the PATH Environment Variable -> per the instructions on the site. I opened a new Qt4 project in Code:: Blocks-in and it seemed that everything was OK. There is by default an example: #include <QApplication> #include <QFont> #include <QPushButton> int main(int argc, char* argv[]) { QApplication app(argc, argv); QPushButton quit("Quit"); quit.resize(75, 30); quit.setFont(QFont("Times", 18, QFont::Bold)); QObject::connect(&quit, SIGNAL(clicked()), &app, SLOT(quit())); quit.show(); return app.exec(); } Started it an it was all OK. After that I went to a tutorial on the official site and there is a final example. Some kind of simple game.I have done copy-paste of all .h and .cpp files and then put them in current project to see how it works but then problems arise. Code::Blocks does not recognize some classes. For example :: #include QTimer : No such file or directory #include QRect : No such file or directory I uninstall QT and re-installed and configured everything again but the problem does not go out. These classes are not working nor in the default example :: #include <QApplication> #include <QFont> #include <QPushButton> #include <QTimer> does not have real purpose , just for illustration int main(int argc, char* argv[]) { QApplication app(argc, argv); QPushButton quit("Quit"); quit.resize(75, 30); quit.setFont(QFont("Times", 18, QFont::Bold)); QObject::connect(&quit, SIGNAL(clicked()), &app, SLOT(quit())); quit.show(); return app.exec(); } ba\107\main.cpp|4|QTimer: No such file or directory| ||=== Build finished: 1 errors, 0 warnings ===| I dont now how much classes don work properly , this is just some of them. Not to reveal hot water for days on google looking for a solution, maybe for some of you , this is a bizarrely easy problem. Thanks
You need to either spend time monkeying with the default include search path, or else just provide a more explicit path the header you want to include. I was able to reproduce your problem with Code::Blocks 10.05 (with bundled gcc) on Windows XP/32 and a previously installed Qt 4.6. Here is the slightly changed version of your code that I was able to build without any problem: #include <QApplication> #include <QFont> #include <QPushButton> #include <QtCore/QTimer> int main(int argc, char* argv[]) { QApplication app(argc, argv); QPushButton quit("Quit"); quit.resize(75, 30); quit.setFont(QFont("Times", 18, QFont::Bold)); QObject::connect(&quit, SIGNAL(clicked()), &app, SLOT(quit())); quit.show(); return app.exec(); } Take a look in your Qt install directory. You'll be able to see the include directory, and where all the headers are within it if you run into this problem with any other headers. It looks like the Code::Blocks projects sets up the QtGui directory as an include search path by default, which is why you didn't need to explicitly mention it for including QPushButton and whatnot.
3,088,783
3,088,849
Suitability of C# for clustered calculation-heavy apps?
I'm preparing to write a photonic simulation package that will run on a 128-node Linux and Windows cluster, with a Windows-based client for designing jobs (CAD-like) and submitting them to to the cluster. Most of this is well-trod ground, but I'm curious how C# stacks up to C++ in terms of real number-crunching ability. I'm very comfortable with both languages, but I find the superior object model and framework support of C# with .NET or Mono incredibly enticing. However, I can't, with this application, sacrifice too much in processing power for the sake of developer preference. Does anyone have any experience in this area? Are there any hard benchmarks available? I'd assume that the the final machine code would be optimized using the same techniques whether it comes from a C# or C++ source, especially since that typically takes place at the pcode/IL level.
The optimisation techniques employed by C# and native C++ are vastly different. C# compilers emit IL, which is only marginally optimised and then JIT'ed to binary code when it is about to execute for the first time. Most of the optimisation work happens inside the JIT compiler. This has pros and cons. JIT has time budgets, which limits how much effort it can expend on optimisation. But it also has intimate knowledge of the hardware it is actually running on, so it can (in theory) make transparent use of newer CPU opcodes and detailed knowledge of performance data such as a pipeline hazards database. In practice, I don't know how significant the latter is. I do know that at least Mono will parallelise some loops automatically if it finds itself running on a CPU with SSE (SSE2, perhaps?), which may be a big deal for your scenario.
3,088,919
3,089,123
Expected specifier-qualifier-list before... Error in C++/Objective-C iPhone project
So I'm going through the first tutorial in O'Reilly's iPhone 3D Programming book. At this point in the tutorial, it pulls all the OpenGL ES stuff into a seperate c++ interface. I have followed the book to the letter, as far as I can tell, yet I can't seem to figure out this compiler error. I'm fairly new to C++ (mostly C# in the past), so I'm sure it's something stupid. Below is the current state of all the relevant files. I have a c++ header file called IRenderingEngine.hpp with the following contents: enum DeviceOrientation { Unknown, Portrait, PortraitUpsideDown, LandscapeLeft, LandscapeRight, FaceUp, FaceDown, }; struct IRenderingEngine* CreateRenderer1(); struct IRenderingEngine { virtual void Initialize(int width, int height) = 0; //Compiler error "expected specifier-qualifier-list before 'virtual' virtual void Render() const = 0; virtual void UpdateAnimation(float timeStep) = 0; virtual void OnRotate(DeviceOrientation newOrientation) = 0; virtual ~IRenderingEngine() {} }; I have an objective-c/c++ header file called GLView.h that looks like this: #import "IRenderingEngine.hpp" #import <OpenGLES/EAGL.h> #import <QuartzCore/QuartzCore.h> @interface GLView : UIView { EAGLContext* m_context; IRenderingEngine* m_renderingEngine; //Compiler error: Expected specifier-qualifier-list before "IRenderingEngine" float m_timeStamp; } - (void) drawView: (CADisplayLink*) displayLink; - (void) didRotate: (NSNotification*) notification; @end And finally, a GLView.mm file with a barebones implementation: #import "GLView.h" @implementation GLView + (Class) layerClass { return [CAEAGLLayer class]; } - (id)initWithFrame:(CGRect)frame { return self; } - (void) drawView:(CADisplayLink *)displayLink { } -(void) didRotate:(NSNotification *)notification { } @end
This error message e.g. occurs if one of your two headers gets included in a plain Objective-C source file, which doesn't know anything about handling C++ code. To allow GLView to be used from plain Objective-C sources, use only a forward declaration for the rendering engine and don't include the C++ header in GLView.h: // GLView.h: struct IRenderingEngine; @interface GLView : UIView { struct IRenderingEngine* m_renderingEngine; // ... @end // GLView.mm: #import "IRenderingEngine.hpp" // ... etc. Alternatively you can use opaque pointers for wrapping C++ instances to keep the Objective-C interface more stable, see e.g. Rob Napiers post on the subject. When this is fixed, you still need to fix the declaration for CreateRenderer1() as others pointed out - either forward-declare struct IRenderingEngine; before the function or just move it after the definition of the struct.
3,088,955
3,088,990
Recommendations for Secure TCP Connections For Consumer Application
I'm designing a training program in C++ that will be distributed to a large number of facilities, most of which won't have much in the way of an IT staff. The program connects via a TCP connection to a central database which stores various pieces of data for research and evaluation purposes. The problem I have is that I would like to make the transmission secure, and the most commonly recommended way to do that seems to be OpenSSL - which seems all well and good, but I've got a problem. As I understand it, OpenSSL must be installed specifically on each of the systems. The facilities won't have the expertise required to compile and install the source on their systems, the computers will be sufficiently varied (all Windows boxes, but of varying make and quality) to rule out distributing a specifically-compiled binary, and continent-wide distribution makes it impossible for my team to personally set it up. Does anyone have a recommendation for how to solve this problem? Am I simply incorrect in my assumptions, and one can distribute it without installation? If not, is there a more practical alternative?
As long as all your machines are XP+, with two versions of OpenSSL you should be ready, one for 32bits and one for 64bits. Just provide two separate installers and that should be it. There's no need to compile for each machine. Just remember to include the Visual C++ redistributable package in your installer as well. If you have to support ancient Windows versions, it gets a bit more complex but not that much.
3,088,987
3,089,069
interface forwarding from member variable using C++ templates
How do I say: template<typename T> class X { // if T has method x(), define // Y x() { return t.x() } T t; };
Just define it. If X::x isn't called, then T::x doesn't have to exist either. If X::x is called and T::x doesn't exist, the error message will point to the use of X::x. Most compilers would use wording along the lines of: "Unknown identifier x while compiling Y X<Something>::x(void) within this context: whatever called X::x() for a Something that doesn't support it". EDIT: Since you're using C++0x, by all means use decltype: template<typename T> class Forwards { T t; public: decltype(this->t.x()) x() { return this->t.x(); } }; I'm not 100% sure about whether to use decltype(T::x()), decltype(t.x()), or decltype(this->t.x()), but I'm pretty sure this should work. If t doesn't supply x, then the Forwards::x() function wouldn't be able to be instantiated. This still isn't perfect forwarding, since you need to know the argument list a-priori, but now you can deal with return type variation.