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,528,097 | 2,528,104 | problems with overloaded function members C++ | I have declared a class as
class DCFrameListener : public FrameListener, public OIS::MouseListener, public OIS::KeyListener
{
bool keyPressed(const OIS::KeyEvent & kEvt);
bool keyReleased(const OIS::KeyEvent &kEvt);
//*******some code missing************************
};
But if i try defining the members like this
bool DCFrameListener::keyPressed(const OIS::KeyEvent kEvt)
{
return true;
}
The compiler refuses with this error
error C2511: 'bool DCFrameListener::keyPressed(const OIS::KeyEvent)' : overloaded member function not found in 'DCFrameListener'
see declaration of 'DCFrameListener'
Why is this happening, yet i declared the member keyPressed(const OIS::KeyEvent) in my function declaration.
any help will be appreciated. Thanks
| The one in the declaration has a reference:
bool keyPressed(const OIS::KeyEvent & kEvt);
^!
bool DCFrameListener::keyPressed(const OIS::KeyEvent kEvt)
^?
|
2,528,199 | 2,528,234 | C++ syntax of constructors " 'Object1 a (1, Object1(2))'' | I have a such syntax in program
/* The Object1 is allowed to be changed */
class Object1 : BaseClass {
BaseClass *link;
int i;
public:
Object1(int a){i=a;}
Object1(int a, Object1 /*place1*/ o) {i=a; link= &o;}
};
int main(){
/* The initialization syntax must be preserved. No any new(), no other local objects b,c */
Object1 a(1, /*place2*/ Object1(2));
...
}
What do I need in place1? I want to save a link (pointer) to the second object in the first object. Should I use in place1 reference "&"?
What type will have "Object1(2)" in place2? Is it a constructor of the anonymous object? Will it have a "auto" storage type?
Thanks
UPDATE:
In the place2, the syntax is fixed and I really must support creating of "chain", like
Object1 a(1, Object1(2, Object1(6, Object1(999753))));
I can't add any symbol in the definiton of a.
UPDATE2:
for place1: Object1(int a, Object1 &o) {i=a; link= &o;} and Object1 a(1, Object1(2)); in place2 I have a compile error (g++):
main.cpp||In function `int main()':|
main.cpp|19|error: no matching function for call to `Object1::Object1(int, Object1)'|
main.cpp|9|note: candidates are: Object1::Object1(const Object1&)|
main.cpp|14|note: Object1::Object1(int, Object1&)|
main.cpp|13|note: Object1::Object1(int)|
| In "place1", you need a reference. Object1 isn't fully defined, so you can't take it by value. That said, you wouldn't want to pass by value; when you take the address of it, you'd be getting the address of the copy, not the actual object.
Since you only want a pointer to a BaseClass, it might make more sense to only place that restriction on the parameter. (Of course, if you really need an Object1, reflect that in the type of link: Object1* link;).
Also consider using an initialization list:
Object1(int a) : i(a), link(0) /* <- important! */ { }
Object1(int a, BaseClass& o) : i(a), link(&o) { }
Always use an initialize list.
"place2" creates an unnamed instance of Object1 using a constructor. It has no storage(?) auto storage, and dies at the end of the expression.
That is, once you've hit the semicolon in Object1 a(1, /*place2*/ Object1(2));, it ceases to exist and you have a pointer to an non-existent object! This results in undefined behavior.
Give it a lifetime beyond the expression:
Object1 x(2);
Object1 a(1, x);
Always make sure that when you refer an object, it will live the entire time you refer to it.
Your new compile error is because you can't have a reference to a temporary variable. You can have one with a const-reference, though. The thing is, your pointer needs to point to a const BaseClass now, which may dampen what you want.
Again, your design needs reworking, unfortunately.
|
2,528,274 | 2,528,296 | Native Endians and Auto Conversion | so the following converts big endians to little ones
uint32_t ntoh32(uint32_t v)
{
return (v << 24)
| ((v & 0x0000ff00) << 8)
| ((v & 0x00ff0000) >> 8)
| (v >> 24);
}
works. like a charm.
I read 4 bytes from a big endian file into char v[4] and pass it into the above function as
ntoh32 (* reinterpret_cast<uint32_t *> (v))
that doesn't work - because my compiler (VS 2005) automatically converts the big endian char[4] into a little endian uint32_t when I do the cast.
AFAIK, this automatic conversion will not be portable, so I use
uint32_t ntoh_4b(char v[])
{
uint32_t a = 0;
a |= (unsigned char)v[0];
a <<= 8;
a |= (unsigned char)v[1];
a <<= 8;
a |= (unsigned char)v[2];
a <<= 8;
a |= (unsigned char)v[3];
return a;
}
yes the (unsigned char) is necessary.
yes it is dog slow.
there must be a better way. anyone ?
| The better way, IMHO, is using the htonl and ntohl functions. If you want to be really portable you can not think in terms of "convert to little endian". Rather you should think about "convert to host endian". That's what ntohl is for, if your input is a big-endian for sure (which is what the network standard is).
Now, if you read your bytes individually, you can read them as an unsigned long (in binary mode) - this should give you a big-endian long, and then you can convert it to whatever you need - if you need host endian, then ntohl.
|
2,528,457 | 2,528,472 | Static variables in C and C++ | Is there any difference between a variable declared as static outside any function between C and C++. I read that static means file scope and the variables will not be accessible outside the file. I also read that in C, global variables are static . So does that mean that global variables in C can not be accessed in another file?
| No, there's no difference between C and C++ in this respect.
Read this SO answer about what static means in a C program. In C++ there are a couple of other meanings related to the use of static for class variables (instead of instance variables).
Regarding global vars being static - only from the point of view of memory allocation (they are allocated on the data segment, as all globals are). From the point of view of visibility:
static int var; // can't be seen from outside files
int var; // can be seen from outside files (no 'static')
|
2,528,542 | 2,553,611 | VS C++ throwing divide by zero exception after a specific check | In the following C++ code, it should be impossible for ain integer division by zero to occur:
// gradedUnits and totalGrades are both of type int
if (gradedUnits == 0) {
return 0;
} else {
return totalGrades/gradedUnits; //call stack points to this line
}
however Visual Studio is popping up this error:
Unhandled exception at 0x001712c0 in DSA_asgn1.exe: 0xC0000094: Integer division by zero.
And the stack trace points to the line indicated in the code.
UPDATE: I may have just been doing something silly here. While messing around trying to get VS to pay attention to my debug breakpoints, I rebuilt the solution and the exception isn't happening any more. It seems likely to me that I was stopping in the middle of a debug session and resuming it, when I thought I was starting new sessions.
Thanks for the responses. Would it be appropriate here to delete my question since it's resolved and wasn't really what I thought it was?
It seems like VS might just do this with any integer division, without checking whether a divide by zero is possible. Do I need to catch this exception even though the code should never be able to throw it? If so, what's the best way to go about this?
This is for an assignment that specifies VS 2005/2008 with C++. I would prefer not to make things more complicated than I need to, but at the same time I like to do things properly where possible.
| It turns out this problem was caused by the code I originally had, which did not have the divide-by-zero check, shown here:
return totalGrades/gradedUnits;
The problem was that although I'd updated the code, I was actually still in the same debug session that threw the original error, so the program was still running on the old code and threw the error again every time I restarted it.
The problem was solved by rebuilding the solution, which forced a new debug session. Simply terminating the debug session and restarting it with a rebuild would have solved it too (I just hadn't noticed I was still in the session).
|
2,528,618 | 2,528,828 | C++ invalid reference problem | I'm writing some callback implementation in C++.
I have an abstract callback class, let's say:
/** Abstract callback class. */
class callback {
public:
/** Executes the callback. */
void call() { do_call(); };
protected:
/** Callback call implementation specific to derived callback. */
virtual void do_call() = 0;
};
Each callback I create (accepting single-argument functions, double-argument functions...) is created as a mixin using one of the following:
/** Makes the callback a single-argument callback. */
template <typename T>
class singleArgumentCallback {
protected:
/** Callback argument. */
T arg;
public:
/** Constructor. */
singleArgumentCallback(T arg): arg(arg) { }
};
/** Makes the callback a double-argument callback. */
template <typename T, typename V>
class doubleArgumentCallback {
protected:
/** Callback argument 1. */
T arg1;
/** Callback argument 2. */
V arg2;
public:
/** Constructor. */
doubleArgumentCallback(T arg1, V arg2): arg1(arg1), arg2(arg2) { }
};
For example, a single-arg function callback would look like this:
/** Single-arg callbacks. */
template <typename T>
class singleArgFunctionCallback:
public callback,
protected singleArgumentCallback<T> {
/** Callback. */
void (*callbackMethod)(T arg);
public:
/** Constructor. */
singleArgFunctionCallback(void (*callback)(T), T argument):
singleArgumentCallback<T>(argument),
callbackMethod(callback) { }
protected:
void do_call() {
this->callbackMethod(this->arg);
}
};
For user convenience, I'd like to have a method that creates a callback without having the user think about details, so that one can call (this interface is not subject to change, unfortunately):
void test3(float x) { std::cout << x << std::endl; }
void test5(const std::string& s) { std::cout << s << std::endl; }
make_callback(&test3, 12.0f)->call();
make_callback(&test5, "oh hai!")->call();
My current implementation of make_callback(...) is as follows:
/** Creates a callback object. */
template <typename T, typename U> callback* make_callback(
void (*callbackMethod)(T), U argument) {
return new singleArgFunctionCallback<T>(callbackMethod, argument);
}
Unfortunately, when I call make_callback(&test5, "oh hai!")->call(); I get an empty string on the standard output. I believe the problem is that the reference gets out of scope after callback initialization.
I tried using pointers and references, but it's impossible to have a pointer/reference to reference, so I failed. The only solution I had was to forbid substituting reference type as T (for example, T cannot be std::string&) but that's a sad solution since I have to create another singleArgCallbackAcceptingReference class accepting a function pointer with following signature:
void (*callbackMethod)(T& arg);
thus, my code gets duplicated 2^n times, where n is the number of arguments of a callback function.
Does anybody know any workaround or has any idea how to fix it? Thanks in advance!
| The problem is that in make_callback(), T becomes const std::string&, which in turn becomes T in your singleArgumentCallback. U, however, is a const char*, so a temporary std::string object is created and bound to that reference in singleArgumentCallback. When make_callback() finishes, that temporary is destroyed, leaving the created singleArgumentCallback object with a reference to a no longer existing object.
What you will have to do is to first remove references (and, maybe, cv qualifiers) from the types passed into make_callback(). As Marcelo suggested, Boost.TypeTraits can help you do this, but if you want, it isn't hard to cook up something on your own:
template< typename T > struct remove_ref { typedef T result_type; };
template< typename T > struct remove_ref<T&> { typedef T result_type; };
Then change make_callback() to:
template <typename T, typename U>
callback* make_callback(void (*callbackMethod)(T), U argument)
{
typedef typename remove_ref<T>::result_type arg_type;
return new singleArgFunctionCallback<arg_type>(callbackMethod, argument);
}
|
2,528,776 | 2,529,170 | Windows/C++: Is it possible to find the line of code where exception was thrown having "Exception Offset" | One of our users having an Exception on our product startup.
She has sent us the following error message from Windows:
Problem Event Name: APPCRASH
Application Name: program.exe
Application Version: 1.0.0.1
Application Timestamp: 4ba62004
Fault Module Name: agcutils.dll
Fault Module Version: 1.0.0.1
Fault Module Timestamp: 48dbd973
Exception Code: c0000005
Exception Offset: 000038d7
OS Version: 6.0.6002.2.2.0.768.2
Locale ID: 1033
Additional Information 1: 381d
Additional Information 2: fdf78cd6110fd6ff90e9fff3d6ab377d
Additional Information 3: b2df
Additional Information 4: a3da65b92a4f9b2faa205d199b0aa9ef
Is it possible to locate the exact place in the source code where the exception has occured having this information?
What is the common technique for C++ programmers on Windows to locate the place of an error that has occured on user computer?
Our project is compiled with Release configuration, PDB file is generated.
I hope my question is not too naive.
| Yes, that's possible. Start debugging with the exact same binaries as ran by your user, make sure the DLL is loaded and you've got a matching PDB file for it. Look in Debug + Windows + Modules for the DLL base address. Add the offset. Debug + Windows + Disassembly and enter the calculated address in the Address field (prefix with 0x). That shows you the exact machine code instruction that caused the exception. Right-click + Go To Source code to see the matching source code line.
While that shows you the statement, this isn't typically good enough to diagnose the cause. The 0xc0000005 exception is an access violation, it has many possible causes. Often you don't even get any code, the program may have jumped into oblivion due to a corrupted stack. Or the real problem is located far away, some pointer manipulation that corrupted the heap. You also typically really need a stack trace that shows you how the program ended up at the statement that bombed.
What you need is a minidump. You can easily get one from your user if she runs Vista or Win7. Start TaskMgr.exe, Processes tab, select the bombed program while it is still displaying the crash dialog. Right-click it and Create Dump File.
To make this smooth, you really want to automate this procedure. You'll find hints in my answer in this thread.
|
2,528,780 | 2,528,806 | is multiple inheritance a compiler writers problem? - c++ | i have been reading about multiple inheritance
What is the exact problem with multiple inheritance?
http://en.wikipedia.org/wiki/Diamond_problem
http://en.wikipedia.org/wiki/Virtual_inheritance
http://en.wikipedia.org/wiki/Multiple_inheritance
But since the code does not compile until the ambiguity is resolved, doesn't this make multiple inheritance a problem for compiler writers only? - how does this problem affect me in case i don't want to ever code a compiler
| If you want to write code that compiles, you have to know what kind of problems might cause it to not compile and how to avoid these situations. It is your problem, as a user of the compiler, to design your inheritance hierarchies in a way that they will be compilable.
Also if you don't understand how multiple inheritance works you might have wrong assumptions about what exactly your classes do. If classes behave differently than you expect it will cause bugs when you try to use them.
|
2,528,995 | 2,529,011 | Remove \r from a string in C++ | in a C++ program, there is a point when it reads a string like:
"NONAME_1_1\r"
the \r is causing me trouble. I guess it prints or adds something like "^M". Is it right? Anyway it casues me problem, and I want to get rid of it.
I can not modify the input. I wonder how could I at this point, using C++, and in the easiest way, to remove \r for this string.
I know how to do it on bash but no clue on C++.
Thanks.
| I'm assuming that by string, you mean std::string.
If it's only the last character of the string that needs removing you can do:
mystring.pop_back();
mystring.erase(mystring.size() - 1);
Edit: pop_back() is the next version of C++, sorry.
With some checking:
if (!mystring.empty() && mystring[mystring.size() - 1] == '\r')
mystring.erase(mystring.size() - 1);
If you want to remove all \r, you can use:
mystring.erase( std::remove(mystring.begin(), mystring.end(), '\r'), mystring.end() );
|
2,529,046 | 2,530,733 | Change table columns width on resizing window or splitter | Consider there is a QTablWidget and a QTextEdit. Both of them are in a horisontal QSplitte. Let the QTable widget has 2 columns.
The problem is to resize the table columns' width as you do resize operation by moving the splitter with mouse. Are there any options to may colums to be resized synchornosly with the table?
Thanks.
| QHeaderView *header = ui->tableWidget->horizontalHeader();
header->setResizeMode(QHeaderView::Stretch);
This code sets all columns of ui->tableWidget to equal width and let it change automatically.
And take a look on QHeaderView description in docs, you can do almost anything you can imagine with table columns with this API.
Sad, but you can't set any stretch factor or smth., if you need relational column widths not to be equal, but you still can reimplement sizeHint() or resize sections when header's geometriesChanged fires.
|
2,529,617 | 2,529,625 | How to stop C++ console application from exiting immediately? | Lately, I've been trying to learn C++ from this website. Unfortunately whenever I try to run one of the code samples, I see that program open for about a half second and then immediately close. Is there a way to stop the program from closing immediately so that I can see the fruits of my effort?
| Edit: As Charles Bailey rightly points out in a comment below, this won't work if there are characters buffered in stdin, and there's really no good way to work around that. If you're running with a debugger attached, John Dibling's suggested solution is probably the cleanest solution to your problem.
That said, I'll leave this here and maybe someone else will find it useful. I've used it a lot as a quick hack of sorts when writing tests during development.
At the end of your main function, you can call std::getchar();
This will get a single character from stdin, thus giving you the "press any key to continue" sort of behavior (if you actually want a "press any key" message, you'll have to print one yourself).
You need to #include <cstdio> for getchar.
|
2,529,770 | 2,529,997 | How to use libraries compiled with MingW in MSVC? | I have compiled several libraries with MingW/MSYS... the generated static libraries are always .a files.
When I try to link the library with a MSVC project, Visual Studio throws 'unresolved external symbols' ... It means that the .a static library is incompatible with MS C++ Linker. I presume it has to be converted to a MSVC compatible .lib file.
Either .a and .lib are just AR archives of .o or .obj files, so is there any way how to use MingW compiled libs in a MSVC project? Or do I have to compile/link everything just in one compiler/linker - MSVC only/MingW only?
The MingW compiler is said to be compatible with MSVC.
I read a few threads about this topic, but they mostly say that renaming the file to .lib should do the work, but it unfortunately doesn't work for me.
The libraries Im trying to link are written in C.
MSVC Linker throws errors like:
error LNK2019: unresolved external symbol "int __cdecl openssl_call(struct ssl_State *,int,int,int)" (?openssl_call@@YAHPAUssl_State@@HHH@Z) referenced in function _main MyAPP.obj
... and 4 more same errors referring to other functions called from my app.
Thanks for any advice.
| Based on this error you put in a comment:
error LNK2019: unresolved external
symbol "int __cdecl
openssl_call(struct ssl_State
*,int,int,int)" (?openssl_call@@YAHPAUssl_State@@HHH@Z)
referenced in function _main MyAPP.obj
all other 4 errors are same only with
other functions names
Try putting extern "C" around your include files for openssl. For example:
extern "C" {
include "openssl.h"
}
using extern "C" will instruct the compiler that the functions are using C linkage, not C++, which will stop it from performing name mangling on the functions. So it will look for the function openssl_call in the library rather than ?openssl_call@@YAHPAUssl_State@@HHH@.
|
2,529,999 | 2,530,027 | What sorting algorithm is this? | Update: OK I see it's a bubble sort, but is it less efficient because it doesn't stop when there's no swap on a particular run? It runs until first is null.
Hi, I have a sorting algorithm as follows. My question is, which sorting algorithm is this? I thought it was bubble sort, but it does not do multiple runs. Any idea?
Thanks!
//sorting in descending order
struct node
{
int value;
node* NEXT;
}
//Assume HEAD pointer denotes the first element in the //linked list
// only change the valuesβ¦donβt have to change the //pointers
Sort( Node *Head)
{
node* first,second,temp;
first= Head;
while(first!=null)
{
second=first->NEXT;
while(second!=null)
{
if(first->value < second->value)
{
temp = new node();
temp->value=first->value;
first->value=second->value;
second->value=temp->value;
delete temp;
}
second=second->NEXT;
}
first=first->NEXT;
}
}
| Let's make the algorithm clearer:
Sort {
first = head;
while (first β NULL) {
next = first.next
while (next β NULL) {
if (first.value < next.value)
swap first.value and next.value
advance next
}
advance first
}
}
This is a very inefficient implementation of insertion sort.
Example run revealing the insertion sort characteristics:
5 β 2 β 3 β 1 β nil
^ ^
f n [swap]
2 β 5 β 3 β 1 β nil
^ ^
f n
2 β 5 β 3 β 1 β nil
^ ^
f n [swap]
1 β 5 β 3 β 2 β nil
^ ^
f n
1 β 5 β 3 β 2 β nil // insert the minimum value 1 to the beginning of the sublist
^ ^
f n [swap]
1 β 3 β 5 β 2 β nil
^ ^
f n [swap]
1 β 2 β 5 β 3 β nil // insert the minimum value 2 to the beginning of the sublist
^ ^
f n
1 β 2 β 5 β 3 β nil
^ ^
f n [swap]
1 β 2 β 3 β 5 β nil // insert the minimum value 3 to the beginning of the sublist
^ ^
f n
1 β 2 β 3 β 5 β nil // insert the minimum value 5 to the beginning of the sublist
^ ^
f n
1 β 2 β 3 β 5 β nil
^
f
|
2,530,124 | 2,530,165 | How to append to the beginning of a text fle in g++ | I want to write to a file without overwriting anything. It is a text file containing records. When I delete a specific record, I do not actually remove it from the file, I just put information in the header saying that it is deleted. How can I do this?
| You cannot append to the BEGINNING of a file without having to rewrite it from scratch. It has to go at the end (which makes sense, since that's what the word "append" means).
If you want to be able to flag a record as deleted without reserving space for that flag, you'll need to place the information at the end, or rewrite everything.
A more sensible approach is indeed to reserve the space upfront - for example by placing a "deleted" field in each record.
|
2,530,180 | 2,530,187 | Question about Null vs zero | I have this function:
void ToUpper(char * S)
{
while (*S!=0)
{
*S=(*S >= 'a' && *S <= 'z')?(*S-'a'+'A'):*S;
S++;
}
}
What does it mean for *S != 0, should it be null instead?
| That is checking for the end of the string which is a character which has the value of zero. It is not connected to NULL pointers in any way.
|
2,530,274 | 2,530,351 | How to overwrite only part of a file in c++ | I want to make modifications to the middle of a text file using c++, without altering the rest of the file. How can I do that?
| If the replacement string is the same length, you can make the change in place. If the replacement string is shorter, you may be able to pad it with zero-width spaces or similar to make it the same number of bytes, and make the change in place. If the replacement string is longer, there just isn't enough room unless you first move all remaining data.
|
2,530,286 | 2,530,321 | I need to create a very large array of bits/boolean values. How would I do this in C/C++? | Is it even possible to create an array of bits with more than 100000000 elements? If it is, how would I go about doing this? I know that for a char array I can do this:
char* array;
array = (char*)malloc(100000000 * sizeof(char));
If I was to declare the array by char array[100000000] then I would get a segmentation fault, since the maximum number of elements has been exceeded, which is why I use malloc.
Is there something similar I can do for an array of bits?
| If you are using C++, std::vector<bool> is specialized to pack elements into a bit map. Of course, if you are using C++, you need to stop using malloc.
|
2,530,443 | 2,530,468 | Is modifying a file without writing a new file possible in c++? | Let's say I have a text file that is 100 lines long. I want to only change what is in the 50th line.
One way to do it is open the file for input and open a new file for output. Use a for-loop to read in the first half of the file line by line and write to the second file line by line, then write what I want to change, and then write out the second half using a for-loop again. Finally, I rename the new file to overwrite the original file.
Is there another way besides this? A way to modify the contents in the middle of a file without touching the rest of the file and without writing everything out again?
If there is, then what's the code to do it?
| Open the file, use fseek to jump to the place you need and write the data, then close the file.
from http://www.cplusplus.com/reference/clibrary/cstdio/fseek/...
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ( "example.txt" , "r+" );
fputs ( "This is an apple." , pFile );
fseek ( pFile , 9 , SEEK_SET );
fputs ( " sam" , pFile );
fclose ( pFile );
return 0;
}
|
2,530,466 | 2,530,472 | funny looking comments - c++ | when i read through source files of opensource projects i often come across some weird phrases in the comments
/*
@brief ......
@usage.....
@remarks....
@par....
*/
questions
1.What are they?(were not mentioned when i was learning c++)
2.Do they have any documentation(where)
| They are just comments and as such have no special meaning in C++. They are probably to allow a documentation generator (For example Doxygen) to extract the data from the comments.
|
2,530,624 | 2,530,633 | Why won't gcc compile a class declaration as a reference argument? | This compiles fine in Visual studio, but why not in XCode?
class A()
{};
someMethod(A& a);
someMethod(A()); //error: no matching function call in XCode only :(
Is this bad form?
it seems annoying to have to write the following every time:
A a;
someMethod(a); //successful compile on Xcode
Am i missing something? I am not very experienced so thank you for any help!
| You cannot bind a temporary to a non-const reference. It would work if you changed the function to take a const reference:
someMethod(const A& a);
In addition,
A a();
does not declare a local variable. It declares a function named a that takes no parameters and returns an object of type A. You mean:
A a;
|
2,530,650 | 2,530,661 | Multiple variables in switch statement in c | How to write following statement in c using switch statement in c
int i = 10;
int j = 20;
if (i == 10 && j == 20)
{
Mymethod();
}
else if (i == 100 && j == 200)
{
Yourmethod();
}
else if (i == 1000 || j == 2000) // OR
{
Anymethod();
}
EDIT:
I have changed the last case from 'and' to 'or' later. So I appologise from people who answered my question before this edit.
This scenario is for example, I just wanted to know that is it possible or not. I have google this and found it is not possible but I trust gurus on stackoverflow more.
Thanks
| In general you can't. What you are doing already is fine, although you might want to add an else clause at the end to catch unexpected inputs.
In your specific example it seems that j is often twice the value of i. If that is a general rule you could try to take advantage of that by doing something like this instead:
if (i * 2 == j) /* Watch out for overflow here if i could be large! */
{
switch (i)
{
case 10:
// ...
break;
case 100:
// ...
break;
// ...
}
}
|
2,530,691 | 2,530,706 | Using a method of an abstract class | is it possible to use a method of an abstract class?
how can i use a method of a class without having an instance?
| If you declare a method as static, you can call it directly without needing a class instance. Otherwise you will need to have an instance of a derived class.
Since an abstract class cannot be instantiated directly, you cannot call a method of an abstract class directly unless it is a static method. But you can call a static method of an abstract class directly, here is a quick example:
#include <iostream>
#include <ostream>
#include <fstream>
using namespace std;
class stest{
public:
static void test();
virtual void a() = 0;
};
void stest::test(){ cout << "test\n"; }
int main(){
stest::test();
return 0;
}
Alternatively, if you have an instance of a class that is derived from an abstract class, you can treat it as an instance of the abstract class, and can call any methods on it.
|
2,530,738 | 2,530,753 | How to read in space-delimited information from a file in c++ | In a text file I will have a line containing a series of numbers, with each number separated by a space. How would I read each of these numbers and store all of them in an array?
| std::ifstream file("filename");
std::vector<int> array;
int number;
while(file >> number) {
array.push_back(number);
}
|
2,530,796 | 2,530,816 | issue with std::advance on std::sets | I've stumbled upon what I believe is a bug in the stl algorithm advance.
When I'm advancing the iterator off of the end of the container, I get inconsistent results. Sometimes I get container.end(), sometimes I get the last element. I've illustrated this with the following code:
#include <algorithm>
#include <cstdio>
#include <set>
using namespace std;
typedef set<int> tMap;
int main(int argc, char** argv)
{
tMap::iterator i;
tMap the_map;
for (int i=0; i<10; i++)
the_map.insert(i);
#if EXPERIMENT==1
i = the_map.begin();
#elif EXPERIMENT==2
i = the_map.find(4);
#elif EXPERIMENT==3
i = the_map.find(5);
#elif EXPERIMENT==4
i = the_map.find(6);
#elif EXPERIMENT==5
i = the_map.find(9);
#elif EXPERIMENT==6
i = the_map.find(2000);
#else
i = the_map.end();
#endif
advance(i, 100);
if (i == the_map.end())
printf("the end\n");
else
printf("wuh? %d\n", *i);
return 0;
}
Which I get the following unexpected (according to me) behavior in experiment 3 and 5 where I get the last element instead of the_map.end().
[tim@saturn advance]$ uname -srvmpio
Linux 2.6.18-1.2798.fc6 #1 SMP Mon Oct 16 14:37:32 EDT 2006 i686 athlon i386 GNU/Linux
[tim@saturn advance]$ g++ --version
g++ (GCC) 4.1.1 20061011 (Red Hat 4.1.1-30)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[tim@saturn advance]$ g++ -DEXPERIMENT=1 advance.cc
[tim@saturn advance]$ ./a.out
the end
[tim@saturn advance]$ g++ -DEXPERIMENT=2 advance.cc
[tim@saturn advance]$ ./a.out
the end
[tim@saturn advance]$ g++ -DEXPERIMENT=3 advance.cc
[tim@saturn advance]$ ./a.out
wuh? 9
[tim@saturn advance]$ g++ -DEXPERIMENT=4 advance.cc
[tim@saturn advance]$ ./a.out
the end
[tim@saturn advance]$ g++ -DEXPERIMENT=5 advance.cc
[tim@saturn advance]$ ./a.out
wuh? 9
[tim@saturn advance]$ g++ -DEXPERIMENT=6 advance.cc
[tim@saturn advance]$ ./a.out
the end
[tim@saturn advance]$ g++ -DEXPERIMENT=7 advance.cc
[tim@saturn advance]$ ./a.out
the end
[tim@saturn advance]$
From the sgi website (see link at top), it has the following example:
list<int> L;
L.push_back(0);
L.push_back(1);
list<int>::iterator i = L.begin();
advance(i, 2);
assert(i == L.end());
I would think that the assertion should apply to other container types, no?
What am I missing?
Thanks!
|
When I'm advancing the iterator off of the end of the container, ...
... you get undefined behavior. Whatever happens then, is fine according to the C++ standard. That could be much worse than inconsistent results.
|
2,530,806 | 2,794,213 | Problem with displaying graphs on a Qt canvas | Let's say I'm a Qt newbie.
I want a good Qt library for displaying simple graphs. I've found the quanava library. But there is a problem. When I compiled a basic example it looks like graph edges are not painted properly when moving nodes. I don't have any idea where is a bug but this code seems to be rather simple. I think this is a problem with paint method in NodeItem class. Maybe someone has already solved this problem because this library is quite popular.
| Ok, first of all saying graph i mean mathematical concept G=(V,E).
I improved quanava library, which is a very good starting point for graph visualization.
|
2,530,842 | 2,530,889 | Calling a constructor to reinitialize variables doesn't seem to work? | I wanted to run 1,000 iterations of a program, so set a counter for 1000 in main. I needed to reinitialize various variables after each iteration, and since the class constructor had all the initializations already written out - I decided to call that after each iteration, with the result of each iteration being stored in a variable in main.
However, when I called the constructor, it had no effect...it took me a while to figure out - but it didn't reinitialize anything!
I created a function exactly like the constructor - so the object would have its own version. When I called that, it reinitialized everything as I expected.
int main()
{
Class MyClass()
int counter = 0;
while ( counter < 1000 )
{ stuff happens }
Class(); // This is how I tried to call the constructor initially.
// After doing some reading here, I tried:
// Class::Class();
// - but that didn't work either
/* Later I used...
MyClass.function_like_my_constructor; // this worked perfectly
*/
}
...Could someone try to explain why what I did was wrong, or didn't work, or was silly or what have you? I mean - mentally, I just figured - crap, I can call this constructor and have all this stuff reinitialized. Are constructors (ideally) ONLY called when an object is created?
| Your line Class(); does call the constructor of the class Class, but it calls it in order to create a "temporary object". Since you don't use that temporary object, the line has no useful effect.
Temporary objects (usually) disappear at the end of the expression in which they appear. They're useful for passing as function parameters, or initializing other objects. It's almost never useful to just create one in a statement alone. The language allows it as a valid expression, it's just that for most classes it doesn't do very much.
There is no way in C++ to call a constructor on an object which has already been constructed. The lifecycle of a C++ object is one construction, and one destruction. That's just how it works. If you want to reset an object during its life, you've done the right thing, which is to call a function to reset it. Depending on your class you might not need to write one - the default assignment operator might do exactly what you need. That's when a temporary can come in handy:
Class myObject;
// ... do some stuff to myObject ...
myObject = Class();
This updates myObject with the values from the freshly-constructed temporary. It's not necessarily the most efficient possible code, since it creates a temporary, then copies, then destroys the temporary, rather than just setting the fields to their initial values. But unless your class is huge, it's unlikely that doing all that 1000 times will take a noticeable amount of time.
Another option is just to use a brand new object for each iteration:
int main() {
int counter = 0;
while (counter < 1000) {
Class myObject;
// stuff happens, each iteration has a brand new object
}
}
Note that Class MyClass(); does not define an object of type Class, called MyClass, and construct it with no parameters. It declares a function called MyClass, which takes no parameters and which returns an object of type Class. Presumably in your real code, the constructor has one or more parameters.
|
2,530,843 | 2,530,857 | Deriving a class from an abstract class (C++) | I have an abstract class with a pure virtual function f() and i want to create a class inherited from that class, and also override function f(). I seperated the header file and the cpp file.
I declared the function f(int) in the header file and the definition is in the cpp file. However, the compiler says the derived class is still abstract.
How can i fix it?
| The functions f() and f(int) do not have the same signature, so the second would not provide an implementation for the first. The signatures of the PVF and the implementation must match exactly.
|
2,530,864 | 2,531,041 | gcc precompiled headers weird behaviour with -c option | Short story:
I can't make precompiled headers work properly with gcc -c option.
Long story:
Folks, I'm using gcc-4.4.1 on Linux and before trying precompiled headers in a really large project I decided to test them on simple program. They "kinda work" but I'm not happy with results and I'm sure there is something wrong about my setup.
First of all, I wrote a simple program(main.cpp) to test if they work at all:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/type_traits.hpp>
int main()
{
return 0;
}
Then I created the precompiled headers file pre.h(in the same directory) as follows:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/type_traits.hpp>
...and compiled it:
$ g++ -I. pre.h
(pre.h.gch was created)
After that I measured compile time with and without precompiled headers:
with pch
$ time g++ -I. -include pre.h main.cpp
real 0m0.128s
user 0m0.088s
sys 0m0.048s
without pch
$ time g++ -I. main.cpp
real 0m0.838s
user 0m0.784s
sys 0m0.056s
So far so good! Almost 7 times faster, that's impressive! Now let's try something more realistic. All my sources are built with -c option and for some reason I can't make pch play nicely with it. You can reproduce this with the following steps below...
I created the test module foo.cpp as follows:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/type_traits.hpp>
int whatever()
{
return 0;
}
Here are the timings of my attempts to build the module foo.cpp with and without pch:
with pch
$ time g++ -I. -include pre.h -c foo.cpp
real 0m0.357s
user 0m0.348s
sys 0m0.012s
without pch
$ time g++ -I. -c foo.cpp
real 0m0.330s
user 0m0.292s
sys 0m0.044s
That's quite strange, looks like there is no speed up at all!(I ran timings for several times). It turned out precompiled headers were not used at all in this case, I checked it with -H option(output of "g++ -I. -include pre.h -c foo.cpp -H" didn't list pre.h.gch at all).
What am I doing wrong?
| Ok, I think I've found the solution: -fpch-preprocess should be used alongside with -c option. It works like a charm!
Here's the timings:
with pch
$ time g++ -I. -include pre.h -c foo.cpp -fpch-preprocess
real 0m0.028s
user 0m0.016s
sys 0m0.016s
without pch
$ time g++ -I. -c foo.cpp
real 0m0.330s
user 0m0.292s
sys 0m0.044s
Update: I asked the same question on the gcc help mailing list and Ian Lance Taylor explained this strange behavior by my usage of distcc/ccache. These tools first preprocess the source that's why this options is required.
|
2,530,996 | 2,531,006 | Custom http service responds fine to local IP address but NOT to localhost or 127.0.0.1 | I'm trying to connect to a custom http service written by another developer.
The service responds fine on a local IP address and port number. Such as: http://10.1.1.1:1234 but it does NOT respond to http://localhost:1234 or http://127.0.0.1:1234
The service is a simple single function application written in VC++ that takes an http post string and returns another string.
I'm trying to all it from C# using HttpWebRequest.GetResponse, but I can reproduce the same problem manually from a web browser...
Test environment is Windows 2008 Server.
Bottom line I'm looking for some troubleshooting tips to help the other developer fix his code.
| The HTTP server socket is bound to the network ip of the server. It needs to be bound to all the interfaces on the host machine. (this will include the loopback interface, localhostor 127.0.0.1)
|
2,531,000 | 2,531,089 | C++ whats the difference between uint64 and *uint64? | Why does:
const char example;
(uint64*)example have a value of 140734799798420
and
*(uint64*)example have a value of 7004431430466964258
p.s. dont worry about the type cast, I am interested why the second * increases the value.
Thanks
| As others have said, you've invoked undefined behavior. No particular behavior is guaranteed.
That said, you see different values because you are printing different locations in memory -- the first prints data from the memory location where example is stored, and the second prints data from the memory location stored as the value of example.
const char example
Defines a char variable on the stack without initializing it, so its value will be garbage; probably whatever was last stored in the location on the stack where it was allocated.
(uint64 *)example
Interprets the value of example as a pointer to (the address of) a uint64. This prints out the value stored in example as if it were a pointer.
*(uint64 *)example
Dereferences that pointer. It interprets the value of example as a pointer to (the address of) a uint64, then prints what is at that address as if it were a uint64.
|
2,531,063 | 2,531,092 | virtual methods and template classes | I got over a problem, I think a very specific one.
I've got 2 classes, a B aseclass and a D erived class (from B aseclass).
B is a template class ( or class template) and has a pure virtual method virtual void work(const T &dummy) = 0;
The D erived class is supposed to reimplement this, but as D is Derived from B rather than D being another template class, the compiler spits at me that virtual functions and templates don't work at once.
Any ideas how to accomplish what I want?
I am thankfull for any thoughts and Ideas, especially if you allready worked out that problem
this class is fixed aka AS IS, I can not edit this without breaking existing code base
template <typename T>
class B {
public:
...
virtual void work(const T &dummy) = 0;
..
};
take int* as an example
class D : public B<int*>{
...
virtual void work(const int* &dummy){ /* put work code here */ }
..
};
Edit: The compiler tells me, that void B<T>::work(const T&) [with T = int*] is pure virtual within D
| You placed the const in the wrong place. Try
virtual void work(int* const &dummy){ /* put work code here */ }
const int* is the same as int const*, i.e. it associates the const with the int and not the pointer.
|
2,531,359 | 2,531,397 | Do condition variables still need a mutex if you're changing the checked value atomically? | Here is the typical way to use a condition variable:
// The reader(s)
lock(some_mutex);
if(protected_by_mutex_var != desired_value)
some_condition.wait(some_mutex);
unlock(some_mutex);
// The writer
lock(some_mutex);
protected_by_mutex_var = desired_value;
unlock(some_mutex);
some_condition.notify_all();
But if protected_by_mutex_var is set atomically by say, a compare-and-swap instruction, does the mutex serve any purpose (other than that pthreads and other APIs require you to pass in a mutex)? Is it protecting state used to implement the condition? If not, is it safe then to do this?:
// The writer
atomic_set(protected_by_mutex_var, desired_value);
some_condition.notify_all();
With the writer never directly interacting with the reader's mutex? Note that the 'protected_by_mutex_var' name is no longer really appropriate (it's not mutex protected anymore). If so, is it even necessary that different readers use the same mutex?
| Imagine the following scenario:
| Thread 1 | Thread 2 |
| if(protected_by_mutex_var != desired_value) -> true | |
| | atomic_set(protected_by_mutex_var, desired_value); |
| | some_condition.notify_all(); |
| some_condition.wait(some_mutex); | |
This situation sees Thread 1 waiting for a notify that may never come.
Because the statements acting on the condition are not part of the variable read / atomic set, this presents a race condition.
Using the mutex effectively makes these actions inseparable (assuming all accesses to the variable behave properly and lock the mutex.)
|
2,531,515 | 2,531,522 | Can someone explain this "endian-ness" function for me? | Write a program to determine whether a computer is big-endian or little-endian.
bool endianness() {
int i = 1;
char *ptr;
ptr = (char*) &i;
return (*ptr);
}
So I have the above function. I don't really get it. ptr = (char*) &i, which I think means a pointer to a character at address of where i is sitting, so if an int is 4 bytes, say ABCD, are we talking about A or D when you call char* on that? and why?
Would some one please explain this in more detail? Thanks.
So specifically, ptr = (char*) &i; when you cast it to char*, what part of &i do I get?
| If you have a little-endian architecture, i will look like this in memory (in hex):
01 00 00 00
^
If you have a big-endian architecture, i will look like this in memory (in hex):
00 00 00 01
^
The cast to char* gives you a pointer to the first byte of the int (to which I have pointed with a ^), so the value pointed to by the char* will be 01 if you are on a little-endian architecture and 00 if you are on a big-endian architecture.
When you return that value, 0 is converted to false and 1 is converted to true. So, if you have a little-endian architecture, this function will return true and if you have a big-endian architecture, it will return false.
|
2,531,848 | 2,531,856 | How can I round money values to the nearest $5.00 interval? | I have an Informix-SQL based Pawnshop app which calculates an estimate of how much money should be loaned to a customer, based on the weight and purity of gold. The minimum the pawnshop lends is $5.00. The pawnshop employee will typically lend amounts which either ends with a 5 or 0. examples: 10, 15, 20, 100, 110, 125, etc. They do this so as to not run into shortage problems with $1.00 bills. So, if for example my system calculates the loan should be: $12.49, then round it to $10, $12.50 to $15.00, $13.00 to $15.00, $17.50 to $20.00, and so on!..The employee can always override the rounded amount if necessary. Is it possible to accomplish this within the instructions section of a perform screen or would I have to write a cfunc and call it from within perform?.. Are there any C library functions which perform interval rounding of money values?.. On another note, I think the U.S. Government should discontinue the use of pennies so that businesses can round amounts to the nearest nickel, it would save so much time and weight in our pockets!
| I'd just divide by 5, round to the appropriate integer, and multiply by 5.
There might be an easier way but that would work.
|
2,531,968 | 2,531,992 | Intermediate values in C++ | I can not find how to implement a design in C++. In the language of Delphi in case the operator can write the following design:
case s[j] of
'0'..'9','A'..'Z','a'..'z','_': doSomeThing();
How can i do the same in c++. Attracts me is the construction type 'a' .. 'z' and etc...
Thank you
| The short answer is that it is impossible. You can simulate a list of values like this:
switch (s[j])
{
case '0':
case '1':
case '2':
case '3':
doSomething1();
break;
case 'a':
case 'b':
case 'c':
case 'd':
doSomething2();
break;
}
But you cannot specify ranges. You should use if-else-if if you need ranges:
if ( (s[j] >= '0') && (s[j] <= '9'))
doSomething1();
else if ( (s[j] >= 'a') && (s[j] <= 'z'))
doSomething2();
Anyway, if's are much more safe than switch's :-)
|
2,532,105 | 2,532,111 | question regarding "this" pointer in c++ | i have been given class with int variables x and y in private, and an operator overload function,
class Bag{
private:
int x;
int y;
public:
Bag();
~Bag();
//.......
//.....etc
};
Bag operator+ (Bag new) const{
Bag result(*this); //what does this mean?
result.x += new.x;
result.y += new.y;
}
What is the effect of having "Bag result(*this);" there?.
| Bag result(*this) creates a copy of the object on which the operator function was called.
Example if there was:
sum = op1 + op2;
then result will be a copy of op1.
Since the operator+ function is doing a sum of its operands and returning the sum, we need a way to access the operand op1 which is done through the this pointer.
Alternatively we could have done:
Bag result;
result.x = (*this).x + newobj.x; // note you are using new which is a keyword.
result.y = (*this).y + newobj.y; // can also do this->y instead
return result;
|
2,532,107 | 2,532,119 | Why are data members private by default in C++? | Is there any particular reason that all data members in a class are private by default in C++?
| Because it's better to be properly encapsulated and only open up the things that are needed, as opposed to having everything open by default and having to close it.
Encapsulation (information hiding) is a good thing and, like security (for example, the locking down of network services), the default should be towards good rather than bad.
|
2,532,290 | 2,532,297 | How to compile and build c++ application with hand written makefile in windows? | Can someone provide a HelloWorld demo ?
| There's an nmake tutorial available here (nmake is what comes with visual studio).
Is there something more specific you're trying to do? It would help get a better answer. Are there some specific differences with Windows that concern you?
|
2,532,412 | 2,532,418 | When is .h not needed to include a header file? | This works:
#include <iostream>
using namespace std;
but this fails:
#include <stdio>
When is .h not needed?
About the namespace issue,I didn't find such logic in cstdio:
#pragma once
#ifndef _CSTDIO_
#define _CSTDIO_
#include <yvals.h>
#ifdef _STD_USING
#undef _STD_USING
#include <stdio.h>
#define _STD_USING
#else /* _STD_USING */
#include <stdio.h>
#endif /* _STD_USING */
// undef common macro overrides
#undef clearerr
#undef feof
#undef ferror
#undef getc
#undef getchar
#undef putc
#undef putchar
#define _HAS_CONVENTIONAL_CLIB 1
#define _IOBASE _base
#define _IOPTR _ptr
#define _IOCNT _cnt
#ifndef _FPOSOFF
#define _FPOSOFF(fp) ((long)(fp))
#endif /* _FPOSOFF */
typedef FILE _Filet;
#ifndef RC_INVOKED
#if _GLOBAL_USING
_STD_BEGIN
using ::_Filet;
using ::size_t; using ::fpos_t; using ::FILE;
using ::clearerr; using ::fclose; using ::feof;
using ::ferror; using ::fflush; using ::fgetc;
using ::fgetpos; using ::fgets; using ::fopen;
using ::fprintf; using ::fputc; using ::fputs;
using ::fread; using ::freopen; using ::fscanf;
using ::fseek; using ::fsetpos; using ::ftell;
using ::fwrite; using ::getc; using ::getchar;
using ::gets; using ::perror;
using ::putc; using ::putchar;
using ::printf; using ::puts; using ::remove;
using ::rename; using ::rewind; using ::scanf;
using ::setbuf; using ::setvbuf; using ::sprintf;
using ::sscanf; using ::tmpfile; using ::tmpnam;
using ::ungetc; using ::vfprintf; using ::vprintf;
using ::vsprintf;
_STD_END
#endif /* _GLOBAL_USING */
#endif /* RC_INVOKED */
#endif /* _CSTDIO_ */
| It's not needed for the header files defined by the C++ Standard, none of which have a .h extension. The C++ version of stdio.h is:
#include <cstdio>
which wraps stdio.h, placing the names in it in the C++ std namespace,
but you can still use all the C Standard header files in C++ code, if you wish.
Edit: The macro that places the names in the std namespace in the GCC version of cstdio is:
_GLIBCXX_BEGIN_NAMESPACE(std)
You can check that your own header does what it should do by trying to use something like:
std::printf( "hello" );
in your code.
|
2,532,422 | 2,532,428 | Conversion of pointer-to-pointer between derived and base classes? | Regarding the following C++ program:
class Base { };
class Child : public Base { };
int main()
{
// Normal: using child as base is allowed
Child *c = new Child();
Base *b = c;
// Double pointers: apparently can't use Child** as Base**
Child **cc = &c;
Base **bb = cc;
return 0;
}
GCC produces the following error on the last assignment statement:
error: invalid conversion from βChild**β to βBase**β
My question is in two parts:
Why is there no implicit conversion from Child** to Base**?
I can make this example work with a C-style cast or a reinterpret_cast. Using these casts means throwing away all type safety. Is there anything I can add to the class definitions to make these pointers cast implicitly, or at least phrase the conversion in a way that allows me to use static_cast instead?
| If this was allowed, you could write this:
*bb = new Base;
And c would end up pointing to an instance of Base. Bad.
|
2,532,454 | 2,543,150 | Subclassing and adding data members | I have an hierarchy of classes that looks like the following:
class Critical
{
public:
Critical(int a, int b) : m_a(a), m_b(b) { }
virtual ~Critical() { }
int GetA() { return m_a; }
int GetB() { return m_b; }
void SetA(int a) { m_a = a; }
void SetB(int b) { m_b = b; }
protected:
int m_a;
int m_b;
};
class CriticalFlavor : public Critical
{
public:
CriticalFlavor(int a, int b, int flavor) : Critical(a, b), m_flavor(flavor) { }
virtual ~CriticalFlavor() { }
int GetFlavor() { return m_flavor; }
void SetFlavor(int flavor) { m_flavor = flavor; }
protected:
int m_flavor;
};
class CriticalTwist : public Critical
{
public:
CriticalTwist(int a, int b, int twist) : Critical(a, b), m_twist(twist) { }
virtual ~CriticalTwist() { }
int GetTwist() { return m_twist; }
void SetTwist(int twist) { m_twist = twist; }
protected:
int m_twist;
};
The above does not seem right to me in terms of the design and what bothers me the most is
the fact that the addition of member variables seems to drive the interface of these classes
(the real code that does the above is a little more complex but still embracing the same pattern).
That will proliferate when in need for another "Critical" class that just adds some other
property.
Does this feel right to you? How could I refactor such code?
An idea would be to have just a set of interfaces and use composition when it comes to the base object
like the following:
class Critical
{
public:
virtual int GetA() = 0;
virtual int GetB() = 0;
virtual void SetA(int a) = 0;
virtual void SetB(int b) = 0;
};
class CriticalImpl : public Critical
{
public:
CriticalImpl(int a, int b) : m_a(a), m_b(b) { }
~CriticalImpl() { }
int GetA() { return m_a; }
int GetB() { return m_b; }
void SetA(int a) { m_a = a; }
void SetB(int b) { m_b = b; }
private:
int m_a;
int m_b;
};
class CriticalFlavor
{
public:
virtual int GetFlavor() = 0;
virtual void SetFlavor(int flavor) = 0;
};
class CriticalFlavorImpl : public Critical, public CriticalFlavor
{
public:
CriticalFlavorImpl(int a, int b, int flavor) : m_flavor(flavor), m_critical(new CriticalImpl(a, b)) { }
~CriticalFlavorImpl() { delete m_critical; }
int GetFlavor() { return m_flavor; }
void SetFlavor(int flavor) { m_flavor = flavor; }
int GetA() { return m_critical->GetA(); }
int GetB() { return m_critical->GetB(); }
void SetA(int a) { m_critical->SetA(a); }
void SetB(int b) { m_critical->SetB(b); }
private:
int m_flavor;
CriticalImpl* m_critical;
};
| My suggestion: find the most patient person you work with who is familiar with this code, and ask them some of these questions. I assume you are not posting a more complete example because of IP concerns. That makes it hard to provide good advice.
Based on your first code sample, I would say just use structs with public data and no accessors. But if I saw the real code, I would probably change my tune.
For your second code sample: A benefit is that you could have another class depend on CriticalFlavor without knowing anything about Critical (could be used to implement something like the Bridge pattern, for example). But if that potential benefit isn't an actual benefit in your situation, then it's just making your code unnecessarily complicated and YAGNI (probably).
The comments from your reviewers:
base classes should be abstract
I would say, "base classes usually should have at least one virtual method, other than the destructor". If not, then it's just a means to share common code or data amongst other classes; try to use composition instead.
Most of the time, at least one of those virtual methods will be pure virtual, so the base class will be abstract. But sometimes there is a good default implementation for every virtual method and subclasses will pick and choose which to override. In that case, make the base class constructors protected to prevent instantiation of the base class.
protected members are not advisable in base classes
... and they're completely pointless in non-base classes, so this advice basically says to never use them.
When are protected member variables advisable? Infrequently. Your code example isn't realistic enough to determine what you're trying to do or how it could be best written. The members are protected, but there are public getters/setters, so they're essentially public.
design by interface
Don't get carried away by this, or you may end up with an amazingly complicated design for an amazingly simple task. Use interfaces where they make sense. It's hard to tell if they make sense without seeing some of the "calling code" that uses Critical and its subclasses. Who calls GetFlavor and GetTwist?
Does the calling code only interact with Critical subclasses via the Critical interface, or does the calling code know the specific subclass and call specific subclass methods? Have you added interface methods to Critical in order to provide access to data/functionality only present in some of the subclasses? That can be a bad smell.
Your comment:
the addition of member variables seems to drive the interface of these classes
makes me think of an item in C++ Coding Standards (Sutter/Alexandrescu): "Be clear what kind of class you're writing". Sorry, no online reference to that item (buy the book).
Let me also suggest that you honestly evaluate your skill level and that of your reviewers. Are your reviewers experienced C++ developers who really know what they are talking about (if so, listen!), or have they just returned from Code Review 101 and know to say things like "public data is bad" and "destructors should always be virtual"? If the latter, hopefully you can respond to the review comments by saying, "That's generally good advice, but does not apply in this situation because XYZ."
|
2,532,495 | 2,532,577 | C++ struct, public data members and inheritance | Is it ok to have public data members in a C++ class/struct in certain particular situations?
How would that go along with inheritance?
I've read opinions on the matter, some stated already here
practices on when to implement accessors on private member variables rather than making them public
Accessors vs. public members
or in books/articles (Stroustrup, Meyers) but I'm still a little bit in the shade.
I have some configuration blocks that I read from a file (integers, bools, floats) and
I need to place them into a structure for later use. I don't want to expose these externally just use them inside another class (I actually do want to pass these config parameters to another class but don't want to expose them through a public API).
The fact is that I have many such config parameters (15 or so) and writing getters and setters seems an unnecessary overhead. Also I have more than one configuration block and these are sharing some of the parameters. Making a struct with all the data members public and then subclassing does not feel right. What's the best way to tackle that situation?
Does making a big struct to cover all parameters provide an acceptable compromise (I
would have to leave some of these set to their default values for blocks that do not use them)?
| If you have a data structure that isn't intended to have behaviour but genuinely is nothing more than a pure struct in the C sense, particularly if each instance of it is only used internally to the implementation of other "proper" classes, then it is fine to make it a struct and have public fields. After all, as you've pointed out, once you've given it get/set accessor functions for every field then you're back to the logical equivalent of public data anyway.
|
2,532,534 | 2,533,911 | C++ Professional Code Analysis Tools | I would like to ask about the available (free or not) Static and Dynamic code analysis tools that can be used to C++ applications ESPECIALLY COM and ActiveX.
I am currently using Visual Studio's /analyze compiler option, which is good and all but I still feel there is lots of analysis to be done.
I'm talking about a C++ application where memory management and code security is of utmost importance.
I'm trying to check for problems relating to security such as memory management, input validation, buffer overflows, exception handling... etc
I'm not interested in, say, inheritance depth or lines of executable code.
| Without a doubt you want to use Axman. This is by far the best ActiveX/Com security testing tool available, and its open source. This was one of the leading tools used in the Month Of Browser Bugs by H.D. Moore, who is also the creator of Metasploit. I I have personally used Axman to find vulnerabilities and write exploit code.
Axman uses TypeLib to identify all of the components that makeup a COM . This is a type relfection, and it means that Source code is not required. Axman uses reflection to automatically generate fuzz test cases against a COM.
|
2,532,542 | 2,532,658 | What does using mean in c++? | Like :
using ::size_t; using ::fpos_t; using ::FILE;
In fact it's a question inspired by the comment under this question:
When is .h not needed to include a header file?
| This is called using declaration. There are actually two ways you can use the using keyword. There is a third special form of using declarations used inside class definitions, but i'll focus on the general using declaration here. (see below).
using declaration
using directive
These have two very different effects. A using declaration declares a name to be an alias to another declaration or a set of declarations (if you were to name a set of overloaded functions). The name is declared in the current scope. That is, you can use it inside blocks too
int main() {
using std::swap;
// ...
}
This is quite useful if you use a name very often locally and you don't want to prefix it in all uses, and it's also useful in implementing the swap using argment dependent lookup idiom.
A using directive names a namespace and does not declare any names. Instead it will modify name lookup to find names that aren't really declared where it thinks they are. For unqualified name lookup, it find names declared in the enclosing namespace that encloses both the using directive and the target namespace. All names that are declared in the target namespaces will be found:
int cout;
int main() {
using namespace std;
// cout << 1; ambiguous!
}
Here, cout will be thought as being declared twice in the global namespace, and causes an ambiguity (:: encloses both main and std). In qualified namelookup, it will build the transitive closure of a namespace with all the namespaces named in using directives.
using namespace foo;
int main() {
::c++;
}
c is not only looked up in the global namespace, but also in the namespace foo and in the namespaces that foo has using directives for and so on. If however the global namespace would contain a direct declaration (including a using declaration), that declaration will hide the declarations found indirectly by using directives:
using namespace foo;
int c;
int main() {
::c++; // not ambiguous!
}
Using declarations can appear in many places, including inside class definitions. Its meaning is similar to its meaning otherwhere with an important restriction: It declares a name to be an alias to one or more declarations, but the declarations must be members of a base class. This is very useful for making names visible in a derived class that would otherwise be hidden by the same name declared there
struct base {
void f();
};
struct derived : base {
using base::f; // name "f" declared in derived
void f(int); // overloads the using declaration
};
Now you can call d.f(). If there were no using declaration, then name lookup would only find one declaration of f in derived and stop lookup, not delving into the base class scope:
derived d;
d.f(); // invalid without the using declaration
d.f(0); // valid with or without the using declaration
// explicitly starting lookup in base: valid with or without the using declaration
d.base::f();
It also allows to change the accessibility of base-class members, although you should use that sparingly :)
In practice, i found it useful for making virtual member function re-visible:
struct base {
virtual void f();
virtual void f(int);
};
struct derived : base {
// using base::f; would solve it
virtual void f() { ... }
};
Oops - now d.f(0); is invalid because name lookup only finds the zero parameter f! The using directive would solve it. Notice that if you alias a function declaration that has the same parameter types and constness as an explicit declaration (like f() in this case), then the explicit declaration will still hide the one that the using declaration is an alias for - so both f() functions won't conflict in this case.
An alternative to solve this is using the non-virtual interface idiom
struct base {
void f() { do_f(); }
void f(int) { do_f(0); }
private:
virtual void do_f();
virtual void do_f(int);
};
struct derived : base {
private:
virtual void do_f() { ... }
};
struct derived1 : derived {
private:
virtual void do_f(int) { ... }
};
Now, both d.f(0) and d.f() are valid no matter on what object you call it.
|
2,532,625 | 2,532,691 | Remove from a std::set<shared_ptr<T>> by T* | I have a set of shared pointers:
std::set<boost::shared_ptr<T>> set;
And a pointer:
T* p;
I would like to efficiently remove the element of set equal to p, but I can't do this with any of the members of set, or any of the standard algorithms, since T* is a completely different type to boost::shared_ptr<T>.
A few approaches I can think of are:
somehow constructing a new shared_ptr from the pointer that won't take ownership of the pointed to memory (ideal solution, but I can't see how to do this)
wrapping / re-implementing shared_ptr so that I can do the above
just doing my own binary search over the set
| Construct a shared_ptr<T> from T with a null_deleter (see boost:::shared_ptr FAQ).
struct null_deleter {
void operator()(void const *) const { }
};
size_t remove_ptr_from_set(std::set<boost::shared_ptr<T>> &set, X* x)
{
shared_ptr<X> px(x, null_deleter());
return set.erase(px);
}
That way the types are compatible and you don't have to worry about your temporary shared_ptr deleting any object.
Or, as one of the comments say, if you can change T to inherit from enable_shared_from_this you could get a correct shared ptr from your object.
|
2,532,714 | 2,532,781 | Does replacing statements by expressions using the C++ comma operator could allow more compiler optimizations? | The C++ comma operator is used to chain individual expressions, yielding the value of the last executed expression as the result.
For example the skeleton code (6 statements, 6 expressions):
step1;
step2;
if (condition)
step3;
return step4;
else
return step5;
May be rewritten to: (1 statement, 6 expressions)
return step1,
step2,
condition?
step3, step4 :
step5;
I noticed that it is not possible to perform step-by-step debugging of such code, as the expression chain seems to be executed as a whole. Does it means that the compiler is able to perform special optimizations which are not possible with the traditional statement approach (specially if the steps are const or inline)?
Note: I'm not talking about the coding style merit of that way of expressing sequence of expressions! Just about the possible optimisations allowed by replacing statements by expressions.
| Most compilers will break your code down into "basic blocks", which are stretches of code with no jumps/branches in or out. Optimisations will be performed on a graph of these blocks: that graph captures all the control flow in the function. The basic blocks are equivalent in your two versions of the code, so I doubt that you'd get different optimisations. That the basic blocks are the same isn't entirely obvious: it relies on the fact that the control flow between the steps is the same in both cases, and so are the sequence points. The most plausible difference is that you might find in the second case there is only one block including a "return", and in the first case there are two. The blocks are still equivalent, since the optimiser can replace two blocks that "do the same thing" with one block that is jumped to from two different places. That's a very common optimisation.
It's possible, of course, that a particular compiler doesn't ignore or eliminate the differences between your two functions when optimising. But there's really no way of saying whether any differences would make the result faster or slower, without examining what that compiler is doing. In short there's no difference between the possible optimisations, but it doesn't necessarily follow that there's no difference between the actual optimisations.
The reason you can't single-step your second version of the code is just down to how the debugger works, not the compiler. Single-step usually means, "run to the next statement", so if you break your code into multiple statements, you can more easily debug each one. Otherwise, if your debugger has an assembly view, then in the second case you could switch to that and single-step the assembly, allowing you to see how it progresses. Or if any of your steps involve function calls, then you may be able to "do the hokey-cokey", by repeatedly doing "step in, step out" of the functions, and separate them that way.
|
2,532,725 | 2,532,741 | gcc returns error with nested class | I am attempting to use the fully qualified name of my nested class as below, but the compiler is balking!
template <class T> class Apple {
//constructors, members, whatevers, etc...
public:
class Banana {
public:
Banana() {
//etc...
}
//other constructors, members, etc...
};
};
template <class K> class Carrot{
public:
//etc...
void problemFunction()
{
Apple<int>::Banana freshBanana = someVar.returnsABanana(); //line 85
giveMonkey(freshBanana); //line 86
}
};
My issue is, the compiler says:
Carrot.h:85: error: expected ';' before 'freshBanana'
Carrot.h:86: error: 'freshBanana' was not declared in this scope
I had thought that using the fully qualified name permitted me to access this nested class? It's probably going to smack me in the face, but what on earth am I not seeing here??
| That's probably not what you do in your code. The error message looks like you do this
Apple<K>::Banana freshBanana = someVar.returnsABanana();
The compiler has to know before it parses the code whether a name names a type or not. In this case, when it parses, it cannot know because what type K is, is not yet known (you could have a specialization for Apple<int> that doesn't have that nested class). So it assumes Apple<K>::Banana is not a type. But then, it is an expression and an operator is needed after it or a semicolon.
You can fix it by inserting typename:
typename Apple<K>::Banana freshBanana = someVar.returnsABanana();
That asserts the name is a type, and the compiler then knows to parse this as a declaration.
|
2,532,907 | 2,532,917 | Combining C++ and C# | Is it a good idea to combine C++ and C# or does it pose any immediate issues?
I have an application that needs some parts to be C++, and some parts to be C# (for increased efficiency). What would be the best way to achieve using a native C++ dll in C#?
| Yes using C# and C++ for your product is very common and a good idea.
Sometimes you can use managed C++, in which case you can use your managed C++ module just like any other .NET module.
Typically you'd do everything that you can in C#. For the parts you need to do in C++ you'd typically create a C++ DLL and then call into that DLL from C#. Marshalling of parameters is done automatically for you.
Here is an example of importing a C function inside a DLL into C#:
[DllImport("user32", CharSet=CharSet.Auto, SetLastError=true)]
internal static extern int GetWindowText(IntPtr hWnd, [Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpString, int nMaxCount);
|
2,532,983 | 2,533,095 | Free Cryptography libraries | What are the most stable and useful Cryptography libraries, that they are:
written with/for python, c++, c#, .net
opensource, GNU, or other free license
| The standard Python library (implementing common ciphers like AES and RSA) is PyCrypto. It doesn't support things like PKCS yet, however. There is a partial Python wrapper for the Crypto++ library given by PyCryptopp, which you may find useful.
The OpenSSL library is also wrapped for Python by PyOpenSSL. A Python implementation of SSH is Paramiko.
|
2,533,132 | 2,574,342 | How to get this Qt state machine to work? | I have two widgets that can be checked, and a numeric entry field that should contain a value greater than zero. Whenever both widgets have been checked, and the numeric entry field contains a value greater than zero, a button should be enabled. I am struggling with defining a proper state machine for this situation. So far I have the following:
QStateMachine *machine = new QStateMachine(this);
QState *buttonDisabled = new QState(QState::ParallelStates);
buttonDisabled->assignProperty(ui_->button, "enabled", false);
QState *a = new QState(buttonDisabled);
QState *aUnchecked = new QState(a);
QFinalState *aChecked = new QFinalState(a);
aUnchecked->addTransition(wa, SIGNAL(checked()), aChecked);
a->setInitialState(aUnchecked);
QState *b = new QState(buttonDisabled);
QState *bUnchecked = new QState(b);
QFinalState *bChecked = new QFinalState(b);
employeeUnchecked->addTransition(wb, SIGNAL(checked()), bChecked);
b->setInitialState(bUnchecked);
QState *weight = new QState(buttonDisabled);
QState *weightZero = new QState(weight);
QFinalState *weightGreaterThanZero = new QFinalState(weight);
weightZero->addTransition(this, SIGNAL(validWeight()), weightGreaterThanZero);
weight->setInitialState(weightZero);
QState *buttonEnabled = new QState();
buttonEnabled->assignProperty(ui_->registerButton, "enabled", true);
buttonDisabled->addTransition(buttonDisabled, SIGNAL(finished()), buttonEnabled);
buttonEnabled->addTransition(this, SIGNAL(invalidWeight()), weightZero);
machine->addState(registerButtonDisabled);
machine->addState(registerButtonEnabled);
machine->setInitialState(registerButtonDisabled);
machine->start();
The problem here is that the following transition:
buttonEnabled->addTransition(this, SIGNAL(invalidWeight()), weightZero);
causes all the child states in the registerButtonDisabled state to be reverted to their initial state. This is unwanted behaviour, as I want the a and b states to remain in the same state.
How do I ensure that a and b remain in the same state? Is there another / better way this problem can be solved using state machines?
Note. There are a countless (arguably better) ways to solve this problem. However, I am only interested in a solution that uses a state machine. I think such a simple use case should be solvable using a simple state machine, right?
| After reading your requirements and the answers and comments here I think merula's solution or something similar is the only pure Statemachine solution.
As has been noted to make the Parallel State fire the finished() signal all the disabled states have to be final states, but this is not really what they should be as someone could uncheck one of the checkboxes and then you would have to move away from the final state. You can't do that as FinalState does not accept any transitions. The using the FinalState to exit the parallel state also causes the parallel state to restart when it is reentered.
One solution could be to code up a transition that only triggers when all three states are in the "good" state, and a second one that triggers when any of those is not. Then you add the disabled and enabled states to the parallel state you already have and connect it with the aforementioned transitions. This will keep the enabled state of the button in sync with all the states of your UI pieces. It will also let you leave the parallel state and come back to a consistent set of property settings.
class AndGateTransition : public QAbstractTransition
{
Q_OBJECT
public:
AndGateTransition(QAbstractState* sourceState) : QAbstractTransition(sourceState)
m_isSet(false), m_triggerOnSet(true), m_triggerOnUnset(false)
void setTriggerSet(bool val)
{
m_triggerSet = val;
}
void setTriggerOnUnset(bool val)
{
m_triggerOnUnset = val;
}
addState(QState* state)
{
m_states[state] = false;
connect(m_state, SIGNAL(entered()), this, SLOT(stateActivated());
connect(m_state, SIGNAL(exited()), this, SLOT(stateDeactivated());
}
public slots:
void stateActivated()
{
QObject sender = sender();
if (sender == 0) return;
m_states[sender] = true;
checkTrigger();
}
void stateDeactivated()
{
QObject sender = sender();
if (sender == 0) return;
m_states[sender] = false;
checkTrigger();
}
void checkTrigger()
{
bool set = true;
QHashIterator<QObject*, bool> it(m_states)
while (it.hasNext())
{
it.next();
set = set&&it.value();
if (! set) break;
}
if (m_triggerOnSet && set && !m_isSet)
{
m_isSet = set;
emit (triggered());
}
elseif (m_triggerOnUnset && !set && m_isSet)
{
m_isSet = set;
emit (triggered());
}
}
pivate:
QHash<QObject*, bool> m_states;
bool m_triggerOnSet;
bool m_triggerOnUnset;
bool m_isSet;
}
Did not compile this or even test it, but it should demonstrate the principle
|
2,533,353 | 2,533,361 | How do you make a private member in the base class become a public member in the child class? | Consider the following code:
class Base
{
void f() { }
};
class Derived: public Base
{
public:
};
What can you change in the derived class, such that you can perform the following:
Derived d;
d.f();
If the member is declared as public in the base class, adding a using declaration for Base::f in the derived class public section would've fix the problem. But if it is declared as private in the base class, this doesn't seem to work.
| This is not possible. A using declaration can't name a private base class member. Not even if there are other overloaded functions with the same name that aren't private.
The only way could be to make the derived class a friend:
class Derived;
class Base
{
void f() { }
friend class Derived;
};
class Derived: public Base
{
public:
using Base::f;
};
Since you make the names public in the derived class anyway so derived classes of Derived will be able to access them, you could make them protected in the base-class too and omit the friend declaration.
|
2,533,464 | 2,534,401 | How to Join N live MP3 streams into one using FFMPEG? | How to Join N live MP3 streams (radio streams like such live KCDX mp3 stream http://mp3.kcdx.com:8000/stream
) into 1 using FFMPEG? (I have N incoming live mp3 streams I want to join them and stream out 1 live mp3 stream) I mean I want to mix sounds like thay N speakers speak at the same time (btw N stereo to 1 mono), please help.
BTW: My problem is mainly how to make FFMPEG read from stream not from file...
Would you mind giving some code examples, please.
| It looks like url_fopen(), defined in avio.h, is the function you are looking for.
|
2,533,476 | 2,533,500 | What will happen when I call a member function on a NULL object pointer? | I was given the following as an interview question:
class A
{
public:
void fun()
{
std::cout << "fun" << std::endl;
}
};
A* a = NULL;
a->fun();
What will happen when this code is executed, and why?
See also:
When does invoking a member function on a null instance result in undefined behavior?
| It's undefined behavior, so anything might happen.
A possible result would be that it just prints "fun" since the method doesn't access any member variables of the object it is called on (the memory where the object supposedly lives doesn't need to be accessed, so access violations don't necessarily occur).
|
2,533,481 | 2,533,543 | Analog of Java Form Layout in Qt | Once I have programmed GUI with Java and have used Form Layouts. Form layout (if I am not mistaken that is from SWT library) made possible to give right, left, top and bottom adges of any GUI element (widget) with respect to other widgets in the same widget (parent widget) or with respect to the adges of parent widget. So it was possible to control the future of widgets that are inside of another one, when that "another widget" is being resized.
In Qt I have find the QFormLayout which is similar to Java one, but seems I can't handle with widgets as flexible in terms of relative positioning, as it was with Java's Form Layout.
So are there any other means to give a widget position with respect to the others (without overloading resizeEvent function) as that was in Java?
Thanks.
| It's hard to understand what you need exactly, but Qt has a plethora of layout options. QFormLayout, it so happens, is not what you need here (it's meant for forms in the web-sense: labels with text input boxes).
But QBoxLayout (and its subclasses) and QGridLayout probably are what you need. I was always able to satisfy all my layout needs in Qt with combinations of these. See some examples of their usage in the Qt demo and I'm sure you'll have your problem solved.
|
2,533,580 | 2,533,928 | Creating and using a static lib in xcode | I am trying to create a static library in xcode and link to that static library from another program.
So as a test i have created a BSD static C library project and just added the following code:
//Test.h
int testFunction();
//Test.cpp
#include "Test.h"
int testFunction() {
return 12;
}
This compiles fine and create a .a file (libTest.a).
Now i want to use it in another program so I create a new xcode project (cocoa application)
Have the following code:
//main.cpp
#include <iostream>
#include "Testlib.h"
int main (int argc, char * const argv[]) {
// insert code here...
std::cout << "Result:\n" <<testFunction();
return 0;
}
//Testlib.h
extern int testFunction();
I right clicked on the project -> add -> existing framework -> add other
Selected the .a file and it added it into the project view.
I always get this linker error:
Build TestUselibrary of project TestUselibrary with configuration Debug
Ld build/Debug/TestUselibrary normal x86_64
cd /Users/myname/location/TestUselibrary
setenv MACOSX_DEPLOYMENT_TARGET 10.6
/Developer/usr/bin/g++-4.2 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.6.sdk
-L/Users/myname/location/TestUselibrary/build/Debug
-L/Users/myname/location/TestUselibrary/../Test/build/Debug
-F/Users/myname/location/TestUselibrary/build/Debug
-filelist /Users/myname/location/TestUselibrary/build/TestUselibrary.build/Debug/TestUselibrary.build/Objects-normal/x86_64/TestUselibrary.LinkFileList
-mmacosx-version-min=10.6 -lTest -o /Users/myname/location/TestUselibrary/build/Debug/TestUselibrary
Undefined symbols:
"testFunction()", referenced from:
_main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
I am new to macosx development and fairly new to c++. I am probably missing something fairly obvious, all my experience comes from creating dlls on the windows platform.
I really appreciate any help.
| Are you sure that the libraries source file is named Test.cpp and not Test.c? With .c i get exactly the same error.
If it is Test.c you need to add extern "C" to the header for C++. E.g.:
#ifdef __cplusplus
extern "C" {
#endif
int testFunction();
#ifdef __cplusplus
}
#endif
See e.g. the C++ FAQ lite entry for more details.
|
2,533,728 | 2,533,964 | c++ floating point precision loss: 3015/0.00025298219406977296 | The problem.
Microsoft Visual C++ 2005 compiler, 32bit windows xp sp3, amd 64 x2 cpu.
Code:
double a = 3015.0;
double b = 0.00025298219406977296;
//*((unsigned __int64*)(&a)) == 0x40a78e0000000000
//*((unsigned __int64*)(&b)) == 0x3f30945640000000
double f = a/b;//3015/0.00025298219406977296;
the result of calculation (i.e. "f") is 11917835.000000000 (((unsigned __int64)(&f)) == 0x4166bb4160000000) although it should be 11917834.814763514 (i.e. ((unsigned __int64)(&f)) == 0x4166bb415a128aef).
I.e. fractional part is lost.
Unfortunately, I need fractional part to be correct.
Questions:
1) Why does this happen?
2) How can I fix the problem?
Additional info:
0) The result is taken directly from "watch" window (it wasn't printed, and I didn't forget to set printing precision). I also provided hex dump of floating point variable, so I'm absolutely sure about calculation result.
1) The disassembly of f = a/b is:
fld qword ptr [a]
fdiv qword ptr [b]
fstp qword ptr [f]
2) f = 3015/0.00025298219406977296; yields correct result (f == 11917834.814763514 , ((unsigned __int64)(&f)) == 0x4166bb415a128aef ), but it looks like in this case result is simply calculated during compile-time:
fld qword ptr [__real@4166bb415a128aef (828EA0h)]
fstp qword ptr [f]
So, how can I fix this problem?
P.S. I've found a temporary workaround (i need only fractional part of division, so I simply use f = fmod(a/b)/b at the moment), but I still would like to know how to fix this problem properly - double precision is supposed to be 16 decimal digits, so such calculation isn't supposed to cause problems.
| Are you using directx in your program anywhere as that causes the floating point unit to get switched to single precision mode unless you specifically tell it not to when you create the device and would cause exactly this
|
2,533,774 | 2,533,778 | Measuring execution time of a call to system() in C++ | I have found some code on measuring execution time here
http://www.dreamincode.net/forums/index.php?showtopic=24685
However, it does not seem to work for calls to system(). I imagine this is because the execution jumps out of the current process.
clock_t begin=clock();
system(something);
clock_t end=clock();
cout<<"Execution time: "<<diffclock(end,begin)<<" s."<<endl;
Then
double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks)/(CLOCKS_PER_SEC);
return diffms;
}
However this always returns 0 seconds... Is there another method that will work?
Also, this is in Linux.
Edit: Also, just to add, the execution time is in the order of hours. So accuracy is not really an issue.
Thanks!
| Have you considered using gettimeofday?
struct timeval tv;
struct timeval start_tv;
gettimeofday(&start_tv, NULL);
system(something);
double elapsed = 0.0;
gettimeofday(&tv, NULL);
elapsed = (tv.tv_sec - start_tv.tv_sec) +
(tv.tv_usec - start_tv.tv_usec) / 1000000.0;
|
2,534,449 | 2,534,501 | What are the parts that a good C++ project should contain? (Docs, Makefile, Tests etc...) | i am writing my bachelor thesis and there is some C++ code attached to it.
I want to have a nice clean Project.
So what should be in it ?
I think :
Documentation in html ( generated with Doxygen)
README File
Makefile ( which make ? CMake ? )
Unit-Tests ( which unit test framework? )
Copyright Text ?
...
Did i miss something ?
| Simplify the list:
Documentation in a place and form that can easily be found and read, including
instructions on how to build it;
instructions on how to use it.
Some sort of confidence testing ("I compiled it, but does it work?").
Whether the docs are HTML, plain text or in-source comments; whether there's a Makefile or a batch script or a copy & paste one-liner in the README.txt; whether you've got a full-blown unit testsuite or a "golden file" test:
It doesn't matter really.
The important thing is that you can build it, test it, and use it as easily as possible.
Adding personal opinion:
KISS. (Keep it short and simple.)
Go with simple source comments for small projects, and only start the Doxygen stuff when you grow beyond a certain point. Make sure your documentation framework doesn't make it harder to find things via full-text search, because in my experience, that's what people end up doing unless you wrote your docs really well.
Go with a simple Makefile and use more sophisticated stuff (like CMake, automake etc.) only when it becomes necessary. For small projects, the amount of "metadata" in comparison to "real" source files can become ridiculous.
You can sink quite some time and energy in this "supporting cast", which - in the beginning of a project - should be put into the project itself. Build system, documentation etc. can grow as necessary, but the project architecture itself is a bitch to refactor once it's been released. That's where your primary focus should be.
|
2,534,502 | 2,557,239 | Is there a good graph layout library callable from C++? | The (directed) graphs represent finite automata. Up until now my test program has been writing out dot files for testing. This is pretty good both for regression testing (keep the verified output files in subversion, ask it if there has been a change) and for visualisation. However, there are some problems...
Basically, I want something callable from C++ and which plans a layout for my states and transitions but leaves the drawing to me - something that will allow me to draw things however I want and draw on GUI (wxWidgets) windows.
I also want a license which will allow commercial use - I don't need that at present, and I may very well release as open source, but I don't want to limit my options ATM.
The problems with GraphViz are (1) the warnings about building from source on Windows, (2) all the unnecessary dependencies for rendering and parsing, and (3) the (presumed) lack of a documented API specifically and purely for layout.
Basically, I want to be able to specify my states (with bounding rectangle sizes) and transitions, and read out positions for the states and waypoints for each transition, then draw based on those co-ordinates myself. I haven't really figured out how annotations on transitions should be handled, but there should be some kind of provision for specifying bounding-box-sizes for those, associating them with transitions, and reading out positions.
Does anyone know of a library that can handle those requirements?
I'm not necessarily against implementing something for myself, but in this case I'd rather avoid it if possible.
| Although the answers so far were worth an upvote, I can't really accept any of them. I've still been searching, though.
One thing I found is AGLO. The code is GPL v1, but there are papers that describe the algorithms, so it should be easy enough to re-implement from scratch if necessary.
There's also the paper by Gansner, Koutsofios, North and Vo - "A Technique for Drawing Directed Graphs" - available from here on the Graphviz site.
I've also been looking closely at the BSD-licensed (but Java) JGraph.
One way or the other, it looks like I might be re-implementing the wheel, if not actually re-inventing it.
|
2,534,507 | 2,534,631 | Semi-generic function | I have a bunch of overloaded functions that operate on certain data types such as int, double and strings. Most of these functions perform the same action, where only a specific set of data types are allowed. That means I cannot create a simple generic template function as I lose type safety (and potentially incurring a run-time problem for validation within the function).
Is it possible to create a "semi-generic compile time type safe function"? If so, how? If not, is this something that will come up in C++0x?
An (non-valid) idea;
template <typename T, restrict: int, std::string >
void foo(T bar);
...
foo((int)0); // OK
foo((std::string)"foobar"); // OK
foo((double)0.0); // Compile Error
Note: I realize I could create a class that has overloaded constructors and assignment operators and pass a variable of that class instead to the function.
| Use sfinae
template<typename> struct restrict { };
template<> struct restrict<string> { typedef void type; };
template<> struct restrict<int> { typedef void type; };
template <typename T>
typename restrict<T>::type foo(T bar);
That foo will only be able to accept string or int for T. No hard compile time error occurs if you call foo(0.f), but rather if there is another function that accepts the argument, that one is taken instead.
|
2,534,607 | 2,534,670 | Multimap erase doesn't work | following code doesn't work with input:
2
7
add Elly 0888424242
add Elly 0883666666
queryname Elly
querynum 0883266642
querynum 0888424242
delnum 0883666666
queryname Elly
3
add Kriss 42
add Elly 42
querynum 42
Why my erase doesn't work?
#include<stdio.h>
#include<iostream>
#include<map>
#include <string>
using namespace std;
void PrintMapName(multimap<string, string> pN, string s)
{
pair<multimap<string,string>::iterator, multimap<string,string>::iterator> ii;
multimap<string, string>::iterator it;
ii = pN.equal_range(s);
multimap<string, int> tmp;
for(it = ii.first; it != ii.second; ++it)
{
tmp.insert(pair<string,int>(it->second,1));
}
multimap<string, int>::iterator i;
bool flag = false;
for(i = tmp.begin(); i != tmp.end(); i++)
{
if(flag)
{
cout<<" ";
}
cout<<i->first;
if(flag)
{
cout<<" ";
}
flag = true;
}
cout<<endl;
}
void PrintMapNumber(multimap<string, string> pN, string s)
{
multimap<string, string>::iterator it;
multimap<string, int> tmp;
for(it = pN.begin(); it != pN.end(); it++ )
{
if(it->second == s)
{
tmp.insert(pair<string,int>(it->first,1));
}
}
multimap<string, int>::iterator i;
bool flag = false;
for(i = tmp.begin(); i != tmp.end(); i++)
{
if(flag)
{
cout<<" ";
}
cout<<i->first;
if(flag)
{
cout<<" ";
}
flag = true;
}
cout<<endl;
}
void PrintFull(multimap<string, string> pN)
{
multimap<string, string>::iterator it;
for(it = pN.begin(); it != pN.end(); it++ )
{
cout<<"Key = "<<it->first<<" Value = "<<it->second<<endl;
}
}
int main()
{
multimap<string, string> phoneNums;
int N;
cin>>N;
int tests;
string tmp, tmp1,tmp2;
while(N > 0)
{
cin>>tests;
while(tests > 0)
{
cin>>tmp;
if(tmp == "add")
{
cin>>tmp1>>tmp2;
phoneNums.insert(pair<string,string>(tmp1,tmp2));
}
else
{
if(tmp == "delnum")
{ /////////////////////////////////////////HEREEEEEEE
multimap<string, string>::iterator it;
multimap<string, string>::iterator tmpr;
for(it = phoneNums.begin(); it != phoneNums.end();)
{
tmpr = it;
if(it->second == tmp1)
{
++tmpr;
if(tmpr == phoneNums.end())
{
phoneNums.erase(it,tmpr);
break;
}
else
{
phoneNums.erase(it,tmpr);
}
}
}
}
else
{
if(tmp == "delname")
{
cin>>tmp1;
phoneNums.erase(tmp1);
}
else
{
if(tmp =="queryname")
{
cin>>tmp1;
PrintMapName(phoneNums, tmp1);
}
else//querynum
{
cin>>tmp1;
PrintMapNumber(phoneNums, tmp1);
}
}
}
}
tests--;
}
N--;
}
return 0;
}
| You never move the iterator it in your loop.
|
2,534,647 | 2,534,701 | Programming help Loop adding | I know this probably really simple but Im not sure what im doing wrong...
The assignment states:
For the second program for this lab, you are to have the user enter an integer value in the range of 10 to 50. You are to verify that the user enters a value in that range, and continue to prompt him until he does give you a value in that range.
After the user has successfully entered a value in that range, you are to display the sum of all the integers from 1 to the value entered.
I have this so far:
#include <iostream.h>
int main () {
int num, sum;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
{
int i;
int sum = 0;
for (num = 1; num <= 50; num ++)
sum = sum + num;
}
cout << endl << "The sum is " << sum << endl;
return 0;
}
Im just not sure exactly what i'm doing wrong... I keep getting the wrong sum for the total...
| The Corrected code is
#include <iostream.h>
int main () {
int num;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
//<----Removed the extra set of {}
int i,sum=0;//<---- Changed the declaration here
for (i= 1; i <= num; i++) //<----Change Here
sum += i;
cout << endl << "The sum is " << sum << endl;
return 0;
}
|
2,534,815 | 2,534,830 | How to move a struct into a class? | I've got something like:
typedef struct Data_s {
int field1;
int field2;
} Data;
class Foo {
void getData(Data& data);
void useData(Data& data);
}
In another class's function, I might do:
class Bar {
Data data_;
void Bar::taskA() {
Foo.getData(data_);
Foo.useData(data_);
}
}
Is there a way to move the Data out of the global scope and into Foo without creating a new class? Data mirrors a struct existing in a library I'm using elsewhere. (i.e. same fields, just different name. I cast Data into the other struct later. I do this because Foo is an abstract class, and the derived class using the library is just one of many.)
Currently, just pasting it inside the class and replacing Data with Foo::Data everywhere doesn't work.
class Foo {
typedef struct Data_s {
int field1;
int field2;
} Data;
...
}
I get 'Data' in class 'Foo' does not name a type at Bar data_;
| You can define the struct inside the class, but you need to do it ahead of the place where you first use it. Structs, like classes themselves, must be forward-declared in order to use them:
class Foo
{
public:
struct Data
{
int field1;
int field2;
};
void getData(Foo::Data& data) {}
void useData(Foo::Data& data) {}
};
void UseFooData()
{
Foo::Data bar;
Foo f;
f.getData(bar);
f.useData(bar);
}
Edit: Updated example to use the same fields/class names as listed in the original question. Please note that in order to be visible outside of the Foo class, Data needs to be declared public and other code needs to reference it as Foo::Data.
|
2,534,827 | 2,534,840 | What's the outcome if I use free with new or delete with malloc? | It is a compiler error or runtime error? The code below can be compiled!
class Base{
void g();
void h();
};
int main()
{
Base* p = new Base();
free(p);
return 0;
}
However it can't be compiled with a virtual function if I declare the class Base like this
class Base{
virtual void g();
void h();
};
The code below can be compiled all the time, no matter the function is virtual or not.
class Base{
void g();
void h();
};
int main()
{
Base* p = (Base*)malloc(sizeof(Base));
delete p;
return 0;
}
| Undefined outcome, plus malloc() doesn't call constructors and free() doesn't call destructors.
|
2,535,008 | 2,535,017 | C++ include statement required if defining a map in a headerfile | I was doing a project for computer course on programming concepts. This project was to be completed in C++ using Object Oriented designs we learned throughout the course. Anyhow, I have two files symboltable.h and symboltable.cpp. I want to use a map as the data structure so I define it in the private section of the header file. I #include <map> in the cpp file before I #include "symboltable.h".
I get several errors from the compiler (MS VS 2008 Pro) when I go to debug/run the program the first of which is:
Error 1 error C2146: syntax error : missing ';' before identifier 'table' c:\users\jsmith\documents\visual studio 2008\projects\project2\project2\symboltable.h 22 Project2
To fix this I had to #include <map> in the header file, which to me seems strange.
Here are the relevant code files:
// symboltable.h
#include <map>
class SymbolTable {
public:
SymbolTable() {}
void insert(string variable, double value);
double lookUp(string variable);
void init(); // Added as part of the spec given in the conference area.
private:
map<string, double> table; // Our container for variables and their values.
};
and
// symboltable.cpp
#include <map>
#include <string>
#include <iostream>
using namespace std;
#include "symboltable.h"
void SymbolTable::insert(string variable, double value) {
table[variable] = value; // Creates a new map entry, if variable name already exist it overwrites last value.
}
double SymbolTable::lookUp(string variable) {
if(table.find(variable) == table.end()) // Search for the variable, find() returns a position, if thats the end then we didnt find it.
throw exception("Error: Uninitialized variable");
else
return table[variable];
}
void SymbolTable::init() {
table.clear(); // Clears the map, removes all elements.
}
| My guess is that you have another file that includes the header file #include "symboltable.h". And that other source file doesn't #include <map> nor #include <string> nor has using namespace std before it includes "symboltable.h".
Check which file is being compiled when you get the error. Is it maybe a different source file than the .cpp that you mentioned? Possibly something like main.cpp?
Another way to solve your problem is to put the includes you need in your header file and use std::map instead of simply map. Also you use string which is also inside the namespace std. So that needs to be std::string. And put the missing #include <string>.
|
2,535,072 | 2,535,228 | Accessing C++ Functions From Text storage | I'm wondering if anyone knows how to accomplish the following:
Let's say I have a bunch of data stored in SQL, lets say one of the fields could be called funcName, function name would contain data similar to "myFunction" What I'm wondering is, is there a way I can than in turn extract the function name and actually call that function?
There's a few ways I can think of to accomplish this, one is changing funcName to funcId and linking up with an array or similar, but I'm looking for something a bit more dynamic that would allow me to add the data on fly without having to update the actual source code every time I add a call to a new function assuming of course that the function already exists and is accessible via scope location we call it from.
Any help would be greatly appreciated.
| Use a macro to define new functions that register themselves automatically.
// callable_function.h
class CallableFunction {
public:
virtual void operator()() = 0;
};
class CallableFunctionRegistry {
public:
static CallableFunction *Register(const string &func_name,
CallableFunction *func_impl) {
Instance()->registered_functions_.insert(make_pair(func_name, func_impl));
}
static void Run(const string &func_name) {
(*Instance()->registered_functions_[func_name])();
}
private:
static CallableFunctionRegistry *Instance() {
static CallableFunctionRegistry *instance = new CallablefunctionRegistry;
return instance;
}
CallableFunctionRegistry() {}
map<string, CallableFunction*> registered_functions_;
};
#define REGISTER_CALLABLE_FUNCTION(FuncName) \
class FuncName : public CallableFunction { \
public: \
virtual void operator()(); \
}; \
CallableFunction *impl_ ##FuncName = \
CallableFunctionRegistry::Register(#FuncName, new FuncName); \
void FuncName::operator()()
And use it like this:
//other_file.cc
REGISTER_CALLABLE_FUNCTION(DoStuff) {
// do stuff here.
}
And this:
//yet_another_file.cc
CallableFunctionRegistry::Run("DoStuff");
You could do it with function ptrs instead of CallableFunction object, but my syntax on that is hazy. Either way, add error checking for duplicate registrations and lookup not found.
|
2,535,148 | 2,535,246 | "volatile" qualifier and compiler reorderings | A compiler cannot eliminate or reorder reads/writes to a volatile-qualified variables.
But what about the cases where other variables are present, which may or may not be volatile-qualified?
Scenario 1
volatile int a;
volatile int b;
a = 1;
b = 2;
a = 3;
b = 4;
Can the compiler reorder first and the second, or third and the fourth assignments?
Scenario 2
volatile int a;
int b, c;
b = 1;
a = 1;
c = b;
a = 3;
Same question, can the compiler reorder first and the second, or third and the fourth assignments?
| The C++ standard says (1.9/6):
The observable behavior of the
abstract machine is its sequence of
reads and writes to volatile data and
calls to library I/O functions.
In scenario 1, either of the changes you propose changes the sequence of writes to volatile data.
In scenario 2, neither change you propose changes the sequence. So they're allowed under the "as-if" rule (1.9/1):
... conforming implementations are
required to emulate (only) the
observable behavior of the abstract
machine ...
In order to tell that this has happened, you would need to examine the machine code, use a debugger, or provoke undefined or unspecified behavior whose result you happen to know on your implementation. For example, an implementation might make guarantees about the view that concurrently-executing threads have of the same memory, but that's outside the scope of the C++ standard. So while the standard might permit a particular code transformation, a particular implementation could rule it out, on grounds that it doesn't know whether or not your code is going to run in a multi-threaded program.
If you were to use observable behavior to test whether the re-ordering has happened or not (for example, printing the values of variables in the above code), then of course it would not be allowed by the standard.
|
2,535,218 | 2,535,233 | Process.WaitForExit not triggering with __debugbreak | I'm trying to write a program to test student code against a good implementation. I have a C++ console app that will run one test at a time determined by the command line args and a C# .net forms app that calls the c++ app once for each test. The goal is to be able to detect not just pass/fail for each test, but also "infinite" (>5secs) loop and exceptions (their code dying for whatever reason).
The problem is that not all errors kill the C++ app. If they corrupt the heap the system calls __debugbreak which pops up a window saying Debug Error! HEAP CORRUPTION DETECTED... My C# app is using Process.WaitForExit(5000) to wait, but this error doesn't count as an exit, so I see a timeout.
So my question is, how can I either get the C# app to detect that this is an error OR how can I get the C++ app to die when this error occurs rather than giving a dialog box and asking if I want to debug?
Edit:
Here's the error that pops up: Debug Error
Here's the normal application failed dialog that pops up if I press retry in the previous dialog: Windows Error. The debug option goes away if you turn off the JIT debugger.
| You should turn of JIT debugging, this page has instructions for how to turn it on or off.
Edit You can also use the _CrtSetReportMode and _CrtSetReportFile functions inside the C++ program to change the behaviour of the debug asserts (in particular, you can use _CRTDBG_MODE_FILE to write the contents of the message to a file instead of popping up a dialog.
If you're compiling the program as part of your tests, then you can just add your own .cpp file which includes a global class that does the work in it's constructor. Something like this:
// AssertModify.cpp
class AssertModify
{
public:
AssertModify()
{
::_CrtSetReportMode(...);
::_CrtSetReportFile(...);
}
};
AssertModify am;
This'll cause the code to run before main() is entered which should catch all possible cases (unless the student overrides your value themselves, but you can add a check for any calls to _CrtSetReportMode in their submitted code before you compile it)
|
2,535,284 | 2,535,307 | How can I hash a string to an int using c++? | I have to write my own hash function. If I wanted to just make the simple hash function that maps each letter in the string to a numerical value (i.e. a=1, b=2, c=3, ...), is there a way I can perform this hash on a string without having to first convert it to a c-string to look at each individual char? Is there a more efficient way of hashing strings?
| Re the first question, sure, e.g, something like:
int hash = 0;
int offset = 'a' - 1;
for(string::const_iterator it=s.begin(); it!=s.end(); ++it) {
hash = hash << 1 | (*it - offset);
}
regarding the second, there are many better ways to hash strings. E.g., see here for a few C examples (easily translatable to C++ along the lines of the snippet above).
|
2,535,362 | 2,535,376 | How to write a cctor and op= for a factory class with ptr to abstract member field? | I'm extracting files from zip and rar archives into raw buffers. I created the following to wrap minizip and unrarlib:
Archive.hpp - Used to access everything. If I could make all the functions in the other classes inaccessible from the outside, I would. (Actually, I suppose I could friend all the other classes in Archive and use private function callbacks..., but that's soo roundabout.)
#include "ArchiveBase.hpp"
#include "ArchiveDerived.hpp"
class Archive {
public:
Archive(string path) {
/* logic here to determine type */
switch(type) {
case RAR:
archive_ = new ArchiveRar(path);
break;
case ZIP:
archive_ = new ArchiveZip(path);
break;
case UNKNOWN_ARCHIVE:
throw;
break;
}
}
Archive(Archive& other) {
archive_ = // how do I copy an abstract class?
}
~Archive() { delete archive_; }
void passThrough(ArchiveBase::Data& data) { archive_->passThrough(data); }
Archive& operator = (Archive& other) {
if (this == &other) return *this;
ArchiveBase* newArchive = // can't instantiate....
delete archive_;
archive_ = newArchive;
return *this;
}
private:
ArchiveBase* archive_;
}
ArchiveBase.hpp
class ArchiveBase {
public:
// Is there any way to put this struct in Archive instead,
// so that outside classes instantiating one could use
// Archive::Data instead of ArchiveBase::Data?
struct Data {
int field;
};
virtual void passThrough(Data& data) = 0;
/* more methods */
}
ArchiveDerived.hpp "Derived" being "Zip" or "Rar"
#include "ArchiveBase.hpp"
class ArchiveDerived : public ArchiveBase {
public:
ArchiveDerived(string path);
void passThrough(ArchiveBase::Data& data);
private:
/* fields needed by minizip/unrarlib */
// example zip:
unzFile zipFile_;
// example rar:
RARHANDLE rarFile_;
}
ArchiveDerived.cpp
#include "ArchiveDerived.hpp"
ArchiveDerived::ArchiveDerived(string path) { //implement }
ArchiveDerived::passThrough(ArchiveBase::Data& data) { //implement }
Somebody had suggested I use this design so that I could do:
Archive archiveFile(pathToZipOrRar);
archiveFile.passThrough(extractParams); // yay polymorphism!
How do I write a cctor for Archive?
What about op= for Archive?
What can I do about "renaming" ArchiveBase::Data to Archive::Data? (Both minizip and unrarlib use such structs for input and output. Data is generic for Zip & Rar and later is used to create the respective library's struct.) Everything else is accessed via Archive, and I'd like to make declaring Data in an outside class this way as well.
I know I could throw away my current class Archive, name ArchiveBase into Archive, and use a global factory function. However, I wanted to avoid using the global function.
| First of all you can't "copy" an abstract class because you can't instantiate one. Instead, what you should do is set up a std::tr1::shared_ptr of that class and pass in a pointer.
Archive(ArchiveBase *_archiveBase)
Use a factory function outside of the Archive class for instantiation.
Archive createArchive(string _path, int _type){
switch(type) {
case RAR:
return Archive( new ArchiveRar(path) );
case ZIP:
return Archive( new ArchiveZip(path) );
case UNKNOWN_ARCHIVE:
throw exception("Unknown archive format");
break;
default:
throw exception("Improper archive type");
}
For the = operator, simply holding onto a smart pointer such as this and using the "=" will perform the safe transfer of knowledge between classes. It performs reference counting and will delete the pointer so you don't have to and only when it's safe to do so.
Archive& operator = (Archive& other) {
m_ArchiveBasePtr = other.m_ArchiveBasePtr;
return *this;
}
Let the smart pointers worry about deleting, copying, and all that for you.
|
2,535,370 | 2,535,634 | C++ -- typedef "inside" template arguments? | Imagine I have a template function like this:
template<typename Iterator>
void myfunc(Iterator a, typename Iterator::value_type b)
{ ... }
Is there a way to implement the same thing by declare a typedef for Iterator::valuetype that I can use in the function signature? For example, I'd prefer to be able to do something like this:
template<
typename Iterator,
typedef Iterator::value_type type>
void myfunc(Iterator a, type b)
{ ... }
Thus far, I've resorted to using default template arguments and Boost concept checking to ensure the default is always used:
template<
typename Iterator,
typename type = typename Iterator::value_type >
void myfunc(Iterator a, type b)
{
BOOST_STATIC_ASSERT((
boost::is_same<
typename Iterator::value_type,
type
>::value
));
...
}
...but it would be nice if there was support in the language for this type of thing.
Edit
I probably should have used a class instead of a function, since default arguments aren't standard for functions.
template<
typename T,
typename V = typename T::value_type>
class A : public B<T, V>
{
BOOST_STATIC_ASSERT((boost::is_same<typename T::value_Type, V>::type));
};
| You are looking for a templated typedef to be used inside a templated function definition. I don't think you can do that...
You can have a templated class with a static function & typedefs... But using it gets ugly:
template<typename Iterator>
class arbitraryname
{
public:
typedef typename Iterator::value_type value;
static void myfunc( Iterator a, value b )
{
value c = b;
cout << "Test" << c << endl;
}
};
struct Foo
{
typedef int value_type;
};
int main()
{
Foo f;
myfunc<Foo>(f,2); // Old way.
arbitraryname<Foo>::myfunc(f,3); // With templated class.
}
Personally, in this case, I'd go with a #define...
#define VALUE_TYPE typename Iterator::value_type
template<typename Iterator>
void myfunc(Iterator a, VALUE_TYPE b)
#undef VALUE_TYPE
{
typedef typename Iterator::value_type bar;
bar z = b;
cout << "Test" << z << endl;
}
Sure #define's are ugly and sinful. But so is code that's painfully obtuse to read...
p.s. Just to be safe, you might want to add:
#ifdef VALUE_TYPE
#error "VALUE_TYPE already defined!"
#endif
|
2,535,445 | 2,535,504 | Negative execution time | I wrote a little program that solves 49151 sudoku's within an hour for an assignment, but we had to time it. I thought I'd just let it run and then check the execution time, but it says -1536.087 s. I'm guessing it has to do with the timer being some signed dataype or something, but I have no idea what datatype is used for the timer in the console (code::blocks console, I'm not sure if this is actually a separate console, or just a runner that runs the terminal from the local operating system), so I can't check what the real time was. I'd rather not run this again with some coded timer within my program, since I'd like to be able to use my pc again now. Anybody have any idea what this time could be? It should be somewhere between 40 and 50 minutes, so between 2400 and 3000 seconds.
| If the time was stored in microseconds in a 32-bit signed int, 2758880296 us (microseconds) would produce this result, since 2758880296-2^32 = -1536087000. In minutes and seconds, that's 45:58.880296. (treat those last few decimal places with a grain of salt, since presumably what you printed was rounded to the nearest millisecond)
But of course, that's just an intelligent guess based on the information you provided.
|
2,535,525 | 2,535,531 | Sending the contents of a file to a client | I am writing a C++ server side application called quote of the day. I am using the winsock2 library. I want to send the contents of a file back to the client, including newlines by using the send function. The way i tried it doesn't work. How would i go about doing this?
| Reading the file and writing to the socket are 2 distinct operations. Winsock does not have an API for sending a file directly.
As for reading the file, simply make sure you open it in read binary mode if using fopen, or simply use the CreateFile, and ReadFile Win32 API and it will be binary mode by default.
Usually you will read the file in chunks (for example 10KB at a time) and then send each of those chunks over the socket by using send or WSASend. Once you are done, you can close the socket.
On the receiving side, read whatever's available on the socket until the socket is closed. As you read data into a buffer, write the amount read to a file.
|
2,535,640 | 2,535,686 | maps, iterators, and complex structs - STL errors | So, I have two structs:
struct coordinate {
float x;
float y;
}
struct person {
int id;
coordinate location;
}
and a function operating on coordinates:
float distance(const coordinate& c1, const coordinate& c2);
In my main method, I have the following code:
map<int,person> people;
// populate people
map<int,map<float,int> > distance_map;
map<int,person>::iterator it1,it2;
for (it1=people.begin(); it1!=people.end(); ++it1) {
for (it2=people.begin(); it2!=people.end(); ++it2) {
float d = distance(it1->second.location,it2->second.location);
distance_map[it1->first][d] = it2->first;
}
}
However, I get the following error upon build:
stl_iterator_base_types.h: In instantiation of βstd::iterator_traits<coordinate>β:
stl_iterator_base_types.h:129: error: no type named βiterator_categoryβ in βstruct coordinateβ
stl_iterator_base_types.h:130: error: no type named βvalue_typeβ in βstruct coordinateβ
stl_iterator_base_types.h:131: error: no type named βdifference_typeβ in βstruct coordinateβ
stl_iterator_base_types.h:132: error: no type named βpointerβ in βstruct coordinateβ
stl_iterator_base_types.h:133: error: no type named βreferenceβ in βstruct coordinateβ
And it blames it on the line:
float d = distance(it1->second.location,it2->second.location);
Why does the STL complain about my code?
| There's a function in the standard library called std::distance, which operates on iterators. So it looks like the compiler is trying to call that one instead of yours. I'd remove the using namespace std; directive if you're using it, and just say using std::map;, etc.
|
2,535,783 | 2,535,789 | Simple vector program error | Hi iam new to c++ and iam trying out this vector program and i am getting the following error:
error: conversion from test*' to non-scalar typetest' requested|
Here is the code
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
class test{
string s;
vector <string> v;
public:
void read(){
ifstream in ("c://test.txt");
while(getline(in,s))
{
v.push_back(s);
}
for(int i=0;i<v.size();i++)
{
cout<<v[i]<<"\n";
}
}
};
int main()
{
cout<<"Opening the file to read and displaying on the screen"<<endl;
test t=new test();
t.read();
}
| new is used to dynamically allocate memory. You don't need to do that, so just do:
test t; // create an instance of test with automatic storage
t.read(); // invoke a method
The error is because the type of new test() is a test*, a pointer to a (newly created) test. You can't assign a test* to a test.
The pointer version, for what it's worth, would have been:
test* t = new test();
t->read(); // the arrow is short for (*test).
delete t; // don't forget to clean up!
However, it's bad style to do raw memory allocation like that. You'd use something called a smart pointer to make sure it gets deleted automatically, instead. The standard library has one in the header <memory>, called auto_ptr, that would suffice:
std::auto_ptr<test> t(new test()); // put a new test into a pointer wrapper
t->read(); // treat it like a normal pointer
// nothing else to worry about, will be deleted automatically
However, all this isn't needed for you, in this case. Always prefer automatic (stack) allocation over dynamic allocation.
|
2,535,807 | 2,535,861 | How can I fix my program from crashing in C++? | I'm very new to programming and I am trying to write a program that adds and subtracts polynomials. My program sometimes works, but most of the time, it randomly crashes and I have no idea why. It's very buggy and has other problems I'm trying to fix, but I am unable to really get any further coding done since it crashes. I'm completely new here but any help would be greatly appreciated.
Here's the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int getChoice();
class Polynomial10
{
private:
double* coef;
int degreePoly;
public:
Polynomial10(int max); //Constructor for a new Polynomial10
int getDegree(){return degreePoly;};
void print(); //Print the polynomial in standard form
void read(); //Read a polynomial from the user
void add(const Polynomial10& pol); //Add a polynomial
void multc(double factor); //Multiply the poly by scalar
void subtract(const Polynomial10& pol); //Subtract polynom
};
void Polynomial10::read()
{
cout << "Enter degree of a polynom between 1 and 10 : ";
cin >> degreePoly;
cout << "Enter space separated coefficients starting from highest degree" << endl;
for (int i = 0; i <= degreePoly; i++) cin >> coef[i];
}
void Polynomial10::print()
{
for (int i = 0;i <= degreePoly; i++) {
if (coef[i] == 0) cout << "";
else if (i >= 0) {
if (coef[i] > 0 && i != 0) cout<<"+";
if ((coef[i] != 1 && coef[i] != -1) || i == degreePoly) cout << coef[i];
if ((coef[i] != 1 && coef[i] != -1) && i != degreePoly ) cout << "*";
if (i != degreePoly && coef[i] == -1) cout << "-";
if (i != degreePoly) cout << "x";
if ((degreePoly - i) != 1 && i != degreePoly) {
cout << "^";
cout << degreePoly-i;
}
}
}
}
void Polynomial10::add(const Polynomial10& pol)
{
for(int i = 0; i<degreePoly; i++) {
int degree = degreePoly;
coef[degreePoly-i] += pol.coef[degreePoly-(i+1)];
}
}
void Polynomial10::subtract(const Polynomial10& pol)
{
for(int i = 0; i<degreePoly; i++) {
coef[degreePoly-i] -= pol.coef[degreePoly-(i+1)];
}
}
void Polynomial10::multc(double factor)
{
//int degreePoly=0;
//double coef[degreePoly];
cout << "Enter the scalar multiplier : ";
cin >> factor;
for(int i = 0; i<degreePoly; i++) coef[i] *= factor;
}
Polynomial10::Polynomial10(int max)
{
degreePoly = max;
coef = new double[degreePoly];
for(int i; i < degreePoly; i++) coef[i] = 0;
}
int main()
{
int choice;
Polynomial10 p1(1),p2(1);
cout << endl << "CGS 2421: The Polynomial10 Class" << endl << endl << endl;
cout
<< "0. Quit\n"
<< "1. Enter polynomial\n"
<< "2. Print polynomial\n"
<< "3. Add another polynomial\n"
<< "4. Subtract another polynomial\n"
<< "5. Multiply by scalar\n\n";
int choiceFirst = getChoice();
if (choiceFirst != 1) {
cout << "Enter a Polynomial first!";
}
if (choiceFirst == 1) {choiceFirst = choice;}
while(choice != 0) {
switch(choice) {
case 0:
return 0;
case 1:
p1.read();
break;
case 2:
p1.print();
break;
case 3:
p2.read();
p1.add(p2);
cout << "Updated Polynomial: ";
p1.print();
break;
case 4:
p2.read();
p1.subtract(p2);
cout << "Updated Polynomial: ";
p1.print();
break;
case 5:
p1.multc(10);
cout << "Updated Polynomial: ";
p1.print();
break;
}
choice = getChoice();
}
return 0;
}
int getChoice()
{
int c;
cout << "\nEnter your choice : ";
cin >> c;
return c;
}
| When you create your objects with p1(1) and p2(1) the coef array in each object is allocated to contain one element. Then in read() you simply set degreePoly to a (possibly higher) value but don't change the allocation of coef. It will still contain only one element, but all coefficients are written to it, probably writing over the bounds of the array. Instead the old coefshould be freed and a new array of suitable size be allocated.
Also in add and subtract you are assigning to coefficients out of bounds (for i=0):
coef[degreePoly-i] -= pol.coef[degreePoly-(i+1)];
It also seems wrong mathematically to subtract the coefficients at index degreePoly-(i+1) from those at index degreePoly-i. Additionally the case that the two polygons might have different degrees is currently not handled.
|
2,535,836 | 2,535,853 | defining < operator for map of list iterators | I'd like to use iterators from an STL list as keys in a map. For example:
using namespace std;
list<int> l;
map<list<int>::const_iterator, int> t;
int main(int argv, char * argc) {
l.push_back(1);
t[l.begin()] = 5;
}
However, list iterators do not have a comparison operator defined (in contrast to random access iterators), so compiling the above code results in an error:
/usr/include/c++/4.2.1/bits/stl_function.h:227: error: no match for βoperator<β in β__x < __yβ
If the list is changed to a vector, a map of vector const_iterators compiles fine.
What is the correct way to define the operator < for list::const_iterator?
| Parameterise map with a custom comparator:
struct dereference_compare {
template <class I>
bool operator()(const I& a, const I& b) {
return *a < *b;
}
};
map<list<int>::const_iterator, int, dereference_compare> t;
|
2,535,963 | 2,535,978 | Questions on usages of sizeof | Question 1
I have a struct like,
struct foo
{
int a;
char c;
};
When I say sizeof(foo), I am getting 8 on my machine. As per my understanding, 4 bytes for int, 1 byte for char and 3 bytes for padding. Is that correct? Given a struct like the above, how will I find out how many bytes will be added as padding?
Question 2
I am aware that sizeof can be used to calculate the size of an array. Mostly I have seen the usage like (foos is an array of foo)
sizeof(foos)/sizeof(*foos)
But I found that the following will also give same result.
sizeof(foos) / sizeof(foo)
Is there any difference in these two? Which one is preferred?
Question 3
Consider the following statement.
foo foos[] = {10,20,30};
When I do sizeof(foos) / sizeof(*foos), it gives 2. But the array has 3 elements. If I change the statement to
foo foos[] = {{10},{20},{30}};
it gives correct result 3. Why is this happening?
Any thoughts..
| Answer 1
Yes - your calculation is correct. On your machine, sizeof(int) == 4, and int must be 4-byte aligned.
You can find out about the padding by manually adding the sizes of the base elements and subtracting that from the size reported by sizeof(). You can predict the padding if you know the alignment requirements on your machine. Note that some machines are quite fussy and give SIGBUS errors when you access misaligned data; others are more lax but slow you down when you access misaligned data (and they might support '#pragma packed' or something similar). Often, a basic type has a size that is a power of 2 (1, 2, 4, 8, 16) and an n-byte type like that must be n-byte aligned. Also, remember that structures have to be padded so that an array of structures will leave all elements properly aligned. That means the structure will normally be padded up to a multiple of the size of the most stringently aligned member in the structure.
Answer 2
Generally, a variant on the first is better; it remains correct when you change the base type of the array from a 'foo' to a 'foobar'. The macro I customarily use is:
#define DIM(x) (sizeof(x)/sizeof(*(x)))
Other people have other names for the same basic operation - and you can put the name I use down to pollution from the dim and distant past and some use of BASIC.
As usual, there are caveats. Most notably, you can't apply this meaningfully to array arguments to a function or to a dynamically allocated array (using malloc() et al or new[]); you have apply to the actual definition of an array. Normally the value is a compile-time constant. Under C99, it could be evaluated at runtime if the array is a VLA - variable-length array.
Answer 3
Because of the way initialization works when you don't have enough braces. Your 'foo' structure must have two elements. The 10 and the 20 are allocated to the first row; the 30 and an implicit 0 are supplied to the second row. Hence the size is two. When you supply the sub-braces, then there are 3 elements in the array, the first components of which have the values 10, 20, 30 and the second components all have zeroes.
|
2,536,077 | 2,536,236 | How to optimize erasing from multimap | I have two multimaps defined so multimap phoneNums; and multimap numPhones; they are some kind of phone registry - phoneNums contains Key name, and second argument phonenumber, numPhones contain Key phonenumber and second is name. I want to optimize erase from both of them when i want to delete string Key form phoneNums, which is also second element in numPhones. When i enter data it is entered in both multimaps so they are actually the same but with swapped first and second
when i put it on tests it says that erasing is too slow - N*N and must be only N
cin>>stringToErase;
phoneNums.erase(stringToErase);
multimap<string, string>::iterator it;
multimap<string, string>::iterator tmpr;
for(it = numPhones.begin(); it != numPhones.end();it++)
{
if(it->second == tringToErase)
{
tmpr = it;
numPhones.erase(it,tmpr);
}
}
| More generally, for this kind of problem, you can use the following technic:
A container, which holds the data
Several indexes, which point to the data aforementioned
If you place reverse indexes along the data (so as to point to the places in the indexes that refer to this item), then you can efficiently remove any item:
Look it up using the most suitable index (depending on the info you have)
Delete the references in the various indexes (you have iterators to them, so it's efficient)
Delete the data itself
This may seem tedious, but it's what Boost.MultiIndex is for :)
For the very specific case you are speaking of, there is a wrapper above the MultiIndex library called Boost.Bimap as mentioned by Jack.
|
2,536,289 | 2,536,347 | Compiler optimization of references | I often use references to simplify the appearance of code:
vec3f& vertex = _vertices[index];
// Calculate the vertex position
vertex[0] = startx + col * colWidth;
vertex[1] = starty + row * rowWidth;
vertex[2] = 0.0f;
Will compilers recognize and optimize this so it is essentially the following?
_vertices[index][0] = startx + col * colWidth;
_vertices[index][1] = starty + row * rowWidth;
_vertices[index][2] = 0.0f;
| Yes. This is a basic optimization that any modern (and even ancient) compilers will make.
In fact, I don't think it's really accurate to call that you've written an optimisation, since the move straightforward way to translate that to assembly involves a store to the _vertex address, plus index, plus {0,1,2} (multiplied by the appropriate sizes for things, of course).
In general though, modern compilers are amazing. Almost any optimization you can think of will be implemented. You should always write your code in a way that emphasizes readability unless you know that one way has significant performance benefits for your code.
As a simple example, code like this:
int func() {
int x;
int y;
int z;
int a;
x = 5*5;
y = x;
z = y;
a = 100 * 100 * 100* 100;
return z;
}
Will be optimized to this:
int func() {
return 25
}
Additionally, the compiler will also inline the function so that no call is actually made. Instead, everywhere 'func()' appears will just be replaced with '25'.
This is just a simple example. There are many more complex optimizations a modern compiler implements.
|
2,536,615 | 2,536,690 | Generation of an array of Random numbers with defined Min, Max, Mean and Stdev with given number of elements and error level | I'd like to generate an array of Random numbers with defined Min, Max, Mean and Stdev with given number of elements and error level. Is there such a library in C, C++, PHP or Python to do so? Please kindly advise. Thanks!
| The Boost C++ random number library may do some of what you want, certainly you can with some distributions select the modal value of the distribution. That's all I've needed in my own code, so I've never investigated further. The library doesn't generate arrays - you would typically use a C++ std::vector to contain the results of random number generation.
|
2,537,048 | 2,537,430 | Changing code at runtime | I have a pointer to a function (which i get from a vtable) and I want to edit the function by changing the assembler code (changing a few bytes) at runtime. I tried using memset and also tried assigning the new value directly (something like mPtr[0] = X, mPtr[1] = Y etc.) but I keep getting segmentation fault.
How can I change the code?
(I'm using C++)
OS is windows.
| In generally: if memory is allocated with API call VirtualAlloc than you can change the memory attributes with API call VirtualProtect.
Check first memory attributes with API call VirtualQuery
|
2,537,077 | 2,539,168 | cvHaarDetectObjects(): "Stack aound the variable 'seq_thread' was corrupted." | I have been looking in to writing my own implementation of Haar Cascaded face detection for some time now, and have begun with diving in to the OpenCV 2.0 implementation.
Right out of the box, running in debug mode, Visual Studio breaks on cvhaar.cpp:1518, informing me:
Run-Time Check Failure #2 - Stack aound the variable seq_thread was corrupted.
It seems odd to me that OpenCV ships with a simple array out-of-bounds problem. Running the release works without any problems, but I suspect that it is merely not performing the check and the array is exceeding the bounds.
Why am I receiving this error message? Is it a bug in OpenCV?
| A little debugging revealed the culprit, I believe. I "fixed" it, but this all still seems odd to me.
An array of size CV_MAX_THREADS is created on cvhaar.cpp:868:
CvSeq* seq_thread[CV_MAX_THREADS] = {0};
On line 918 it proceeds to specify max_threads:
max_threads = cvGetNumThreads();
In various places, seq_thread is looped using the following for statement:
for( i = 0; i < max_threads; i++ ) {
CvSeq* s = seq_thread[i];
// ...
}
However, cxmisc.h:108 declares CV_MAX_THREADS:
#define CV_MAX_THREADS 1
Hence, the declaration of seq_thread must never be allowed to exceed size 1, yet cvGetNumThreads() returns 2 (I assume this reflects the number of cores in my machine).
I resolved the problem by adding the following simple little statement:
if (max_threads > CV_MAX_THREADS) max_threads = CV_MAX_THREADS;
Does any of this make sense?
|
2,537,130 | 2,537,183 | is back_insert_iterator<> safe to be passed by value? | I have a code that looks something like:
struct Data { int value; };
class A {
public:
typedef std::deque<boost::shared_ptr<Data> > TList;
std::back_insert_iterator<TList> GetInserter()
{
return std::back_inserter(m_List);
}
private:
TList m_List;
};
class AA {
boost::scoped_ptr<A> m_a;
public:
AA() : m_a(new A()) {}
std::back_insert_iterator<A::TList> GetDataInserter()
{
return m_a->GetInserter();
}
};
class B {
template<class OutIt>
CopyInterestingDataTo(OutIt outIt)
{
// loop and check conditions for interesting data
// for every `it` in a Container<Data*>
// create a copy and store it
for( ... it = ..; .. ; ..) if (...) {
*outIt = OutIt::container_type::value_type(new Data(**it));
outIt++; // dummy
}
}
void func()
{
AA aa;
CopyInterestingDataTo(aa.GetDataInserter());
// aa.m_a->m_List is empty!
}
};
The problem is that A::m_List is always empty even after CopyInterestingDataTo() is called. However, if I debug and step into CopyInterestingDataTo(), the iterator does store the supposedly inserted data!
update:
I found the culprit. I actually have something like:
class AA {
boost::scoped_ptr<A> m_a;
std::back_insert_iterator<A::TList> GetDataInserter()
{
//return m_a->GetInserter(); // wrong
return m_A->GetInserter(); // this is the one I actually want
}
// ..... somewhere at the end of the file
boost::scoped_ptr<A> m_A;
};
Now, which answer should I mark as answer?
Really sorry for those not chosen, but you guys definitely got some up-votes : )
| The short answer is yes, back_insert_iterator is safe to pass by value. The long answer: From standard 24.4.2/3:
Insert iterators satisfy the
requirements of output iterators.
And 24.1.2/1
A class or a built-in type X satisfies
the requirements of an output iterator
if X is an Assignable type (23.1) ...
And finally from Table 64 in 23.1:
expression t = u
return-type T&
post-condition t is equivalent to u
EDIT: At a glance your code looks OK to me, are you 100% certain that elements are actually being inserted? If you are I would single step through the code and check the address of the aa.m_a->m_List object and compare it to the one stored in outIt in CopyInterestingDataTo, if they're not the same something's fishy.
|
2,537,132 | 2,560,851 | Windows Programming in C++ | Being a C#/Java programmer, I really need to know a fact: Has Windows Programming with Win32SDK/MFC/wxWidget become antiquated?
What is the status of popularity of these technologies in software industry now?
Being a C#/Java programmer, do I need to learn Win32SDK/MFC/wxWidget now?
| Yes, learn Win32, even if don't ever intend to write or maintain C/C++ apps.
No, don't bother learning MFC/wxWidget now. MFC does come with its source code, so you can study how some classes implement wrappers for Win32, but that is more interesting to C++ programmers. MFC is has decreased in popularity, though Visual Studio continues to support this older tech. Learn MFC/wxWidget only for an as-needed basis, if you need to maintain some older code.
With C#/Java, you can solve a lot of problems, but there are times when you will need to use Win32 directly to achieve some task. for a variety of reasons. Maybe some functionality is simply missing from .NET/Java, or has a bug that can be avoided by going directly to Win32. Maybe your particular problem to solve has unusual or strict requirements, and you would consider writing a portion of your app in native code using some Win32 calls as necessary. Lots of examples/situations really.
Another reason to learn Win32 is that both .NET/Java are higher level abstractions (which is in itself a good thing), but it really does help to understand the internals for these reasons:
You get an appreciation of how much work .NET/Java do for you. Of course, you can do the same things in C/C++, but it takes a lot more work. Consider these two compelling .NET technologies, WPF and WCF, which do a lot work for you.
You will better understand resource management. Specifically, both .NET/Java are garbage collected environments, but you must deterministically release OS resources (explicitly calling Dispose), for such things as network connections, window handles, kernel objects, and plenty more. You should never rely on the garbage collector to release these objects for you, since the GC is non-deterministic.
Debugging, knowing the internals seriously helps here.
Knowing Win32 can sometimes help explain the API design in .NET at least. Some parts of the .NET API are modeled on Win32 API, but some parts of the .NET API are extreme improvements over some truly heinous Win32 API designs (consider the API for using GDI for example).
Finally, knowing Win32 can help solve performance problems in your apps.
Win32 won't become antiquated, until the Microsoft's popular operating systems are based on something else. At one point, Microsoft was going to replace Win32/64 with .NET in Vista, but this didn't pan out. Even for whatever replaces Win32/64 is the future, you still need to understand the OS SDK. At the risk of sounding like a salesman, I will say that learning Win32 will in fact help you write more robust applications and will greatly aid your debugging skills, two important items to help you stay employed. I would never hire a windows programmer who doesn't have at least some experience with Win32.
I would suggest "Windows via C/C++" by Richter/Nasarre, as one example of a good book on Win32 (yes, it's obviously geared towards C/C++, but these authors do an excellent job explaining Win32).
Hope this helps.
|
2,537,229 | 2,537,330 | How can I write a function template for all types with a particular type trait? | Consider the following example:
struct Scanner
{
template <typename T>
T get();
};
template <>
string Scanner::get()
{
return string("string");
}
template <>
int Scanner::get()
{
return 10;
}
int main()
{
Scanner scanner;
string s = scanner.get<string>();
int i = scanner.get<int>();
}
The Scanner class is used to extract tokens from some source. The above code works fine, but fails when I try to get other integral types like a char or an unsigned int. The code to read these types is exactly the same as the code to read an int. I could just duplicate the code for all other integral types I'd like to read, but I'd rather define one function template for all integral types.
I've tried the following:
struct Scanner
{
template <typename T>
typename enable_if<boost::is_integral<T>, T>::type get();
};
Which works like a charm, but I am unsure how to get Scanner::get<string>() to function again. So, how can I write code so that I can do scanner.get<string>() and scanner.get<any integral type>() and have a single definition to read all integral types?
Update: bonus question: What if I want to accept more than one range of classes based on some traits? For example: how should I approach this problem if I want to have three get functions that accept (i) integral types (ii) floating point types (iii) strings, respectively.
| struct Scanner
{
template <typename T>
typename boost::enable_if<boost::is_integral<T>, T>::type get()
{
return 10;
}
template <typename T>
typename boost::disable_if<boost::is_integral<T>, std::string>::type get()
{
return "string";
}
};
Update "What if I want to accept more than one range of classes based on some traits?"
struct Scanner
{
template <typename T>
typename boost::enable_if<boost::is_integral<T>, T>::type get()
{
return 10;
}
template <typename T>
typename boost::enable_if<boost::is_floating_point<T>, T>::type get()
{
return 11.5;
}
template <typename T>
std::string get(
typename boost::disable_if<boost::is_floating_point<T>, T>::type* = 0,
typename boost::disable_if<boost::is_integral<T>, T>::type* = 0)
{
return std::string("string");
}
};
|
2,537,484 | 2,537,862 | dynamic linking:change of the linking path | Normally it happens that when ever the path of the library that has to be linked dynamically is defined in LD_LIBRARY_PATH or it it will be mentioned with -L flag while creating the binary.
In actual scenario if ,lets say the binary has been built and deployed at the client place.
Now if there is a change in the path of one of the dynamic link library path.
then we need to supply a new make file to all the clients where the binary was deployed.
is there any other method where we need not tell all the clients to change their makefiles and can something can be done in the code itself?
if yes...could anybody please suggest how?
This was ironically an interview question that was asked to me and i didnot have the answer for it.
EDIT:: I was specifically asked about what can be done in the code without touching the makefile.
| Maybe the interviewers wanted to know about dlopen and dlsym?
http://linux.die.net/man/3/dlsym
|
2,537,500 | 2,537,577 | What is the modern equivalent (C++) style for the older (C-like) fscanf method? | What is the best option if I want to "upgrade" old C-code to newer C++ when reading a file with a semicolon delimiter:
/* reading in from file C-like: */
fscanf(tFile, "%d", &mypost.nr); /*delimiter ; */
fscanf(tFile, " ;%[^;];", mypost.aftername);/* delimiter ; */
fscanf(tFile, " %[^;]", mypost.forename); /*delimiter ; */
fscanf(tFile, " ;%[^;];", mypost.dept);/*delimiter ; */
fscanf(tFile, " %[^;];", mypost.position);/* delimiter ; */
fscanf(tFile, "%d", &mypost.nr2);
//eqivalent best C++ method achieving the same thing?
| You could overload the right-shift operator on istream for your struct, so:
std::istream& operator>>(std::istream& is, mypost_struct& mps) {
is >> mps.nr;
is.ignore(1, ';');
is.getline(mps.forename, 255, ';');
is.getline(mps.aftername, 255, ';');
is >> mps.dept;
is.ignore(1, ';');
is >> mps.position;
is.ignore(1, ';');
is >> mps.nr2;
return is;
}
Subsequently, input is as simple as is >> mypost;, where is is the file that you have opened.
Edit: @UncleBens Thanks for pointing this out, I had forgotten to take spaces in account. I have updated the answer, assuming that forename and aftername are likely to contain spaces. And there was this rather embarrasing bit about the delimiters being double-quoted...
I just checked it using a struct definition as under:
struct mypost_struct {
int nr;
char forename[255], aftername[255];
int dept, position, nr2;
};
.. and the result was as expected.
|
2,537,708 | 12,783,060 | Process Management Solution | I'm working on a project that requires a process management solution much like init.d but with the following requirements:
1) Working with Windows not Linux
2) Must be able to start/stop/restart programs written in heterogeneous languages.
3) Must be able to extend process manager to start / stop processes depending on run-mode information obtained from remote-host over pub/sub interface (most likely DDS).
Ideally we would want this in Java, but can be C / C++. Also, the process manager must be fail safe (I assume running in a service with auto-restart on fail will be enough).
I could write my own implementation for scratch, but we have a unreasonably tight schedule, so obviously an already developed solution is preferable.
Michael
| In the end I simply bootstrapped my processes with a Windows service wrapper and manually managed their lifecycle programatically with windows APIs for services.
|
2,537,716 | 2,537,825 | Why is partial specialization of a nested class template allowed, while complete isn't? | template<int x> struct A {
template<int y> struct B {};.
template<int y, int unused> struct C {};
};
template<int x> template<>
struct A<x>::B<x> {}; // error: enclosing class templates are not explicitly specialized
template<int x> template<int unused>
struct A<x>::C<x, unused> {}; // ok
So why is the explicit specialization of a inner, nested class (or function) not allowed, if the outer class isn't specialized too? Strange enough, I can work around this behaviour if I only partially specialize the inner class with simply adding a dummy template parameter. Makes things uglier and more complex, but it works.
I would consider complete specializations as a subset of partial specializations - especially because you can express every complete specialization as a partial with adding a dummy parameter. So this disambiguation between partial and full specialization doesn't really make sense for me.
Unfortunatly nobody at comp.std.c++ dared to answer, so I am putting it up here again with a bounty.
Note: I need this feature for recursive templates of the inner class for a set of the outer class and the specialization of the inner parameter does depend on the outer template parameter.
| My guess as to why this happens: complete specializations are no longer "template classes/functions", they are are "real" classes/methods, and get to have real (linker-visible) symbols. But for a completely-specialized template inside a partially-specialized one, this would not be true.
Probably this decision was taken just to simplify the life of compiler-writers (and make life harder for coders, in the process :P ).
|
2,537,799 | 2,538,310 | How can I convert a Perl regex to work with Boost::Regex? | What is the Boost::Regex equivalent of this Perl regex for words that end with ing or ed or en?
/ing$|ed$|en$/
...
| /^[\.:\,()\'\`-]/
should become
"^[.:,()'`-]"
The special Perl regex delimiter / doesn't exist in C++, so regexes are just a string. In those strings, you need to take care to escape backslashes correctly (\\ for every \ in your original regex). In your example, though, all those backslashes were unnecessary, so I dropped them completely.
There are other caveats; some Perl features (like variable-length lookbehind) don't exist in the Boost library, as far as I know. So it might not be possible to simply translate any regex. Your examples should be fine, though. Although some of them are weird. .*[0-9].* will match any string that contains a number somewhere, not all numbers.
|
2,537,819 | 2,538,879 | How to find string in a string | I somehow need to find the longest string in other string, so if string1 will be "Alibaba" and string2 will be "ba" , the longest string will be "baba". I have the lengths of strings, but what next ?
char* fun(char* a, char& b)
{
int length1=0;
int length2=0;
int longer;
int shorter;
char end='\0';
while(a[i] != tmp)
{
i++;
length1++;
}
int i=0;
while(b[i] != tmp)
{
i++;
length++;
}
if(dlug1 > dlug2){
longer = length1;
shorter = length2;
}
else{
longer = length2;
shorter = length1;
}
//logics here
}
int main()
{
char name1[] = "Alibaba";
char name2[] = "ba";
char &oname = *name2;
cout << fun(name1, oname) << endl;
system("PAUSE");
return 0;
}
| Wow lots of bad answers to this question. Here's what your code should do:
Find the first instance of "ba" using the standard string searching functions.
In a loop look past this "ba" to see how many of the next N characters are also "ba".
If this sequence is longer than the previously recorded longest sequence, save its length and position.
Find the next instance of "ba" after the last one.
Here's the code (not tested):
string FindLongestRepeatedSubstring(string longString, string shortString)
{
// The number of repetitions in our longest string.
int maxRepetitions = 0;
int n = shortString.length(); // For brevity.
// Where we are currently looking.
int pos = 0;
while ((pos = longString.find(shortString, pos)) != string::npos)
{
// Ok we found the start of a repeated substring. See how many repetitions there are.
int repetitions = 1;
// This is a little bit complicated.
// First go past the "ba" we have already found (pos += n)
// Then see if there is still enough space in the string for there to be another "ba"
// Finally see if it *is* "ba"
for (pos += n; pos+n < longString.length() && longString.substr(pos, n) == shortString; pos += n)
++repetitions;
// See if this sequence is longer than our previous best.
if (repetitions > maxRepetitions)
maxRepetitions = repetitions;
}
// Construct the string to return. You really probably want to return its position, or maybe
// just maxRepetitions.
string ret;
while (maxRepetitions--)
ret += shortString;
return ret;
}
|
2,537,942 | 2,537,973 | Nullable values in C++ | I'm creating a database access layer in native C++, and I'm looking at ways to support NULL values. Here is what I have so far:
class CNullValue
{
public:
static CNullValue Null()
{
static CNullValue nv;
return nv;
}
};
template<class T>
class CNullableT
{
public:
CNullableT(CNullValue &v) : m_Value(T()), m_IsNull(true)
{
}
CNullableT(T value) : m_Value(value), m_IsNull(false)
{
}
bool IsNull()
{
return m_IsNull;
}
T GetValue()
{
return m_Value;
}
private:
T m_Value;
bool m_IsNull;
};
This is how I'll have to define functions:
void StoredProc(int i, CNullableT<int> j)
{
...connect to database
...if j.IsNull pass null to database etc
}
And I call it like this:
sp.StoredProc(1, 2);
or
sp.StoredProc(3, CNullValue::Null());
I was just wondering if there was a better way than this. In particular I don't like the singleton-like object of CNullValue with the statics.
I'd prefer to just do
sp.StoredProc(3, CNullValue);
or something similar. How do others solve this problem?
| Boost.Optional probably does what you need.
boost::none takes the place of your CNullValue::Null(). Since it's a value rather than a member function call, you can do using boost::none; if you like, for brevity. It has a conversion to bool instead of IsNull, and operator* instead of GetValue, so you'd do:
void writeToDB(boost::optional<int> optional_int) {
if (optional_int) {
pass *optional_int to database;
} else {
pass null to database;
}
}
But what you've come up with is essentially the same design, I think.
|
2,537,947 | 2,538,007 | Example where TYPE_ALIGNMENT() fails | I have a question relating to alignment in C/C++. In
Determining the alignment of C/C++ structures in relation to its members Michael Burr posted this macro:
#define TYPE_ALIGNMENT( t ) offsetof( struct { char x; t test; }, test )
In the comments someone wrote this might fail with non POD types. Can someone give me an code example where this fails?
| offsetof is only specified to work for POD types. If a class contains any data members that are not POD, the class itself is not POD. So, if t in your example is a non-POD type, it is not guaranteed to work.
From the C++ standard (18.1/5):
The macro offsetof accepts a restricted set of type arguments in this International Standard. type shall be a POD structure or a POD union.
So, if you use offsetof on a non-POD type, the results are undefined.
|
2,538,078 | 2,538,095 | What's the bug in the following code? | #include <iostream>
#include <algorithm>
#include <vector>
#include <boost/array.hpp>
#include <boost/bind.hpp>
int main() {
boost::array<int, 4> a = {45, 11, 67, 23};
std::vector<int> v(a.begin(), a.end());
std::vector<int> v2;
std::transform(v.begin(), v.end(), v2.begin(),
boost::bind(std::multiplies<int>(), _1, 2));
std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, " "));
}
When run, this gives a creepy segmentation fault. Please tell me where I'm going wrong.
| v2 has a size of zero when you call transform. You either need to resize v2 so that it has at least as many elements as v before the call to transform:
v2.resize(v.size());
or you can use std::back_inserter in the call to transform:
std::transform(v.begin(), v.end(), std::back_inserter(v2), boost::bind(std::multiplies<int>(), _1, 2));
|
2,538,083 | 2,602,092 | Eclipse CDT: cannot debug or terminate application | I have Eclipse set up fairly nicely to run the G++ compiler through Cygwin. Even the character encoding is set up correctly!
There still seems to be something wrong with my configuration: I can't debug. The pause button in the debug view is simply disabled, and no threads appear in my application tree. It seems that gdb is simply not communicating with Eclipse.
Presently, I have the debug settings as follows:
Debugger: "Cygwin gdb Debugger"
GDB debugger: gdb
GDB command file: .gdbinit
Protocol: Default
I should mention here that I have no idea what .gdbinit does; in my project it is merely an empty file.
What is wrong with my configuration?
Debugging
When attempting to terminate the application in debug mode, Eclipse displays the following error:
Target request failed: failed to interrupt.
I can't kill the process, either; I have to kill its parent gdb.exe, which in turn kills my application.
Running
When running it normally, a bunch of kill.exes are called, doing nothing, while Eclipse displays the following error:
Terminate failed.
I can kill FaceDetector.exe from the task manager.
Process Explorer
This is what it looks like in Process Explorer (debugging left, running right):
| The only workaround that I've found is to start Eclipse directly from Cygwin.
Start a Cygwin Bash Shell, navigate to Eclipse's installation directory, and enter ./eclipse.exe.
It would appear that there's some problem with the way that CDT communicates with Cygwin; the standard output is passed and kill.exe is executed, but kill.exe doesn't succeed in actually terminating the application unless Eclipse is run through Cygwin. Debugging via gdb gives similar problems; also this is resolved with the workaround.
|
2,538,103 | 2,538,216 | How to call a function from a shared library? | What is the easiest and safest way to call a function from a shared library / dll? I am mostly interested in doing this on linux, but it would be better if there were a platform-independent way.
Could someone provide example code to show how to make the following work, where the user has compiled his own version of foo into a shared library?
// function prototype, implementation loaded at runtime:
std::string foo(const std::string);
int main(int argc, char** argv) {
LoadLibrary(argv[1]); // loads library implementing foo
std::cout << "Result: " << foo("test");
return 0;
}
BTW, I know how to compile the shared lib (foo.so), I just need to know an easy way to load it at runtime.
| NOTE: You are passing C++ objects (in this case STL strings) around library calls. There is no standard C++ ABI at this level, so either try to avoid passing C++ objects around, or ensure that both your library and your program have been built with the same compiler (ideally the same compiler on the same machine, to avoid any subtle configuration-related surprises.)
Do not forget to declare your exported methods extern "C" inside your library code.
The above having been said, here is some code implementing what you said you want to achieve:
typedef std::string (*foo_t)(const std::string);
foo_t foo = NULL;
...
# ifdef _WIN32
HMODULE hDLL = ::LoadLibrary(szMyLib);
if (!hDll) { /*error*/ }
foo = (foo_t)::GetProcAddress(hDLL, "foo");
# else
void *pLib = ::dlopen(szMyLib, RTLD_LAZY);
if (!pLib) { /*error*/ }
foo = (foo_t)::dlsym(pLib, "foo");
# endif
if (!foo) { /*error*/ }
...
foo("bar");
...
# ifdef _WIN32
::FreeLibrary(hDLL);
# else
::dlclose(pLib);
# endif
You can abstract this further:
#ifdef _WIN32
#include <windows.h>
typedef HANDLE my_lib_t;
#else
#include <dlfcn.h>
typedef void* my_lib_t;
#endif
my_lib_t MyLoadLib(const char* szMyLib) {
# ifdef _WIN32
return ::LoadLibraryA(szMyLib);
# else //_WIN32
return ::dlopen(szMyLib, RTLD_LAZY);
# endif //_WIN32
}
void MyUnloadLib(my_lib_t hMyLib) {
# ifdef _WIN32
return ::FreeLibrary(hMyLib);
# else //_WIN32
return ::dlclose(hMyLib);
# endif //_WIN32
}
void* MyLoadProc(my_lib_t hMyLib, const char* szMyProc) {
# ifdef _WIN32
return ::GetProcAddress(hMyLib, szMyProc);
# else //_WIN32
return ::dlsym(hMyLib, szMyProc);
# endif //_WIN32
}
typedef std::string (*foo_t)(const std::string);
typedef int (*bar_t)(int);
my_lib_t hMyLib = NULL;
foo_t foo = NULL;
bar_t bar = NULL;
...
if (!(hMyLib = ::MyLoadLib(szMyLib)) { /*error*/ }
if (!(foo = (foo_t)::MyLoadProc(hMyLib, "foo")) { /*error*/ }
if (!(bar = (bar_t)::MyLoadProc(hMyLib, "bar")) { /*error*/ }
...
foo("bar");
bar(7);
...
::MyUnloadLib(hMyLib);
|
2,538,149 | 2,539,084 | What should be contained in a global source code control ignore pattern for Visual Studio 2010? | After installing and using Visual Studio 2010, I'm seeing some newer file types (at least with C++ projects ... don't know about the other types) as compared to 2008. e.g. .sdf, .opensdf, which I guess are the replacement for ncb files with Intellisense info stored in SQL Server Compact files? I also notice .log files are generated, which appear to be build logs.
Given this, what's safe to add to my global ignore pattern? Off the bat, I'd assume .sdf, .opensdf, but what else?
| For C++ projects, you should be fine ignoring the following files:
*.sdf and *.opensdf (temporary file opened only while .vcxproj/.sln is loaded to
Visual Studio IDE)
*.suo
*.vcxproj.user
ipch folder, if your project uses Pre-compiled Headers (PCH); it is a storage for Intellisense compiler which can now utilise PCH for better performance
For C# projects, it's also a good idea to ignore bin and obj directories, and *.suo too.
|
2,538,491 | 2,538,516 | this pointer to base class constructor? | I want to implement a derived class that should also implement an interface, that have a function that the base class can call. The following gives a warning as it is not safe to pass a this pointer to the base class constructor:
struct IInterface
{
void FuncToCall() = 0;
};
struct Base
{
Base(IInterface* inter) { m_inter = inter; }
void SomeFunc() { inter->FuncToCall(); }
IInterface* m_inter;
};
struct Derived : Base, IInterface
{
Derived() : Base(this) {}
FuncToCall() {}
};
What is the best way around this? I need to supply the interface as an argument to the base constructor, as it is not always the dervied class that is the interface; sometimes it may be a totally different class.
I could add a function to the base class, SetInterface(IInterface* inter), but I would like to avoid that.
| You shold not publish this from the constructor, as your object is not yet initialized properly at that point. In this actual situation, though, it seems to be safe, since you are publishing it only to the base class, which only stores it and does not invoke it until some point later, by which time the construction will have been finished.
However, if you want to get rid of the warning, you could use a static factory method:
struct Base
{
public:
Base() { }
void setInterface(IInterface* inter) { m_inter = inter; }
void SomeFunc() { inter->FuncToCall(); }
IInterface* m_inter;
};
struct Derived : Base, IInterface
{
private:
Derived() : Base() {}
public:
static Derived* createInstance() {
Derived instance = new Derived();
instance->setInterface(instance);
return instance;
}
FuncToCall() {}
};
Note that the constructor of Derived is private to ensure that instantiation is done only via createInstance.
|
2,538,562 | 2,538,627 | In what order does evaluation of post-increment operator happen? | Given
std::vector<CMyClass> objects;
CMyClass list[MAX_OBJECT_COUNT];
Is it wise to do this?
for(unsigned int i = 0; i < objects.size(); list[i] = objects.at(i++));
Or should I expand my loop to this?
for(unsigned int i = 0; i < objects.size(); i++)
{
list[i] = objects.at(i);
}
| The former is undefined behavior. It's not specified whether list[i] is evaluated (to provide an lvalue for the lhs of the assignment) before or after the function call to objects.at.
Hence there is a legal ordering of the various parts of the expression, in which i is accessed (in list[i]) and separately modified (in i++), without an intervening sequence point.
This is precisely the condition for undefined behavior in the C++ standard - whether such a legal ordering exists. IIRC the C standard expresses it slightly differently but with the same effect.
If in doubt, don't write an expression which uses an increment operator, and also uses the same value anywhere else in the expression. You can do it with the comma operator (i++, i++ is fine) and the conditional operator (i ? i++ : i-- is fine) because they have sequence points in them, but it's rarely worth it. || and && likewise, and something like p != end_p && *(p++) = something; isn't totally implausible. Any other use, and if you stare at it long enough you can usually work out an order of evaluation that messes things up.
That's aside from the comprehensibility of complicated for expressions and for loops with empty bodies.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.