question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,339,077
2,339,088
Is it possible I have forward declaration of a class, without making them reference or pointer in header file
// I prefer to perform forward declaration on myclass, as I do not // wish to ship "myclass.h" to client // However, the following code doesn't allow me to do so, as class defination // is needed in header file. // // a.h #include "myclass.h" class a { public: a(); myclass me; }; I try to do it another way around. However, I need to use dynamic allocation, which I usually try to avoid. // a.h class myclass; class a { public: a(); myclass& me; }; // But I just wish to avoid new and delete, is it possible? // a.cpp #include "myclass.h" a::a() : me(*(new myclass())) { } a::~a() { delete *myclass; } Is it possible to do so, without using any reference or pointer? (Or more precisely, without using new/delete)
No. The reason being, that the compiler needs to know the size of your object (i.e. myclass) in order to know the size of the object (i.e. class "a" in your example). If you have only forward declared myclass, the compiler has no way of knowing the size that must be allocated for the "a" class. A reference or pointer alleviates this b/c a pointer or reference has a defined size at the time of compilation and thus the compiler knows the memory requirements.
2,339,167
2,339,198
How to forward declare the following template class
I try to forward declare concurrent_bounded_queue ; class MyClass { namespace tbb { template<typename T> class cache_aligned_allocator; template<class T, class A = cache_aligned_allocator> class concurrent_bounded_queue; }; // I wish to maintain this syntax. tbb::concurrent_bounded_queue<std::string>& concurrentBoundedQueue; } I get the following error : error C3203: 'cache_aligned_allocator' : unspecialized class template can't be used as a template argument for template parameter 'A', expected a real type error C2955: 'tbb::cache_aligned_allocator' : use of class template requires template argument list c:\projects\vitroxreport\src\Executor.h(21) : see declaration of 'tbb::cache_aligned_allocator' May I know how I can avoid? Thanks.
Allocator is a template, but second argument of the queue is concrete class. Try this: class MyClass { namespace tbb { template<typename T> class cache_aligned_allocator; template<class T, class A = cache_aligned_allocator<T> > class concurrent_bounded_queue; }; tbb::concurrent_bounded_queue<std::string>& concurrentBoundedQueue; };
2,339,226
2,339,244
Typedef compilation error on function overload
Why can't I compile the program 1 when the the program 2 is working fine ? Why is it's behavior different? Program 1: #include <iostream> typedef int s1; typedef int s2; void print(s1 a){ std::cout << "s1\n"; } void print(s2 a){ std::cout << "s2\n"; } int main() { s1 a; s2 b; print(a); print(b); return 0; } Program 2: #include <iostream> typedef struct{int a;} s1; typedef struct{int a;} s2; void print(s1 a){ std::cout << "s1\n"; } void print(s2 a){ std::cout << "s2\n"; } int main() { s1 a; s2 b; print(a); print(b); return 0; } This is a bug reproduce from templated class, How can I verify if two template argument are from the same type (in the case of the program 1)
Typedefs don't define new types, they merely create aliases for existing types. In your first program s1 and s2 are both aliases for int. In your second program they are aliases for two different structures that just happen to be identical in structure. You could have assigned names to the two structures which would have made this clearer: // Semantically identical to program 2 typedef struct a {int a;} s1; typedef struct b {int a;} s2; On the other hand if you made them aliases for the same type then the second program would fail just like the first: // Different from program 2. This will draw a compile error. struct s {int a;}; typedef struct s s1; typedef struct s s2;
2,339,381
2,373,761
Converting C++ TCP/IP applications from IPv4 to IPv6. Difficult? Worth the trouble?
Over the years I've developed a small mass of C++ server/client applications for Windows using WinSock (Routers, Web/Mail/FTP Servers, etc... etc...). I’m starting to think more and more of creating an IPv6 version of these applications (While maintaining the original IPv4 version as well, of course). Questions: What pitfalls might I run into? Is the porting/conversion difficult? Is the conversion worth it? For a reference (or for fun), you can sneek a peak of the IPv4 code at the core of my applications.
getaddrinfo and getnameinfo are your friends.. As much as possible I suggest they be your best friends in your quest to provide IPv4 and IPv6 support in an existing application. If done right by adding IPv6 support you also end up abstracting the system to the point where an unknown future IP protocol can run without code modification. Normally when connecting you would fill out a socket structure, port, address family, IP address, converting address/ports to network byte order, etc. With getaddrinfo you send an IP address or hostname and port or port name, and it returns a linked list with the structures and everything ready to be passed directly into socket() and connect(). getaddrinfo is critical for working with both IP protocols as it knows if the host has IPv6 or IPv4 connectivity and it knows if the peer does as well by looking at DNS AAAA vs A records and dynamically figures out which protocol(s) are available to service the specific connection request. I highly advise against use of inet_pton(), inet_addr() or smiliar devices that are IP version specific. On the Windows platform specifically inet_pton() is not compatible with earlier versions of MS Windows (XP, 2003 et al.) unless you roll your own. Also advise against separate versions for IPv4 and IPv6... This is unworkable as a technical solution because in the near future both protocols will need to be used concurrently and people may not know ahead of time which to use. The socket interfaces are abstract and it's easy to detect dualstack or IPv6 support by attempting to create an IPv6 socket or attempt to set the IPv6 dualstack socket option for listeners. There is no reason the resulting application won't run on a system that does not support or know about IPv6. For outgoing connections use PF_UNSPEC in getaddrinfo so that the address family is chosen for you when making outgoing connections. This, IMHO, is better than the dualstack approach because it allows platforms that do not support dualstack to work. For incoming connections you can either bind IPv4/IPv6 sockets separately if it's reasonable given the design or use dualstack if you can't do separate listeners. When using dualstack getnameinfo returns an IPv6 address for IPv4 addresses which IMHO ends up being quite useless. A small utility routine can convert the string to a normal IPv4 address. From my experience when done right you've removed dependencies on specific IP versions and ended up with less socket management code than you started.
2,339,445
2,339,553
Error launching a Java app from a Win32 C++ app using CreateProcess
I'm trying to launch a Java app from a C++ app using the following code: #include <windows.h> #include <memory.h> #include <tchar.h> int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { STARTUPINFOW siStartupInfo; PROCESS_INFORMATION piProcessInfo; memset(&siStartupInfo, 0, sizeof(siStartupInfo)); memset(&piProcessInfo, 0, sizeof(piProcessInfo)); if (CreateProcess(TEXT("c:\\java\\jre\\bin\\java.exe"), TEXT("-jar testapp.jar"), NULL, NULL, false, CREATE_DEFAULT_ERROR_MODE, NULL, NULL, &siStartupInfo, &piProcessInfo) == false) { MessageBox(NULL, L"Could not load app", L"Error", 0); } CloseHandle(piProcessInfo.hProcess); CloseHandle(piProcessInfo.hThread); return 0; } When I build and run the program I get the following error: Exception in thread "main" java.lang.NoClassDefFoundError: testapp/jar Caused by: java.lang.ClassNotFoundException: testapp.jar at: java.net.URLClassLoader$1.run(Uknown Source) at: java.security.AccessController.doPrivileged(Native Method) at: java.net.URLClassLoader.findClass(Uknown Source) at: java.lang.ClassLoader.loadClass(Uknown Source) at: sun.misc.Launcher$AppClassLoader.loadClass(Uknown Source) at: java.lang.ClassLoader.loadClass(Uknown Source) Could not find the main class: testapp.jar. Program will exit. The testapp.jar file is a runnable JAR file exported from an Eclipse project with a single class in it: public class Test { public static void main(String[] args) { System.out.println("test"); } } The EXE and JAR file are in the exact same folder, and I'm running the EXE from the command line. If I run the JAR directly by putting c:\java\jre\bin\java.exe -jar testapp.jar into the command-prompt everything works as expected. Does anyone have any idea what's going on here? EDIT: Thank you all for your help, but it looks like I've got it working now.
Solved it. I used: if (CreateProcess(TEXT("C:\\Program Files\\Java\\jre6\\bin\\java.exe"), TEXT(" -jar test.jar"), NULL, NULL, false, CREATE_DEFAULT_ERROR_MODE, NULL, NULL, &siStartupInfo, &piProcessInfo) == false) { MessageBox(NULL, L"Could not load app", L"Error", 0); } Whereas you've used: if (CreateProcess(TEXT("C:\\Program Files\\Java\\jre6\\bin\\java.exe"), TEXT("-jar test.jar"), NULL, NULL, false, CREATE_DEFAULT_ERROR_MODE, NULL, NULL, &siStartupInfo, &piProcessInfo) == false) { MessageBox(NULL, L"Could not load app", L"Error", 0); } which, when I used it, replicates your error. The difference is a space preceding the -jar switch and why that should be, I don't know, I stumbled upon it in error!
2,339,459
2,339,496
Is there any reason a .Net windows programmer needs to learn C or C++ anymore?
Can someone describe what advantages a C or C++ programmer would have over a .Net programming when developing for Windows?
There's a saying that every sufficiently complex C application ultimately ends up reimplementing parts of C++. The same goes with C++ programs and higher languages. Learning C and C++ will indirectly make you a better programmer by helping you gain a deeper understanding of how .Net actually works, and why the designers made the choices they made. A programmer is only as good as his understanding of the layers beneath him. .Net does a pretty good job of abstracting a lot of machine architecture issues out of view, but it's not perfect. There are still leaks in the abstraction layer where an understanding of lower-level issues will help you make good decisions at the .Net layer. A short, incomplete list of these issues includes: Interop with native code, especially with the Windows API CPU cache coherency (if you don't believe me, google the slides from the PLINQ presentation at PDC '09) Value type performance vs. Reference type performance (this is firmly footed in the .Net world, but learning C/C++ makes the differences between stack and heap allocations more explicit in some ways). Kernel scheduling issues (i.e. why it's a bad idea to spin off 1000 threads) Understanding the garbage collector is also best achieved by writing a few memory management schemes in non-garbage collected languages.
2,339,487
2,339,510
Calculate Angle of 2 points
Given P1 and P2, how can I get the angle from P1 to P2? Thanks
It's just float angle = atan2(p1.y - p2.y, p1.x - p2.x). Of course the return type is in radians, if you need it in degrees just do angle * 180 / PI
2,339,558
2,339,619
Mocking non-virtual methods in C++ without editing production code?
I am a fairly new software developer currently working adding unit tests to an existing C++ project that started years ago. Due to a non-technical reason, I'm not allowed to modify any existing code. The base class of all my modules has a bunch of methods for Setting/Getting data and communicating with other modules. Since I just want to unit testing each individual module, I want to be able to use canned values for all my inter-module communication methods. I.e. for a method Ping() which checks if another module is active, I want to have it return true or false based on what kind of test I'm doing. I've been looking into Google Test and Google Mock, and it does support mocking non-virtual methods. However the approach described (http://code.google.com/p/googlemock/wiki/CookBook#Mocking_Nonvirtual_Methods) requires me to "templatize" the original methods to take in either real or mock objects. I can't go and templatize my methods in the base class due to the requirement mentioned earlier, so I need some other way of mocking these virtual methods Basically, the methods I want to mock are in some base class, the modules I want to unit test and create mocks of are derived classes of that base class. There are intermediate modules in between my base Module class and the modules that I want to test. I would appreciate any advise! Thanks, JW EDIT: A more concrete examples My base class is lets say rootModule, the module I want to test is leafModule. There is an intermediate module which inherits from rootModule, leafModule inherits from this intermediate module. In my leafModule, I want to test the doStuff() method, which calls the non virtual GetStatus(moduleName) defined in the rootModule class. I need to somehow make GetStatus() to return a chosen canned value. Mocking is new to me, so is using mock objects even the right approach?
I would write a Perl/Ruby/Python script to read in the original source tree and write out a mocked source tree in a different directory. You don't have to fully parse C++ in order to replace a function definition.
2,339,593
6,578,941
overriding ctype<wchar_t>
I'm writing a lambda calculus interpreter for fun and practice. I got iostreams to properly tokenize identifiers by adding a ctype facet which defines punctuation as whitespace: struct token_ctype : ctype<char> { mask t[ table_size ]; token_ctype() : ctype<char>( t ) { for ( size_t tx = 0; tx < table_size; ++ tx ) { t[tx] = isalnum( tx )? alnum : space; } } }; (classic_table() would probably be cleaner but that doesn't work on OS X!) And then swap the facet in when I hit an identifier: locale token_loc( in.getloc(), new token_ctype ); … locale const &oldloc = in.imbue( token_loc ); in.unget() >> token; in.imbue( oldloc ); There seems to be surprisingly little lambda calculus code on the Web. Most of what I've found so far is full of unicode λ characters. So I thought to try adding Unicode support. But ctype<wchar_t> works completely differently from ctype<char>. There is no master table; there are four methods do_is x2, do_scan_is, and do_scan_not. So I did this: struct token_ctype : ctype< wchar_t > { typedef ctype<wchar_t> base; bool do_is( mask m, char_type c ) const { return base::do_is(m,c) || (m&space) && ( base::do_is(punct,c) || c == L'λ' ); } const char_type* do_is (const char_type* lo, const char_type* hi, mask* vec) const { base::do_is(lo,hi,vec); for ( mask *vp = vec; lo != hi; ++ vp, ++ lo ) { if ( *vp & punct || *lo == L'λ' ) *vp |= space; } return hi; } const char_type *do_scan_is (mask m, const char_type* lo, const char_type* hi) const { if ( m & space ) m |= punct; hi = do_scan_is(m,lo,hi); if ( m & space ) hi = find( lo, hi, L'λ' ); return hi; } const char_type *do_scan_not (mask m, const char_type* lo, const char_type* hi) const { if ( m & space ) { m |= punct; while ( * ( lo = base::do_scan_not(m,lo,hi) ) == L'λ' && lo != hi ) ++ lo; return lo; } return base::do_scan_not(m,lo,hi); } }; (Apologies for the flat formatting; the preview converted the tabs differently.) The code is WAY less elegant. I does better express the notion that only punctuation is additional whitespace, but that would've been fine in the original had I had classic_table. Is there a simpler way to do this? Do I really need all those overloads? (Testing showed do_scan_not is extraneous here, but I'm thinking more broadly.) Am I abusing facets in the first place? Is the above even correct? Would it be better style to implement less logic?
(It's been a year with no substantive answer, and I've learned a lot about iostreams in the meantime…) The custom facet exists exclusively to serve the string extraction operator in >> token. That operator is defined in terms of use_facet< ctype< wchar_t > >( in.getloc() ).is( ios::space, c ) "for the next available input character c." (§21.3.7.9) ctype::is is simply a stub for ctype::do_is, so it would seem that do_is is sufficient. Nevertheless, recent versions of the GCC standard library do implement operator>> in terms of scan_is. The catch is that do_scan_is is then implemented as a series of calls to do_is, virtual dispatch and all. The header file describes do_scan_is as a hook for user optimization. So, it would seem that the as-if rule shelters an implementation that only provides the first override. Note that the second override, which retrieves mask values, is an odd one out. It could be implemented in terms of the first, by inefficiently building the mask bit by bit. In GCC it is implemented in terms of system calls, inefficently building the mask bit by bit with 15 calls per character. This seems to sacrifice both performance and compatibility. Fortunately it seems nobody uses it. Anyway, this is all well and good, but simply writing a tokenizer using streambuf_iterator<wchar_t> is easier, far more extensible, and simplifies exception handling.
2,339,679
2,339,910
What are the differences between .so and .dylib on macOS?
.dylib is the dynamic library extension on macOS, but it's never been clear to me when I can't / shouldn't use a traditional unix .so shared object. Some of the questions I have: At a conceptual level, what are the main differences between .so and .dylib? When can/should I use one over the other? Compilation tricks & tips (For example, the replacement for gcc -shared -fPIC, since that doesn't work on osx)
The Mach-O object file format used by Mac OS X for executables and libraries distinguishes between shared libraries and dynamically loaded modules. Use otool -hv some_file to see the filetype of some_file. Mach-O shared libraries have the file type MH_DYLIB and carry the extension .dylib. They can be linked against with the usual static linker flags, e.g. -lfoo for libfoo.dylib. They can be created by passing the -dynamiclib flag to the compiler. (-fPIC is the default and needn't be specified.) Loadable modules are called "bundles" in Mach-O speak. They have the file type MH_BUNDLE. They can carry any extension; the extension .bundle is recommended by Apple, but most ported software uses .so for the sake of compatibility. Typically, you'll use bundles for plug-ins that extend an application; in such situations, the bundle will link against the application binary to gain access to the application’s exported API. They can be created by passing the -bundle flag to the compiler. Both dylibs and bundles can be dynamically loaded using the dl APIs (e.g. dlopen, dlclose). It is not possible to link against bundles as if they were shared libraries. However, it is possible that a bundle is linked against real shared libraries; those will be loaded automatically when the bundle is loaded. Historically, the differences were more significant. In Mac OS X 10.0, there was no way to dynamically load libraries. A set of dyld APIs (e.g. NSCreateObjectFileImageFromFile, NSLinkModule) were introduced with 10.1 to load and unload bundles, but they didn't work for dylibs. A dlopen compatibility library that worked with bundles was added in 10.3; in 10.4, dlopen was rewritten to be a native part of dyld and added support for loading (but not unloading) dylibs. Finally, 10.5 added support for using dlclose with dylibs and deprecated the dyld APIs. On ELF systems like Linux, both use the same file format; any piece of shared code can be used as a library and for dynamic loading. Finally, be aware that in Mac OS X, "bundle" can also refer to directories with a standardized structure that holds executable code and the resources used by that code. There is some conceptual overlap (particularly with "loadable bundles" like plugins, which generally contain executable code in the form of a Mach-O bundle), but they shouldn't be confused with Mach-O bundles discussed above. Additional references: Fink Porting Guide, the basis for this answer (though pretty out of date, as it was written for Mac OS X 10.3). ld(1) and dlopen(3) Dynamic Library Programming Topics Mach-O Programming Topics
2,339,702
2,340,294
Setting Resized bitmap file to an MFC Picture Control
Is there an easier way to do it than this, and if this is the only way, are there any potential memory leaks here? CImage img1; int dimx = 100, dimy = 100; img1.Load(filename); //filename = path on local system to the bitmap CDC *screenDC = GetDC(); CDC *pMDC = new CDC; pMDC->CreateCompatibleDC(screenDC); CBitmap *pb = new CBitmap; pb->CreateCompatibleBitmap(screenDC, dimx, dimy); CBitmap *pob = pMDC->SelectObject(pb); pMDC->SetStretchBltMode(HALFTONE); img1.StretchBlt(pMDC->m_hDC,0, 0, dimx, dimy, 0, 0, img1.GetWidth(), img1.GetHeight(), SRCCOPY); pMDC->SelectObject(pob); CImage new_image; new_image.Attach((HBITMAP)(*pb)); // m_pictureCtrl.SetBitmap(new_image.Detach()); ReleaseDC(screenDC);
I see no need for the CImage new_image (as SetBitmap takes a HBITMAP which you already have through pb) and pb and pMDC must be deleted (after detaching the HBITMAP), but for the rest it seems correct. CImage img1; int dimx = 100, dimy = 100; img1.Load(filename); //filename = path on local system to the bitmap CDC *screenDC = GetDC(); CDC mDC; mDC.CreateCompatibleDC(screenDC); CBitmap b; b.CreateCompatibleBitmap(screenDC, dimx, dimy); CBitmap *pob = mDC.SelectObject(&b); mDC.SetStretchBltMode(HALFTONE); img1.StretchBlt(mDC.m_hDC, 0, 0, dimx, dimy, 0, 0, img1.GetWidth(), img1.GetHeight(), SRCCOPY); mDC.SelectObject(pob); m_pictureCtrl.SetBitmap((HBITMAP)b.Detach()); ReleaseDC(screenDC); Of course I would put the scaling of the CImage/CBitmap into a separate function (make it reusable).
2,339,759
2,339,938
Why Visual C++ 6 complains on private destructor
The following code works fine for Visual C++ 2008. However, when comes to Visual C++ 6, I get the following error. May I know why, and how I can fix the error, but still make the destructor remains in private. class X { public: static X& instance() { static X database; return database; } private: X() {} // Private constructor ~X() {} // Private destructor X(const X&); // Prevent copy-construction X& operator=(const X&); // Prevent assignment }; int main() { X::instance(); } C:\Projects\ttt6\main.cpp(178) : error C2248: 'X::~X' : cannot access private member declared in class 'X' C:\Projects\ttt6\main.cpp(175) : see declaration of 'X::~X'
The revised sample shows a confirmed compiler bug for VC6 - the common workaround was to simply make the destructor public.
2,339,773
2,369,220
How to do a Extensible Storage Engine (JetBlue) repair in code?
I'm using ESE (JetBlue) in an app, when JetAttachDatabase is called it returns JET_errDatabaseDirtyShutdown. What am I supposed to do in my app? my desire is for any uncommeted transactions to be deleted
Log recovery will be done automatically by the call to JetInit, which will automatically rollback uncomitted transactions. In order for JetInit to work it has to find the logfiles so in this case you have probably either: Deleted the logfiles. Don't do that. Didn't set the logfile path correctly. Always set the same logfile path when initializing so that ESE can find the logs. Moved the database. The logs contain a hard-coded path to the database so moving the database breaks recovery. To deal with this you can set the alternate recovery path system parameter to the directory containing the database.
2,340,005
2,340,225
c++ MFC CBitmap , CImage or BITMAP structure , get resolution (DPI)
HEllo , i can not find any way to get horizontal or/and vertical resolution for bitmap. If you know how to get it, please say it me , Thank you!
Is your question that you want to know the size of the image? CBitmap -> GetBitmapDimension CImage -> GetWidth and GetHeight BITMAP -> bmWidth and bmHeight Or that you want to know the size it will have on a display? GetDeviceCaps(hdc, LOGPIXELSX)
2,340,240
2,340,405
force exit from readline() function
I am writing program in c++ which runs GNU readline in separate thread. When main thread is exited I need to finish the thread in which readline() function is called. The readline() function is returned only when standart input came (enter pressed). Is there any way to send input to application or explicitly return from readline function? Thanks in advance.
Instead of returning from main thread, call exit(errno). All other threads will be killed nastily! Or, if you wanted to be nicer, and depending on your OS, you could send a signal to the readline thread, which would interrupt the syscall. Or, if you wanted to be cleverer, you could run readline in async mode, using a select() loop with a timeout so that your thread never blocks in readine functions, and your thread can clean up after itself.
2,340,281
2,340,309
Check if a string contains a string in C++
I have a variable of type std::string. I want to check if it contains a certain std::string. How would I do that? Is there a function that returns true if the string is found, and false if it isn't?
Use std::string::find as follows: if (s1.find(s2) != std::string::npos) { std::cout << "found!" << '\n'; } Note: "found!" will be printed if s2 is a substring of s1, both s1 and s2 are of type std::string.
2,340,311
2,340,346
posix_memalign for std::vector
Is there a way to posix_memalign a std::vector without creating a local instance of the vector first? The problem I'm encountering is that I need to tell posix_memalign how much space to allocate and I don't know how to say sizeof(std::vector<type>(n)) without actually creating a new vector. Thanks
Well, there are two sizes here. The vector itself is typically no more than a pointer or two to some allocated memory, and unsigned integers keeping track of size and capacity. There is also the allocated memory itself, which is what I think you want. What you want to do is make a custom allocator that the vector will use. When it comes time, it will use your allocator and you can have your own special functionality. I won't go over the full details of an allocator, but the specifics: template <typename T> struct aligned_allocator { // ... pointer allocate(size_type pCount, const_pointer = 0) { pointer mem = 0; if (posix_memalign(&mem, YourAlignment, sizeof(T) * pCount) != 0) { throw std::bad_alloc(); // or something } return mem; } void deallocate(pointer pPtr, size_type) { free(pPtr); } // ... }; And then you'd use it like: typedef std::vector<T, aligned_allocator<T> > aligned_T_vector; aligned_T_vector vec; vec.push_back( /* ... */ ); // array is aligned But to reiterate the first point, the size of a vector is the same regardless of how many elements it's holding, as it only points to a buffer. Only the size of that buffer changes.
2,340,318
2,340,560
How can I visually design a component in C++ Builder?
I have been away from C++ for a couple of years now doing AS3/Flex work. I have gotten used to being able to create a component and place it in design mode with very little fuss and I am struggling to get my head around the C++ Builder way of doing the same thing. I have written many components for C++ Builder in the past, but none of them have been visual. What I would like to do now is create a component for customer search and another for order processing because I want to be able to create a new instance of these on the fly. What I don't want to do is have to place each of the components like the dbgrid and search fields manually in code. I would like to do this (as well as set their properties) in design mode. How do I go about this? I have browsed the source for other Delphi components and I notice they have dfm files which seems to be what I need. How do I do this in C++ Builder? The only option I see is to add a new form if I want a dfm, but this isn't what I want as my components will be based on TPanel. Is there a way to do this or do I have to resort to doing it all in code with no visual reference? Pursuing the DFM idea I did a test this morning where I created a component based on TPanel and added a new form to it which I create and parent in the constructor of the component. In design mode I set the form border to none and placed a grid on it. This all looks OK until I place the component in my application, at that point it looks like a panel with a standard looking form in it and the grid is missing. If I run the app the panel shows as expected, borderless and with a grid. The DFM appears to be ignored in design mode for some reason. If you know a better way to do this than using components then please give me some pointers. Any help and advice will be appreciated beyond words
You might want to have a look at frames (look for "Frame objects"). They are "subforms" you can design visually and then place on forms.
2,340,487
2,341,506
Is the Non-Virtual Interface (NVI) idiom as useful in C# as in C++?
In C++, I often needed NVI to get consistency in my APIs. I don't see it used as much among others in C#, though. I wonder if that is because C#, as a language, offers features that makes NVI unnecessary? (I still use NVI in C#, though, where needed.)
I think the explanation is simply that in C#, "traditional" Java-style OOP is much more ingrained, and NVI runs counter to that. C# has a real interface type, whereas NVI relies on the "interface" actually being a base class. That's how it's done in C++ anyway, so it fits naturally there. In C#, it can still be done, and it is still a very useful idiom (far more so, I'd say, than "normal" interfaces), but it requires you to ignore a built-in language feature. Many C# programmers just wouldn't think of a NVI class as being "a proper interface". I think this mental resistance is the only reason why it's less common in C#.
2,340,506
2,340,523
Updating DataGrid View in Multithreaded Environment
I have set of c++ dlls and a c# exe . My c++ dlls are multi-threaded and they put data into a Database. My c# exe uses Background worker . My c# exe gets these data to a Data table asynchronously. To achieve this I am using named Mutex. My problem is when I assign this Data Table to my grid view It is crashing. I am using delegates and Begin Invoke .
With begin invoke do you mean myDelegate.BeginInvoke? you could try myForm.Invoke this runs the delegate on the UI Thread...
2,340,691
2,340,820
Techniques for generating a 2D game world
I want to make a 2D game in C++ using the Irrlicht engine. In this game, you will control a tiny ship in a cave of some sort. This cave will be created automatically (the game will have random levels) and will look like this: Suppose I already have the the points of the polygon of the inside of the cave (the white part). How should I render this shape on the screen and use it for collision detection? From what I've read around different sites, I should use a triangulation algorithm to make meshes of the walls of the cave (the black part) using the polygon of the inside of the cave (the white part). Then, I can also use these meshes for collision detection. Is this really the best way to do it? Do you know if Irrlicht has some built-in functions that can help me achieve this? Any advice will be apreciated.
Describing how to get an arbitrary polygonal shape to render using a given 3D engine is quite a lengthy process. Suffice to say that pretty much all 3D rendering is done in terms of triangles, and if you didn't use a tool to generate a model that is already composed of triangles, you'll need to generate triangles from whatever data you have there. Triangulating either the black space or the white space is probably the best way to do it, yes. Then you can build up a mesh or vertex list from that, and render those triangles that way. The triangles in the list then also double up for collision detection purposes. I doubt Irrlicht has anything for triangulation as it's quite specific to your game design and not a general approach most people would take. (Typically they would have a tool which permits generation of the game geometry and the navigation geometry side by side.) It looks like it might be quite tricky given the shapes you have there.
2,340,730
22,927,149
Are there C++ equivalents for the Protocol Buffers delimited I/O functions in Java?
I'm trying to read / write multiple Protocol Buffers messages from files, in both C++ and Java. Google suggests writing length prefixes before the messages, but there's no way to do that by default (that I could see). However, the Java API in version 2.1.0 received a set of "Delimited" I/O functions which apparently do that job: parseDelimitedFrom mergeDelimitedFrom writeDelimitedTo Are there C++ equivalents? And if not, what's the wire format for the size prefixes the Java API attaches, so I can parse those messages in C++? Update: These now exist in google/protobuf/util/delimited_message_util.h as of v3.3.0.
I'm a bit late to the party here, but the below implementations include some optimizations missing from the other answers and will not fail after 64MB of input (though it still enforces the 64MB limit on each individual message, just not on the whole stream). (I am the author of the C++ and Java protobuf libraries, but I no longer work for Google. Sorry that this code never made it into the official lib. This is what it would look like if it had.) bool writeDelimitedTo( const google::protobuf::MessageLite& message, google::protobuf::io::ZeroCopyOutputStream* rawOutput) { // We create a new coded stream for each message. Don't worry, this is fast. google::protobuf::io::CodedOutputStream output(rawOutput); // Write the size. const int size = message.ByteSize(); output.WriteVarint32(size); uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size); if (buffer != NULL) { // Optimization: The message fits in one buffer, so use the faster // direct-to-array serialization path. message.SerializeWithCachedSizesToArray(buffer); } else { // Slightly-slower path when the message is multiple buffers. message.SerializeWithCachedSizes(&output); if (output.HadError()) return false; } return true; } bool readDelimitedFrom( google::protobuf::io::ZeroCopyInputStream* rawInput, google::protobuf::MessageLite* message) { // We create a new coded stream for each message. Don't worry, this is fast, // and it makes sure the 64MB total size limit is imposed per-message rather // than on the whole stream. (See the CodedInputStream interface for more // info on this limit.) google::protobuf::io::CodedInputStream input(rawInput); // Read the size. uint32_t size; if (!input.ReadVarint32(&size)) return false; // Tell the stream not to read beyond that size. google::protobuf::io::CodedInputStream::Limit limit = input.PushLimit(size); // Parse the message. if (!message->MergeFromCodedStream(&input)) return false; if (!input.ConsumedEntireMessage()) return false; // Release the limit. input.PopLimit(limit); return true; }
2,340,795
2,340,982
Does function-level linking in VC++ have any negative effects?
Visual C++ has function-level linking. Looks like it's a great thing - it can reduce the size of generated executables. Does it have any negative effects? Will I have to pay anything for the advantages of this option or can I just turn it on and enjoy the benefits?
Actually, there could be some small increase of compilation time. I don't think that it can affect negativily anything else.
2,340,919
2,341,014
Const-Correctness on complex return value
struct Foo { char * DataPtr; }; class ISomeInterface { public: Foo GetFoo( ) const; Foo GetFoo( ); }; The Foo::DataPtr is a pointer to an internal buffer of the object behing ISomeInterface. Is there a way to make sure that the Foo::DataPtr returned by the const version of ISomeInterface::GetFoo is a const char * ?
You need a struct ConstFoo { const char* DataPtr; }; for this. The const in C++ is not transitive. (this is also why you have iterator and const_iterator.)
2,340,930
2,340,942
Stray '\342' in C++ program
I'm getting these errors in my program after pasting in some code: showdata.cpp:66: error: stray ‘\342’ in program showdata.cpp:66: error: stray ‘\200’ in program showdata.cpp:66: error: stray ‘\235’ in program showdata.cpp:66: error: stray ‘\’ in program showdata.cpp:66: error: stray ‘\342’ in program showdata.cpp:66: error: stray ‘\200’ in program showdata.cpp:66: error: stray ‘\235’ in program showdata.cpp:67: error: stray ‘\342’ in program showdata.cpp:67: error: stray ‘\200’ in program showdata.cpp:67: error: stray ‘\235’ in program showdata.cpp:67: error: stray ‘\’ in program showdata.cpp:67: error: stray ‘\342’ in program showdata.cpp:67: error: stray ‘\200’ in program showdata.cpp:67: error: stray ‘\235’ in program Here are the two lines that are causing the errors. size_t startpos = str.find_first_not_of(” \t”); size_t endpos = str.find_last_not_of(” \t”); How can I fix this?
The symbol ” is not ". Those are called 'smart quotes' and are usually found in rich documents or blogs.
2,341,084
2,341,507
How to change an object's attribute in a value into a map
I have a map like this: map<prmNode,vector<prmEdge> > nodo2archi; In a certain situation, I have to change an object's attribute in a value into the vector of prmEdge. This is the code: prmNode par=freePathNode[z]; z++; prmNode arr=freePathNode[z]; map<prmNode,vector<prmEdge> >::iterator it; it=nodo2archi.find(par); app.clear(); vector<prmEdge> arc; arc=(*it).second; app=arc; vector<prmEdge>::iterator itarc; for (itarc=app.begin(); itarc!=app.end(); itarc++){ prmEdge arco=(*itarc); int a=arco.getFrom(); int b=arco.getTo(); int f=par.getIndex(); int t=arr.getIndex(); if ((a==f && b==t) || (b==f && a==t)){ if (arco.getState()==0){ if (!is_free_arco(par,arr)){ togli_arco_par(arco,arr); erased = true; return erased; } else{ //ERROR //it->second(it->second.begin()).setState(1); //(*it).second.begin().setState(1); } } } } I have to use the method setState to change an attribute into the map. The problem is that I don't have any method from map to make this operation, and in this way i have a compilation error. Could anybody give me an help to solve this?? Thank you very much!
it->second.begin()->setState(1) should do it. it->second.begin() is a vector iterator, so you need -> to access the vector element. If you need to access the other elements of the vector, you can of course use the vector's interface rather than iterators, e.g. it->second[2].setState(1).
2,341,113
2,341,160
How to shut off a certain process on windows?
I have some .exe name i want to terminate if its running, how? Edit: I modified mike's example to this, and its perfect: WinExec("taskkill /IM notepad.exe /F", SW_HIDE);
If you know the name of a process to kill, for example notepad.exe, use the following command from a command prompt to end it taskkill /IM notepad.exe This will cause the program to terminate gracefully, asking for confirmation if there are unsaved changes. To forcefully kill the same process, add the /F option to the command line. Be careful with the /F option as it will terminate all matching processes without confirmation.
2,341,177
2,341,202
c++ std::ofstream flush() but not close()
I'm on MacOSX. In the logger part of my application, I'm dumping data to a file. suppose I have a globally declared std::ofstream outFile("log"); and in my logging code I have: outFile << "......." ; outFile.flush(); Now, suppose my code crashes after the flush() happens; Is the stuff written to outFile before the flush() guaranteed to be written to disk (note that I don't call a close()). Thanks!
From the C++ runtime's point of view, it should have been written to disk. From an OS perspective it might still linger in a buffer, but that's only going to be an issue if your whole machine crashes.
2,341,354
2,348,295
Qt in visual studio: connecting slots and signals doesn't work
I have installed Qt and Qt for VS plugin. Everything works fine, UI applications compile and run that's ok, but connecting signals and slots doesn't. I have Q_OBJECT in my class and for connecting I am using this code in constructor: connect(ui.mainTableView, SIGNAL(activated(const QModelIndex &)), this, SLOT(showDetail(const QModelIndex &))); EDIT: showDetail method: void MyClass::showDetail(const QModelIndex &index) { this->setWindowTitle("it works"); } window title is not changed and breakpoint is not reached. moc files are generated in Generated Files directory, but moc file of that class is empty (others not), I think that it is because the class has no signal, but only one slot. even connections generated by Designer don't work and the call of connect method returns true.
RESULT: Oh no it turns out to be a silly question, thanks everybody, all answers pushed me towards the solution, but the last step was to find out that on my platform items are activated only by double-click, not single. Sorry
2,341,866
2,341,921
Why was Cassandra written in Java?
Question about Cassandra Why the hell on earth would anybody write a database ENGINE in Java ? I can understand why you would want to have a Java interface, but the engine... I was under the impression that there's nothing faster than C/C++, and that a database engine shouldn't be any slower than max speed, and certainly not use garbage collection... Can anybody explain me what possible sense that makes / why Cassandra can be faster than ordinary SQL that runs on C/C++ code ? Edit: Sorry for the "Why the hell on earth" part, but it really didn't make any sense to me. I neglected to consider that a database, unlike the average garden-varitety user programs, needs to be started only once and then runs for a very long time, and probably also as the only program on the server, which self-evidently makes for an important performance difference. I was more comparing/referencing to a 'disfunctional' (to put it mildly) Java tax program I was using at the time of writing (or rather would have liked to use). In fact, unlike using Java for tax programs, using Java for writing a dedicated server program makes perfect sense.
I can see a few reasons: Security: it's easier to write secure software in Java than in C++ (remember the buffer overflows?) Performance: it's not THAT worse. It's definitely worse at startup, but once the code is up and running, it's not a big thing. Actually, you have to remember an important point here: Java code is continually optimized by the VM, so in some circumstances, it gets faster than C++
2,341,987
2,362,757
Where is the call to std::map::operator[] in this code?
I have the following typedef's in my code: typedef unsigned long int ulint; typedef std::map<ulint, particle> mapType; typedef std::vector< std::vector<mapType> > mapGridType; particle is a custom class with no default constructor. VS2008 gives me an error in this code: std::set<ulint> gridOM::ids(int filter) { std::set<ulint> result; ulint curId; for ( int i = 0; i < _dimx; ++i ) { for ( int j = 0; j < _dimy; ++j ) { // next line is reported to be erroneous for ( mapType::iterator cur = objectMap[i][j].begin(); cur != objectMap[i][j].end(); ++cur ) { curId = (*cur).first; if ( (isStatic(curId) && filter != 2) || (!isStatic(curId) && filter != 1) ) { result.insert(curId); } } } } return result; } objectMap is an object of mapGridType. The error reads: error C2512: 'gridOM::particle::particle' : no appropriate default constructor available while compiling class template member function 'gridOM::particle &std::map<_Kty,_Ty>::operator [](const unsigned long &)' with [ _Kty=ulint, _Ty=gridOM::particle ] .\gridOM.cpp(114) : see reference to class template instantiation 'std::map<_Kty,_Ty>' being compiled with [ _Kty=ulint, _Ty=gridOM::particle ] Correct me if I'm wrong, but the above code should not be making calls to map::operator[] at all. The first operator[] call is made to vector< vector<mapType> > and returns a vector<mapType>, the second is made to vector<mapType> and returns a mapType aka a map<ulint, particle>, and I only call begin() and end on that map. So why do I get an error trying to compile the operator[] for map?
Case closed. It turns out that I did in fact make the coding mistake of writing a call to operator[], but it was hundreds of lines further down in the source file from where the error was reported. Apparently VS just pointed me to the first usage of a variable of mapType instead of the actual point where it tried to instantiate the method.
2,342,037
2,343,072
To which extent is "boost does it" equivalent to "very portable, use it"?
In this answer to a question asking "is doing Z this way portable" the idea is "boost does it this way, it means it is very portable". Can I just always consult boost sources to find the most portable way of doing something in C++? How can I judge for myself if boost is really such a collection of super-portable code?
There are some cases where Boost libraries exist precisely because they wrap very non-portable code. The most obvious examples are the file system and threading stuff. The telltale sign of this is a large use of Boost.Config macros. Boost code that doesn't depend on Boost.Config (or other non-standard #ifdefs) will be highly portable.
2,342,162
2,342,176
std::string formatting like sprintf
I have to format std::string with sprintf and send it into file stream. How can I do this?
You can't do it directly, because you don't have write access to the underlying buffer (until C++11; see Dietrich Epp's comment). You'll have to do it first in a c-string, then copy it into a std::string: char buff[100]; snprintf(buff, sizeof(buff), "%s", "Hello"); std::string buffAsStdStr = buff; But I'm not sure why you wouldn't just use a string stream? I'm assuming you have specific reasons to not just do this: std::ostringstream stringStream; stringStream << "Hello"; std::string copyOfStr = stringStream.str();
2,342,511
2,342,596
What if I don't call ReleaseBuffer after GetBuffer?
From CString to char*, ReleaseBuffer() must be used after GetBuffer(). But why? What will happen if I don't use ReleaseBuffer() after GetBuffer()? Can somebody show me an example? Thanks.
I'm not sure that this will cause a memory leak, but you must call ReleaseBuffer to ensure that the private members of CString are updated. For example, ReleaseBuffer will update the length field of the CString by looking for the terminating null character.
2,342,921
2,395,290
C or C++ HTTP daemon in a thread?
I'm starting up a new embedded system design using FreeRTOS. My last one used eCos, which has a built-in HTTP server that's really lightweight, especially since I didn't have a filesystem. The way it worked, in short, was that every page was a CGI-like C function that got called when needed by the HTTP daemon. Specifically, you would write a function of the form: int MyWebPage(FILE* resp, const char* page, const char* params, void* uData); where page was the page part of the url, params were any form parameters (only GET was supported, not POST, which prevented file uploads and thus made burning the flash a pain), uData is a token passed in that was set when you registered the function, so you could have the same function serve multiple URLs or ranges with different data, and resp is a file handle that you write the HTTP response (headers and all) out to. Then you registered the function with: CYG_HTTPD_TABLE_ENTRY(www_myPage, "/", MyWebPage, 0); where CYG_HTTPD_TABLE_ENTRY is a macro where the first parameter was a variable name, the second was a page URL (the * wildcard is allowed; hence page getting passed to MyWebPage()), third is the function pointer, and last is the uData value. So a simple example: int HelloWorldPage(FILE* resp, const char*, const char* params, void*) { fprintf("Content-Type: text/html;\n\n"); fprintf("<html><head><title>Hello World!</title></head>\n"); fprintf("<body>\n"); fprintf("<h1>Hello, World!</h1>\n"); fprintf("<p>You passed in: %s</p>\n", params); fprintf("</body></html>\n"); } CYG_HTTPD_TABLE_ENTRY(www_hello, "/", HelloWorldPage, 0); (Actually, params would be passed through a function to escape the HTML magic characters, and I'd use another couple functions to split the params and make a <ul> out of it, but I left that out for clarity.) The server itself just ran as a task (i.e. thread) and didn't get in the way as long as it had a lower priority than the critical tasks. Needless to say, having this proved invaluable for testing and debugging. (One problem with embedded work is that you generally can't toss up an XTerm to use as a log.) So when Supreme Programmer reflexively blamed me for something not working (path of least resistance, I guess), I could pull up the web page and show that he had sent me bad parameters. Saved a lot of debug time in integration. So anyway... I'm wondering, is there something like this available as an independent library? Something that I can link in, register my callbacks, spawn a thread, and let it do the magic? Or do I need to crank out my own? I'd prefer C++, but can probably use a C library as well. EDIT: Since I'm putting a bounty on it, I need to clarify that the library would need to be under an open-source license.
I suggest you have a look at libmicrohttpd, the embedded web server: http://www.gnu.org/software/libmicrohttpd/ It is small and fast, has a simple C API, supports multithreading, is suitable for embedded systems, supports POST, optionally supports SSL/TLS, and is available under either the LGPL or eCos license (depending). I believe this fulfils all your requirements. It would be trivial to wrapper in C++ if you preferred.
2,343,191
2,343,223
failed constructor and failed destructor in C++
I have one question about failed constructor and failed destructor in C++. I noticed that when the constructor failed, an exception will be thrown. But there is no exception thrown in destructor. My question is 1) If constructor failed, what exception will be thrown? bad_alloc? or anything else related? Under what situation, a constructor would fail? What about the successfully constructed part? 2) Under what situation, a destructor would fail? If no exception is thrown, what would happen to the destructor? How does the compiler deal with it? What's the return value to the function it is called? Thanks! Any comments are strongly appreciated!
If a constructor fails, an exception is thrown only if the constructor is implemented so that it throws an exception. (You might need to differentiate between memory allocation and construction. Allocating memory using new might fail throwing a std::bad_alloc exception.) There is no case where a constructor, in general, fails. It fails only if it is written so that it might fail. If so, how it fails depends on how it is written. In general, destructors should be written so they don't fail, as it is not safe to throw exceptions from destructors. (That's because they might be called during stack unwinding.) Note that "failing" as used in your question generally refers to runtime failures. So the compiler has nothing to do with it. Also, neither constructors nor destructors return anything.
2,343,208
2,343,294
Can you catch an exception by the type of a conversion operator?
I don't know how to phrase the question very well in a short subject line, so let me try a longer explanation. Suppose I have these exception classes: class ExceptionTypeA : public std::runtime_error { // stuff }; class ExceptionTypeB : public std::runtime_error { // stuff operator ExceptionTypeA() const; // conversion operator to ExceptionTypeA }; Can I then do this, and have it trigger the catch block? try { throw ExceptionTypeB(); } catch (ExceptionTypeA& a) { // will this be triggered? } I'm going to guess that it will not, which is unfortunate, but I thought I'd ask, since I couldn't find any info on it on the net or on SO. And yes, I realize I could just run the program in my compiler and see what happens, but that wouldn't tell me what the standard says about this behavior, just what my compiler implements (and I don't trust it).
You cannot. Standardese at 15.3/3: A handler is a match for an exception object of type E if The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv- qualifiers), or the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or the handler is of type cv1 T* cv2 and E is a pointer type that can be converted to the type of the handler by either or both of a standard pointer conversion (4.10) not involving conversions to pointers to private or protected or ambiguous classes a qualification conversion Your desired scenario matches none of these. cv means "const and/or volatile combination"
2,343,245
2,343,337
Can you please explain this C++ delete problem?
I have the following code: std::string F() { WideString ws = GetMyWideString(); std::string ret; StringUtils::ConvertWideStringToUTF8(ws, ret); return ret; } WideString is a third-party class, so are StringUtils. They are a blackbox to me. Second parameter is passed by reference. When I step through the debugger the line return ret throws a nasty popup (Visual C++) saying that heap may be corrupted. Upon closer examination copy of the string that gets returned is OK, but the deletion of ret fails. ret contains correct value before return. What could the converting function possibly do to cause this? Any ideas to fix? Update: Project itself is a dll StringUtils is a lib Project is compiled against Multithreaded CRT (not debug, not dll) Program seems to run fine when run outside of Visual Studio
If StringUtils was compiled separately (e.g., with a different compiler version), you may have a conflict in the object layout. If StringUtils is in a DLL, you have to ensure that both it and the main program are compiled to use the standard library in a DLL. Otherwise, each module (executable and DLL) will have its own heap. When StringUtils tries to play with data in the string that was allocated from a different heap, bad things happen.
2,343,558
2,343,630
How do I declare an array of objects whose class has no default constructor?
If a class has only one constructor with one parameter, how to declare an array? I know that vector is recommended in this case. For example, if I have a class class Foo{ public: Foo(int i) {} } How to declare an array or a vector which contains 10000 Foo objects?
For an array you would have to provide an initializer for each element of the array at the point where you define the array. For a vector you can provide an instance to copy for each member of the vector. e.g. std::vector<Foo> thousand_foos(1000, Foo(42));
2,343,719
2,344,146
C++ templated functor in lambda expression
This first piece has been solved by Eric's comments below but has led onto a secondary issue that I describe after the horizontal rule. Thanks Eric! I'm trying to pass a functor that is a templated class to the create_thread method of boost thread_group class along with two parameters to the functor. However I can't seem to get beyond my current compile error. With the below code: #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <boost/thread.hpp> #include <vector> using namespace boost::lambda; using namespace std; namespace bl = boost::lambda; template<typename ftor, typename data> class Foo { public: explicit Foo() { } void doFtor () { _threads.create_thread(bind(&Foo<ftor, data>::_ftor, _list.begin(), _list.end())); //_threads.create_thread(bind(_ftor, _list.begin(), _list.end())); _threads.join_all(); } private: boost::thread_group _threads; ftor _ftor; vector<data> _list; }; template<typename data> class Ftor { public: //template <class Args> struct sig { typedef void type; } explicit Ftor () {} void operator() (typename vector<data>::iterator &startItr, typename vector<data>::iterator &endItr) { for_each(startItr, endItr, cout << bl::_1 << constant(".")); } } I also tried typedef-ing 'type' as I thought my problem might have something to do with the Sig Template as the functor itself is templated. The error I am getting is: error: no matching function for call to ‘boost::lambda::function_adaptor<Ftor<int> Foo<Ftor<int>, int>::*>::apply(Ftor<int> Foo<Ftor<int>, int>::* const&, const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int>> >&, const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&)’ with a bunch of preamble beforehand. Thanks in advance for any help! Okay I've modified the code taking in Eric's suggestions below resulting in the following code: #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <boost/thread.hpp> #include <vector> using namespace boost::lambda; using namespace std; namespace bl = boost::lambda; template<typename ftor, typename data> class Foo { public: explicit Foo() { } void doFtor () { _threads.create_thread(bl::bind(boost::ref(_ftor), _list.begin(), _list.end())); _threads.join_all(); } private: boost::thread_group _threads; ftor _ftor; vector<data> _list; }; template<typename data> class Ftor { public: typedef void result_type; explicit Ftor () {} result_type operator() (typename vector<data>::iterator &startItr, typename vector<data>::iterator &endItr) { for_each(startItr, endItr, cout << bl::_1 << constant(".")); return ; } }; However this results in another compile error: /usr/local/include/boost/lambda/detail/function_adaptors.hpp:45: error: no match for call to ‘(Ftor<int>) (const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&, const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&)’ ftor.h:41: note: candidates are: void Ftor<data>::operator()(typename std::vector<data, std::allocator<_CharT> >::iterator&, typename std::vector<data, std::allocator<_CharT> >::iterator&) [with data = int] /usr/local/include/boost/lambda/detail/function_adaptors.hpp:45: error: return-statement with a value, in function returning 'void' It seems having defined void as a result_type it is now expecting the operator() to return something. I tried returning result_type from within the function but this also generated errors. Any ideas?
Sig (or in your case, simply typedef void result_type; is necessary. IIRC, lambda::bind makes const copies of its arguments. There is thus a problem with functors with non-const operator(). This is solved by making Ftor::operator()const or by wrapping (in doFtor()), _ftor with boost::ref There is a similar problem with the iterators. Wrapping in boost::ref here won't work directly because it would end up using a reference to a temporary. The simpler solution is to modify Ftor::operator() to take its arguments by copy. The simplest is thus to modify Ftor so that its operator() is const and it takes its arguments by copy: void operator() (typename vector<data>::iterator startItr, typename vector<data>::iterator endItr)const If you really can't make Ftor::operator() const, you could modify doFtor() as follows (but it is still necessary to make Ftor::operator() take its arguments by copy): _threads.create_thread(bind(boost::ref(_ftor), _list.begin(), _list.end()));
2,343,821
2,350,352
How to include the calling class and line number in the log using Pantheios?
I just started using Pantheios and it feels really like a great library for logging! Maybe even the greatest one for C++! Congratulations to the author! However, I could not find neither in the documentation nor in all the forum posts anything about how to include the calling class and the line number in the log. I'm using be.file as back end and I defined custom front end, looking at the example of fe.simple. Is this something to do with the PANTHEIOS_EXTERN_C const char PANTHEIOS_FE_PROCESS_IDENTITY[] or I'm on a completely wrong way?
The answer for this actually is in the FAQ file included in the library download. I have a fixed-back-end DLL that has the following header in it and I am able to include the class, function and line number in the log file. #include <pantheios/pantheios.hpp> #include <pantheios/frontends/fe.N.h> //#include <pantheios/frontends/fe.simple.h> #ifndef PANTHEIOS_INCL_PANTHEIOS_H_TRACE #define PANTHEIOS_TRACE_PREFIX __FILE__ "(" PANTHEIOS_STRINGIZE(__LINE__) "): " __FUNCTION__ ": " #endif /* PANTHEIOS_INCL_PANTHEIOS_H_TRACE */ #include <pantheios/trace.h> #include <pantheios/inserters.hpp> #include <pantheios/backends/bec.file.h> // be.file header What is happening here is that you have to redefine PANTHEIOS_TRACE_PREFIX before including trace.h, which is what I have shown above. The other lines of code are included simply to show you where the #define goes. And sorry for the delayed response. If you wish I could post a download on my blog with a fixed-back-end DLL project that anyone could use in their solution for simple file-based logging. Leave a comment if you have any interest in that project Update 2/28/2010 12:53 AM CST: For your reference here is the question from the FAQ: Q9: "Does Pantheios provide a configuration that yields a logged message containing the containing function, equivalent to: log(informational, __FUNCTION__, ": my message"); without having to write that (or some wrapper that checks for compiler support)." [15th March 2008] A9: You need to #define PANTHEIOS_TRACE_PREFIX to what you want. By default it is __FILE__ "(" PANTHEIOS_STRINGIZE(__LINE__) "): ", which gives the format <file>(<line>): To include the function, lets says you want it to have the format <file>(<line>): <func>:. To achieve this you'd define it as follows: #include <pantheios/pantheios.h> #define PANTHEIOS_TRACE_PREFIX __FILE__ " " PANTHEIOS_STRINGIZE(__LINE__) ": " __FUNCTION__ ": " #include <pantheios/trace.h> Note that the definition must come before the inclusion of pantheios/trace.h. Therefore, a safer way of doing this is as follows: /* File: myPantheiosRootHeader.h */ #include <pantheios/pantheios.h> #ifdef PANTHEIOS_INCL_PANTHEIOS_H_TRACE # error pantheios/trace.h must not be included before myPantheiosRootHeader.h #endif /* PANTHEIOS_INCL_PANTHEIOS_H_TRACE */ #define PANTHEIOS_TRACE_PREFIX __FILE__ " " PANTHEIOS_STRINGIZE(__LINE__) ": " __FUNCTION__ ": " #include <pantheios/trace.h>
2,343,979
2,343,998
I'm getting error C2664 on some I/O code
void BinaryTree::InitializeFromFile(string Filename){ ifstream inFile; inFile.open(Filename, fstream::binary); if(inFile.fail()){ cout<<"Error in opening file "<<Filename; return; } for(int i=0;i<=255;i++) Freq[i]=0; char c; inFile.get(c); while(!inFile.eof()){ Freq[c] ++; inFile.get(c); } } HuffmanTree.cpp(293) : error C2664: 'void std::basic_ifstream<_Elem,_Traits>:: open(const wchar_t *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'std::string' to 'const wchar_t *' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called Line 293 is inFile.open(Filename, fstream::binary);
Use Filename.c_str() instead - open() doesn't take a std::string as a parameter for the filename.
2,344,081
2,344,106
NLP project, python or C++
We are working on Arabic Natural Language Processing project, we have limited our choices to either write the code in Python or C++ (and Boost library). We are thinking of these points: Python Slower than C++ (There is ongoing work to make Python faster) Better UTF8 support Faster in writing tests and trying different algorithms C++ Faster than Python Familiar code, every programmer knows C or C-like code After the project is done, it should be not very hard to port the project to another programming languages. What do you think is better and suitable for the project?
Write it in Python, profile it, and if you need to speed parts of it up, write them in C++. Python and C++ are similar enough that the "familiar" advantage with C++ will be irrelevant pretty quick. I say this as someone who has developed primarily in C++ and has recently gotten serious with Python. I like them both, but I can get Python code working a lot faster than C++. Seriously, dict beats std::map in usability. P.S. Here's some information on how to call C code from Python.
2,344,087
2,344,108
Try does not catch exception in DllImport function
I call C++ function from C# project: [System.Runtime.InteropServices.DllImport("C.dll")] public static extern int FillSlist(out string slist); and then try { FillSlist(out slist); } catch { } C++ dll is protected by third-party tool, so some code is being performed before FillSlist is really executed. Something really bad happens while this third-party code is executed and the program stops working at all. Neither "try" isolates the problem nor "AppDomain.CurrentDomain.UnhandledException" is executed. Is there anything that can help to isolate crash of C++ function from C# calling code?
Is this running on CLR 4.0? If so ... If an exception does not get caught in an open catch block as demonstrated in your code it's because the CLR considers it a corrupted state exception and is by default not handled by user code. Instead it propagates up and causes the process to terminate. It does this for a reason for these types of exceptions there is no action managed code can take to correct the problem. The only possible solution is to terminate the process. You can override this behavior by adding an HandledCorruptedStateException attribute to the method. But generally speaking this is a bad idea. More details http://msdn.microsoft.com/en-us/magazine/dd419661.aspx If not then it's possible the program is simply crashing out in native code and execution never properly returns to managed code.
2,344,233
2,344,248
Validate HWND using Win32 API
From the native Win32 API using C++ is there a way to determine whether the window associated with an HWND is still valid?
You could use the Win32 API IsWindow. It is not recommended to use it though for 2 reasons: Windows handles can be re-used once the window is destroyed, so you don't know if you have a handle to an entirely different window or not. The state could change directly after this call and you will think it is valid, but it may really not be valid. From MSDN (same link as above): A thread should not use IsWindow for a window that it did not create because the window could be destroyed after this function was called. Further, because window handles are recycled the handle could even point to a different window. What can be done? Perhaps your problem can be re-architected so that you do not have the need to check for a valid handle. Maybe for example you can establish a pipe from the client to the server. You could also create a windows hook to detect when certain messages occur, but this is probably overkill for most needs.
2,344,288
2,344,962
Qt Asynchronous Action During aboutToQuit
I've got some Asynchronous cleanup activity I need to do as my Qt application is shutting down. My current approach is to trap the aboutToQuit signal. I launch my Asynchronous behavior, and then the application shuts down. Is there any way to block Qt from shutting down until my asynchronous behavior is complete? This works on windows by trapping the main window's closeEvent and calling ignore() on the event. But on Mac, when a user quits, my ignore() isn't honored, and the Application shuts down before my asynchronous activity is complete. Thanks.
Why do you launch your cleanup code asynchronously if you have to wait anyway until your code is done? If you don't connect your slot as QueuedConnection to aboutToQuit it should block until your cleanup code is done. But if you really want launch it asynchronously you have to synchronize it by hand: QSemaphore wait4CleanupDone; class MyQuitHandler { ... public slots: void handleQuit(); ... } myQuitHandler; void MyQuitHandler::handleQuit() { ... ; wait4CleanupDone.release(); } int main(int argc, char** argv) { QApplication app(argc, argv); QObject::connect(&app, SIGNAL(aboutToQuit()), &myQuitHandler, SLOT(handleQuit())); ... int result = app.exec(); wait4CleanupDone.acquire(); return result; } But note, that your asynchronous code might be ignored in some cases anyway: "We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application's main() function. This is because, on some platforms the QApplication::exec() call may not return. For example, on the Windows platform, when the user logs off, the system terminates the process after Qt closes all top-level windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the main() function, after the QApplication::exec() call." From: http://doc.trolltech.com/4.6/qapplication.html#exec
2,344,294
2,344,380
Command arguments in compiler configurations
[edit] I meant to say "command arguments in compiler configs" . for the title. I am trying to get into game mods. And I am trying to implement the source sdk. one of the steps is to go into debugging in my compiler configurations and add some data to the command arguments -dev -sw -game "C:\Program Files (x86)\Steam\steamapps\SourceMods\firstmod" Now I know what command arguments are. They are passed through the parameters of WinMain and judging by the name in the compiler configurations. I assume that has something to do with it. or maybe not. I am just not sure if the above would be considered 1 argument or multiple arguments. and what is it trying to achieve by passing a directory through. They weren't too detailed with the information.
In a normal (read console) C/C++ application you would have program entry point with the following declaration: int main( int argc, char* argv[] ); Here argc is the number of command line "strings", including the command itself, while argv is the array of these strings. So in your example it'd be argc of 5 (adding the program name), and argv[0] is the name of the program, argv[1] is "-dev", etc. Now under Windows a GUI application is different - the entry point is declared as: int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ); So the whole command line (this time excluding the app name) is pointed to by lpCmdLine, so it'd be one string as you put it above. There are helper functions to split that string though. Take a look at these two entries on MSDN: What's is WinMain How to get normal argv-style command line parameters
2,344,330
2,344,365
Algorithm to add or subtract days from a date?
I'm trying to write a Date class in an attempt to learn C++. I'm trying to find an algorithm to add or subtract days to a date, where Day starts from 1 and Month starts from 1. It's proving to be very complex, and google doesn't turn up much, Does anyone know of an algorithm which does this?
The easiest way is to actually write two functions, one which converts the day to a number of days from a given start date, then another which converts back to a date. Once the date is expressed as a number of days, it's trivial to add or subtract to it. You can find the algorithms here: http://alcor.concordia.ca/~gpkatch/gdate-algorithm.html
2,344,465
2,344,578
How to create interface for C++ application with XAML?
How to create interface for C++ application with XAML? (I SEARCH FOR SOME APP LIKE EXPRESSION BLEND (OR even beter a plug in for it))
Visual Studio Pro 2008 does support C++ .Net and XAML interface designer so it should do what you are looking for. PS : Visual Studio 2010 is going to be released soon. I never tried XAML with this one but it should have a better support.
2,344,670
2,344,689
Tired of building web applications? Trying maybe C++?
I'm getting a little tired of building web applications. Feels like same thing over and over again. Are there any other cool things you can do. I'm maybe getting to start coding in C++. Any suggestions for tips in that area? Should I delve into Qt or MFC? Any suggestions?
If you're just starting out in C++, I recommend starting with some simple console-based applications first. Get used to the syntax and some fundamentals like strong typing, pointers, and understanding the difference between pointers and references. (Depending on your experience as a developer, you may already know all or most of the theory behind these concepts.) If you're comfortable with these things, building GUI applications is easier (although still far from trivial.) I'd recommend going with a toolkit like Qt rather than MFC, which is largely deprecated in favor of dot NET, if I'm not mistaken. Edit: also, consider trying out a language like C# instead. C# is newer, a little more cohesive, and lets you use dot NET for building Windows GUI applications.
2,344,673
2,344,709
Alternative version of find_if which finds all, not just the first?
Is there an alternative version of std::find_if that returns an iterator over all found elements, instead of just the first one? Example: bool IsOdd (int i) { return ((i % 2) == 1); } std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); std::vector<int>::iterator it = find_if(v.begin(), v.end(), IsOdd); for(; it != v.end(); ++it) { std::cout << "odd: " << *it << std::endl; }
You can just use a for loop: for (std::vector<int>:iterator it = std::find_if(v.begin(), v.end(), IsOdd); it != v.end(); it = std::find_if(++it, v.end(), IsOdd)) { // ... } Alternatively, you can put your condition and action into a functor (performing the action only if the condition is true) and just use std::foreach.
2,344,691
2,344,714
How can I convert the following java function into C++?
If I have the following Java code: int[][] readAPuzzle() { Scanner input = new Scanner(System.in); int[][] grid = new int[9][9]; for (int i=0; i<9; i++) for (int j=0; j<9; j++) grid[i][j] = input.nextInt(); return grid; } public static void main(String[] args) { // Read a Sudoku puzzle int[][] grid = readAPuzzle(); } How can I convert this to C++? I get hung up on passing the array. Here is my attempt: #include <iostream> using namespace std; const int puzzle_width = 9; const int puzzle_height = 9; void readAPuzzle(int (&grid)[puzzle_height][puzzle_width]) { for(int i = 0; i < 9; i++) for(int j = 0; j < 9; j++) grid[i][j] = cin >> grid[i][j]; return; } int main() { int[9][9] grid; readAPuzzle(grid); } What am I doing wrong in general?
You need to read in the input text into your array grid and pass it on. grid[i][j] = cin >> grid[i][j]; Doesn't do what you think it does, it tries to assign an object of type istream to grid[ i ][ j ] cin >> grid[i][j]; however suffices. Also, note in C++ the dimensions follow the identifier as in: int grid[9][9];
2,344,788
2,344,827
iostream, some questions
I've seen people do things like.... istringstream ibuf; if (ibuf >> zork >> iA >> Comma >> iB) now I guess the value depends on what >>iB exposes but exactly what is that and what does it mean? Does true mean all the ietms were extracted? Also, after an expression like ibuf >> zork >> iA >> Comma >> iB; is there any way to find out how many characters and items where extracted?
This works because of two properties of istream objects: istreams return themselves after each extraction (the >> operator) to allow chaining multiple extractions (a >> b >> c) istreams return their status (as though .good() were called) when they're cast/converted to bool, via overloading bool operator !() Basically the code you wrote is a short-hand version of: if ( ((((ibuf >> zork) >> ia) >> Comma) >> ib).good() ) { } Once all the extractions have occured, you're left with if (ibuf) which is implicitly like writing if ((bool)ibuf), which checks ibuf.good(). There is no way to get the number of characters extracted over a series of chained extractions, but you can find the number of characters extracted during the last operation with the function gcount. However, it only works for certain format-ignoring functions like get and getline, and not the extraction operator.
2,344,887
2,345,126
Select which handles are inherited by child process
When creating a child process in C++ using Windows API, one can allow inheritance of handles from parent to child. In a Microsoft example "Creating a Child Process with Redirected Input and Output", redirecting a child process' std in/out to pipes created by the parent, it is necessary to allow inheritance for the redirection pipes to be usable. I'm working on a small demo class that launches an external executable, reads the output, and then spits it back to the caller (who records the returned output to a file). I'm trying to build in a time-out feature, where it will only block for a certain amount of time before calling TerminateProcess() on the child and continuing on with life. However, I've found that by allowing handle inheritance, the child process also has a handle (visible with Process Explorer) to the output file. I do not want the child process to obtain this handle, but the parent in this case (this demo class) is not aware of the handle either, so I cannot currently use SetHandleInformation() to unflag the output file specifically to exclude it from inheritance. I am certain there must be a better way to inherit ONLY the specific handles that I want, without allowing "blanket" inheritance which passes unintended and undesired handles. Unfortunately I have been unable to find a solution, having browsed as many related MSDN articles as I can find, and having Googled myself into a state of discouragement. At the very least, I need to do something to remove the handles from the child, without necessarily having those handles within the demo class (they're used by the calling class, and this demo class has no explicit knowledge of their existence). Any solutions for more selective inheritance? I'm especially interested in the solution that allows me to specifically declare what handles to inherit, and all un-specified handles will not be inherited, if such a solution exists. Thank you kindly.
If the output file handle is inherited by the child process, then that is because the code in the parent process that opened the file explicitly stated that the file handle should be inheritable. It passed a value for the lpSecurityAttributes parameter of CreateFile. The default state is for the handle to not be inheritable. It seems to me that your process-creating class shouldn't try to second-guess its caller, who has already opened the file. However, if you have special knowledge of exactly which handles the new process needs, then as of Windows Vista, there is a mechanism for specifying which handles should be inherited. When you prepare to call CreateProcess, use a STARTUPINFOEX structure instead of the usual STARTUPINFO. It has an lpAttributeList member. Allocate and initialize it, and then use UpdateProcThreadAttribute with PROC_THREAD_ATTRIBUTE_HANDLE_LIST to set the list of handles to be inherited. All the handles need to be inheritable, and you still need to specify bInheritHandles = TRUE when you call CreateProcess. You also need to include EXTENDED_STARTUPINFO_PRESENT in the dwCreationFlags parameter. Raymond Chen demonstrated the technique in an article in 2011. If that added functionality isn't available to you, then you could certainly try to enumerate all your program's open handles and set all their inheritance properties with SetHandleInformation, but that seems to be beyond the scope of a function whose job is to create child processes. Let the code that creates the handles worry about whether they should be inheritable.
2,344,910
2,345,028
Create derived class instance from a base class instance without knowing the class members
Is this scenario even possible? class Base { int someBaseMemer; }; template<class T> class Derived : public T { int someNonBaseMemer; Derived(T* baseInstance); }; Goal: Base* pBase = new Base(); pBase->someBaseMemer = 123; // Some value set Derived<Base>* pDerived = new Derived<Base>(pBase); The value of pDerived->someBaseMemer should be equeal to pBase->someBaseMember and similar with other base members.
Why wouldn't you actually finish writing and compiling the code? class Base { public: // add this int someBaseMemer; }; template<class T> class Derived : public T { public: // add this int someNonBaseMemer; Derived(T* baseInstance) : T(*baseInstance) // add this { return; } // add this }; This compiles and runs as you specified. EDIT: Or do you mean that someNonBaseMemer should equal someBaseMemer?
2,344,929
2,345,017
Pointers in C# to Retrieve Reference From DllImport Function
I am referencing a DLL in my C# project as follows: [DllImport("FeeCalculation.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] public static extern void FeeCalculation(string cin, string cout, string flimit, string frate, string fwindow, string fincrement, string fbird, string fparameter, string fvalidation, string fcoupon); The FeeCalculation function is exported as follows in the DLL: extern "C" __declspec(dllexport) void __stdcall FeeCalculation(char *cin, char *cout, char *flimit, char *frate, char *fwindow, char *fincrement, char *fbird, char *fparameter, char *fvalidation, char *fcoupon); The DLL function returns a reference to it's internal structures in the form of char * so if you were to reference this DLL in C++, you would do the following to do the calculation and get the returned structures: FeeCalculation(buff, (char *)&fans, (char *)fl, (char *)ft, (char *)fw, (char *)fi, (char *)fe, (char *)&fm, (char *)val, (char *)cpn); Now, how do I retrieve those values that are returned by reference using C#? Meaning, how do I do the same thing in C# to get the returned structures to get my returned calculation? I know I need to create an unsafe method, but I am unclear on how to deal with the memory addresses in C# like you would in C++. Edit: Below states to use IntPtr but how do you place into identical structure so the fields of the structure can be referenced? Edit: Here is the returned structure that I am interested in (cout): struct feeAnswer { unsigned int fee; unsigned int tax1; unsigned int tax2; unsigned int tax3; unsigned int tax4; unsigned int surcharge1; unsigned int surcharge2; unsigned int validationFee; unsigned int couponFee1; unsigned int couponFee2; unsigned int couponFee3; unsigned int couponFee4; unsigned short int dstay; //Day Stay unsigned short int mstay; //Minute Stay }; Here is the (cin) that I would pass along with other structures (they are zero byte at the moment, I want to get this to work first then I will implement the rest): struct feeRequest { unsigned char day; unsigned char month; unsigned int year; //2000 ~ 2099 unsigned char hour; unsigned char minute; unsigned char rate; unsigned char validation; unsigned char coupon1; unsigned char coupon2; unsigned char coupon3; unsigned char coupon4; };
Edit: now that we have structures to work with, a better solution is possible. Just declare structs in C# that match your C++ structs, and use them in the extern declaration [StructLayout(LayoutKind.Sequential)] public struct feeAnswer { public uint fee; public uint tax1; public uint tax2; public uint tax3; public uint tax4; public uint surcharge1; public uint surcharge2; public uint validationFee; public uint couponFee1; public uint couponFee2; public uint couponFee3; public uint couponFee4; public ushort dstay; //Day Stay public ushort mstay; //Minute Stay }; [StructLayout(LayoutKind.Sequential, Pack=1)] public struct feeRequest { public byte day; public byte month; public uint year; //2000 ~ 2099 public byte hour; public byte minute; public byte rate; public byte validation; public byte coupon1; public byte coupon2; public byte coupon3; public byte coupon4; }; [DllImport ("FeeCalculation.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] public static extern void FeeCalculation ( feeRequest cin, out feeAnswer cout, ... .... original answer (before we had structs) below It appears to me that these are not references to internal strings, but rather pointers to string buffers that will be filled in by the call. If you were returning string pointers, then these would be declared char** rather than char*. So I think these are just standard out parameters. There's just a lot of them. So your C# interop would look like this [DllImport("FeeCalculation.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] public static extern void FeeCalculation(string cin, [MarshalAs(UnmanagedType.LPStr, SizeConst=100)] out string cout, [MarshalAs(UnmanagedType.LPStr, SizeConst=100)] out string flimit, or this if your "strings" aren't really strings [DllImport("FeeCalculation.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] public static extern void FeeCalculation(string cin, [MarshalAs(UnmanagedType.LPArray, SizeConst=100)] out byte[] cout, [MarshalAs(UnmanagedType.LPArray, SizeConst=100)] out byte[] flimit, ....
2,345,034
2,345,077
Terminate all (grand)children when terminating a child process
I will jump right in, to be brief and descriptive: C++, Windows API I am creating child processes using CreateProcess to run external (command-line) applications. I have built in a time-out, and if the child process has not returned normal execution by that time, I wish to force termination on that child process. Ideally, I would like for that child process to act the same as if it had called ExitProcess, or as if a Ctrl+C was sent to its console (which calls ExitProcess from the default console control handler). My solution so far has been the use of TerminateProcess to kill the child forcefully. This does force the child to terminate immediately, but unfortunately if that child spawned any children of its own they are left to run until their "natural" completion. Is there a way to tell the child process to call ExitProcess, or to force all of the child's children to also terminate when TerminateProcess is called? These external applications are beyond my control, and as such I can not modify them to provide a custom work-around. Assume no knowledge of grand-child processes (names/pids/etc) that would allow me to manually call TerminateProcess on grand-child processes individually. Although this could be done by manually enumerating all processes, mapping process relationships, and tracking all processes, I do not consider this a valid solution except as the absolute last resort. Thank you for your time.
You can use Job objects to kill all the processes as a unit. You create a job object via the CreateJobObject API, and assign a process to it with AssignProcessToJobObject. New processes created by a process in a job object belong to the same job object by default. Calling TerminateJobObject will terminate all associated processes in the job object.
2,345,079
2,345,106
static array allocation issue!
I want to statically allocate the array. Look at the following code, this code is not correct but it will give you an idea what I want to do class array { const int arraysize; int array[arraysize];//i want to statically allocate the array as we can do it by non type parameters of templates public: array(); }; array::array():arraysize(10) { for(int i=0;i<10;i++) array[i]=i; } main() { array object; }
If your array size is always the same, make it a static member. Static members that are integral types can be initialized directly in the class definition, like so: class array { static const int arraysize = 10; int array[arraysize]; public: array(); }; This should work the way you want. If arraysize is not always the same for every object of type array, then you cannot do this, and you will need to use template parameters, dynamically allocate the array, or use an STL container class (e.g. std::vector) instead.
2,345,177
2,345,223
Basic C++ Idioms / Techniques
Note: marked as community wiki. In recent days, I've realized how little I know about C++. Besides: using the STL implementing RAII implementing ref-counted smart pointers writing my own policy-based template classes overloading operators << for fun What other techniques are must-know for a good C++ programmer? Thanks!
I think this should cover it: More C++ Idioms - Wikibooks
2,345,191
2,345,210
Windows game: UTF-8, UTF-16, DirectX and Lua
I'm developing a game for windows for learning purposes (I'm learning DirectX). I would like it to have UTF support. Reading this question I learned that windows uses wchar_t, which is UTF-16. I want my game to have Lua scripting support, and Lua doesn't really like Unicode much.. It simply treats strings as a "stream of bytes"; this works well enough for UTF-8, but UTF-16 would be virtually impossible to use. Long story short: windows wants UTF-16, lua wants UTF-8. So I thought, let's just use UTF-8 with normal char* and string! .length() will be messed up but who cares? However it doesn't work: const char test_utf8[] = { 111, 108, 0xc3, 0xa9, 0 }; // UTF-8 for olè mFont->DrawTextA(0, test_utf8, -1, &R, DT_NOCLIP, BLACK); /* DrawText is a Direct3d function to, well, draw text. * It's like MessageBox: it is a define to either DrawTextA * or DrawTextW, depending if unicode is defined or not. Here * we will use DrawTextA, since we are passing a normal char*. */ This prints olé. In other words it doesn't appear to use UTF-8 but rather ISO-8859-1. So, what can I do? I can think of the following: Abandon the idea of UTF; use ISO-8859-1 and be happy (this is what World of Warcraft does, at least for the enUS version) Convert every single string at every single frame from UTF-8 to UTF-16 (I'm worried about performance issues, though, considering it will do this 60+ times a second for each string and it's O(N) I'm pretty sure it will be fairly slow) For each lua string keep an UTF-16 copy; huge waste of memory, very difficult to implement (keeping the UTF-16 strings up to date when they change in Lua, etc)
It doesn't use 8859-1 either, it uses your system's local code page. You can convert to UTF16 and use DrawText() by converting the string yourself. If your class library doesn't have any support then you can use MultiByteToWideChar().
2,345,284
2,345,366
Can C++ policy classes be used to specify existence / non-existence of constructors?
Suppose I have: struct Magic { Magic(Foo* foo); Magic(Bar* bar); }; Is there a way to make Magic a template, and define template classes s.t. typedef Magic<FooPolicy, ...> MagicFoo; typedef Magic<BarPolicy, ...> MagicBar; typedef Magic<..., ...> MagicNone; typedef Magic<FooPolicy, BarPolicy> MagicAll; s.t. MagicFoo & MagicAll have the Foo* constructor; MagicBar & MagicAll has the Bar* constructor; and MagicNone nas neither the Foo* nor the Bar* constructor? Basically I want constructors to exist or not exist based on policy classes.
You can write a constructor accepting anything, and then delegate to whatever the policies provide: // "Tag" and "No" are used to make the class/function unique // (makes the using declarations work with GCC). template<int Tag> struct No { void init(No); }; template<typename P1 = No<0>, typename P2 = No<1>, typename P3 = No<2> > struct Magic : P1, P2, P3 { template<typename T> Magic(T t) { init(t); } private: using P1::init; using P2::init; using P3::init; }; Now, once you forward the argument, the compiler will figure out the best match among the policies: struct IntPolicy { void init(int) { std::cout << "called int!"; } }; struct FloatPolicy { void init(float) { std::cout << "called float!"; } }; Magic<IntPolicy, FloatPolicy> m(0), n(0.0f);
2,345,347
2,345,440
Finding the "Nth node from the end" of a linked list
This seems to be returning the correct answer, but I'm not sure if this is really the best way to go about things. It seems like I'm visiting the first n nodes too many times. Any suggestions? Note that I have to do this with a singly linked list. Node *findNodeFromLast( Node *head, int n ) { Node *currentNode; Node *behindCurrent; currentNode = head; for( int i = 0; i < n; i++ ) { if( currentNode->next ) { currentNode = currentNode->next; } else { return NULL; } } behindCurrent = head; while( currentNode->next ) { currentNode = currentNode->next; behindCurrent = behindCurrent->next; } return behindCurrent; }
Another way to do it without visiting nodes twice is as follows: Create an empty array of size n, a pointer into this array starting at index 0, and start iterating from the beginning of the linked list. Every time you visit a node store it in the current index of the array and advance the array pointer. When you fill the array, wrap around and overwrite the elements you stored before. When you reach the end of the list, the pointer will be pointing at the element n from the end of the list. But this also is just an O(n) algorithm. What you are currently doing is fine. I see no compelling reason to change it.
2,345,390
2,345,421
How to find the time taken to send data across UDP
I have a simple UDP client server written in C++ on Ubuntu 9.10 where the client sends a set to the server. How can I check how much time s it taking to sent it. I need to find the time from start of transfer to end. Supposing my server and client are on the same machine then can I somehow save the system time and find the difference or something ?
If you are asking how long it takes for the packet to arrive at the server, there is no built in way to get that information. If the server sends a reply, you can time how long it takes between sending the request and getting the reply and divide by 2 (not accurate, but a decent estimate).
2,345,551
2,345,560
What does this dynamic allocation do?
Today, I found out that you can write such code in C++ and compile it: int* ptr = new int(5, 6); What is the purpose of this? I know of course the dynamic new int(5) thing, but here i'm lost. Any clues?
You are using the comma operator, it evaluates to only one value (the rightmost). The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered. Source The memory address that the pointer is pointing to is initialized with a value of 6 above.
2,345,744
2,345,769
reference counting with cycles in C++ smart pointer
In shared_ptr smart pointer, reference counting is used. However, reference counting has a problem, that it can't break cycles of reference. I have four questions with this issue. 1) Could anybody offer me one snippet in which the cycles of reference happened? 2) If it can't break cycles of reference, how does RCSP guarantee success resource manage? Is there any way to break the cycles with 3rd party product? 3) Is there anyway to avoid the cycles of reference? 4) How about other smart pointers? How does they deal with the source manage? For example, share_ptr, scope_ptr? Many thanks!
The usual way to avoid cycles is to use weak references in any one point of the cycle. shared_ptr has a companion type, weak_ptr, which is designed for this purpose. Which part of the cycle to weaken is a matter of design. In designs where "parent" objects own "children", then the reference from parent to child should be strong (shared_ptr), and the reference from child back to parent should be weak (weak_ptr).
2,345,774
2,345,777
Confused on C++ casting
I have been reading a lot about C++ casting and I am starting to get confused because I have always used C style casting. I have read that C style casting should be avoided in C++ and that reinterpret_cast is very very dangerous and should not be used whenever there is an alternative. On the contrary to not using reinterpret_cast, I have seen it used many times on MSDN in their sample code. This leads me to ask my first question, when is it ok to use reinterpret_cast? For example: LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { switch (Msg) { case WM_CREATE: { LPCREATESTRUCT lpCreateStruct = reinterpret_cast<LPCREATESTRUCT>(lParam); return 0; } } ... } If that is not ok, then how would I cast the LPARAM value to a pointer using only static, dynamic, and/or const casting? Also: If reinterpret_cast is not portable, how would I rewrite it to be portable (for good practice)
Using reinterpret_cast is acceptable if you know that the pointer was originally of the destination type. Any other use is taking advantage of implementation-dependent behavior, although in many cases this is necessary and useful, such as casting a pointer to a structure into a pointer to bytes so that it can be serialized. It is considered dangerous because it does no checking, either at compile-time or at runtime. If you make a mistake, it can and will crash and burn horribly, and be difficult to debug. You are essentially telling the compiler "I know better than you what this actually is, so just compile the code and let me worry about the consequences."
2,345,933
2,345,936
Boost Regex Find host/domain name
I'm very new to c++ and boost. I'm trying to get the host name of a given url: this is what I have now: int main() { string url = "http://www.amazon.com/gp/product/blabla"; //Regular Expression from Javascript. boost::regex ex("/^((\w+):\/\/\/?)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#;\|]+)?([;\|])?([^\?#]+)?\??([^#]+)?#?(\w*)/"); boost::regex_search(url, ex); // I want it to get "http://www.amazon.com/". } and I get tons of errors : "unrecognized character escape sequence" I took this regex from Javascript. I'm not sure I can do that. What is the Regular Expressions types I can use in 'Boost.regex' except Perl? Is there any kind of regex converter? (because I'm converting tons of code from Javascript to c++, and I have few more Regular Expressions). btw, this is the function I have in Javascript: parseHostname: function(url) { m = /^((\w+):\/\/\/?)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#;\|]+)?([;\|])?([^\?#]+)?\??([^#]+)?#?(\w*)/.exec(url) || []; return m[6]; }, To see this example with PCRE and the complete code - link.
Since the backslash (\) is an escape character in C (& C++) string constants, you need to escape it. i.e replace all instances of \ with \\ LOL. I had the same problem with this post! All the backslashes disappeared because I forgot to escape them. Check this page to see the different regex types available in Boost. It has a JavaScript type which just maps to normal, which implies the default is compatible with JavaScript regexes.
2,346,060
2,346,146
Calling Lua function without executing script
I am embedding Lua into a C/C++ application. Is there any way to call a Lua function from C/C++ without executing the entire script first? I've tried doing this: //call lua script from C/C++ program luaL_loadfile(L,"hello.lua"); //call lua function from C/C++ program lua_getglobal(L,"bar"); lua_call(L,0,0); But it gives me this: PANIC: unprotected error in call to Lua API (attempt to call a nil value) I can only call bar() when I do this: //call lua script from C/C++ program luaL_dofile(L,"hello.lua"); //this executes the script once, which I don't like //call lua function from C/C++ program lua_getglobal(L,"bar"); lua_call(L,0,0); But it gives me this: hello stackoverflow!! I am wanting this: stackoverflow! This is my lua script: print("hello"); function bar() print("stackoverflow!"); end
As was just discussed in #lua on freenode luaL_loadfile simply compiles the file into a callable chunk, at that point none of the code inside the file has run (which includes the function definitions), as such in order to get the definition of bar to execute the chunk must be called (which is what luaL_dofile does).
2,346,083
2,346,098
why implicit conversion is harmful in C++
I understand that the keyword explicit can be used to prevent implicit conversion. For example Foo { public: explicit Foo(int i) {} } My question is, under what condition, implicit conversion should be prohibited? Why implicit conversion is harmful?
Use explicit when you would prefer a compiling error. explicit is only applicable when there is one parameter in your constructor (or many where the first is the only one without a default value). You would want to use the explicit keyword anytime that the programmer may construct an object by mistake, thinking it may do something it is not actually doing. Here's an example: class MyString { public: MyString(int size) : size(size) { } //... other stuff int size; }; With the following code you are allowed to do this: int age = 29; //... //Lots of code //... //Pretend at this point the programmer forgot the type of x and thought string str s = x; But the caller probably meant to store "3" inside the MyString variable and not 3. It is better to get a compiling error so the user can call itoa or some other conversion function on the x variable first. The new code that will produce a compiling error for the above code: class MyString { public: explicit MyString(int size) : size(size) { } //... other stuff int size; }; Compiling errors are always better than bugs because they are immediately visible for you to correct.
2,346,130
2,346,589
Does the GPLv2 preclude me from using KLone for my website?
I recently discovered Klone. Being a C++ developer, I'm fascinated by the idea of getting to use C++ for my web development work (I know, I'm a glutton for punishment!)... Anyhow, it looks like the open source version of KLone is licensed under GPLv2... Normally, this would be fine, but since you're app is compiled and linked right into the server, it looks like KLone's license would also force me to open source the complete sources to any website I develop with it. The quote on their license page also leads me to this conclusion: This license is for those who develop (and possibly distribute) Free Software and want to use KLone to build their GPL product. GPL imposes that all code that is linked to any GPL'd object file must be released under GPL. This means that the patches applied to KLone source base (if any) and server embedded content (in the form of generated C files) must be provided on request as stated by GPL v2 license. First, is my read of this correct? If so, does anyone know of any similar open source project with a less restrictive license?
I think the answer on the GPL version: Yes, if you are making a non-GPL compatible open source product, they are expressly asking that you not use the source code version of klone. That is sort of the point of the GPL. You can't use the source if you don't open up your source. As to the question of does the GPL cover linked software... that is way over my non-legal head, but there are plenty of people that have sounded in on it, just google. ... BUT ... all is not lost: From their site license page For those whose cannot use GPL license in their product because of third party license restrictions, or those who prefer not to disclose the source code of their product, the KLone Commercial License can be used instead of GPL. KLone Commercial License grants permission to distribute or embed binary-only versions of KLone-based applications allowing the development, distribution and sale of proprietary software. Honestly, I'd contact them if you had questions. It sounds like they are pretty amicable to commercial use of klone, as long as you follow their licensing guidelines. Certainly the GPL route is out (as is all other GPL code that you would use from the web and distribute, for sale or otherwise).
2,346,163
2,346,223
pimpl idiom vs. bridge design pattern
I just noticed a new term pimpl idiom, what's the difference between this idiom with Bridge design pattern? I am confused about that. I also noticed the pimpl idiom is always used for swap function, what's that? Could anybody give me an example?
PIMPL is a way of hiding the implementation, primarily to break compilation dependencies. The Bridge pattern, on the other hand, is a way of supporting multiple implementations. swap is a standard C++ function for exchanging the values of two objects. If you swap the pointer to the implementation for a different implementation, you are essentially changing the mechanism of the class at runtime. But in its basic and common form, a class using PIMPL points to a single implementation, so there is no abstract class with distinct subclasses — just one class, forward declared, and compiled elsewhere. Changing the implementation class does not require any recompilation of sources that include the main header. For example, say you have a lot of private member functions, private enums, and private data. And these private "bits" change fairly frequently as the class is developed and maintained. If the #include dependencies are such that touching this header file causes a large number of sources to be recompiled, you have a good candidate for PIMPL. So the Bridge pattern is about object-oriented design, while the PIMPL idiom is about physical design of files. (For more on physical design, I recommend the book Large-Scale C++ Software Design by John Lakos.)
2,346,189
2,346,203
How can I break out of my do/while loop?
void GasPump::dispense() { bool cont = true; char stop; do{ cout << "Press any key, or enter to dispense.\n" << "Or press 0 to stop: \n"; cin.get(stop); gasDispensed = gasDispensed + gasDispensedPerCycle; charges = costPerGallon*gasDispensed; displayGasNCharges(); if(stop == 0) cont = false; } while(cont); } Doing an assignment, this is my first program to write with objects so bear with me. I just can't get the output of this code to turn out right. I need a way to get out of the loop, and what I'm using just isn't working. Any suggestions, hints or tips?
Try comparing stop to the zero char. stop == '0' Also you can simplify your code by doing this. void GasPump::dispense() { char stop; do { cout << "Press any key, or enter to dispense.\n" << "Or press 0 to stop: \n"; cin.get(stop); gasDispensed = gasDispensed + gasDispensedPerCycle; charges = costPerGallon*gasDispensed; displayGasNCharges(); } while (stop != '0'); }
2,346,277
2,346,290
Does the following code invoke Undefined Behavior?
#include <iostream> #include <cmath> #define max(x,y) (x)>(y)? (x): (y) int main() { int i = 10; int j = 5; int k = 0; k = max(i++,++j); std::cout << i << "\t" << j << "\t" << k << std::endl; }
No, it doesn't. In this case the situation is saved by the fact the ?: operator has a sequence point immediately after evaluating the first operand (the condition) and after that only one of the two expressions (second or third operand) is evaluated. Your code is equivalent to ... bool c = i++ > ++j; k = c ? i++ : ++j; ... No undefined behavior here.
2,346,328
2,346,344
Breaking down WinMain's cmdLine in old style main()'s arguments
I want to convert WinMain's cmdLine argument to argc and argv so I can use the argument parsing function I wrote for console applications. This would be trivial except that I want to support "quotes" too. For example: test.exe test1 test2 "testing testing" should be argv[0] = "test.exe"; argv[1] = "test1"; argv[2] = "test2"; argv[3] = "testing testing"; I realize that cmdLine doesn't have the program name (the argv[0]); this doesn't matter I can use a dummy value. I was thinking of doing it with a regex, (("[^"]+")\s+)|(([^\s]+)\s*) I'm not sure how well it would work though.. Probably not very well? Is there any function to do that in the windows api? Thanks
CommandLineToArgvW looks like it would be helpful here.
2,346,462
2,346,538
Tracking down strange error
I'm trying to do some C++ exercises, but I'm running into a error on build, which doesn't just jump out at me. What am I missing? I'm just getting back to C++ from C# et al after having done it years ago. [ERROR] syntax error : 'return' [/ERROR] #include <iostream> using namespace std; /* Pre-compiler directives / macros */ #define isValidDrinkChoice(Choice,MaxNumDrinks) ((Choice < MaxNumDrinks) && (Choice > 0)) /* Primary Entry Point for Executable */ int main(const int & argc, char * argv[]){ const int MaxNumDrinks = 4; char ** Drinks; Drinks = new char* [MaxNumDrinks]; Drinks[0] = "Soda"; Drinks[1] = "Water"; Drinks[2] = "Coffee"; Drinks[3] = "Tea"; Drinks[4] = "Perrier Sparkling Water"; int Choice = -1; do while(!isValidDrinkChoice(Choice, MaxNumDrinks)) { cout << "Please select your favorite drink\r\n\r\n" << endl; for (int x = 0; x < MaxNumDrinks; x++) cout << "\t" << Drinks[x] << endl; cin >> Choice; if (isValidDrinkChoice(Choice, MaxNumDrinks)) cout << "\r\n\r\n" << "You chose " << *Drinks[Choice] << endl; } return 0; }
The Corrected code sample its the while loop that needs replacement #include <iostream> namespace { bool isValidDrinkChoice(int Choice, int MaxNumDrinks) { return ((Choice < MaxNumDrinks) && (Choice >= 0)); } } /* Primary Entry Point for Executable */ int main() { using namespace std; const char *Drinks[] = { "Soda", "Water", "Coffee", "Tea", "Perrier Sparkling Water" }; const int MaxNumDrinks = sizeof(Drinks) / sizeof(*Drinks); int Choice = -1; do { cout << "Please select your favorite drink\r\n\r\n" << endl; for (int i = 0; i < MaxNumDrinks; i++) cout << Drinks[i] << endl; cin >> Choice; if (isValidDrinkChoice(Choice, MaxNumDrinks)) cout << "\r\n\r\n" << "You chose " << Drinks[Choice] << endl; } while(!isValidDrinkChoice(Choice, MaxNumDrinks) && cin) ; return cin.good() ? 0 : 1; }
2,346,481
2,346,494
An initial value assumption about map in c++
I am initializing a map map<string,int> ex; in C++. I could not find contains_key or similar function in stl, hence I am just using ex[inputString]++; The debugger shows the int to be initialized to zero correctly, is it a good assumption?
Yes, values that do not exist when accessed with operator[] are default-constructed. For numeric values, this is 0. That said, you're looking for the count method: bool hasElement = ex.count("element");
2,346,533
2,346,647
partial specialization of template class issue!
The following code is confusing me //partial specialization of vector template<class t> class vector {.... }; template<class t> //teacher said that this partial specialization will handle all type of pointers class vector<t*> ... }; This is confusing me a lot, Suppose t is a char* , as the compiler will first look for the complete specialization as there is no complete specialization here , the partial specialization would be considered. Now it will become char** in partial specialization as t is char*, then it means we are not achieving the functionality that we want. Please Explain in more understandable manner.
When the compiler instantiates vector<char*>, it matches the following template: template<class T> class vector<T*> { ... }; For this template to produce a class vector<char*> it needs to be instantiated with T=char, and this is exactly what the compiler does. When the compiler sees the type vector<char*> it will not use T=char* to instantiate the template, because this would result in the wrong type vector<char**>. It will use T=char instead, which results in vector<char*>. The compiler uses template parameters that will give the correct resulting type.
2,346,616
2,346,658
Need clarifications in C-style, reinterpret, and const casts
Am I right in assuming that C-style casts (which are discouraged) are nothing but reinterpret_casts? Using the latter is visually striking and easy to search when looking for nasty casts, and hence it's recommended over C-style casts? If casting away const using const_cast and writing to a originally const object is undefined, what is the purpose of const_cast? Note: I know that Bjarne rightly condemns casting operations that they are unsafe and even goes to the extent of stating "An ugly operation should have an ugly syntactic form." and hence the verbosity of casting operators in C++. So I'll try to minimize their usage. Promise. :)
No. A C cast can do the equivalent of a const_cast, a static_cast, a reinterpret_cast, or a combination thereof. In case that wasn't quite enough, it can also do at least one minor trick that no combination of the newer casts can do at all! You can use const_cast with defined results if the original variable is defined without const, but all you have is a const pointer or reference to that object. OTOH, if you think you have a good reason to use a const_cast, chances are that you should really look up mutable instead. Edit: I suppose I should have said it right off, but a C-style cast can convert to an an inaccessible base class. For example, consider something like: [Edit: I'm updating the code to something that'll compile and (usually) demonstrate problem. ] #include <iostream> class base1 { public: virtual void print() { std::cout << "base 1\n"; } }; class base2 { public: virtual void print() { std::cout << "base 2\n"; } }; class derived : base1, base2 {}; // note: private inheritance int main() { derived *d = new derived; base1 *b1 = (base1 *)d; // allowed b1->print(); // prints "base 1" base2 *b2 = (base2 *)d; // also allowed b2->print(); // prints "base 2" // base1 *bb1 = static_cast<base *>(d); // not allowed: base is inaccessible // Using `reinterpret_cast` allows the code to compile. // Unfortunately the result is different, and normally won't work. base1 *bb2 = reinterpret_cast<base1 *>(d); bb2->print(); // may cause nasal demons. base2 *bb3 = reinterpret_cast<base2 *>(d); bb3->print(); // likewise return 0; } The code using the reinterpret_casts will compile -- but attempting to use the result (of at lest one of the two) will cause a major problem. The reinterpret_cast takes the base address of the derived object and attempts to treat it as if it was the specified type of base object -- and since (at most) one base object can actually exist at that address, trying to treat it as the other can/will cause major problems. Edit: In this case, the classes are essentially identical except for what they print, so although anything could happen, with most compilers, both of the last two will print out "base 1". The reinterpret_cast takes whatever happens to be at that address and tries to use it as the specified type. In this case, I've (tried to) make that do something harmless but visible. In real code, the result probably won't be so pretty. The C-style cast will work like a static_cast would if the code had used public inheritance instead of private -- i.e. it's aware of where in the derived class each base class object "lives", and adjusts the result, so each resulting pointer will work because it's been adjusted to point at the right place.
2,346,653
2,347,752
How to globally mute and unmute sound in Vista and 7, and to get a mute state?
I'm using the old good Mixer API right now, but it does not work as expected on Windows Vista & 7 in the normal, not in XP compatibility mode. It mutes the sound for the current app only, but I need a global (hardware) mute. How to rearch the goal? Is there any way to code this w/o COM interfaces and strange calls, in pure C/C++?
The audio stack was significantly rewritten for Vista. Per-application volume and mute control was indeed one of the new features. Strange calls will be required to use the IAudioEndpointVolume interface.
2,346,714
2,346,721
How can I sort a std::list with case sensitive elements?
This is my current code: #include <list> #include <string> using std::string; using std::list; int main() { list <string> list_; list_.push_back("C"); list_.push_back("a"); list_.push_back("b"); list_.sort(); } Does the sort() function sort the elements according to their character codes? I want the result here to be a b C after the sorting is done.
The default comparator (<) using the default char_traits< char > will sort your list as C a b. See list::sort. In order to achieve the desired order a b C you can either: compose your list of string types with custom char_traits, or provide an instance of a custom string comparator to sort, e.g. bool istring_less(const string& lhs, const string& rhs) { string::const_iterator \ lb = lhs.begin(), le = lhs.end(), rb = rhs.begin(), re = rhs.end(); const char lc, rc; for ( ; lb != le && rb != re; ++lb, ++rb) { lc = tolower(*lb); rc = tolower(*rb); if (*lc < *rc) return true; if (*lc > *rc) return false; } // if rhs is longer than lhs then lhs<rhs return (rb != re); } ... list.sort(istring_less);
2,346,728
2,347,737
What may be the causes of the error 0x80010108 (The object invoked has disconnected from its clients)?
In C++ program the call to method of coclass returns the error 0x80010108 (The object invoked has disconnected from its clients). What may be the causes of that?
It is an RPC error, you'll see it when you use out-of-process COM. It tells you that the server .exe stopped running. It probably bombed. Or decided to exit even though there were still active interface references. That could be a reference count problem. Or improper use of CAtlModule::Lock(). Etcetera, I can only guess. Debug the server with Tools + Attach to Process and find out why it decided to quit.
2,346,797
2,346,825
Why does a class used as a value in a STL map need a default constructor in ...?
Below is the class used as the value in a map: class Book { int m_nId; public: // Book() { } <----- Why is this required? Book( int id ): m_nId( id ) { } }; Inside main(): map< int, Book > mapBooks; for( int i = 0; i < 10; ++i ) { Book b( i ); mapBooks[ i ] = b; } The statement causing the error is: mapBooks[ i ] = b; If I add a default constructor, the error does not appear. However, I don't understand why the need. Can anyone explain? If I use insert(), the problem does not appear. By the way, I'm using Visual C++ 2008 to compile.
operator[] performs a two step process. First it finds or creates a map entry for the given key, then it returns a reference to the value part of the entry so that the calling code can read or write to it. In the case where entry didn't exist before, the value half of the entry needs to be default constructed before it is assigned to. This is just the way the interface needs to work to be consistent with the case where the entry already existed. If need to use such a type in a map then you have to avoid the use of operator[] by using find and insert "manually".
2,346,800
2,346,810
C++ EOF Getline Error
I was using the form used in one of the related questions. Only problem is that i keep getting right at the end of the file. The file is an fstream and the str is a string. Unhandled exception Microsoft C++ exception: std::ios_base::failure while (getline(file, str)) { } if (cin.bad()) { // IO error } else if (!cin.eof()) { // format error (not possible with getline but possible with operator>>) } else { // format error (not possible with getline but possible with operator>>) // or end of file (can't make the difference) }
If you are getting std::ios_base::failure exceptions thrown it is most likely caused by you (or some code that you are using) turning them on for your file. They should be off by default. Just to test, you can try turning them off immediately before the while loop, but you probably need to investigate what is turning them on. file.exceptions(std::ios_base::goodbit);
2,346,806
2,346,849
What is a segmentation fault?
What is a segmentation fault? Is it different in C and C++? How are segmentation faults and dangling pointers related?
Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” It’s a helper mechanism that keeps you from corrupting the memory and introducing hard-to-debug memory bugs. Whenever you get a segfault you know you are doing something wrong with memory – accessing a variable that has already been freed, writing to a read-only portion of the memory, etc. Segmentation fault is essentially the same in most languages that let you mess with memory management, there is no principal difference between segfaults in C and C++. There are many ways to get a segfault, at least in the lower-level languages such as C(++). A common way to get a segfault is to dereference a null pointer: int *p = NULL; *p = 1; Another segfault happens when you try to write to a portion of memory that was marked as read-only: char *str = "Foo"; // Compiler marks the constant string as read-only *str = 'b'; // Which means this is illegal and results in a segfault Dangling pointer points to a thing that does not exist anymore, like here: char *p = NULL; { char c; p = &c; } // Now p is dangling The pointer p dangles because it points to the character variable c that ceased to exist after the block ended. And when you try to dereference dangling pointer (like *p='A'), you would probably get a segfault.
2,346,879
2,347,810
How do I fix class template has already been defined?
I am implementing ZipArchive library into my project, and I fought with it for over an hour getting it setup right to stop all the linker errors. But now I still have this left over and I am not sure of the best approach to fix it, could use some help. C:\Program Files\Microsoft Visual Studio 9.0\VC\atlmfc\include\afxtls_.h(199) : error C2953: 'CThreadLocal' : class template has already been defined c:\dev-mms\hl2sdk-ob-valve\public\tier0/threadtools.h(283) : see declaration of 'CThreadLocal' C:\Program Files\Microsoft Visual Studio 9.0\VC\atlmfc\include\afxtls_.h(202) : warning C4005: 'THREAD_LOCAL' : macro redefinition c:\dev-mms\hl2sdk-ob-valve\public\tier0/threadtools.h(71) : see previous definition of 'THREAD_LOCAL'
Both MS' ATL/MFC headers and the HL2 SDK contain a class template CThreadLocal. If you'd include those in the right order, i.e. ATL/MFC headers first (or the headers which include them), then the HL2 SDK headers, the HL2 SDK should handle that problem via an #ifndef __AFXTLS_H__.
2,346,940
2,346,953
How to copy string into fixed length string in C++
I have a string which I want to copy into a fixed length string. For example I have a string s = "this is a string" that is 16 characters long. I want to copy this into a fixed length string s2 that is 4 characters long. So s2 will contain "this". I also want to copy it into a fixed length string s3 that is 20 characters long. The end of the string will have extra spaces since the original string is only 16 characters long.
s.resize(expected_size,' ');
2,347,138
2,515,224
Fast implementation/approximation of pow() function in C/C++
I m looking for a faster implementation or good a approximation of functions provided by cmath. I need to speed up the following functions pow(x,y) exp(z*pow(x,y)) where z<0. x is from (-1.0,1.0) and y is from (0.0, 5.0)
Here are some approxmiations: Optimized pow Approximation for Java and C / C++. This approximation is very inaccurate, you have to try for yourself if it is good enough. Optimized Exponential Functions for Java. Quite good! I use it for a neural net. If the above approximation for pow is not good enough, you can still try to replace it with exponential functions, depending on your machine and compiler this might be faster: x^y = e^(y*ln(x)) And the result: e^(z * x^y) = e^(z * e^(y*ln(x))) Another trick is when some parameters of the formula do not change often. So if e.g. x and y are mostly constant, you can precalculate x^y and reuse this.
2,347,230
2,347,253
Keeping encrypted data in memory
I'm working with a listview control which saves the data using AES encryption to a file. I need to keep the data of every item in listview in std::list class of std::string. should I just keep the data encrypted in std::list and decrypt to a local variable when its needed? or is it enough to keep it encrypted in file only?
To answer this question you need to consider who your attackers are (i.e. who are you trying to hide the data from?). For this purpose, it helps if you work up a simple Threat Model (basically: Who you are worried about, what you want to protect, the types of attacks they may carry out, and the risks thereof). Once this is done, you can determine if it is worth your effort to protect the data from being written to the disk (even when held decrypted only in memory). I know this answer may not seem useful, but I hope it helps you to become aware that you need to specifically state (and hence know) you your attackers are, before you can correctly defend against them (i.e, you may end up implementing completely useless defenses, and so on).
2,347,357
2,347,995
how to get new vertex coordinates of a rectangular block after applying glRotate()
I am drawing a rectangular block: GLfloat cubeVertexV[] = { // FRONT -0.5f, -1.0f, 0.5f, 0.5f, -1.0f, 0.5f, -0.5f, 1.0f, 0.5f, 0.5f, 1.0f, 0.5f, // BACK -0.5f, -1.0f, -0.5f, 0.5f, -1.0f, -0.5f, -0.5f, 1.0f, -0.5f, 0.5f, 1.0f, -0.5f, // LEFT -0.5f, -1.0f, 0.5f, -0.5f, 1.0f, 0.5f, -0.5f, -1.0f, -0.5f, -0.5f, 1.0f, -0.5f, // RIGHT 0.5f, -1.0f, -0.5f, 0.5f, 1.0f, -0.5f, 0.5f, -1.0f, 0.5f, 0.5f, 1.0f, 0.5f, // TOP -0.5f, 1.0f, 0.5f, 0.5f, 1.0f, 0.5f, -0.5f, 1.0f, -0.5f, 0.5f, 1.0f, -0.5f, // BOTTOM -0.5f, -1.0f, 0.5f, -0.5f, -1.0f, -0.5f, 0.5f, -1.0f, 0.5f, 0.5f, -1.0f, -0.5f, }; Now I apply glRotate() in x, y, and z axes on this block. Now I want to change the cubeVertex array with the new coordinates resulting from the application of glRotate call. Is this possible in OpenGL?
Generally speaking, OpenGL will just accumulate the transforms, and only actually apply them to the data when you render it. In the plain old fixed-function graphics pipeline, there's no way to do it. However, as programmability has been increasing every generation, there is support for this now via OpenGL extensions, provided you're using a recent enough graphics card. Whether you have an nVidia or ATI card might also make a difference, as they don't always support the same extensions. It's been some time since I did much OpenGL, so this is going to be a little vague, but the general idea is: you bind a pair of Vertex Buffer Objects, put your data in the first one, use Transform Feedback to render the transformed vertices into the second, and you can then read back data from the second VBO into memory. The nVidia Transform Feedback Fractal demo on their OpenGL Code Samples page should help you with the actual code for this. If you want to do more general math on your GPU, you should look into GPGPU techniques, there's a LOT more stuff you can do, and with CUDA / OpenCL / etc. it gets a lot easier to code, too.
2,347,370
2,347,760
How can i check that button is clicked in no modal dialog
I created main dialog and call no modal dialog, how can i check in main dialog that button is clicked in no modal? For example if i call modal i can check like this: Dialog Dlg; int DlgResult = static_cast<int>(Dlg.DoModal()); if (DlgResult== IDOK) { //do smth. }
If its a custom dialog, one way would be to use SendMessage() or PostMessage() to send the result to the main dialog when the non-modal dialog closes.
2,347,562
2,347,610
Program crashes only in Release mode outside debugger
I have quite massive program (>10k lines of C++ code). It works perfectly in debug mode or in release mode when launched from within Visual Studio, but the release mode binary usually crashes when launched manually from the command line (not always!!!). The line with delete causes the crash: bool Save(const short* data, unsigned int width, unsigned int height, const wstring* implicit_path, const wstring* name = NULL, bool enable_overlay = false) { char* buf = new char[17]; delete [] buf; } EDIT: Upon request expanded the example. The "len" has length 16 in my test case. It doesn't matter, if I do something with the buf or not, it crashes on the delete. EDIT: The application works fine without the delete [] line, but I suppose it leaks memory then (since the block is never unallocated). The buf in never used after the delete line. It also seems it does not crash with any other type than char. Now I am really confused. The crash message is very unspecific (typical Windows "xyz.exe has stopped working"). When I click the "Debug the program" option, it enters VS, where the error is specified to be "Access violation writing location xxxxxxxx". It is unable to locate the place of the error though "No symbols were loaded for any stack frame". I guess it is some pretty serious case of heap corruption, but how to debug this? What should I look for? Thanks for help.
have you checked memory leaks elsewhere? usually weird delete behavior is caused by the heap getting corrupted at one point, then much much later on, it becomes apparent because of another heap usage. The difference between debug and release can be caused by the way windows allocate the heap in each context. For example in debug, the heap can be very sparse and the corruption doesn't affect anything right away.
2,347,599
2,347,751
assigning shared ptrs (boost) in constructor , unit testing
I have a C++ class(inside a dll project) whose member variables are boost::shared_ptrs to objects of other classes. Is it better to assign them inside the class constructor or have a separate init() function which does that. I am assuming the default value of pointer to T inside boost::shared_ptr is NULL. So if I do nothing inside the constructor will boost::shared_ptr's get() return NULL before calling Init() function. Also, what happens when there is a memory allocation problem with new in one of the assignment statement should I catch the exception(in Init) or is it good to tell the caller of this Init() to catch that exception? boost::shared_ptr a( new T); Are there standard approaches to simulate the memory allocation exceptions inside unit tests? and see all the objects are properly de-allocated
I have a C++ class(inside a dll project) whose member variables are boost::shared_ptrs to objects of other classes. Is it better to assign them inside the class constructor or have a separate init() function which does that. It is usally better to do everything in the constructor. Having an init() function that is called afterwords implies that the object is not valid after construction, so you then need to keep a state flag to indicate if init() has been called and check that flag whenever any public method are called and do somthing appropriate for an uninitialized object I am assuming the default value of pointer to T inside boost::shared_ptr is NULL. So if I do nothing inside the constructor will boost::shared_ptr's get() return NULL before calling Init() function. Yes: The default constructor for shared_ptr will initialize it to NULL. Also, what happens when there is a memory allocation problem with new in one of the assignment statement should I catch the exception(in Init) or is it good to tell the caller of this Init() to catch that exception? boost::shared_ptr a( new T); If you have a constructor: Then all members that had been constructed will be destroyed correctly (via destructor), while unitialised objects will not be touched, and the memory for the current object will be release as if never allocated (Another good reason to use the initialiser list). If you use an init(): Then you must catch the exception clean up the object correctly and release the memory. Depending on how complex the object you may be able to do this inside the init (but it is hard to do correctly) or the caller must do it. After that you should do the same as if an exception had been thrown from the constructor (so that depends on usage). Are there standard approaches to simulate the memory allocation exceptions inside unit tests? and see all the objects are properly de-allocated You can use a factory object to allocate the objects. You pass the factory object to the constructor. When you want to simulate an exception during construction just pass a mock factory that generates that appropriate exception.
2,347,823
2,347,855
How does delete differentiate between built-in data types and user defined ones?
If I do this: // (1.) int* p = new int; //...do something delete p; // (2.) class sample { public: sample(){} ~sample(){} }; sample* pObj = new sample; //...do something delete pObj; Then how does C++ compiler know that object following delete is built-in data type or a class object? My other question is that if I new a pointer to an array of int's and then I delete [] then how does compiler know the size of memory block to de-allocate?
The compiler knows the type of the pointed-to object because it knows the type of the pointer: p is an int*, therefore the pointed-to object will be an int. pObj is a sample*, therefore the pointed-to object will be a sample. The compiler does not know if your int* p points to a single int object or to an array (int[N]). That's why you must remember to use delete[] instead of delete for arrays. The size of the memory block to de-allocate and, most importantly, the number of objects to destroy, are known because new[] stores them somewhere, and delete[] knows where to retrieve these values. This question from C++ FAQ Lite shows two common techniques to implement new[] and delete[].
2,347,948
2,347,980
When should I define my own copy ctor and assignment operator
I am reading effective C++ in Item 5, it mentioned two cases in which I must define the copy assignment operator myself. The case is a class which contain const and reference members. I am writing to ask what's the general rule or case in which I must define my own copy constructor and assignment operator? I would also like to know when I must define my own constructor and destructor. Thanks so much!
You must create your own copy constructor and assignment operator (and usually default constructor too) when: You want your object to be copied or assigned, or put into a standard container such as vector The default copy constructor and assignment operator will not do the Right Thing. Consider the following code: class A; // defined elsewhere class B { private: A *my_very_own_a; }; If you let the automatic copy constructor copy a B, it will copy the A * pointer value across, so that the copy points to the same A instance as the original. But part of the design of this class is that each B has its own A, so the automatic copy constructor has broken that contract. So you need to write your own copy constructor which will create a new A for the new B to point to. However, consider this case: class A; // defined elsewhere class B { private: A *shared_reference_to_a; }; Here each B contains a pointer to an A, but the class contract doesn't demand a unique A for each B. So the automatic copy constructor might well do the Right Thing here. Note that both examples are the same code, but with different design intent. An example of the first situation might be B == dialog box, A == button. If you create a copy of a dialog box, it probably needs a copy of all the contents too. An example of the second might be B == dialog box, A == reference to window manager. If you copy a dialog box, the copy probably exists in the same window manager as the original.
2,348,045
2,348,070
Resolve C++ virtual functions from base class
Sorry if this is a dupe, I cant find an answer quite right. I want to call a function from a base class member, and have it resolve to the subclass version. I thought declaring it virtual would do it, but it isn't. Here's my approach: class GUIWindow { public: GUIWindow() { SetupCallbacks(); } virtual void SetupCallbacks() { // This function always called } }; class GUIListbox : public GUIWindow { public: void SetupCallbacks() { // This never called } }; GUIListbox lb; // GUIWindow::SetupCallbacks is called :( What am I doing wrong? Many thanks Si
Never call a virtual function in the constructor.
2,348,363
2,348,372
String array in C++ not working properly?
I'm working on a program for class that takes in a number from 0 to 9999, and spits out the word value (ie 13 would be spit out as "thirteen", etc) And I'm having a pain with the array for some reason. Here is the class so far: #include<iostream> #include<string> using namespace std; class Numbers { private: int number; string lessThan20[ ] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; string incrementsOfTen[ ] = {"twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"}; string hundred = "hundred"; string thousand = "thousand"; public: Numbers(int newNumber) { setNumber(newNumber); } void setNumber(int newNumber) { if(newNumber < 0 || newNumber > 9999) { cout << "Number cannot be negative or larger than 9999, defaulted to zero." << endl; number = 0; } else { number = newNumber; } } int getNumber() { return number; } }; My issue is up at the two string arrays, I'm getting these errors back from my compiler: 1>f:\college work\csis 297\assignment 4\chapter 11-1\chapter 11-1\11-1.cpp(19) : error C2059: syntax error : '{' 1>f:\college work\csis 297\assignment 4\chapter 11-1\chapter 11-1\11-1.cpp(19) : error C2334: unexpected token(s) preceding '{'; skipping apparent function body 1>f:\college work\csis 297\assignment 4\chapter 11-1\chapter 11-1\11-1.cpp(22) : error C2059: syntax error : '{' 1>f:\college work\csis 297\assignment 4\chapter 11-1\chapter 11-1\11-1.cpp(22) : error C2334: unexpected token(s) preceding '{'; skipping apparent function body 1>f:\college work\csis 297\assignment 4\chapter 11-1\chapter 11-1\11-1.cpp(24) : error C2864: 'Numbers::hundred' : only static const integral data members can be initialized within a class 1>f:\college work\csis 297\assignment 4\chapter 11-1\chapter 11-1\11-1.cpp(25) : error C2864: 'Numbers::thousand' : only static const integral data members can be initialized within a class I'm sure if I spend more time on the single variable strings I can figure those out, but I've spent the better part of an hour looking up what I'm doing wrong on the two arrays, any advice or information would be appreciated. Thanks in advance. PS: No, there is no main, haven't gotten there yet, my program has a blank main right now as I'm simply trying to get the class to compile error free for now. EDIT for clarification: The first two errors are on the first array, the second two errors on the second array, and the last two errors are on the non-array strings.
The error message says it all: only static const integral data members can be initialized within a class You cannot do what you want, you have to separate declaration and initialization, and move the initialization either to the constructor, or use a static const, and put the initialization outside the class. This is preferred, since the values don’t actually change, or depend on an instance: class Numbers { private: static const string lessThan20[]; // … }; string const Numbers::lessThan20[ ] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; And analogously for the other array.
2,348,371
2,348,436
GUI declarative language implementation
I've recently begun working on a project regarding GUI building using some form of declarative language. What i mean is that i need to describe an hierarchy of objects, without specifying the type of GUI widgets that will be used to "show" that hierarchy. For example, for some existing hierarchy H, using JSON notation (or something like that): H = { "title" : "Label_1" "children" : [ { "title" : "Label_2" "children": [ { "title": "Field_A" "type": "Integer" "value": 10 }, { "title": "Field_B" "type": "String" "value": "YES" } ] } ] } Someone could build a simple window, that would be shown to the user by pressing a button labeled "Label_1". The window could be then titled "Label_2" and have two fields labeled "Field_A" and "Field_B" accepting integer and boolean values respectively. Someone else, could put this hierarchy on a tree list, e.g -------------------------------------------------------- >Label_1 | >Label_2 | >Field_A | 10 >Field_B | YES My first question is, well, do i have to build some form of a language parser to achieve something like this ? Could i use JSON then ? Though i don't need to support complex hierarchies, there is need to support mutually exclusive hierarchies (something like radio buttons enabling/disabling options). I have the feeling that it looks like some form of language parsing with a couple of operators. Don't get me wrong, i am of a Mechanical Engineering background, and i am not an experienced programmer. Thank you in advance for your comments and help.
JSON would be one choice. XML would be another -- for example, Microsoft uses XAML (an XML dialect) for exactly this purpose and the W3C has a (fairly new) Widget packaging specification (using another dialect of XML). Any of these will let you use existing parsers instead of building yet another from the ground up.
2,348,442
2,348,447
What does "WINAPI" in main function mean?
Could you please explain to me the WINAPI word in the WinMain() function? In the simplest way.. #include <windows.h> int -->WINAPI<-- WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MessageBox(NULL, "Goodbye, cruel world!", "Note", MB_OK); return 0; } Is it just some Windows funky mode? What does it do? Or rather what is this C++ feature I haven't encountered yet?
WINAPI is a macro that evaluates to __stdcall, a Microsoft-specific keyword that specifies a calling convention where the callee cleans the stack. The function's caller and callee need to agree on a calling convention to avoid corrupting the stack.
2,348,581
2,349,256
How to know when a wxFrame is closed?
I have a wxDialog where I open a wxFrame. Now I want to know when the wxFrame is closed, so I can do something in the Dialog caller [on the frame I modify a list which is present too in the dialog, and I need to update this (with a function provided by me)]. Any Ideas? I'm using C++ with wxWidgets 2.8-10 Here is the code of the function who call the frame: OK=false; password dialog(this,&OK); //I check the admin password, if it's correct, OK is true dialog.ShowModal(); if (OK){ GestionFrame* Frame = new GestionFrame(0,listaGlobal); //listaGlobal is a list of names Frame->Show(); reload(); //reload the list of names on the dialog, but reload must be called after the frame is closed (and the data is saved)
You'll know when the frame is closed by handling the wxCloseEvent. In the handler, do whatever to notify the "Dialog caller" that it should reload (e.g by posting an event). BTW, ShowModal won't return until the dialog is dismissed, and it will return a value (set by EndModal). Then you wouldn't need to mess with the OK reference.
2,348,759
2,349,638
OOP: self-drawing shapes and barking dogs
Most of the books on object-oriented programming I've read used either a Shape class with a Shape.draw() member function or a Dog class with a Dog.talk() member function, or something similar, to demonstrate the concept of polymorphism. Now, this has been a source of confusion for me, which has nothing to do with polymorphism. class Dog : public Animal { public: ... virtual void talk() { cout << "bark! bark!" << endl; } ... }; While this might work as a simple example, I just can't imagine a good way to make this work in a more complicated application, where Dog.talk() might need to access sound subroutines of another class, e.g. to play bark.mp3 instead of using cout for output. Let's say I have: class Audio { public: ... void playMP3(const string& filename) ... }; What would be a good way to access Audio.playMP3() from within Dog.talk() at design time? Make Audio.playMP3() static? Pass around function pointers? Have Dog.talk() return the filename it wants to play and let another part of the program deal with it?
My solution would be for the Dog class to be passed an audio device in the bark function. The dog should not store a pointer to the audio device all the time, that's not one of its responsibilities. If you go that route, you end up with the constructor taking two dozen objects, essentially pointing to all the rest of the application (it needs a pointer to the renderer too, so it can be drawn. It needs a pointer to the ground, and to the input manager telling it where to go, and........... Madness lies that way. None of that belongs in the dog. If it needs to communicate with another object, pass that object to the specific method that needs it. The dog's responsibility is to bark. A bark makes a sound. So the bark method needs a way to generate a sound: It must be passed a reference to an audio object. The dog as a whole shouldn't care or know about that. class Dog: public Animal { public: virtual void talk(Audio& a); }; By the same logic, shapes should not draw themselves. The renderer draws objects, that's what it's for. The rectangle object's responsibility is just to be rectangular. Part of this responsibility is to be able to pass the necessary drawing data to the renderer when it wishes to draw the rectangle, but drawing itself is not part of it.