question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,849,961
1,849,967
Disallow any member function to change its data members in C++ Class
So how i can do this? So that no member function can change the value of its data members once object has been initialized in C++.
Make all the member functions const. That's the only mechanism for the job, and it works just fine. If you also make them private you're completely covered. If for some reason you feel compelled to mark them protected, then things are more complicated. You will need to make the individual fields const, and that will in turn require you to initialize them via the member initialization list, or a const_cast of this in the constructor. Or maybe a mutable ctor, but I'm not sure there is such a thing.
1,849,991
1,850,002
Best practices: Where should function comments go in C/C++ code?
So... I understand this might be subjective, but I'd like some opinions on what the best practice for this is. Say I have the following header and .cpp file: header: // foo.h class foo { public: int bar(int in); }; cpp: // foo.cpp int foo::bar(int in) { // some algorithm here which modifies in and returns the modified value } Now say I have this function comment: /* input: an integer as input to algorithm foo output: The result of the algorithm foo on input in remarks: This function solves P = NP */ Would best practice be to place this function comment in the header above the function declaration or above the function definition in the cpp file? Thanks SO
I put comments describing what the function does in the header and comments describing how it does it in the cpp file.
1,850,192
1,850,552
Correct way to write console applications on GNU/Linux with C++
I really like the console and got recently hooked on programming console applications using nCurses mainly in conjunction with the C programming language. Unfortunately i think the ncurses API is totally borked and very hard to use, and the C++ bindings are undocumented. So my question is, what is THE API to use for C++ console applications?
maybe you'd like s-lang better?
1,850,227
1,850,285
Cross language development problem
I'm working on a project that involves a database (My SQL), website (PHP) and a custom high performance server application (C++). The C++ application (and its accompanying client application) make up the main bulk of the project, with the database storing long term data for it. The website is primarily for displaying various statistics, and administration. 1) I want the PHP scripts and c++ application to be able to communicate in some way, since the database is only used for persistent data, and additionally the c++ application may cache some things so needs to be told to reload the data in some cases. It is highly likely they will be on different machines, and even possibly different OS's. I've been considering the idea that TCP may be the best option with some simple command - response protocol? 2) What is the best way to write the common database interface code once, and be able to use it from both the PHP website and the c++ applications?
You might try not allowing PHP to access the database at all. Make the C++ app do all the database work, and make it serve data to the PHP site. You could run part of the C++ app as a server for the PHP to fetch reports etc from it.
1,850,636
1,850,664
Conditional compilation
How do I add conditional compilation to my makefile: say if I have a #ifdef SAVE_DATA in a cpp (.cc) file.
Usually something like CXXFLAGS+=-DSAVE_DATA
1,850,809
1,850,825
Static struct linker error
I'm trying to create a static struct in C++: static struct Brushes { static HBRUSH white ; static HBRUSH yellow ; } ; But its not working, I'm getting: Error 4 error LNK2001: unresolved external symbol "public: static struct HBRUSH__ * Brushes::white" Why? The idea is to be able to use Brushes::white, Brushes::yellow throughout the program, without having to create an instance of Brushes.
You have to define the static members somewhere, usually in the .cxx file, e.g.: HBRUSH Brushes::white; The reason is that the header file doesn't make the definition, it only declares it.
1,851,034
1,851,068
USB How do you create a bootable custom USB application?
Many LCD televisions nowadays have USB ports so you can plug in your camera and it becomes a camera gallery on the TV. I want to write a gallery program which, when plugged in to the TV, will start to cycle through the images on the USB device. How would I do this? Is it possible to write some sort of OS/application which can run on the USB device alone?
That would depend entirely on the television's firmware whether it would even be supported. If it were, the specification of how to do it would need to be observed.
1,851,053
1,851,923
Calling static pointer to a list from a shared library in c++
I have a static class member class bar {...} class foo { public: static QHash<qint64,bar>* barRepHash; } Now I call a function which accesses this member within a shared library, I get a memory error whereas when I access the function through the main program, it works fine. I've tested this under a number of circumstances. I initialize the variable in the main application but I don't intialize it again in the shared library (it seemed unnecessary). I'm using GCC and QT in Ubuntu. What going and how can I fix it?
IIRC the exe and shared library will get their own copies of static member variables like that, and that as such you will need to initialise it separately in each case. Since its a pointer, one way may be to initialise it in your main program as normal and then pass the pointer to the dll when you load it so that the dll's version can be set to point to the same place as the exe's one. EDIT: Ok, I did some tests (Windows, VC9), and it appears that globals, and static variables (be it function, class, whatever) are per-module (i.e. every exe and dll will gets it's own copy, even if the variable came from a common source, like say a static library). I'm going to test to see if the dllimport/export on the class makes them use a common copy. EDIT2: Ok using __declspec(dllexport) in the dll and __declspec(dllimport) in the exe (use preprocessor macros to switch between them depending on what includes the header), for the static variable declaration made the static variable common to both modules. It also works for global variables, and I'll assume static function variables. #pragma once //defined when compiling test.dll #ifdef TEST_EXPORTS #define DLL __declspec(dllexport) #else #define DLL __declspec(dllimport) #endif //foo and bar definition in test.cpp, ie only in the dll's compile class X { public: static int foo; }; DLL extern int bar; AFAIK GCC however doesn't have dllexport and dllimport, however it may have some other way of achieving the same effects when creating shared libaries (be it a dll or so). If it doesn't, then the only other solution I can think of is what I first suggested. Initialise your static pointer in the exe, then have a function in the dll to set the static var, which the exe can call passing its copy of the pointer.
1,851,078
1,851,118
Random bytes with fread
#post The names of my variables are not imporant! This code will be deleted when it works! #post Alright, so I'm using fread in stdio.h to read a text file. The problem is that I keep reading random bytes that don't exist in the text file from my knowledge. I'm assuming they are part of files scheme, but I just wanna make sure it's not my code. #include "stdafx.h" #ifdef WIN32 #include <io.h> #else #include <sys/io.h> #endif #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include "n_script_timer.h" //using namespace std; #ifdef _INC_WCHAR typedef wchar_t CHR; #else typedef char CHR; #endif int _tmain(int argc, CHR* argv[]) { #ifndef _DEBUG if(argc == 1) { printf("You must drag a file onto this program to run it."); scanf("%*c"); return 0; } CHR* fname = argv[1]; #else #ifdef _INC_WCHAR const CHR fname[16] = L"f:\\deleteme.bin"; #else const CHR fname[16] = "f:\\deleteme.bin"; #endif #endif FILE* inFile; long len; struct Script_Timer a; //static const int bsize = 4096*6; static const int bsize = 84; typedef CHR chhh[bsize]; int alen; printf("#Opening File '%s' ...\n",fname); #ifdef _INC_WCHAR if((inFile = _wfopen(fname,L"rb")) == NULL) #else if((inFile = fopen(fname,"r")) == NULL) #endif { printf("Error opening file '%s' ",fname); return 0; } fseek(inFile,SEEK_SET,0); #ifdef _WIN32 len = _filelength( inFile->_file ); #else len = _filelength(inFile->_fileno); #endif printf(" !FileLength: %d\n",len); printf("#Creating Buffers...\n"); if(((float)len/(float)bsize) > (len/bsize)) { alen = (len/bsize) + 1; } else alen = (len/bsize); #ifdef WIN32 //chhh *cha = new chhh[alen]; chhh cha[alen]; #else chhh cha[alen]; #endif printf("#Reading File...\n"); Start_ST(&a); int i = 0; for(i=0;i<alen;++i) { fread(&cha[i],sizeof(CHR),bsize,inFile); printf("[%i]%s",i,cha[i]); } End_ST(&a); fclose(inFile); printf("Characters per millisecond: %f \n",((float)len/a.milliseconds)); printf("Characters per second: %f \n",((float)len/a.milliseconds) * 1000); scanf("%*c"); return 0; }
A couple of weird things here: int i = 0; for(i=0;i<alen;++i) { fread(&cha[i],sizeof(CHR),bsize,inFile); printf("[%i]%s",i,cha[i]); } You don't null terminate the buffer before printing it (as RageZ pointed out). You increment i on each loop repetition, but every time you read 84 chars (bsize) into &cha[i]. I think this should mean you're only seeing every 84th character. Also, if I were you I'd be checking the return value of fread every time. It's not guaranteed to always return the number of bytes you're expecting. EDIT: The size of the block you're reading is fine. I got confused for a minute by the typedef. Every time you increment i by 1, it advances the pointer by 84*sizeof(CHR), as you intended. Still, you can't guarantee that it read the number of bytes that you think it did. If it came up short then you'll be left with junk in the buffer: say it read 60 chars, that leaves 24 junk chars before the insertion point for the next read.
1,851,167
1,851,220
Algorithm for finding path to point
I'm not sure if I worded this properly, but basically I have an object at point X,Y and I want an algorithm that can get this point to X',Y' but like show its route so I can animate it. I'm building a tile game and when the game starts I want the tiles to magically place themselves into a nice 2d array. So I will generate a random coordinate and then tell it to go to its goal within 50 frames. Thanks
It sounds like you just want a linear transformation. Like Xt = (((X'-X)/T)*t)+X, Yt = (((Y'-Y)/T)*t)+Y Or in English the coordinate for a tile at time t is t/total_frames length along it's path. A* is overkill if you aren't trying to avoid obstacles.
1,851,267
1,851,334
MinGW/GCC Delay Loaded DLL equivalent?
I'm trying to port some old MSVC C++ code to MinGW/GCC. One problem is that the project relies heavily on the /DELAYLOAD option for functions that aren't always used, and where the proper dll is located at runtime. Is there such a similar option on MinGW/GCC? This code is targeting the windows platform.
On elf targets (for Unix-like systems), you can specify the -z lazy option (which is the default anyway) with ld (the linker that MinGW also uses). As far as I know, the i386 PE target (for Windows) does not have an explicit lazy linking option. I can find no documentation of it being available.
1,851,279
1,852,123
What is the recommended way of passing keyboad events to QProcess transparently?
I have a GUI application, which creates a QProcess inside, catches its output and shows it on a form. I need to somehow catch key events from the form to pass them to QProcess (to make it fell as close as possible to real terminal window). So, I suppose, I should process keyReleaseEvent() and somehow transform either event.text() (which is QString) or event.key() (which is int) to argument, suitable for process.write() (which takes char* or QByteArray). Is there some recommended way to do such a conversion (taking into account localization issues, ctrl/alt/shift modifiers and so on)? I do not really want to construct some sort of mapping from key() return values to char* strings; and text() drops modifiers. Moreover, if I start process with command bash -c sudo something in QProcess, it exits instantly, complaining that "no tty present and no askpass program specified", so I may be doing something completely wrong...
The problem is more than just deciding what to write to the process. You can't emulate a terminal just by reading/writing stdout/stdin of a process, it's more complicated than that. Think about the program less, or any pager, for example. How does it know how many lines to print at a time? It needs information about the terminal which isn't represented through stdin/stdout/stderr. Emulating a terminal is beyond the scope of QProcess. If you're really sure you need to do this then use some existing Qt-based terminal emulator as a starting point (e.g. Konsole).
1,851,315
3,398,066
Boost's Interpreter.hpp example with class member functions
Boost comes with an example file in boost_1_41_0\libs\function_types\example called interpreter.hpp and interpreter_example.hpp I am trying to create a situation where I have a bunch of functions of different arguments, return types, etc all register and be recorded to a single location. Then have the ability to pull out a function and execute it with some params. After reading a few questions here, and from a few other sources I think the design implemented in this example file is as good as I will be able to get. It takes a function of any type and allows you to call it using a string argument list, which is parsed into the right data types. Basically its a console command interpreter, and thats probably what its meant to illustrate. I have been studying the code and poking around trying to get the same implementation to accept class member functions, but have been unsuccessful so far. I was wondering if someone could suggest the modifications needed, or maybe worked on something similar and have some same code. In the example you'll see interpreter.register_function("echo", & echo); interpreter.register_function("add", & add); interpreter.register_function("repeat", & repeat); I want to do something like test x; interpreter.register_function("classFunc", boost::bind( &test::classFunc, &x ) ); But this breaks the any number of arguments feature. So I am thinking some kind of auto generating boost::bind( &test::classFunc, &x, _1, _2, _3 ... ) would be the ticket, I just am unsure of the best way to implement it. Thanks
I've been working on this issue and i've somewhat succeeded to make the boost interpreter accept the member function such as: // Registers a function with the interpreter, // will not compile if it's a member function. template<typename Function> typename boost::enable_if< ft::is_nonmember_callable_builtin<Function> >::type register_function(std::string const& name, Function f); // Registers a member function with the interpreter. // Will not compile if it's a non-member function. template<typename Function, typename TheClass> typename boost::enable_if< ft::is_member_function_pointer<Function> >::type register_function(std::string const& name, Function f, TheClass* theclass); The enable_if statement is used to prevent the use of the wrong method at the compile time. Now, what you need to understand : It uses the boost::mpl to parse trough the argument's parameter types of the callable builtin (which is basically a function pointer) Then, prepares a fusion vector at the compile-time (which is a vector that can stock different objects of different types at the same time) When the mpl is done parsing every arguments, the "parsing" apply method will fork in the "invoke" apply method, following the templates. The main issue is that the first argument of a member callable builtin is the object which holds the called method. As far a I know, the mpl cannot parse the arguments of something else than a callable builtin (i.e A Boost::Bind result) So, what needs to be done is simply add one step to the "parsing" apply, which would be to add the concerned object to the apply loop! Here it goes: template<typename Function, typename ClassT> typename boost::enable_if< ft::is_member_function_pointer<Function> >::type interpreter::register_function( std::string const& name, Function f, ClassT* theclass); { typedef invoker<Function> invoker; // instantiate and store the invoker by name map_invokers[name] = boost::bind(&invoker::template apply_object<fusion::nil,ClassT> ,f,theclass,_1,fusion::nil()); } in interpreter::invoker template<typename Args, typename TheClass> static inline void apply_object( Function func, TheClass* theclass, parameters_parser & parser, Args const & args) { typedef typename mpl::next<From>::type next_iter_type; typedef interpreter::invoker<Function, next_iter_type, To> invoker; invoker::apply( func, parser, fusion::push_back(args, theclass) ); } This way, it will simply skip the first argument type and parse everything correctly. The method can be called this way: invoker.register_function("SomeMethod",&TheClass::TheMethod,&my_object);
1,851,355
1,851,381
Converting STL String, and STL Vector into void*?
Ive got some C++ code, that we use to serialize arbitrary data and store it into a specialized image format as metadata. Anyways, it takes it as a void*. Can i just do a simple memcpy? Or is there a better way to do this?
For std::string you can use c_str() to obtain the char* pointing to the internal string. For std::vector the standard dictates that the elements are contiguous in memory and so you can access the pointer to the beginning of the data as &v[0]. You should of course be careful with these since you are basically handing the library you are using a pointer to the internal data of the objects. If needed you can make a copy of the data using memcpy using the above as the src pointer but obviously you'll need to take care that you use the correct size. Without knowing the details of the function(s) you're passing this data to it's not possible for us to comment on whether such copying is needed or not.
1,851,468
1,851,482
Usage of 'short' in C++
Why is it that for any numeric input we prefer an int rather than short, even if the input is of very few integers. The size of short is 2 bytes on my x86 and 4 bytes for int, shouldn't it be better and faster to allocate than an int? Or I am wrong in saying that short is not used?
CPUs are usually fastest when dealing with their "native" integer size. So even though a short may be smaller than an int, the int is probably closer to the native size of a register in your CPU, and therefore is likely to be the most efficient of the two. In a typical 32-bit CPU architecture, to load a 32-bit value requires one bus cycle to load all the bits. Loading a 16-bit value requires one bus cycle to load the bits, plus throwing half of them away (this operation may still happen within one bus cycle).
1,851,525
1,851,599
C++ can native type char hold End of File character?
The title is pretty self explanatory. char c = std::cin.peek(); // sets c equal to character in stream I just realized that perhaps native type char can't hold the EOF. thanks, nmr
Short answer: No. Use int instead of char. Slightly longer answer: No. If you can get either a character or the value EOF from a function, such as C's getchar and C++'s peek, clearly a normal char variable won't be enough to hold both all valid characters and the value EOF. Even longer answer: It depends, but it will never work as you might hope. C and C++ has three character types (except for the "wide" types): char, signed char and unsigned char. Plain char can be signed or unsigned, and this varies between compilers. The value EOF is a negative integer, usually -1, so clearly you can't store it in an unsigned char or in a plain char that is unsigned. Assuming that your system uses 8-bit characters (which nearly all do), EOF will be converted to (decimal) 255, and your program will not work. But if your char type is signed, or if you use the signed char type, then yes, you can store -1 in it, so yes, it can hold EOF. But what happens then when you read a character with code 255 from the file? It will be interpreted as -1, that is, EOF (assuming that your implementation uses -1). So your code will stop reading not just at the end of the file, but also as soon as it finds a 255 character.
1,851,863
1,851,877
reasons for choosing com
i was wondering why one would choose Com as his software development "technology" my first though is machine/programming _language independence what's yours ?
COM is the de facto standard for automation and IPC on windows (though .Net has begun to shift the focus), thus there are areas you simply don't have (or had) a choice: Shell extensions ActiveX builds on COM Internet Explorer extensions extending MS Office applications Scriptability for JScript, VBScript, ... with one binary Before the event of .Net nearly all automation of MS applications was through COM and quite some firms got on that train as well. Also DCOM is, if you're willing to limit yourself to windows, a reliable and proven technology for distributed components.
1,852,243
1,852,280
qt soap client + ASP.net Web service
I'm writing Qt client for ASP.NET web service with FORMS based authentication. The service consists of 3 methods: Login(user,pass) Helloworld() - this method returns info about authenticated user. Logout() Every thing working fine on the dot.net client with CookieContainer. The problem begins with HelloWorld() methods. it returns null because I can't access server session. I'm doing the following: from the response of Login() request I'm getting the cookies which are sent to client: QNetworkAccessManager *manager = http.networkAccessManager(); cookie = manager->cookieJar(); When sending the second soaprequest for HelloWorld method I adding these cookies to QtSoapHttpTransport http: http.networkAccessManager()->setCookieJar(cookie) but the request which is going from server is empty. I moved further with my investigation and monitored HTTP traffic coming to server from Qt client and .NET client. The HTTP Header for both SOAP requests are different: This is Request coming from .NET client POST /test/service1.asmx HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.3053) VsDebuggerCausalityData: uIDPoyhZznNkbItPkJSR3EA+zEIAAAAAUkpe7URduE6nmhnT8f uQeqCQBMlX0zxCm65yW4ZPBkUACQAA Content-Type: text/xml; charset=utf-8 SOAPAction: "http://localhost/test/HelloWorld" Host: localhost:8080 Cookie: MyAuthenCookie=DC7620DA79E080FECA37AC6866BF2690D57 B37443506F0D7EEA9DF209827360894D80D37E1B121D73EE44 766BDAEE16BA3FB0E8B95ADB1252AB00A76706930ACDC87CF9 F26744B7E9E3EB7FBB3812997 Content-Length: 291 Expect: 100-continue and this is Request coming from Qt SOAP client: POST /test/Service1.asmx HTTP/1.1 Content-Type: text/xml;charset=utf-8 SOAPAction: http://localhost/test/HelloWorld Content-Length: 350 Cookie: MyAuthenCookie=9AFB2B22EE78D19DFD52BD2193A3D71627C F7303C15E4354E43CC2F31AECBDFFAD09176AA45F33B35C3C3 73891F1FE994580E8EE70FD4D01507670743138E74E152CFF4 EB3C37D90D3A7A0E272A804C3 Connection: Keep-Alive Accept-Encoding: gzip User-Agent: Mozilla/5.0 Host: localhost:8080 Does any body have any idea what might be the problem and hoe to solve it? How can I modify Headers for HTTP POST request in QtSoapHttpTransport object in order to make it identical to .NET request? Thank you in advance, Danny.
Are you running IIS or the ASP.NET Development server? I was able to recreate a similar problem where everything worked fine using ASP.NET Development server but under IIS the session was null. One thing to look for is when you invoke the session-enabled-service you should see the ASP.NET_SessionId being set in the response headers Set-Cookie: ASP.NET_SessionId=5vxqwy45waoqma45lbbozj45; path=/; HttpOnly Set-Cookie: MyAuthenCookie=510969D70201B358F8B0BBEEE7E79316B7ABCCC74312B0BD678DA4BE90E5C51CD6E7CDCA486DDB41BCBF489DB7280B3B979FD70B78D7F63B03C33431ADDAFDCA; expires=Mon, 07-Dec-2009 06:41:04 GMT; path=/; HttpOnly To get sessions working under IIS, I had to add the following to web.config under system.web: <sessionState mode="InProc" cookieless="false" timeout="20" /> <httpModules> <add name="Session" type="System.Web.SessionState.SessionStateModule" </httpModules> This was under Windows 2003.
1,852,302
1,852,310
A proposal to add statemachine support to C++-like language
Lately as part of my day job I've been learning IBM Rhapsody and using it to generate code in C++ from the UML. Yesterday it struck me that it might be cool to think about adding state machine support to my C++ compiler, so I jotted a few notes here: http://ellcc.org/wiki/index.php/State_machines_and_Active_Classes My motivations for doing this are: It seems like a cool idea. The compiler could do much better semantic checking (with better error checking) than the current Rhapsody/normal C++ compiler. There are many optimization possibilities available when the compiler itself understands the state machine structure. I may try to extend my grammar to except something like the proposal to see how well it works. What is your opinion of the proposal? Does it seem readable? Does it seem worthwhile? Edit: Thanks for the answers recommending specific libraries to do state machines, but that wasn't my question. I've implemented many state machines using both libraries and code that I've written. I was really looking for ideas, criticism, etc. about the design of a state machine extension to a C++-like language, not whether this change would be appropriate for addition to standard C++. Think of it as a domain specific extension, where my my domain is real-time control applications. I've started implementation of the extension in my compiler as described here: http://ellcc.org/wiki/index.php/State%5Fmachines%5Fand%5FActive%5FClasses So far the concept hasn't had to change much going from proposal to implementation but there have been a few changes in details and I'm refining my understanding of the semantics of the problem. Time will tell whether the whole concept has any value, however. ;-)
With a few exceptions, C++ has traditionally been extended using class libraries, not new keywords. State machines can easily be implemented using such libraries, so I don't think your proposal has much of a chance. One problem I see in your proposal is the use of 'goto' to go to another state. What happens if I want to use goto in my own code within a state transition?
1,852,556
1,852,576
Casting a pointer to a sub-class (C++)
I'm developing a game and I need to find a way of getting the value of a certain 'map block' in the game (in char format). I have a class DisplayableObject which takes care of all sprites, and a sub-class ThreeDCubePlayer which takes care of the player object. For ease of rendering/updating everything, all DisplayableObjects are stored in an array, with the 0th cell containing the player (which is of type ThreeDCubePlayer). ThreeDCubePlayer has a different constructor from DisplayableObject (it takes two additional arguments) and only ThreeDCubePlayer has the GetMap() functions that I need. So, here is what I have done so far: ThreeDCubePlayer* cubePlayer = &((ThreeDCubePlayer &)m_ppDisplayableObjects[0]); char mapEntry = GetMapEntry((int)*(cubePlayer->GetMapX()), (int)*(cubePlayer->GetMapY())); This is the part of ThreeDCubeGame.cpp (the function which controls the map and keyboard input). The problem I've had is that both of these lines give an 'illegal indirection' error at compilation. I thought this error is when I try to dereference something that isn't a pointer, and I'm sure cubePlayer looks like a pointer... Does anyone have an idea as to what I should do?
Use one of the type safe casts, e.g. dynamic_cast instead of the C-style cast. If m_ppDisplayableObjects is a DisplayableObject**, then it would look something like this: ThreeDCubePlayer* cubePlayer = dynamic_cast<ThreeDCubePlayer*>(m_ppDisplayableObjects[0]); if (cubePlayer != NULL) { char mapEntry = GetMapEntry(cubePlayer->GetMapX(), cubePlayer->GetMapY()); } else // Not a ThreeDCubePlayer* ...
1,852,624
3,356,692
Play RTP video stream using Qt?
I want to create a Qt widget that can play incoming RTP streams where the video is encoded as H264 and contains no audio. My basic plan for implementation is this: Create a Phonon MediaSource object (Stream type). Connect it with a QIODevice subclass that provides the data Obtain the video data using either: The JRTPLIB client library The GStreamer gstrtpbin plugin. This plugin takes care depayloading the packages and decoding the video. Maybe this improves the chances that Phonon will recognize the data. My environment: Ubuntu 9.10 Qt 4.6 My questions: Is my approach a good one? Perhaps I'm overlooking a more obvious or simple solution? I'm currently experiencing this issue: when trying to play the video stream the state of the MediaObject turns to ErrorState with errorType FatalError. Can anyone tell me what I'm doing wrong? Edit One solution I found is using libVLC in combination with Qt, which I learned about in this thread. Here's a code sample for the interested. I'm still looking for a Phonon-based solution. Ideally I would only need to provide an SDP file and job is done.
I was able to get it to work using the libVLC solution. I can't garantuee that this is the best solution though as I simply stopped looking after that. Here's a link to the libVLC sample.
1,852,652
1,852,702
How can I #include a file whose name is built up from a macro?
On a cross-platform project, I want to #include a header file whose name contains the name of the platform. I have a #define macro for the platform. So for example, for #define PLATFORM win32 I want #include "engine\win32\devices_win32.h" while for #define PLATFORM linux I want #include "engine\linux\devices_linux.h" I'm going with Richard Pennington's answer, minus one line of code - it works for me! #define PLATFORM Linux #define xstr(x) #x #define str(x) xstr(x) #define sub(x) x #include str(sub(engine/PLATFORM/devices_)PLATFORM.h)
#define PLATFORM Linux #define xstr(x) #x #define str(x) xstr(x) #define sub(x) x #define FILE str(sub(engine/PLATFORM/devices_)PLATFORM.h) #include FILE I'm not sure I'd use it, though. ;-) I had to use Linux rather than linux because linux is defined as 1 in my compiler.
1,852,655
1,852,700
How to create an SDL pop up menu?
I've seached around how to create a pop up menu in a SDL window application using c++ ? I haven't found any clues ! I would like to have something that looks like this : http://www.youtube.com/watch?v=Mc_CE9OiHvA I've tried to use glutMenu, but it doesn't work ... Thanks
SDL is a low-level graphics library. I don't remember seeing anything like menus, buttons, or other GUI controls in it last time I used it. It's possible that one of the many add-on libraries has menuing functions. Generally, you're expected to build such things yourself from primitives SDL provides. One add-on library you might want to get is SDL_ttf, for drawing text using TrueType fonts. That and a few lines and mouse handers, et voilà, you have a menu.
1,852,744
1,852,779
Where do data files go so the Microsoft Visual C++ 2008 debugger can find them?
I am writing code that opens an istream object on a file specified by the user. I want to be able to run the program in the debugger and just type the filename (eg data.txt) at the prompt, not the whole path. I haven't worked out how to do this inside the IDE so I have been saving my .txt file to the debug folder and running the .exe file, but that means I can't step through the program. How do I make it work inside the IDE instead? Thanks.
you can set the working path of the executable (project properties->Debugging->Working Directory), which leads the debugger to start the executable with that path as working directory. This has the advantage that if you set the same path for all your configurations (Debug/Release/...), you only need 1 data.txt on your entire system, which is especially nice if you want to change data.txt or it's name.
1,852,752
1,852,765
Appending an int to a wchar_t*? ..unresolved, lack of concrete example
I am building a string of int values, stored in a wchar_t*. If I have an integer, how can I append it onto the end of a wchar_t*? Windows only solutions are fine for this and I'd rather not include boost :)
Use a wide version of stringstream and the '<<' operator. The correct operator to perform the conversion for you should be defined. If I am missing some subtlety here you could depend on boost and use this. I'm still a fan of secure versions of sprintf and so is Herb Sutter :D.
1,852,801
1,852,820
How do I modify the internal buffer of std::cin
I am writing a software that grabs a password using std::cin However unlikely, i am trying to avoid the possibility that the password get paged to the disk from memory so I want to modify the buffer of std::cin to overwrite the password as soon as I'm done with it. right now i have this: std::cin.clear(); std::stringstream ss; ss << "0000000000000000000000000000000000000000000000"; std::cin.rdbuf(ss.rdbuf()); std::cin.clear(); but I'm pretty sure this is bad since it doesn't take into account the current size of the cin buffer. How do i properly overwrite the contents of the buffer? thanks for any help!
You can use gptr() and egptr() to get the beginning and end of the buffer. Edit: As Charles Bailey pointed out, these are protected. My assumption is that if you want a stream buffer that you can clear its contents at a specified time, that you'd be implementing one of your own that derives from one of the standard stream buffer classes, but provides a clear() member (or whatever name you find convenient). Changing the contents of the buffer without the buffer manager knowing about it will generally be a rather bad thing...
1,852,856
1,852,868
Linker error 'unresolved external symbol' : working with templates
I have a template based class [Allotter.h & Allotter.cpp]: template <typename allotType> class Allotter { public: Allotter(); quint32 getAllotment(allotType*); bool removeAllotment(quint32, int auto_destruct = 0); private: QVector<QPair<quint32, allotType*>> indexReg; int init_topIndex; }; and it's usage is shown as [ActiveListener.h & ActiveListener.cpp]: class ActiveListener: public QObject { Q_OBJECT public: ActiveListener(); private slots: void processConnections(); void readFromSocket(int); private: QTcpServer* rootServer; QSignalMapper* signalGate; Allotter<QTcpSocket> TcpAllotter; }; I am not showing the complete definitions, since it doesn't really matter. The problem is when I compile, all files compile properly. The files are in a VC++ project. Earlier when I did not use a template-based approach for Allotter, everything was compiling and linking fine. But now, I get this error: 1>ActiveListener.obj : error LNK2019: unresolved external symbol "public: __thiscall Allotter<class QTcpSocket>::Allotter<class QTcpSocket>(void)" (??0?$Allotter@VQTcpSocket@@@@QAE@XZ) referenced in function "public: __thiscall ActiveListener::ActiveListener(void)" (??0ActiveListener@@QAE@XZ) 1>ActiveListener.obj : error LNK2019: unresolved external symbol "public: unsigned int __thiscall Allotter<class QTcpSocket>::getAllotment(class QTcpSocket *)" (?getAllotment@?$Allotter@VQTcpSocket@@@@QAEIPAVQTcpSocket@@@Z) referenced in function "private: void __thiscall ActiveListener::processConnections(void)" (?processConnections@ActiveListener@@AAEXXZ) The surprising thing is, that the constructor, ActiveListener::ActiveListener() does not make any reference at all Allotter<QTcpSocket>::Allotter(). The second reference however does exist. But I don't understand why the linker isn't able to resolve this external symbol. The build output just before the errors appear is: 1>Moc'ing ActiveListener.h... 1>Compiling... 1>stdafx.cpp 1>Compiling... 1>ActiveListener.cpp 1>Allotter.cpp 1>moc_ActiveListener.cpp 1>main.cpp 1>Generating Code... 1>Linking... I don't understand if any of this is relevant, mostly because all this used to work perfectly before. It's just that after I use templates a problem is caused. Any help will be appreciated. Thanks a lot.
You cannot split templates into .h and .cpp files - you need to put the complete code for the template in the .h file.
1,852,934
1,852,986
Finding the command line options a process was launched with
I'm trying to find out how to do this, I'm currently using CreateToolHelp32SnapShot to get a list of the running processes and I've got the FilePaths of the executables which are currently running, but I need to be able to find out what command line options were used to start the process. I know its possible since you can see it on Process Explorer, I tried finding the source code of the old Process Explorer but had no luck :(
check if NtQueryInformationProcess and ReadProcessMemory win API calls will do what you need. There is no simple example for that so check the source code here: Get Process Info with NtQueryInformationProcess another way for getting this data is throgh WMI, smth like this: SELECT CommandLine FROM Win32_Process WHERE ProcessId = ??? more info here: Win32_Process Class
1,853,062
1,854,104
c++: Operator overloading and error handling
I am currently starting to look into operator overloading in c++ for a simple 2D vertex class where the position should be available with the [] operator. That generally works, but I dont really know how to deal with errors for instance if the operator is out of bounds (in the case of a 2D vertex class which only has x and y values, it is out of bounds if it is bigger than one) What is the common way to handle errors in cases like that? Thanks
Error handling is a tricky beast in the best of times. It pretty much boils down to how big a deal the error is, and what if anything is expected to happen with it when it occurs. There are four basic paths you can follow: Throw an exception The sledgehammer of error handling. A great tool, definitely want to use it if you need it, but if you're not careful you'll end up smashing yourself in the foot. Essentially skips everything between the throw and the catch, leaving nothing but death and destruction in it's wake. If it's not caught, it will abort your program. Return a value that indicates failure Leave it to the programmer to check for success and react accordingly. Failure value would depend on type. Pointers can return NULL or 0, STL containers return object.end(), else otherwise unused values can be used (such as -1 or ""). Process the condition gracefully Sometimes, an error isn't really an error, just an inconvenience. If useful results can still be provided, a mistake can easily be swept under the carpet without hurting anyone. For example, an out of range error can just return the last variable in an array, without needing to resort to any of that messy exception stuff. So long as it's predictable and defined, the programmer can make of it what they wish. Undefined behaviour Hey, programmers shouldn't be giving you bad input in the first place. Let them suffer. In general, I would resort to option one only for stuff that's program-breaking, for things that I don't really expect to recover from without concerted effort. Otherwise, using exceptions as a form of flow control is little better than going back to the days of goto. Option two is probably the most common for non-program-breaking errors, but it's effectiveness really depends on the types of return you're dealing with. It is advantageous since it lets the programmer control the flow locally by detecting failures and recovering themselves. When dealing with overloading operators, it is of limited use, but I figured I'd throw it in for the sake of completeness. Option three is very circumstance-specific. Many errors can't be handled in such a way, and even the ones that can can lead to unintuitive results. Use with caution, and be sure to document thoroughly. Or, don't document it at all, and pretend it's option four. Now, as to the specific example provided, that being an out of range error on an overloaded operator[], I would personally go for option four. Not because I particularly enjoy watching other programmers suffer when they deal with my code (I do, incidentally, but that's tangential to the discussion), but because it's expected. Most cases where a programmer would be using operator[], they expect to handle their own bounds checking and don't rely on the type or class to do anything for them. Even in the STL containers, you can see operator[] (no range checking) in parallel with the otherwise redundant object.at() (which does range checking). Reflecting the expected behaviour with your own overloaded operators tends to make for more intuitive code.
1,853,082
1,853,680
search a Binary search tree
I am trying to find a name within a key. I think it is retrieving it fine. however, its coming up as not found. maybe my code is wrong somewhere? if (database.retrieve(name, aData)) // both contain the match in main() static void retrieveItem(char *name, data& aData) { cout << ">>> retrieve " << name << endl << endl; if (database.retrieve(name, aData)) // name and aData both contain the match cout << aData << endl; else cout << "not found\n"; cout << endl; } static void removeItem(char *name) { cout << ">>> remove " << name << endl << endl; if (database.remove(name)) cout << name << " removed\n"; else cout << name << " not found\n"; cout << endl; } int main() { #ifdef _WIN32 // request memory leak report in Output Window after main returns _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif data aData; << "Database Of Great Computer Scientists\n\n"; database.insert(data("Ralston, Anthony")); database.insert(data("Liang, Li")); database.insert(data("Jones, Doug")); database.insert(data("Goble, Colin")); database.insert(data("Knuth, Donald")); database.insert(data("Kay, Alan")); database.insert(data("Von Neumann, John")); database.insert(data("Trigoboff, Michael")); database.insert(data("Turing, Alan")); displayDatabase(true); retrieveItem("Trigoboff, Michael", aData); retrieveItem("Kaye, Danny", aData); removeItem("Ralston, Anthony"); displayDatabase(true); retrieve function... bool BST::retrieve(const char *key, data &aData, int parent) const { for(int index=0; index < maxsize+1; index++) { if (!items[index].empty) { if ( items[index].instanceData == key ) { aData.setName(key); return true; // doesn't return right away } } } } and defined in data.cpp bool operator== (const data& d1, const data& d2) { return strcmp(d1.getName(), d2.getName()) == 0; } so this bit of code inside main() is where it says not found when i think it should be working correctly. both name and aData contain the right name that was found.. static void retrieveItem(char *name, data& aData) { cout << ">>> retrieve " << name << endl << endl; if (database.retrieve(name, aData)) // name and aData both contain the match cout << aData << endl; else cout << "not found\n"; cout << endl; }
You should be using the BST to navigate through the tree - not looping over each item in your array, like others have said. Try something like: bool retrieve(key, aData) retrieve(key, aData, parent) if (key == aData) return true else return false bool retrieve(key, aData, parent) if (key == items[parent].name) aData.setName(key) else if (key < items[parent].name) retrieve(key, aData, 2*parent+1) else retrieve(key, aData, 2*parent+2) That should work well! :)
1,853,121
1,853,158
Should a function's comment include descriptions of work done by functions it calls?
Let's say I have a function called DisplayWhiskers() which puts some slashes and backslashes on the screen to represent an animal's whiskers like this: /// \\\. I might write a comment for this function along the lines of // Represents an animal's whiskers by displaying three // slashes followed by a space and three backslashes But if I then add functions DisplayKitten() and DisplaySealion() which as part of their work call DisplayWhiskers(), how much detail about the displaying of whiskers should go in the comments for these other functions? On one hand, it seems that I should be able to look at the comments for DisplayKitten() and understand everything I need to about what it's going to do, including exactly how it will display the whiskers. I shouldn't have to go elsewhere to read the comments for DisplayWhiskers() to find this out. On the other hand, if the comments for DisplayKitten() explicitly refer to three slashes followed by three backslashes, this seems to go against the spirit of encapsulation and could become erroneous if DisplayWhiskers() is later changed. What is considered best practice? EDIT: Several answers have suggested that the solution is to read the code. I understand the principle of good code being its own best comment, but for this question I didn't mean to refer to in-code comments, but to the comments in header files that accompany the function prototypes. Let's assume the actual code is pre-compiled and not accessible to the client who wants to use or call it.
Your functions should ideally do one thing only, whatever a "thing" may be and at what level of granularity. Similarly, they should be described at the appropriate level of granularity. If you're printing out an ASCII kitten, you can leave that as the description for DisplayKitten(). You don't have to describe every last thing it does. Think about it. If every function described every last thing it did, your main function would have to describe every individual thing anything in the program would do, and that's way overkill. Moreover, most of that comment would be distributed among the called functions, and so on, so the program would wind up as mostly ridiculously detailed comments. So, leave the comments to what the function does in general, and as long as your function names are sufficiently descriptive (and yours are) cut those to a minimum. If you or your users need more detail, they can examine the code.
1,853,148
1,853,238
Disable Exceptions in BOOST?
I want to use boost::asio but I don't want boost to throw exceptions, because in my environment exceptions must not be raised. I've encountered BOOST_NO_EXCEPTIONS but the documentation says that callers of throw_exception can assume that this function never returns. But how can a user supplied function not return? What replacement function would I need to insert here? Do I have to terminate the process in case boost code wants to throw an exception?
Either you terminate the process or you goto a something like a global error handler using longjmp which you've previously defined with setjmp.
1,853,358
1,857,314
Use a regular iterator to iterate backwards, or struggle with reverse_iterator?
I recently learned about the right way to work with reverse iterators in C++ (specifically when you need to erase one). (See this question and this one.) This is how you're supposed to do it: typedef std::vector<int> IV; for (IV::reverse_iterator rit = iv.rbegin(), rend = iv.rend(); rit != rend; ++rit) { // Use 'rit' if a reverse_iterator is good enough, e.g., *rit += 10; // Use (rit + 1).base() if you need a regular iterator e.g., iv.erase((rit + 1).base()); } But I think thought this is much better (Don't do this, not standards compliant, as MooingDuck points out): for (IV::iterator it = iv.end(), begin = iv.begin(); it-- != begin; ) { // Use 'it' for anything you want *it += 10; iv.erase(it); } Cons: You tell me. What's wrong with it? It's not standards compliant, as MooingDuck points out. That pretty much overrules any of the possible advantages below. Pros: Uses a familiar idiom for reverse for-loops Don't have to remember (or explain) the +1 Less typing Works for std::list too: it = il.erase(it); If you erase an element, you don't have to adjust the iterator If you erase, you don't have to recompute the begin iterator
The reason for reverse iterators is that the standard algorithms do not know how to iterate over a collection backwards. For example: #include <string> #include <algorithm> std::wstring foo(L"This is a test, with two letter a's involved."); std::find(foo.begin(), foo.end(), L'a'); // Returns an iterator pointing // to the first a character. std::find(foo.rbegin(), foo.rend(), L'a').base()-1; //Returns an iterator // pointing to the last A. std::find(foo.end(), foo.begin(), L'a'); //WRONG!! (Buffer overrun) Use whichever iterator results in clearer code.
1,853,584
1,853,795
Using AlphaBlend() and FillRect()
So, I'm using AlphaBlend() to copy a rectangle from one HBITMAP to another. It works, but there is a problem. Whenever I use the FillRect() function, the alpha values in the HBITMAP get slammed out to 0. Everytime. So I have to GetDIBits(), reset the alpha back to 255, and then SetDIBits(), after every call to the Win32 api functions like FillRect(). So, is there a way to create an HBRUSH or otherwise tell FillRect() not to touch the alpha channel values in the HBITMAP it is going to be drawing to?
With the exception of AlphaBlend... BitBlt is the only other GDI function that will preserve the alpha channel in any way. Your options basically therefore are: Switch to using DIBSections. This will not solve the basic problem of GDI apis overwiting the alpha channel, but as a DIBSection you can avoid the costly DDB -> DIB -> DDB transformation needed to patch up the alpha channel. DIBSections give you access to both an HBITMAP and a memory section where the bitmaps bits are stored. Use an alpha aware painting API like GdiPlus instead of GDI.
1,853,619
1,853,638
Strange characters appear when using strcat function in C++
I am a newbie to C++ and learning from the MSDN C++ Beginner's Guide. While trying the strcat function it works but I get three strange characters at the beginning. Here is my code #include <iostream> #include <cstdio> #include <cstring> using namespace std; int main() { char first_name[40],last_name[40],full_name[80],space[1]; space[0] = ' '; cout << "Enter your first name: "; gets(first_name); cout << "Enter your last name: "; gets(last_name); strcat(full_name,first_name); strcat(full_name,space); strcat(full_name,last_name); cout << "Your name is: " << full_name; return 0; } And here is the output Enter your first name: Taher Enter your last name: Abouzeid Your name is: Y}@Taher Abouzeid I wonder why Y}@ appear before my name ?
The array that you are creating is full of random data. C++ will allocate the space for the data but does not initialize the array with known data. The strcat will attach the data to the end of the string (the first '\0') as the array of characters has not been initialized (and is full of random data) this will not be the first character. This could be corrected by replacing char first_name[40],last_name[40],full_name[80],space[1]; with char first_name[40] = {0}; char last_name[40] = {0}; char full_name[80] = {0}; char space[2] = {0}; the = {0} will set the first element to '\0' which is the string terminator symbol, and c++ will automatically fill all non specified elements with '\0' (provided that at least one element is specified).
1,853,658
1,853,666
binary '=': no operator found which takes a right-hand operand of type "Button *"
I've got a Menu class which is a singleton. It is now going to have three Button objects on it, m_Load, m_Save, m_New. I am calling their constructors in an Init() method like so: void Menu::Init() { Menu::m_Load = new Button(L"../Data/png/load.png"); Menu::m_Save = new Button(L"../Data/png/save.png"); Menu::m_New = new Button(L"../Data/png/new.png"); } And they are defined in the Menu.h file as class Menu : public Singleton<Menu> { friend class Singleton<Menu>; //snip private: Menu(); Button m_Load; Button m_Save; Button m_New; }; That Init method is giving the compiler error described in the title. How come?
You're trying to assign a pointer to a Button to a Button. Declare your button members as pointers. Button *m_Load;
1,853,788
1,855,127
Design choice with a container class that several classes use
I have a class that wraps around a list called ExplosionGroup (previously called AllExplosions for reasons I'll explain) which is a list of 'Explosion's (another class). My original design choice, and what ran for awhile, was to have an ExplosionGroup in the 'Level' class that runs all the levels. Any classes (like ships or bosses) that had functions that would cause them to explode would have this ExplosionGroup passed to those functions. So basically, the Level's ExplosionGroup was sucking in all of the explosions created (hence it was then called AllExplosions). void Foo::Explode( AllExplosions &explosions ) { ...// Create the explosion explosions.Add( newExplosions ); } Recently I ran into a problem where this solution wouldn't work since I needed to create an explosion outside one of these functions, and just putting the code in those functions would a) not make any sense and b) not work correctly. Thus I came up with the idea to have each of the classes that exploded have their own explosion group. This would allow the classes to deal with explosions however they want, not just in a function where an ExplosionGroup was passed. Then I wrote a TakeExplosions function for ExplosionGroup (which just uses std::list's splice) which took an ExplosionGroup parameter and sucked all of the explosions out of that group. This would be used by Level in unison with an accessor for each classes' ExplosionGroup. void Foo::TakeExplosions( ExplosionGroup &explosions ) { m_Explosions.splice( m_Explosions.end(), explosions ); } I thought this was great, but I've realized that if I use this technique I'll want to use it for all classes that can explode to be consistent. However, there are a few special cases in which I'll need to do this indirectly in order to get the explosions to the Level's explosions. For example, a Boss class holds a BlockWall (a list of blocks), and blocks explode. Thus, the block wall would need to extract explosions from its blocks, the boss would need to extract explosions from the block wall, and the level would need to extract explosions from the Boss (unless I provided an accessor for the Boss' wall, which I have no intention of doing). I really don't want to use a global container for explosions so that all of the classes can just add in explosions as they please and be done with it, so I'm asking for any recommendations or ideas towards this issue. I've also considered ditching handling explosions in the Level class and having each class handling in completely on its own, but that seems like a bad abstraction to me. someBlockWall.ShowExplosions( p_Buffer ); playerShip.ShowExplosions( p_Buffer ); // etc. Seems ugly? P.S. I understand that its hard to answer a question like this without knowing how animations in the game work, etc. I'm also being tempted to use a global container because I'm slightly worried that all of this playing with lists could have performance implications. However, I haven't done any profiling so I'm trying not to even consider it.
I have no answers, just some questions that would help others (and maybe also yourself) to find a good answer. What are the exact steps that have to be performed in order to show an explosion? What are my invariants here? (e.g. are all explosions the same, are the object-specific, dependant on time or position on the level) Which objects are involved in showing an explosion (renderer, clock, explodable object, etc.)? There are many possible solutions, but it is hard to choose without knowing all the forces involved.
1,853,906
1,854,158
How to implement class composition in C++?
If I understand correctly we have at least two different ways of implementing composition. (The case of implementation with smart pointers is excluded for simplicity. I almost don't use STL and have no desire to learn it.) Let's have a look at Wikipedia example: class Car { private: Carburetor* itsCarb; public: Car() {itsCarb=new Carburetor();} virtual ~Car() {delete itsCarb;} }; So, it's one way - we have a pointer to object as private member. One can rewrite it to look like this: class Car { private: Carburetor itsCarb; }; In that case we have an object itself as private member. (By the way, am I right to call this entity an object from the terminology point of view?) In the second case it is not obligatory to implicitly call default constructor (if one need to call non-default constructor it's possible to do it in initializer list) and destructor. But it's not a big problem... And of course in some aspects these two cases differ more appreciably. For example it's forbidden to call non-const methods of Carburetor instance from const methods of Car class in the second case... Are there any "rules" to decide which one to use? Am I missing something?
In that case we have an object itself as private member. (By the way, calling this entity as object am I write from the terminology point of view?) Yes you can say "an object" or "an instance" of the class. You can also talk about including the data member "by value" instead of "by pointer" (because "by pointer" and "by value" is the normal way to talk about passing parameters, therefore I expect people would understand those terms being applied to data members). Is there any "rules" to decide which one to use? Am I missed something? If the instance is shared by more than one container, then each container should include it by pointer instead of value; for example if an Employee has a Boss instance, include the Boss by pointer if several Employee instances share the same Boss. If the lifetime of the data member isn't the same as the lifetime of the container, then include it by pointer: for example if the data member is instantiated after the container, or destroyed before the container, or destroyed-and-recreated during the lifetime of the container, or if it ever makes sense for the data member to be null. Another time when you must including by pointer (or by reference) instead of by value is when the type of the data member is an abstract base class. Another reason for including by pointer is that that might allow you to change the implementation of the data member without recompiling the container. For example, if Car and Carburetor were defined in two different DLLs, you might want to include Carburetor by pointer: because then you might be able to change the implementation of the Carburetor by installing a different Carburetor.dll, without rebuilding the Car.dll.
1,854,006
1,872,341
C++ : When do I need a shared memory allocator for std::vector?
First_Layer I have a win32 dll written in VC++6 service pack 6. Let's call this dll as FirstLayer. I do not have access to FirstLayer's source code but I need to call it from managed code. The problem is that FirstLayer makes heavy use of std::vector and std::string as function arguments and there is no way of marshaling these types into a C# application directly. Second_Layer The solution that I can think of is to first create another win32 dll written in VC++6 service pack 6. Let's call this dll as "SecondLayer". SecondLayer acts as a wrapper for FirstLayer. This layer contains wrapper classes for std::vector so std::vector is not exposed in all function parameters in this layer. Let's call this wrapper class for std::vector as StdVectorWrapper. This layer does not make use of any new or delete operations to allocate or deallocate memory since this is handled by std::vector internally. Third_Layer I also created a VC++2005 class library as a wrapper for SecondLayer. This wrapper does all the dirty work of converting the unmanaged SecondLayer into managed code. Let's call this layer as "ThirdLayer". Similar to SecondLayer, this layer does not make use of new and delete when dealing with StdVectorWrapper. Fourth_Layer To top it all, I created a C#2005 console application to call ThirdLayer. Let's call this C# console application as "FourthLayer". Call Sequence Summary FourthLayer(C#2005) -> ThirdLayer(VC++2005) -> SecondLayer(VC++6) -> FirstLayer(VC++6) The Problem I noticed that the "System.AccessViolationException: Attempted to read or write protected memory" exception is being thrown which I suspect to be due to SecondLayer's internal std::vector allocating memory which is illegal for ThirdLayer to access. This is confirmed I think because when I recompile FirstLayer (simulated) and SecondLayer in VC++2005, the problem disappears completely. However, recompiling the production version of FirstLayer is not possible as I do not have the source code. I have heard that in order to get rid of this problem, I need to write a shared memory allocator in C++ for SecondLayer's std::vector which is found in the StdVectorWrapper class. I do not fully understand why I need a shared memory allocator and how it works? Any idea? Is there any readily available source code for this on the internet that I can just compile and use together with my code in SecondLayer? Note that I am unable to use the boost library for this.
I have found a solution for the problem. Basically, the StdVectorWrapper class which I wrote do not implement deep copy. So all I need to do is to add the following to the StdVectorWrapper class to implement deep copy. Copy Constructor Assignment Operator Deconstructor Edit: Alternative Solution An even better solution would be to use clone_ptr for all the elements contained in std::vector as well as for std::vector itself. This eliminates the need for the copy constructor, assignment operator and deconstructor.
1,854,113
1,854,138
ostringstream problem with int in c++
I would expect the following code to output hello5. Instead, it only outputs hello. It seems to be a problem with trying to output an int to the ostringstream. When I output the same directly to cout I receive the expected input. Using XCode 3.2 on Snow Leopard. Thanks! #include <iostream> #include <string> #include <sstream> using namespace std; int main(){ int myint = 5; string mystr = "hello"; string finalstr; ostringstream oss; oss << mystr << myint; finalstr = oss.str(); cout << finalstr; return 0; } EDIT: See the answer I posted below. This seems to be created by a problem in the Active Configuration 'Debug' in XCode 3.2 on Snow Leopard
Changing the Active Configuration in XCode from 'Debug' to 'Release' works as a workaround.
1,854,115
1,854,163
boost.asio tcp sockets, Will asynchronous operations be ordered?
If am am calling boost::asio::async_write/async_read directly after each other, will the data be ordered? Or do I need to wait on the callback before I am calling write/read again? Thanks in advance!
The data is not guaranteed to be ordered and if you are using those functions you should wait for the callback before writing again. (Discussion in terms of async_write, also applies to async_read) Because async_write is implemented in terms of multiple calls to the underlying stream's async_write_some function, those calls are not atomic. Each call attempts to write data to the stream and has an internal callback to deal with partial operations, in effect waiting on completion as you might code yourself. So you could easily end up with mixed data if you don't wait for completion. You also need to consider threads. If you call async_x on a stream multiple times you could end up with concurrent operations on the same underlying stream in different threads, leading to undefined behaviour.
1,854,164
1,957,704
How to use boost::function_types::parameter_types with ClassTypeTransform
I have been toying with an example hpp provided in the boost library and I am trying to figure out how to use this parameter_types function correctly. From the boost doc, parameter_types needs a ClassTypeTransform in order to parse class member function signatures. I want to parse member function signatures, but I cannot find any doc on what this lamda expression is supposed to do. ClassTransform MPL - Lambda Expression to transform the class type if F is a member function pointer Which is from the page itself, I cannot find any sample code actually using it and I was hoping someone know how to use it to parse member function signatures.
ClassTransform is simply used to modify the first argument type in case parameter_types<> is applied to a member function pointer type. The default is add_reference<_>, so for instance: parameter_types<void(X::*)(int)>::type -> SomeSequence<void, X&, int> parameter_types<void(X::*)(int), mpl::identity<_> >::type -> SomeSequence<void, X, int> parameter_types<void(X::*)(int), add_pointer<_> >::type -> SomeSequence<void, X*, int>
1,854,241
1,854,250
How to set a default parameter for a vector <string> for use in a default constructor within a class?
For example, a class named Table, with its constructor being: Table(string name="", vector <string> mods); How would I initialize the vector to be empty? Edit: Forgot to mention this was C++.
Table(string name="", vector <string> mods); if you want vector to be empty inside constructor then mods.clear(); or mods.swap(vector<string>()); In case you want as a default parameter: Table(string name="", vector<string> mods = vector<string>()); Like any other default parameter.
1,854,251
1,855,146
Why doesn't this compile?
When I try to declare iss using the first form, g++ gives me "error: no match for 'operator>>' in 'iss >> s'". But don't the two different declarations do the same thing? #include <iostream> #include <sstream> #include <string> int main() { const char *buf = "hello world"; std::string ss(buf); //std::istringstream iss(std::string(buf)); // this doesn't work std::istringstream iss(ss); // but this does std::string s; iss >> s; }
This is known as the "most vexing parse" of C++: what looks like an instance declaration to you actually looks like a function declaration to the compiler. std::string name(); //function declaration std::string name; //object declaration with default constructor std::stringstream ss(std::string(buf)); //function declaration std::stringstream ss(std::string buf); //another function declaration std::stringstream ss(std::string); //also a function declaration std::stringstream ss(std::string()); //ditto, argument names are optional std::stringstream ss((std::string(buf))); //object declaration Note the extra brackets in the last example. These brackets wouldn't be legal in a function declaration. The first example with the default constructor is well-known. What adds unclarity in the second case is that brackets around parameter names in C++ are legal but optional. For example, you can define a function like this: void foo(int (bar)) {} Basically you'll run into this every time when all arguments to a constructor are temporaries from constructor invocations that take 0 or 1 arguments, and the quick solution is to put extra brackets around one of the arguments.
1,854,290
1,854,305
Combine native DLL and assembly into a single DLL
I am currently programming in C++ and C#. Using native C++ for the numerical computing part. Originally I intended to use C++/CLI to make a wrapper to the native C++ classes, but I found it would result in a 2 to 4 times slowdown. So I decided to compile my native C++ to a DLL and call in .NET/C# via P/Invoke. I will do data preprocessing in C# and number crunching in the native DLL. The problem is that when I deliver my work for others to use, I'd like it to be a single DLL. Is this possible? BTW, I have all source code to the native C++.
You can mix languages in the same assembly in .NET but not naturally. I would avoid this unless absolutely necessary. See: http://www.hanselman.com/blog/MixingLanguagesInASingleAssemblyInVisualStudioSeamlesslyWithILMergeAndMSBuild.aspx I keep assemblies from different languages separate.
1,854,304
1,854,343
C++ : How to include boost library header in VC++6?
I used this guide to rebuild the boost library in VC++6 under windows XP. But is having problems trying to include the header files. By default, the boost library makes use of point 1 as follows to declare the header files. But if I used point 1, I get "fatal error C1083: Cannot open include file...". I tried using point 2 to declare and it seem to work but all the header files referenced internally by point 2 will have to be changed. This lead to a cascade of header declaration to be changed which is not realistic. Did I miss something? What is the correct way of including the header file without errors? 1) #include <boost/interprocess/managed_shared_memory.hpp> 2) #include "..\boost\interprocess\managed_shared_memory.hpp"
Did you add the boost include path to your project? If you try to compile your program from Visual Studio you can add extra include paths in the global options (menus: Tools -> Options -> Directories -> Show directories for: Include files). If you will also make use of the compiled boost libraries (e.g. for boost::filesystem), you should add the library path to your setup too.
1,854,323
1,868,240
Recommendation for C++ wrapper for cross platform in-process dynamic library bindings (i.e. a lightweight, high performance COM or CORBA)
We're developing an application that will have a plug-in "architecture" to allow consumers of the app to provide their own proprietary algorithms. (We will basically have a set of parsers and allow third parties to provide their own as well) The domain space requires very high performance, so out-of-process bindings are not going to work and we'd rather leave the heavyweight things like CORBA and COM alone. Basically we're looking for a simple cross-platform wrapper around: load library from a relative path provide a mapping of the particular dll/.so to some configuration/name do some initialization and query the library to ensure it provides the necessary functionality I think this is really just a wrapping around loadlibrary() and the method calls exported. We can write this ourselves, but we'd rather use existing code as we have enough on our plate. Again, throughput and performance are very very important. Similar questions are: Cross-platform alternative to COM - this one is close, but we want in-process only - no need for out of process and our needs are a little "lighter weight". C++ Cross Platform Dynamic Libraries; Linux and Windows This is for unmanaged C++ - we cannot use .NET EDIT - what we found We found that Poco works great for our needs. As a bonus This page is a much appreciated comment on the state of C++ development and the language direction... It was a simple cross platform wrapping that we needed that Poco provides. Really there is not much to it, but still saves us time and testing. No additional overhead during run time.
I think this might also work: http://pocoproject.org/docs/Poco.SharedLibrary.html
1,854,335
1,854,337
How to create a Java class, similar to a C++ template class?
How do I write an equivalent of this in Java? // C++ Code template< class T > class SomeClass { private: T data; public: SomeClass() { } void set(T data_) { data = data_; } };
class SomeClass<T> { private T data; public SomeClass() { } public void set(T data_) { data = data_; } } You probably also want to make the class itself public, but that's pretty much the literal translation into Java. There are other differences between C++ templates and Java generics, but none of those are issues for your example.
1,854,439
1,854,460
Method not being called in switch statement
Edit: Works perfectly in debugger now, but block doesn't rotate at all when run normally.. I'm having a problem that I've run through the debugger a ton and have narrowed it down to this. I've got a block on screen that comes down in the middle and rotates. The image of the block obviously changes depends on the rotation, and this is done in a switch statement. switch ( m_CurrentRotation ) { case BossRotation_ZeroDegrees: { ApplySurface( m_BossRect.topLeftX, m_BossRect.topLeftY, BossFiveImage::p_ZeroDegrees, p_Buffer ); break; } case BossRotation_NinetyDegrees: { ApplySurface( m_BossRect.topLeftX, m_BossRect.topLeftY, BossFiveImage::p_NinetyDegrees, p_Buffer ); break; } case BossRotation_OneEightyDegrees: { ApplySurface( m_BossRect.topLeftX, m_BossRect.topLeftY, BossFiveImage::p_OneEightyDegrees, p_Buffer ); break; } case BossRotation_TwoSeventyDegrees: { ApplySurface( m_BossRect.topLeftX, m_BossRect.topLeftY, BossFiveImage::p_TwoSeventyDegrees, p_Buffer ); break; } default: {} } The block enters at zero degrees, and once it gets in the middle it starts rotating. I've found from debugging that in the switch statement, the ApplySurface for the FIRST case isn't being called (when I try to step into it, nothing happens). This causes the block to go "blank" every time it gets to that rotation point. Here are the odd things... 1) If the ApplySurface function isn't being called, then why can you see the block coming down at first (before it starts rotating)? 2) Running the program in the debugger and running it normally show different results. Normally, it just shows the block in its zero degree position the whole time. The debugger is the only time it actually attempts to rotate the block. Are there compiler optimizations going on that are preventing whatever is going horribly wrong in my switch statement from happening?
Your code seems unnecessarily long and repetitive. It should be refactored: image = NULL; switch ( m_CurrentRotation ) { case BossRotation_ZeroDegrees: { image = BossFiveImage::p_ZeroDegrees; break; } case BossRotation_NinetyDegrees: { image = BossFiveImage::p_NinetyDegrees; break; } case BossRotation_OneEightyDegrees: { image = BossFiveImage::p_OneEightyDegrees; break; } case BossRotation_TwoSeventyDegrees: { image = BossFiveImage::p_TwoSeventyDegrees; break; } default: {} } if (image) { ApplySurface( m_BossRect.topLeftX, m_BossRect.topLeftY, image, p_Buffer ); } This simpler code should also be easier to debug. What is the type and the possible values of m_CurrentRotation?
1,854,444
1,854,664
Compiling SDL on OS X with makefile
I'm trying to compile the tetris program I wrote with C++ and SDL on OS X. First I tried doing this: `g++ -o tetris main.cpp `sdl-config --cflags --libs` -framework Cocoa` and got this: Undefined symbols: "Game::startGame()", referenced from: _main in ccQMhbGx.o "Game::Game()", referenced from: _main in ccQMhbGx.o ld: symbol(s) not found collect2: ld returned 1 exit status Here is the main.cpp file: #include <iostream> #include "Game.h" int main(int argc, char* argv[]) { Game *game = new Game(); game->startGame(); return 0; } Game.h is the game class where all of the other classes (Board.h, IO.h, Piece.h, Pieces.h) are included and the main logic of the game is contained. I'd really like to be able to write a makefile for this or find some way to easily distribute it to friends. EDIT: here is the final makefile in case anyone else is having the same problem: CC=g++ CFLAGS=-c -Wall SDLFLAGS=`sdl-config --cflags --libs` -framework Cocoa SOURCES=main.cpp Game.cpp IO.cpp Board.cpp Pieces.cpp Piece.cpp OBJECTS=$(SOURCES:.cpp=.o) EXECUTABLE=tetris all: $(SOURCES) $(EXECUTABLE) $(EXECUTABLE): $(OBJECTS) $(CC) $(OBJECTS) $(SDLFLAGS) -o $@ .cpp.o: $(CC) $(CFLAGS) $< -o $@ clean: rm -rf *.o $(EXECUTABLE)
I think your compile issue is related to the SDL main function. The compile failure is because you're missing references to "Game.o" or whatever the object file resulted out of compiling Game.cpp is called. Try: g++ -o tetris main.cpp Game.o Pieces.o Whateverelse.o `sdl-config --cflags --libs` -framework Cocoa
1,854,499
1,854,509
Is string::compare reliable to determine alphabetical order?
Simply put, if the input is always in the same case (here, lower case), and if the characters are always ASCII, can one use string::compare to determine reliably the alphabetical order of two strings? Thus, with stringA.compare(stringB) if the result is 0, they are the same, if it is negative, stringA comes before stringB alphabetically , and if it is positive, stringA comes after?
According to the docs at cplusplus.com, The member function returns 0 if all the characters in the compared contents compare equal, a negative value if the first character that does not match compares to less in the object than in the comparing string, and a positive value in the opposite case. So it will sort strings in ASCII order, which will be alphabetical for English strings (with no diacritical marks or other extended characters) of the same case.
1,854,575
1,854,591
glBitmap() without GL_COLOR_INDEX
Is it somehow possible to get glBitmap() to draw a GL_RGBA bitmap? glBitmap() is a lot quicker than glDrawPixels(), but perhaps that has to do with that the format is GL_COLOR_INDEX instead of GL_RGBA? I'm running my glDrawPixels() in a display list; is there perhaps some smart way to speed it up?
From the documentation: "A bitmap is a binary image" - Here a "binary image" simply means an image in which every pixel has exactly two possible colors which map to "transparent" and "the current raster color". You can't paint anything else using this function. Some other things you can try to achieve the same effect, possibly with better performance: Drawing a screen-aligned quad with a texture Drawing a textured point sprite using texture coordinate replacement
1,854,711
1,855,269
How to check if a Graph is a Planar Graph or not?
I'm learning about the Planar Graph and coloring in c++. But i don't know install the algorithm to do this work. Someone please help me? Here i have some information for you! This is my code! And it still has a function does not finish. If someone know what is a "Planar Graph", please fix the Planar_Graph function below! :D thanks so much! :x # define MAX 100 int kt[MAX]; int tk=0; int my_array[MAX][MAX]; // Graph FILE *f; int n,m; //m: Edge, n: Vertex int index[MAX]; int ke[MAX]; int Color[MAX] ; //Color Array int colors_max; char filename[MAX]; int input(char filename[MAX]) { int i,j; f = fopen(filename,"r"); if (f== NULL) { printf("\n Error \n"); return 1; } else { printf("File mane: %s \n",filename); printf("Content :\n"); fscanf(f,"%d",&n); fscanf(f,"%d",&m); for(i=0;i<n;i++) { for(j=0;j<n;j++) { fscanf(f,"%d",&my_array[i][j]); printf("%d ",my_array[i][j]); } printf("\n"); } return 0; } } void Default() { for(int i=0;i<colors_max;i++) Color[i]= i; } void Init() { filename[0]=NULL; n = 0; } int Planar_Graph(int my_array[MAX][MAX],int n, int m) // This is my problem { /* for(int i=0;i<n;i++) if(n>=2 && (int)(n+1)*(n-2)/(n-1)>=m) return 1; } else { return 0; } */ } int max() { int max; int count=0; for(int i=0;i<n;i++) { count = 0; for(int j=0;j<n;j++) if (my_array[i][j] > 0) count++ ; if (max < count) max = count; } return max+1; } void Check(int x,int y) // Check around { int i; Default(); for(i=0;i<n;i++) { if (my_array[x][i] != -1) // if edge [x,ke[i]] is color t Color[my_array[x][i]] = -1; // then Color[t] = 0 } for(i=0;i<n;i++) { if (my_array[y][i] != -1) Color[my_array[y][i]] = -1; } } void Coloring() { int t; for(int i=0;i<n;i++) for(int j=0;j<n;j++) if (my_array[i][j] > 0) { Check(i,j) ; for(t=0;t < colors_max;t++) if (Color[t] == t) { my_array[i][j] = t; my_array[j][i] = t; break; } } } void main() { if(input("input.txt")!=1) { Default(); colors_max = max() ; Coloring(); printf("\n Result:\n\n"); Planar_Graph(my_array,n,m); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) if (my_array[i][j]>0) { printf(" %c,%c] coloring %d \n",i + 'A',j + 'A',my_array[i][j]) ; my_array[i][j] = -1; my_array[j][i] = -1; } printf("\n") ; } } } The input file example: 10 18 0 1 0 1 1 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 1 0 1 1 0 0 1 0 1 1 0 1 1 0 1 0 1 0 0 0 1 0 1 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 0 1 0 0 1 0 1 1 0 0 0 0 1 1 0 1 0 1 0 0 0 0 0 0 0 1 1 0
Regarding planarity... The well known e <= 3v - 6 criteria by Euller mentioned here says that if a graph is planar, then that condition must hold. However, not all graphs in which that condition holds are necessarily planar. That is why you actually need a planarity test algorithm. A thing to notice is that planarity testing algorithms are not easy to implement. There's a very old one which is based on subgraphs finding and removal. I can't remember the original authors right now, but the problem with their algorithm is that it has O(n³) complexity. The first planarity test algorithm considered to be efficient - O(n) in the case - is due to Hopcroft and Tarjan. This was already mentioned here in the post by Yin Zhu. You can find the original paper here. This time, the problem with the algorithm was that many people found it too hard to understand and even to implement. So there are papers with the intention of just clarifying points of the original paper. For instance, the Kocay paper. The Hopcraft-Tarjan paper is classic and if you want to try to implement it, the best reference I have is this other paper, which presents the theory together with a C++ implementation. That was written by the people who implemented the algorithm in the LEDA library. Years later after the Hopcroft-Tarjan paper (which was in 1974), others O(n) algorithms were published. I don't know much about them, but some used PC/PQ trees. There is one, however, which I read and found very interesting. It's due to Boyer and Myrvold and it's from 2004. You can find it here. Besides the algorithm itself, of course, a good thing about this paper is that it provides a rigorous historical reference about planarity test algorithms. Very recently, I discovered a another paper from 2008 in which Tarjan is one of the authors. Haven't checked it yet. Well, if you got tired just by reading this post, I assume you don't want to implement your own algorithm. :) In this case, I can recommend some C++ libraries. Boost. GDToolkit. LEDA. OGDF. GTAD - This is my own graph library (which, unfortunately, I haven't been able to work on it lately). There's an implementation of the Hopcroft-Tarjan algorithm, which I wrote based on that paper I mentioned. Since the paper already provides real code, things are a lot easier.
1,855,459
1,855,465
maximum value of int
Is there any code to find the maximum value of integer (accordingly to the compiler) in C/C++ like Integer.MaxValue function in java?
In C++: #include <limits> then use int imin = std::numeric_limits<int>::min(); // minimum value int imax = std::numeric_limits<int>::max(); std::numeric_limits is a template type which can be instantiated with other types: float fmin = std::numeric_limits<float>::min(); // minimum positive value float fmax = std::numeric_limits<float>::max(); In C: #include <limits.h> then use int imin = INT_MIN; // minimum value int imax = INT_MAX; or #include <float.h> float fmin = FLT_MIN; // minimum positive value double dmin = DBL_MIN; // minimum positive value float fmax = FLT_MAX; double dmax = DBL_MAX;
1,855,472
1,855,503
antlr : C++ target with visual studio 2008
the Antlr site is not clear on the subject of compiling a grammar for C++, it says that the tool will generate C code compatible with C++, what dose it mean? will I be able to compile this code with VS 2008 ?
VS 2008 has both C and C++ compiler (and C++ compiler can compile C code, this is what they meant), I don't think you'll have any problems. They say: "C target as of release 3.1 is C++ compatible, compile .c files as C++. C+ classes will be provided as a separate library later in 2008." Meaning it's C++ compatible.
1,855,482
1,855,538
How to properly initialize class value member?
lets say we have this: class Foo { public: Foo(const Bar& b) : m_bar(b) {} private: Bar m_bar; }; Now regarding efficiency C++ FAQ LITE says this: Consider the following constructor that initializes member object "x" using an initialization list: Fred::Fred() : x(whatever) { }. The most common benefit of doing this is improved performance. For example, if the expression whatever is the same type as member variable "x", the result of the whatever expression is constructed directly inside "x" — the compiler does not make a separate copy of the object. Should the constructor better have the parameter as value instead of reference? Since I am using the constructor initialization list, would there be a performance difference? Finally, and most important, would there be a semantic difference? e.g., to the caller of new Foo(Bar()) Thank you -- Edit -- Corrected the parameter declaration as const reference.
I'll break it down into performance and semantic differences, as you requested: Should the constructor better have the parameter as value instead of reference? Unless it is a primitive type or small struct, it should have the parameter passed by const reference. Passing by reference gives you a performance difference: the program does not have to make a copy of the whole object before passing it to the constructor. For small objects, however, the time saved by avoiding the copy may not be offset by the extra level of indirection. Passing by const ensures that you can call the constructor with temporary objects. Thus, to the caller of the constructor, there is no semantic difference as to whether you are calling by value or by const reference. Since I am using the constructor initialization list, would there be a performance difference? If you do not use the initialization list, and the object you are initializing has a default constructor, this is what happens semantically: class Foo { Bar bar; Foo(const &Bar bar_) /* bar(Bar()) is implicitly called here, before the start of the function body */ { /* Note that we cannot do bar(bar_) now as bar has already been constructed. So we might do this instead: */ bar = bar_; // the assignment operator function is called here } }; However, if the compiler is able to see that the default constructor of Bar has no side effects other than to initialize bar, and that this value of bar is overwritten in the body of the constructor, it may choose to elide (remove) this call completely. But we can always make life easier for the compiler and not make that extra call. Note that if the object you want to initialize does not have a default constructor, then you must initialize it in the initialization list. This is another semantic difference.
1,855,628
1,855,644
Network protocol object serialization in C++
I'm writing some C++ code that will have to send data over TCP/IP. I want this code to be portable on Linux/Windows/Osx. Now, as it is the first time I write portable network code, I basically need some simple functions to add to certain objects like: class myclass{ ...member... public: string serialize(){ std::ostringstream out(); out << member1; out << member2; out << member3; return out.str(); } } ... which is all I need for now. Anyway I started reading ostringstream related docs and turns out the binary/text problem. In fact it will convert line breaks to the right sequence of everysystem. Suppose for example that a member is a pointer to const char* foo = "Hello\nMan\n", that will be translated in certain byte sequence on linux, another on windows... and so on. My bytes will go on a packet over the internet, a different OS machine will read them and I think trouble will occurr... Now I read that I might initialize ostringstream with ostringstream(ios::bin)... Will it solve the problem (provided that I will use a de-serialization function that will use a istringstream(ios::bin)??? I'm confused about the whole picture, if you may spend a few clarifying lines that'll be much appreciated. Thanks.
Why do it all manually if there are great libraries like Boost.Serialization that you can build on? From their goals: Data Portability - Streams of bytes created on one platform should be readable on any other. Also of interest for you might be points 4 and 5: Deep pointer save and restore. That is, save and restore of pointers saves and restores the data pointed to. Proper restoration of pointers to shared data.
1,855,704
1,855,756
C++ binary file I/O to/from containers (other than char *) using STL algorithms
I'm attempting a simple test of binary file I/O using the STL copy algorithm to copy data to/from containers and a binary file. See below: 1 #include <iostream> 2 #include <iterator> 3 #include <fstream> 4 #include <vector> 5 #include <algorithm> 6 7 using namespace std; 8 9 typedef std::ostream_iterator<double> oi_t; 10 typedef std::istream_iterator<double> ii_t; 11 12 int main () { 13 14 // generate some data to test 15 std::vector<double> vd; 16 for (int i = 0; i < 20; i++) 17 { 18 double d = rand() / 1000000.0; 19 vd.push_back(d); 20 } 21 22 // perform output to a binary file 23 ofstream output ("temp.bin", ios::binary); 24 copy (vd.begin(), vd.end(), oi_t(output, (char *)NULL)); 25 output.close(); 26 27 // input from the binary file to a container 28 std::vector<double> vi; 29 ifstream input ("temp.bin", ios::binary); 30 ii_t ii(input); 31 copy (ii, ii_t(), back_inserter(vi)); 32 input.close(); 33 34 // output data to screen to verify/compare the results 35 for (int i = 0; i < vd.size(); i++) 36 printf ("%8.4f %8.4f\n", vd[i], vi[i]); 37 38 printf ("vd.size() = %d\tvi.size() = %d\n", vd.size(), vi.size()); 39 return 0; 40 } The resulting output is as follows and has two problems, afaik: 1804.2894 1804.2985 846.9309 0.9312 1681.6928 0.6917 1714.6369 0.6420 1957.7478 0.7542 424.2383 0.2387 719.8854 0.8852 1649.7605 0.7660 596.5166 0.5171 1189.6414 0.6410 1025.2024 0.2135 1350.4900 0.4978 783.3687 0.3691 1102.5201 0.5220 2044.8978 0.9197 1967.5139 0.5114 1365.1805 0.1815 1540.3834 0.3830 304.0892 0.0891 1303.4557 0.4600 vd.size() = 20 vi.size() = 20 1) Every double read from the binary data is missing the information before the decimal place. 2) The data is mangled at the 3rd decimal place (or earlier) and some arbitrary error is being introduced. Please any help would be appreciated. (I would love for someone to point me to a previous post about this, as I've come up short in my search)
For the question 1) You need to specify a separator (for example a space). The non-decimal part was stuck to the decimal part of the previous number. Casting and using NULL is generally wrong in C++. Should have been a hint ;) copy (vd.begin(), vd.end(), oi_t(output, " ")); For the question 2) #include <iomanip> output << setprecision(9);
1,855,725
1,855,750
Assigning a "const char*" to std::string is allowed, but assigning to std::wstring doesn't compile. Why?
I assumed that std::wstring and std::string both provide more or less the same interface. So I tried to enable unicode capabilities for our application # ifdef APP_USE_UNICODE typedef std::wstring AppStringType; # else typedef std::string AppStringType; # endif However that gives me a lot of compile errors when -DAPP_USE_UNICODE is used. It turned out, that the compiler chokes when a const char[] is assigned to std::wstring. EDIT: improved example by removing the usage of literal "hello". #include <string> void myfunc(const char h[]) { string s = h; // compiles OK wstring w = h; // compile Error } Why does it make such a difference? Assigning a const char* to std::string is allowed, but assigning to std::wstring gives compile errors. Shouldn't std::wstring provide the same interface as std::string? At least for such a basic operation as assignment? (environment: gcc-4.4.1 on Ubuntu Karmic 32bit)
The relevant part of the string API is this constructor: basic_string(const charT*); For std::string, charT is char. For std::wstring it's wchar_t. So the reason it doesn't compile is that wstring doesn't have a char* constructor. Why doesn't wstring have a char* constructor? There is no one unique way to convert a string of char to a string of wchar. What's the encoding used with the char string? Is it just 7 bit ASCII? Is it UTF-8? Is it UTF-7? Is it SHIFT-JIS? So I don't think it would entirely make sense for std::wstring to have an automatic conversion from char*, even though you could cover most cases. You can use: w = std::wstring(h, h + sizeof(h) - 1); which will convert each char in turn to wchar (except the NUL terminator), and in this example that's probably what you want. As int3 says though, if that's what you mean it's most likely better to use a wide string literal in the first place.
1,855,773
1,855,981
Avoid slicing of exception types (C++)
I am designing an exception hierarchy in C++ for my library. The "hierarchy" is 4 classes derived from std::runtime_error. I would like to avoid the slicing problem for the exception classes so made the copy constructors protected. But apparently gcc requires to call the copy constructor when throwing instances of them, so complains about the protected copy constructors. Visual C++ 8.0 compiles the same code fine. Are there any portable way to defuse the slicing problem for exception classes? Does the standard say anything about whether an implementation could/should require copy constructor of a class which is to be thrown?
I would steer clear of designing an exception hierarchy distinct to your library. Use the std::exception hierarchy as much as possible and always derive your exceptions from something within that hierarchy. You might want to read the exceptions portion of Marshall Cline's C++ FAQ - read FAQ 17.6, 17.9, 17.10, and 17.12 in particular. As for "forcing users to catch by reference", I don't know of a good way of doing it. The only way that I have come up with in an hour or so of playing (it is Sunday afternoon) is based on polymorphic throwing: class foo_exception { public: explicit foo_exception(std::string msg_): m_msg(msg_) {} virtual ~foo_exception() {} virtual void raise() { throw *this; } virtual std::string const& msg() const { return m_msg; } protected: foo_exception(foo_exception const& other): m_msg(other.m_msg) {} private: std::string m_msg; }; class bar_exception: public foo_exception { public: explicit bar_exception(std::string msg_): foo_exception(msg_), m_error_number(errno) {} virtual void raise() { throw *this; } int error_number() const { return m_error_number; } protected: bar_exception(bar_exception const& other): foo_exception(other), m_error_number(other.m_error_number) {} private: int m_error_number; }; The idea is to make the copy constructor protected and force users to call Class(args).raise() instead of throw Class(args). This lets you throw a polymorphicly bound exception that your users can only catch by reference. Any attempt to catch by value should be greeted with a nice compiler warning. Something like: foo.cpp:59: error: ‘bar_exception::bar_exception(const bar_exception&)’ is protected foo.cpp:103: error: within this context Of course this all comes at a price since you can no longer use throw explicitly or you will be greeted with a similar compiler warning: foo.cpp: In function ‘void h()’: foo.cpp:31: error: ‘foo_exception::foo_exception(const foo_exception&)’ is protected foo.cpp:93: error: within this context foo.cpp:31: error: ‘foo_exception::foo_exception(const foo_exception&)’ is protected foo.cpp:93: error: within this context Overall, I would rely on coding standards and documentation stating the you should always catch by reference. Make sure that your library catches exceptions that it handles by reference and throw fresh objects (e.g., throw Class(constructorArgs) or throw;). I would expect other C++ programmers to have the same knowledge - but add a note to any documentation just to be sure.
1,855,859
1,855,989
Curving from one point to another
I have tiles that are in random spots, and they wind up at x',y' (to make a nice 2d array) by doing : Xt = (((X′-X)/T)*t)+X , Yt = (((Y′-Y)/T)*t)+Y This works well, but it is linear. I'm looking for something curvier. A little bit like a parabola works. Basically instead of getting to X' in a straight line, I'm looking for an algorithm that will curve out and end up at X' and the amount of curvature is base on a variable. Thanks *EDIT I think Bezier curve look to be what I want, but I'm not sure how to implement it. Could someone please explain the quadratic bezier formula. I'm also unsure what the 'E' - like symbol does. I think it relates to a range but I'm not sure, Thanks
You're looking for Bezier Curves, or some other similar parametric curve. These are programatically quite easy to code and have the advantage of being intuitively straightforward to manipulate. The best treatise I know of is in the classic book Mathematical Elements of Computer Graphics, but any textbook on computer graphics will probably include a basic introduction.
1,855,885
1,855,897
How do I get \0 off my string from C++ when read in C#
I'm kind of stuck here. I'm developing a custom Pipleline component for Commerce Server 2009, but that has little to do with my problem. In the setup of the pipe, I give the user a windows form to enter some values for configuration. One of those values is a URL for a SharePoint site. Commerce Server uses C++ components behind all this pipeline stuff, so the entered values are put into an IDictionary and eventually persisted to the DB via the C++ component from Microsoft. When I read the string in during pipeline execution, it is handed to me in an IDictionary object from C++. My C# code sees that URL suffixed with \0\0. I'm not sure where those are coming from, but my code blows up because it's not a valid URI. I am trimming the string before I save it and trimming it when I read it and still can't get rid of those. Any ideas what is causing this and how I can get rid of it? I prefer not to have a hack like substring it, but something that gets at the root cause. Thanks, Corey
Would this help: string sFixedUrl = "hello\0\0".Trim('\0');
1,855,948
1,855,966
instantiated from here error
my compiler is torturing me with this instantiation error which I completely don't understand. i have template class listItem: template <class T> class tListItem{ public: tListItem(T t){tData=t; next=0;} tListItem *next; T data(){return tData;} private: T tData; }; if i try to initialize an object of it with non-primitive data type like e.g: sPacket zomg("whaever",1); tListItem<sPacket> z(zomg); my compiler always throws this error.. the error isnť thrown with primitive types. output from compiler is: ../linkedList/tListItem.h: In constructor ‘tListItem<T>::tListItem(T) [with T = sPacket]’: recvBufTest.cpp:15: instantiated from here ../linkedList/tListItem.h:4: error: no matching function for call to ‘sPacket::sPacket()’ ../packetz/sPacket.h:2: note: candidates are: sPacket::sPacket(const char*, int) ../packetz/sPacket.h:1: note: sPacket::sPacket(const sPacket&) i wouldn't bother you but i don't want to spend 2 hours with something stupid..... so thx for all your replies
As it stands, your code needs a default constructor for the type T. Change your template constructor to: tListItem(T t) : tData(t), next(0) {} The difference being that your version default constructs an instance of type T and then assigns to it. My version uses an initialisation list to copy construct the instance, so no default constructor is required.
1,855,951
1,856,401
Sharing object by reference or pointer
Say I have an object of type A having Initialize() method. The method receives object B, which are kept as the object data member. B object is shared between several objects, thus A should contain the originally received B object and not its copy. class A { public: bool Initialize(B?? b); private: B?? m_B; } Object B must present. Thus I think to pass it by reference, instead of passing by pointer and failing Initialize() in case B is NULL. The only alrernative for m_B is to be of type of pointer B (it cann't be reference of B, since the intializating of B is not done in A c-tor). Thus Initialize should look like: bool A::Initialize(B& b) { m_B = &b; .... } Is this aproach is ok? UPD: The code is not new and I'm just trying to "fix" some problems. Actually I'm not talking about some concrete A and b classes, rather about a way the problem is approached in my code base. The code widely passes pointer to B and verifying it in Initialize() if it's NULL. Passing B to A's c-tor is not always a good option too. There're also other parametrs passed to A, which are not exists at A creation time. Therefore I woudln't prefer to pass part of parameters to A c-tor and the rest to A::Initialize(). shared_ptr can be "NULL" too, so passing it to A::Initialize() not different from passing just pointer to B, in that aspect that signature of Initialize() dosn't declare if B is mandatory or not. In my case it is and I want to express it by passing reference to B. Our code currently is not using boost at all. So, although shared_ptr better solution than just passing raw pointer, can solution proposed by me be considered as bad, but still solution.
I'd stay with pointer. Reference here just sends wrong message. You don't use references to object in situations when you plan to take pointer to object and keep or share it, etc. Main reason for references in C++ is allowing things like operator overloading and copy constructors to work for user defined types. Without them it would be difficult to provide this functionality with syntax that doesn't differ from built in types. But in this situation you're not trying to mimic built in type. You are operating on object which is normally used through pointer and even shared through several different pointers. So be explicit about that. As for b being NULL, by all means use assert(b) (or similar construct) to enforce contract and stop invalid program. (I wouldn't throw exception though. Even if you forget about problems with exceptions in C++, are you planning to ever catch and handle such exception in your code?) I would also add such assertions to all code that uses m_B in case someone forgot to call A::Initialize(). Using reference to ensure pointer is not null, might misfire. In most implementation you can make reference from NULL or dangling pointer without raising any error. Your application will fail only if you try to use this reference. So if someone accidentally passes you B *pb which equals NULL, you could call pa->Initialize(*pb) and nothing happens. Except that pa->m_B is now NULL. Whether to use something like boost::shared_ptr is up to you and your strategy of memory management. It's a completely unrelated issue.
1,856,013
1,856,034
What is the C++ equivalent of C# Collection<T> and how do you use it?
I have the need to store a list/collection/array of dynamically created objects of a certain base type in C++ (and I'm new to C++). In C# I'd use a generic collection, what do I use in C++? I know I can use an array: SomeBase* _anArrayOfBase = new SomeBase[max]; But I don't get anything 'for free' with this - in other words, I can't iterate over it, it doesn't expand automatically and so on. So what other options are there? Thanks
There is std::vector which is a wrapper around an array, but it can expand and will do automatically. However, it is a very expensive operation, so if you are going to do a lot of insertion or removal operations, don't use a vector. (You can use the reserve function, to reserve a certain amount of space) std::list is a linked list, which has far faster insertion and removal times, but iteration is slower as the values are not stored in contiguous memory, which means that address calculation is far more complex and you can't take advantage of the processors cache when iterating over the list. The major upside compared to the vector or deque is that elements can be added or removed from anywhere in the list fairly cheaply. As a compromise, there is std::deque, which externally works in a similar way to a vector, but internally they are very different. The deque's storage doesn't have to be contiguous, so it can be divided up into blocks, meaning that when the deque grows, it doesn't have to reallocate the storage space for its entire contents. Access is slightly slower and you can't do pointer arithmetic to get an element.
1,856,307
1,856,479
To iterate or to use a counter, that is the question
Whenever someone starts using the STL and they have a vector, you usually see: vector<int> vec ; //... code ... for( vector<int>::iterator iter = vec.begin() ; iter != vec.end() ; ++iter ) { // do stuff } I just find that whole vector<int>::iterator syntax sickitating. I know you can typedef vector<int>::iterator VecIterInt, and that is slightly better.. But the question is, what's wrong with good ol': for( int i = 0 ; i < vec.size() ; i++ ) { // code }
When you use index to perform essentially sequential access to a container (std::vector or anything else) you are imposing the random-access requirement onto the underlying data structure, when in fact you don't need this kind of access in your algorithm. Random-access requirement is pretty strong requirement, compared to a significantly weaker requirement of sequential access. Imposing the stronger requirement without a good reason is a major design error. So the correct answer to your question is: use sequential (iterator) access whenever you can, use random (index) access only when you absolutely have to. Try to avoid index access whenever possible. If your algorithm critically relies on the container being random-accessible, it becomes the external requirement of the algorithm. In this case you can use index access without any reservations. However, if it is possible to implement the same algorithm using iterators only, it is a good practice to stick to iterators only, i.e. exclusively rely on sequential access. Of course, the above rule, while true, only makes sense in the code is generic to a certain degree. If some other portion of the code is so specific, that you know for sure that the data structure you are working with is a std::vector and will always be a std::vector, then the access method no longer matters. Use whatever you prefer. However, I would still avoid index access in situations when sequential access is perfectly sufficient.
1,856,309
1,856,543
C++ Overloading the >> operator
I need to overload the stream extraction operator. I need to do this by allowing a user to input a string of characters at a prompt, say "iamastring", and then the operator would extract each character from the string and test whether or not it is whitespace and if it is not whitespace store it in a character array which is then passed to an object. @Chip et al. For example output I am not expecting it to output anything to the screen. Instead after a user types in a string and hits enter the user should be prompted again to enter a new menu selection. As it stands right now the user inputs a string hits enter and then a "bad read error" is displayed and the prompt comes back up awaiting new input.
It's quite funny - your name is like mine, but reversed :) How about: char buffer[buffSize+1]; // no need for dynamic allocation here unsigned i = 0; while(std::cin && !std::isspace(std::cin.peek()) && i < buffSize) buffer[i++] = std::cin.get(); buffer[i] = '\0'; // null termination can be important. // i now contains the length btw It's exactly your own code, just a little refactored - I removed all unneccesary stuff etc, nothing more.. Edit: Now fixed to verify stream status & prevent stack overflow :) Edit II: Changed std::cin.good() && !std::cin.eof() to std::cin. Btw: why does cin have a conversion to void* and not to a bool?
1,856,468
1,856,541
How to output IEEE-754 format integer as a float
I have a unsigned long integer value which represents a float using IEEE-754 format. What is the quickest way of printing it out as a float in C++? I know one way, but am wondering if there is a convenient utility in C++ that would be better. Example of the way that I know is: union { unsigned long ul; float f; } u; u.ul = 1084227584; // in HEX, this is 0x40A00000 cout << "float value is: " << u.f << endl; (This prints out "float value is: 5" )
The union method you suggested is the usual route that most people would take. However, it's technically undefined behavior in C/C++ to read a different member from a union than the one that was most recently written. Despite this, though, it's well-supported among pretty much all compilers. Casting pointers, as Jon Skeet suggested, is a bad idea -- that violates the strict aliasing rules of C. An aggressive optimizing compiler will produce incorrect code for this, since it assumes that pointers of types unsigned long * and float * will never alias each other. The most correct way, in terms of standards compliance (that is, not invoking undefined behavior), is to cast through a char*, since the strict aliasing rules permit a char* pointer to alias a pointer of any other type: unsigned long ul = 0x40A00000; float f; char *pul = (char *)&ul; // ok, char* can alias any type char *pf = (char *)&f; // ok, char* can alias any type memcpy(pf, pul, sizeof(float)); Though honestly, I would just go with the union method. From the cellperformance.com link above: It is an extremely common idiom and is well-supported by all major compilers. As a practical matter, reading and writing to any member of a union, in any order, is acceptable practice.
1,856,529
1,856,871
How to use DLL library file in a C++ project?
I have a C++ project and a DLL library made using C#. Is it possible to add it to the C++ project and use its methods? I am using Visual Studio 2008
http://support.microsoft.com/kb/828736
1,856,567
1,856,574
Passing an iterator to another function
I was wondering what would be the best way to accomplish something like this... // Iterating through a list if ( foo ) { RemoveBar( it ); } void RemoveBar( std::list< Type >::iterator it ) { it = listName.erase( it ); ...// Other stuff related to cleaning up the removed iterator } I don't think pass by value will work here. Obviously what I want to do is stay in the correct iterator position when I call RemoveBar. Is pass by reference the best alternative?
Iterators are normally passed by value. I'd make RemoveBar() return the new iterator.
1,856,597
1,856,619
What _can_ I use as std::map keys?
Extends. I have: struct Coord { int row, col ; bool operator<( const Coord& other ) const { return row < other.row && col < other.col ; } } ; I'm trying to create a map<Coord, Node*>, where you can look up a Node* by Coord. The problem is, it has bugs. Lookups into the map<Coord, Node*> by Coord are returning the wrong ones. I'm having difficulty figuring out if this is appropriate or not. Wikipedia says, map [keys] requires a strict weak ordering. Have I done this wrong? Is there a way to make it work, or should keys for a map be simple values that can be "strictly ordered"? Basically the question is what is required for a custom struct to work as a key for my std::map?
Yes you could very well have a problem with strict-weak ordering. Odds are its not working like you'd expect. Consider: bool operator<( const Coord& other ) const { return row < other.row && col < other.col ; } obj1 (this) row: 2 col: 3 obj2 row: 3 col: 2 obj1 < obj2? => false ok well then: obj2 < obj1? => false The only conclusion is that they must be equal (based on your < operator). Since this is a map, and keys are unique, both keys reselve to the same spot. This behavior may-or-may not be what you expect, but it sounds like it probably isn't. What you need is to make a precedence between row/col so that < really works like you'd expect: bool operator<( const Coord& other ) const { // look at row first, if row is equal, check column. if (row < other.row) { return true; } else if (row == other.row) { return col < other.col ; } return false; }
1,856,600
2,174,595
Qt, text on a black and white screen
I'm using Qt (embedded) to make a GUI on a black and white screen. The problem is Qt renders text with shades of grey so it is unreadable on the black and white screen. Does anyone have any idea how to make the text just use 1 bit per pixel, or purely black and white? Thanks, Mark
Incase anyone sees this trying to do the same thing - Turning off AA and setting the supported bit depths to only 1 will not work, virtually all fonts just have grey in them, and if so you can't use them. Best solution is to just create your own purely black and white fonts as a bdf with a 96 resolution (fontforge is good) use something to convert it to a pfa then give that to qt to use and set the pixel size to the same height as the bdfs.
1,856,640
1,856,968
The procedure entry point _ftol2 could not be located in the dynamic link library msvcrt.dll
I've recently been tinkering with a little gameproject using VC++ 2008. I'm using SDL, OpenGL, Boost and Box2D as included libraries. It works fine on my windows 7 machine, aswell as a friend's w7 machine. How ever it wont work on my second friend's XP sp3 machine, with the vc++ 2008 SP1 redist pack installed. When he starts the .exe he get's the error: "The procedure entry point _ftol2 could not be located in the dynamic link library msvcrt.dll" Most forum threads I've read suggests that the msvcrt.dll is corrupt or outdated. My version of the msvcrt.dll is 7.0.7600.1385 and his is 7.0.2600.5512 . Can't find an update for it, can't simply replace it because it reverts to the old version on reboot, and it doesn't seem to help to simply include my msvcrt.dll in my game's folder. According to this thread on gamedev.net, OpenGL32.dll calls the _ftol2. Their conclusion is to install the vc++ 2008 redist pack, which I've mentioned is already installed. Any ideas that might shed light on a solution to this error? Edit: Using Dependency Walker I assured that OpenGL32.dll and GLU32.dll does indeed call the _ftol2 in MSVCRT.dll. How do I avert this dependency?
I shouldn't have included the opengl32.dll from my system with my game. The opengl32.dll on XP is an older version and is properly linked with the MSVCRT.dll on XP aswell. When I included the windows 7 opengl32.dll it simply didn't match with the xp dlls. Removing the opengl32.dll and glu32.dll from my game folder solved the problem and the game works fine.
1,856,646
1,856,689
Is it allowed to inherit from a class in the std namespace (namely std::wstring)?
The class std::wstring is missing some operations for "normal" c strings (and literals). I would like to add these missing operations in my own custom class: #include <string> class CustomWString : public std::wstring { public: CustomWString(const char*); const char* c_str(void); }; The code above compiles fine on Ubuntu Karmic with g++ v4.4.1. But I am wondering if there are arguments against doing so? EDIT: some examples to clarify what I mean with "missing operations" : std::wstring foo("hello"); // requires the L() macro or something like that std::string bar("hello"); std::wstring goose(bar.c_str()); foo="hello"; // requires the L() macro foo=bar.c_str(); foo=bar; EDIT: I would like to have this somehow "centralized". That's because I have a project to be ported from M$-Windows with thousand's of these failing operations. The nice thing is: there is one central place where the string type to be used is defined, e.g.: #ifdef WINDOWS_OS typedef std::wstring AppStringClass; #else typedef std::string AppStringClass; #endif
The compiler definitely lets you, as there is no way to seal a class with a public constructor in C++. STL containers are not designed for inheritance, so it's generally a bad idea. C++ has to many strange corners to ignore that. Your derived class might break with another STL implementation, or just with an update of the build environment. However, I'd consider it a striong warning sign, not a total no-go. It's a "are you really really sure what you are doing, do you know all implications, and have good arguments against all alternatives"? In your case: Providing additional constructors is fine (since the public interface is documented and you can replicate that), and as long as you are not introducing new data members or a VMT, slicing or non-virtual destructor is not a problem. (Keep in mind though that the C++ standard claim undefined behavior when deleting through a base class pointer without virtual DTor) However I am not sure how you want to implement char const * c_str() without also providing storage for the string. And as soon as you introduce new data members, you are entering a field of landmines.
1,856,680
1,856,764
Origin of term "reference" as in "pass-by-reference"
Java/C# language lawyers like to say that their language passes references by value. This would mean that a "reference" is an object-pointer which is copied when calling a function. Meanwhile, in C++ (and also in a more dynamic form in Perl and PHP) a reference is an alias to some other name (or run-time value in the dynamic case). I'm interested in the etymology here. What were early uses of the term "reference"? Lets go for pre-Java, but if you know of pre-C++ uses, that would also interest me. (I'm aware that vocabulary changes, etc, but I'm just interested in the history).
There is an early usage of the term "call by reference" in the paper "Semantic Models of Parameter Passing" by Richard E Fairley, March 1973. In the early days, the terminology was inconsistent. For example, the Fortran 66 specification uses the phrases "association by name" and "association by value". We would now call these "call by reference" and "call by value". By contrast, Algol 60 specification (1962) used the terms "call by name" and "call by value" ... and neither of these are what we currently refer to as call by reference. EDIT: To those who want to label the pioneers who specified Fortran 66 as confused for using the phrase "association by name", consider this: The Fortran 66 was the first attempt to specify a language with (what we now call) call by reference. It was only the second attempt to specify a language with subroutines that supported parameter passing. Fortran 66's "association by name" can be viewed as a restricted (degenerate) form of Algol 60's "call by name". The restriction being that in Fortran, the name had to be a simple variable or array name, where in Algol 60 it could be any expression. It was not clear at the time (1966) that Algol 60's "call by name" was destined to be abandoned as a bad idea. Indeed, when I studied Algol 60 as an undergraduate in 1977, I don't recall the lecturer presenting "call by name" as a bad idea. (It was presented as difficult to understand ... but that's a different thing.)
1,856,727
1,856,747
Can more than one boost::signal be connected to 1 slot?
i know i can connect multiple slots to the same signal. but Can I do it the other way round? having 3 signals connected to the same slot? anyone ever tried this? thanks a lot!
There is nothing preventing you from connecting more than one signal to a slot. Do it if you need to, it'll work fine.
1,856,892
2,182,290
Problem in accessing members of class in C# DLL from C++ project
I have added a C# DLL into a C++ project as mentioned at MS support, however I was not able to access its variables and methods inside the class. It also says that it's a struct and not a class, I don't know if it is important but I thought I should mention it is as well. Whenever I write . or -> or :: after the object, nothing appear. But it appear at the name of the class only although they are not static.
Starting with Visual Studio 2005, you can use C++/CLI, Microsoft's ECMA-approved C++ dialect that allows using managed and unmanaged code together. In VS2005, there are the "Managed Extensions for C++", with which you can achieve roughly the same, but you have to use horribly-looking syntaxes for writing managed code in C++ (with lots of double underscores). With C++/CLI, you can mix managed and unmanaged code in your project, and use C# types directly. IMHO, that's a lot easier than using COM.
1,856,947
1,856,964
Displaying multiple icons in a single cell of a QTableView
I am writing a small gui app with QT4.5 in QtCreator. The main screen on the app contains a QTreeView with two columns, the first is text the second is a group of icons. These icons represent the last few states of the item displayed in the row. I am not sure what the best way to do this is. I have currently implemented this by generating a QPixmap the model's data() method. QVariant MyModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case 0: return item_.at(index.row()).title(); } } if (role == Qt::DecorationRole) { switch(index.column()) { case 1: return makeImage(item_.add(index.row()).lastStates()); } } return QVariant(); } QVariant MyModel::makeImage(const QList<MyState> &states) const { const int IconSize = 22; QPixmap image(IconSize * states.size(), IconSize); QPainter painter(&image); painter.fillRect(0, 0, IconSize * count, IconSize, Qt::transparent); for (int i = 0; i < states.size(); ++i) { QIcon * icon = stateIcon(state.at(i)); icon->paint(&painter, IconSize * i, 0, IconSize, IconSize); } return image; } This works but for some small problems, the background which should be transparent is full of random noise, even filling this with a transparent colour does not fix it. Second this does not seem very efficient, I am generating a new Image every time this is called, should I not just draw the icons onto the widget for the cell? What is the best way to display multiple icons in a single cell?
I would create a custom delegate, based on a hbox, into which you can place all the pictures. Have a look at delegates in the Qt Documentation about model view programming.
1,857,292
1,857,310
How do you get the location, in x-y coordinate pixels, of a mouse click?
In C++ (WIN32), how can I get the (X,y) coordinate of a mouse click on the screen?
Assuming the plain Win32 API, use this in your handler for WM_LBUTTONDOWN: xPos = GET_X_LPARAM(lParam); yPos = GET_Y_LPARAM(lParam);
1,857,458
1,858,763
CDirScan function NextL raises KERN-EXEC 0
CDirScan function NextL raises "Main Panic KERN-EXEC 0" if it is not called right away SetScanDataL() (i.e. if it is called later within the same active object after another event) f1() - called within active object iDirScan = CDirScan::NewLC(aFs); iDirScan->SetScanDataL(aPath, KEntryAttDir|KEntryAttMatchExclusive, ESortNone, CDirScan::EScanDownTree); //wait for some asynchronous event f2() - called within the same active object, after some asynchonous event CDir* dir = NULL; TRAPD(error, iDirScan->NextL(dir)); -->> "Main Panic KERN-EXEC 0" If iDirScan->NextL() is called before waiting for some asynchronous event, everything works fine. Why CDirScan variable looses its validity? Note that the asynchronous event has nothing to do, it can be a simple dummy timer.
I wrote some test code in an attempt to reproduce this but couldn't. Generally, KERN-EXEC 0 panics are most often caused by stale R object handles. For example, make sure that the RFs handle you pass to CDirScan is not closed too early.
1,857,484
1,858,466
C++0x, Compiler hooks and hard coded languages features
I'm a little curious about some of the new features of C++0x. In particular range-based for loops and initializer lists. Both features require a user-defined class in order to function correctly. I came accross this post, and while the top-answer was helpful. I don't know if it's entirely correct (I'm probably just completely misunderstanding, see 3rd comment on first answer). According to the current specifications for initializer lists, the header defines one type: template<class E> class initializer_list { public: initializer_list(); size_t size() const; // number of elements const E* begin() const; // first element const E* end() const; // one past the last element }; You can see this in the specifications, just Ctrl + F 'class initializer_list'. In order for = {1,2,3} to be implicitly casted into the initializer_list class, the compiler HAS to have some knowledge of the relationship between {} and initializer_list. There is no constructor that receives anything, so the initializer_list as far as I can tell is a wrapper that gets bound to whatever the compiler is actually generating. It's the same with the for( : ) loop, which also requires a user-defined type to work (though according to the specs, updated to not require any code for arrays and initializer lists. But initializer lists require <initializer_list>, so it's a user-defined code requirement by proxy). Am I misunderstanding completely how this works here? I'm not wrong in thinking that these new features do infact rely extremely heavily on user code. It feels as if the features are half-baked, and instead of building the entire feature into the compiler, it's being half-done by the compiler and half done in includes. What's the reason for this? Edit: I typed 'rely heavily on compiler code', and not 'rely heavily on user code'. Which I think completely threw off my question. My confusion isn't about new features being built into the compiler, it's things that are built into the compiler that rely on user code.
I'm not wrong in thinking that these new features do infact rely extremely heavily on compiler code They do rely extremely on the compiler. Whether you need to include a header or not, the fact is that in both cases, the syntax would be a parsing error with today compilers. The for (:) does not quite fit into todays standard, where the only allowed construct is for(;;) It feels as if the features are half-baked, and instead of building the entire feature into the compiler, it's being half-done by the compiler and half done in includes. What's the reason for this? The support must be implemented in the compiler, but you are required to include a system's header for it to work. This can serve a couple of purposes, in the case of initialization lists, it brings the type (interface to the compiler support) into scope for the user so that you can have a way of using it (think how va_args are in C). In the case of the range-based for (which is just syntactic sugar) you need to bring Range into scope so that the compiler can perform it's magic. Note that the standard defines for ( for-range-declaration : expression ) statement as equivalent to ([6.5.4]/1 in the draft): { auto && __range = ( expression ); for ( auto __begin = std::Range<_RangeT>::begin(__range), __end = std::Range<_RangeT>::end(__range); __begin != __end; ++__begin ) { for-range-declaration = *__begin; statement } } If you want to use it only on arrays and STL containers that could be implemented without the Range concept (not in the C++0x sense), but if you want to extend the syntax into user defined classes (your own containers) the compiler can easily depend upon the existing Range template (with your own possible specialization). The mechanism of depending upon a template being defined is equivalent to requiring a static interface on the container. Most other languages have gone in the direction of requiring a regular interface (say Container,...) and using runtime polymorphism on that. If that was to be done in C++, the whole STL would have to go through a major refactoring as STL containers do not share a common base or interface, and they are not prepared to be used polimorphically. If any, the current standard will not be underbaked by the time it goes out.
1,857,668
1,866,668
C++ Visual Studio character encoding issues
Not being able to wrap my head around this one is a real source of shame... I'm working with a French version of Visual Studio (2008), in a French Windows (XP). French accents put in strings sent to the output window get corrupted. Ditto input from the output window. Typical character encoding issue, I enter ANSI, get UTF-8 in return, or something to that effect. What setting can ensure that the characters remain in ANSI when showing a "hardcoded" string to the output window? EDIT: Example: #include <iostream> int main() { std:: cout << "àéêù" << std:: endl; return 0; } Will show in the output: óúÛ¨ (here encoded as HTML for your viewing pleasure) I would really like it to show: àéêù
Before I go any further, I should mention that what you are doing is not c/c++ compliant. The specification states in 2.2 what character sets are valid in source code. It ain't much in there, and all the characters used are in ascii. So... Everything below is about a specific implementation (as it happens, VC2008 on a US locale machine). To start with, you have 4 chars on your cout line, and 4 glyphs on the output. So the issue is not one of UTF8 encoding, as it would combine multiple source chars to less glyphs. From you source string to the display on the console, all those things play a part: What encoding your source file is in (i.e. how your C++ file will be seen by the compiler) What your compiler does with a string literal, and what source encoding it understands how your << interprets the encoded string you're passing in what encoding the console expects how the console translates that output to a font glyph. Now... 1 and 2 are fairly easy ones. It looks like the compiler guesses what format the source file is in, and decodes it to its internal representation. It generates the string literal corresponding data chunk in the current codepage no matter what the source encoding was. I have failed to find explicit details/control on this. 3 is even easier. Except for control codes, << just passes the data down for char *. 4 is controlled by SetConsoleOutputCP. It should default to your default system codepage. You can also figure out which one you have with GetConsoleOutputCP (the input is controlled differently, through SetConsoleCP) 5 is a funny one. I banged my head to figure out why I could not get the é to show up properly, using CP1252 (western european, windows). It turns out that my system font does not have the glyph for that character, and helpfully uses the glyph of my standard codepage (capital Theta, the same I would get if I did not call SetConsoleOutputCP). To fix it, I had to change the font I use on consoles to Lucida Console (a true type font). Some interesting things I learned looking at this: the encoding of the source does not matter, as long as the compiler can figure it out (notably, changing it to UTF8 did not change the generated code. My "é" string was still encoded with CP1252 as 233 0 ) VC is picking a codepage for the string literals that I do not seem to control. controlling what the console shows is more painful than what I was expecting So... what does this mean to you ? Here are bits of advice: don't use non-ascii in string literals. Use resources, where you control the encoding. make sure you know what encoding is expected by your console, and that your font has the glyphs to represent the chars you send. if you want to figure out what encoding is being used in your case, I'd advise printing the actual value of the character as an integer. char * a = "é"; std::cout << (unsigned int) (unsigned char) a[0] does show 233 for me, which happens to be the encoding in CP1252. BTW, if what you got was "ÓÚÛ¨" rather than what you pasted, then it looks like your 4 bytes are interpreted somewhere as CP850.
1,857,673
1,857,681
How can I implement scripting in my game?
I'm trying to write a game and implement scripting so that later on in development I won't have to recompile everything when I want to change numbers. My problem is that I don't know how scripts should interface with the game. The scripting language I'm using is angelscript. Right now, I have a state: the intro state, which I'm using as a test for most of the modules in my game "engine" (it's more like a loose collection of classes). It will load and draw a picture and draw text, and use scripting to update itself, and maybe switch to a dummy state afterwards to test the state manager. While writing it, I realized that using the script to do most of the updating would require that I register most of my game engine's modules with the script, and pretty much move the bulk of the code to the scripting language. Personally, I'd rather have the C++ portion doing the majority of the work, and have the scripting language come up with the numbers to use in the formulas/drawing/whatever. However, if I'm right, doing it that way would entail lots of different update modules for the majority of the things in the game that need to be updated, and requiring that they all be loaded in, and that the C++ code would have to run each update function individually. Or, there's a way to achieve script and program interoperability that I'm overlooking. Either way, could someone help me figure out what the best way to get scripting implemented into my game is?
There's no correct answer to such a large question really. You do it the same way you would do engine/game logic separation in C++. Define an API that the script can call that allows it whatever it is you want it to do. Register functions in that API with the script, and use the API in angelscript. What that API should be depends entirely on your needs and what kind of power you want to give the scripter.
1,857,721
1,857,766
how to synchronize a varied number of threads?
Could someone please help me with synchronizing varied number of threads? The problem is when the number of threads can vary from one to 9 and when for instance two clients are connected to server, the communication should be synchronized in this form : client1, client2, client1, client2 ... until the communication is over. I tried with pthread_join , pthread_mutex_lock and pthread_mutex_lock, but this blocks client1 until finish communicating to start client2. Any help would be appreciated and thanks for your reply
I actually don't understand well how the threads should be synchronized. If there is some block of code that needs to be done in a serialized manner then the pthread_mutex_lock should be good enough. If the order of operation should be preserved (1,2,3,1,2,3) I suggest using pthread_mutex_lock along with some variable indicating which thread is allowed to enter the critical section now. // id_to_go iterates from 0 up to number_of_thread - 1 // each thread has my_id from the same range while(1) { pthread_mutex_lock(mutex); if (id_to_go == my_id) { // set to next thread id id_to_go = (id_to_go + 1) % number_of_threads; } else { // it's not our turn, try again pthread_mutex_unlock(mutex); continue; } handle_the_client; pthread_mutex_unlock(mutex); }
1,857,850
1,857,947
Deleting And Reconstructing Singleton in C++
I have an application which runs on a controlling hardware connected with different sensors. On loading the application, it checks the individual sensors one by one to see whether there is proper communication with the sensor according to predefined protocol or not. Now, I have implemented the code for checking the individual sensor communication as a singleton thread and following is the run function, it used select system call and pipe for interprocess communication to signal the end of thread. void SensorClass::run() { mFdWind=mPort->GetFileDescriptor(); fd_set readfs; int max_fd = (mFdWind > gPipeFdWind[0] ? mFdWind : gPipeFdWind[0]) + 1; int res; mFrameCorrect=false; qDebug("BEFORE WHILE"); while(true) { qDebug("\n IN WHILE LOOP"); usleep(50); FD_ZERO(&readfs); FD_SET(mFdWind,&readfs); FD_SET(gPipeFdWind[0],&readfs); res=select(max_fd,&readfs,NULL,NULL,NULL); if(res < 0) perror("Select Failed"); else if(res == 0) puts("TIMEOUT"); else { if(FD_ISSET(mFdWind,&readfs)) { puts("*************** RECEIVED DATA ****************"); mFrameCorrect=false; FlushBuf(); //int n=mPort->ReadPort(mBuf,100); int n=mPort->ReadPort(mBuf,100); if(n>0) { Count++; QString str((const char*)mBuf); //qDebug("\n %s",qPrintable(str)); //See if the Header of the frame is valid if(IsHeaderValid(str)) { if( (!IsCommaCountOk(str)) || (!IsChecksumOk(str,mBuf)) || (!CalculateCommaIndexes(str)) ) { qDebug("\n not ok"); mFrameCorrect=false; } //if frame is incorrect else { qDebug("\n OK"); mFrameCorrect=true; }//if frame is correct(checksum etc are ok) }//else if header is ok }//if n > 0 }//if data received FD_ISSET if(FD_ISSET(gPipeFdWind[0],&readfs)) break; }//end nested else res not <= 0 }//infinite loop } The above thread is run started from the main GUI thread. This runs fine. The problem is I have given an option to the user to retest the subsystem at will. For this I delete the singleton instance using delete SensorClass::instance(); and then restart the singleton using SensorClass::instace()->start(); The problem is this time the control comes out of while loop in run() function immedeately upon entering the while loop, my guess is the pipe read has again read from the write pipe which was written to the last time. I have tried to use the fflush() to clear out the I/O but no luck. My question is Am I thinking on the right track? If yes then how do we clear out the pipes? If not can anyone suggest why is the selective retest not working? Thanks in advance..
fflush clears the output buffer. If you want to clear the input buffer, you're going to need to read the data or seek to the end. I'm not convinced the "Singleton" pattern is appropriate. There are other ways of ensuring at most one instance for each piece of hardware. What if you later want multiple threads, each working with a different sensor?
1,858,141
1,858,544
Is UnregisterHotKey() important for clean up?
Simple question I think, after I have registered a few system-wide hotkeys with RegisterHotKey() do I need to eventually call UnregisterHotKey() to clean them up, or can I simply exit my application without worrying about it? MSDN doesn't seem to say, that or I misunderstand it, anyways: I realize I should just go ahead and call UnregisterHotKey to be safe, but if anyone knows otherwise it'd be useful just to know, for knowings sake. Thanks!
If the MSDN doesn't explicitly tell you to unregister, then it's probably safe to just quit. The MSDN is usually pretty good at pointing things like this out. However, I also use RegisterHotKey and I always make sure to call UnRegisterHotKey when my application quits as you never know if not doing do will cause you problems in a future version of Windows. Better to be safe than sorry IMHO.
1,858,297
1,858,325
What is the best LALR parser generator for C++ that can generate meaningful error messages
I am looking for the best solution for a LALR parser generator for C++ that will allow me to generate really good error messages. I really hate the syntax errors that MySQL generates and I want to take the parser in it and replace it with a "lint" checker that will tell me more than just ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'a from users' at line 1 I have used YACC/LEX and BISON/FLEX. It has to work on Mac or Linux.
Why do you require LALR? One of the benefits of LL(k) parsers is that they can often make it easier to generate clear error messages. Most grammars that can be parsed by an LALR parser can be easily refactored to be parsable by an LL(k) parser. ANTLR is a popular LL(k) parser generator that can generate C++ (as well as a number of other languages). From Chapter 10 of The Definitive ANTLR Reference: The quality of a language application’s error messages and recovery strategy often makes the difference between a professional application and an amateurish application. Error recovery is the process of recovering from a syntax error by altering the input stream or consuming symbols until the parser can restart in a known state. Many hand-built and many non-LL-based recognizers emit less than optimal error messages, whereas ANTLR-generated recognizers automatically emit very good error messages and recover intelligently, as shown in this chapter. Many grammars are also available for ANTLR, including a MySQL grammar.
1,858,364
1,858,375
how to bias a random number generator
i am using the random number generator provided with stl c++. how do we bias it so that it produces smaller random numbers with a greater probability than larger random numbers.
Well, in this case you probably would like a certain probability distribution. You can generate any distribution from a uniform random number generator, the question is only how it should look like. Rejection sampling is a common way of generating distributions that are hard to describe otherwise, but in your case something simpler might suffice. You can take a look at this article for many common distribution functions. Chi, Chi-Square and Exponential look like good candidates.
1,858,419
1,858,862
Reopening a closed Piped read file descriptor?
I have used pipes to facilitate interprocess communication. They work just fine. But in my scenario I want to close and reopen the read end of the file descriptor fd[0]. Does anyone know how to do that?
You cannot reopen an unnamed pipe. If you really need to do this reopening magic, consider using named pipes, that can be opened and reopened as many times as you wish. But before doing it, consider whether it makes any sense at all.
1,858,500
1,858,535
Small question concerning redefining member functions
I'm trying to redefine two member functions from their parent's definition.I don't know if I have it right or not, but something in my code has errors attached and I can't find out what. some of the header: class Account { public: Account(double); void creditBalance(double); void debitBalance(double); double getBalance() const; protected: double balance; }; class CheckingAccount : public Account { public: CheckingAccount(double, double); void feeCreditBalance(double); void feeDebitBalance(double); private: double fee = 10; }; relevant cpp file part: void Account::creditBalance(double plus) { if(plus > 0) balance += plus; else cout << "Cannot credit negative."; } void Account::debitBalance(double minus) { if(minus <= balance) balance -= minus; else cout << "Debit amount exceeded account balance."; } void CheckingAccount::feeCreditBalance(double plus) { if(plus > 0){ balance += plus; balance -= fee; } else cout << "Cannot credit negative."; } void CheckingAccount::feeDebitBalance(double minus) { if(minus <= balance){ balance -= minus; balance -= fee; } else cout << "Debit amount exceeded account balance."; } UPDATE: I added this: class Account { public: Account(double); virtual void creditBalance(double); virtual void debitBalance(double); double getBalance() const; protected: double balance; }; Now I get error: virtual outside class declaration I could use an example of how to properly initialize fee correctly. EDIT 2: I have tried changing the constructor line to this: CheckingAccount::CheckingAccount(double initBal, double phi) : Account(initBal), fee(phi) { if(initBal < 0) initBal = 0; balance = initBal; cerr << "Initial balance was invalid."; if(phi < 0) phi = 0; fee = phi; } not working, I'm going to work around with changing syntax on the fee(phi) part. I don't know if anyone will respond to this.
If the intention is that for instances of CheckingAccount accounts the versions which use a fee is called, then you want to use virtual methods. A virtual method is a method decalared (at least in the base class) as "virtual", and has the same name and signiture in any derived classes. When a virtual method is called, it will call the "most derived" version for the instance. To do this just declare "void creditBalance(double);" and "void debitBalance(double);" virtual (ie "virtual void creditBalance(double);" and "virtual void debitBalance(double);". Then in CheckingAccount rename "feeCreditBalance" and "feeDebitBalance" to "creditBalance" and "debitBalance". EDIT: Simple example. Header class Base { public: Base(int x); //declare virtual so that derived classes may overide it virtual void sayHello(); protected: int x; }; class Derived : public Base { public: Derived(int x, int y); //overide Base::sayHello(). the virtual keyword here is optional. virtual void sayHello(); protected: int y; }; Cpp Base::Base(int x) :x(x) {} Derived::Devired(int x, int y) :Base(x), y(y) {} void Base::sayHello() { std::cout << "Hello from Base!" << std::endl; std::cout << "X = " << x << std::endl; } void Derived::sayHello() { std::cout << "Hello from Derived!" << std::endl; std::cout << "X = " << x << " Y = " << y << std::endl; } int main() { Base a(5); a.sayHello();//"Hello from Base!..." Derived b(10, -20); b.sayHello();//"Hello from Derived!..." Base *c = &b;//take pointer to b, reference would also do c->sayHello();//"Hello from Derived!..." because its a Derived instance, eventhough its a Base variable. } You can then derive from Derive again (class DerivedAgain : public Derived) and also overload the functions again. You can also derive multiple subclasses from Base, which can each have their own overrides for the virtual methods, just like I did for the Derived class. EDIT2: Added variables to example and how to use initialiser list to initialise the base class and member variables.
1,858,571
1,858,765
C++ Duplicate Symbol error when defining static class variable in XCode
I have a static class member incremented in the constructor. As per the rules, it is declared in the class and defined outside. This should be totally legal. Any ideas why I'm getting a duplicate symbol error? class Player { private: static int numPlayers; public: Player() { numPlayers++; } }; int Player::numPlayers = 0;
The problem is that you are not separating your DECLARATION from your DEFINITION. Consider: class Player { private: static int numPlayers; public: Player() { numPlayers++; } }; The code above merely declares the existence of "numPlayers" in the class "Player". It does not, however, reserve any space or assign a memory address to the variable "Player::numPlayers". However: int Player::numPlayers = 0; The code above is a DEFINITION -- it reserves space for the object Player::numPlayers and designates a unique address for that object. Having that line appear more than once in a program violates the one-definition-rule. Now what is most likely happening is that you are including this file... You should NEVER, EVER include a ".c", ".cpp", ".m", ".mm" or any other "source" file (i.e. a file that contains DEFINITIONS). You should only include "header" files (i.e. files containing purely DECLARATIONS). For many build systems, including Xcode, each source file is automatically compiled and linked into the project. If you include a source file from another source file, then the definitions get linked in twice -- first when it is compiled on its own and then again when it is referenced by another source file. Since you are asking about Xcode... you can remedy this issue by unchecking the source file in the project detail view; a check mark next to a source file indicates that it will be compiled and linked-in for the current target. However, I strongly suggest that you leave your ".mm" file checked, create a ".h" file in which you put your declarations, and include the ".h" file instead of including one source file from another.
1,858,639
1,858,876
Shall I place try...catch block in destructor, if I know my function won't throw exception
I know destructor shouldn't not throw exception. http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.13 I have the following code : ~a() { cleanup(); } // I do not expect exception being thrown in this function. // If exception really happen, I know that it is something not recoverable. void a::cleaup() { delete p; } In my static source code analysis, it complains that I shall call the cleanup function in this way : ~a() { try { cleanup(); } catch(...) { // What to do? Print out some logging message? } } // I do not expect exception being thrown in this function. // If exception really happen, I know that it is something not recoverable. void a::cleaup() { delete p; } I am not sure whether this is a good practice, to place try...catch block in destructor, whenever it calls functions. As : (1) If cleanup function able to throw exception, I know something bad had happened. I prefer it to be fail-fast. That is, just let the whole system crash, and let the programmer debugs it. (2) Overhead occur while entering and exiting try...catch block. (3) The code look cumbersome, with a lot of try...catch block around classes' destructor. I may miss out some other points, why try...catch block should be in place. Thanks.
Since delete won't throw, neither will cleanup and as such there is no need to put the call in try-catch. Since your static analysis tool is probably having a hard time figuring that out, perhaps you could help it out (it's only a guess though) by declaring cleanup as no-throw. void cleanup() throw();
1,858,727
1,861,703
Connecting and Fetching a record form sequel server 2005
I have a windows application in visual C++. I am not using MFC, in this application I have connect to SQL server 2005 and fetch records form a database file. Can any one guide me how this can done. Thanks in advance.
I would say, you could use some wrapper framework around the odbc calls. Currently I was working on a project where SQL server communication was involved so I found this wrapper framework: TinyODBC which is a minimalistic ODBC wrapper library. It's pretty trivial how can one use it, but I have to admit I had to patch it for a little more functionality. But otherwise it is a useful choice of ODBC communication. Now, you can use the native SQL driver via ODBC. Since it's a minimal framework, if you go through the tutorial you'll be ready to create new application with it. Now
1,858,778
1,877,384
How can I simplify my C++ code to reverse characters?
Hello I have this program which reverses letters I enter. I'm using iostream. Can I do it another way and replace iostream and cin.getline with cin >> X? My code: //Header Files #include<iostream> #include<string> using namespace std; //Recursive Function definition which is taking a reference //type of input stream parameter. void ReversePrint(istream&); //Main Function int main() { //Printing cout<<"Please enter a series of letters followed by a period '.' : "; //Calling Recursive Function ReversePrint(cin); cout<<endl<<endl; return 0; } //Recursive Function implementation which is taking a //reference type of input stream parameter. //After calling this function several times, a stage //will come when the last function call will be returned //After that the last character will be printed first and then so on. void ReversePrint(istream& cin) { char c; //Will retrieve a single character from input stream cin.get(c); //if the character is either . or enter key i.e '\n' then //the function will return if(c=='.' || c=='\n') { cout<<endl; return; } //Call the Recursive function again along with the //input stream as paramter. ReversePrint(cin); //Print the character c on the screen. cout<<c; }
below function gets line from standard input, reverses it and writes to stdout #include <algorithm> #include <string> #include <iostream> int main() { std::string line; std::getline( std::cin, line ); std::reverse( line.begin(), line.end() ); std::cout << line << std::endl; }
1,858,963
1,859,026
Vectors, "virtual", Segmentation Fault on function call
I'm getting a Segmentation Fault when trying to call a function that is within a object that is part of a vector of "Shape" Pointers My problem is in this function:: Point findIntersection(Point p, Point vecDir, int *status) { Point noPt; for (int i = 0; i < shapes.size(); i++) { Point temp; cout << "Shapes size" << shapes.size() << endl; **SEGMENTATIONFAULT HERE >>>>>** bool intersect = shapes[0]->checkIntersect(p, vecDir, &temp); if (intersect) { *status = 1; // Code 1 for intersecting the actual shape return temp; } } return noPt; } Initially, I am only adding one shape: void createScene() { image = QImage(width, height, 32); // 32 Bit Sphere s(Point(0.0,0.0,-50.0), 40.0); shapes.push_back(&s); cout << shapes.size() <<endl; } So I have a vector of "shapes" which is global. vector shapes; I have a class shape #include "Point.h" #ifndef SHAPE_H #define SHAPE_H using namespace std; class Shape { public: Shape() {} ~Shape(){} virtual bool checkIntersect(Point p, Point d, Point *temp) {}; // If intersects, return true else false. virtual void printstuff() {}; }; #endif and also a Sphere class #include "shape.h" #include <math.h> #include <algorithm> using std::cout; using std:: endl; using std::min; class Sphere : public Shape { public: Point centerPt; double radius; Sphere(Point center, double rad) { centerPt = center; radius = rad; } bool checkIntersect(Point p, Point vecDir, Point *temp) { cout << "Hi" << endl; /* Point _D = p - centerPt; double a = Point :: dot(vecDir, vecDir); double b = 2 * ( Point :: dot(vecDir, _D) ); double c = (Point :: dot(_D,_D)) - (radius * radius); // Quadratic Equation double tempNum = b * b - 4 * a * c; if (tempNum < 0) { return false; } else { double t1 = ( -b + sqrt(tempNum) ) / (2 * a); double t2 = ( -b - sqrt(tempNum) ) / (2 * a); double t; if (t1 < 0 && t2 > 0) { t = t2; } else if (t2 < 0 && t1 > 0) { t = t1; } else if ( t1 < 0 && t2 < 0 ) { return false; } else { t = min(t1, t2); } Point p1 = p + (vecDir * t); if (p1.z > 0) // Above our camera { return false; } else { temp = &p1; return true; } } */ return false; } };
The problem is here: Sphere s(Point(0.0,0.0,-50.0), 40.0); shapes.push_back(&s); at this point, you've created the Sphere s locally on the stack, and you've pushed its address into your vector. When you leave scope, local objects are freed, and so the address you've stored in your vector now points to memory you no longer own and its contents is undefined. Instead, do Sphere *s = new Sphere(Point(0.0,0.0,-50.0), 40.0); shapes.push_back(s); to allocate the Sphere from the heap so that it persists. Make sure to delete it when you are done with it.
1,858,970
1,858,984
How to catch this error? [C++]
I'm trying to catch dividing by zero attempt: int _tmain(int argc, _TCHAR* argv[]) { int a = 5; try { int b = a / 0; } catch(const exception& e) { cerr << e.what(); } catch(...) { cerr << "Unknown error."; } cin.get(); return 0; } and basically it doesn't work. Any advice why? Thank you. P.S. Any chance that in the future code can be placed between [code][/code] tags instead of four spaces?
Divide by zero does not raise any exceptions in Standard C++, instead it gives you undefined behaviour. Typically, if you want to raise an exception you need to do it yourself: int divide( int a, int b ) { if ( b == 0 ) { throw DivideByZero; // or whatever } return a / b; }
1,858,978
1,859,021
Segmentation fault when instantiating object from particular library
I have an C++ application (heavily shortened down, shown below); #include <iostream> #include "MyClass.h" void foobar() { MyClass a; } int main(int argc, char** argv) { std::cout << "Hello world!\n"; return 0; } Where "MyClass" is defined in a statically linked library (.a). However, this application Segfaults the instant its started, and I never get to the "Hello world". I can create an instance of an interface from the same library, but I cannot create an instance of a class that implements the interface. I.e; void foobar() { IMyClass a; // Having this in the application works. MyClass b; // Segfault if this is in. } As you can see from above, the code doesn't even need to get called for the application to segfault. I'm using Netbeans 6.7.1 and GCC 4.3.2. Now, I'm presuming there is something wrong with the linking of the library but I cannot tell what. I'm linking in other libraries (all statically linked) as well. The classes above are from the first linked library (first in the list at least). If I create an instance of a class from the second listed library, everything runs fine. It's possible that the problem is similar (or related) to my other problem: https://stackoverflow.com/questions/1844190/linking-with-apache-xml-security-causes-unresolved-references Does anyone have any suggestions on what might be the problem?
There may be some static initialization inside the the MyClass library that goes wrong, if you don't have the source code it will be hard to find and fix.
1,859,117
1,859,189
Difference between double dispatch and visitor pattern in Java and C++
Is there any difference between double dispatch and visitor pattern? I'm working with Java and C++ and wondering if there is any split between the two.
The visitor pattern is a means of adding a new operation to existing classes. Double dispatch is a means of dispatching function calls with respect to two (or, when generalised, more) polymorphic types, rather than a single polymorphic type, which is what languages like C++ and Java support directly.
1,859,176
1,859,217
Component Object Model via C++(maybe VS)
I was searching through google about Microsoft Component Object Model. Found only few normal articles and only 1 step by step example, which doesn't work. Is there any links/references/books/tutorials you know how to build simple COM component via VS C++? Any answer or help would be appreciated!
COM is generally considered antiquated technology these days. That's not to say nobody is still using it - there are plenty of legacy systems that are still invested in it - but it's rare to find someone approaching it as a newbie nowadays. I'm not sure if things have moved on much but my recommendations would be Don Box's Essential COM and ATL Internals . Actually my overriding recommendation would be to avoid it if you can :-)
1,859,415
1,940,361
Export every frame as image from a Movie-File (QuickTime-API)
I want to open an existing Movie-File and export every frame of this file to an image like JPEG or TIFF. I got so far until now: int main(int argc, char* argv[]) { char filename[255]; // Filename to ping. OSErr e; // Error return. FSSpec filespec; // QT file specification short filemovie; // QT movie handle. Movie movie; // QT movie "object". InitializeQTML(0); EnterMovies(); // Because of QT's Mac origin, must convert C-string filename // to Pascal counted string, then use that to make a filespec. c2pstr(filename); FSMakeFSSpec(0, 0L, (ConstStr255Param)filename, &filespec); OpenMovieFile(&filespec, &filemovie, fsRdPerm); NewMovieFromFile(&movie, filemovie, nil, nil, newMovieActive, nil); ... Until now it works fine (I tested with TimeValue movietime = GetMovieDuration(movie); and print it), but now I want to get every frame of the movie and export it to a file (for first, later i just want to keep the data in memory to work with it, but i have to know if it really works, so export to an image-file is better for now). How do I do that? Do I need a GWorld or a PixMap? How do I get a GWorld/PixMap from a Movie-File, especially each frame of it? edit: My Platform is WinXP
As a beginning, this article on Movie exporters should pretty much get you started: http://www.mactech.com/articles/mactech/Vol.16/16.05/May00QTToolkit/index.html Even though MacTech is a Mac resource, all described API functions should be available in the QuickTime for Windows SDK as well. I will slap some sample code together myself as a reference here as soon as I find the time. Edit See this book excerpt for additional info: QuickTime Toolkit - Basic Movie Playback and Media Types @ Google Books Edit 2 - The High-Level Approach: Movie Exporters If all you need to accomplish is to extract all video frames from a QuickTime Movie and convert them to another format supported by the QuickTime API you won't have to take any low-level actions whatsoever if using a Movie Exporter. The below sample code allows to extract and convert all video frames from a QuickTime Movie to, f.e., a bunch of JPEG files using a programmatically invoked Movie Export Dialog. Just select Movie to Image Sequence in the Export combo box of the dialog and select your desired image format by hitting Options. Note 1: If you need to do this non-interactively, just let me know. Note 2: error handling has been omitted for clarity #include "Movies.h" #include "QTML.h" #pragma comment (lib, "QTMLClient.lib") ... int flags = createMovieFileDeleteCurFile | showUserSettingsDialog | movieToFileOnlyExport; ItemCount movie_prop_count = 0; CFStringRef cfpath = 0; Boolean bool_true = true; QTNewMoviePropertyElement movie_props[ 2 ]; Movie movie; // initialize QuickTime API InitializeQTML( 0 ); EnterMovies(); // set up Core Foundation string for source path (argv[ 1 ]) contains the full path to the MOV file to convert cfpath = CFStringCreateWithCString( 0, argv[ 1 ], kCFStringEncodingASCII ); movie_props[movie_prop_count].propClass = kQTPropertyClass_DataLocation; movie_props[movie_prop_count].propID = kQTDataLocationPropertyID_CFStringNativePath; movie_props[movie_prop_count].propValueSize = sizeof(cfpath); movie_props[movie_prop_count].propValueAddress = (void*)&cfpath; movie_props[movie_prop_count].propStatus = 0; ++movie_prop_count; // make Movie active movie_props[movie_prop_count].propClass = kQTPropertyClass_NewMovieProperty; movie_props[movie_prop_count].propID = kQTNewMoviePropertyID_Active; movie_props[movie_prop_count].propValueSize = sizeof(bool_true); movie_props[movie_prop_count].propValueAddress = &bool_true; movie_props[movie_prop_count].propStatus = 0; ++movie_prop_count; // aquire Movie for our Movie file NewMovieFromProperties( movie_prop_count, movie_props, 0, 0, &movie ); // invoke conversion dialog ConvertMovieToFile( movie, 0, 0, 0, 'TVOD', 0, 0, flags, 0 ); // clean up DisposeMovie( movie ); CFRelease( cfpath ); ExitMovies(); TerminateQTML(); ...