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 a vector of indexes for each dimension in the array. The leftmost (most significant) dimension is alIndex[0].
This made me think that, to get to the same element, one would need to reverse the order of the indices in a multidimensional array. However, I have not found this to be the case in practice.
Am I misusing this interface and getting lucky, misunderstanding the documentation, or is this possibly an error in the docs?
| 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.year = 1999;
tempCar.fee = 20.5;
Compiler keeps saying tempCar is of type car*. I'm not sure what I'm doing wrong
| 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 questions:
1.) Is there a reason that this option is not offered in the MultiDim method?
2.) The docs don't specify if the referenced variable is copied. Is it copied implicitly?
(In my case I would like it not to be copied, since it is a temporary wrapper for a VARIANT type that could be 'Detach'd after setting it into the array)
| 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 code that defines the symbol or you've forgotten to include the object file with that symbol into your library.
In your case it looks like a symbol from your implementation's C library so you would expect that to be undefined in your own library. It will be defined in your libc.so wherever that is, possibly /usr/lib.
|
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 error.
What am I missing here?
EDIT: I knew it had to be right in front of me, but there was nothing else wrong in the file. it was the semicolon at the end of an included class. Thanks.
| 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 working with C++, wxWidgets and wxFormBuilder.
| 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 panels you want to add
wxWindow * pPanel3; // they can be wxPanel's or any window
// Add the panels to the window
pManager->AddPane(pPanel1,wxAuiPaneInfo().Top());
pManager->AddPane(pPanel2,wxAuiPaneInfo().Centre());
pManager->AddPane(pPanel3,wxAuiPaneInfo().Bottom());
Hopefully this works for you.
|
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 throws an exception. This causes my program to explode without giving the user any useful output... is there some way I can catch the exception so I can log it?
| 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 SomeOtherClass MyVariable(someOtherFunction());
return MyVariable;
}
This way, the exception will be throw only on first use, and yet the object will be const.
This is quite a powerful idiom to delay execution. It had a little overhead (basically the compiler checks a flag each time it enters the method), but better worry about correctness first ;)
If this is called from multiple threads:
if your compiler handles it, fine
if your compiler does not, you may be able to use local thread storage (it's const anyway)
you could use boost::once in the Boost.Threads library
since it's const, you may not care if it's initialized multiple times, unless someOtherFunction does not support parallel execution (beware of resources)
Guideline: only use static or global variables instantiation for simple objects (that cannot throw), otherwise use local static variables to delay execution until you can catch the resulting exceptions.
|
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;
}
What I could gather from http://www.libsdl.org/faq.php?action=listentries&category=7 was that by including SDL.h, it renames my main function through some macro magic. But then SDLMain.m is supposed to make things right again by calling that renamed function. But somehow that is not happening?
I'm running Leopard.
Note that this is a different issue from question 550455.
| 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/Developer/Shared/Xcode/Project Templates/SDL Application/SDLMain.m"
|
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){
if(carArray[i]->year > carArray[j+1]->year){
swap(carArray[j], carArray[j+1]);
}
}
}
}
The above method works for int's (year). How can I make it work for char pointers?
| 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 set Configuration Properties > Linker > General > Additional Library Directories.
|
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 elements. This call has last < first, which is illegal (!), so I'm guessing that the position you're giving to insert at is wrong. Are you sure vnum hasn't underflowed somewhere along the line? In GDB with that trace showing, you should run
frame 10
print vnum
to check. In fact, if you haven't just abbreviated in your question, I've just found your bug. Your second line is:
new_mesh->Face(face_loc)->vertices.insert(vertices.begin()+vnum+1, new_vertices[j]);
It should have been:
new_mesh->Face(face_loc)->vertices.insert(new_mesg->Face(face_loc)->vertices.begin()+vnum+1, new_vertices[j]);
The first line gives the insertion point relative to the start of some other variable called vertices, not the one you want to insert into.
|
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 precision?
| 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 give maximum precision.
ss.precision(std::numeric_limits<double>::digits10 + 2);
|
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 char* arguments, how come the second argument can pass a (char* + int) to a char* and have it work out properly? How does the type system interpret this statement?
Thanks in advance.
| 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 implemented by modern c++ compilers like g++. Are they handled like global variables?
| 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 output, no matter how many threads you use.
If you want to enable more efficiency, allow the user to specify the buffer themselves as one of the parameters.
See the difference between global and static variables here.
|
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 [] pleak; // will only get here if x == 0. if x!=0, throw exception
}
int main()
{
try
{
func( 10 );
}
catch ( const std::exception& e )
{
return 1;
}
return 0;
}
Here memory allocated for pleak will be lost if an exception is thrown, while memory allocated to s will be properly released by std::string destructor in any case. The objects allocated on the stack are "unwound" when the scope is exited (here the scope is of the function func.) This is done by the compiler inserting calls to destructors of automatic (stack) variables.
Now this is a very powerful concept leading to the technique called RAII, that is Resource Acquisition Is Initialization, that helps us manage resources like memory, database connections, open file descriptors, etc. in C++.
Now that allows us to provide exception safety guarantees.
|
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 is a pointer reference, why is it not required for them to be initialized as follows?
void swap(int*& a, int*& b) : a(a), b(b) {}
Here's the reference question/answer posting (the answer is the point of interest):
Swapping addresses of pointers in c
| 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 included, how it can be used?
Any thoughts..?
| 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 included, how it can be used?".
All files that use this macro include yvals.h somehow. For example <vector> includes <memory>, which includes <iterator>, which includes <xutility>, which includes <climits>, which includes <yvals.h>. The chain may be deep, but it does include it it some point.
And I want to clarify, this only applies to this particular implementation of the standard library; this is in no way standardized.
|
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 argc, char *argv[])
{
managed_shared_memory segment(create_only, "MySharedMemory", 65536);
const ShmemAllocator alloc_inst (segment.get_segment_manager());
MyCircBuffer *myCircBuf = segment.construct<MyCircBuffer>("MyCircBuffer")(alloc_inst);
return 0;
}
I get a compilation error (caused by segment.construct()). Any idea what I am doing wrong? Is it because circular_buffer is not one of the containers listed in /boost/interprocess/containers, i.e. it's not compatible with Interprocess?
Thanks,
C
| 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 emulate absolutely anything. There's nothing to prevent a C or C++ implementation from implementing the int type of any size and with any representation, as long as it is large enough to meet the minimum requirements specified in the language standard. Practical examples of such level of abstraction are readily available, e.g. programming languages based on "virtual machine" platform, like Java.
However, C and C++ are intended to be highly efficient languages. In order to achieve maximum efficiency a C or C++ implementation has to take into account certain considerations derived from the underlying hardware. For that reason it makes a lot of sense to make sure that each basic type is based on some representation directly (or almost directly) supported by the hardware. In that sense, the size of basic types do depend on the hardware.
In other words, a specific C or C++ implementation for a 64-bit hardware/OS platform is absolutely free to implement int as a 71-bit 1's-complement signed integral type that occupies 128 bits of memory, using the other 57 bits as padding bits that are always required to store the birthdate of the compiler author's girlfriend. This implementation will even have certain practical value: it can be used to perform run-time tests of the portability of C/C++ programs. But that's where the practical usefulness of that implementation would end. Don't expect to see something like that in a "normal" C/C++ compiler.
|
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 the collision occurred.
Can someone please suggest me something that I can use and make this happen ?
Thanks
| 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 vertex arrays and maintain a map from your triangle vertices to coordinates indexing the vertex arrays; then you can take whatever vertices trigger the collision test and manually modify their associated color data on each frame.
|
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 interfaceClass
{
inheritedClass(int getInt): m_interfaceVar(getInt){};
~inheritedClass(){};
}
and i have to do it like this
class inhertitedClass : public interfaceClass
{
inheritedClass(int getInt){ m_interfaceVar = getInt;}
~inheritedClass(){};
}
I'm sorry if this is a dumb question, but i just ran in to it the other night while i was switching my abstract class into an interface class (the back to an abstract class).
| 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 ) = 0;
virtual void func2( void ) = 0;
protected:
int m_interfaceVar;
interfaceClass(int x) { m_interfaceVar=x; }
}
and then you can do things the right way, namely
class inhertitedClass : public interfaceClass
{
inheritedClass(int getInt): interfaceClass(getInt){};
~inheritedClass(){};
}
|
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 <iostream>
#define PASSWD "+++"
#define MAX_LEN 1023
#define MAX_CODE_SIZE (0x10 * 1024)
#define OFFSET_1 0x42
#define OFFSET_2 0x67
#define x_original_1 0xc01b0574
#define x_original_2 0x44681574
#define x_original_all 0x13D4C04B
#define x_crypt 0x66
using namespace std;
int check_user()
{
char passwd[MAX_LEN];
cout<< "enter password:";
fgets(passwd, MAX_LEN, stdin);
return ~strcmp(passwd, PASSWD);
}
int my_func()
{
if (check_user())
{
cout<<"passwd ok\n";
}
else
{
cout<<"wrong passwd\n";
exit(-1);
}
return 0;
}
int main()
{
int a, b = 0;
#pragma pack(1)
union f
{
char buf[MAX_CODE_SIZE];
struct
{
int local_var_1;
int local_var_2;
char gag_1[OFFSET_1 - sizeof(int) * 2];
int x_val_1;
char gag_2[OFFSET_2 - OFFSET_1 - sizeof(int)];
int x_val_2;
};
};
union f ZZZ;
memcpy(&ZZZ, &check_user, (int)&main - (int)&check_user);
for (a = 0; a < (int)&main - (int)&check_user; a++)
{
(*(char *) ((int)&ZZZ + a)) ^= x_crypt;
}
memcpy(&check_user, &ZZZ, (int)&main - (int)&check_user);
for (a = 0; a < (int)&main - (int)&check_user; a++)
{
b += *(int *)((int)&check_user + a);
}
if (b != x_original_all)
{
fprintf(stderr, "-ERR: invalid CRC (%x)\n", b);
return 0;
}
my_func();
}
| 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 flags for either of these calls: again you want writable, executable memory.
Also, interacting directly with this via function pointers is kind of sketchy. I think you should write some code, compile/assemble it, apply some kind of cypher, and put in your obfuscated code as a sequence of bytes. Or something like that.
Did I mention this is a bad idea?
|
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 structures in C#
and
Reading a C/C++ data structure in C# from a byte array
After reading data into structure i need to covert the short variable to big endian. (reversing bytes).
| 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 classes of the library
// that I would like to hide from the external interface
void setSecretParam(double aParam);
private:
double m_Param;
}
My first attempt was to create the external interface as an ABC:
class Algorithm {
public:
// factory method that creates instances of AlgorithmPrivate
static Algorithm* create();
virtual void compute(const Data& data, Result& result) const = 0;
}
class AlgorithmPrivate : public Algorithm {
public:
void compute(const Data& data, Result& result) const;
void setSecretParam(double aParam);
private:
double m_Param;
}
Pros:
The user of Algorithm cannot see the internal interface
Cons:
The user has to use a factory method to create instances
I have to downcast Algorithm to AlgorithmPrivate when I want to access the secret parameters from inside the library.
I hope you understand what I try to achieve and I'm looking forward to any suggestions.
| 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 STRUCT_TYPE, typename MEMBER_TYPE, membername NAME>
class cMemberExtractor
{
public:
MEMBER_TYPE
extract(const STRUCT_TYPE* pStruct) const
{
return pStruct->NAME;
}
};
The idea behind is to use the template like this:
/*somewhere*/
void
producer()
{
//produce update
tStructA* pUpdate=new tStructA;
...
//send update to receivers
emit(pUpdate);
}
/*elsewhere*/
void
consumer(const tStructA* pUpdate)
{
//extract data
int data=cMemberExtractor<tStructA,int,memberB>().extract(pUpdate);
//process data
...
}
Thanks for your help!
| 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.*ptr ), ptr(ptr)
{}
void operator()( C & obj ) {
obj.*ptr = new_value;
}
M new_value;
member_ptr_t ptr;
};
struct test {
int value;
};
int main() {
updater_t<test,int> update( &test::value, 10 );
test object;
update( object );
test object2;
updater_t<test,int> update_copy( &test::value, object );
update_copy( object2 );
}
Edit: Moving the member pointer to a template argument as suggested by litb:
template <typename C, typename M, M C::* Ptr>
struct updater_t {
updater_t( M const & new_value ) : new_value( new_value ) {}
updater_t( member_ptr_t ptr, C & original ) : new_value( original.*Ptr ) {}
void operator()( C & obj ) {
obj.*ptr = new_value;
}
M new_value;
};
int main() {
updater_t<test,int, &test::value> update( 10 );
test object;
update( object );
}
|
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"), Gdiplus::ImageFormatJPEG);
and all is ok , now all i want is to send that image to print...
i use
DWORD pcchBuffer=100;
char * pszBuffer=new char[100];
GetDefaultPrinter(pszBuffer,&pcchBuffer);
again all is ok.
to get defaulet printername , for print i know WritePrinter function, but that fonction gives argumens LPVOID buffer to print , how can i send my image to print?
Many many Thanks!
| 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 have to define for example in an array what types of data are you interested in.
|
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 ensure that each window keeps its order in the window stack even if a window receives input.
I am thinking I need to write some sort of simple window manager that will maintain the correct Z-order of the windows.
The problem is, I need to know if a particular window has changed position. I have found that there is a WM_WINDOWPOSCHANGING message but my understanding is that this message is send to the window whose position has changed.
I need my window manager application to be somehow notified that the Z-order has changed.
Is there some way I can catch all WM_ messages and determine if the message applies to one of the windows I wish to control?
| 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;
} Field;
typedef struct _Packet {
WORD nMessageType;
WORD nSecurityType;
BYTE bExchangeId;
BYTE bMarketCenter;
int iFieldCount;
char cSymbol[20];
Field FieldArr[1];
} Packet;
What are the C# equivalent of these C++ structs?
I am migrating some code from C++ to C# and having problems to migrate these structures. I had tried a few things but I always ended up having marshalling problems.
| 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; -> Single f; (though 'float' still works)
double *d; -> Double d; (was this meant to be a pointer???)
char *p; -> String s; (assuming its a string here, in the marshaling you can tell it whether it is ASCII or wide char format)
With this info it should be relatively easy to translate those strucutres (just make sure you keep them as a struct and give it the attribute "[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]", which will make sure that the marshaller keeps all the data in the same order.
Also, I recommend looking through both the classes and attributes in System.Runtime.InteropServices as they do provide quite a few methods for automating marshaling of data to c/c++ code (and it doesn't require "unsafe" c# code either).
|
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 )
{
//whatever
}
template<class T>
void tryProcess( T& object )
{
process( &object )
}
In tryProcess() I need to get a T* pointer holding the address of the actual object of type T.
The above implementation of tryProcess() will only work allright if class T doesn't have operator&() overloaded. So if I call tryProcess<_com_ptr_<Interface>>() I can get unexpected results - the overloaded operator&() is triggered.
In another question the following workaround is suggested:
template<class T>
T* getAddress( T& object )
{
return reinterpret_cast<T*>( &reinterpret_cast<char&>( object ) );
}
With such a function I can implement tryProcess() as follows:
template<class T>
void tryProcess( T& object )
{
process( getAddress( object ) )
}
and will always get the same behavior independent of whether class T has operator&() overloaded. This introduces zero overhead with optimizations on on Visual C++ 7 - the compiler gets what to do and just gets the object address.
How portable and standard-compilant is this solution to the problem? How could it be improved?
| 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 rejected when the reinterpret_cast solution was brought up. Since this offered a standard-compliant way around the problem, the committee did not see a need to add extra requirements to the offsetof, and left fixes to the implementations.
|
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 parameters should be
MyFunc/({+}/(
and the replace parameters simply
/1
But this gives me a syntax error in my pattern. I'm new to search and replace with regex under visual studio. Can the above be easily achieved? I've had a look at similar questions on this site, which suggest I'm roughly on the right track, but seem to be missing something.
Edit: If you can answer the above, how about if it is part of a class deference, e.g.
MyClass.MyFunc(Param)
or
MyClass->MyFunc(Param)
(FWIW, I also picked up a copy of VisualAssist in the hope it could do this but it doesn't appear to be able to handle this situation).
Second edit: Thanks to Joe for the correct response, but for anyone else using this approach, beware of some pitfalls,
MyFunc(MyArray[MyOtherFunc(x)])
ends up as
MyArray[MyOtherFunc(x])
and
MyFunc((SomeType)x)
ends up as
(SomeTypex)
Once you do a search to check what you get prior to doing a search and replace, make sure you keep modified files open in case you need to undo, and backup your source files before starting, this works well enough. Even with the pitfalls listed, still a huge time saver.
| 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 TreeNode parent, firstChild, nextSibling;
public InsertChild(TreeNode newChild)
{
newChild.parent = this;
newChild.nextSibling = firstChild;
firstChild = newChild;
}
}
var root = new TreeNode();
var child1 = new TreeNode();
root.InsertChild(child1);
Points of interest:
No need to modify the type with * when declaring the members
No need to set them to null in a constructor (they're already null)
No special -> operator for member access
No need to write a destructor (although look up IDisposable)
|
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;
double x;
x = lexical_cast<double>(word);
cout << x << endl;
} while (iss);
What am I doing wrong here? I appreciate any help, thanks
| 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 >> word;
if(iss)
{
double x;
x = lexical_cast<double>(word);
cout << x << endl;
}
} while (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( boost::detail::addr_impl_ref<T>( v ), 0 );
}
boost::detail::addressof_impl<T>::f() accepts T& as the first parameter. boost::addressof<T>() also has T& v as the parameter.
Why is boost::detail::addr_impl_ref() temporary object used here to store and return T& instead of just passing T& v?
| 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 = m.find( key );
if ( it == m.end() ) {
return defval;
}
else {
return it->second;
}
}
int main() {
map <string,int> x;
...
int i = GetWithDef( x, string("foo"), 42 );
}
C++11 Update
Purpose: Account for generic associative containers, as well as optional comparator and allocator parameters.
template <template<class,class,class...> class C, typename K, typename V, typename... Args>
V GetWithDef(const C<K,V,Args...>& m, K const& key, const V & defval)
{
typename C<K,V,Args...>::const_iterator it = m.find( key );
if (it == m.end())
return defval;
return it->second;
}
|
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)
{
//vpszRecvd = NULL;
int recvsize = 0;
char TempBuf[1024];
int Result = 0;
char* temp;
do
{
memset(TempBuf, 0, sizeof(TempBuf));
Result = recv( this->sSocket, TempBuf, sizeof(TempBuf) -1, 0 );
if (recvsize == 0)
recvsize = Result;
if ( Result > 0 )
{
if ( vpszRecvd != NULL )
{
if (temp == NULL)
{
temp = (char*)calloc(recvsize + 1, sizeof(char));
}
else
{
realloc(temp, recvsize + 1);
}
if (temp == NULL)
return 0;
memcpy(temp, vpszRecvd, recvsize);
realloc(vpszRecvd, recvsize + Result);
if (vpszRecvd == NULL)
return 0;
memset(vpszRecvd, 0, recvsize + Result);
memcpy(vpszRecvd, TempBuf, Result);
memcpy(vpszRecvd + recvsize, TempBuf, Result);
recvsize += Result;
}
else
{
realloc(vpszRecvd, Result);
if (vpszRecvd == NULL)
return 0;
memset(vpszRecvd, 0, Result);
memcpy(vpszRecvd, TempBuf, Result);
recvsize += Result;
}
}
else if ( Result == 0 )
{
return recvsize;
}
else //if ( Result == SOCKET_ERROR )
{
closesocket(this->sSocket);
this->sSocket = INVALID_SOCKET;
return SOCKET_ERROR;
}
}
while( Result > 0 );
return recvsize;
}
Does anybody see anything that could cause the crash, or does anyone have a better / faster / smaller and stable example how to receive a full packet via recv()?
I can't use strings, it must be done with chars, though.
Thanks for your help.
| 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 reason realloc returns a new address is because expansion of the buffer may necessitate it being moved if that current block is surrounded in the memory arena (in other words, it can't just expand into a free block following it). In that case, a new block will be created in the arena, the contents transferred from the old block and the old block freed. You have to get the return value from realloc in case that happens.
Keep in mind that realloc doesn't have to return a new pointer, it may give you the same pointer if, for example, there was enough free space after the block to satisfy the new size or if you're reducing the size.
It can also return NULL if it can't expand the block, you should watch out for that as well, especially since:
temp = realloc (temp, newsize);
will result in a memory leak when it returns NULL (it doesn't free the old block).
A few other things:
you rarely need to use calloc, especially in this case since you're copying over the memory anyway.
similarly, you don't need to memset a memory chunk to 0 if you're immediately going to memcpy over it.
provided you initialise temp to NULL, you can just use realloc without testing it. That's because realloc(NULL,7) is identical to malloc(7) - realloc is perfectly capable of starting with a null pointer.
since you don't need calloc, this is for education only - sizeof(char) is always 1 by definition.
you seem to be doing an awful lot of unnecessary copying of data.
Why don't we start with something a bit simpler? Now, this is totally from my head so there may be some bugs but it's at least cut down from the memory-moving behemoth in the question :-) so should be easier to debug.
It's basically broken down into:
initialise empty message.
enter infinite loop.
get a segment.
if error occurred, free everything and return error.
if no more segments, return current message.
create space for new segment at end of message.
if no space could be created, free everything and return empty message.
append segment to message and adjust message size.
and the code looks like this:
int Socket::Recv(char *&vpszRecvd) {
int recvsize = 0;
char TempBuf[1024];
int Result = 0;
char *oldPtr;
// Optional free current and initialise to empty.
//if (vpszRecvd != NULL) free (vpszRecvd);
vpszRecvd = NULL;
// Loop forever (return inside loop on end or error).
do {
Result = recv( this->sSocket, TempBuf, sizeof(TempBuf) -1, 0 );
// Free memory, close socket on error.
if (Result < 0) {
free (vpszRecvd);
closesocket(this->sSocket);
this->sSocket = INVALID_SOCKET;
return SOCKET_ERROR;
}
// Just return data and length on end.
if (Result == 0) {
return recvsize;
}
// Have new data, use realloc to expand, even for initial malloc.
oldPtr = vpszRecvd;
vpszRecvd = realloc (vpszRecvd, recvsize + Result);
// Check for out-of-memory, free memory and return 0 bytes.
if (vpszRecvd == NULL) {
free (oldPtr);
return 0;
}
// Append it now that it's big enough and adjust the size.
memcpy (&(vpszRecvd[recvsize], TempBuf, Result);
recvsize += Result;
} while (1);
}
|
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/time_bug.png
It happens after I've called root.initialise() in Ogre3D graphics engine, but only when using Direct3D, not when using OpenGL.
So this might be related to Direct3D...
| 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 thread. If you do not specify this flag, Direct3D defaults to single-precision round-to-nearest mode for two reasons:
Double-precision mode will reduce Direct3D performance.
Portions of Direct3D assume floating-point unit exceptions are masked; unmasking these exceptions may result in undefined behavior.
|
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<_Tp, _Alloc>::swap(std::deque<_Tp, _Alloc>&)’:
In file included from /usr/include/c++/4.4/deque:65,
/usr/include/c++/4.4/bits/stl_deque.h:1404: error: ‘swap’ is not a member of ‘std’
/usr/include/c++/4.4/bits/stl_deque.h:1405: error: ‘swap’ is not a member of ‘std’
/usr/include/c++/4.4/bits/stl_deque.h:1406: error: ‘swap’ is not a member of ‘std’
/usr/include/c++/4.4/bits/stl_deque.h:1407: error: ‘swap’ is not a member of ‘std’
I don't know how to fix it and if is possible that stl contains a bug. Can you help me, please?
Thanks a lot for all advices.
| #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&>(reinterpret_cast<const volatile char&>(v)));
}
}
What's the purpose of cast to const volatile char& instead of just casting to char&?
| 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 32-bit build. I ran the tests on a quad core 64-bit machine. So there is the question of comparing apples to oranges since the 32-bit was running under the emulation mode obviously. However, it seems that many things I read such as this, for example, consistently say that the speed hit for WOW64 is not significant. But even if that statement is not true, your application will almost certainly be run on a 64-bit OS. Thus a comparison of a 32-bit build versus 64-bit on a 64-bit machine has value.
In the testing I performed (certainly not comprehensive), I did not find any cases where the 32-bit build was faster. However many of the SQL intensive operations I ran (high CPU and high I/O) were 20% to 50% faster when running with the 64-bit build. These tests involved some fairly “ugly” SQL statements and also some TPCC tests with high concurrency. Of course, a lot depends on compiler switches quite a bit, so you need to do your own testing.
|
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 float& m22, const float& m23,
const float& m30, const float& m31, const float& m32, const float& m33)
{
_m00 = m00;
_m01 = m01;
_m02 = m02;
_m03 = m03;
_m10 = m10;
_m11 = m11;
_m12 = m12;
_m13 = m13;
_m20 = m20;
_m21 = m21;
_m22 = m22;
_m23 = m23;
_m30 = m30;
_m31 = m31;
_m32 = m32;
_m33 = m33;
}
My question is, how can I return a float array of this data? I have no problem creating the array in the class for example:
float arrayToReturn[16] = { m00, m01, m02, m03, ... m33 };
However I can not return this value from the class. I've read about returning a pointer to the array, but have had no luck with it.
| 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.
It would be better to create a copy constructor, a () operator, and an assignment operator for your Matrix4d class and just pass that around. You'd be less likely to have runtime errors due to bad memory management or data corruption.
Your () operator would look like this:
float& operator()( unsigned int xIndex, unsigned int yIndex )
{
//return the right attribute
}
You would call it like this for setting values:
aMatrix(0,0) = 2.0;
or this for retrieving:
float attributeCopy = aMatrix(0,0);
It works both ways.
EDIT: Forgot that the [] operator only took one argument. Changed the operator to the () operator a.k.a the functional operator.
|
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 know is how do you implement multiple read and multiple writes on a single object in terms of mutex and other synchronization objects needed?
| 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 threads to
share a single-use resource without
conflict, using only shared memory for
communication.
Note that Dekker's algorithm uses a spinlock (not a busy waiting) technique.
(Th. J. Dekker's solution, mentioned by E. W. Dijkstra in his EWD1303 paper)
|
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 following.
CComPtr<IStream> pFileStream;
CComPtr<IXmlReader> pReader;
I am a tad bit confused. 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. Or does CComptr already have IStream and the only way for istream to be effective is to extend like above???
| 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 implements an interface -- it does not actually implement any interface itself.
Is it possible to implment a COM interface without creating a custom interface?
I'm not 100% positive here, but I don't believe you need to implement an interface. You do however need to implement the interface itself in a coclass.
|
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 bother with that register. In some situations, this can yield a slight performance increase, mostly due to reduced code footprint (that's better for cache) and to the extra available register (especially on x86 in 32-bit mode, which is notoriously starved on registers).
|
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 did it though, the application got laggy, and I found out that it was because paintEvent() was being called in a seemingly infinite loop.
Trying to figure out how to fix that, I moved the code that drew the labels and lines to the constructor of the class. Only the labels were drawn on the application though. After that, I left the labels in the constructor, but moved the code that drew the lines back to paintEvent(). It worked, the lines were drawn as expected, and paintEvent() was called only when dragging stuff around.
Why were the lines not being drawn on the constructor, and why paintEvent() got into an infinite loop?
Here's the snippet that's supposed to draw the labels and lines:
QPen pen(Qt::lightGray, 0, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin);
QPainter paint(this);
paint.setPen(pen);
int scale = 20;
for(int x=0; x<25; x++){
QString timetext= "0"+QString::number(x)+":00";
QLabel *time= new QLabel(timetext,this);
time->move(x*scale,2);
time->show();
paint.drawLine(x*scale,12,x*scale,400);
}
| 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() is only for painting! Not for creating objects or anything else.
Do it like this:
QFont font(painter.font());
font.setBold(true);
painter.setFont(font);
painter.fillRect(rect(), Qt::black);
painter.setPen(Qt::white);
painter.drawText(rect(), Qt::AlignCenter, tr("White text on dark background. Awesome."));
|
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 stream;
stream << t;
U u;
stream >> u;
return u;
}
|
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 speaking of that, I notice in most cases you never initiate new objects, but always call on methods that return that pointer. What if that pointer is being used somewhere else. Couldn't you mess something up if you alter that pointer and it is being used somewhere else?
| 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 need just a simple ABI, that consists of almost just the definition for the calling convention to use for functions (and something about the structures layout). C++ and other object oriented languages, on the contrary, require a complex ABI, that must define how objects are laid out in memory, how to handle inheritance, how to lay out the vtable, how to propagate exceptions, where to put RTTI data, ... Moreover not all the languages are object oriented, and using APIs thought for C++ with other non-object oriented languages may be a real pain (if you ever used COM from C you know what I mean).
As an aside, when Windows was initially designed C++ wasn't so widespread on PCs, and also C wasn't used so much: actually, a large part of Windows 3.11 and many applications were still written in assembly, since the memory and CPU constraints at the era were very tight; compilers were also less smart than now are, especially C++ ones. On machines where hand-forged assembly was often the only solution, the C++ overhead was really unacceptable.
For the pointers thing: Windows APIs use almost always handles, i.e. opaque pointers, to be able to change the underlying nature of every resource without affecting the existing applications and to stop applications to mess around with internal structures. It doesn't matter if the structure used by the window manager to represent a window internally is changed: all the applications use simply an HWND, which is always of the size of a pointer. You may think at this as some kind of PIMPL idiom.
However, Windows is in some way object-oriented (see for example the whole "window class" concept, or, at a deeper level, the inner working of the NT kernel, which is heavily based on the "object" concept), however its most basic APIs, being simple C functions, somehow hide this OO nature. The shell, on the other side, being designed many years after, is written mostly in C++ and it provides a really object-oriented COM interface.
Interestingly, you can see in COM all the tradeoffs that you must face in building a cross-language but still C++ biased object-oriented interface: the result is quite complicated, in some respects ugly and not really simple to use from any language. The Windows APIs, instead, being simple functions are generally more easily callable.
If you are interested in a system based on C++ APIs you may have a look at Haiku; personally, this is one of the aspects because of which I am quite interested in that project.
By the way, if you are going to do Win32 programming just with the APIs you'd better get a good book to get used to these "particularities" and to other Win32 idioms. Two well-known ones are the Rector-Newcomer and the Petzhold.
|
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.
For listing the existing restore points you can use the VBScript sample code from here (Note that the code needs elevation on Vista and above):
Set RPSet = GetObject("winmgmts:root/default").InstancesOf ("SystemRestore")
for each RP in RPSet
wscript.Echo "Dir: RP" & RP.SequenceNumber & ", Name: " & RP.Description & ", Type: ", RP.RestorePointType & ", Time: " & RP.CreationTime
next
|
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, const comma_op &rhs)
{
cout << "Reached!\n"; // this gets printed though
rhs, lhs; // reversing this leads to a infinite recursion ;)
}
int main()
{
comma_op obj;
12.5f, obj;
return 0;
}
Basically, I'm trying to get the comma operator usable from both sides, with a float. Having a member function only allows me to write obj, float_val, while having an additional helper non-friend non-member function allows me to write float_val, obj; but the member operator function doesn't get called.
GCC cries:
comma.cpp: In function ‘void operator,(const float&, const comma_op&)’:
comma.cpp:19: warning: left-hand operand of comma has no effect
comma.cpp:19: warning: right-hand operand of comma has no effect
Note:
I realise that overloading operators, that too to overload comma op., Is confusing and is not at all advisable from a purist's viewpoint. I'm just learning C++ nuances here.
| 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,, so the default definition will be used.
|
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 env variables that point to those libs on my hard drive. How can I tell VS to use them as additional include paths? Again, it's 2010 version so no vs per solution setup available. I do not want to set it manually in every project.
| 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 actually stored in LocalAppData, just as VCComponents.dat file was, in the directory %LocalAppData%\Microsoft\VisualStudio\10.0. Using the property editor on the property sheet (just right-click on this property sheet node and select Properties…), you can see that you are able to make edits directly to this file. Since all projects, by default, import this property sheet, you are effectively editing the VC++ directories in the same way you were able to do before.
The key is that you get to the VC++ Directories property through the "Property Manager" windows (open it via the View/"Property Manager" menu selection). The VC++ Directories setting is in the "Microsoft.Cpp.Win32.user" property sheet - that edits the global setting, so you should only have to do it once.
There seem to be quite a few people who dislike this change; I think that's because it's less discoverable and obvious than how the setting was managed before. The trade-off is that it's more flexible and integrates into the MSBuild architecture better, and once you do know about it it's just as easy to change as before (it's just harder to find, particularly if you're used to the old place).
|
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.
};
/**
*
* \struct Tick_Data_Row
*
* \brief Holder for one row or snapshot of tick data.
*
**/
struct __declspec (dllexport) Tick_Data_Row {
Tick_Data_Row (); ///< Constructor. Sets all columns to NaN
void init (); ///< Helper function to reset everything to NaN
double m_cols[TC_MAX]; ///< The data. Indexed by Tick_Column_Type.
};
Everything seems to work fine (the enum ends up at file scope, but I have a \file, so it appears, along with the descriptions, correctly formatted.
What I want (and is not happening) is that I'd like the reference to Tick_Column_Type in the documentation for Tick_Data_Row::m_cols to link back to that document page. Doxygen usually seems to be quite smart at figuring out "aha, that's a name I know, I'll hot-link it", but it fails to do so in this case.
It does not matter if I move the enum inside the struct.
Any clues?
| 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.
[TEST]square
apparently I can't write the square here, but is it something about the ofstream being binary or something?
| 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 that do the work for me
Links to cool C++ Rakefiles that I should check out that do similar things
Here's what I have so far. It's a function that returns the list of dependencies given a source file. I feed in the source file for a given object file, and I want a list of files that will force me to rebuild my object file.
def find_deps( file )
deps = Array.new
# Find all include statements
cmd = "grep -r -h -E \"#include\" #{file}"
includes = `#{cmd}`
includes.each do |line|
dep = line[ /\.\/(\w+\/)*\w+\.(cpp|h|hpp)/ ]
unless dep.nil?
deps << dep # Add the dependency to the list
deps += find_deps( dep )
end
end
return deps
end
I should note that all of my includes look like this right now:
#include "./Path/From/Top/Level/To/My/File.h" // For top-level files like main.cpp
#include "../../../Path/From/Top/To/My/File.h" // Otherwise
Note that I'm using double quotes for includes within my project and angle brackets for external library includes. I'm open to suggestions on alternative ways to do my include pathing that make my life easier.
| 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([](){
foo([]() { }); // error C2893: Failed to specialize function template ''unknown-type' foo(F)'
});
}
As indicated in the comment, the compiler generates an error on the line foo([]() { }).
I hate to shout "compiler bug", but I really can't see any good explanation for this error.
Apparently, while inside the outer lambda expression, the compiler can not specialize the foo function template for the inner lambda.
However, if the definition of foo is changed to hardcode the return type, like this:
template <typename F>
void foo(F f){
return f();
}
then everything compiles just fine.
Is there some obscure quirk of decltype when used to deduce the return type of lambda expression parameters inside the scope of another lambda that I'm not aware of?
| 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())
{
return f();
}
int main()
{
auto f = [](){};
auto x = [&]()
{ // pre-defined lambda
foo(f);
};
}
Fails
template <typename F>
auto foo(F f) -> decltype(f())
{
return f();
}
int main()
{
auto x = []()
{ // in-argument lambda
foo([]{});
};
}
template <typename F>
auto foo(F f) -> decltype(f())
{
return f();
}
int main()
{
auto x = []()
{ // in-scope lambda
auto f = []{};
foo(f);
};
}
template <typename F>
auto foo(F f) -> decltype(f())
{
return f();
}
int main()
{
auto x = []()
{ // in-scope lambda, explicit return
// (explicit return type fails too, `-> void`)
auto f = [](){ return; };
foo(f);
};
}
template <typename F>
auto foo(F f) -> decltype(f())
{
return f();
}
int main()
{
auto x = []()
{ // in-argument lambda, explicit return non-void
// (explicit return type fails too, `-> int`)
foo([]{ return 5; });
};
}
So it does seem to have to do with scope and the void type of the internal lambda, even when made explicit.(?)
|
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 you set it, it is set until you explicitly unset it for the remainder of the stream output.
fixed: will enforce that all floating-point numbers are output the same way. So if your precision is set to 4 places, 6.2, and 6.20 will both be output as:
6.2000
6.2000
showpoint: will force the decimal portions of a floating-point variable to be displayed, even if it is not explicitly set. For instance, 4 will be output as:
4.0
Using them all together:
outfile << fixed << showpoint;
outfile << setprecision(4);
outfile << x;
|
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 uses argc/argv. The code used to check for the arguments is as follows:
// Process the arguments
if (!strcmp(option, "-h"))
{
// do stuff...
}
else if (!strcmp(option, ""))
{
// do stuff...
}
else if (!strcmp(option, "-t"))
{
// do stuff...
}
else if (!strcmp(option, "-a"))
{
// do stuff...
}
if ( *argv == NULL )
{
exit(1);
}
Where "option" has been populated with the switch in argv[1], and argv[2] and higher has the remaining arguments. The first block I understand just fine, if the switch equals the string do whatever based on the switch. I'm wondering what the purpose of the last if block is though.
It could be that my C++ is somewhat rusty, but I seem to recall *argv being equivalent to argv[0], basically meaning it is checking to make sure arguments exist. Except I was under the impression that argv[0] always (at least in most implementations) contained the name of the program being run. It occurs to me that argv[0] could be null if argc is equal to 0, but searching around on Google I couldn't find a single post determining whether or not that is even possible.
And so I turn to you. What exactly is that final if block checking?
EDIT: I've gone with the reasoning provided in the comments of the selected answer, that it may be possible to intentionally cause argv[0] to become NULL, or otherwise become NULL based on an platform-specific implementation of main.
| 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 doing garbage collection, they look at memory and see if anything points at it or not, then make decisions to delete the unused variable, etc.
| 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:
CGI
FastCGI
WSGI
Now, as I have absolutely no experience on using those interfaces, I don't really know what to choose. I do have some requirements though.
needs to be reasonably fast (from what I've heard of, this pretty much rules out CGI)
should be easily usable in a pure C/C++ environment (e.g. there should be libraries available)
must provide support for HTTP 1.1 (dunno if that matters)
Thanks for any suggestions :)
| 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. Tasks that have a lot of startup overhead benefit most from FCGI; the FCGI controller can be configured to spawn additional processes to handle heavy loads.
Practically any web server will run CGI with minimal configuration; you'll likely need an additional module to run FCGI but that depends on the web server.
http://en.wikipedia.org/wiki/FastCGI
|
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
{
virtual void bar() { std::cout << "FooDerived::bar()\n"; }
};
int main()
{
FooBase* pFoo = new FooDerived();
pFoo->bar();
return 0;
}
In this example the compiler surely knows what will be the type of pFoo at compile time, so it does not need to use a vptr for pFoo, right?
Are there more interesting cases where the compiler can avoid using a vptr?
| 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, including in your example. Because pFoo's initialization is in that scope, the compiler knows that pFoo->bar must mean FooDerived::bar, and doesn't need to check the vtable. There are also several caching techniques to avoid multiple vtable lookups, ranging from the simple to the complex.
|
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] string code,
[In] int length,
StringBuilder key);
|
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://www.ferdychristant.com/blog//archive/DOMM-76JN6N , but I think that only applies to Unix variants. Everytime I compile I get the error: "cannot find -lboost_filesystem" . I've scoured the net, but cannot find a way to properly use Boost in Eclipse under a Windows platform. Any help or suggestions are appreciated.
| 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 key differences between references and all of the 3 types of const pointers above:
Const pointers can be NULL.
A reference does not have its own address whereas a pointer does.
The address of a reference is the actual object's address.
A pointer has its own address and it holds as its value the address of the value it points to.
See my answer here for much more differences between references and pointers.
|
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 because the Boost website talks about the BGL being a header-only library that does not need to be built. My next question is, how do I access the BGL and use it in Eclipse on Mac?? Your help is appreciated.
| 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 are copied the Boost's include directory.
In order to use the BGL you do not have to build and link to a library or dll (or whatever they are called on Mac). All the code is in these header files, and will be pulled into your code when you #include it.
As to eclipse. I do not know.
|
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 find how much memory is freed?
EDIT
is there any method to find how much memory is freed?
better than nothing,
mallinfo() can shed some light as pointed by "Fred Larson"
| 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 the block in the space immediately preceding the returned pointer. Then, free() would look something like this:
void free(void *ptr)
{
size_t *size = (size_t *)ptr - 1;
return_to_heap(ptr, *size);
}
Where return_to_heap() is used here to mean a function that does the actual work of returning the specified block of memory to the heap for future use.
|
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 the swap chain
swapChainDesc.BufferDesc.Width = 640;
swapChainDesc.BufferDesc.Height = 480;
// Set the refresh rate. This is how often the buffers get swapped out
swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
// Set the surface format of the buffers
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferDesc.ScanlineOrdering.DXGI_MODE;
//_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
// Set how the buffers are used. Since you are drawing to the buffers, they are
//considered a render target
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
// Set the number of back buffers, 1 is the minimum and normally sufficient
swapChainDesc.BufferCount = 1;
// A handle to the main application window
swapChainDesc.OutputWindow = hWnd;
// Set whether you are running in a window or fullscreen mode
swapChainDesc.Windowed = TRUE;
// How the buffers are swapped. Discard allows the buffers to be overwritten
//completely when swapped.
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_NONPREROTATED;
| 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, please provide an example by which the need of member template functions becomes clear to me.
Also, tell me the use of member template functions in c++, what are the situations where we use member template functions?
| 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? Well, in that case you should understand the general purpose of member function templates, because it is exactly the same.
|
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( void )
{
...
}
In clientfoo
#include "libfoo/libfoo.h"
...
libfoofunc = dlsym( libfoo, MAKE_STRING(FOO_SO_FUNCTION_A) );
My problem is that
#FOO_SO_FUNCTION_A
Will simply change into "FOO_SO_FUNCTION_A" because the preprocessor rightfully only runs once. Is there another way to accomplish this?
| 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 means each .cpp file depends on its corresponding header
# and, since the .o files depend on .cpp files (a builtin make rule),
# they will be recompiled if the headers change
#
# you can also get more complex and generate dependencies automatically
# look at the -MM option for gcc, for example
%.cpp: %.h
|
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 version of integer.i, rather than pack and unpack functions.
union _integer{
char pack[4];
int i;
}integer;
Can some one shed some light on why union is a bad choice?
Is there any better method of packing data?
| 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 serialization and Google protobuf.
|
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(). The code should be robust--not necessarily against deliberate tampering but definitely in the face of nested mountpoints, symlinks, etc.
I haven't been able to find a simple system call to do this. It looks like I'll have to write the check myself. Here's a rough outline of what I'm planning.
Canonicalize the file name a la the readlink shell command. How?
Read /etc/mtab with getmntent() & co.
Determine the corresponding mount entry for the file. How?
For #1 is there a simple system call or do I need to read each directory component of the path and resolve them with readlink(2) if they are symlinks? And handle . and .. myself? Seems like a pain.
For #3 I've got various ideas on how to do this. Not sure which is best.
open() the file, its parent, its parent's parent, etc. using openat(fd, "..") until I reach one of the /etc/mtab entries. (How do I know when I do? fstat() them and compare the inode numbers?)
Find the longest directory name in the mount table which is a substring of my file name.
I'm leaning towards the first option but before I code it all up I want to make sure I'm not overlooking anything--ideally a built-in function that does this already!
| 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 buflen)
{
struct stat s;
FILE * fp;
dev_t dev;
if (stat(filename, &s) != 0) {
return NULL;
}
dev = s.st_dev;
if ((fp = setmntent("/proc/mounts", "r")) == NULL) {
return NULL;
}
while (getmntent_r(fp, mnt, buf, buflen)) {
if (stat(mnt->mnt_dir, &s) != 0) {
continue;
}
if (s.st_dev == dev) {
endmntent(fp);
return mnt;
}
}
endmntent(fp);
// Should never reach here.
errno = EINVAL;
return NULL;
}
Thanks to @RichardPennington for the heads up on realpath(), and on comparing device numbers instead of inode numbers.
|
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 preprocessor… and that’s not really the same thing at all) in ANSI C. So, did I miss something huge somewhere, or is this a really esoteric extension by gcc or something, or is my teacher way off-base?
| 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 + operation "string + (string)". how would you return the return value, by ref or by val.
| 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 is a std::ostream, and inserting data into the stream is a modifying operation, so to implement the << operator to insert into an ostream, the operator is defined like this:
std::ostream& operator<< (std::ostream& lhs, const MyType& rhs)
{
// Do whatever to put the contents of the rhs object into the lhs stream
return lhs;
}
This way, when you have a compound statement like cout << x << y, the sub-expression cout << x is evaluated first, and then the expression [result of cout << x ] << y is evaluated. Since the operator << on x returns a reference to cout, the expression [result of cout << x ] << y is equivalent to cout << y, as expected.
Conversely, for "string + string", the result is a new string (both original strings are unchanged), so it must return by value (otherwise you would be returning a reference to a temporary, which is undefined behavior).
|
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 the following:
//This is all in my .cpp file
static int myEventType; //This will contain my registered type
/*If I create a static instance of this class the constructor
gets called before the main() function starts.
*/
class DoRegisterMyEventType {
public:
DoRegisterMyEventType() {
myEventType = QEvent::registerEventType();
}
};
static DoRegisterMyEventType doRegisterMyEventType;
//Here is the constructor for MyEvent class which inherits QEvent.
MyEvent::MyEvent()
: QEvent(myEventType)
{
}
How 'evil' is this? I could wrap the whole thing in a namespace to prevent polluting the global namespace.
| 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::MyEvent()
: QEvent(GetMyEventType())
{
}
This solution has the property that registerEventType is guaranteed to be called before you need your event type even if you construct MyEvent during static initialization, which is good, but it does open you up to thread-safety issues if it's possible for MyEvent to be constructed on multiple threads.
Here's a thread-safe version, based on boost::call_once:
#include "boost/thread/once.hpp"
static boost::once_flag sHaveRegistered = BOOST_ONCE_INIT; //This is initialized statically, effectively at compile time.
static int sEventType = -1; //-1 is not a valid event
static void DoRegister()
{
sEventType = QEvent::registerEventType();
}
static inline int GetMyEventType()
{
boost::call_once(sHaveRegistered, &DoRegister);
return sEventType;
}
|
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...
Recently I was asked by one of my more junior peers whether I thought it was a good idea and I found that I didn't really have a good answer for my preference... Is this really a wholly stylistic choice or are there real reasons why not prefixing this-> on member variable accesses is better?
| 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 single underscore or an m, or m_, etc.
That is much easier to read, in my opinion. If you need this-> to differentiate between variables, you're doing it wrong. Either change the parameter name (from x to newX) or have a member variable naming convention.
Consistency is preferred, so instead of forcing this-> on yourself for the few cases you need to differentiate (note in initializer lists this is completely well-defined: x(x), where the member x is initialized by the parameter x), just get better variable names.
This leaves the only time I use this: when I actually need the address of the instance, for whatever reason.
|
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 error "the procedure entry point vorvis_synthesis_halfrate could not be located in the dynamic link library libvorbis.dll"
How do i fix this error? Btw im using windows 7 and VC++ 2008.
PS. I have googled and posted other places and no one knows :(
| 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 he hid in a comment) is probably the easiest: the AssaultCube installer will install new versions. The harder alternative is to download the relevant sources from http://xiph.org/vorbis/ and build those DLLs yourself.
|
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 starts, but I suspect some sort of issue with one of the DLL's. Can anyone recommend some good tools to use to help isolate the cause of the startup issue?
| 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 calculate the minimal number of steps needed to turn all the binary numbers into one state - 1 or 0.
If M = 6 and N = 3 and the array is 1 0 0 1 0 0, then the solution will be 2.
Explanation: We can flip them so they all be 1 in two steps: we flipped from index 2 to 4 and we transform the array to 111000, and then flip the last three (N) 0s to 1.
| 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 to flip the N elements a[k],a[k+1],...a[k+N-1]. This is only defined for 1≤k≤M-N+1, clearly.
By performing a sequence of these operations Sk, you want to reach either the state of all 0s, or all 1s. We'll solve for both separately, and take the smaller number. So suppose we want to make them all 0 (the other case, all 1s, is symmetric).
The crucial idea is that you would never want to perform any operation Sk more than once (doing it twice is equivalent to not doing it at all), and that the order of operations does not matter. So the question is only to determine which subset of the operations you perform, and this is easy to determine. Look at a[1]. If it's 0, then you know you won't perform S1. Else, you know you must perform S1 (as this is the only operation that will flip a[1]), so perform it — this will toggle all bits from a[1] to a[N]. Now look at a[2] (after this operation). Depending on whether it is 1 or 0, you know whether you will perform S2 or not. And so on — you can determine how many operations (and which) to perform, in linear time.
Edit: Replaced pseudo-code with C++ code, since there's a C++ tag. Sorry for the ugly code; when in "contest mode" I revert to contest habits. :-)
#include <iostream>
using namespace std;
const int INF = 20000000;
#define FOR(i,n) for(int i=0,_n=n; i<_n; ++i)
int flips(int a[], int M, int N, int want) {
int s[M]; FOR(i,M) s[i] = 0;
int sum=0, ans=0;
FOR(i,M) {
s[i] = (a[i]+sum)%2 != want;
sum += s[i] - (i>=N-1?s[i-N+1]:0);
ans += s[i];
if(i>M-N and s[i]!=0) return INF;
}
return ans;
}
int main() {
int M = 6, N = 3;
int a[] = {1, 0, 0, 1, 0, 0};
printf("Need %d flips to 0 and and %d flips to 1\n",
flips(a, M, N, 0), flips(a, M, N, 1));
}
|
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 it's copy-pasta), but works.
Okay, so, here's the attempt:
template<char c0, typename THEN, typename ELSE>
struct char_if
{
typename THEN type;
};
template<typename THEN, typename ELSE>
struct char_if<0, THEN, ELSE>
{
typename ELSE type;
};
class emptyClass {};
template<char c> class key
{
char getKey(){return c;}
};
template<char c0, char c1, char c2, char c3, char c4>
class inheritFromAll
{
typename char_if<c0, key<c0>, emptyClass>::type valid;
class inherit
: valid
, inheritFromAll<c1, c2, c3, c4, 0>::inherit
{};
};
template<char c1, char c2, char c3, char c4>
class inheritFromAll<0, c1, c2, c3, c4>
{
class inherit {};
};
template<char c0 = 0, char c1 = 0, char c2 = 0, char c3 = 0, char c4 = 0>
class whatINeedToDo
: public inheritFromAll<c0, c1, c2, c3, c4>::inherit
{
bool success(){return true;}
};
int main()
{
whatINeedToDo<'A', 'B', 'c', 'D'> experiment;
return 0;
}
I had originally though I could use Boost::Mpl to do it, but I honestly couldn't figure out how; I couldn't figure how you'd pass around a list<...> without always explicitly knowing the ... part.
Just doing:
template<> class key<0> {};
doesn't work because if I then have more than one 0 parameter, I try to inherit from the same thing twice. (If you can think of workaround for that, that'd also work).
I also haven't tried macros, because I think I know them less than I know metaprogramming, so they might work as a solution.
Any ideas?
Edit: I have a bad solution. I'd still like a meta-programming solution, for the learning, but the bad solution is this:
template<char c1, char c2, char c3> class inheritFromMany
: public key<c1>
, public key<c2>
, public key<c3>
{
};
template<char c1, char c2> class inheritFromMany<c1, c2, 0>
: key<c1>
, key<c2>
{
};
Edit2: Woof, but I forgot a part. I need to pass a variable to the constructor of ''key'' - it's the same in all cases, but it's necessary.
Edit3: Addressing comments:
I'm not expecting the user to submit the same character more than once. If they did, I would only only want to inherit from that key once - I mean, I guess I didn't mention that because you can't do that? Which is why other, simpler solutions don't work?
The actual point of this is that key is a wrapper for a signal/slot (channel) behavior. The channel keeps a list of callbacks, which is actually just virtual key<ch>::callback. So, inheriting from a key gives you access to that key's channel, lets (or makes) you supply a callback. keyInput<ch1, ch2, ch3,...> is then a wrapper for that, so you don't have to key<ch1>, key<ch2>, key<ch3>
| 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_linearly<
Values
, mpl::inherit< mpl::_1, key<mpl::_2> >
>::type
{};
// usage:
typedef mpl::vector_c<char, 1,2,3> values;
typedef derivator<values> generated;
// or:
derivator< mpl::vector_c<char, 1,2,3> > derived;
Maybe you can clarify on that basis what you need.
I need to pass a variable to the constructor of ''key'' - it's the same in all cases, but it's necessary.
Do you mean you want to pass a parameter through the inheritance-chain to all constructors? Then take a look at the solutions to this question.
As for avoiding mpl::vector_c in the visible interface, you could use your previous approach and build it internally by only inserting values not equal to zero in it:
template<char c, class S> struct push_char {
typedef typename mpl::push_front<S, mpl::char_<c> >::type type;
};
template<class S> struct push_char<0, S> {
typedef S type; // don't insert if char is 0
};
template<char c1=0, char c2=0, char c3=0>
struct char_vector {
// build the vector_c
typedef
typename push_char<c1
, typename push_char<c2
, typename push_char<c3
, mpl::vector_c<char>
>::type>::type>::type
type;
};
template<char c1=0, char c2=0, char c3=0>
struct derivator
: mpl::inherit_linearly<
typename char_vector<c1,c2,c3>::type
, mpl::inherit< mpl::_1, key<mpl::_2> >
>::type
{};
|
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:
class Anchor
{
public:
Anchor(&MeshClass, x, y)
moveAnchor(x, y);
}
The problem is when I try to make the Anchor in the MeshClass::getAnchorPoint method, something like return Anchor(this, x, y) but because this is const I can't. As a workaround until I get this figured out I have Anchor accepting a reference to the point and moveAnchor moves the point directly.
Edit: The problem was most likely something dumb I was doing with trying to use a Reference. I changed to using a pointer like I normally would and I can pass in this with no complaints from the compiler. I'm almost certain I was getting an error related to this being const, but I can't recreate it so I must just be out of my mind.
| 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, int x, int y);
}
|
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 other can simple get the pointer and start using it ??
I am using Ubuntu 9.10
| 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. a null at the end)
Now this hadn't shown up because theWholeLot was then being used to take the const char * portion using string::c_str() That meant that the null was masked as it became just a delimiter. However, when this changed to use strings throughout, the null suddenly meant something and comparisons such as:
if ( theWholeLot == "7HABITS" )
would fail. This got me thinking: Presumably the reason for ends is a throwback to the days of ostrstream when the stream was not normally terminated with a null and had to be so that str() (which then cast out not a string but a char *) would work correctly.
However, now that it's not possible to cast out a char * from a ostringstream, using ends is not only superfluous, but potentially dangerous and I'm considering removing them all from my clients code.
Can anyone see an obvious reason to use ends in a std::string only environment?
| 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 coding horror, I came to this site: http://codility.com which has this interesting programming test.
Anyway, I got 60 out of 100 in my submission, and basically ( I think ) is because this implementation of sum, because those parts where I failed are the performance parts. I'm getting TIME_OUT_ERROR's
So, I was wondering if an optimization in the algorithm is possible.
So, no built in functions or assembly would be allowed. This my be done in C, C++, C#, Java or pretty much in any other.
EDIT
As usual, mmyers was right. I did profile the code and I saw most of the time was spent on that function, but I didn't understand why. So what I did was to throw away my implementation and start with a new one.
This time I've got an optimal solution [ according to San Jacinto O(n) -see comments to MSN below - ]
This time I've got 81% on Codility which I think is good enough. The problem is that I didn't take the 30 mins. but around 2 hrs. but I guess that leaves me still as a good programmer, for I could work on the problem until I found an optimal solution:
Here's my result.
I never understood what is those "combinations of..." nor how to test "extreme_first"
| 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[] A ) {
int equi = -1;
long lower = 0;
long upper = 0;
foreach (int i in A)
upper += i;
for (int i = 0; i < A.Length; i++)
{
upper -= A[i];
if (upper == lower)
{
equi = i;
break;
}
else
lower += A[i];
}
return equi;
}
|
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 specified and exist. I heard there existed a gcc flag to delay the dependency resolution to runtime.
| 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 are in a shared library rather than
a regular object file. It does not affect how undefined symbols in regular
object files are handled.
The reason that --allow-shlib-undefined is the default is that the shared
library being specified at link time may not be the same as the one that
is available at load time, so the symbols might actually be resolvable at
load time. Plus there are some systems, (eg BeOS) where undefined symbols
in shared libraries is normal. (The kernel patches them at load time to
select which function is most appropriate for the current architecture.
This is used for example to dynamically select an appropriate memset
function). Apparently it is also normal for HPPA shared libraries to have
undefined symbols.
Allowing undefined symbols is the default, though, so I'm guessing your problem is actually something different.
|
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 and QScriptExtensionPlugin for both approaches.
|
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 boot
I am familiar with HTTP headers and am an experienced PHP and .Net web developer, but I am not sure where to start with this task.
Can you advise me with some resources to bridge the learning curve?
| 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 application, BSD socket programming for the TCP/IP network programming, and the HTTP protocol.
Commonly used texts include:
Unix application development:
Advanced Programming in the Unix Environment, Stevens & Rago
Advanced Unix Programming
TCP/IP (sockets) programming:
Unix Network Programming, Volume 1 Stevens et all
TCP/IP Illustrated, Stevens
Ineternetworking with TCP/IP, Volume 3, Comer
HTTP Protocol
RFCs including
RFC 2616 for HTTP v1.1,
RFC 2068 for pre-v1.1
plus others depending on support (compression, URI / URL) and completeness
|
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 formatted data with a stream's >> operator, but when I want to extract a string it stops at the first whitespace character. Is there a way to configure a stream to stop parsing a string only at a newline or end-of-file? I saw that there was a getline method to extract an entire line, but then I still have to split it up manually [with find_first_of], don't I?
Is there an easy way to parse data in this format using only STL?
| 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 function:
// Dispatch a message onto all connected clients
void MsgProxy::dispatch_msg(t_ic_msg_shptr message) {
deque<t_socket_shptr>::const_iterator iter = clientList_.begin();
for(; iter != clientList_.end(); ++iter) {
message->async_send(*iter,
boost::bind(&MsgProxy::handle_dispatch, this, _1, _2, _3));
}
}
For reference, the handle dispatch function looks like this:
// Called to handle result of saync_send command in dispatch_msg
void MsgProxy::handle_dispatch(t_ic_msg_shptr messsage, t_socket_shptr socket_ptr,
const boost::system::error_code &error) {
if (error) {
RDEBUG("Error forwarding message onto clients -- %s",
error.message().c_str());
}
}
And finally the async_send function that's being called:
void async_send (t_socket_shptr, t_icsend_callback);
Where t_icsend_callback is:
typedef boost::function<void (t_socket_shptr, const boost::system::error_code&)>
t_icsend_callback;
Basically I've got a function (async_send) that takes a socket to send out a message on,
as well as a callback (defined using boost::function) to report status to asynchronously. I'm trying to bind a member to that boost::function argument, but boost doesn't seem to like what I'm doing here. I've been up and down the boost::function and boost:bind documentation and it seems to me this should work... I even have a call that's almost identical a little further up that's not throwing an error... color me stumped.
| 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 argument).
|
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 C compiler.
int main() {
const int i = 1;
const int j = 2;
const int k = 3;
int array[i + j + k];
return 0;
}
| 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 <<:
short unsigned int SLWD = 11434;
S is (SLWD >> 12), L is ((SLWD << 4) >> 12),
W is ((SLWD << 8) >> 12), and D is ((SLWD << 8) >> 12)
However, I have no idea how to encompase this in a function of class, since any type of GetVal() function would have to be of type int, which defeats the purpose of isolating the bits in the first place.
| 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 worth noting that while you gain by not requiring so much storage, you lose because it becomes more costly to access everything, since each read or write now has a bunch of bit twiddling mechanics associated with it. Given that storage is cheap, it's probably not worth it.
Edit: You can also use vector<bool> to store 1-bit bools; but beware of it because it doesn't act like a normal vector! In particular, it doesn't provide iterators. It's sufficiently different that it's fair to say a vector<bool> is not actually a vector. Scott Meyers wrote very clearly on this topic in 'Effective STL'.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.