question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,329,574
2,330,372
CComSafeArray: Are Indices Really Reversed for MultiDimSetAt and MultiDimGetAt?
In the MSDN documentation for CComSafeArray::MultiDimSetAt, alIndex is documented as follows: Pointer to a vector of indexes for each dimension in the array. The rightmost (least significant) dimension is alIndex[0]. In the documentation for CComSafeArray::MultiDimGetAt, alIndex is documented differently: Pointer to...
It seems to be docs error - I'd suggest you to refer to SafeArrayGetElement/SafeArrayPutElement documentation as it seems to be more accurate. To set and get the same element you should use the same array of indices (without reversing). By the way, nice catch!
2,329,581
2,329,607
C++ Pointers. How to assign value to a pointer struct?
I have the following struct: typedef struct{ int vin; char* make; char* model; int year; double fee; }car; Then I create a pointer of type car car *tempCar; How do I assign values to the tempCar? I'm having trouble tempCar.vin = 1234; tempCar.make = "GM"; tempCar.y...
You need to use the -> operator on pointers, like this: car * tempCar = new car(); tempCar->vin = 1234; tempCar->make = "GM"; //... delete tempCar; Also, don't forget to allocate memory for tempCar if you're using a pointer like this. That's what 'new' and 'delete' do.
2,329,655
2,330,234
Does CComSafeArray MultiDimSetAt Make a Copy of the Referenced Element?
The CComSafeArray::SetAt method provides a parameter to control whether the referenced variable is copied: HRESULT SetAt( LONG lIndex, const T& t, BOOL bCopy = TRUE ); ... but the CComSafeArray::MultiDimSetAt method does not offer the same parameter: HRESULT MultiDimSetAt( const LONG * alIndex, const T& t ); Two que...
Internally MultiDimSetAt uses SafeArrayPutElement function. It means that BSTRs would be copied and objects would be AddRef'ed.
2,329,722
2,329,780
nm: "U" The symbol is undefined
When I nm on one of my libs: nm libmylib.so I get a line like this U _ZNSs4_Rep20_S_empty_rep_storageE@@GLIBCXX_3.4 I checked the man page for nm and I got "U" The symbol is undefined. What does an undefined symbol really mean? If it is really undefined, then why does nm report it at all?
An undefined symbol is a symbol that the library uses but was not defined in any of the object files that went into creating the library. Usually the symbol is defined in another library which also needs to be linked in to your application. Alternatively the symbol is undefined because you've forgotten to build the cod...
2,329,917
2,329,942
error: expected ';' before '<' token
my compiler throws error: expected ';' before '<' token on this line of code: std::vector< std::vector<int> > data; What's real weird is that I compiled this earlier today on my mac with g++ on the command line and now i'm trying to compile in xCode on the same mac (which i assume also uses g++) and it throws this er...
Probably you are missing a semicolon at the end of what's on the previous line. If you have no code before that line, then it is a missing semicolon at the end of one of your included header files. For example you can reproduce this error using: #include <vector> class C { } std::vector< std::vector<int> > data;
2,330,061
2,330,881
How to make '3 part' splitter window in wxWidgets?
I want to create 3 parts in a window or panel. All the 3 Parts should have possibility to resized by user and be automatically resized when user change size of Main window. Its something like 3 panels added to vertical box sizer, but user can resize all of three parts. I can add up to 2 panels to wxSplitterWindow. Im w...
Can you use wxAuiManager? You could use this to create 'panels' (for lack of a better word) that can be resized and moved around (even undocked and floated). For you it would look something like: wxAuiManager * pManager; // a pointer to the manager for the wxFrame wxWindow * pPanel1; wxWindow * pPanel2; // the 3 pane...
2,330,117
2,332,936
How to catch exception thrown while initializing a static member
I have a class with a static member: class MyClass { public: static const SomeOtherClass myVariable; }; Which I initialize in the CPP file like so: const SomeOtherClass MyClass::myVariable(SomeFunction()); The problem is, SomeFunction() reads a value from the registry. If that registry key doesn't exist, it thro...
I don't like static data members much, the problem of initialization being foremost. Whenever I have to do significant processing, I cheat and use a local static instead: class MyClass { public: static const SomeOtherClass& myVariable(); }; const SomeOtherClass& MyClass::myVariable() { static const SomeOtherClas...
2,330,165
2,330,183
How does Chrome knows when Flash crashed?
unfortunately many times the Flash plugin at Google's Chrome crashes. But fortunately, they just present a message box and a sad face. My question is, how do they do it? my first thought is that they use structured exception handling but then again, how they know its Flash that crashed? thanks for any ideas! Lior
they run it in a separate process. when the child process terminates, the parent is notified by the operating system. the parent can then query the system about the nature of the termination.
2,330,233
2,330,240
C++ "class Foo return Bar" and "class Bar return Foo" possible?
Is it possible to define C++ classes Foo and Bar s.t. class Foo { Bar makeBar(); }; class Bar { Foo makeFoo(); }; ? Thanks!
Yes it is, you just have to put forward declarations at the top. class Foo; class Bar; class Foo { Bar makeBar(); }; class Bar { Foo makeFoo(); };
2,330,257
2,331,101
SDL causes Undefined symbols: "_main", referenced from: start in crt1.10.5.o
When I try to use SDL in my c++ program, I get the following: > g++ minimal.cpp SDLMain.m Undefined symbols: "_main", referenced from: start in crt1.10.5.o ld: symbol(s) not found collect2: ld returned 1 exit status Here's my minimal.cpp: #include <SDL/SDL.h> int main(int argc, char **argv) { return 0; } ...
Solution was to use the SDLMain.m file included in SDL-devel-1.2.14-extras.dmg from the SDL homepage. For some reason the one I was using before had mysteriously stopped working. Here's my working compile command: g++ -framework SDL -framework Cocoa -I/usr/local/include/SDL/ minimal.cpp "/Library/Application Support/De...
2,330,350
2,330,384
C or C++. How to compare two strings given char * pointers?
I am sorting my array of car two ways. one by year which is shown below. and another one by make. Make is a char* How do I compare strings when I just have pointers to them? int i, j; for(i=0; i<100; i++){ for(j=0; j<100-i; j++){ if(carArray[i]!=NULL && carArray[j]!= NULL && carArray[j+1]!=NULL){ ...
In pretty much either one, the way is to call strcmp. If your strings (for some weird reason) aren't NUL terminated, you should use strncmp instead. However, in C++ you really shouldn't be manipulating strings in char arrays if you can reasonably avoid it. Use std::string instead.
2,330,530
2,330,554
How are .libs created in your VS solution linked by another project?
If I have a project Foo that has a .lib as an output that's also used by projects Bar and Baz, how do I let Bar and Baz know where to find the library assuming MSVC? I have the project dependencies set up already, but how do I #pragma comment(lib, "????/Foo.lib") properly?
You have two options. Firstly, Visual Studio itself has a global library path that it searches for all projects. You can add directories to this via Tools > Options > Projects and Solutions > VC++ Directories > Library files. Alternatively, you can set the library path for specific projects. In the project properties s...
2,330,551
2,330,744
c++ insert into vector at known position
I wish to insert into a c++ vector at a known position. I know the c++ library has an insert() function that takes a position and the object to insert but the position type is an iterator. I wish to insert into the vector like I would insert into an array, using a specific index.
Look at that debugging trace. The last thing that's executed is std::copy(__first=0x90c6fa8, __last=0x90c63bc, __result=0x90c6878). Looking back at what caused it, you called insert giving the position to insert at as 0x90c63bc. std::copy copies the range [first, last) to result, which must have room for last - first e...
2,330,850
2,330,919
Correct Way to set maximum double precision for ostringstream
By referring to How do I print a double value with full precision using cout? and What is the meaning of numeric_limits<double>::digits10 I am slightly confused. Shall I used : ss.precision(std::numeric_limits<double>::digits10); or ss.precision(std::numeric_limits<double>::digits10 + 2); to get maximum double preci...
it depend on number of "decimal component" you have in data. std::numeric_limits::digits10 will give the maximum number of "floating component" ios_base::precision specifies the number of digits (decimal + float components) to display. if your decimal component is always less than 100 (-99 to 99), code below always giv...
2,331,005
2,331,292
breakpoints not working after installing valgrind
I just installed valgrind but now my breakpoints dont work in qtcreator. How can I fix this? debug:NO GDB PROCESS RUNNING, CMD IGNORED: -stack-list-arguments 2 0 0
The problem was with QTcreator itself and not Valgrind this was a coincidence that I had added all the possible views for debugger (Debug->Views then select them all) this somehow made most of my code unreachable by breakpoints. Is this a bug or a consequence of the type of views I added?
2,331,023
2,331,044
'static' for c++ class member functions?
Why is the static keyword necessary at all? Why can't the compiler infer whether it's 'static' or not? As follows: Can I compile this function without access to non-static member data? Yes -> static funcion. No -> non-static function. Is there any reason this isn't inferred?
If you expect the compiler to decide on the spot whether it's static or not, how does that affect external source files linking against the header file that just defines the method signatures?
2,331,166
2,331,182
Elementary C++ Type Confusion
I was reading the following text from Stanford's Programming Paradigms class, and I noticed that when the author uses the string class, the constructor does a function call that looks like this: string::string(const char* str) { initializeFrom(str, str + strlen(str)); } If the initializeFrom function takes two cha...
That is called pointer arithmetic. A char* + int results in a char* that is int characters higher in memory.
2,331,293
2,331,310
Get FILE* from fstream
Possible Duplicate: Getting a FILE* from a std::fstream Is there a way to obtain a FILE* from an a iostream derived class? Particularly from an fstream?
No, at least not in a portable way. GCC's libstdc++ has a class called stdio_filebuf that you can use with a stream, and it does allow you to directly get the associated FILE*, but, stdio_filebuf is not a basic_filebuf, and cannot be used with basic_fstream.
2,331,295
2,332,646
Wrote an SDL game using C++ and want to deploy it
I wrote this really simple game in SDL using C++ and now I want to show it to some of my friends who are using Windows. I wrote my program in Ubuntu 9.10 using Code::Blocks. I want to take my source code and make a Windows installer so they can install and play it. How can I go about doing this?
I created an installer using NSIS some time ago. I started out from scratch, and got a reasonable installer in 5-10 minutes, following the examples. Best of all: it's free!
2,331,306
2,331,314
Reusing Memory in C++
Just wondering is this kind of code recommended to increase performance? void functionCalledLotsofTimes() { static int *localarray = NULL; //size is a large constant > 10 000 if (localarray == NULL) localarray = new int[size]; //Algorithm goes here } I'm also curious how static variables are implemente...
It is not recommended because you are introducing global state to a function. When you have global state in a function you have side effects. Side effects cause problems especially in multi threaded programs. See Referential Transparency for more information. With the same input you always want to have the same ou...
2,331,316
2,331,413
What is stack unwinding?
What is stack unwinding? Searched through but couldn't find enlightening answer!
Stack unwinding is usually talked about in connection with exception handling. Here's an example: void func( int x ) { char* pleak = new char[1024]; // might be lost => memory leak std::string s( "hello world" ); // will be properly destructed if ( x ) throw std::runtime_error( "boom" ); delete [] ple...
2,331,407
2,331,417
What is the meaning of a function parameter of type *& in C++?
After reading a description about swapping pointer addresses on Stackoverflow, I have a question about C++ syntax for references. If you have a function with the following signature: void swap(int*& a, int*& b) What is the meaning of int*& ? Is that the address of a pointer to an integer? And furthermore being that it...
A reference to an int pointer. This function would be called as follows: int* a=...; //points to address FOO int* b=...; //points to address BAR swap(a,b); //a now points to address BAR //b now points to address FOO
2,331,557
2,331,683
Declaring namespace as macro - C++
In standard library, I found that namespace std is declared as a macro. #define _STD_BEGIN namespace std { #define _STD_END } Is this a best practice when using namespaces? The macro is declared in Microsoft Visual Studio 9.0\VC\include\yvals.h. But I couldn't find the STL files including this. If it is not i...
Probably not a best practice as it can be difficult to read compared to a vanilla namespace declaration. That said, remember rules don't always apply universally, and I'm sure there is some scenario where a macro might clean things up considerably. "But I couldn't find the STL files including this. If it is not include...
2,331,613
2,335,693
Problem creating a circular buffer in shared memory using Boost
I am trying to create a circular buffer in shared memory using Boost circular_buffer and Interprocess libraries. I compiled and ran the the example given in the Interprocess documentation for creating a vector in shared memory with no problem. However, when I modify it to use the Boost circular_buffer as: int main(int ...
I asked the same question on the boost user forum and the solution that was suggested was to use -DBOOST_CB_DISABLE_DEBUG or -DNDEBUG flags, since circular_buffer relies on raw pointers for debug support. Any other suggestions?
2,331,751
2,331,835
Does the size of an int depend on the compiler and/or processor?
Would the size of an integer depend upon the compiler, OS and processor?
The answer to this question depends on how far from practical considerations we are willing to get. Ultimately, in theory, everything in C and C++ depends on the compiler and only on the compiler. Hardware/OS is of no importance at all. The compiler is free to implement a hardware abstraction layer of any thickness and...
2,331,819
2,331,883
How do I color / texture a 3d object dynamically?
I have a 3D model, composed of triangles. What I want to do is, given a point near to the model, I would like to color the model (triangles) to another color, say blue. Right now, I have a bounding sphere about the model, and when the collision occurs, I just want to approximately color the portions of model from where...
If you just have one or a small number of points to test against, the fastest-to-render method would probably be to write a shader in GLSL that conditionally modifies fragment colors based on world-space distance to your point(s). An alternative that may be simpler if you've never done GLSL programming would be to use ...
2,332,006
2,332,046
Why can't i set a member variable of an interface class as follows
So i have a interface class class interfaceClass { public: virtual void func1( void ) = 0; virtual void func2( void ) = 0; protected: int m_interfaceVar; } and a class that inherits from it. Why can't i set the member variable of the interface class as follows. class inhertitedClass : public interface...
The initializer list in a constructor can specify the ctor for the base classes first and foremost. By depriving interfaceClass of a (protected) constructor (which it obviously should have) you've cut off that lifeline. So add that protected ctor, e.g.: class interfaceClass { public: virtual void func1( void )...
2,332,355
2,332,395
Dom Vs Sax - creating Xmls
I know the difference between Sax and Dom is pretty substantial regarding parsing Xml, but what about creating ones ? is there even a way to create new Xml using Sax or that if i want to create new Xml file based on my data in my program , i will have to use DOM ? Thanks
SAX is, quoting wikipedia : SAX (Simple API for XML) is a serial access parser API for XML. SAX provides a mechanism for reading data from an XML document. i.e. SAX can be great for reading an XML document, but if you want to write one, you'll probably be using DOM.
2,332,455
2,332,478
trying to copy data with memcpy, getting error "Access violation writing location"
I'm getting error on second memcpy memcpy(&check_user, &ZZZ, (int)&main - (int)&check_user); "Unhandled exception at 0x72cc1f57 (msvcr100.dll) in 11.exe: 0xC0000005: Access violation writing location 0x00f31000." What is wrong? #include <stdio.h> #include <tchar.h> #include <windows.h> #include <stdio.h> #include <iost...
OK. It's weird, but I think I get it. You want some code to be "encrypted" via a XOR. You're going to have to do this in a memory buffer you allocate yourself that is read-write and also executable. On Windows you can achieve this with VirtualAlloc() . On Unix you can use mmap() with MAP_ANON. See the protection f...
2,332,545
2,387,162
Fixed/variable length structure in c# and big endian conversion
Struct { byte F1[2] SHORT F2 byte F3[512] } BPD CBD { SHORT CLENGTH byte DATA[] } Above are 2 c++ structure. Here SHORT is of 2 byte signed. What would be the best way to convert it into C#? (Note that in 2nd struture length of DATA is uundefined.) I have seen following two links. Fixed length strings or struct...
Solved myself. Structures are good but if you are not going to modify any data classes are better to use. I have create classes in c# for c++ structure and for big to little endian conversion i have create 3 library functions and it works for me. Thnaks everybody for the valuable input.
2,332,655
2,332,894
Creating internal and external interfaces for a class / information hiding
For some classes of a static C++ library I want to offer different interfaces for the user of the library and for the library itself. An example: class Algorithm { public: // method for the user of the library void compute(const Data& data, Result& result) const; // method that I use only from other c...
The simplest way might be to make setSecretParam() private and make the following a friend of Algorithm: void setSecretParam(Algorithm& algorithm, double aParam) { void setSecretParam(double aParam); }
2,332,690
2,332,775
Can I extract struct or public class members using a template?
Basically, I have lots of differently typed structs like this: typedef struct { char memberA; int memberB; ... } tStructA; Is it possible to use a template to get/extract an arbitrary member from the struct? In pseudocode, I'm looking for something like this: /*This is pseudocode!*/ template <typename STRU...
You can do that not with names but with member pointers: template <typename C, typename M> struct updater_t { typedef M C::*member_ptr_t; updater_t( member_ptr_t ptr, M const & new_value ) : new_value( new_value ), ptr(ptr) {} updater_t( member_ptr_t ptr, C & original ) : new_value( original.*p...
2,332,701
2,333,248
c++ sending image to printer , (PRINT)
this is code which i use to make image. Bitmap bitmap; bitmap.CreateBitmap(715, 844,1,1, NULL); CDC memDC; memDC.CreateCompatibleDC(NULL); memDC.SelectObject(&bitmap); CString SS="Sun Goes Down"; memDC.TextOutA(1,2,SS); CImage image; image.Attach(bitmap); image.Save(_T("C:\\test.bmp"), Gdipl...
Instead of making the image, saving it, then printing it, you should: Create a DC for the printer (see http://msdn.microsoft.com/en-us/library/dd183521%28VS.85%29.aspx) Paint the image on this DC Write or paint whatever you want on the DC Close the DC Look for all the detailed steps on MSDN.
2,332,823
2,333,051
Parameter marshaling protocol homework for RPC call?
I have a homework to build on paper a parameter marshaling protocol to be suited to call a method with one variable, or with an array (like a polymorphism). procedure(var1) procedure(array1) How would you define the protocol? How about the method in C++
You could try to make the functions with Object parameters. i.e void myFunction(void* param, int paramType) { if(paramType == definedTypes[0] ) { // do stuff } else if(paramType == definedTypes[1]) { //do something else } } you pass 2 parameters: in the first your object, in the second the type of your object, you h...
2,332,861
2,332,900
Terminating because of 6 signal
I compiled and ran my code and got the following error: Terminating because of 6 signal What is signal 6 and what causes it?
It's probably talking about signal 6, which is SIGABRT, i.e. abort. The code itself most likely called abort(), or perhaps an assert failed. You can list the signal numbers from the command line using kill -l HTH.
2,333,233
2,349,726
Window handling manager
I have a Windows box that is running three applications. When the applications are started each application creates a borderless window which is positioned such that they overlap in a particular way. At the moment, when I click on a control on the bottom window, it comes to the top of the window stack. I need to ensur...
Instead of MSalter's approach trying to DLL injection into each of the running the application, consider installing a WH_CBT Windows hook. In your CBTProc, return 0 when you get a HCBT_MOVESIZE for the three application window handles you care about. Read MSDN for the docs on CBTProc and SetWindowsHookEx.
2,333,302
2,333,804
What are the C# equivalent of these C++ structs
typedef union _Value { signed char c; unsigned char b; signed short s; unsigned short w; signed long l; unsigned long u; float f; double *d; char *p; } Value; typedef struct _Field { WORD nFieldId; BYTE bValueType; Value Value; }...
I'm assuming the 'char' is being used as an 8 bit number, if so, then here are you're mappings: signed char c; -> SByte c; unsigned char b; -> Byte b; signed short s; -> Int16 s; unsigned short w; -> UInt16 w; signed long l; -> Int32 l; unsigned long u; -> UInt32 u; float f; -> Sing...
2,333,321
2,334,854
Most portable and reliable way to get the address of variable in C++
Using & to get an address of a variable can be problematic if the variable type has overloaded operator&(). For example, _com_ptr_ has operator&() overloaded with a side effect of modifying the object. Now I have a complicated set of templates with functions like this: template<class T> void process( const T* object ) ...
It is standard-complaint. The issue was brought to the attention of the ISO C++ committee in relation to problems with offsetof implementations that broke on this. Amongst the solutions considered were tightening the POD definition, or adding an extra restriction on types to be used with offsetof. Those solutions were ...
2,333,366
2,333,390
Search and replace with regular expressions under Visual Studio 2003
I have a large C++ code base that I'm doing some refactoring on where a number of functions have become redundant, and hence should be removed. So I would like to replace MyFunc(Param) with Param where Param could be a literal value, variable, function call etc... From the online help I gathered that the search par...
Try this instead: Find = MyFunc\({[^\)]*}\) Replace = \1 Your slashes are the wrong way around and the expression in the parenthesis ({+}) is invalid. This won't work for parameters that contain function calls or other uses of parentheses - the balanced bracket matching problem isn't solveable using regular expressions...
2,333,574
2,333,621
Is there pointer in C# like C++? Is it safe?
I'm writing an application that work with a tree data structure. I've written it with C++, now i want to write it by C#. I use pointers for implementing the tree data structure. Is there a pointer in C# too? Is it safe to use it?
If you're implementing a tree structure in C# (or Java, or many other languages) you'd use references instead of pointers. NB. references in C++ are not the same as these references. The usage is similar to pointers for the most part, but there are advantages like garbage collection. class TreeNode { private TreeNo...
2,333,625
2,333,721
boost lexical_cast throws exception
I'm using boost libs for c++ and the function lexical_cast behaves really weird. If I do lexical_cast("0.07513994") it works fine, but if I use my variable which I need to convert, it throws the bad_lexical_cast exception. Here is the code: string word; istringstream iss(line); do { string word; iss >> word; ...
Your problem is probably that the loop is processed one more time than you expect. The last time through the loop, the read to word fails, setting the fail bit in iss, which is what while(iss) is checking. To fix it you need to do something like this. string word; istringstream iss(line); do { string word; iss >>...
2,333,666
2,333,690
What's the purpose of boost::detail::addr_impl_ref?
Inside boost there's boost::detail::addr_impl_ref struct that basically has a constructor accepting a T& reference and an overloaded operator T&() that returns that reference. It is used in the implementation of boost::addressof(): template<class T> T* addressof( T& v ) { return boost::detail::addressof_impl<T>::f(...
It prevents other implicit conversion operators of T to be a part of the conversion. EDIT: For instance: struct foo { operator foo*() { return 0; } };
2,333,728
2,333,816
std::map default value
Is there a way to specify the default value std::map's operator[] returns when an key does not exist?
No, there isn't. The simplest solution is to write your own free template function to do this. Something like: #include <string> #include <map> using namespace std; template <typename K, typename V> V GetWithDef(const std::map <K,V> & m, const K & key, const V & defval ) { typename std::map<K,V>::const_iterator it...
2,333,827
2,333,981
C C++ - TCP Socket Class : Receive Problem
I did my own Socket class, to be able to send and receive HTTP requests. But I still got some problems. The following code (my receive function) is still buggy, and crashing sometimes. I tried debugging it, but it must be somewhere in the pointer arithmetics / memory management. int Socket::Recv(char *&vpszRecvd) { /...
You don't initialise temp and, on top of that, your call to realloc is wrong. It should be: temp = realloc (temp, recvsize+1); When you call realloc as you have, you throw away the new address and there's a good chance that the old address has now been freed. All bets are off when you then try to dereference it. The r...
2,333,848
2,342,036
Can't modify value returned by time.time() in Python code embedded in C++
I'm facing a very strange problem. The following code: import time target_time = time.time() + 30.0 doesn't work in Python code called from C++ (embedding)! target_time has the same value as time.time() and any attempt to modify it leaves the value unchanged in a pdb console... alt text http://dl.dropbox.com/u/3545118...
Found the answer in that thread: http://www.ogre3d.org/forums/viewtopic.php?f=1&t=55013&p=373940&hilit=D3DCREATE_FPU_PRESERVE#p373940 http://msdn.microsoft.com/en-us/library/ee416457%28VS.85%29.aspx D3DCREATE_FPU_PRESERVE Set the precision for Direct3D floating-point calculations to the precision used by the calling t...
2,333,952
2,334,011
G++ 4.4 compile error, lower versions works
I have my program written in C++ and it is can be successfully compiled on Ubuntu 9.04 with g++ 4.3.4 and Solaris OS with g++ 3.4.3. Now I have upgraded my Ubuntu to version 9.10 and g++ to version 4.4.1. Now compiler invokes the error in STL. /usr/include/c++/4.4/bits/stl_deque.h: In member function ‘void std::deque<_...
#include <algorithm>
2,333,960
2,334,078
Why and when is cast to char volatile& needed?
In boost::detail::addressof_impl::f() a series of reinterpret_casts is done to obtain the actual address of the object in case class T has overloaded operator&(): template<class T> struct addressof_impl { static inline T* f( T& v, long ) { return reinterpret_cast<T*>( &const_cast<char&>(rein...
A cast straight to char& would fail if T has const or volatile qualifiers - reinterpret_cast can't remove these (but can add them), and const_cast can't make arbitrary type changes.
2,334,024
2,774,330
How to know if the Kerberos ticket has expired
I have a client side application that uses Kerberos authentication to connect to remote service. When reseting the password for the SPN in ADSI without renewing the ticket, the authentication fails (of course). The question is, if there is a way to know in advance that the ticket is not valid\ expired.
Call LsaCallAuthenticationPackage with the message type KerbQueryTicketCacheMessage. Run over the returned KERB_QUERY_TKT_CACHE_RESPONSE Tickets[Index].EndTime and compare it with the current time (You can refer to the EndTime as a TimeStamp). That's all.
2,334,148
2,334,172
Is there any real point compiling a Windows application as 64-bit?
I'd confidently say 99% of applications we write don't need to address more than 2Gb of memory. Of course, there's a lot of obvious benefit to the OS running 64-bit to address more RAM, but is there any particular reason a typical application would be compiled 64bit?
There are performance improvements that might see with 64-bit. A good example is that some parameters in function calls are passed via registers (less things to push on the stack). Edit I looked up some of my old notes from when I was studying some of the differences of running our product with a 64-bit build versus a...
2,334,280
2,334,313
Return a float array in C++
I currently have a 4x4 matrix class in C++ and I store each value as a float: Matrix4d::Matrix4d(const float& m00, const float& m01, const float& m02, const float& m03, const float& m10, const float& m11, const float& m12, const float& m13, const float& m20, const float& m21, const...
This would work if your internal array looked like float array[4][4]: float** Matrix4d::getMatrix(); If your internal array was a one-dimensional array: float* Matrix4d::getMatrix(); But both cases expose the internal workings of your class to the outside world, with makes your code less safe and harder to maintain. ...
2,334,364
2,334,413
Read write mutex in C++
This is an interview question. How do you implement a read/write mutex? There will be multiple threads reading and writing to a resource. I'm not sure how to go about it. If there's any information needed, please let me know. Update: I'm not sure if my statement above is valid/understandable. But what I really want to ...
Check out Dekker's algorithm. Dekker's algorithm is the first known correct solution to the mutual exclusion problem in concurrent programming. The solution is attributed to Dutch mathematician Th. J. Dekker by Edsger W. Dijkstra in his manuscript on cooperating sequential processes. It allows two threa...
2,334,370
2,334,459
Is it possible to implment a COM interface without creating a custom interface?
I am learning c++ and I am trying to better understand it. I was reading the msdn documents on how to use xml lite. it said that I must use a class that implements the IStream interface. It said to declare and instantiate my class that extends Istream and use CComPtr when declaring the varible. then it showed me the fo...
if CComptr is used to pull the xml. why do I have to extend . Why not just have CComptr already implement IStream and just call CComptr? IStream is an interface -- saying "I want some class which implements this interface" does not tell how you want to actually get the data. CComPtr is only a pointer to a coclass which...
2,334,396
2,334,447
-fomit-frame-pointer, is it safe to use it?
I've seen in many places that people often use the option -fomit-frame-pointer when compiling C / C++ code and I wonder, is the use of that option safe? What is it used for? Thank you very much, best regards.
The option is safe but makes debugging harder. Normally, the C compiler outputs code which stores in a conventional register (ebp on x86) a pointer to the stack frame for the function. Debuggers use that to print out local variable contents and other such information. The -fomit-frame-pointer flag instructs gcc not to ...
2,334,673
2,334,724
QWidget's paintEvent() lagging application
i'm studying and modifying the fridge magnets example, and the last thing I've tried to do was to draw a few labels and lines that are supposed to be on the background. After looking around trying to figure out how to draw the labels and lines, I learned that I could override QWidget's paintEvent() to do it. After I di...
You are adding Objects to the Widget Tree during paintEvent(). That is deemed to fail. The Qt scheduler for damage&drawing will see that a new child has to be drawn and try to manage that and likely the loop is the result. If you override paintEvent(), do all the painting in the same object! Golden rule: paintEvent() i...
2,334,735
2,334,815
C++: what benefits do string streams offer?
could any one tell me about some practical examples on using string streams in c++, i.e. inputing and outputing to a string stream using stream insertion and stream extraction operators?
You can use string streams to convert anything that implements operator << to a string: #include <sstream> template<typename T> std::string toString(const T& t) { std::ostringstream stream; stream << t; return stream.str(); } or even template <typename U, typename T> U convert(const T& t) { std::stringstream...
2,334,966
2,335,079
win32 application aren't so object oriented and why there are so many pointers?
This might be a dumb question to some of you and maybe I asked this question wrong, because I am new to C++. But I notice when working in a lot of Win32 applications, you use a lot of resources that are pointers. Why do you have to always acquire a objects pointer? Why not initiate a new instance of the class. and spea...
Windows APIs were designed for C, which was and still is the most used language for system programming; C APIs are the de-facto standard for system APIs, and for this almost all other languages had and have some way to call external C functions, so writing a C API helps to be compatible with other languages. C APIs nee...
2,334,991
2,335,202
How to enumerate system restore points using WinAPI (not WMI)?
Must work for WinXp - Vista - Windows 7
After having a short look at the available documentation it seems that there is no way around WMI if you want to list existing restore points. The Windows API only offers you functions for setting and removing restore points: SRSetRestorePoint, and SRRemoveRestorePoint MSDN also has samples how to use these methods. ...
2,335,011
2,335,074
Why doesn't my overloaded comma operator get called?
I'm trying to overload the comma operator with a non-friend non-member function like this: #include <iostream> using std::cout; using std::endl; class comma_op { int val; public: void operator,(const float &rhs) { cout << this->val << ", " << rhs << endl; } }; void operator,(const float &lhs,...
void operator,(const float &rhs) You need a const here. void operator,(const float &rhs) const { cout << this->val << ", " << rhs << endl; } The reason is because rhs, lhs will call rhs.operator,(lhs) Since rhs is a const comma_op&, the method must be a const method. But you only provide a non-const operator,, ...
2,335,030
2,335,948
visual C++ express 2010 and setting env variables solution wide
I'm C++ dev migrating to visual 2010 c++ from vim/g++. Here blog I've read that VC++ directories are no more and that I should use property pages in vs 2010 but I don't know how... Here is what I need to do. I have w solution (50 projects strong) and all of them use boost, pthreads, xercesc and few other libs. I have e...
The answer to your question is also in the blog that you linked to, but it's mentined in a kind of round about way: If you open up the Property Manager view to see the property sheets associated with your project, you’ll see that one of the property sheets is named Microsoft.Cpp.Win32.User. This property sheet is actu...
2,335,091
2,343,219
How do I get Doxygen to "link" to enum defintions?
I have the following code: /// \file Doxygen_tests.h /** * * \enum Tick_Column_Type * * \brief Values that represent Tick_Column_Type. **/ enum Tick_Column_Type { TC_OPEN, ///< Opening price TC_HIGH, ///< High price TC_MAX, ///< Required as last enum marker. }; /** ...
From the docs (Automatic Link Generation): One needs to change from ///< The data. Indexed by Tick_Column_Type. to ///< The data. Indexed by ::Tick_Column_Type.
2,335,320
2,335,365
Problem with iostream, my output endl are littles squares
I have a problem with with my output when I write to I file I get squares when I put endl to change lines. std::ofstream outfile (a_szFilename, std::ofstream::binary); outfile<<"["<<TEST<<"]"<<std::endl; I get something like this in my file plus the other outputs don't write on the next line but on the same one. [TE...
You don't really want to open the file in binary mode in this case. Try this instead: std::ofstream outfile (a_szFilename); outfile<<"["<<TEST<<"]"<<std::endl;
2,335,335
2,335,506
Help with rake dependency mapping
I'm writing a Rakefile for a C++ project. I want it to identify #includes automatically, forcing the rebuilding of object files that depend on changed source files. I have a working solution, but I think it can be better. I'm looking for suggestions for: Suggestions for improving my function Libraries, gems, or tools ...
Use the gcc command to generate a Make dependency list instead, and parse that: g++ -M -MM -MF - inputfile.cpp See man gcc or info gcc for details.
2,335,530
2,337,397
Unable to instantiate function templates which uses decltype to deduce return type, if called from inside a lambda?
I'm trying to use C++0x, and in particular lambda expression and decltype to simplify some of my code, using the MSVC10 RC compiler. I've run into the following very odd problem: template <typename F> auto foo(F f) -> decltype(f()){ return f(); } template <typename F> void bar(F f){ f(); } int main() { bar([]()...
These are just some test cases for people to observe. Works template <typename F> auto foo(F f) -> decltype(f()) { return f(); } void dummy() {} int main() { auto x = []() { // non-lambda parameter foo(dummy); }; } template <typename F> auto foo(F f) -> decltype(f()) ...
2,335,657
2,336,130
Prevent scientific notation in ostream when using << with double
I need to prevent my double to print in scientific notation in my file, when I do this outfile << X;
To set formatting of floating variables you can use a combination of setprecision(n), showpoint and fixed. In order to use parameterized stream manipulators like setprecision(n) you will have to include the iomanip library: #include <iomanip> setprecision(n): will constrain the floating-output to n places, and once yo...
2,336,027
2,336,038
Why check if (*argv == NULL)?
In the data structures class that I am currently taking, we have been tasked with writing a web crawler in C++. To give us a head start, the professor provided us with a program to get the source from a given URL and a simple HTML parser to strip the tags out. The main function for this program accepts arguments and so...
argc will provide you with the number of command line arguments passed. You shouldn't need to check the contents of argv too see if there are not enough arguments. if (argc <= 1) { // The first arg will be the executable name // print usage }
2,336,054
2,336,070
Find pointers from pointee
From this code: int x = 5; int other = 10; vector<int*> v_ptr; v_ptr.push_back(&x); v_ptr.push_back(&other); v_ptr.push_back(&x); Is there anyway I can know who points at x, from the x variable itself, so that I don't have to search inside v_ptr for address of x? Is this possible in C++ or C++0x? I read that when d...
No. It is like asking a person if they know everyone who knows their address.
2,336,075
2,336,209
What web server interface to choose?
I'm in the process of planning a web service, which will be written in C++. The goal is to be able to select more or less any web server to drive the service. For this to become true, I obviously have to choose a standardized interface between web servers and applications. Well known methods that I've heard of are: ...
WSGI is for Python apps; if your language is C++ this isn't an option. FCGI is a good way to go. An FCGI can be invoked as a standard CGI, convenient for debugging and testing, then run as an FCGI in production. Performance of CGI vs. FCGI depends a lot on what you're trying to do and the amount of traffic you expect. ...
2,336,107
2,336,314
Are there cases where a class declares virtual methods and the compiler does not need to use a vptr?
I was wondering if there is a possible optimization where the compiler does not need to assign a vptr to an instantiated object even though the object's type is a class with virtual methods. For example consider: #include <iostream> struct FooBase { virtual void bar()=0; }; struct FooDerived : public FooBase { vir...
Building on Andrew Stein's answer, because I think you also want to know when the so-called "runtime overhead of virtual functions" can be avoided. (The overhead is there, but it's tiny, and rarely worth worrying about.) It's really hard to avoid the space of the vtable pointer, but the pointer itself can be ignored, ...
2,336,144
2,336,369
How to Access/marshall char *variable from dll import in C#
I need to access functionality from win32 dll , for that I am using [dllimport] in C# code. what exact method signature i need to create with [dllimport] for the following c++ methods void GetGeneratedKey(char *code, int len, char *key) pls help in this. Thanks nRk
This depends highly on what is happening to the variables key and code in the native C function. Based on the signature I am guessing that code is being read from and key is being written to. If that is the case then try the following signature [DllImport("SomeDll")] public static extern void GetGeneratedKey( [In] ...
2,336,211
2,341,156
Adding Boost Library to a C++ project in Windows Eclipse
I recently installed the Boost Library on Windows using the installer, I'm trying to link to the library in Eclipse but am not having any luck. I tried going through Project Properties -> C/C++ Build -> Settings -> MinGW C++ Linker -> Libraries and add the reference "boost_filesystem" according to this website: http:/...
I think Eclipse for Visual Studio C++ Developers ( also has explanations for boost library) ) is what you needed..
2,336,230
2,336,251
Difference between const. pointer and reference?
What is the difference between a constant pointer and a reference? Constant pointer as the name implies can not be bound again. Same is the case with the reference. I wonder in what sort of scenarios would one be preferred over the other. How different is their C++ standard and their implementations? cheers
There are 3 types of const pointers: //Data that p points to cannot be changed from p const char* p = szBuffer; //p cannot point to something different. char* const p = szBuffer; //Both of the above restrictions apply on p const char* const p = szBuffer; Method #2 above is most similar to a reference. There are ke...
2,336,268
2,338,393
How do I know which thread called a method
I have a threadSafe method that gets called by multiple threads. Is there a way to know which thread called it?
Well, you know the thread that calls the method, and by extension the same thread will be active inside that method call. You can just call QThread::currentThread() to get this.
2,336,342
2,336,974
Using Boost Graph Library on Mac Eclipse
I have a similar question regarding using Boost under Windows. I'm very new to Boost and I just installed the Boost library on my Mac, I'm interested primarily in the Boost Graph Library. My questions are as follows, when installing Boost by default on my Mac, is the BGL installed automatically as well? I ask this be...
I have used the Boost Graph Library on Windows and on several Unix flavors, but not on Mac. But I think my comments are relevant nevertheless. You are confusing the library being installed with the library being built. When you installed Boost on the Mac, the BGL is also "installed", in the sense that the BGL headers a...
2,336,345
2,336,372
what happens when tried to free memory allocated by heap manager, which allocates more than asked for?
This question was asked to me in an interview. Suppose char *p=malloc(n) assigns more than n,say N bytes of memory are allocated and free(p) is used to free the memory allocated to p. can heap manager perform such faulty allocation ? what happens now, will n bytes are freed or N bytes are freed? is there any method to...
Yes, that's what happens almost every time do you a malloc(). The malloc block header contains information about the the size of the block, and when free() is called, it returns that amount back to the heap. It's not faulty, it's expected operation. A simple implementation might, for instance, store just the size of ...
2,336,368
2,336,473
error C2228: left of '.DXGI_MODE' must have class/struct/union Direct X
I am trying to setup my swap chain Buffer but I get the following error error C2228: left of '.DXGI_MODE' must have class/struct/union 1> type is 'DXGI_MODE_SCANLINE_ORDER' Note sure what I am doing wrong. here is the code DXGI_SWAP_CHAIN_DESC swapChainDesc; // Set the width and height of the buffers in th...
Shouldn't this bit swapChainDesc.BufferDesc.ScanlineOrdering.DXGI_MODE; //_SCANLINE_ORDER_UNSPECIFIED; in fact be swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; ?
2,336,454
2,336,655
What is the use of member template functions in c++?
Given a class with a member template function like this one: template <typename t> class complex { public: complex(t r, t im); template<typename u> complex(const complex<u>&); private: //what would be the type of real and imaginary data members here. } I am confused about member template functions, ple...
The general purpose and functionality of member function templates is in no way different from that of ordinary (non-member) function templates. The only [irrelevant] difference is that member functions have access to the implicit this parameter. You understand the general purpose of ordinary function templates, do you...
2,336,952
2,337,007
Preprocessor syntax to use an #define as an identifier (function name) and a string
I'm not sure if this is possible, but I would like to create a shared object file and I would like to make it easy to use by having a #define that can be used to dereference the function names. In libfoo.h #define FOO_SO_FUNCTION_A aFunction In libfoo.so #include "libfoo/libfoo.h" extern "C" int FOO_SO_FUNCTION_A(...
Use this: #define REALLY_MAKE_STRING(x) #x #define MAKE_STRING(x) REALLY_MAKE_STRING(x) Due to some details of the rules when exactly the preprocessors substitutes macros, an extra level of indirection is required.
2,337,006
2,337,288
Using make for my program
I have a bunch of files in different folders: /ai/client.cpp # contains the main function /ai/utils/geometry.h /ai/utils/geometry.cpp /ai/world/world.h /ai/world/world.cpp /ai/world/ball.h /ai/world/ball.cpp /ai/world/bat.h /ai/world/bat.cpp How do I write a makefile to compile this program? I'm using Ubuntu....
Make is a versatile tool, and there are many different subtleties to using it. However, you can keep things simple: OBJ := ai/utils/geometry.o ai/world/world.o ai/world/ball.o ai/world/bat.o all: ai/client .PHONY: all # specific to GNU make, which is what Ubuntu provides ai/client: ai/client.o $OBJ # this rule mea...
2,337,061
2,337,115
Can marshalling or packing be implemented by unions?
In beej's guide to networking there is a section of marshalling or packing data for Serialization where he describes various functions for packing and unpacking data (int,float,double ..etc). It is easier to use union(similar can be defined for float and double) as defined below and transmit integer.pack as packed vers...
Different computers may lay the data out differently. The classic issue is endianess (in your example, whether pack[0] has the MSB or LSB). Using a union like this ties the data to the specific representation on the computer that generated it. If you want to see other ways to marshall data, check out the Boost serial...
2,337,139
2,337,741
Where is a file mounted?
Given a path to a file or directory, how can I determine the mount point for that file? For example, if /tmp is mounted as a tmpfs filesystem then given the file name /tmp/foo/bar I want to know that it's stored on a tmpfs rooted at /tmp. This will be in C++ and I'd like to avoid invoking external commands via system()...
This is what I've come up with. It turns out there's usually no need to iterate through the parent directories. All you have to do is get the file's device number and then find the corresponding mount entry with the same device number. struct mntent *mountpoint(char *filename, struct mntent *mnt, char *buf, size_t bufl...
2,337,142
2,337,160
Does the typename keyword exist in C++, for backwards compatibility with “C templates?”
I’m taking a C++ class, and my teacher mentioned in passing that the typename keyword existed in C++ (as opposed to using the class keyword in a template declaration), for backwards compatibility with “C templates.” This blew my mind. I’ve never seen or heard tell of anything like C++’s templates (except, perhaps, the ...
I think your teacher is off base. See Stan Lippman's post: Why C++ Supports both Class and Typename for Type Parameters for the real reason why C++ supports both.
2,337,213
2,337,234
return value of operator overloading in C++
I have a question about the return value of operator overloading in C++. Generally, I found two cases, one is return-by-value, and one is return-by-reference. So what's the underneath rule of that? Especially at the case when you can use the operator continuously, such as cout<<x<<y. For example, when implementing a + ...
Some operators return by value, some by reference. In general, an operator whose result is a new value (such as +, -, etc) must return the new value by value, and an operator whose result is an existing value, but modified (such as <<, >>, +=, -=, etc), should return a reference to the modified value. For example, cout...
2,337,446
2,338,527
Is it ok to use a static variable to initialize/register variables?
Language: C++ Toolkit: Qt4 The toolkit I'm using has a static method called int QEvent::registerEventType() to register my own event types. When I subclass this QEvent I need to supply the base class this value. QEvent::QEvent(int type). Is it ok to use a static variable to call this before application starts? Consider...
Static level initialization is a huge compiler-dependent grey area, as others have mentioned. However, function level initialization is not a grey area and can be used to your advantage. static inline int GetMyEventType() { static int sEventType = QEvent::registerEventType(); return sEventType; } MyEvent::MyEv...
2,337,540
2,337,575
When should you use the "this" keyword in C++?
Possible Duplicates: Is excessive use of this in C++ a code smell Years ago, I got in the habit of using this-> when accessing member variables. I knew it wasn't strictly necessary, but I thought it was more clear. Then, at some point, I started to prefer a more minimalistic style and stopped this practice... Recen...
While this is a totally subjective question, I think the general C++ community prefers not to have this->. Its cluttering, and entirely not needed. Some people use it to differentiate between member variables and parameters. A much more common practice is to just prefix your member variables with something, like a sing...
2,337,679
2,340,532
Why can't I run AssaultCube built from source?
a error with open source. I have been playing AssaultCube for about 2 weeks and I found that it is open source. I downloaded from SourceForge and I got everything to compile but... It could not find 3 .DLL(libvorbisfile.dll, libogg.dll, libvorbis.dll) files so I downloaded them and put them in \windows\. Now i get the ...
It's important to get the spelling right, and I don't know who made the mistake here. The actual function name is vorbis_synthesis_halfrate not vorvis_synthesis_halfrate. (B not V). Googling that turns up quite a few results. It's indeed a "recent" function, and older Vorbis versions don't have it. GMan's answer (which...
2,337,730
2,337,792
Best tools for analyzing dll loads conditions in Visual Studio for C++
I am using Visual Studio 2008 to run an application, which loads a number of DLL's at startup, that immediately exits with "The program '[3668] cb_tcl.exe: Native' has exited with code -1072365566 (0xc0150002)." Unfortunately I get no other clues about the source of the problem and the exit occurs before the program s...
I'm not positive this is what you are looking for, but Dependency Walker is very helpful for me in situations like this.
2,337,810
2,338,117
Minimal number of steps needed to turn all binary bits to one state
There is an array of M binary numbers and each of them is in state '0' or '1'. You can perform several steps in changing the state of the numbers and in each step you are allowed to change the state of exactly N sequential numbers. Given the numbers M, N and the array with the members of course, you are about to calcul...
If I've understood the question correctly, a little bit of thought will convince you that even dynamic programming is not necessary — the solution is entirely trivial. This is the question as I understand it: you are given an array a[1]..a[M] of 0s and 1s, and you are allowed operations of the form Sk, where Sk means t...
2,338,049
2,338,410
Inheriting off of a list of templated classes, when supplied with the list of template arguments
I'm trying to write some metaprogramming code such that: Inheriting from some class foo<c1, c2, c3, ...> results in inheritance from key<c1>, key<c2>, key<c3>, ... The simplest approach doesn't quite work because you can't inherit from the same empty class more than once. Handling the "..." portion isn't pretty (since...
Without you saying what you actually want to achieve, this is a mostly academic exercise... but here is one way how you'd use MPL to inherit linearly: template<class T> struct key { enum { value = T::value }; char getKey() { return value; } }; template<class Values> struct derivator : mpl::inherit_linearl...
2,338,169
2,338,203
C++ using 'this' as a parameter
I have a class which looks approximately like this: class MeshClass { public: Anchor getAnchorPoint(x, y) { return Anchor( this, x, y ); } private: points[x*y]; } I want to make another class which represents an "Anchor" point which can get access to the Mesh and modify the point, like this: clas...
In C++, this is a pointer, not a reference. You could do something like this: class Anchor; //forward declaration class MeshClass { public: Anchor getAnchorPoint(int x, int y) { return Anchor(*this, x, y ); } private: int points[WIDTH*HEIGHT]; } class Anchor { public: Anchor(MeshClass &mc...
2,338,195
2,338,207
Is it possible to have a common pointer between 2 different programs on the same computer
I need 2 different programs to work on a single set of data. I have can set up a network (UDP) connection between them but I want to avoid the transfer of the whole data by any means. It sounds a little absurd but is it possible to share some kind of pointer between these two programs so that when one updates it the ot...
You're talking about IPC - Interprocess Communication. There are many options. One is a memory-mapped file. It comes close to doing what you described. It may or may not be the optimal approach for your requirements, though. Read up on IPC to get some depth.
2,338,377
2,338,596
What use is there for 'ends' these days?
I came across a subtle bug a couple of days ago where the code looked something like this: ostringstream ss; int anInt( 7 ); ss << anInt << "HABITS"; ss << ends; string theWholeLot = ss.str(); The problem was that the ends was sticking a '\0' into the ostringstream so theWholeLot actually looked like "7HABITS\0" (i.e...
You've essentially answered your own question is as much detail that's needed. I certainly can't think of any reason to use std::ends when std::string and std::stringstream handle all that for you. So, to answer your question explicitly, no, there is no reason to use std::ends in a std::string only environment.
2,338,402
2,338,985
faster implementation of sum ( for Codility test )
How can the following simple implementation of sum be faster? private long sum( int [] a, int begin, int end ) { if( a == null ) { return 0; } long r = 0; for( int i = begin ; i < end ; i++ ) { r+= a[i]; } return r; } EDIT Background is in order. Reading latest entry on codin...
I don't think your problem is with the function that's summing the array, it's probably that you're summing the array WAY to frequently. If you simply sum the WHOLE array once, and then step through the array until you find the first equilibrium point you should decrease the execution time sufficiently. int equi ( int[...
2,338,612
2,338,632
Confusing use of a comma in an 'if' statement
I have this piece of code in C++: ihi = y[0]>y[1] ? (inhi=1,0) : (inhi=0,1); But how would it look in C#?
It means this: if (y[0]>y[1]) { inhi = 1; ihi = 0; } else { inhi = 0; ihi = 1; } Or written another way (in C++): inhi = (y[0]>y[1]); ini = !inhi;
2,338,708
2,338,761
Skip compile-time symbol resolution when building Linux shared libraries with dependencies
Is there a gcc flag to skip resolution of symbols by the compile-time linker when building a shared library (that depends on other shared libraries)? For some reason my toolchain is giving undefined reference errors when I try to build shared library C that depends on B.so and A.so, even though the dependencies are spe...
I think you're looking for --allow-shlib-undefined. From the ld man page: --allow-shlib-undefined --no-allow-shlib-undefined Allows (the default) or disallows undefined symbols in shared libraries. This switch is similar to --no-undefined except that it determines the behaviour when the undefined symbols...
2,338,740
2,357,941
how to specify Qt plugin constructor?
I wonder if it is possible to specify a constructor in a Qt plugin interface? (extending an app) I want to force the plugins using the interface to take a parameter in the constructor.
I don't think that it's possible to do exactly what you described. However, you might try to create factory object and then pass parameters to YourFactory::create() method, which returns pointer to YourObject. Another (uglier IMHO) way is to add initialize() method to YourObject. Check interfaces of QFontEnginePlugin ...
2,338,775
2,338,857
How do I write a web server in C/C++ on linux
I am looking into developing a small (read:rudimentary) web server on a linux platform and I have no idea where to start. What I want it to be able to do is: Listen on a specific port Take HTTP post and get requests Respond appropriately No session management required Has to be in C or C++ Has to run as a service on b...
From top-down, you'll need to know about: HTTP Protocol TCP server - BSD socket programming writing a basic Unix daemon (persistent service) process management (fork) parsing text (read a configuration text file) file handling (I/O) debugging C / C++ programming :) So you will have to learn about writing a basic Unix...
2,338,827
2,338,896
Reading formatted data with C++'s stream operator >> when data has spaces
I have data in the following format: 4:How do you do? 10:Happy birthday 1:Purple monkey dishwasher 200:The Ancestral Territorial Imperatives of the Trumpeter Swan The number can be anywhere from 1 to 999, and the string is at most 255 characters long. I'm new to C++ and it seems a few sources recommend extracting for...
You can read the number before you use std::getline, which reads from a stream and stores into a std::string object. Something like this: int num; string str; while(cin>>num){ getline(cin,str); }
2,338,875
2,338,945
Boost::function error ambiguous overload for ‘operator[]’
The full error I'm getting is this: error: ambiguous overload for ‘operator[]’ in ‘a[boost::_bi::storage4<A1, A2, A3, boost::arg<I> >::a4_ [with A1 = boost::_bi::value<MsgProxy*>, A2 = boost::arg<1>, A3 = boost::arg<2>, int I = 3]]’ It references line 116 of a class I have, which is the boost::bind call in this ...
t_icsend_callback is a function taking 2 agruments. boost::bind(&MsgProxy::handle_dispatch, this, _1, _2, _3) returns a function that takes 3 arguments. I think you want to say message->async_send(*iter, boost::bind(&MsgProxy::handle_dispatch, this, message, _1, _2)); (note "message" as first bounded a...
2,338,894
2,338,901
How to invoke C compiler under gcc
According to my memory the following piece of code should compile fine on C++ but not in C. Only problem is how to test it? It compiled fine with g++ and also with gcc. I'm assuming that g++ is C++ compiler and gcc is C compiler. I've tried it with mingw under Windows. Am I correct? if not then how to compile it using ...
No, that will compile in C99, which has support for variable length arrays. To get strict C89 behavior, try compiling with: gcc -std=c89 -pedantic-errors That gives: error: ISO C90 forbids variable length array ‘array’ c89 means use C89, pedantic-errors means error on non-C89 code.
2,339,027
2,339,065
How to use an int as an array of ints/bools?
I noticed while making a program that a lot of my int type variables never went above ten. I figure that because an int is 2 bytes at the shortest (1 if you count char), so I should be able to store 4 unsigned ints with a max value of 15 in a short int, and I know I can access each one individually using >> and <<: sh...
First, remember the Rules of Optimization. But this is possible in C or C++ using bitfields: struct mystruct { unsigned int smallint1 : 3; /* 3 bits wide, values 0 -- 7 */ signed int smallint2 : 4; /* 4 bits wide, values -8 -- 7 */ unsigned int boolean : 1; /* 1 bit wide, values 0 -- 1 */ }; It's wo...