question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,305,947 | 1,306,069 | Why does C++ need a separate header file? | I've never really understood why C++ needs a separate header file with the same functions as in the .cpp file. It makes creating classes and refactoring them very difficult, and it adds unnecessary files to the project. And then there is the problem with having to include header files, but having to explicitly check if it has already been included.
C++ was ratified in 1998, so why is it designed this way? What advantages does having a separate header file have?
Follow up question:
How does the compiler find the .cpp file with the code in it, when all I include is the .h file? Does it assume that the .cpp file has the same name as the .h file, or does it actually look through all the files in the directory tree?
| You seem to be asking about separating definitions from declarations, although there are other uses for header files.
The answer is that C++ doesn't "need" this. If you mark everything inline (which is automatic anyway for member functions defined in a class definition), then there is no need for the separation. You can just define everything in the header files.
The reasons you might want to separate are:
To improve build times.
To link against code without having the source for the definitions.
To avoid marking everything "inline".
If your more general question is, "why isn't C++ identical to Java?", then I have to ask, "why are you writing C++ instead of Java?" ;-p
More seriously, though, the reason is that the C++ compiler can't just reach into another translation unit and figure out how to use its symbols, in the way that javac can and does. The header file is needed to declare to the compiler what it can expect to be available at link time.
So #include is a straight textual substitution. If you define everything in header files, the preprocessor ends up creating an enormous copy and paste of every source file in your project, and feeding that into the compiler. The fact that the C++ standard was ratified in 1998 has nothing to do with this, it's the fact that the compilation environment for C++ is based so closely on that of C.
Converting my comments to answer your follow-up question:
How does the compiler find the .cpp file with the code in it
It doesn't, at least not at the time it compiles the code that used the header file. The functions you're linking against don't even need to have been written yet, never mind the compiler knowing what .cpp file they'll be in. Everything the calling code needs to know at compile time is expressed in the function declaration. At link time you will provide a list of .o files, or static or dynamic libraries, and the header in effect is a promise that the definitions of the functions will be in there somewhere.
|
1,305,967 | 1,306,428 | How to determine whether output iterator has been modified | I have a template function that takes the following form:
template < class ITER1, class ITER2 >
bool example(ITER1 Input1, ITER1 Input2, ITER2 Output)
{
ITER2 OrigOutput(Output);
// ...
std::copy(Input1, Input2, Output);
return (OrigOutput != Output);
}
And I'm calling example() like this:
std::vector < int > Input;
std::set < int > Output;
if (example(Input.begin(), Input.end(), inserter(Output, Output.begin())))
{
...
}
I'd like example() to return true if elements have been inserted into Output, however I'm getting a compile error (msvc 2008):
Error 1 error C2678: binary '!=' : no operator found which takes a left-hand
operand of type 'std::insert_iterator<_Container>' (or there is no acceptable
conversion)
Is there a way I can determine whether any elements were inserted into the output iterator in order to return the correct bool value?
| Write a wrapper iterator which delgates to another iterator, which you would construct from your insert iterator. Your delegate then can set a modified member to be true in the operator= method.
Something along the lines of this:
template<typename ITER>
class ModifiedIterator : public std::iterator<std::output_iterator_tag, void, void, void, void>
{
protected:
typedef ITER Iter;
Iter iter;
bool& isModified;
public:
explicit ModifiedIterator (Iter i, bool& isMod)
: iter(i), isModified (isMod)
{}
template<typename T>
ModifiedIterator& operator= (const T& value)
{
iter = value;
++iter;
isModified = true;
return *this;
}
ModifiedIterator& operator* () { return *this; }
ModifiedIterator& operator++ () { return *this; }
ModifiedIterator operator++ (int) { return *this; }
};
|
1,306,094 | 1,306,127 | Does the memory get released when I throw an exception? | I was debating with some colleagues about what happens when you throw an exception in a dynamically allocated class. I know that malloc gets called, and then the constructor of the class. The constructor never returns, so what happens to the malloc?
Consider the following example:
class B
{
public:
B()
{
cout << "B::B()" << endl;
throw "B::exception";
}
~B()
{
cout << "B::~B()" << endl;
}
};
void main()
{
B *o = 0;
try
{
o = new B;
}
catch(const char *)
{
cout << "ouch!" << endl;
}
}
What happens to the malloced memory o, does it leak? Does the CRT catch the exception of the constructor and deallocate the memory?
Cheers!
Rich
| A call to
new B();
resolves in two things:
allocating with an operator new() (either the global one or a class specific one, potentially a placement one with the syntax new (xxx) B())
calling the constructor.
If the constructor throw, the corresponding operator delete is called. The case where the corresponding delete is a placement one is the only case where a placement delete operator is called without the syntax ::operator delete(). delete x; or delete[] x; don't call the placement delete operators and there is no similar syntax to placement new to call them.
Note that while the destructor of B will not be called, already constructed subobjects (members or B and base classes of B) will be destructed before the call to operator delete. The constructor which isn't called is the one for B.
|
1,306,118 | 1,319,983 | Overhead due to use of Events | I have a custom thread pool class, that creates some threads that each wait on their own event (signal). When a new job is added to the thread pool, it wakes the first free thread so that it executes the job.
The problem is the following : I have around 1000 loops of each around 10'000 iterations do to. These loops must be executed sequentially, but I have 4 CPUs available. What I try to do is to split the 10'000 iteration loops into 4 2'500 iterations loops, ie one per thread. But I have to wait for the 4 small loops to finish before going to the next "big" iteration. This means that I can't bundle the jobs.
My problem is that using the thread pool and 4 threads is much slower than doing the jobs sequentially (having one loop executed by a separate thread is much slower than executing it directly in the main thread sequentially).
I'm on Windows, so I create events with CreateEvent() and then wait on one of them using WaitForMultipleObjects(2, handles, false, INFINITE) until the main thread calls SetEvent().
It appears that this whole event thing (along with the synchronization between the threads using critical sections) is pretty expensive !
My question is : is it normal that using events takes "a lot of" time ? If so, is there another mechanism that I could use and that would be less time-expensive ?
Here is some code to illustrate (some relevant parts copied from my thread pool class) :
// thread function
unsigned __stdcall ThreadPool::threadFunction(void* params) {
// some housekeeping
HANDLE signals[2];
signals[0] = waitSignal;
signals[1] = endSignal;
do {
// wait for one of the signals
waitResult = WaitForMultipleObjects(2, signals, false, INFINITE);
// try to get the next job parameters;
if (tp->getNextJob(threadId, data)) {
// execute job
void* output = jobFunc(data.params);
// tell thread pool that we're done and collect output
tp->collectOutput(data.ID, output);
}
tp->threadDone(threadId);
}
while (waitResult - WAIT_OBJECT_0 == 0);
// if we reach this point, endSignal was sent, so we are done !
return 0;
}
// create all threads
for (int i = 0; i < nbThreads; ++i) {
threadData data;
unsigned int threadId = 0;
char eventName[20];
sprintf_s(eventName, 20, "WaitSignal_%d", i);
data.handle = (HANDLE) _beginthreadex(NULL, 0, ThreadPool::threadFunction,
this, CREATE_SUSPENDED, &threadId);
data.threadId = threadId;
data.busy = false;
data.waitSignal = CreateEvent(NULL, true, false, eventName);
this->threads[threadId] = data;
// start thread
ResumeThread(data.handle);
}
// add job
void ThreadPool::addJob(int jobId, void* params) {
// housekeeping
EnterCriticalSection(&(this->mutex));
// first, insert parameters in the list
this->jobs.push_back(job);
// then, find the first free thread and wake it
for (it = this->threads.begin(); it != this->threads.end(); ++it) {
thread = (threadData) it->second;
if (!thread.busy) {
this->threads[thread.threadId].busy = true;
++(this->nbActiveThreads);
// wake thread such that it gets the next params and runs them
SetEvent(thread.waitSignal);
break;
}
}
LeaveCriticalSection(&(this->mutex));
}
| If you are just parallelizing loops and using vs 2008, I'd suggest looking at OpenMP. If you're using visual studio 2010 beta 1, I'd suggesting looking at the parallel pattern library, particularly the "parallel for" / "parallel for each"
apis or the "task group class because these will likely do what you're attempting to do, only with less code.
Regarding your question about performance, here it really depends. You'll need to look at how much work you're scheduling during your iterations and what the costs are. WaitForMultipleObjects can be quite expensive if you hit it a lot and your work is small which is why I suggest using an implementation already built. You also need to ensure that you aren't running in debug mode, under a debugger and that the tasks themselves aren't blocking on a lock, I/O or memory allocation, and you aren't hitting false sharing. Each of these has the potential to destroy scalability.
I'd suggest looking at this under a profiler like xperf the f1 profiler in visual studio 2010 beta 1 (it has 2 new concurrency modes which help see contention) or Intel's vtune.
You could also share the code that you're running in the tasks, so folks could get a better idea of what you're doing, because the answer I always get with performance issues is first "it depends" and second, "have you profiled it."
Good Luck
-Rick
|
1,306,414 | 1,306,445 | What is the meaning and usage of __stdcall? | I've come across __stdcall a lot these days.
MSDN doesn't explain very clearly what it really means, when and why should it be used, if at all.
I would appreciate if someone would provide an explanation, preferably with an example or two.
| All functions in C/C++ have a particular calling convention. The point of a calling convention is to establish how data is passed between the caller and callee and who is responsible for operations such as cleaning out the call stack.
The most popular calling conventions on windows are
__stdcall, Pushes parameters on the stack, in reverse order (right to left)
__cdecl, Pushes parameters on the stack, in reverse order (right to left)
__clrcall, Load parameters onto CLR expression stack in order (left to right).
__fastcall, Stored in registers, then pushed on stack
__thiscall, Pushed on stack; this pointer stored in ECX
Adding this specifier to the function declaration essentially tells the compiler that you want this particular function to have this particular calling convention.
The calling conventions are documented here
https://learn.microsoft.com/en-us/cpp/cpp/calling-conventions
Raymond Chen also did a long series on the history of the various calling conventions (5 parts) starting here.
https://devblogs.microsoft.com/oldnewthing/20040102-00/?p=41213
|
1,306,604 | 1,306,615 | Why i can't declare following function in Visual C++ "string timeToStr(string);"? | When i'm trying to declare a function with a string parameter in .h file an error occurs. I haven't forgot to include string.h =) Everything builds fine when i'm using char[], but the i want the argument to be a string.
| string.h doesn't exist in C++. Did you mean string (without the .h)? Additionally, the string class resides in the std namespace you need to qualify the type usage:
std::string timeToStr(std::string);
It would be helpful if you had posted the exact error message and a code to reproduce the error.
|
1,306,611 | 1,306,683 | How do I implement no-op macro (or template) in C++? | How do I implement no-op macro in C++?
#include <iostream>
#ifdef NOOP
#define conditional_noop(x) what goes here?
#else
#define conditional_noop(x) std::cout << (x)
#endif
int main() {
conditional_noop(123);
}
I want this to do nothing when NOOP is defined and print "123", when NOOP is not defined.
| As mentioned before - nothing.
Also, there is a misprint in your code.
it should be #else not #elif. if it is #elif it is to be followed by the new condition
#include <iostream>
#ifdef NOOP
#define conditional_noop(x) do {} while(0)
#else
#define conditional_noop(x) std::cout << (x)
#endif
Have fun coding!
EDIT: added the [do] construct for robustness as suggested in another answer.
|
1,306,778 | 1,306,837 | Virtual/pure virtual explained | What exactly does it mean if a function is defined as virtual and is that the same as pure virtual?
| From Wikipedia's Virtual function
...
In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part of the (runtime) polymorphism portion of object-oriented programming (OOP). In short, a virtual function defines a target function to be executed, but the target might not be known at compile time.
Unlike a non-virtual function, when a virtual function is overridden the most-derived version is used at all levels of the class hierarchy, rather than just the level at which it was created. Therefore if one method of the base class calls a virtual method, the version defined in the derived class will be used instead of the version defined in the base class.
This is in contrast to non-virtual functions, which can still be overridden in a derived class, but the "new" version will only be used by the derived class and below, but will not change the functionality of the base class at all.
whereas..
A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract.
When a pure virtual method exists, the class is "abstract" and can not be instantiated on its own. Instead, a derived class that implements the pure-virtual method(s) must be used. A pure-virtual isn't defined in the base-class at all, so a derived class must define it, or that derived class is also abstract, and can not be instantiated. Only a class that has no abstract methods can be instantiated.
A virtual provides a way to override the functionality of the base class, and a pure-virtual requires it.
|
1,306,823 | 1,306,889 | Can you give an example of a buffer overflow? | I've heard so much about buffer overflows and believe I understand the problem but I still don't see an example of say
char buffer[16];
//code that will over write that buffer and launch notepad.exe
| First, you need a program that will launch other programs. A program that executes OS exec in some form or other. This is highly OS and language-specific.
Second, your program that launches other programs must read from some external source into a buffer.
Third, you must then examine the running program -- as layed out in memory by the compiler -- to see how the input buffer and the other variables used for step 1 (launching other programs) exist.
Fourth, you must concoct an input that will actually overrun the buffer and set the other variables.
So. Part 1 and 2 is a program that looks something like this in C.
#include <someOSstuff>
char buffer[16];
char *program_to_run= "something.exe";
void main( char *args[] ) {
gets( buffer );
exec( program_to_run );
}
Part 3 requires some analysis of what the buffer and the program_to_run look like, but you'll find that it's probably just
\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 s o m e t h i n g . e x e \x00
Part 4, your input, then has to be
1234567890123456notepad.exe\x00
So it will fill buffer and write over program_to_run.
|
1,307,547 | 1,308,418 | Determine object identity from a reference to a superclass | I have the following pair of functions:
void RegisterSink( ISink & Sink )
void UnregisterSink( ISink & Sink )
Where ISink is an abstract base class. Internally, I would like to store pointers to the sinks in an std::set. When a sink is unregistered, i simply search for the pointer in my set, and remove it. My question is, is there any way, that taking the adress of the parameter Sink would yield different results, although the same object was passed as a parameter. I know, that pointers can change when casting in certain multiple inheritance szenarios, but what about this situation?
Thanks in advance!
| In case of multiple inheritance the meaning of "same object" sometimes is not obvious.
For example, if ISink is present twice in the list of base classes and wasn't inherited with "virtual", such situation is possible:
class A {};
class B:public A {};
class C:public A {};
class D:public B,public C {};
...
void f(A *a);
...
{
D d;
f(static_cast<B*>(&d));
f(static_cast<C*>(&d));
}
In this case f will get two different addresses.
Whether is's same object or not probably depends on context.
If you want to treat them as the same object, dynamic_casting to void* may help - it castes to most derived class (something virtual in A is needed, of course)
|
1,307,642 | 1,310,580 | What is a good way to edit C++ on Mac OS X? | I am a first year Comp. Sci. student and am looking for the best way to develop C++ on a Mac. I have Xcode and Textmate.
What are the benefits/negatives of each? Are there any better ones?
I am not a fan of having to use a whole project to run programs with Xcode. Is this the only way to do it, or am I mistaken?
Also, is there a way to change the default text that is included in a .cpp file in xcode?
| I almost exclusively use Textmate, but to be fair the decision to switch to Textmate (coming from codewarrior in OS 9 days), was mainly because the XCode editor (then named ProjectBuilder) was annoyingly slow at editing larger files.
I'm sure that changed a lot over the years, but I see no reason to switch so I don't.
That said, one thing where XCode really outshines Textmate is the integration of a debugger, when you're just starting to learn, I think having an integrated debugger will help you quickly understand what's going on with your code, and will be a great advantage...
If you've got Textmate, just try em both for a few months, you're a student anyway, you should have plenty of time
|
1,307,831 | 1,309,207 | what is the result of incrementing an istream_iterator which is already at the end of the stream? | I've looked at the standard and didn't see an obvious answer.
suppose i've done this:
std::istream_iterator<char> is(file);
while(is != std::istream_iterator<char>()) {
++is;
}
now is is at the end of the stream and is equal to std::istream_iterator<char>(). What happens if I increment it one more time? Is it still equal to std::istream_iterator<char>()? or os the result undefined?
The standard explicitly states that *is is undefined behavior if is is at the end of the stream. But I haven't seen anything regarding iterating beyond the end of the stream...
EDIT:
I ask because I stumbled across some code which does something like this:
// skip 2 input chars
++is;
++is;
if(is != std::istream_iterator<char>()) {
// continue using is and do some work...but what if the first
// increment made it EOS? is this check valid?
}
| Table 72 in C++03 about input iterator requirements says that the pre-condition of ++r is that r is de-referenceable. The same pre-conditions holds for r++.
Now, 24.5.1/1 says about istream_iterator
The result of operator* on an end of stream is not defined.
In conclusion, the effects of operator++ on an end-of-stream iterator are undefined.
Table 72 in C++03 about input iterator requirements says that the pre-condition of ++r is that r is de-referenceable. The same pre-conditions holds for r++.
Now, 24.5.1/1 says about istream_iterator
The result of operator* on an end of stream is not defined.
In conclusion, the effects of operator++ on an end-of-stream iterator are undefined.
Note that I think this conclusion makes behavior undefined only when you write or use an algorithm taking input iterators which exhibits that behavior, and then pass an istream iterator. From only using the istream iterator itself explicitly, without treating it as an input iterator and relying on its invariants, then i think the conclusion above isn't quite right (we may have a class that doesn't require that r is dereferenceable, for example).
But looking at how istream iterator is described, an invocation of operator++ after reaching the end of stream value results in undefined behavior either. operator== for it is defined as being equivalent to
x.in_stream == y.in_stream
Where in_stream is a pointer to the stream iterated over - and exposed into the Standard text for defining behavior and semantics "exposition only". Now, the only implementation i can think of that makes this work, is using an end-of-stream iterator that stores as stream pointer a null pointer. But operator++ is defined as doing something having the effect of the following
*in_stream >>value
Now, if you enter the end-of-stream state, and we would set in_stream to a null pointer, then surely the effect of that would be undefined behavior.
So even if you use the istream iterator alone, there doesn't seem to be any guarantee that you may increment past the end-of-stream value.
|
1,307,876 | 1,308,335 | How do conversion operators work in C++? | Consider this simple example:
template <class Type>
class smartref {
public:
smartref() : data(new Type) { }
operator Type&(){ return *data; }
private:
Type* data;
};
class person {
public:
void think() { std::cout << "I am thinking"; }
};
int main() {
smartref<person> p;
p.think(); // why does not the compiler try substituting Type&?
}
How do conversion operators work in C++? (i.e) when does the compiler try substituting the type defined after the conversion operator?
| Some random situations where conversion functions are used and not used follow.
First, note that conversion functions are never used to convert to the same class type or to a base class type.
Conversion during argument passing
Conversion during argument passing will use the rules for copy initialization. These rules just consider any conversion function, disregarding of whether converting to a reference or not.
struct B { };
struct A {
operator B() { return B(); }
};
void f(B);
int main() { f(A()); } // called!
Argument passing is just one context of copy initialization. Another is the "pure" form using the copy initialization syntax
B b = A(); // called!
Conversion to reference
In the conditional operator, conversion to a reference type is possible, if the type converted to is an lvalue.
struct B { };
struct A {
operator B&() { static B b; return b; }
};
int main() { B b; 0 ? b : A(); } // called!
Another conversion to reference is when you bind a reference, directly
struct B { };
struct A {
operator B&() { static B b; return b; }
};
B &b = A(); // called!
Conversion to function pointers
You may have a conversion function to a function pointer or reference, and when a call is made, then it might be used.
typedef void (*fPtr)(int);
void foo(int a);
struct test {
operator fPtr() { return foo; }
};
int main() {
test t; t(10); // called!
}
This thing can actually become quite useful sometimes.
Conversion to non class types
The implicit conversions that happen always and everywhere can use user defined conversions too. You may define a conversion function that returns a boolean value
struct test {
operator bool() { return true; }
};
int main() {
test t;
if(t) { ... }
}
(The conversion to bool in this case can be made safer by the safe-bool idiom, to forbid conversions to other integer types.) The conversions are triggered anywhere where a built-in operator expects a certain type. Conversions may get into the way, though.
struct test {
void operator[](unsigned int) { }
operator char *() { static char c; return &c; }
};
int main() {
test t; t[0]; // ambiguous
}
// (t).operator[] (unsigned int) : member
// operator[](T *, std::ptrdiff_t) : built-in
The call can be ambiguous, because for the member, the second parameter needs a conversion, and for the built-in operator, the first needs a user defined conversion. The other two parameters match perfectly respectively. The call can be non-ambiguous in some cases (ptrdiff_t needs be different from int then).
Conversion function template
Templates allow some nice things, but better be very cautious about them. The following makes a type convertible to any pointer type (member pointers aren't seen as "pointer types").
struct test {
template<typename T>
operator T*() { return 0; }
};
void *pv = test();
bool *pb = test();
|
1,307,883 | 1,307,927 | error C2664 converting from from const std::string to std::string& | I keep receiving a C2664 conversion error in visual studio
It tells me that it can't convert parameter 1 from const std::string to std::string&. I tried adding/removing the const in the stringToWstring prototype and in the function itself and the error still comes up.
wstring hexval = buff.substr(buff.find(L"hex(2):"));
wstring h;
wchar_t ch;
typedef boost::tokenizer<boost::char_separator<wchar_t> > tokenizer;
boost::char_separator<wchar_t> sep(L"//,");
tokenizer tokens(hexval, sep);
for(tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); tok_iter++)
{
ch = someFunction(*tok_iter); //error here
h += ch;
}
wstring stringToWstring(const string& s)
{
wstring temp(s.length(), L'');
copy(s.begin(), s.end(), temp.begin());
return temp;
}
wchar_t someFunction(const wstring &hex_val)
{
}
Any ideas?
EDIT:
I see that this is really confusing so I'm going to explain a bit more..
Originally, what I wanted was these lines inside the for loop
ch = someFunction(*tok_iter);
h += ch
I also expected *tok_iter to return a wstring but I was getting an error like: cannot convert parameter 1 from const std::string to const std::wstring&
Because of that, I assumed that somehow, *tok_iter is a const std::string thus, I created a stringToWstring function to do the conversion. To do this in the for loop
ch = someFunction(stringToWstring(*tok_iter));
h += ch
When I did that, I got:
Error 1 error C2664: 'std::_String_const_iterator<_Elem,_Traits,_Alloc>::_String_const_iterator(const std::_String_const_iterator<_Elem,_Traits,_Alloc> &)' : cannot convert parameter 1 from 'std::_String_const_iterator<_Elem,_Traits,_Alloc>' to 'const std::_String_const_iterator<_Elem,_Traits,_Alloc> &' c:\program files\boost\boost_1_39\boost\tokenizer.hpp 63
I hope that's clearer now.
| Looking at the edited question, your error is inside boost/tokenizer.hpp, not at the specified line.
So my guess is that your tokenizer is wrong. Looking at http://www.boost.org/doc/libs/1_34_0/libs/tokenizer/tokenizer.htm it takes three template arguments, and the third one defaults to std::string. Since you want to use it on a std::wstring, I'd say you should create your tokenizer like this instead:
tokenizer<boost::char_separator<wchar_t>, std::wstring::const_iterator, std::wstring>
In general when debugging errors in template types, be sure to look in the Output pane, at the lines following the error. Visual Studio will tell you the types used in the templates there, allowing you to distinguish the first std::_String_const_iterator<_Elem,_Traits,_Alloc> in the error message from the second const std::_String_const_iterator<_Elem,_Traits,_Alloc> & (VC++ really isn't very good at formatting this information, but it's there)
Most likely, one of them has char for _Elem and the other has wchar_t.
|
1,307,977 | 1,308,025 | Which way to go Web Side ,Mobile Development, Stand alone applications? | I am currently intern at telecominication company which is major one and also undergraduate student.I have lots of options sitting front.By know i know c,c++,c#,java languages on stand alone application side,on mobile side i trying to get into android world and also know php,mysql,asp.net and also java ee,spring on web side.But i really can not choose which side to go or focus,any suggestion from expreinced developers would be great for me.
| Just find a project that you find interesting (regardless of whether its standalone, mobile or web). And just work at it, you'll gain valuable experience not just in the specifics of whatever the project is aimed at, but also as a programmer in general, these skills will carry over into the other fields.
Really just find a project which is interesting to you, none of the types you mention are going anywhere, so it shouldn't matter which you choose.
|
1,308,013 | 1,308,062 | Audio analyzer for finding songs pitch | Is there anyway to analyze the audio pitches programmatically. For example, i know most of the players show a graph or bar & if the songs pitch is high @ time t, the bar goes up at time t .. something like this. Is there any utility/tool/API to determine songs pitch so that we interpolate that to a bar which goes up & down.
Thanks for any help
| Naive but robust: transform a modest length segment into Fourier space and find the peaks. Repeat as necessary.
Speed may be an issue, so choose the segment length as a power of 2 so that you can use the Fast Fourier Transform which is, well, fast.
Lots of related stuff on SO already. Try: https://stackoverflow.com/search?q=Fourier+transform
|
1,308,052 | 1,308,108 | Policy with catching std::bad_alloc | So I use Qt a lot with my development and love it. The usual design pattern with Qt objects is to allocate them using new.
Pretty much all of the examples (especially code generated by the Qt designer) do absolutely no checking for the std::bad_alloc exception. Since the objects allocated (usually widgets and such) are small this is hardly ever a problem. After all, if you fail to allocate something like 20 bytes, odds are there's not much you can do to remedy the problem.
Currently, I've adopted a policy of wrapping "large" (anything above a page or two in size) allocations in a try/catch. If that fails, I display a message to the user, pretty much anything smaller, I'll just let the app crash with a std::bad_alloc exception.
So, I wonder what the schools of thought on this are on this?
Is it good policy to check each and every new operation? Or only ones I expect to have the potential to fail?
Also, it is clearly a whole different story when dealing with an embedded environment where resources can be much more constrained. I am asking in the context of a desktop application, but would be interested in answers involving other scenarios as well.
| The problem is not "where to catch" but "what to do when an exception is caught".
If you want to check, instead of wrapping with try catch you'd better use
#include <new>
x = new (std::nothrow) X();
if (x == NULL) {
// allocation failed
}
My usual practice is
in a non-interactive program, catch at main level and display an adequate error message there.
in a program having a user interaction loop, catch also in the loop so that the user can close some things and try to continue.
Exceptionally, there are other places where a catch is meaningful, but it's rare.
|
1,308,472 | 1,308,694 | Visual Studio 2008 sp1 vc++ project works in 32 bit mode, but not 64 bit | I have a project that runs perfectly well under windows 7, x86 installation. On the same machine, but in a different drive, I've installed windows 7, x64, and visual studio 2008 sp1 on both.
The project compiles and runs under win32. When I try to compile the project under x64, I get nothing, and everything gets 'skipped'. Furthermore, when I try to get the properties of anything under the 64 bit version, the operation fails with an 'unspecified error'. On the 64 bit side, I can switch to the win32 build target, watch it work, and then try to switch to the x64 bit side, and then clench my teeth in frustration. If I try to do a batch build for every configuration, again, total failure unless I just do win32 projects.
I've seen this project work on someone else's machine, so I know that it works in 64 bits, but for some strange reason, this project just doesn't work for me.
I've tried to run
devenv /resetskippkgs
as per this suggestion here, but there's no love.
Any help is appreciated...
EDIT from Pavel's suggestion, I tried to run using
vcbuild /platform:x64
and I get the error:
vcbuild.exe : warning VCBLG6001: Project 'project.proj' does not support platform
'x64', or the platform support DLL for this platform is not installed.
That help? Does visual studio not automatically Do The Right thing when installed?
| The solution! Posted because I lost so much time to this, and I'd hope that someone else does not similarly lose time (otherwise, I'd just delete the question).
Apparently, the visual studio 2008 installer declined to install the x64 compiler tools by default on my machine. I don't know if that's because I'm on an AMD machine and there's some question about running on that processor, or just someone made a mistake, or what, but once I checked what had been installed by visual studio, I found the glaring red 'x' indicating that the x64 compiler was not installed. ARM, yes, x64, the processor I'm using, no.
So, adding that processor option back seems to have restored the universe to its rightful place.
|
1,308,899 | 1,308,925 | How to pointer-cast Foo** to const Foo** in C++ | I have
class Fred
{
public:
void inspect() const {};
void modify(){};
};
int main()
{
const Fred x = Fred();
Fred* p1;
const Fred** q1 = reinterpret_cast<const Fred**>(&p1);
*q1 = &x;
p1->inspect();
p1->modify();
}
How would it be possible to do the
const Fred** q1 = &p1
via pointer-casting?
(I have just been reading that this might be possible)
Thank you for your answers. The const_cast works indeed for objects
#include <iostream>
#include <stdio.h>
using namespace std;
class Fred
{
int a;
public:
Fred(){};
Fred(int a_input)
{
a = a_input;
};
void inspect() const
{
cout << "Inspect called"<< endl;
cout << "Value is ";
cout << a << endl;
};
void modify()
{
cout << "Modify called" << endl;
a++;
};
};
int main()
{
const Fred x = Fred(7);
const Fred* q1 = &x;
Fred* p1 = const_cast<Fred*>(q1);
p1->inspect();
p1->modify();
p1->inspect();
x.inspect();
*p1 = Fred(10);
p1->inspect();
}
gives
Inspect called
Value is 7
Modify called
Inspect called
Value is 8
Inspect called
Value is 8
Inspect called
Value is 10
Inspect called
Value is 10
However, for predefined types it does not work:
int main()
{
const double a1 = 1.2;
const double* b1 = &a1;
cout << "a1 is " << (*b1) << endl;
cout << "b1 is " << b1 << endl;
double* c1 = const_cast<double*>(&a1);
cout << "b1 is " << b1 << endl;
cout << "c1 is " << c1 << endl;
double* d1 = static_cast<double*>(static_cast<void*>(c1));
cout << "d1 is " << d1 << endl;
cout<< "*d1 is " << *d1 << endl;
*d1=7.3;
cout<< "*d1 is " << *d1 << endl;
cout<< "*d1 address is "<< d1 << endl;
cout << "a1 is " << a1 << endl;
cout << "a1 address is" << &a1 << endl;
cout<< "*d1 is " << *d1 << endl;
cout<< "*d1 address is "<< d1 << endl;
double f1=a1;
printf("f1 is %f \n", f1);
}
is resulting in:
a1 is 1.2
b1 is 0xffbff208
b1 is 0xffbff208
c1 is 0xffbff208
d1 is 0xffbff208
*d1 is 1.2
*d1 is 7.3
*d1 address is 0xffbff208
a1 is 1.2
a1 address is0xffbff208
*d1 is 7.3
*d1 address is 0xffbff208
f1 is 1.200000
Apparently the g++ compiler optimizes such that it replaces a1 by 1.2 whenever it finds it, so, even if its value on the stack has changed, it does not care.
(In my case I had problems with directly reading the *b1, *c1, so I had to do the double static cast - the reinterpret cast did not work).
Is it any way to really change a1, compiling "normally", therefore not compiling without the optimization (so I overtake the optimization effect)?
| You want const_cast.
|
1,309,129 | 1,309,133 | Convert a pointer to an array in C++ | The CreateFileMapping function returns a pointer to a memory mapped file, and I want to treat that memory mapping as an array.
Here's what I basically want to do:
char Array[] = (char*) CreateFileMapping(...);
Except apparently I can't simply wave my arms and declare that a pointer is now an array.
Do you guys have any idea how I can do this? I don't want to copy the the values the pointer is pointing to into the array because that will use too much memory with large files.
Thanks a bunch,
| You do not need to. You can index a pointer as if it was an array:
char* p = (char*)CreateFileMapping(...);
p[123] = 'x';
...
|
1,309,187 | 1,309,221 | Reading binary data with seekg fails | I'm trying to read binary data from a specific offset.
I write the data in the following way:
long RecordIO::writeRecord(Data *record)
{
this->openWrite();
fstream::pos_type offset = file->tellp();
file->write(reinterpret_cast<char*>(record), sizeof(Data));
return (long)offset;
}
The offset returned is stored, and retrieved later. Data is a struct with the data.
Later i try to read that same data again with the following code:
Data* RecordIO::getRecord(long offset)
{
openRead();
file->seekg((fstream::pos_type) offset);
Data data;
file->read(reinterpret_cast<char *>(&data), sizeof(Data));
return new Data(data);
}
sizeof(Data) returns 768. Some off the offsets i get back is 768 and 1536. But when I check the contents of the data, i get complete gibberish. Am i doeing something wrong?
Edit:
This is the struct:
struct Data{
long key;
char postcode[8];
char info1[251];
char info2[251];
char info3[251];
};
And this is how i fill it:
for(int i = 1; i <= numOfRecords; ++i){
newData.key = i;
newData.postcode[0] = '1' + (rand() % 8);
newData.postcode[1] = '0' + (rand() % 9);
newData.postcode[2] = '0' + (rand() % 9);
newData.postcode[3] = '0' + (rand() % 9);
newData.postcode[4] = ' ';
newData.postcode[5] = 'A' + (rand() % 25);
newData.postcode[6] = 'Z' - (rand() % 25);
newData.postcode[7] = '\0';
for(int j = 0; j < 250; ++j){
newData.info1[j] = '+';
newData.info2[j] = '*';
newData.info3[j] = '-';
}
newData.info1[250] = '\0';
newData.info2[250] = '\0';
newData.info3[250] = '\0';
int offset = file->writeRecord(&newData);
index->setOffset(i, offset);
}
Btw, the data is stored correctly, because i can retreive them one by one, sequentialy
| You do this:
file->write(reinterpret_cast<char*>(record), sizeof(Data));
Do you ever close or flush the file? The data will be buffered in memory to be written to disk later unless you force it.
|
1,309,384 | 1,309,416 | regdeletekey returning file not found | I've been playing with this and I can't understand why the RegDeleteKey function is resulting to a file not found error..
I created this test key and it exists. HKLM\Software\test
I am also the administrator of this computer. OS is Vista 32 bit.
int main()
{
HKEY hReg;
LONG oresult;
LONG dresult;
oresult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\test", 0, KEY_ALL_ACCESS, &hReg);
if(oresult == ERROR_SUCCESS)
{
cout << "Key opened successfully." << endl;
}
dresult = RegDeleteKey(hReg, L"SOFTWARE\\test");
if(dresult == ERROR_SUCCESS)
{
cout << "Key deleted succssfully." << endl;
}
else
{
if(dresult == ERROR_FILE_NOT_FOUND)
{
cout << "Delete failed. Key not found." << endl;
cout << "\n";
}
}
RegCloseKey(hReg);
return 0;
}
The output is:
key opened successfully
delete failed. key not found.
| According to the MSDN page, the second parameter is a subkey of the key in hKey:
The name of the key to be deleted. It
must be a subkey of the key that hKey
identifies, but it cannot have
subkeys. This parameter cannot be
NULL.
That means your code actually tries to delete HLKM\SOFTWARE\test\SOFTWARE\test.
You probably want to try something like:
RegDeleteKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\test");
This may come in handy.
|
1,309,432 | 1,309,968 | Selected item in my CListCtrl shows ellipsis, despite having plenty of room! | I have a CListCtrl with plenty of room for all of the items, and they all display correctly --- until selected! As soon as any entry is selected, the end of that entry is truncated and an ellipsis is added:
Click for Image
I have no idea why this is happening. You can't see it in this image, but even very short entries show this behavior, even if the entries above or below are much longer and display fully. Here's the .rc code that created the control (and dialog):
IDD_COMBOBOX_DIALOG DIALOGEX 0, 0, 320, 200
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_VISIBLE |
WS_CAPTION | WS_SYSMENU
EXSTYLE WS_EX_APPWINDOW
CAPTION "ComboBox"
FONT 8, "MS Shell Dlg", 0, 0, 0x1
BEGIN
DEFPUSHBUTTON "OK",IDOK,263,7,50,16
PUSHBUTTON "Cancel",IDCANCEL,263,25,50,16
CONTROL "",IDC_LIST1,"SysListView32",LVS_REPORT | LVS_SINGLESEL |
LVS_SORTASCENDING | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER |
WS_TABSTOP,7,78,306,85
END
and here's the code from InitDialog() that sets up and populates the CListCtrl:
myListCtrl.InsertColumn(0,_T("Allergies"));
FILE *f = fopen("c:\\allergies.txt", "r");
char sz[100];
if (f)
while (fgets(sz,100,f))
myListCtrl.InsertItem(0, sz);
if (f)
fclose(f);
myListCtrl.SetColumnWidth(0,LVSCW_AUTOSIZE);
LVFINDINFO FI;
FI.flags = LVFI_PARTIAL|LVFI_STRING;
FI.psz = _T("A");
int i = myListCtrl.FindItem(&FI);
myListCtrl.SetItemState(i, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
myListCtrl.EnsureVisible(i, FALSE);
This one is making me really crazy. Any tips would be MUCH appreciated! Thanks for having a look.
| I'd try adding
myListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT);
before the InsertColumn line and see if that helps.
|
1,309,509 | 1,309,514 | Correct way to marshal SIZE_T*? | I have the following C++ function definition, which I am trying to call through PInvoke from managed code:
bool FooBar(SIZE_T* arg1);
My managed declaration looked as follows:
[DllImport("mydll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern bool FooBar(ref uint arg1);
Some of you may notice the same bug I eventually did. This is not 64bit portable. SIZE_T is of variable size (32-64 bit) as is the pointer to it. On the managed size the pointer correctly translates to 64bit, but the uint does not, and you can end up with trash in the upper bits of arg1. This was an especially persistent error since the trash was often just zeros :(
The only solution I have gotten to work is the following managed declaration:
[DllImport("mydll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern bool FooBar(ref IntPtr arg1);
This works of course because IntPtr can vary its size correctly. In my code I just treat the IntPtr as an integer, and it works, though it looks like an ugly hack. It seems to me there should be some way to specify this properly, perhaps using UnmanagedType.SysUInt, but I have been unable to come up with any other working solution.
| Using IntPtr and/or UIntPtr is doing it properly - the types are there specifically for this purpose! I do not understand why you consider it an "ugly hack". I'm also not sure what your proposed alternative would be - any kind of attribute to allow values to be mapped to uint would be inherently wrong, because C# uint is guaranteed to be 32-bit regardless of the architecture, and so on 64-bit platform, to marshal it correctly, it would have to trim half of it, losing data, and likely rendering the result useless.
|
1,309,612 | 1,309,734 | How do I unit test a console input class? | In one of my applications I have a class which is responsible for user input. The default method of input is the console (keyboard), and I want to write some unit tests for it to make sure it is correct.
I am considering using the google-test framework for my unit testing, which makes it easy to automate all the testing. However, I am not sure how I can automate testing of the console input.
Is there any way to simulate user input on the keyboard? Or do I have to manually enter my test input? Or perhaps redirect stdin (either in code or by a pipe when running the unit test)?
EDIT: I am planning on using GNU readline for user input. At the moment I can't see any way to redirect the input stream of this library - perhaps someone else has experience with this?
| You could use expect.
|
1,309,921 | 1,309,937 | Storing a List of Objects | Let's say I have a generic Object class, and a generic List class. I want to maintain a list of these Objects. Should I store them as List<Object> or List<Object*>?
If I use List<Object> and I have a method like:
if(some_condition) {
Object obj;
myObjectList.append(obj);
}
And my list class only keeps a reference to the object, so as soon as that if statement terminates, the object is destroyed, and the object I pushed becomes invalid. So then I end up doing something like:
Object *obj = new Object;
myObjectList.append(*obj);
So that it doesn't get destroyed. But now the objects are undeletable, no? Because now they're stored safely in the List as Objects, not pointers to Objects, so I can't call delete on them... or will they automatically be destroyed when they're popped from the list?
In that case, I should probably use List<Object*> and delete them from the list when I'm done with them, no?
So confused... I'm sure I have a fundamental misunderstanding here somewhere.
| EDIT:
As mentioned in a comment boost::ptr_list is even better since it is more efficient and has the same net effect as a std::list<boost::shared_ptr<T> >.
EDIT:
You mention that you are using Qt in your comment. If you are using >= 4.5 you can use Qt's QList and QSharedPointer classes like this:
QList<QSharedPointer<Object> > object_list;
object_list.push_back(QSharedPointer<Object>(new Object));
I would recommend you use std::list<>. You also likely just want to store pointers to the objects so they aren't being copied all of the time.
So bottom line is:
Let's say you have a class named Object. You should do this:
std::list<boost::shared_ptr<Object> > object_list;
object_list.push_back(new Object);
For c++11/14, no need for boost, just use the standard smart pointers:
std::list<std::shared_ptr<Object>> object_list;
object_list.push_back(std::make_shared<Object>());
By using shared pointers, the objects will get cleaned up automatically when they are removed from the list (if there are no other shared_ptrS also pointing to it).
You could have a list<Object *>. But given your experience level, I feel that a reference counted pointer would be much easier for you to work with.
In that case, I should probably use
List and delete them from the
list when I'm done with them, no?
Yes, this is a viable option, but I highly recommend smart pointers to avoid the "...and delete them from the list..." step entirely.
NOTE:
also the example code you gave:
Object *obj = new Object;
myObjectList.append(*obj);
is probably not what you wanted, this makes a new object on the heap, they puts a copy of that in the list. If there is no delete obj after that, then you have a memory leak since raw pointers are not automatically deleted.
|
1,310,214 | 1,310,392 | Register an object creator in object factory | I have the convenient object factory template that creates objects by their type id names. The implementation is pretty obvious: ObjectFactory contains the map from std::string to object creator function. Then all objects to be created shall be registered in this factory.
I use the following macro to do that:
#define REGISTER_CLASS(className, interfaceName) \
class className; \
static RegisterClass<className, interfaceName> regInFactory##className; \
class className : public interfaceName
where RegisterClass is
template<class T, class I>
struct RegisterClass
{
RegisterClass()
{
ObjectFactory<I>::GetInstance().Register<T>();
}
};
Usage
class IFoo
{
public:
virtual Do() = 0;
virtual ~IFoo() {}
}
REGISTER_CLASS(Foo, IFoo)
{
virtual Do() { /* do something */ }
}
REGISTER_CLASS(Bar, IFoo)
{
virtual Do() { /* do something else */ }
}
Classes are defined and registered in factory simultaneously.
The problem is that regInFactory... static objects are defined in .h files, so they will be added to every translation unit. The same object creator will be registered several times, and, more important, there will be a lot of redundant objects with static storage duration.
Is there any way to do such elegant registration (not to copy/paste class and interface names), but do not spread redundant static objects around the globe?
If a good solution needs some VC++ specific extensions (not conforming to C++ standard), I will be OK with that.
| So you want to put variables definitions in header file? There is a portable way: static variables of template classes. So we get:
template <typename T, typename I>
struct AutoRegister: public I
{
// a constructor which use ourRegisterer so that it is instantiated;
// problem catched by bocco
AutoRegister() { &ourRegisterer; }
private:
static RegisterClass<T, I> ourRegisterer;
};
template <typename T, typename I>
RegisterClass<T, I> AutoRegister<T, I>::ourRegisterer;
class Foo: AutoRegister<Foo, IFoo>
{
public:
virtual void Do();
};
Note that I've kept the inheritance of IFoo non virtual. If there is any risk of inheriting from that class multiple times, it should be virtual.
|
1,310,272 | 1,322,478 | Difference between use C# and C or C++ on windows mobile | I am new to windows mobile development. I have certain doubts related to windows mobile development which are as follows.
1) What is the major difference between C# and C (C++) as far as selecting language for development. ( not syntactically ) .
2) Which language should i select for development and Why ??
3) If i go C# as a mobile development then can i have access to all APIs for C# on
desktop .
| 1) Applications written in native code will run faster. Furthermore, memory footprint is smaller in native applications.
2) It depends on application you are writing. If it does not demand top performance and if it does not require a lot of native functionality, then the code should be managed. If you need a lot of flexibility, go for native.
3) No. .Net Compact Framework has a subset of desktop APIs.
|
1,310,338 | 1,311,700 | Does any C++ Component Framework beyond Corba Components exist? | I'm looking for a C++ Component Framework like EJB3 (sure, it's Java only) or Corba Components. But I'm not looking for Corba Components.
My requirements are
portable (linux, unix, optional Windows)
C++ interfaces (so, it's not a requirement for the framework itself to be written in C++)
optinal well documented or good examples given
edit:
remote objects (remote procedure call) shall be supported. [XPCOM does not support remote objects]
Thanks in advance.
| I'm aware of a few things. I'm only remembering of (I don't have access to my bookmarks file)
ICE
Facebook's Thrift
I know there are other component oriented frameworks in C++.
|
1,310,344 | 1,310,405 | Why use !! when converting int to bool? | What can be a reason for converting an integer to a boolean in this way?
bool booleanValue = !!integerValue;
instead of just
bool booleanValue = integerValue;
All I know is that in VC++7 the latter will cause C4800 warning and the former will not. Is there any other difference between the two?
| The problems with the "!!" idiom are that it's terse, hard to see, easy to mistake for a typo, easy to drop one of the "!'s", and so forth. I put it in the "look how cute we can be with C/C++" category.
Just write bool isNonZero = (integerValue != 0); ... be clear.
|
1,310,473 | 1,312,807 | Regex matching spaces, but not in "strings" | I am looking for a regular exression matching spaces only if thos spaces are not enclosed in double quotes ("). For example, in
Mary had "a little lamb"
it should match the first an the second space, but not the others.
I want to split the string only at the spaces which are not in the double quotes, and not at the quotes.
I am using C++ with the Qt toolkit and wanted to use QString::split(QRegExp). QString is very similar to std::string and QRegExp are basically POSIX regex encapsulated in a class. If there exist such a regex, the split would be trivial.
Examples:
Mary had "a little lamb" => Mary,had,"a little lamb"
1" 2 "3 => 1" 2 "3 (no splitting at ")
abc def="g h i" "j k" = 12 => abc,def="g h i","j k",=,12
Sorry for the edits, I was very imprecise when I asked the question first. Hope it is somewhat more clear now.
| (I know you just posted almost exactly the same answer yourself, but I can't bear to just throw all this away. :-/)
If it's possible to solve your problem with a regex split operation, the regex will have to match even numbers of quotation marks, as MSalters said. However, a split regex should match only the spaces you're splitting on, so the rest of the work has to be done in a lookahead. Here's what I would use:
" +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"
If the text is well formed, a lookahead for an even number of quotes is sufficient to determine that the just-matched space is not inside a quoted sequence. That is, lookbehinds aren't necessary, which is good because QRegExp doesn't seem to support them. Escaped quotes can be accommodated too, but the regex becomes quite a bit larger and uglier. But if you can't be sure the text is well formed, it's extremely unlikely you'll be able to solve your problem with split().
By the way, QRegExp does not implement POSIX regular expressions--if it did, it wouldn't support lookaheads OR lookbehinds. Instead, it falls into the loosely-defined category of Perl-compatible regex flavors.
|
1,310,643 | 1,310,774 | const reference binding to an rvalue | Working on this question, I found an inconsistent behavior.
Why reference binding behave different in a constructor from a common function?
struct A {
};
struct B : public A {
B(){}
private:
B(const B&);
};
void f( const B& b ) {}
int main() {
A a( B() ); // works
A const & a2 = B(); // C++0x: works, C++03: fails
f( B() ); // C++0x: works, C++03: fails
}
I have tested it for C++03 with g++-4.1 and Comeau 4.2.45.2 in strict C++03 mode and with C++0x extensions disabled. I got same results.
For C++0x was tested with g++-4.4 and Comeau 4.3.9 in relaxed mode and with C++0x extensions enabled. I got same results.
| A a(B());
is the declaration of a function named a returning an A and taking a pointer to a function without argument returning a B. See
here.
Add parenthesis and you'll get the error you expect:
A a((B()));
|
1,310,790 | 1,310,911 | Bad Re-throw compiles but crash at runtime | Following code will compile but crash at run time:
int main() {
try {
throw;
}
catch(...){
cout<<"In catch";
}
return 0;
}
Result: “Unhandled exception at 0x7c812a5b in hello.exe: Microsoft C++ exception: [rethrow] @ 0x00000000”
Why compiler allows the code to compile? it looks not so difficult job for compiler to check if this code is part of catch block or not.
| From C++ Standard (15.1.8)
If no exception is presently being handled, executing a throw-expression with no operand calls std::terminate()
As standard allows it and gives clear semantics, a compiler can only conform to it.
|
1,310,853 | 1,310,905 | Uses of std::basic_string | The basic_string class was apparently designed as a general purpose container, as I cannot find any text-specific function in its specification except for the c_str() function. Just out of curiosity, have you ever used the std::basic_string container class for anything else than storing human-readable character data?
The reason I ask this is because one often has to choose between making something general or specific. The designers chose to make the std::basic_string class general, but I doubt it is ever used that way.
| It was designed as a string class (hence, for example, length() and all those dozens of find functions), but after the introduction of the STL into the std lib it was outfitted to be an STL container, too (hence size() and the iterators, with <algorithm> making all the find functions redundant).
It's main purpose is to store characters, though. Using anything than PODs isn't guaranteed to work (and doesn't work, for example, when using Dinkumware's std lib). Also, the necessary std::char_traits isn't required to be available for anything else than char and wchar_t (although many implementations come with a reasonable implementation of the base template).
In the original standard, the class wasn't required to store its data in a contiguous piece of memory, but this has changed with C++03.
In short, it's mostly useful as a container of characters (a.k.a. "string"), where "character" has a fairly wide definition.
The "wildest" I have used it for is for storing differently encoded strings by using different character types. That way, strings of different encodings are incompatible even if they use the same character size (ASCII and UTF-8) and, e.g., assignment causes compile-time errors.
|
1,310,922 | 1,310,943 | Accessing private class in operator<< in namespace | I have a class CFoo with a private inner class CBar. I want to implement a stream ouput operator for CFoo, which in turn uses a stream output for CBar in it's implementation. I can get this working when CFoo is in the common namespace, but when i place it in a new namespace (namespace foobar), the operator can no longer access the private inner class. I suspect this has something to do with the full signature of the operator, but I can't figure out the correct way to specify the friend declaration and the actual operator declaration so the implementation compiles. Can anyone suggest what I might be missing?
Note that it will compile if the stream implementation is done inline in the header, but I hate to expose implementation like this unnecessarily!
in foobar.h (just comment out the usefoobarnamespace to test the non-namespaced version):
#define usefoobarnamespace
#ifdef usefoobarnamespace
namespace foobar
{
#endif // usefoobarnamespace
class CFoo
{
public:
CFoo() {}
~CFoo();
void AddBar();
private:
class CBar
{
public:
CBar() {m_iVal = ++s_iVal;}
int m_iVal;
static int s_iVal;
};
std::vector<CBar*> m_aBars;
friend std::ostream& operator<<(std::ostream& rcStream, CFoo& rcFoo);
friend std::ostream& operator<<(std::ostream& rcStream, CFoo::CBar& rcBar);
};
std::ostream& operator<<(std::ostream& rcStream, CFoo& rcFoo);
std::ostream& operator<<(std::ostream& rcStream, CFoo::CBar& rcBar);
#ifdef usefoobarnamespace
}
#endif // usefoobarnamespace
and in foobar.cpp:
#ifdef usefoobarnamespace
using namespace foobar;
#endif // usefoobarnamespace
int CFoo::CBar::s_iVal = 0;
CFoo::~CFoo()
{
std::vector<CBar*>::iterator barIter;
for (barIter = m_aBars.begin(); barIter != m_aBars.end(); ++barIter)
{
delete (*barIter);
}
}
void CFoo::AddBar()
{
m_aBars.push_back(new CBar());
}
std::ostream& operator<<( std::ostream& rcStream, CFoo& rcFoo )
{
rcStream<<"CFoo(";
std::vector<CFoo::CBar*>::iterator barIter;
for (barIter = rcFoo.m_aBars.begin(); barIter != rcFoo.m_aBars.end(); ++barIter)
{
rcStream<<(*barIter);
}
return rcStream<<")";
}
std::ostream& operator<<( std::ostream& rcStream, CFoo::CBar& rcBar )
{
return rcStream<<"CBar("<<rcBar.m_iVal<<")";
}
| Simply put the code in the .cpp file into the namespace:
namespace foobar {
// your existing code
}
|
1,311,166 | 1,314,452 | How to pinpoint where a long function returns | Suppose there is a function with 1000 code of line named LongFunction, and we used it:
bool bSuccess = LongFunction();
assert(bSuccess);
Here I got an assert when debugging, and I know there is something wrong with LongFunction, so I need to find where the function meet problems and returns:
I could probably debug it step by step, it works but is time-consuming, we don't what to do it this way.
I could search the keyword "return" (or even more refined search use RegExp), and set breakpoint at those returns, it should be faster, but it is still tedious manual work which can't be automated.
#define return TRACE(LINE); return
It works but have following problems:
It will print too much redundant information as return is frequently used.(Or we could use some EnvVar to switch it on or off)
Does't work for following case: if(bOK) return true;
Do you have any other creative ideas on how to pinpoint the problem?
Edit:
Here are some details to let us focus on the problem.
It is about C++, and not platform specfic.
We don't want to refactoring the functions(Yea, I know we should), we even don't want to change any code - at this point we just want to provide some facility to make our application debugging easier. I also believe this should be a common requirement, don't you ever run into this?
The LongFunction() have multiple exit point, and the return type is not necessay bool(HRESULT, user defined errorcode...)
Edit: A summary of current discussions:
We have some controversies:
You should refactor the function.
Yea, everyone know that we should, but that is not the point.If I had make the call to refactor the function, I won't be here to ask the question.
Find where the LongFunction() returns failure doesn't help.
It is always the first thing I do to locate where the error occurs to know what happened, I am curious why this doesn't help, what did you do in this situation? (Assume I am already familiar with how the function works)
And we have 2 reasonable solutions:
ReturnMarker from Crashworks, a stack object in the function will destruct when function returns, set the breakpoint at the destructor will show you where it returns in debuger
CMyBool(x) from Binary & Sadsido, change the return type of LongFunction to CMyBool which can contruct from a bool, return from LongFunction will contruct that object, so just set a breakpoint at the constructor will work.
| Obviously you ought to refactor this function, but in C++ you can use this simple expedient to deal with this in five minutes:
class ReturnMarker
{
public:
ReturnMarker() {};
~ReturnMarker()
{
dummy += 1; //<-- put your breakpoint here
}
static int dummy;
}
int ReturnMarker::dummy = 0;
and then instance a single ReturnMarker at the top of your function. When it returns, that instance will go out of scope, and you'll hit the destructor.
void LongFunction()
{
ReturnMarker foo;
// ...
}
|
1,311,242 | 17,080,640 | Precise floating-point<->string conversion | I am looking for a library function to convert floating point numbers to strings, and back again, in C++. The properties I want are that str2num(num2str(x)) == x and that num2str(str2num(x)) == x (as far as possible). The general property is that num2str should represent the simplest rational number that when rounded to the nearest representable floating pointer number gives you back the original number.
So far I've tried boost::lexical_cast:
double d = 1.34;
string_t s = boost::lexical_cast<string_t>(d);
printf("%s\n", s.c_str());
// outputs 1.3400000000000001
And I've tried std::ostringstream, which seems to work for most values if I do stream.precision(16). However, at precision 15 or 17 it either truncates or gives ugly output for things like 1.34. I don't think that precision 16 is guaranteed to have any particular properties I require, and suspect it breaks down for many numbers.
Is there a C++ library that has such a conversion? Or is such a conversion function already buried somewhere in the standard libraries/boost.
The reason for wanting these functions is to save floating point values to CSV files, and then read them correctly. In addition, I'd like the CSV files to contain simple numbers as far as possible so they can be consumed by humans.
I know that the Haskell read/show functions already have the properties I am after, as do the BSD C libraries. The standard references for string<->double conversions is a pair of papers from PLDI 1990:
How to read floating point numbers accurately, Will Klinger
How to print floating point numbers accurately, Guy Steele et al
Any C++ library/function based on these would be suitable.
EDIT: I am fully aware that floating point numbers are inexact representations of decimal numbers, and that 1.34==1.3400000000000001. However, as the papers referenced above point out, that's no excuse for choosing to display as "1.3400000000000001"
EDIT2: This paper explains exactly what I'm looking for: http://drj11.wordpress.com/2007/07/03/python-poor-printing-of-floating-point/
| I think this does what you want, in combination with the standard library's strtod():
#include <stdio.h>
#include <stdlib.h>
int dtostr(char* buf, size_t size, double n)
{
int prec = 15;
while(1)
{
int ret = snprintf(buf, size, "%.*g", prec, n);
if(prec++ == 18 || n == strtod(buf, 0)) return ret;
}
}
A simple demo, which doesn't bother to check input words for trailing garbage:
int main(int argc, char** argv)
{
int i;
for(i = 1; i < argc; i++)
{
char buf[32];
dtostr(buf, sizeof(buf), strtod(argv[i], 0));
printf("%s\n", buf);
}
return 0;
}
Some example inputs:
% ./a.out 0.1 1234567890.1234567890 17 1e99 1.34 0.000001 0 -0 +INF NaN
0.1
1234567890.1234567
17
1e+99
1.34
1e-06
0
-0
inf
nan
I imagine your C library needs to conform to some sufficiently recent version of the standard in order to guarantee correct rounding.
I'm not sure I chose the ideal bounds on prec, but I imagine they must be close. Maybe they could be tighter? Similarly I think 32 characters for buf are always sufficient but never necessary. Obviously this all assumes 64-bit IEEE doubles. Might be worth checking that assumption with some kind of clever preprocessor directive -- sizeof(double) == 8 would be a good start.
The exponent is a bit messy, but it wouldn't be difficult to fix after breaking out of the loop but before returning, perhaps using memmove() or suchlike to shift things leftwards. I'm pretty sure there's guaranteed to be at most one + and at most one leading 0, and I don't think they can even both occur at the same time for prec >= 10 or so.
Likewise if you'd rather ignore signed zero, as Javascript does, you can easily handle it up front, e.g.:
if(n == 0) return snprintf(buf, size, "0");
I'd be curious to see a detailed comparison with that 3000-line monstrosity you dug up in the Python codebase. Presumably the short version is slower, or less correct, or something? It would be disappointing if it were neither....
|
1,311,321 | 1,311,831 | Private members vs temporary variables in C++ | Suppose you have the following code:
int main(int argc, char** argv) {
Foo f;
while (true) {
f.doSomething();
}
}
Which of the following two implementations of Foo are preferred?
Solution 1:
class Foo {
private:
void doIt(Bar& data);
public:
void doSomething() {
Bar _data;
doIt(_data);
}
};
Solution 2:
class Foo {
private:
Bar _data;
void doIt(Bar& data);
public:
void doSomething() {
doIt(_data);
}
};
In plain english: if I have a class with a method that gets called very often, and this method defines a considerable amount of temporary data (either one object of a complex class, or a large number of simple objects), should I declare this data as private members of the class?
On the one hand, this would save the time spent on constructing, initializing and destructing the data on each call, improving performance. On the other hand, it tramples on the "private member = state of the object" principle, and may make the code harder to understand.
Does the answer depend on the size/complexity of class Bar? What about the number of objects declared? At what point would the benefits outweigh the drawbacks?
| From a design point of view, using temporaries is cleaner if that data is not part of the object state, and should be preferred.
Never make design choices on performance grounds before actually profiling the application. You might just discover that you end up with a worse design that is actually not any better than the original design performance wise.
To all the answers that recommend to reuse objects if construction/destruction cost is high, it is important to remark that if you must reuse the object from one invocation to another, in many cases the object must be reset to a valid state between method invocations and that also has a cost. In many such cases, the cost of resetting can be comparable to construction/destruction.
If you do not reset the object state between invocations, the two solutions could yield different results, as in the first call, the argument would be initialized and the state would probably be different between method invocations.
Thread safety has a great impact on this decision also. Auto variables inside a function are created in the stack of each of the threads, and as such are inherently thread safe. Any optimization that pushes those local variable so that it can be reused between different invocations will complicate thread safety and could even end up with a performance penalty due to contention that can worsen the overall performance.
Finally, if you want to keep the object between method invocations I would still not make it a private member of the class (it is not part of the class) but rather an implementation detail (static function variable, global in an unnamed namespace in the compilation unit where doOperation is implemented, member of a PIMPL...[the first 2 sharing the data for all objects, while the latter only for all invocations in the same object]) users of your class do not care about how you solve things (as long as you do it safely, and document that the class is not thread safe).
// foo.h
class Foo {
public:
void doOperation();
private:
void doIt( Bar& data );
};
// foo.cpp
void Foo::doOperation()
{
static Bar reusable_data;
doIt( reusable_data );
}
// else foo.cpp
namespace {
Bar reusable_global_data;
}
void Foo::doOperation()
{
doIt( reusable_global_data );
}
// pimpl foo.h
class Foo {
public:
void doOperation();
private:
class impl_t;
boost::scoped_ptr<impl_t> impl;
};
// foo.cpp
class Foo::impl_t {
private:
Bar reusable;
public:
void doIt(); // uses this->reusable instead of argument
};
void Foo::doOperation() {
impl->doIt();
}
|
1,311,953 | 1,311,971 | Starting a new Windows app: Should I use _TCHAR or wchar_t for text? | I'm coding up a new (personal hobby) app for Windows in c++.
In previous low-level Windows stuff I've used _TCHAR (or just TCHAR) arrays/basic_strings for string manipulation.
Is there any advantage to using _TCHAR over straight up Unicode with wchar_t, if I don't care about Windows platforms pre Win2k?
edit: after submitting I discovered a similar question here from Oct 2008:
Is TCHAR still relevant?
Seems to be more consensus now about ditching TCHAR
| No there is not. Just go with wchar_t.
TCHAR is only useful if you want to be able to use a conditional compilation switch to convert your program to operate in ASCII mode. Since Win2K and up are unicode platforms this switch does not provide any value. You'd instead be implying to other developers in your project that ASCII was a valid target when in fact it's not.
|
1,312,056 | 1,314,436 | Can I call a Win32 API from the Visual Studio Immediate Window? | I'm debugging a C++ Win32 application and I'd like to call an arbitrary Win32 API from the context of that process, as though the program had run this line of code:
DestroyWindow(0x00021c0e);
But entering that into the Immediate Window gives:
CXX0017: Error: symbol "DestroyWindow" not found
Edit: Using the full name of the function, {,,user32.dll}_NtUserDestroyWindow@4, I can get the Immediate Window to understand which function I mean and display the function's address:
{,,user32.dll}_NtUserDestroyWindow@4
0x76600454 _NtUserDestroyWindow@4
but when I try to call it, this happens:
{,,user32.dll}_NtUserDestroyWindow@4(0x00021c0e);
CXX0004: Error: syntax error
Is it even possible to call a C function from the Immediate Window like this, or am I barking up the wrong tree?
| Once you have the function address (as you've done in the updated question), you can try casting it to a function pointer and calling it:
(*(BOOL (*)(HWND))0x76600454)((HWND)0x00021c0e)
The first part of that casts the address to BOOL (*)(HWND), which is a pointer to a function taking an HWND parameter and returning BOOL. Then, the function pointer is dereferenced and called. Make sure to get the parameters correct, otherwise bad things will happen. On 64-bit systems, and HWND might be 64 bits, so you might not be able to get away with passing the parameter as an int.
Edit: See the comments for the full story.
|
1,312,132 | 1,312,152 | Boolean in ifdef: is "#ifdef A && B" the same as "#if defined(A) && defined(B)"? | In C++, is this:
#ifdef A && B
the same as:
#if defined(A) && defined(B)
?
I was thinking it wasn't, but I haven't been able to find a difference with my compiler (VS2005).
| They are not the same. The first one doesn't work (I tested in gcc 4.4.1). Error message was:
test.cc:1:15: warning: extra tokens at
end of #ifdef directive
If you want to check if multiple things are defined, use the second one.
|
1,312,241 | 1,312,267 | using a static const int in a struct/class | struct A {
static const int a = 5;
struct B {
static const int b = a;
};
};
int main() {
return A::B::b;
}
The above code compiles. However if you go by Effective C++ book by Scott Myers(pg 14);
We need a definition for a in addition to the declaration.
Can anyone explain why this is an exception?
| C++ compilers allow static const integers (and integers only) to have their value specified at the location they are declared. This is because the variable is essentially not needed, and lives only in the code (it is typically compiled out).
Other variable types (such as static const char*) cannot typically be defined where they are declared, and require a separate definition.
For a tiny bit more explanation, realize that accessing a global variable typically requires making an address reference in the lower-level code. But your global variable is an integer whose size is this typically around the size of an address, and the compiler realizes it will never change, so why bother adding the pointer abstraction?
|
1,312,439 | 1,313,543 | What is the major authority (ies) for big C++ projects? | For many years, I have been re-reading John Lakos's classic Large-Scale C++ Software Design. Not only it was the first guidebook of this kind, but it also revolutionized how to develop a project in C++, in an efficient fashion to this day!
Do you feel his ideas are outdated now? Some C++ techniques in the book are in fact old (don't forget that book has been written before the latest standard was published) .
What's a good authority to guide building of a big system in C++ nowadays.
Don't get me wrong, I am not giving up Lakos at all. It will always be referenced for me, and occupy a prime location on the bookshelf.
Thanks
| Interestingly, his next book, Scalable C++: Component-Based Development, is anticipated in 2006.
I don't think it has ever came to fruition... one day it may!
Also, Agile Principles and patterns are widespread and effective software developing paradigm. I am shifting my gears in that directions.
Check out this book: Agile Software Development, Principles, Patterns, and Practices
|
1,312,540 | 1,312,628 | How to implement smart pointer which can be instantiated with void? | Some smart pointer templates, such as boost::shared_ptr, may be instantiated with void to hold an arbitrary object:
http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/sp_techniques.html#pvoid
Below is a minimal scoped_ptr implementation. When instantiated with void, the compiler complains about an illegal "reference to void" being formed in the dereference operator. It seems the "substitution failure is not an error" (SFINAE) rule does not cover this situation.
How then is it possible to implement a scoped_ptr? In particular, is there an alternative to writing a template specialization? This would cause large code reduplication with a realistic smart pointer implementation.
#include <cstdlib>
template<typename T>
void destroy(T* ptr)
{
delete ptr;
}
class scoped_ptr_impl_base
{
public:
virtual ~scoped_ptr_impl_base() { }
};
template<typename T, typename F>
class scoped_ptr_impl : public scoped_ptr_impl_base
{
public:
scoped_ptr_impl(T* ptr, F dtor)
: m_ptr(ptr), m_dtor(dtor)
{
}
virtual ~scoped_ptr_impl()
{
m_dtor(m_ptr);
}
private:
T* m_ptr;
F m_dtor;
};
template<typename T>
class scoped_ptr
{
public:
explicit scoped_ptr(T* ptr = 0)
: m_ptr(ptr),
m_impl(new scoped_ptr_impl<T, void (*)(T*)>(&destroy<T>))
{
}
template<typename F>
scoped_ptr(T* ptr, F dtor)
: m_ptr(ptr),
m_impl(new scoped_ptr_impl<T, F>(ptr, dtor))
{
}
~scoped_ptr()
{
delete m_impl;
}
T& operator*()
{
return *m_ptr;
}
T* operator->()
{
return m_ptr;
}
private:
T* m_ptr;
scoped_ptr_impl_base* m_impl;
scoped_ptr(const scoped_ptr&);
scoped_ptr& operator=(const scoped_ptr&);
};
int main()
{
scoped_ptr<void> p(std::malloc(1), std::free);
// scoped_ptr.cpp: In instantiation of `scoped_ptr<void>':
// scoped_ptr.cpp:76: instantiated from here
// scoped_ptr.cpp:56: error: forming reference to void
// (g++ 4.3.3)
return 0;
}
| You could use a type trait for the reference type:
template<typename T>
struct type_trait
{
typedef T& reference;
};
template<>
struct type_trait<void>
{
typedef void reference;
};
then in your scoped_ptr_impl :
typename type_trait<T>::reference operator*()
{
return *m_ptr;
}
Not sure if void is the right type in the specialisation though . What type do you want it to return?
|
1,312,672 | 1,314,991 | Simple client/server, TCP/IP encrypting the message stream, SSL (C++) | Basically my question is the exact same one as this:
Simple client/server, TCP/IP encrypting the message stream, SSL
The difference is that I need this for pure C++, not .NET. I cannot use 3rd party libraries, so unless it's a Windows system component (like the above) I need something with source so I can get the generel idea and build it myself.
Thanks :)
Quoting the other question for reference:
"Writing a little TCP/IP client server
app. Basically it creates a server,
and then you can create several
different clients and set up a bit of
a chat session. What I am wondering is
there is any way to incorporate, using
standard .net libraries some form of
encryption?
m_mainSocket = new
Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Is there any way of speficying tcp
using rsa?
Or would you (me that is) have to
write some custom libaries to do key
exchange and then encrypt the
subsequent chat messages? I have done
that before for uni but that was in
java but I know it would'nt be hard to
convert them. Just trying not to have
to reinvent the wheel...
Or what about utilising a ssl?
Thanks, Ron."
| Writing your own encryption code is "not recommended". It's easy enough to make a simple mistake when using one of these libraries, let alone when you try to write one yourself.
What you really want to use is OpenSSL with Boost.ASIO on top of it. If you can't do that then your next best alternative is to use the Internet Explorer COM object. This isn't quite as flexible, but might work out fine depending on what your exact needs are. You can also explore the Win32 API. Last I looked there weren't enough crypto APIs widely available to do this. The final way of dealing with this is to wrap the .NET APIs so that you can make use of them from native C++.
Only if none of that works out for you should you even consider writing this yourself. You will make mistakes and your application will be less secure as a result. So, before you start trying to write your own crypto code you could also try to look at tunnelling SOCKS over SSH and use somebody else's SSH implementation. The next thing I would look at is to buy in the code rather than write it yourself. The code won't be as good as open source offerings as it will be less used so will have more security problems, but it will still be better than anything you would write on your first outing doing this.
Only if you've exhausted all of these options should you think about writing this yourself. Once you think about it you should try all of the other options again to make sure that you didn't miss getting one of them to work for you the first time around.
If you do still write your own implementation then throw it away and use one of the other options before putting it into production use as there will be mistakes that compromise the security to the extent where you probably may as well not have bothered.
Sorry to sound down on all of this, but getting these things right is really hard and not something you can do by just taking a quick look at somebody else's implementation.
|
1,312,922 | 1,312,957 | Detect if stdin is a terminal or pipe? | When I execute "python" from the terminal with no arguments it brings up the Python interactive shell.
When I execute "cat | python" from the terminal it doesn't launch the interactive mode. Somehow, without getting any input, it has detected that it is connected to a pipe.
How would I do a similar detection in C or C++ or Qt?
| Use isatty:
#include <stdio.h>
#include <io.h>
...
if (isatty(fileno(stdin)))
printf( "stdin is a terminal\n" );
else
printf( "stdin is a file or a pipe\n");
(On windows they're prefixed with underscores: _isatty, _fileno)
|
1,313,001 | 1,317,867 | Intel C++ Compiler for Windows CE | Two years ago I used eMbedded Visual Studio for Windows CE based application development. I had about 40% app performance acceleration with Intel C++ Compiler(v1.2 or v2.0) in comparison with default MS compiler (floating point issues, ARM). It was looked really helpful for me.
I do remember that downloaded it from official Intel site. At that time I saw a lot of information there about this compiler and many press releases.
It's appear I need to solve performance problem again with my new Windows CE (5.0) platform. I've tried to find actual compiler for Windows CE at Intel web-site (hoped to VS2008 integration). But I cannot find anything... even version I used before! I was surprised, it looks like this product no longer exist... (just 2005 year dated comments at forum).
Can somebody explain what happens with this product?
P.S.: Here is a link (Intel web-site) where Intel C++ Compiler for Windows CE mentioned! But "Page Not Found"
http://www.intel.com/cd/software/products/asmo-na/eng/compilers/219762.htm
| Well, this is not too surprising. Since Intel intends to get to the embedded market with Atom they sold the XSCALE department to Marvell along with all other related products. I just checkd Marvell's extranet and they have a C++ compiler for Windows CE V2.2, dedicated for the XSCALE technology. You need to register to the extranet though, and Marvell decides wether to give you access permissions.
PS
I referred to XSCALE and not x86 because the Windows CE compiler specified in the web page you gave the link to refres to that technology. I don't know if Intel ever had a C++ compiler for x86 under Windows CE.
|
1,313,005 | 1,313,023 | How to get a Windows Service custom Status? [C++/C#] | I have a created a C# windows service (Serv.exe) which is responsible for performing various tasks at the request of a running application (A.exe), some of these can take long periods of time and I need a way to know the status of my requested operation (running on the service) from the calling application (A.exe).
Currently the way I have started to implement this is by using the ControlService(handle, command, status) to send a custom command to the Service to perform the task being requested, I am also using QueryServiceStatus(handle, status) to get the status of the service from the SCM - so the basic plumbing is there and working.
Now the problem I have is, after sending my ControlService Command (which works fine) the calling application (A.exe) keeps running and, at a certain point, it needs to know if the task it requested of the service is finished or not - therefore I am looking for a way to Query the Service to report a custom status, not the standard running, stopped, pending, paused state of the actual service but the status of the request I made using the ControlService() request.
Is this at all possible?
Any help or hints would be immensily appreciated.
Thanks,
| In the past, when I've had to handle more complex communication, I usually switch from QueryServiceStatus to having the service actually provide a means of communication via IPC.
Sockets and Pipes both work very well for this. The client and service can have pretty much an unlimited freedom in terms of what is communicated this way.
|
1,313,063 | 1,313,162 | request for member `...' is ambiguous in g++ | I'm getting the following compile error in one of my classes, using gcc 3.4.5 (mingw):
src/ModelTester/CModelTesterGui.cpp:1308: error: request for member `addListener' is ambiguous
include/utility/ISource.h:26: error: candidates are: void utility::ISource<T>::addListener(utility::IListener<T>*) [with T = const SConsolePacket&]
include/utility/ISource.h:26: error: void utility::ISource<T>::addListener(utility::IListener<T>*) [with T = const SControlPacket&]
Hopefully you can see that ISource<T> is a template interface that just indicates that the object can be an informer for an object that is of some matching type IListener<T>. So the thing that has me irked is this idea that for some reason functions are ambiguous when, as far as I can tell, they are not. The addListener() method is overloaded for different input types IListener<const SConsolePacket&> and IListener<const SControlPacket&>. The usage is:
m_controller->addListener( m_model );
Where m_model is a pointer to an IRigidBody object, and IRigidBody inherits only from IListener< const SControlPacket& > and definately not from IListener< const SConsolePacket& >
As a sanity check, I used doxygen to generate the class hierarchy diagram and doxygen agrees with me that IRigidBody does not derive from IListener< const SConsolePacket& >
Evidently my understanding of inheritence in c++ is not exactly correct. I'm under the impression that IListener<const SControlPacket&> and IListener<const SConsolePacket&> are two different types, and that the function declarations
addListener(IListener<const SConsolePacket&>* listener)
and
addListener(IListener<const SControlPacket&>* listener)
declare two separate functions that do two separate things depending on the (distinct) different type of the parameter that is input. Furthermore, I'm under the impression that a pointer to an IRigidBody is also a pointer to an IListener<const SControlPacket&> and that by calling addListener( m_model ) the compiler should understand that I'm calling the second of the above two functions.
I even tried casting m_model like this:
m_controller->addListener(
static_cast<IListener<const SControlPacket&>*>(m_model) );
but still get that error. I cannot for the life of me see how these functions are ambiguous. Can anyone shed light on this issue?
P.S. I know how to force the function to be un-ambiguous by doing this:
m_controller->ISource<const SControlPacket&>::addListener( m_model );
I just happen to think that is terribly unreadible and I would prefer not to have to do that.
Edit... just kidding. That apparently doesn't fix the problem as it leads to a linker error:
CModelTesterGui.cpp:1312: undefined reference to `utility::ISource<aerobat::SControlPacket const&>::addListener(utility::IListener<SControlPacket const&>*)'
| Looks like your situation is like this:
struct A {
void f();
};
struct B {
void f(int);
};
struct C : A, B { };
int main() {
C c;
c.B::f(1); // not ambiguous
c.f(1); // ambiguous
}
The second call to f is ambiguous, because in looking up the name, it finds functions in two different base class scopes. In this situation, the lookup is ambiguous - they don't overload each other. A fix would be to use a using declaration for each member name. Lookup will find names in the scope of C and don't lookup further:
struct C : A, B { using A::f; using B::f; };
Now, the call would find two functions, do overload resolution, and find that the one taking int will fit. Carried over to your code, it would mean that you have to do something like the following
struct controller : ISource<const SConsolePacket&>, ISource<const SControlPacket&> {
using ISource<const SConsolePacket&>::addListener;
using ISource<const SControlPacket&>::addListener;
};
Now, the two names are in the same scope, and now they can overload each other. Lookup will now stop at the controller class, not diving further into the two base-class branches.
|
1,313,073 | 1,313,284 | boost:thread crashes microsoft C++ compiler | Brief version of my question:
This code crashes the compiler.
pThread[0] = new boost::thread(
boost::bind(
&cGridAnimator::DoJob, // member function
this ), // instance of class
0 ); // job number
The compiler crashes when attempting to compile this code. ( It is not my program that crashe when I run this code! )
What needs to be fixed?
Long version of question
I am splitting up the work on a large 3D grid into 8 seperate jobs to be run in seperate threads, so as to take advantage of an 8 core machine.
This works perfectly:
JOB_LOOP {
pThread[kjob] = new boost::thread( ::DoJob, kjob );
}
The global free function DoJob reads the data from a global instance of cGridAnimator, according to the job number.
However, I do not like all these globals floating around, and I do not like having to use so many accessor methods to get at the necessary data. It would be much tidier to use a method of cGridAnimator.
Hence the code at the top of this question.
However, when I compile it on MSVC++ 2008 the compiler issues the following complaints and then crashes.
1>Compiling...
1>mfm1.cpp
1>C:\Program Files\boost\boost_1_38_0\boost/bind.hpp(1643) : warning C4180: qualifier applied to function type has no meaning; ignored
1> C:\Program Files\boost\boost_1_38_0\boost/bind.hpp(1677) : see reference to class template instantiation 'boost::_bi::add_cref<Pm,I>' being compiled
1> with
1> [
1> Pm=void (__thiscall cGridAnimator::* )(int),
1> I=1
1> ]
1> .\mfm1.cpp(158) : see reference to class template instantiation 'boost::_bi::dm_result<Pm,A1>' being compiled
1> with
1> [
1> Pm=void (__thiscall cGridAnimator::* )(int),
1> A1=cGridAnimator *
1> ]
1>C:\Program Files\boost\boost_1_38_0\boost/mem_fn.hpp(318) : warning C4180: qualifier applied to function type has no meaning; ignored
1> C:\Program Files\boost\boost_1_38_0\boost/bind/bind_template.hpp(344) : see reference to class template instantiation 'boost::_mfi::dm<R,T>' being compiled
1> with
1> [
1> R=void (int),
1> T=cGridAnimator
1> ]
1>Project : error PRJ0002 : Error result 1 returned from 'C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.exe'.
| Change the code into:
pThread[0] = new boost::thread(boost::bind(&cGridAnimator::DoJob, this, 0 ));
This code gives a void (void) function to the thread instead of a void (int) function and an extra argument.
|
1,313,157 | 1,313,188 | Multiplying and adding images with CImg In C++ | I am trying to find C in the following function in CImg
C=B*L+(1-B)S
Where C, L and S are all RGB images of the same size (and B is a single channel grayscale matte)
I cannot figure out how to loop over the pixels. I've seen code like:
cimg_forXYZ(S,x,y,z) {... }
But I have never see than kind of syntax before, could it be a macro?
Any suggestions are welcome.
| If you look into the CImg header, you'll see that that code is, in fact, a macro that thunks down into:
#define cimg_forXY(img,x,y) cimg_forY(img,y) cimg_forX(img,x)
#define cimg_forX(img,x) for (int x=0; x<(int)((img).width); ++x)
#define cimg_forY(img,y) for (int y=0; y<(int)((img).height); ++y)
#define cimg_forZ(img,z) for (int z=0; z<(int)((img).depth); ++z)
#define cimg_forXYZ(img,x,y,z) cimg_forZ(img,z) cimg_forXY(img,x,y)
Which means that you will have the following loops:
for (int z=0; z<(int)((img).depth); ++z)
for (int y=0; y<(int)((img).height); ++y)
for (int x=0; x<(int)((img).width); ++x) {
}
So, now, what you probably want to do is reference either the x, y, and z coordinates, or better, the pointer into the data as you step through, like
cimg_library::CImg<float> image;
//assign, etc
float* ptr = image->ptr();
cimg_forXYZ(S, x, y, z){
*ptr = *ptr + 10;
++ptr;
}
I encourage you to read the CImg header; it's quite elegant. You'll get a lot of functionality 'for free'.
|
1,313,246 | 1,313,291 | is it possible to have getline() function accept wistream& | Just for clarification, I'm referring to the global getline() function in the string class.
What I want to do is to have something like this:
int main()
{
wifstream in(L"textfile.txt");
someFunc(in);
return 0;
}
void someFunc(const wistream& read)
{
wstring buff;
while(getline(read, buff))
{
//do some processing here
}
}
but I'm getting a:
Error 2 error C2664: 'std::getline' : cannot convert parameter 1 from 'const std::wistream' to 'std::basic_istream<_Elem,_Traits> &'
In order to fix it, I need to remove the const from const wistream& read. I understand why this is happening but is it possible to configure getline() to accept a wistream instead without any conversions or should I just ignore it and remove the const?
| It does accept a wistream, but getline() demands a non-const argument because it modifies the stream. Try changing it to:
...
void someFunc(wistream& read)
...
|
1,313,259 | 10,354,776 | Tiling Simplex Noise? | I've been interested (as a hobbyist) in pseudo-random noise generation, specifically the Perlin and Simplex algorithms. The advantage to Simplex is speed (especially at higher dimensions), but Perlin can be tiled relatively easily. I was wondering if anyone was aware of a tiling simplex algorithm? Fixed-dimension is fine, generic is better; pseudocode is fine, c/c++ is better.
| It would seem this question has been reasonably solved here, with a detailed description of the idea behind the working solution here. A fantastic answer to a long-standing problem!
|
1,313,727 | 1,314,022 | return by value inline functions | I'm implementing some math types and I want to optimize the operators to minimize the amount of memory created, destroyed, and copied. To demonstrate I'll show you part of my Quaternion implementation.
class Quaternion
{
public:
double w,x,y,z;
...
Quaternion operator+(const Quaternion &other) const;
}
I want to know how the two following implementations differ from eachother. I do have a += implementation that operates in-place to where no memory is created, but some higher level operations utilizing quaternions it's useful to use + and not +=.
__forceinline Quaternion Quaternion::operator+( const Quaternion &other ) const
{
return Quaternion(w+other.w,x+other.x,y+other.y,z+other.z);
}
and
__forceinline Quaternion Quaternion::operator+( const Quaternion &other ) const
{
Quaternion q(w+other.w,x+other.x,y+other.y,z+other.z);
return q;
}
My c++ is completely self-taught so when it comes to some optimizations, I'm unsure what to do because I do not know exactly how the compiler handles these things. Also how do these mechanics translate to non-inline implementations.
Any other criticisms of my code are welcomed.
| Your first example allows the compiler to potentially use somehting called "Return Value Optimization" (RVO).
The second example allows the compiler to potentially use something called "Named Return Value Optimization" (NRVO). These 2 optimizations are clearly closely related.
Some details of Microsoft's implementation of NRVO can be found here:
http://msdn.microsoft.com/en-us/library/ms364057.aspx
Note that the article indicates that NRVO support started with VS 2005 (MSVC 8.0). It doesn't specifically say whether the same applies to RVO or not, but I believe that MSVC used RVO optimizations before version 8.0.
This article about Move Constructors by Andrei Alexandrescu has good information about how RVO works (and when and why compilers might not use it).
Including this bit:
you'll be disappointed to hear that each compiler, and often each compiler version, has its own rules for detecting and applying RVO. Some apply RVO only to functions returning unnamed temporaries (the simplest form of RVO). The more sophisticated ones also apply RVO when there's a named result that the function returns (the so-called Named RVO, or NRVO).
In essence, when writing code, you can count on RVO being portably applied to your code depending on how you exactly write the code (under a very fluid definition of "exactly"), the phase of the moon, and the size of your shoes.
The article was written in 2003 and compilers should be much improved by now; hopefully, the phase of the moon is less important to when the compiler might use RVO/NRVO (maybe it's down to day-of-the-week). As noted above it appears that MS didn't implement NRVO until 2005. Maybe that's when someone working on the compiler at Microsoft got a new pair of more comfortable shoes a half-size larger than before.
Your examples are simple enough that I'd expect both to generate equivalent code with more recent compiler versions.
|
1,313,988 | 1,314,025 | C++: what is the optimal way to convert a double to a string? | What is the most optimal way to achieve the same as this?
void foo(double floatValue, char* stringResult)
{
sprintf(stringResult, "%f", floatValue);
}
| I'd probably go with what you suggested in your question, since there's no built-in ftoa() function and sprintf gives you control over the format. A google search for "ftoa asm" yields some possibly useful results, but I'm not sure you want to go that far.
|
1,314,432 | 1,314,459 | c++ template problem in cross-platform code | I'm having some trouble getting this code to compile on Linux but it works perfectly in Windows.
Windows compiler: Visual Studio 2005
Linux compiler: gcc version 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)
class DoSomething
{
public:
template <class DataType>
bool Execute()
{
//do something here
}
};
template <class Operator>
TypeSwitch(int DataTypeCode, Operator& Op)
{
switch (DataTypeCode)
{
case 1: return Op.Execute<char>();
case 2: return Op.Execute<int>();
//snip;
}
}
//To call the operator
TypeSwitch(Code,DoSomething);
In Windows this code works perfectly and does exactly what I want it to. In Linux, I get the errors:
error: expected primary-expression before '>' token
error: expected primary-expression before ')' token
for each of the lines with the case statement.
Any ideas?
Thanks,
Mike
| The problem is that when the compiler encounters Op.Execute<char>(); and tries to parse it, it gets confused.
Op is a dependant name, so the compiler doesn't know much about its members. So it doesn't know that Execute is a template function. Instead, it assumes that the < means less than.
That you're trying to compare some unknown Execute member to something else.
So instead, the line should look like this:
case 1: return Op.template Execute<char>();
Now the compiler knows that Execute is a template, so when it encounters < it is not "less than", but the beginning of the template parameters.
The problem is similar to how you need typename when specifying types belonging to a dependent name. When you're referring to a template member function, and the template arguments are given explicitly, you need the template keyword.
GCC's behavior is correct, and MSVC is too lenient. If you add the template keyword, your code will work in both compilers (and be correct according to the standard)
|
1,314,526 | 1,314,539 | What is a pseudo-virtual function in C++? | What is a pseudo-virtual function in C++?
| AFAIK it's not a term that appears anywhere with an official definition.
Perhaps someone is talking about simulated dynamic binding?
Edit: a swift web search suggests that someone might have implemented their own dynamic polymorphism, so they perhaps have their own vtables. "Pseudo-virtual" functions would then be functions accessed through their mechanism, rather than actually being virtual functions as their C++ compiler understands them.
One reason to do this would be to implement multi-dispatch.
Do you have any context you can point us at?
|
1,314,717 | 1,314,877 | how do I get the non-flag and non-option tokens after boost::program_options parses my command line args | In python, I can construct my optparse instance such that it will automatically filter out the options and non-option/flags into two different buckets:
(options, args) = parser.parse_args()
With boost::program_options, how do I retrieve a list of tokens which are the remaining non-option and non-flag tokens?
e.g. If my program has flags
--foo
--bar BAR
and I then pass in the command line:
--foo hey --bar BAR you
how can I get a list comprised solely of tokens "hey" and "you"
| IIRC, you have to use a combination of positional_options_description and hidden options. The idea is to (1) add a normal option and give it a name, maybe something like --positional=ARG, (2) don't include that option in the help description, (3) configure command_line_parser to treat all positional arguments as if --positional was specified, and (4) retrieve the positional arguments using vm["positional"].as< std::vector<std::string> >().
There is probably an example somewhere in the source tree but I don't have it on this machine right now.
|
1,314,775 | 1,314,803 | Socket send question | Is there any reason why this shouldn't work?
[PseudoCode]
main() {
for (int i = 0; i < 10000; ++i) {
send(i, "abc", 3, 0);
}
}
I mean, to send "abc" through every number from 0 to 10000, aren't we passing in theory by a lot of different sockets? Most numbers between 0 and 10000 will not correspond to any socket, but some will. Is this correct?
edit: The desired goal is to have "abc" sent through every application that has an open socket.
| That will never work. File descriptors are useful only within the same process (and its children).
You have to create a socket (this will get you a file descriptor you own and can use), connect it to an end point (which of course has to be open and listening) and only then you can send something through it.
For example:
struct sockaddr_in pin;
struct hostent *hp;
/* go find out about the desired host machine */
if ((hp = gethostbyname("foobar.com")) == 0) {
exit(1);
}
/* fill in the socket structure with host information */
memset(&pin, 0, sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
pin.sin_port = htons(PORT);
/* grab an Internet domain socket: sd is the file descriptor */
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
exit(1);
}
/* connect to PORT on HOST */
if (connect(sd,(struct sockaddr *) &pin, sizeof(pin)) == -1) {
exit(1);
}
/* send a message to the server PORT on machine HOST */
if (send(sd, argv[1], strlen(argv[1]), 0) == -1) {
exit(1);
}
The other side of the coin is to create a listening socket (what servers do) which will receive connections. The process is similar but the calls change, they are socket(), bind(), listen(), accept(). Still, you have to create a socket to get the file descriptor in your own process and know where would you want to listen or connect to.
|
1,314,821 | 1,315,543 | accessing element of boost sparse_matrix seems to stall program | I've got a strange bug that I'm hoping a more experience programmer might have some insight into. I'm using the boost ublas sparse matrices, specifically mapped_matrix, and there is an intermittent bug that occurs eventually, but not in the initial phases of the program. This is a large program, so I cannot post all the code but the core idea is that I call a function which belongs to a particular class:
bool MyClass::get_cell(unsigned int i, unsigned int j) const
{
return c(i,j);
}
The variable c is defined as a member of the class
boost::numeric::ublas::mapped_matrix<bool> c;
When the bug occurs, the program seems to stop (but does not crash). Debugging with Eclipse, I can see that the program enters the boost mapped_matrix code and continues several levels down into std::map, std::_Rb_tree, and std::less. Also, the program occasionally traces down to std::map, std::_Rb_tree, and std::_Select1st. While code is executing and the active line what's in memory changes in _Rb_tree, execution never seems to return in the level of std::map. The line in std::map the program is stuck on is the return of the following function.
const_iterator
find(const key_type& __x) const
{ return _M_t.find(__x); }
It seems to me that there is some element in the c matrix that the program is looking for but somehow the underlying storage mechanism has "misplaced it". However, I'm not sure why or how to fix it. That could also be completely off base.
Any help you can provide would be greatly appreciated. If I have not included the right information in this question, please let me know what I'm missing. Thank you.
| Some things to try to debug the code (not necessarily permanent changes):
Change the bool to an int in the matrix type for c, to see if the matrix expects numeric types.
Change the matrix type to another with a similar interface, possibly plain old matrix.
Valgrind the app (if you're on linux) to check you're not corrupting memory.
If that fails, you could try calling get_cell every time you modify the matrix to see what might be causing the problem.
Failing that, you may have to try reduce the problem to a much smaller subset of code which you can post here.
It might help if you tell us what compiler and OS you're using.
|
1,314,824 | 1,314,891 | Implementing Smart Pointer - Dynamic Allocation with templates | I'm in the process of writing a smart pointer countedptr and I've hit a speed bump. The basic function of countedptr is to work like any other smart pointer and also have a count of how many pointers are pointing to a single object. So far, the code is:
[SOLVED]
#include "std_lib_facilities.h"
template <class T>
class counted_ptr{
private:
T* pointer;
int* count;
public:
counted_ptr(T* p = 0, int* c = new int(1)) : pointer(p), count(c) {} // default constructor
explicit counted_ptr(const counted_ptr& p) : pointer(p.pointer), count(p.count) { ++*count; } // copy constructor
~counted_ptr() { --*count; delete pointer; }
counted_ptr& operator=(const counted_ptr& p)
{
pointer = p.pointer;
count = p.count;
++*count;
return *this;
}
T* operator->() const{ return pointer; }
T& operator*() const { return *pointer; }
int Get_count() const { return *count; }
};
int main()
{
counted_ptr<double> one;
counted_ptr<double>two(one);
int a = one.Get_count();
cout << a << endl;
}
When I try to do something like
one->pointer = new double(5);
then I get a compiler error saying "request for member 'pointer' in '*(&one)->counted_ptr::operator->with T = double' which is of non-class type double".
I considered making a function to do this, and while I could make a function to allocate an array of T's, I can't think of a way of making one for allocating actual objects. Any help is appreciated, thanks.
| Old Solution
What about another assignment operator?
counted_ptr& counted_ptr::operator=(T* p)
{
if (! --*count) { delete count; }
pointer = p;
count = new int(1);
return *this;
}
...
one = new double(5);
Also, your destructor always deletes a shared pointer, which is probably what caused *one to be a random nomber. Perhaps you want something like:
counted_ptr::~counted_ptr() { if (! --*count) { delete pointer; delete count; } }
New Solution
As you want repointing a counted_ptr (eg one = new double(5)) to update all related counted_ptrs, place both the pointer and the count in a helper class, and have your pointer class hold a pointer to the helper class (you might already be headed down this path). You could go two ways in filling out this design:
Make the helper class a simple struct (and a private inner class) and place all the logic in the outer class methods
Make counted_ptr the helper class. counted_ptr maintains a reference count but doesn't automatically update the count; it's not a smart pointer, it only responds to release and retain messages. If you're at all familiar with Objective-C, this is basically its traditional memory management (autoreleasing aside). counted_ptr may or may not delete itself when the reference count reaches 0 (another potential difference from Obj-C). counted_ptrs shouldn't be copyable. The intent is that for any plain pointer, there should be at most one counted_ptr.
Create a smart_ptr class that has a pointer to a counted_ptr, which is shared among smart_ptr instances that are supposed to hold the same plain pointer. smart_ptr is responsible for automatically updating the count by sending its counted_ptr release and retain methods.
counted_ptr may or may not be a private inner class of shared_ptr.
Here's an interface for option two. Since you're doing this as an exercise, I'll let you fill out the method definitions. Potential implementations would be similar to what's already been posted except that you don't need a copy constructor and copy assignment operator for counted_ptr, counted_ptr::~counted_ptr doesn't call counted_ptr::release (that's smart_ptr::~smart_ptr's job) and counted_ptr::release might not free counted_ptr::_pointer (you might leave that up to the destructor).
// counted_ptr owns its pointer an will free it when appropriate.
template <typename T>
class counted_ptr {
private:
T *_pointer;
size_t _count;
// Make copying illegal
explicit counted_ptr(const counted_ptr&);
counted_ptr& operator=(const counted_ptr<T>& p);
public:
counted_ptr(T* p=0, size_t c=1);
~counted_ptr();
void retain(); // increase reference count.
bool release(); // decrease reference count. Return true iff count is 0
void reassign(T *p); // point to something else.
size_t count() const;
counted_ptr& operator=(T* p);
T& operator*() const;
T* operator->() const;
};
template <typename T>
class smart_ptr {
private:
counted_ptr<T> *_shared;
void release(); // release the shared pointer
void retain(); // retain the shared pointer
public:
smart_ptr(T* p=0, int c=1); // make a smart_ptr that points to p
explicit smart_ptr(counted_ptr<T>& p); // make a smart_ptr that shares p
explicit smart_ptr(smart_ptr& p); // copy constructor
~smart_ptr();
// note: a smart_ptr's brethren are the smart_ptrs that share a counted_ptr.
smart_ptr& operator=(smart_ptr& p); /* Join p's brethren. Doesn't alter pre-call
* brethren. p is non-const because this->_shared can't be const. */
smart_ptr& operator=(counted_ptr<T>& p); /* Share p. Doesn't alter brethren.
* p is non-const because *this isn't const. */
smart_ptr& operator=(T* p); // repoint this pointer. Alters brethren
size_t count() const; // reference count
T& operator*() const; // delegate these to _shared
T* operator->() const;
};
Hopefully, the only ambiguous points above are the intentional ones.
|
1,314,916 | 1,314,934 | What really is the SOCKET type? | I can see it looks like an alias for an unsigned int pointer, right? Is it just like a pointer in memory? To what would it be actually pointing? Is it pointing to a struct? If yes, how is that struct defined? Is it just a number that is used by socket functions and does not map to a memory address?
| In Win32, a SOCKET data type is the same as a HANDLE, which is an integer used to refer to a kernel data structure of some kind. This kernel data structure is "opaque", which means that application programs do not need to (and in fact cannot) see the internals of the structure. All access to Win32 SOCKETs is done through Winsock API functions.
Note that in Win16, a SOCKET was not the same thing because there was no Win16 HANDLE type. However, Win32 kept the same type name for source compatibility.
|
1,315,041 | 1,315,072 | How can I iterate through a string and also know the index (current position)? | Often when iterating through a string (or any enumerable object), we are not only interested in the current value, but also the position (index). To accomplish this by using string::iterator we have to maintain a separate index:
string str ("Test string");
string::iterator it;
int index = 0;
for ( it = str.begin() ; it < str.end(); it++ ,index++)
{
cout << index << *it;
}
The style shown above does not seem superior to the 'c-style':
string str ("Test string");
for ( int i = 0 ; i < str.length(); i++)
{
cout << i << str[i] ;
}
In Ruby, we can get both content and index in a elegant way:
"hello".split("").each_with_index {|c, i| puts "#{i} , #{c}" }
So, what is the best practice in C++ to iterate through an enumerable object and also keep track of the current index?
| I've never heard of a best practice for this specific question. However, one best practice in general is to use the simplest solution that solves the problem. In this case the array-style access (or c-style if you want to call it that) is the simplest way to iterate while having the index value available. So I would certainly recommend that way.
|
1,315,250 | 1,315,289 | Using ALSA's function snd_pcm_writei can I free the sample buffer right away? | Using ALSA to play audio, after calling snd__pcm__writei, can I free the sound sample buffer right away or do I need to wait until the sound is finished playing before I can free the sample buffer?
For example:
unsigned short *buffer;
buffer = malloc(size of sample to play);
...load data into buffer...
snd_pcm_writei (playback_handle, buffer, size of sample)
free(buffer)
| Easiest way to find out would be to start writing backwards from the end of the buffer and see if you affect the audio playback. If you do then you definitely can't free the buffer. If it makes no difference then you can safely free the buffer as the sound card is not reading from that particular block of memory.
|
1,315,263 | 1,315,285 | LinkedList "node jump" | Trying to figure out why my list() class pointers are being overwritten with the third node. What happens in the insert function (below) is that the third time the insert function is called my headByName->nextByName node pointer is overwritten by the third node, when it should point to the second. So as you can guess the 4th node is overwritten by the 5th and the 6th node is overwritten by the 7th, hence the "jump" in nodes.
The attributes of the winery object are passed through the winery ctor and then to the list::insert function via these calls in main:
//main.cpp
//the attributes of the winery object are the paramaters, name, location, acres, rating:
list *listPtr = new list();
wineries->insert(winery("Lopez Island Vinyard", "San Juan Islands", 7, 95));
wineries->insert(winery("Gallo", "Napa Valley", 200, 25));
wineries->insert(winery("Cooper Mountain", "Willamette Valley", 100, 47));
Then the winery ctor is called where I allocate the private pointer memembers:
//winery.cpp
winery::winery(const char * const name, const char * const location, const int acres, const int rating)
: m_acres( acres ), m_rating( rating )
{
if (name)
{
size_t len = strlen( name ) +1;
m_name = new char[len];
strcpy_s( m_name, len, name );
}
else
m_name = NULL;
if (location)
{
size_t len = strlen( location ) +1;
m_location = new char[len];
strcpy_s( m_location, len, location );
}
else
m_location = NULL;
}
And then to the issue at hand: If you can imagine this function has already been called twice then current_node will have the thrid winery. headByName will have the first node and in it [+], headByName->next will have the third. I need headByName->next to have the second. I am just wondering why it has been overwritten..
// list.cpp
void list::insert(const winery& winery)
{
node *current_node = new node( winery ); // the third wineries info!
node *next_node = NULL;
list *list_ptr = NULL;
do
{
if ( headByName == NULL || headByRating == NULL ) // then we are here for the first item
{
headByName = current_node; // the list ptrs have a node address.
headByRating = current_node;
}
else
{
next_node = current_node;
// transfer by the next call in main.
headByName->nextByName = next_node;
headByRating->nextByRating = next_node;
}
} while ( headByName == NULL || headByRating == NULL );
next_node = NULL;
current_node = NULL;
}
Could someone please find my second node?
oh yeah, and the pointers that are available to me:
struct node
{
winery item;
node * nextByName;
node * nextByRating;
};
class list
{
...
private:
node * headByName;
node * headByRating;
};
this might be of some importance, its the body of the node ctor:
//list.cpp
list::node::node(const winery &winery) :
nextByName( NULL ), nextByRating( NULL ), item( winery.getName(),
winery.getLocation(), winery.getAcres(), winery.getRating() )
{
// where the item paramters are all pub-mem functions of the winery class.
}
| I think that problem is here:
headByName->nextByName = next_node;
headByRating->nextByRating = next_node;
You're always override second node. As I understand you should find last one by iterating through whole list and insert after last node.
|
1,315,266 | 1,315,309 | Displaying another app in my form | I remember I had some app the launched other applications and placed them in tabs in it's form without the titlebars.
I wonder how can that be done?
Preferably with C# but if it's not possible/too hard within .NET C++ is fine too.
Thanks.
| Applications like Excel and Internet Explorer provide specific support (OLE) for being embedded in other windows, so third-party application can run an instance of them within their own window easily.
If the application you wish to embed doesn't supply specific support for it, it would be much harder to achieve. It's easy to control the target application's windows to make them appear to be in your tabs, but when it comes to removing/hiding specific sub-parts of the windows (borders and menus etc) it gets a lot more difficult (all depending on exactly which bits of the application's display you wish to alter).
|
1,315,475 | 1,315,504 | Is it possible to use 'using' declaration on the static class function [C++]? | Is it legal?
class SomeClass {
public:
static void f();
};
using SomeClass::f;
Edit: I forgot to qualify function. Sorry.
| No, it is not. The using keyword is used to bring one or all members from a namespace into the global namespace, so that they can be accessed without specifying the name of the namespace everytime we use the members.
In the using statement you have given, the name of the namespace is not provided. Even if you had provided SomeClass there with a statement like using SomeClass::f; also, it won't work because SomeClass is not a namespace.
Hope this helps.
|
1,315,534 | 1,315,551 | Why is my destructor never called? | I have a base class A and a derived class B:
class A
{
public:
virtual f();
};
class B : public A
{
public:
B()
{
p = new char [100];
}
~B()
{
delete [] p;
}
f();
private:
char *p;
};
For any reason the destructor is never called - why? I dont understand this.
| Your base class needs a virtual destructor. Otherwise the destructor of the derived class will not be called, if only a pointer of type A* is used.
Add
virtual ~A() {};
to class A.
|
1,315,826 | 1,315,832 | Sharing objects between C# and C++ code | Is it possible to share references to C# objects between C# and C++ code without massive complexity? Or is this generally considered a bad idea?
| The best solution for sharing a C# object between native and managed code is to use COM interop. This allows you to essentially share an interface of an object between managed code and it's equivalent signature in C++.
As for the complexity side of things. The majority of COM interop scenarios are straight forward and really are no more complex than good old COM programming. On the managed side it looks really no different than a normal interface.
Once you introduce multiple threads or start playing around between COM apartments though, things can get a bit tricky.
In my experience, the easiest way to get this working is the following.
Define an interface in C# that you wish to use in C++
Mark the interface with the ComVisible(true) attrbute
Run tlbexp on the assembly which generates a TLB file
Import the TLB into your native project
This will get the interface definition into both of your projects. How to pass that between the projects requires a bit more detail into your architecture.
|
1,315,831 | 1,315,862 | Line-breaking algorithm | Where can I find an efficient algorithm for breaking lines of text for formatted display?
| One approach to this very problem is addressed in the book Introduction to Algorithms (Cormen, Leiserson, Rivest, Stein) as problem 15-2.
It takes the approach that a nicely broken block of text has as even spacing at the end as possible, punishing large differences.
This problem is solvable using dynamic programming.
Naturally this is only one approach to the problem, but in my opinion it at least looks better than the greedy algorithm.
I'm not much for putting my solutions to textbook problems on the Internet, so I'll leave it to you to either solve it or Google for a solution, in order to get the exact algorithm needed.
|
1,315,926 | 1,316,016 | GCC: Empty program == 23202 bytes? | test.c:
int main()
{
return 0;
}
I haven't used any flags (I am a newb to gcc) , just the command:
gcc test.c
I have used the latest TDM build of GCC on win32.
The resulting executable is almost 23KB, way too big for an empty program.
How can I reduce the size of the executable?
| Don't follow its suggestions, but for amusement sake, read this 'story' about making the smallest possible ELF binary.
|
1,316,092 | 1,316,275 | Updating Boost Wave from SVN | I have run into some bugs into one of the boost components that I am using. After analyzing the problem a bit, I've found that I was not the only one, and the author had already issued a fix that is available in the boost SVN trunk.
What would be the best approach if I wanted to update just this component and reuse the libraries that are already built? The component is not header only.
Compiler: MSVC 9 with SP1, TR1
OS: Vista
Boost: 1.39 from BoostPro computing
buggy component: Boost Wave
bug: race conditions. The bug was fixed in may this year, but they haven't included it in any release as far as I can tell.
What I did so far:
svn checkout of the wave subdir
replaced local subdir
now I'm looking for a way to specify that I want to build just wave
I'm a bit weary of rebuilding the entire boost lib. I don't know if trunk is production-ready right now.
| Here's what I ended up doing:
First I checked out the version of the wave lib where the issue was fixed (53230). After diffing it to my local copy, I have found the following changes:
- wave was reusing a boost.iterator implementation instead of providing its own
- the flex_string implementation was updated
- a ref counter was made atomic. This should be the bugfix
Then I simply replaced my boost/wave dir with the one from SVN. I ran bootstrap.bat (if using BoostPro you will have to get this from the boost sources zip) and then I ran bjam:
bjam --build-directory=build toolset=msvc variant=debug|release link=static threading=multi runtime-link=shared --with-wave
Adding --with-wave will only build wave and its dependencies.
At this point I got compile errors: it seems that Spirit was also updated. I downloaded Spirit (53252) from SVN and reissued the bjam command.
The library build cleanly and I copied the two libs to my boost lib folder.
After doing those steps, I rebuild my project and the crashing errors were gone.
|
1,316,170 | 1,316,650 | Having an image file buffer in memory, what is the fastest way to create its thumbnail? | Trying to create a an image acquiring application optimized for a fast scanner (which can provide up to 6 compressed images [color+gray+binary][front+rear] for each paper at speed of 150 ppm) I have some speed issues.
Using TWAIN technology and memory buffer transfer mode (TWSX_MEMORY) I receive image buffer (as JPEG or TIFF file loaded in memory) from scanner and save it to my application destination path.
If I do not want to create thumbnails, my application causes no speed loss for the scanner, but if I want to, due the way I do it (saving buffer into a file in my C++ TWAIN handling dll, notifying my .NET host application with destination file path using a function pointer, opening the image file in C# and creating the thumbnail image), my application causes extreme speed loss to scanning speed.
I tried some optimizations such as performing loading phase in a separate thread and sending unmanaged image file buffer to .NET host and trying to load it in an unsafe context (UnmanagedMemoryStream) and creating thumbnail. But it did not improve the speed significantly. So my question is :
Having an image file buffer in memory (e.g. 24 bit JPEG compressed without embeded thumbnail), is there a fast direct way to create a thumbnail image from it? What do you suggest as fastest method for creating thumbnails in this case?
| If it's a JPEG image, you can simply discard most of the DCT data, and create a thumbnail at a power of two size, using only the DCT coefficients.
If you can find the sources for it, take a look at EPEG from the Enlightenment project. It does exactly what you're looking for with JPEG files, entirely without decoding or decompressing the image. The source code would be very instructive.
For other image formats, it's not so simple - you'll need to decode and render the image to a memory buffer, then perform your own scaling. The CImg and boost::GIL libraries can assist with that.
|
1,316,320 | 1,321,004 | A C++ code generator from an XML spec | I'd like to know if there's a tool which allows you to do class definition based on an XML format. I'm not looking for data binding. Anyone can help ?
Thanks
| I know of two tools both of them are commercial products
http://www.codesynthesis.com/products/xsd/
Is open source GPL - commercial licence is avalable for commercial use
I think this is/was used by gSOAP
http://www.artima.com/cppsource/xml_data_binding.html
http://www.codalogic.com/lmx/
don't know any more than the web site
I hope this helps.
Update:
Just found this http://en.wikipedia.org/wiki/XML_data_binding#C.2B.2B
Update 2:
This is great, I have been looking for an open source package to do this for ages and your question has just helped my find it:
http://top.touk.pl/confluence/display/xmlbeansxxdoc/Introduction+to+xmlbeansxx
http://top.touk.pl/confluence/download/attachments/458767/Manipulate_XML_Documents_in_CPP_with_xmlbeansxx.pdf
|
1,316,439 | 1,316,450 | rand() doesn't obey srand() in Qt Creator | I've written a program in Qt Creator 1.0.0 (Qt version 4.5.0) where at the beginning of main() function I've put
srand(time(0));
Then I'm calling rand() from another thread (subclass of QThread). In that function, rand() is producing same sequence of numbers each time I'm running the program. I'm not running the program multiple times in a second.
Why is this happening?
| You need to call srand in each thread, because the seed is stored in a thread-specific block.
|
1,316,601 | 1,316,620 | Implementing Smart Pointer - storing template class in vector | I'm having trouble storing instances of my smart pointer into a container. Here is the code for the pointer.
#include "std_lib_facilities.h"
template <class T>
class counted_ptr{
private:
T* pointer;
int* count;
public:
counted_ptr(T* p = 0, int* c = new int(1)) : pointer(p), count(c) {} // default constructor
explicit counted_ptr(const counted_ptr& p) : pointer(p.pointer), count(p.count) { ++*count; } // copy constructor
~counted_ptr()
{
--*count;
if(!*count) {
delete pointer;
delete count;
}
}
counted_ptr& operator=(const counted_ptr& p) // copy assignment
{
pointer = p.pointer;
count = p.count;
++*count;
return *this;
}
T* operator->() const{ return pointer; }
T& operator*() const { return *pointer; }
int& operator[](int index) { return pointer[index]; }
int Get_count() const { return *count; } // public accessor for count
};
int main()
{
counted_ptr<double>one;
counted_ptr<double>two(one);
one = new double(5);
vector<counted_ptr<double> >test;
}
In int main(), the vector<counted_ptr<double> > line does compile. When I first tried it with just vector<counted_ptr<double> > it didn't compile (probably because it was lacking parameters.) However, when I try to use push_back such as
test.push_back(one);
I get a compiler error that opens up vector.tcc with the specific error saying that
no matching function for call to `counted_ptr<double>::counted_ptr(const counted_ptr<double>&)'|
I'm guessing that push_back can't find a counted_ptr, but I'm really not sure. Any
help is appreciated, thanks.
Edit: However, this works. test[0] = one; I guess the semantics of push_back are what is restricting it.
| You may want to try this:
test.push_back(counted_ptr<double>(one));
You copy constructor is explicit which means that the compiler won't implicitly invoke it.
Personally, I would make the raw pointer constructor explicit and the copy ctor not explicit. That would be closer to usual behavior.
EDIT: I also recommend that you implement a swap method. It makes assignment absolutely trivial. You end up with something like this:
counted_ptr &operator=(const counted_ptr &rhs) {
counted_ptr(rhs).swap(*this);
return *this;
}
This also has the benefit of all of the accounting happening in constructors/destructors which is a lot simpler to manage :-).
|
1,316,699 | 1,316,775 | c++ return if invalid input | I have done up a program which requires the following:
prompts user input account no
prompts user input account type
if account type == a, prompts some input and does a certain formula [if]
if account type == b, prompts some input and does another formula [else if]
if account type is wrong(not a or b), prompts error and return to 2 [else]
prompts user input to exit [do while]
if input == y, exits
if input == n, return to 1
at the moment I'm pretty stuck at 2.3.
it prompts the error and goes to 3 instead of returning to 2 to prompt user input.
where is the problem? the else?
| You have to use a loop to keep asking for an account type if the type is wrong:
do
{
//1
do
{
//2
if (type =="a")
//2.1
else if(type=="b")
//2.2
else
//2.3
}
while (type != "a" and type != "b");
//3
if(input == "y")
return;
}
while (input == "n");
|
1,316,747 | 1,316,763 | How is the C++ standard library linked to my application? | When I usually use code (include headers) from 3rd party (non-standard) C++ libraries, a pre-built binary file is linked to (or included in) the target executable that represents my application, but what happens with C++ standard library?, as far as I have seen I don't have to ship a library with an application that uses code only from the C++ standard library, thus is the code statically linked and included in the executable?
| No, the standard libraries by default are dynamically linked at runtime.
When running the dynamic loader will look in a couple of standard places for dynamic libraries if it finds it loads and runs otherwise the application quits.
On Unix Systems:
/usr/lib: look for: libstdc++*
On Windows:
c:\windows\system32 look for: MSVCRT.DLL
There are also a couple of Environment variables that can affect the search path. Look at your platforms man page for dlopen to see what they are. Everything you need should be in the man pages for dlopen on your platform.
Most systems have these libs in the appropriate places and will automatically be found.
The rest of the STL will not introduces extra shared lib dependencies.
|
1,316,809 | 1,316,829 | Recursive function with static variable | I have a recursive function with a static variable "count". The function increments count recursively and since it has file scope, when I call foo() a second time, count is still equal to 5. Is there a technique to reset count to 0 before the second time foo() is called?
Basically, I don't want count to have file scope but I want it to retain its value through different iterations.
One way I can think of doing it is have an argument in foo() to initialize foo(). Such as foo(int count). But is there another way?
#include <iostream>
using namespace std;
void foo()
{
static int count = 0;
if(count<5)
{
count++;
cout<<count<<endl;
foo();
}
else
{
cout<<"count > 5"<<endl;
}
}
int main()
{
foo(); //increment count from 0 to 5
foo(); //count is already at 5
return 0;
}
| A more idiomatic way is to split it into two functions:
void foo() {
foo_recursive(0);
}
void foo_recursive(int count) {
if (count < 5) {
count++;
cout << count << endl;
foo_recursive(count);
} else {
cout << "count > 5" << endl;
}
}
Which has the benefit of not requiring the caller to supply an argument to foo() and also you don't need a static variable (which I always feel is a bad idea).
|
1,316,924 | 1,317,061 | Are return values going to be passed by rvalue reference in c++0x? | Let's say I have a function:
typedef std::vector<int> VecType;
VecType randomVector();
int processing()
{
VecType v = randomVector();
return std::accumulate(v.begin(), v.end(), 0);
}
Does C++0x specifically say the spurious copy will be averted from the return value of randomVector? Or would a compiler need to implement the RVO? It seems to me like the value randomVector() should be treated as an rvalue, and thus v's move constructor should be called, but I'm not completely sure this is true.
| The rule is the following
If the compiler can do RVO, then it is allowed to do it, and no copy and no move is made.
Otherwise, the appropriate constructor is taken.
Like you say, the temporary is an rvalue, and thus the move constructor is selected, because of a rule in 13.3.3.2/3, which says that a rvalue reference binds to an rvalue better than an lvalue reference. In deciding whether to use the move or the copy constructor, overload resolution will therefor prefer the move constructor.
The rule that the compiler is allowed to perform RVO is written at 12.8/15.
|
1,317,123 | 1,317,661 | How to Avoid DOS Attack using Berkeley Sockets in C++ | I'm working my way through UNIX Network Programming Volume 1 by Richard Stevens and attempting to write a TCP Echo Client that uses the Telnet protocol. I'm still in the early stages and attempting to write the read and write functions.
I'd like to write it to use I/O Multiplexing and the Select function, because it needs to be multi-client and I don't want to try and tackle learning C++ threads while I'm trying to learn the Berkeley Sockets library at the same time. At the end of the chapter on I/O Multiplexing Stevens has a small section on DOS attacks where he says that the method I was planning on using is vulnerable to DOS attacks that simply send a single byte after connecting and then hang. He mentions 3 possible solutions afterwards - nonblocking IO, threading (out), and placing a timeout on the I/O operations.
My question is, are there any other ways of avoiding such an attack? And if not, which of these is the best? I glanced over the section on placing a timeout on the operations, but it doesn't look like something I want to do. The methods he suggests for doing it look pretty complex and I'm not sure how to work them into what I already have. I've only glanced at the chapter on NIO, it looks like it's the way to go right now, but I'd like to see if there are any other ways around this before I spend another couple of hours plowing through the chapter.
Any ideas?
|
... are there any other ways of avoiding such an attack?
Yes, asynchronous I/O is another general approach.
If the problem is that a blocking read() may suspend your execution indefinitely, your general countermeasures are then:
Have multiple threads of executionmulti-threaded, multi-process, both.
Time-limit the blocking operatione.g., instantaneous (non-blocking I/O), or not (SO_RCVTIMEO, alarm(), etc.)
Operate asynchronouslye.g., aio_read
... which of these is the best?
For the newcomer, I'd suggest non-blocking I/O combined with a time-limited select()/poll(). Your application can keep track of whether or not a connection has generated "enough data" (e.g., an entire line) in a "short enough time."
This is a powerful, mostly portable and common technique.
However, the better answer is, "it depends." Platform support and, more importantly, design ramifications from these choices have to be assessed on a case-by-case basis.
|
1,317,130 | 1,317,143 | Random segfaults in C++ | I'm new to C++ and I haven't a clue where to start, so I uploaded the code to a pastebin because there is a lot of it.
This code compiles fine, and doesn't give off a warning, even with gcc's -Wall option.
It's supposed to generate all prime numbers up to a number given as a command line parameter.
On smaller numbers (e.g. 4,000 or 5,000), it works fine. On larger numbers such as 4,000,000, it crashes with a segfault nearly all the time. On numbers in between, it is hit and miss to whether it runs or not.
| int primes[max];
prime = primes;
while(*prime) {
*prime = 0;
prime++;
}
In the preceding code you can easily run randomly through a memory, Essentially you are going through RAM until you find a 0. If there are no 0s in your array then it will run into memory that doesn't not belong to the process and a segfault will occur.
Edit: As pointed out by Alcon you are doing this in other places in your code too.
Its also best not to allocated primes on the stack as you are unlikely to have that much stack memory available.
To fix this try the following code instead
int primes = new int[max];
size_t count = 0;
while( count < max )
{
prime[count] = 0;
count++;
}
And don't forget to call delete[] primes; at the end of your code (when you are finished with the primes array)
|
1,317,238 | 1,317,242 | C++ : error: invalid operands of types ‘String*’ and ‘const char [7]’ to binary ‘operator+’ | I'm learning cpp and In my last assignment I am rewriting the std::string class.
so here is an outline of my code:
string class:
class String {
public:
String(const char* sInput) {
string = const_cast<char*> (sInput);
}
const String operator+(const char* str) {
//snip
print();
}
void print() {
cout<<string;
}
int search(char* str) {
}
private:
char* string;
int len;
};
Oh and I have to say I tried to declare the method as String* operator+(const char* str) and as const String& operator+(const char* str) with no change.
And here is how I run it:
int main(int argc, char* argv[]) {
String* testing = new String("Hello, "); //works
testing->print();//works
/*String* a = */testing+"World!";//Error here.
return 0;
}
The full error goes like such:
foobar.cc:13: error: invalid operands
of types ‘String*’ and ‘const char
[7]’ to binary ‘operator+’
I looked up on Google and in the book I am learning from with no success.
any one with suggestions? (I am pretty sure I am doing something foolish you will have to forgive me I am originally a PHP programmer) can any one point me to what am I missing?
| You probably don't want to use a pointer to your String class. Try this code:
int main(int argc, char* argv[]) {
String testing = String("Hello, "); //works
testing.print();//works
String a = testing+"World!";
return 0;
}
When defining new operators for C++ types, you generally will work with the actual type directly, and not a pointer to your type. C++ objects allocated like the above (as String testing) are allocated on the stack (lives until the end of the "scope" or function) instead of the heap (lives until the end of your program).
If you really want to use pointers to your type, you would modify the last line like this:
String *a = new String(*testing + "World!");
However, following the example of std::string this is not how you would normally want to use such a string class.
|
1,317,295 | 1,317,408 | Checking if DWM/Aero is enabled, and having that code live in the same binary for 2000/XP/Vista/7 | I know the title makes little sense, mostly because it's hard to explain in just one line. So here's the situation:
I have a program who's binary is targeted at Windows 2000 and newer. Now, I went ahead and added some code to check if the user is running under Vista/7, and if so then check if Aero/DWM is enabled. Based on this I'll disable some stuff that isn't relevant to that particular platform, and enable some other features. My main problem is that in order to call DwmIsCompositionEnabled from Visual C++ 2008 I have to add the dwmapi.lib file and compile against it. Running the binary in anything other than Vista or 7 gives the "Unable to locate component. The application failed to start because dwmapi.dll was not found" error. This, of course, is expected to happen since DWM is new and not available for older platforms.
My question is then: will it be possible for me to somehow manage to pull this off? One binary for all OS versions AND include that DWM check code? This program was written under Visual Studio 2008, Visual C++ using MFC.
| Turns out I can just tell the linker to delayload the dwmapi.dll.
I'd like to thank ewanm89 because something he said sort of resonated and led me down the path to finding the actual answer.
|
1,317,424 | 1,317,471 | How to cope with extraneous characters left on the input stream? (cin skipped) | Sorry for the noobish question here, but I am just learning C++ and I am looking for the standard way of dealing with this problem. I am using VS2005.
Given a program:
#include <iostream>
using namespace std;
int main( )
{
while ( true )
{
cout << "enter anything but an integer and watch me loop." << endl;
int i;
cin >> i;
}
return 0;
}
If you enter anything but an integer the program will never allow you to enter anything again. Now, I realize that this is because there is input left on the stream after the format fails, so each call to cin << i just reads up to the next end line (I think). How do you guys clear out the stream or deal with this problem? It must be pretty common.
| Alright, I found the answer. The answer is...
Don't do this. Do not mix formatted and unformatted input using operator >>. Here is a good article on the subject:
http://www.cplusplus.com/forum/articles/6046/
Basically, the code changes to:
#include <iostream>
#include <string>
#include <stream>
using namespace std;
int main( )
{
while ( true )
{
cout << "enter anything but an integer and watch me loop." << endl;
string input;
getline( cin, input );
int i;
stringstream stream( input );
if ( stream >> i ) break;
}
return 0;
}
|
1,317,871 | 1,317,883 | finished writing a poker hand evaluator looking for a new project | just finished writing a five card poker hand evaluator in C++. now im looking for a new project about the same level of difficulty. maybe a very simple DOS command parser?
| It sounds like you might be interested in the type of problems Project Euler offers. In particular, it sounds like you have a solution for Problem 54 already.
|
1,317,948 | 1,318,433 | Any built-in function to test if 4 is in [1,2,3,4] (vector) | In Ruby I can do:
[1,2,3,4].include?(4) #=>True
In Haskell I can do :
4 `elem` [1,2,3,4] #=> True
What should I do in C++?
| There isn't a built-in function doing exactly that.
There is std::find which comes close, but since it doesn't return a bool it is a bit more awkward to use.
You could always roll your own, to get syntax similar to JIa3ep's suggestion, but without using count (which always traverses the entire sequence):
template <typename iter_t>
bool contains(iter_t first, iter_t last, typename iter_t::value_type val){
return find(first, last, val) != last;
}
Then you can simply do this to use it:
std::vector<int> x;
if (contains(x.begin(), x.end(), 4)) {...}
|
1,318,025 | 1,318,062 | How to declate a wide char constant in an IDL | We are migrating our C++ COM application to be unicode, and as part of this migration we want to migrate the constant strings in our IDL to unicode as well.
The problem is that at the moment, we still compile it both in ANSI and in UNICODE, which means that we can't use the L"String" construct to declare wide charts.
At the moment, our string constant defined like this:
const LPSTR STRING_CONST_NAME = "STRING VALUE";
And we want to define it like this:
const LPTSTR STRING_CONST_NAME = "STRING VALUE";
If it were regular code we would just add the _T("STRING VALUE") macro which would have converted it to L"STRING VALUE" when compiling in unicode
But from what I can see we can't use it in the IDL because _T is a pure C++ construct.
Is our approach even correct ? May be we should define it like this no matter what:
const LPTSTR STRING_CONST_NAME = L"STRING VALUE";
| I wonder why you need to have string constants in the IDL file, anyway. Wouldn't it be sufficient to have them in a header file? I see that Microsoft has wide string literals only in sapiaut.idl (looking at all platform SDK IDL files); as those few constants are never used, this might have been a mistake, as well. Also notice that those constants are defined as BSTR.
If you want them in the IDL file, it might be sufficient to cpp_quote them.
If you absolutely want them in the IDL literally, you could use an #ifdef to have two different definitions. In that case, you should also have two different type libraries, with seperate sets of interfaces, with different UUIDs, and so on.
|
1,318,458 | 1,318,516 | template specialization of template class | I want to specialize following member function:
class foo {
template<typename T>
T get() const;
};
To other class bar that depends on templates as well.
For example, I would like bar to be std::pair with some template parameters, something like that:
template<>
std::pair<T1,T2> foo::get() const
{
T1 x=...;
T2 y=...;
return std::pair<T1,T2>(x,y);
}
Where T1 and T2 are templates as well. How can this be done? As far as I know it should be
possible.
So now I can call:
some_foo.get<std::pair<int,double> >();
The full/final answer:
template<typename T> struct traits;
class foo {
template<typename T>
T get() const
{
return traits<T>::get(*this);
}
};
template<typename T>
struct traits {
static T get(foo &f)
{
return f.get<T>();
}
};
template<typename T1,typename T2>
struct traits<std::pair<T1,T2> > {
static std::pair<T1,T2> get(foo &f)
{
T1 x=...;
T2 y=...;
return std::make_pair(x,y);
}
};
| You can't partially specialize function templates, sorry but those are the rules. You can do something like:
class foo {
...
};
template<typename T>
struct getter {
static T get(const foo& some_foo);
};
template<typename T1, typename T2>
struct getter< std::pair<T1, T2> > {
static std::pair<T1, T2> get(const foo& some_foo) {
T1 t1 = ...;
T2 t2 = ...;
return std::make_pair(t1, t2);
};
and then call it like
getter<std::pair<int, double> >::get(some_foo);
though. You may have to do some messing around with friendship or visibility if get really needed to be a member function.
To elaborate on sbi's suggestion:
class foo {
...
template<typename T>
T get() const;
};
template<typename T>
T foo::get() const
{
return getter<T>::get(*this);
/* ^-- specialization happens here */
}
And now you're back to being able to say
std::pair<int,double> p = some_foo.get<std::pair<int, double> >();
|
1,318,525 | 1,319,141 | Policy based design decisions | I have a class called Device that accepts two policies as far as I can see: StatePolicy and BehaviorPolicy.
The StatePolicy holds and manages the state of the device.
The BehaviorPolicy wraps the device driver that is written in C or C++.
Now I have two questions:
How to coordinate between the state and the behavior policies?
How do I store all the devices inside one container? Since Device<X, Y>'s type is different then Device<N, M> I cannot store them with one container.
EDIT 1:
Here's some code to illustrate my problem:
class AbstractDevice
{
public:
virtual ~AbstractDevice() {}
virtual void performAction() = 0;
virtual const string &getName() const = 0;
//virtual void changeState(const ??? &_state) = 0; If I put a template here it won't solve my problem
};
template<typename T>
class State
{
private:
T state;
protected:
typedef T StateType;
public:
State() : state(1) {}
const T &getState() { return state; }
void setState(const T _state) { state = _state; }
};
template <class StatePolicy>
class LightbulbBehvior : protected StatePolicy
{
private:
typedef StatePolicy SP;
public:
virtual void performAction()
{
if ( SP::getState() )
cout << "do stuff";
}
void changeState(const typename SP::StateType &_state)
{
setState(_state);
performAction();
}
};
template<class StatePolicy, template <class> class BehviorPolicy>
class Device : public AbstractDevice, public BehviorPolicy<StatePolicy>
{
private:
string sName;
public:
const string &getName() const { return sName; }
};
int main()
{
AbstractDevice *d = new Device<State<int>, LightbulbBehvior>();
d->changeState(5);
return 0;
}
EDIT 2:
This makes the code works with one downside, I have to maintain a list of all allowed state types. It looks a bit like the visitor pattern to me.
Any thoughts?
class AbstractDevice
{
public:
virtual ~AbstractDevice() {}
virtual void performAction() = 0;
virtual const string &getName() const = 0;
virtual void changeState(const int &_state) = 0;
};
Thanks in advance,
Omer.
| Here is the full design that works and does it's job pretty well at it:
class AbstractState
{
public:
virtual ~AbstractState() {}
};
class AbstractDevice
{
public:
virtual ~AbstractDevice() {}
virtual void performAction() = 0;
virtual const string &getName() const = 0;
virtual void changeState(const AbstractState &_state) = 0;
};
template<typename T>
class State : public AbstractState
{
private:
T state;
protected:
typedef T StateType;
public:
State() {}
State(const T _state) : state(_state) {}
const T &getState() const { return state; }
void setState(const T _state) { state = _state; }
};
template <class StatePolicy>
class LightbulbBehvior : protected StatePolicy
{
private:
typedef StatePolicy SP;
public:
virtual void performAction()
{
if ( SP::getState() )
cout << "do stuff";
}
void changeState(const typename SP::StateType &_state)
{
setState(_state);
performAction();
}
};
template<class StatePolicy, template <class> class BehviorPolicy>
class Device : public AbstractDevice, public BehviorPolicy<StatePolicy>
{
private:
string sName;
typedef BehviorPolicy<StatePolicy> BP;
typedef StatePolicy SP;
public:
const string &getName() const { return sName; }
void performAction()
{
BP::performAction();
}
void changeState(const AbstractState &_state)
{
BP::changeState(((const SP &)_state).getState());
}
};
int main()
{
AbstractDevice *d = new Device<State<int>, LightbulbBehvior>();
d->changeState(State<int>(5));
delete d;
return 0;
}
@cjhuitt: Generally I think you are right but take a look and tell me what do you think.
|
1,318,533 | 1,318,566 | Threads using visual stdio2008 | I want to implement threading in c++.I am using visual stdio2008 and wish to implement threading using pthreads.can any one guide me about pthreads and also about there implementations in vs2008.Thanking in anticipation
| Why do you want to use a plain C API (pthreads) usually used in *nix (pthreads) use in C++ on Windows? Any other reason than ... Whatever.
Use boost.thread. It uses windows threads on windows, pthread on posix platforms. It works well, and is portable.
If you really want to use pthread, you will use something like Microsoft Windows Services for UNIX. Never tried that one, though.
|
1,319,132 | 1,319,162 | Comprehesive information on serial ports and programming? | What are some comprehesive sources on serial programming?
Ideally they would cover things like:
history of devices
current and future uses
how serial devices work
protocols
and, of course, how to program, preferably in C/C++
| This Wikipedia article covers a lot of it, and has links to other information, including
programming for Linux and WIN32
and
Serial Port Communication in VB.NET Programming
In addition to that, Wikibooks has a free book on Serial Programming
|
1,319,160 | 1,319,300 | Can a pointer be stored in std::mbstate_t type? | I'm writing an implementation of std::codecvt facet that uses iconv. This implementation stores a pointer to heap-allocated data in std::mbstate_t state argument.
Everything works fine, but is this code 64-bit compatible?
Is there a platform where a pointer size exceeds the size of std::mbstate_t?
| Doesn't the codecvt template take the state type as a parameter? Can you just use a pointer type there instead? I can't remember whether the various classes that use a codecvt place requirements on the state type.
Assuming that you can't just change the state type... on MSVC 2008, mbstate_t is typedefd as an int. The standard only requires that int be larger than 16 bits and no larger than a long, so it's not 64-bit safe. I guess you would need to store an index or key into some data structure instead of a pointer.
update:
The following compiles under VS2008, at least:
std::wstring const in = L"input";
size_t const buf_size = 256;
char* buf = new char[buf_size];
wchar_t const* char_next;
char * byte_next;
void* state = NULL;
typedef std::codecvt<wchar_t, char, void*> codecvt_t;
codecvt_t::result res =
std::use_facet<codecvt_t>(std::locale()).out(
state, in.c_str(), in.c_str() + in.length(),
char_next, &buf[0], &buf[buf_size], byte_next);
|
1,319,165 | 1,319,174 | Different destructor behavior between vc9 and gcc | The following code gives a different number of destructors when compiled on GCC and vc9. AFAIK when run on vc9 i get 5 destructors showing, which I understand. The + overloaded operator is called, and two object are created, when returned a temporary object is created. This makes destruction of 3 objects possible. When the overloaded = operator is called, one object is created and again a temporary one when returned. This sums it up to five destructs, not counting the three objects created at the start of main.
But when I compile on GCC I get 3.
Which leads me to guess that there isn't a temporary object created when the function is terminated and returned ? or a question about different behavior between compilers. I simply do not know, and some clarification would be nice.
#include <iostream>
using namespace std;
class planetCord {
double x, y, z;
public:
planetCord() { x = y = z = 0; }
planetCord(double j, double i, double k) { x = j; y = i; z = k; }
~planetCord() { cout << "destructing\n"; }
planetCord operator+(planetCord obj);
planetCord operator=(planetCord obj);
void show();
};
planetCord planetCord::operator +(planetCord obj) {
planetCord temp;
temp.x = x + obj.x;
temp.y = y + obj.y;
temp.z = z + obj.z;
return temp;
}
planetCord planetCord::operator =(planetCord obj) {
x = obj.x;
y = obj.y;
z = obj.z;
return *this;
}
void planetCord::show() {
cout << "x cordinates: " << x << "\n";
cout << "y cordinates: " << y << "\n";
cout << "z cordinates: " << z << "\n\n";
}
int main() {
planetCord jupiter(10, 20, 30);
planetCord saturn(50, 100, 200);
planetCord somewhereDark;
jupiter.show();
saturn.show();
somewhereDark.show();
somewhereDark = jupiter + saturn;
jupiter.show();
saturn.show();
somewhereDark.show();
return 0;
}
| GCC is implementing the "return value optimization" to skip temporaries. Set VC9 to Release mode and it'll probably do the same.
If GCC is really good, it is seeing that temp inside operator+ will be default-initialized, just like somewhereDark, and can just use a reference to somewhereDark directly if it tries to inline the function. Or it is seeing that the pass-by-value is useless and can instead pass-by-reference.
|
1,319,234 | 1,319,284 | Analyzing a crash in Windows: what does the error message tell us? | A small utility of mine that I made for personal use (written in C++) crashed randomly yesterday (I've used it roughly 100+ hours with no issues so far) and while I don't normally do this, I was feeling a bit adventurous and wanted to try and learn more about the problem. I decided to go into the Event Viewer and see what Windows had logged about the crash:
Faulting application StraightToM.exe, version 0.0.0.0, time stamp 0x4a873d19
Faulting module name : StraightToM.exe, version 0.0.0.0, time stamp 0x4a873d19
Exception code : 0xc0000005
Fault offset : 0x0002d160,
Faulting process id: 0x17b4
Faulting application start time: time 0x01ca238d9e6b48b9.
My question is, what do each of these things mean, and how would I use these to debug my program? Here's what I know so far: exception code describes the error, and 0xc0000005 is a memory access violation (tried to access memory it didn't own). I'm specifically interested in knowing more about the following:
What does the fault offset mean? Does that represent the location in the file where the error occured, or does it mean the assembly 'line' where the error occured? Knowing the fault offset, how would I use a program like OllyDbg to find the corresponding assembly code that caused the error? Or -- even better -- would it be possible to (easily) determine what line of code in the C++ source caused this error?
It's obvious that the time stamp corresponds to the 32-bit UNIX time at the time of the crash, but what does the 64-bit application start time mean? Why would it be 64-bits if the time stamp is 32?
Note that I'm primarily a C++ programmer, so while I know something about assembly, my knowledge of it is very limited. Additionally, this really isn't a serious problem that needs fixing (and is also not easily reproduced, given the nature of the program), I'm just using this more as an excuse to learn more about what these error messages mean. Most of the information about these crash logs that I've found online are usually aimed at the end-user, so they haven't helped me (as the programmer) very much.
Thanks in advance
| The 64-bit time stamp is the time application's primary thread was created in 100-nanosecond intervals since January 1, 1601 (UTC) (this is known as FILETIME). The 32-bit timestamp is indeed in time_t format (it tells the time the module was created and is stored in the module's header).
I'd say 0x0002d160 is an offset from the module's load address (it seems too low for an absolute address). Fire up Visual Studio, start the debugger, take a look at the "modules" debug window. Your exe file should be listed there. Find the address where the module is loaded, add 0x0002d160 to that address and take a look at the disassembly at the resulting address. Visual Studio shows source code intermixed with the assembly, you should have no problem figuring out what source line caused the problem.
|
1,319,260 | 1,319,323 | Where can I find a reference for the .vcproj file structure? | I looked on MSDN, couldn't find it.
I found an XML Schema for the .vcproj file, which is nice.
But what I really want is an explanation for each of the elements in the vcproj file, a reference.
The immediate question in front of me is, what is the significance of the UniqueIdentifier attribute in the element VisualStudioProject/Files/Filter ? Is the UUID for source files the same across projects? Or is it unique globally?
<VisualStudioProject>
...
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File ... />
...
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File ... />
...
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
<File ... />
...
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
But after I answer that one question I am sure I will have 10000 more. So I'd like a reference, that allows me to edit the .vcproj directly.
Can anyone suggest?
EDIT: Even if MS does not document it, each element does have a meaning. Does anyone know of a list or a summary?
| I suspect Microsoft is not intending to make the format a documented one. Microsoft has stated in the past that documented features and formats require in some cases an order of magnitude more work.
If the format is not documented, it's because Microsoft wants it that way. Any documentation will be through analysis and reverse-engineering.
|
1,319,327 | 1,319,454 | Binary Tree Node Fault | Here's the node definition:
struct node{
int data;
stuct node * left;
struct node * right;
};
What I am trying to do is list all the nodes that point to an ancestor node. After posting the wrong solution and taking advice from the answers, my new solution is:
Recursively go through the binary tree. Add the current node to an array of nodes and then check if the children of the current node point to any of the previous ancestor nodes.
The default case is the node being NULL. If that happens the function returns.
How it is supposed to work:
Adds the node to the array
Checks if the left child is NULL.
If not, it compares the child to each of the previous nodes.
If it finds a fault, it reports it.
If not, it calls the function with the child as the argument.
Repeat until finished.
(Does same for rhs of binary tree)
Questions:
Is an array the best thing to store
the nodes?
Does this work? for (i = 0; i < sizeof(arrOfNodes) / sizeof(node); i++)
Because the function is recursive,
the array and the array index can't
be initialized inside the function
(or can they be?) so should they be
global?
Would it be better to have two arrays?
(one for the LHS and one for the
RHS)
The code:
void findFault(node * root){
if (root == NULL){
return;
}
arrOfNodes[index++] == root; // array of nodes
if (root->left != NULL){
for (i = 0; i < sizeof(arrOfNodes) / sizeof(node); i++){
if (ar[i] == root->left){
printf("%d", root->left);
return;
}
}
findFault(root->left);
} else return;
if (root->right != NULL){
for (i = 0; i < sizeof(ar) / sizeof(node); i++){
if (ar[i] == root->right){
printf("%d", root->right);
return;
}
}
findFault(root->right);
} else return;
}
| Another way to accomplish this kind of check is to do a breadth-first sweep of the nodes, all the while keeping a vector of nodes you have visited already (which you can keep sorted by address). Each time you visit a node, assert it is not in the vector, then add it to the appropriate place to keep the visited list sorted.
The advantage to this kind of check is it can be performed without modifying the tree or node struct itself, though there is a bit of a performance penalty.
Notes:
An array would be a fine way to store the nodes. If you're avoiding STL (curious: why?) then you'll have to manage your own memory. Doable, but it's a brittle wheel to reinvent.
Your for loop check to get the size of the arrays will not work; if you use malloc/free or new/delete then you'll have to specify the size of the array you want beforehand; you should use that size instead of calculating it every time through the for loop.
The typical pattern for a recursive algorithm is to have an "outer" and "inner" function. The outer function is the one called by external code and does the initial setup, etc. The inner function is only called by the outser function, tends to have a more complicated parameter set (taking data set up by the outer function), and calls itself to perform the actual recursion.
You will need two arrays: one for the list of nodes you have visited, and one for the list of nodes you have yet to visit.
|
1,319,482 | 1,319,601 | Forward-declaring template pointer | Do I really need three statements, i.e. like this
class A;
template<class _T> class B;
typedef B<A> C;
to forward-declare a pointer of template type C, like so:
C* c = 0;
I was hoping to be able to conceal the classes A and B in my forward-declaration, is that even possible?
| Although not exactly the same, you could do this instead:
class C;
C* c = 0;
and then later, in the implementation file, after the header files for "A" and "B" have been included, define "C" like this:
class C : public B<A> {};
Using inheritance instead of a typedef should work if you only need to use the default constructor of B<A>.
|
1,319,876 | 1,319,884 | Weird C++ templating issues | So basically the assignment was we had to create a doubly linked list that's templated generically instead of locked to a single data type. I've tried compiling both with gcc and msvc and both compilers are giving me roughly the same errors so I'm assuming its just my bad coding and not the quirkyness of one compiler or the other.
Currently, I'm getting errors saying that my classes in linkList.h are not a template
../linkList.h:34: error: ‘llist’ is not a template type
../linkList.h:143: error: ‘iter’ is not a template type
../josephus.cpp:14: error: ‘llist’ is not a template
../josephus.cpp:14: error: aggregate ‘llist ppl’ has incomplete type
and cannot be defined ../josephus.cpp:15: error: ‘iter’ is not a
template
linkList.h
template<typename T>
class iter
{
public:
iter()
{
position = sentin;
container = sentin->payload;
}
T get() const
{
assert(position != sentin);
return position->payload;
}
void next()
{
position = position->next;
}
void previous()
{
position = position->prev;
}
bool equals(iter itr) const
{
return position == itr.position;
}
private:
node *position;
llist *container;
};
josephus.cpp
llist<int> ppl;
iter<int> pos;
int start = static_cast<int>(argv[1]) - 1;
int end = static_cast<int>(argv[2]) - 1;
Any help in this matter is much appreciated
| Your forward declaration says llist is a class:
class llist;
Then you say it is a template:
template<typename T>
class llist;
Similarly with iter.
I don't know how you could make it compilable easily. However, you can make node and iter 'inside' of llist.
|
1,320,401 | 1,320,417 | How to get Linux distribution name and version? | In Windows I read the registry key SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName to get the full name and version of the OS.
But in Linux, the code
struct utsname ver;
uname(&ver);
retVal = ver.sysname;
returns the string linux, not Ubuntu 9.04.
How can I get the Linux distribution name and version?
| Try:
cat /etc/lsb-release
You can also try
lsb_release -a
Or:
cat /proc/version
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.