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,953,610 | 1,953,630 | C++: decoupling of interface / implementation w/o using virtual functions? | I've been spoiled using Java in the last few months! I have a C++ project where I would like to decouple a class interface (.h file) from its implementation details. But the class's member fields have to be in its declaration, and it seems like I have this unavoidable dependency linking if I want to tweak the class's member fields.
I know one way to do this is using polymorphism + class inheritance (make the interface a base class, make the implementation a derived class), but if I remember right, that requires virtual functions, which are something I would like to avoid -- this is on a DSP and it's advantageous not to get too "C++-y" with things.
any suggestions?
| You want the PIMPL idiom.
|
1,953,621 | 1,953,708 | Reinterpret float vector as unsigned char array and back | I've searched and searched stackoverflow for the answer, but have not found what I needed.
I have a routine that takes an unsigned char array as a parameter in order to encode it as Base64. I would like to encode an STL float vector (vector) in Base64, and therefore would need to reinterpret the bytes in the float vector as an array of unsigned characters in order to pass it to the encode routine. I have tried a number of things from reinterpret and static casts, to mem copies, etc, but none of them seem to work (at least not the way I implemented them).
Likewise, I'll need to do the exact opposite when decoding the encoded data back to a float array. The decode routine will provide the decoded data as an unsigned char array, and I will need to reinterpret that array of bytes, converting it to a float vector again.
Here is a stripped down version of my C++ code to do the encoding:
std::string
EncodeBase64FloatVector( const vector<float>& p_vector )
{
unsigned char* sourceArray;
// SOMEHOW FILL THE sourceArray WITH THE FLOAT VECTOR DATA BITS!!
char* target;
size_t targetSize = p_vector.size() * sizeof(float);
target = new char[ targetSize ];
int result = EncodeBase64( sourceArray, floatArraySizeInUChars, target, targetSize );
string returnResult;
if( result != -1 )
{
returnResult = target;
}
delete target;
delete sourceArray;
return returnResult;
}
Any help would be greatly appreciated. Thanks.
Raymond.
| std::vector guarantees the data will be contiguous, and you can get a pointer to the first element in the vector by taking the address of the first element (assuming it's not empty).
typedef unsigned char byte;
std::vector<float> original_data;
...
if (!original_data.empty()) {
const float *p_floats = &(original_data[0]); // parens for clarity
Now, to treat that as an array of unsigned char, you use a reinterpret_cast:
const byte *p_bytes = reinterpret_cast<const byte *>(p_floats);
// pass p_bytes to your base-64 encoder
}
You might want to encode the length of the vector before the rest of the data, in order to make it easier to decode them.
CAUTION: You still have to worry about endianness and representation details. This will only work if you read back on the same platform (or a compatible one) that you wrote with.
|
1,953,631 | 1,953,781 | QFileDialog: adding extension automatically when saving file? | When using a QFileDialog to save a file and to specify the extension (like *.pdf) and the user types in a name without this extension, also the saved file hasn't this extension.
Example-Code:
QFileDialog fileDialog(this, "Choose file to save");
fileDialog.setNameFilter("PDF-Files (*.pdf)");
fileDialog.exec();
QFile pdfFile(fileDialog.selectedFiles().first());
now when the user enters "foo" as the name, the file will be saved as "foo", not as "foo.pdf". So the QFileDialog doesn't add the extension automatically. My question: How can I change this?
| You could use QFileDialog::setDefaultSuffix():
This property holds suffix added to the filename if no other suffix was specified.
This property specifies a string that will be added to the filename if it has no suffix already. The suffix is typically used to indicate the file type (e.g. "txt" indicates a text file).
|
1,953,639 | 1,953,738 | Is it safe to cast SOCKET to int under Win64? | I’m working on a Windows port of a POSIX C++ program.
The problem is that standard POSIX functions like accept() or bind() expect an ‘int’ as the first parameter while its WinSock counterparts use ‘SOCKET’.
When compiled for 32-bit everything is fine, because both are 32bit, but under Win64 SOCKET is 64 bit and int remains 32 bit and it generates a lot of compiler warning like this:
warning C4244: '=' : conversion from 'SOCKET' to 'int', possible loss of data
I tried to work around the issue by using a typedef:
#ifdef _WIN32
typedef SOCKET sock_t;
#else
typedef int sock_t;
#endif
and replacing ‘int’s with sock_t at the appropriate places.
This was fine until I reached a part of the code which calls OpenSSL APIs.
As it turned out OpenSSL uses ints for sockets even on Win64. That seemed really strange, so I started searching for an answer, but the only thing I found was an old post on the openssl-dev mailing list which refered to a comment e_os.h:
/*
* Even though sizeof(SOCKET) is 8, it's safe to cast it to int, because
* the value constitutes an index in per-process table of limited size
* and not a real pointer.
*/
So my question is:
is it really safe to cast SOCKET to int?
I’d like to see some kind of documentation which proves that values for SOCKET can't be larger than 2^32.
Thanks in advance!
Ryck
| This post seems by the to be repeating the information on kernel objects at msdn:
Kernel object handles are process specific. That is, a process must either create the object or open an existing object to obtain a kernel object handle. The per-process limit on kernel handles is 2^24.
The thread goes on to cite Windows Internals by Russinovich and Solomon as a source for the high bits being zero.
|
1,954,169 | 1,960,646 | Returning Garbage value c++ | I have a method that is suppose to return a garbage value if an item in a tree is not found. All I'm getting though is a runtime exception: "garbage is being used without being defined"
ItemType BstClass::rRetrieve(node* trav, KeyType key, bool& inTree)
{
if(trav == NULL)
{
inTree = false;
ItemType garbage;
return garbage - 1;
}
if(trav->data.key == key)
{
inTree = true;
return trav->data;
}
else if (key < trav->data.key)
return(rRetrieve(trav->left, key, inTree));
else
return(rRetrieve(trav->right, key, inTree));
}// end rRetrieve
Is there another way to do this? We were told to use
return garbage - 1;
| The answer depends on details of class ItemType which we don't have access to. Depending on what sort of operations you can do with ItemType and what sort of requirements you have about the 'garbage' value, you theoretically have a couple of choices.
Directly construct and return your 'garbage' value. Something like return ItemType(-1); or return ItemType(NULL); Specifically how you construct a garbage value depends on what constructors you have and their semantics.
Perhaps you shouldn't even care about the specific value. Since you have the inTree output variable indicating when you haven't found a value, then perhaps just return the default value return ItemType(); This is not as robust because the code is no longer redundant (i.e. for method 1, if the caller does not check inTree then hopefully using the 'garbage' will prevent the code from doing something wrong).
|
1,954,249 | 1,954,281 | Iterator and constant interator in C++ | Whats the difference?
I want to be able to see if an element is in a HashMap and I just found out that if I do h[element], it will return the default element if it is not found, and not null. How would I use the iterator find method to see if the element is there?
Thanks
| Assuming you're talking about STL and not some 3rd party library... m[key] doesn't just return the default object if key isn't in the map. It will create a new element in the map with that key and a default-constructed object as value.
You could use this:
map<string, int> mymap;
//add items to it
map<string, int>::iterator it = mymap.find("key");
if (it != myMap.end()) {
// 'key' exists; (it->second) is the corresponding int
}
Or if you don't need to get the object (you just want to know if it exists):
map<string, int> mymap;
//add items to it
if (mymap.count("key") == 1) {
// 'key' exists
}
|
1,954,404 | 1,954,479 | Program that modifes string inside its exe | I looking for example of program, that modifies a string inside its exe.
I work with C++, Visual Studio under Windows.
I searched working examples in Windows, but I can't find any working code.
I need simple code, that will ask user for string:
string strTest = "";
(if strTest != "")
{
cout << "Modified: " << strTest << endl;
}
cin >> strText;
And code should rewrite:
string strTest = "";
To string that typed user:
string strTest = "SomeStringFromUser";
How, in C++, do you modify a string (from string strTest = ""), to string, what a user typed? (for example to strTest = "foo")?
| When an EXE is running on a Windows machine, the exe file is held open as a CreateFileMapping object with pages marked either as READONLY or COPY_ON_WRITE.
So when the exe writes to itself, the file is not modified. It just creates a new page backed by the swap file. But since the file is kept open, no-one else can open the EXE file and write to it either.
Other than hacking the page protection to turn off COPY_ON_WRITE - Which I'm not sure is even possible. The only way I can think to do this would be to write a little program that runs after your exe finishes and opens the .exe file and writes to it.
I've gotta believe that whatever you are trying to do, there is a better way to go about it.
--- Later ----
Ok, I get it now. you are looking to watermark your exe. Here's the thing, this is pretty easy to do in your installer before the exe starts. But once the .exe is running it's MUCH harder to do.
Here's what I would do.
declare a global string variable of the necessary size, say const char g_szWatermark[100] = "";
Build my exe, then look in the map file to find the address of the variable within its segment (remember about C++ name decoration)
parse the EXE header to find the where the segment begins in the exe.
add these two numbers to get the location of the string within the exe file, give this number to my installer
have the installer run a little program that asks the user for information and then writes it into the .exe. Note: you have do do this before the exe runs or it won't work!
|
1,954,699 | 1,954,880 | Audio track in video file - C++ | My application is transforming an AVI video file into another AVI file. I use
the OpenCV library. Unfortunately videos created with OpenCV have no sound as the library does not support audio.
Is there any easy way to copy the audio track from one video file to another? Maybe FFmpeg?
My application is written in Visual C++.
| You can use FFmpeg. The easiest way would be to just use the command line tool to extract/reassemble. If you need your application to do it itself, looking into the sources for how they do it should help.
Alternatively, as you mention VC++, why not use DirectShow? It should not be too difficult to sink the audio into a file for extraction and later sink the video/audio mix into a file for composition.
|
1,954,718 | 1,954,733 | How to get the elements in a set in C++? | I am confused as to how to get the elements in the set. I think I have to use the iterator but how do I step through it?
| Replace type with, for example, int.. And var with the name of the set
for (set<type>::iterator i = var.begin(); i != var.end(); i++) {
type element = *i;
}
The best way though is to use boost::foreach. The code above would simply become:
BOOST_FOREACH(type element, var) {
/* Here you can use var */
}
You can also do #define foreach BOOST_FOREACH so that you can do this:
foreach(type element, var) {
/* Here you can use var */
}
For example:
foreach(int i, name_of_set) {
cout << i;
}
|
1,954,779 | 1,955,418 | Passing a pointer from C to assembly | I want to use "_test_and_set lock" assembly language implementation with atomic swap assembly instruction in my C/C++ program.
class LockImpl
{
public:
static void lockResource(DWORD resourceLock )
{
__asm
{
InUseLoop: mov eax, 0;0=In Use
xchg eax, resourceLock
cmp eax, 0
je InUseLoop
}
}
static void unLockResource(DWORD resourceLock )
{
__asm
{
mov resourceLock , 1
}
}
};
This works but there is a bug in here.
The problem is that i want to pass DWORD * resourceLock instead of DWORD resourceLock.
So question is that how to pass a pointer from C/C++ to assembly and get it back. ?
thanks in advance.
Regards,
-Jay.
P.S. this is done to avoid context switches between user space and kernel space.
| The main problems with the original version in the question is that it needs to use register indirect addressing and take a reference (or pointer parameter) rather than a by-value parameter for the lock DWORD.
Here's a working solution for Visual C++. EDIT: I have worked offline with the author and we have verified the code in this answer works in his test harness correctly.
But if you're using Windows, you should really by using the Interlocked API (i.e. InterlockedExchange).
Edit: As noted by CAF, lock xchg is not required because xchg automatically asserts a BusLock.
I also added a faster version that does a non-locking read before attempting to do the xchg. This significantly reduces BusLock contention on the memory interface. The algorithm can be sped up quite a bit more (in a contentious multithreaded case) by doing backoffs (yield then sleep) for locks held a long time. For the single-threaded-CPU case, using a OS lock that sleeps immediately on held-locks will be fastest.
class LockImpl
{
// This is a simple SpinLock
// 0 - in use / busy
// 1 - free / available
public:
static void lockResource(volatile DWORD &resourceLock )
{
__asm
{
mov ebx, resourceLock
InUseLoop:
mov eax, 0 ;0=In Use
xchg eax, [ebx]
cmp eax, 0
je InUseLoop
}
}
static void lockResource_FasterVersion(DWORD &resourceLock )
{
__asm
{
mov ebx, resourceLock
InUseLoop:
mov eax, [ebx] ;// Read without BusLock
cmp eax, 0
je InUseLoop ;// Retry Read if Busy
mov eax, 0
xchg eax, [ebx] ;// XCHG with BusLock
cmp eax, 0
je InUseLoop ;// Retry if Busy
}
}
static void unLockResource(volatile DWORD &resourceLock)
{
__asm
{
mov ebx, resourceLock
mov [ebx], 1
}
}
};
// A little testing code here
volatile DWORD aaa=1;
void test()
{
LockImpl::lockResource(aaa);
LockImpl::unLockResource(aaa);
}
|
1,954,853 | 1,955,253 | Does C++ programmer simulate features of Java? | As I read in Thinking in java,
Interface and inner class provide more
sophisiticated ways to organize and
control the objects in your
system. C++, for example, does not
contain such mechanisms, although the
clever programmer may simulate them.
Is it true that C++ programmer simluate features that java owns,e.g. interface and constraint themself not to step over the boundary,e.g. including non-static-final(non-const) data member within the simluated interface?
Are these features that Java provided natural way for developing software.So if C++ programmers could,they should code and think like a Java programmer?
EDIT: I know that every programming langauge have its own characteristics and its application area and the design of programming language is making tradeoffs.But what I want
to know is whether something java introduced for example interface,are better way to help/force programmer think throughly and produce good class design?so C++ programmers would like to simulate some of these features?
thanks.
| I have to say "good" Java design is almost uniformly terrible. I've never seen so much code duplication, ridiculous layered levels of abstraction (but almost never the abstractions that would have actually made sense in the situation) as when looking at Java code.
There are many good features of C++ that Java has no equivalent for.
Features that enable cleaner, more robust and more elegant designs.
C++ programmers should code like C++ programmers. For two very good reasons:
They have to respect the weaknesses and flaws of the language. Trying to pretend you're in a garbage-collected language when you're not is a recipe for disaster. And trying to implement GC-like semantics on top of a language like C++ is probably even worse.
And just as importantly, they should exploit every strength of the language. When you can get truly generic collection classes with zero overhead and a sophisticated iterator implementation, why on Earth would you throw it away? When you've got one single sorting function that works for any container and even more generally, for any sequence of objects of any type, why would you throw it away?
Since you mention interfaces as an example of a feature C++ programmers should emulate, there are two important counterpoints:
C++ has interfaces in the form of abstract classes. The semantics are slightly different, but they can be used to serve the same purpose.
C++ doesn't need interfaces as much, because it has templates and concepts relying on compile-time ducktyping. Rather than having every iterator derive from an IIterator interface, we can simply define how an "iterator" should behave, and write a class that supplies members with the same names. As long as it "looks like" an iterator, it can be used as an iterator. Template metaprogramming tricks even make it possible to adapt existing classes to "retrofit" them to support a concept they weren't designed for. For example, raw pointers (as taken from C) work as perfectly valid iterators, despite missing a few typedef members. And without even being classes in the first place.
Of course, C++ has plenty of weaknesses too. But it is not simply an "inferior Java". It is a different language. There is no need for C++ programmers to emulate Java features.
As I read in Thinking in java
Java books are rarely good sources of information about C++. ;)
|
1,954,858 | 1,955,470 | Sieve of Eratosthenes algorithm | I am currently reading "Programming: Principles and Practice Using C++", in Chapter 4 there is an exercise in which:
I need to make a program to calculate prime numbers between 1 and 100 using the Sieve of Eratosthenes algorithm.
This is the program I came up with:
#include <vector>
#include <iostream>
using namespace std;
//finds prime numbers using Sieve of Eratosthenes algorithm
vector<int> calc_primes(const int max);
int main()
{
const int max = 100;
vector<int> primes = calc_primes(max);
for(int i = 0; i < primes.size(); i++)
{
if(primes[i] != 0)
cout<<primes[i]<<endl;
}
return 0;
}
vector<int> calc_primes(const int max)
{
vector<int> primes;
for(int i = 2; i < max; i++)
{
primes.push_back(i);
}
for(int i = 0; i < primes.size(); i++)
{
if(!(primes[i] % 2) && primes[i] != 2)
primes[i] = 0;
else if(!(primes[i] % 3) && primes[i] != 3)
primes[i]= 0;
else if(!(primes[i] % 5) && primes[i] != 5)
primes[i]= 0;
else if(!(primes[i] % 7) && primes[i] != 7)
primes[i]= 0;
}
return primes;
}
Not the best or fastest, but I am still early in the book and don't know much about C++.
Now the problem, until max is not bigger than 500 all the values print on the console, if max > 500 not everything gets printed.
Am I doing something wrong?
P.S.: Also any constructive criticism would be greatly appreciated.
| I have no idea why you're not getting all the output, as it looks like you should get everything. What output are you missing?
The sieve is implemented wrongly. Something like
vector<int> sieve;
vector<int> primes;
for (int i = 1; i < max + 1; ++i)
sieve.push_back(i); // you'll learn more efficient ways to handle this later
sieve[0]=0;
for (int i = 2; i < max + 1; ++i) { // there are lots of brace styles, this is mine
if (sieve[i-1] != 0) {
primes.push_back(sieve[i-1]);
for (int j = 2 * sieve[i-1]; j < max + 1; j += sieve[i-1]) {
sieve[j-1] = 0;
}
}
}
would implement the sieve. (Code above written off the top of my head; not guaranteed to work or even compile. I don't think it's got anything not covered by the end of chapter 4.)
Return primes as usual, and print out the entire contents.
|
1,954,891 | 1,954,932 | How do i create a GNU Autotool Project in Eclipse CDT from existing C++ source code? | I have an existing C++ source code that is built using autotools and i wish to use in Eclipse CDT. I'm a beginner with Eclipse CDT. I've installed the Autotools plugin for eclipse but don't know how to create a project from existing code.
May you please guide me in the right direction so that i can create an eclipse project that uses autotools to build this source code?
Thanks
| Try to generate all makefiles and then try to import project to eclipse. I think when all Makefiles will exist, then would be no need to install any external plugin for autotools in eclipse IDE. It should work as it is.
|
1,955,037 | 1,955,075 | Why does C++ prohibit non-integral data member initialization at the point of definition? | class Interface {
public:
static const int i = 1;
static const double d = 1.0;
//! static const string *name = new string("Interface name");
virtual string getName() = 0;
}
Since C++ is a traditional truely compiled programming language,it could be easily convinced that it does allow object initialization(?).But why do C++ prohibit double initialization at the point of defintion?I see that g++ now support double initialization at the point of definition,but not msvc.
My question is,since it's easy to support primitive types - float/double initialization at the point of definition and it could make C++ programmer's life easier and happier with this convenient,why do C++ prohibit it?
P.S:
Reference - 9.2.4 section of C++ standard 2003.
A member-declarator can contain a
constant-initializer only if it
declares a static member (9.4) of
const integral or const enumeration
type, see 9.4.2.
| Because otherwise there would be a question of which compilation unit (e.g. object file) the value lived in. Every file that included a header with a class definition would try to create an object that would be assigned to the static value on creation, potentially causing unpredictable behavior.
It's not just assignment that doesn't work; you also still need to define the static value outside of the class declaration. e.g.
class Foo
{
static std::string s;
};
std::string Foo::s = "foo";
I don't know if that's a good reason, but I suspect that's the logic behind it, anyway.
|
1,955,074 | 1,955,109 | Virtual Methods or Function Pointers | When implementing polymorphic behavior in C++ one can either use a pure virtual method or one can use function pointers (or functors). For example an asynchronous callback can be implemented by:
Approach 1
class Callback
{
public:
Callback();
~Callback();
void go();
protected:
virtual void doGo() = 0;
};
//Constructor and Destructor
void Callback::go()
{
doGo();
}
So to use the callback here, you would need to override the doGo() method to call whatever function you want
Approach 2
typedef void (CallbackFunction*)(void*)
class Callback
{
public:
Callback(CallbackFunction* func, void* param);
~Callback();
void go();
private:
CallbackFunction* iFunc;
void* iParam;
};
Callback::Callback(CallbackFunction* func, void* param) :
iFunc(func),
iParam(param)
{}
//Destructor
void go()
{
(*iFunc)(iParam);
}
To use the callback method here you will need to create a function pointer to be called by the Callback object.
Approach 3
[This was added to the question by me (Andreas); it wasn't written by the original poster]
template <typename T>
class Callback
{
public:
Callback() {}
~Callback() {}
void go() {
T t; t();
}
};
class CallbackTest
{
public:
void operator()() { cout << "Test"; }
};
int main()
{
Callback<CallbackTest> test;
test.go();
}
What are the advantages and disadvantages of each implementation?
| Approach 1 (Virtual Function)
"+" The "correct way to do it in C++
"-" A new class must be created per callback
"-" Performance-wise an additional dereference through VF-Table compared to Function Pointer. Two indirect references compared to Functor solution.
Approach 2 (Class with Function Pointer)
"+" Can wrap a C-style function for C++ Callback Class
"+" Callback function can be changed after callback object is created
"-" Requires an indirect call. May be slower than functor method for callbacks that can be statically computed at compile-time.
Approach 3 (Class calling T functor)
"+" Possibly the fastest way to do it. No indirect call overhead and may be inlined completely.
"-" Requires an additional Functor class to be defined.
"-" Requires that callback is statically declared at compile-time.
FWIW, Function Pointers are not the same as Functors. Functors (in C++) are classes that are used to provide a function call which is typically operator().
Here is an example functor as well as a template function which utilizes a functor argument:
class TFunctor
{
public:
void operator()(const char *charstring)
{
printf(charstring);
}
};
template<class T> void CallFunctor(T& functor_arg,const char *charstring)
{
functor_arg(charstring);
};
int main()
{
TFunctor foo;
CallFunctor(foo,"hello world\n");
}
From a performance perspective, Virtual functions and Function Pointers both result in an indirect function call (i.e. through a register) although virtual functions require an additional load of the VFTABLE pointer prior to loading the function pointer. Using Functors (with a non-virtual call) as a callback are the highest performing method to use a parameter to template functions because they can be inlined and even if not inlined, do not generate an indirect call.
|
1,955,091 | 1,955,650 | Cross-platform C++ command line utility | I need to develop a Windows/Linux command line utility. The utility will talk to middleware that has a standard API on both platforms. I have done some cross-platform development before, on FreeBSD/Linux, which was considerably easier - and I had people in the group with experience that I could talk to.
At this point there is no one in my group who has tackled a Windows/Linux development project. I am looking for advice on how to best set it up. I'm kind of a newbie to C++ too, I have mostly developed C#/.Net GUI applications and Linux device driver level "stuff". Kind of a weird mix.
I was thinking that it would be best to define my own data types and not use either the Linux or the Windows defined types - keep the OS specific code in separate folders and include conditionally. That's kind of what we did for the Linux/BSD work. So it seemed like a good start.
One of the developers here is a big fan of Boost... another thought the TCLAP command line parser library was easier to use... Obviously everything has to be compatible with the licensing.
The code will be open sourced, but it is production code - so I don't want to be sloppy. What else should I be doing or looking for? Are there any best practices out there?
| Use standard C or C++ for most of the project. Only use platform specific functions when necessary. If possible, put those in a wrapper in isolated files so that the build (makefile) can substitute in the correct version for the appropriate platform.
Refrain from using #ifdef LINUX or #ifdef WINDOWS or similar conditional compilation. Those get really hard to debug and there are error prone when the keyword is not supplied to the compiler.
|
1,955,420 | 1,955,501 | Best & Fast way to find out if an ip address is reachable | I need the fastest way to see if an ip address is reachable. On each ip address theres a server listening on a specific port so let me know if your method is about to find if a server is listening on a port.
The reason for this is that suppose I have 10 ip addresses with 10 server listening on port 101 on each ip address. I want my client be able to find a Reachable ip address and connect to it as fast as he can(I don't want him to wait 30 seconds to find out if a ip address is reachable and then try the next ip address in the list)
May be it has to be done in treads simultaneously.
| While you can quickly determine that an IP is reachable, your problem is determining that an IP is not reachable. The reason why is that you can't always definitively determine that an IP is not reachable. While there are some conditions where you will be given an affirmative notice that the IP is not reachable, usually your code will just not hear an answer and after waiting for some amount of time, your code will assume the IP is not reachable.
The problem in deciding the timeout is network topology. If you have a large topology (such as the Internet), you will need a large timeout to deal with potentially high latencies if you try to connect to an IP that is 'far' away.
From your description, the best idea would be to try to connect to all servers at the same time and use the first one that accepts the connection. You can use threads or you can use non-blocking sockets. In a non-blocking connect, the connect call returns immediately and you then use select to efficiently determine when the connect call has completed (either successfully or with an error).
|
1,955,486 | 1,956,936 | Using Custom Events in QT4 | I have an app that has a progress bar & spawns a worker thread to do some work & report back progress. The dialog class overrides the customEvent method so that I can process events that are being passed to the gui thread via the worker thread. Before I was using a QThread derived class as the worker thread and I changed it to use ACE_Thread_Manager->spawn() with a static function for the worker.
The problem shows up when I run the app and press the button so the worker is spawned & starts doing work. When it sends the signal to increment the progress bar I get the following errors logged to std out.
QPixmap: It is not safe to use pixmaps outside the GUI thread
This seems to happen when the progressBar->setValue() is called. So it seems like the setting of the progress bar is happening in a different thread than the main gui thread. I'm unclear as to how that's possible. I'm under the impression that I have a main gui thread which has my gui & the customEvent method is on that same thread and the worker is on it's own thread. Is this assumption wrong? And is there any difference when using the QThread derived class versus the static run_svc method?
Any help would be appreciated. The code snippets for the customEvent handler, run_svc, and button handler code are below and the code is attached.
void MyDlgEx::customEvent(QEvent * e)
{
if (e->type() == IdNumOperations)
{
NumOperations* pEvt = static_cast<NumOperations*>(e);
_steps = 0;
cout << "Num Operations = " << pEvt->operations() << endl;
}
else if (e->type() == IdStep)
{
if (_steps % 10 == 0)
{
cout << "Step++ = " << _steps << endl;
}
_steps++;
_progressBar->setValue(_steps);
}
}
void* MyDlgEx::run_svc(void* args)
{
auto_ptr<ThreadArgs> thread_args(static_cast<ThreadArgs*>(args));
QApplication::sendEvent((QObject*)thread_args->m_pDlg, new NumOperations(300));
// does some work that takes time -- ommitted for clarity
// called in a loop
QApplication::sendEvent((QObject*)thread_args->m_pDlg, new Step());
QApplication::sendEvent((QObject*)thread_args->m_pDlg, new Completed());
return 0;
}
Button Handler
Commented out lines where where I used a QT class derived from QThread. Using ACE has to spawn the thread has uncovered this issue.
void MyDlgEx::btnShowProgress_clicked()
{
//_pProc = new ProcessThread(this);
//_pProc->run();
auto_ptr<ThreadArgs> thread_args(new ThreadArgs(this));
if (ACE_Thread_Manager::instance()->spawn(
MyDlgEx::run_svc,
static_cast<void*>(thread_args.get()),
THR_DETACHED | THR_SCOPE_SYSTEM) == -1)
cout << "Failed to spawn thread." << endl;
thread_args.release();
}
| Try calling QApplication::postEvent(...) instead of QApplication::sendEvent(). The docs say that sendEvent sends the event directly, meaning that it calls the customEvent() function directly from the other thread. postEvent() adds the event to the event queue where it can later be dispatched to customEvent() by the main GUI event loop.
Just because the customEvent() function is a member of an object created in the main GUI thread doesn't mean another thread cannot call the function. I believe that is what is happening when you call QApplication::sendEvent() from another thread.
|
1,955,661 | 1,955,670 | How can I call a method given only its name? | I'm trying to have method void run( string method ) which would run method in that class. For example:
class Foo {
public:
void run( string method ) {
// this method calls method *method* from this class
}
void bar() {
printf( "Function bar\n" );
}
void foo2() {
printf( "Function foo2\n" );
}
}
Foo foo;
int main( void ) {
foo.run( "bar" );
foo.run( "foo2" );
}
this would print:
Function bar
Function foo2
Thanks! :)
| You can create an std::map which maps strings to member function pointers, as long as all the functions you want to call have the same signature.
The map would be declared like:
std::map<std::string, void(Foo::*)()> function_map;
|
1,955,806 | 1,956,630 | How do I dynamically create controls with the same visual style as their parent? | I'm using Visual Studio 2005 (and win32 API in C++), and I have a window which was designed using the built-in dialog box editor.
At runtime, I want to be able to use CreateWindow() to add new controls to it. This works, however the controls I create all look really ugly. For the purpose of concreteness, the control I'm adding is a TabControl, when I add it using the built-in dialog box editor, the text in the tab labels looks nice. When I create it at runtime with CreateWindow(), the text is big and bold and looks out of place.
I found Using Windows XP Visual Styles on MSDN, which seems to describe stuff in the right area, but when I follow the instructions in there (embedding a manifest), the dynamically created control seems to be a newer style than the one used by the dialog box editor (the background of the tab control is a much lighter colour).
I also found the SetWindowTheme() function. I'm not quite sure how to use this function... I was hoping that I could use GetWindowTheme() on the window, and then pass the result of this into SetWindowTheme() to make them look the same, however GetWindowTheme() returns a HTHEME, and I have no idea what you can even do with these... you definitely can't pass them to SetWindowTheme() though.
| You really need to show us what you are currently doing (the code) if you want people to be able to help. This answer is going to be as much guesswork as a proper answer. so.
You probably don't need to muck around with the theme handle, Just having themes enabled for your app should be sufficient so long as you set the window styles for your controls correctly.
You need to make sure that you send a WM_SETFONT message to the windows you create. Lots of standard controls default to a really ugly backward compatible font until you give them a new one. In most cases you can probably use GetStockObject(DEFAULT_GUI_FONT) (or GetStockFont() if you include windowsx.h) as the font you send them. If you use a stock font then you don't have to keep track if it and free it later.
You also need to set the WS_EX_CLIENTEDGE or WS_EX_STATICEDGE style for most controls to get the newer display behavior. I think it's usually WS_EX_STATICEDGE when themes are turned on and WS_EX_CLIENTEDGE when they aren't. But you will need to play around with these. Use Spy++ to look around at various controls and see what styles they use and make sure that you match them. Leaving these styles off has the side effect of disabling theme drawing.
Note that these are _EX_ style flags, so you will need to use CreateWindowEx rather than CreateWindow
There may be other things as well, but try this and see how far it takes you.
|
1,955,885 | 1,955,902 | Is there an STL algorithm to find the last instance of a value in a sequence? | Using STL, I want to find the last instance of a certain value in a sequence.
This example will find the first instance of 0 in a vector of ints.
#include <algorithm>
#include <iterator>
#include <vector>
typedef std::vector<int> intvec;
intvec values;
// ... ints are added to values
intvec::const_iterator split = std::find(values.begin(), values.end(), 0);
Now I can use split to do things to the subranges begin() .. split and split .. end(). I want to do something similar, but with split set to the last instance of 0. My first instinct was to use reverse iterators.
intvec::const_iterator split = std::find(values.rbegin(), values.rend(), 0);
This doesn't work because split is the wrong type of iterator. So ...
intvec::const_reverse_iterator split = std::find(values.rbegin(), values.rend(), 0);
But the problem now is that I can't make "head" and "tail" ranges like begin(), split and split, end() because those aren't reverse iterators. Is there a way to convert the reverse iterator to the corresponding forward (or random access) iterator? Is there a better way to find the last instance of an element in the sequence so that I'm left with a compatible iterator?
|
But the problem now is that I can't
make "head" and "tail" ranges using
begin() and end() because those aren't
reverse iterators.
reverse_iterator::base() is what you are looking for - section new members on SGIs reverse_iterator description or here on cppreference.com
|
1,955,899 | 1,955,944 | Is ASSERT redundant? | ASSERT(pointer);
pointer->x;
In this code, the ASSERT seems to be redundant. If the pointer is NULL, pointer->x will fail anyway. Is my argument correct?
| The important (if not main) purpose of assertions is to document the invariants that are supposed to hold at certain point in the code. The fact that assert can also abort the program if the invariant is broken is just icing on the cake, albeit a very useful one. I'd say that in a typical program 90% of assertions are assertions that rather obviously can't fail and never will fail. In other words, assert is to a large degree a kind of formalized comment language. Formalized in a sense that these "comments" are written in the same language the rest of the code is written in (C/C++), as opposed to plain English.
In your code sample the assertion is there to tell you that the pointer is not supposed to be null here. That's why it is there. In that sense this assert is not redundant.
As far as the execution flow is concerned, assert is always redundant, which is why assertions are typically not compiled in the release version of the code. There's nothing to prevent you from keeping the assertions in release code as well, but normally it is done by introducing a special kind of "release assertion". In any case, making the main functionality of the code depend in the actions taken by an assertion is not a good programming practice. Assertions are supposed to be redundant, as far as the main functionality of the code is concerned.
|
1,956,472 | 1,956,490 | Does Visual Studio support data cache operations? | Reading through some great presentations on low latency computing. They had a reference to IBM's XL C/C++ compiler data cache operation __dcbt (Data Cache Block Touch) for their cell compiler. The operation loads a block of memory into L1 cache.
Does Visual Studio (or G++ or Intel) have similar functionality for Intel Processors? If so and the solution is platform specific (i.e. Windows or *nix only) please say so.
| Yes, Visual Studio supports all the SSE and MMX intrinsic operations. The cache control operations are briefly described here: http://www.tommesani.com/SSECacheabilityControl.html
and explained at length in Intel's instruction set reference.
Microsoft documents their intrinsics for cache control at MSDN. Although they look like functions, the compiler actually boils them down to the appropriate hardware instruction. Be sure to look at both their SSE1 and SSE2 cache control instructions, which they list under separate categories (see the expanding tree on the left side of their page).
The x86 equivalent to dcbt is _mm_prefetch. There is no direct equivalent to dcbz, but the closest analogue is _mm_stream_si128.
I believe GCC uses the same intrinsic names (as they are taken from the Intel compiler).
|
1,956,733 | 1,956,775 | How does std::string overload the assignment operator? | class mystring {
private:
string s;
public:
mystring(string ss) {
cout << "mystring : mystring() : " + s <<endl;
s = ss;
}
/*! mystring& operator=(const string ss) {
cout << "mystring : mystring& operator=(string) : " + s <<endl;
s = ss;
//! return this;
return (mystring&)this; // why COMPILE ERROR
} */
mystring operator=(const string ss) {
cout << "mystring : mystring operator=(string) : " + s <<endl;
s = ss;
return *this;
}
mystring operator=(const char ss[]) {
cout << "mystring : mystring operator=(char[]) : " << ss <<endl;
s = ss;
return *this;
}
};
mystring str1 = "abc"; // why COMPILE ERROR
mystring *str2 = new mystring("bcd");
So the questiones are
how to make a correct mystring& opeartor= overload?That is,how could I return a reference rather than a pointer?(could we tranfer between reference and pointer in C++?)
how to make a correct mystring operator= overload?I thought the source code would work fine,but it turns out I still could not assign const char[] to mystring as if I didn't overload the operator=.
thanks.
| What you need is a 'conversion' constructor that takes a const char*:
mystring( char const* ss) {
cout << "mystring : mystring(char*) ctor : " << ss <<endl;
s = ss;
}
The line you're having a problem with:
mystring str1 = "abc"; // why COMPILE ERROR
isn't really an assignment - it's an initializer.
|
1,956,747 | 1,956,765 | Memory leak in trivial stack implementation | I'm decently experienced with Python and Java, but I recently decided to learn C++. I decided to make a quick integer stack implementation, but it has a massive memory leak that I can't understand. When I pop the node, it doesn't seem to be releasing the memory even though I explicitly delete the old node upon poping it. When I run it, it uses 150mb of memory, but doesn't release any of it after I empty the stack. I would appreciate any help since this is my first foray into a language without garbage collection. This was compiled with gcc 4.3 on 64-bit Kubuntu.
//a trivial linked list based stack of integers
#include <iostream>
using namespace std;
class Node
{
private:
int num;
Node * next;
public:
Node(int data, Node * next);
int getData();
Node * getNext();
};
Node::Node(int data, Node * next_node)
{
num = data;
next = next_node;
}
inline int Node::getData()
{
return num;
}
inline Node* Node::getNext()
{
return next;
}
class Stack
{
private:
unsigned long int n;
Node * top;
public:
Stack(int first);
Stack();
void push(int data);
int pop();
int peek();
unsigned long int getSize();
void print();
void empty();
};
Stack::Stack(int first)
{
Node first_top (first, NULL);
top = &first_top;
n = 1;
}
Stack::Stack()
{
top = NULL;
n = 0;
}
void Stack::push(int data)
{
Node* old_top = top;
Node* new_top = new Node(data,old_top);
top = new_top;
n++;
}
int Stack::pop()
{
Node* old_top = top;
int ret_num = old_top->getData();
top = old_top->getNext();
delete old_top;
n--;
return ret_num;
}
inline int Stack::peek()
{
return top->getData();
}
inline unsigned long int Stack::getSize()
{
return n;
}
void Stack::print()
{
Node* current = top;
cout << "Stack: [";
for(unsigned long int i = 0; i<n-1; i++)
{
cout << current->getData() << ", ";
current = current->getNext();
}
cout << current->getData() << "]" << endl;
}
void Stack::empty()
{
unsigned long int upper = n;
for(unsigned long int i = 0; i<upper; i++)
{
this->pop();
}
}
Stack createStackRange(int start, int end, int step = 1)
{
Stack stack = Stack();
for(int i = start; i <= end; i+=step)
{
stack.push(i);
}
return stack;
}
int main()
{
Stack s = createStackRange(0,5e6);
cout << s.peek() << endl;
sleep(1);
cout << "emptying" <<endl;
s.empty();
cout << "emptied" <<endl;
cout << "The size of the stack is " << s.getSize()<<endl;
cout << "waiting..." << endl;
sleep(10);
return 0;
}
| How do you KNOW the memory isn't being released? The runtime library will manage allocations and may not release the memory back to the OS until the program terminates. If that's the case, the memory will be available for other allocations within your program during its execution.
However.... you seem to have other problems. My C++ is really rusty since I've been doing Java for 15 years, but in your Stack::Stack constructor you're allocating a Node instance on the system stack and then storing a reference to it in your "Stack". That Node instance goes out of scope when the constructor ends, leaving a dangling pointer.
|
1,956,764 | 1,956,801 | QMenu* << QAction* -- Help Me Write A Global QMenu Insertion Operator | If for no other reason than for my own amusement, I wish to write a global insertion operator so I can use the fancy code:
aQMenu << aQAction1 << aQAction2 << aQAction2 << seperator << aQAction3;
Perhaps you hate the syntax, but I would at least like to try my hand at using it. The problem is, that this is the first time I have tried to write insertion operator code, and I am stumped. The code for inserting the enum "seperator" to the QMenu* is easy, and I have that working, but I thought this code would work for inserting a QAction* to a QMenu*:
// does not compile: "must have an argument of class or enumerated type"
QMenu *operator<< (QMenu *menu, QAction *action)
{
menu->addAction(action);
return menu;
}
The compiler complains saying this function needs an argument of a class or enumerated type, which confounds me because the second parameter is of class type.. I have tried to rephrase this function using the ampersand, but I have not hit upon the way of writing it down properly. I have looked a lot at web examples, and thought it is about time to just as the question here.
I know that some coders out there will complain about me deviating from standard Qt syntax, but I am having fun overloading the operator<< with other classes as well. It just seems that the insertion operator works nicely here. What can I say -- it makes me happy.
| The compiler complains because all the parameters are pointers. Using a reference for the menu parameter of the operator it would look like this:
QMenu& operator<< (QMenu &menu, QAction *action) {
menu.addAction(action);
return menu;
}
Now this operator should work on menu objects. If you want to use it with a pointer to a menu you need to dereference that pointer when applying the new << operator:
QMenu *menu = new QMenu();
QAction *action1, *action2;
...
*menu << action1 << action2;
|
1,956,851 | 1,956,866 | How to convert double* to a double? | Any ideas for this typecasting problem?
Here's what I am trying to do. This is not the actual code:
LinkedList* angles;
double dblangle;
dblangle = (some function for angle calculation returning double value);
(double*)LinkedListCurrent(angles) = &double;
I hope you get the idea. The last line is causing the problem. Initially angles is void* type so I have to first convert it to double*.
| You use the unary * operator to dereference a pointer. Dereferencing a pointer means extracting the value pointed to, to get a value of the original type.
// Create a double value
double foo = 1.0;
// Create a pointer to that value
double *bar = &foo;
// Extract the value from that pointer
double baz = *bar;
edit 2: (deleted edit 1 as it was not relevant to your actual question, but was based on a miscommunication)
From your clarification, it looks like you are wondering how to set a value pointed to by a pointer that has been cast from a void * to a double *. In order to do this, we need to use the unary * on the left hand side of the assignment, in order to indicate that we want to write to the location pointed to by the pointer.
// Get a void * pointing to our double value.
void *vp = &foo;
// Now, set foo by manipulating vp. We need to cast it to a double *, and
// then dereference it using the * operator.
*(double *)vp = 2.0;
// And get the value. Again, we need to cast it, and dereference it.
printf("%F\n", *(double *)vp);
So, I'm assuming that your LinkedListCurrent is returning a void * pointing to some element in the linked list that you would like to update. In that case, you would need to do the following:
*(double*)LinkedListCurrent(angles) = dbangle;
This updated the value pointed to by the pointer returned from LinkedListCurrent to be equal to dbangle. I believe that is what you are trying to do.
If you are trying to update the pointer returned by LinkedListCurrent, you can't do that. The pointer has been copied into a temporary location for returning from the function. If you need to return a pointer that you can update, you would have to return a pointer to a pointer, and update the inner one.
My explanation above is based on what I believe you are trying to do, based on the example snippet you posted and some guesses I've made about the interface. If you want a better explanation, or if one of my assumptions was bad, you might want to try posting some actual code, any error messages you are getting, and a more detailed explanation of what you are trying to do. Showing the interface to the linked list data type would help to provide some context for what your question is about.
edit 3: As pointed out in the comments, you probably shouldn't be casting here anyhow; casts should be used as little as possible. You generally should use templated collection types, so your compiler can actually do typechecking for you. If you need to store heterogenous types in the same structure, they should generally share a superclass and have virtual methods to perform operations on them, and use dynamic_cast if you really need to cast a value to a particular type (as dynamic_cast can check at runtime that the type is correct).
|
1,956,876 | 1,956,891 | STL with a custom data type | What am I doing wrong?
#include <iostream>
#include <deque>
using namespace std;
struct mystruct {
int number1;
int number2;
};
int main() {
std::deque<mystruct> mydeque;
mydeque.number1.push_front(77);
return 0;
}
| push_front is a method of deque not the number1 of structure mystruct..
The right way is :
struct mystruct {
int number1;
int number2;
mystruct(int n1, int n2) : number1(n1), number2(n2){}
};
int main() {
std::deque<mystruct> mydeque;
mydeque.push_front(mystruct(77,88));
return 0;
}
|
1,957,076 | 1,957,149 | What is the best way to store double dimension vector in c++? | What is the best way to store double dimension vector in c++?
std::vector <std::vector <int> > m_vector(N, std::vector<int>(M));
...
int k = m_vector[i][j];
How else?
| The most efficient and most convenient at the same time is to use boost::multi_array.
|
1,957,141 | 1,960,320 | How to get the fractional part of the seconds in UTCTime using time.h | I want to get the system time including fractional part of the seconds. Is it possible in standard c (ANSI C)?
If not then tell me some libraries for window OS so that I make it possible. In Linux I have the following code with work fine for me.
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char buffer[30];
struct timeval tv;
time_t curtime;
gettimeofday(&tv, NULL);
curtime=tv.tv_sec;
strftime(buffer,30,"%m-%d-%Y %T.",localtime(&curtime));
printf("%s%ld\n",buffer,tv.tv_usec);
return 0;
}
Output is
12-25-2009 11:09:18.35443541
Kindly help me, how is it possible for window OS. IF ANSI C doesn't allow me.
| Standard C does not provide sub-second resolution timing.
POSIX does provide sub-second resolution timing - in fact, a number of different ways of doing it, including gettimeofday() which you show.
|
1,957,227 | 1,957,506 | Build automation by using platform specific project files or by using project generators? | There are some build systems that are able to generate platform specific project files like Visual Studio sln,vcproj,vcxproj files or XCode xcodeproj projects under OS X.
One of them is CMake but I found out that the support for this is quite limited, buggy and that is very hard to keep it updated with newer versions (like VS 2010).
Also, at least CMake, is missing support for property pages for Visual Studio and this makes harder to manage and change project wide configurations - like enabling/disabling Code Analysis for all projects.
An workaround to the above issue is to manually create project files for each platform - in my case there are only two, but even with more the number should not be so big.
It is quite easy to call the platform specific build commands into a generic build automation script. For example I used waf (Python) for automating this on few projects without using its own build part.
I would like to see what you would choose between: trying to repair/maintain project generators or keeping separated project files?
| Here's what we do, it might not be the best way, but it works really good for us and we found that it's not too hard to maintain, maybe you find it interesting.
Our main platform is windows, nearly all development is done in the VS IDE. For the other platforms (only some linux flavors for now) we use CMake exclusively. Basically we chose the "trying to repair/maintain project generators" way, but with Visual Studio project files as a starting point.
we use visual studio project files as a container for all files in a project
all build options are set in property sheets, each project has a standard set and eventually some extra sheets to pull in certain libraries etc
we have some simple scripts that allow to add/remove property sheets in one batch
all property sheets have a cmake counterpart; both are kept in the same directory, and if we update one, we update the counterpart as well, always. This is not done with a script, and I admit this is the 'complicated' part: although we realy heavily on macros, there are always options that are available on one platform but ot on the other.
we have a script that converts vcproj files into cmake files, it basically creates a cmake file which includes the corresponding cmake property sheets and which contains all source files the vcproj has.
last but not least I wrote a build server that runs on all platforms we use. It builds using msbuild or cmake, and it is the key in keeping this system working: each change we make triggers a build+tests on at least two machines, so we know immedeatly if all is stil fine.
We recently started using VS2010, and the migration only took about a day: first we let VS convert all our projects and property sheets, then we made some adjustments to the scripts to handle the new xml file formats.
Edit
sorry but I cannot post the scripts, company policy, hope you understand.
A bit of pseudocode is no problem though. Adding/removing property sheets in VS2008 project files goes like this:
foreach proj in projectfiles //list of vcproj files
foreach config in configuration //configurations eg 'Debug|Win32, Debug|x64'
f = OpenFile( proj );
//find start of Configuration element, then get what's after InheritedPropertySheets=
propsheets = GetPropSheetsForConfig( f, config );
propsheets = DoAction( action, args, propsheets ); //action is add/remove/.. with argument args
SetPropSheetsForConfig( f, propsheets );
For the CMakeLists files this is pretty much the same, except the script works on the 'include(..)' lines.
Convertig from vcproj to CMakeLists:
f = OpenFile( proj );
projname = GetProjectName( f );
sources = GetSourceFiles( f ); //all File/RelativePath elements under Filter 'Source Files'
sources = CheckFilter( sources ); //apply rules to include/exclude platform specific files
propsheets[] = GetPropSheetsForConfig( f, configs[] );
fout = CreateCMakeFromProj( proj ); //CMakeLists.txt in corresponding directory
WriteCMakeHeader( fout, projname );
WriteCMakeSources( sources );
WriteCMakeIncludes( configs[], propsheets[] ); //write includes, conditional on CMAKE_BUILD_TYPE
The build server is quite advanced material now, but in the beginning it was just a TCP listener:
await connection
get optional arguments (property sheets/action)
update of the repository
eventually run the batch script for the property sheets with the given arguments
start command line full rebuild + tests, capture output in file
parse file for lines containing 'error', mail results
|
1,957,308 | 4,165,764 | GDI fails conversion to indexed color with exact palette? | Summary
Using Windows GDI to convert 24-bit color to indexed color, it seems GDI chooses colors which are "close enough" even though there are exact matches in the supplied palette.
Can anyone confirm this as a GDI issue or am I making a mistake somewhere?
Maybe there's a "please check the whole palette for color matches" flag which I've failed to find?
Note: This is not about quantizing. The source is 24-bit but contains 256 or fewer colors so an exact palette is trivial to calculate. The problem is GDI doesn't use the full palette.
Workaround
I've worked around the problem by mapping the colors myself but I'd prefer to use GDI as it should be better optimized. Problem is, it seems to be "fast but wrong."
Detailed description
My source image is 24-bit but uses 256 (or fewer) colors. I generate an exact palette for it and ask GDI to transfer the image into an indexed bitmap using that palette. For some pixels GDI chooses similar, but not exact, colors even though there are exact colors elsewhere in the palette. This ruins smooth gradients.
This problem happens with:
SetDIBitsToDevice
StretchDIBits
BitBlt
StretchBlt
The problem does not happen with:
SetPixel or SetPixelV in a loop (incredibly slow!)
Using my own code to do the mapping
I've tested this on:
Windows 7 (NVidia hardware/drivers)
Windows Vista (ATI hardware/drivers)
Windows 2000 (VMware hardware/drivers)
In every test I get the same results. (Not just the wrong colours but always the same wrong colors.)
I don't think the issue is color management (ICM/ICC profiles/etc.) as most of the APIs say they don't use it, I've tried explicitly turning it off on the GDI DC as well as via the V5 bitmap header, and I don't think it would apply within my vanlilla-Win2k VM.
Test Project
Code for a simple Win32/GDI/VS2008 test project can be found here:
http://www.pretentiousname.com/data/GdiIndexColor.zip
The Test1 function within Win32UI.cpp is the actual test. It has two arrays of RGBQUADs, one the source image and the other the exact palette for it. It verifies that the palette really is exact and then asks GDI to convert the image using the APIs mentioned above, testing the result each time. For each test it'll tell you the first incorrect pixel's before & after colors, or tell you that all pixels are correct if it worked.
Thanks!
Thanks for reading my question! Sorry if it's the result of me doing something really dumb! :-)
| I ran into this exact same problem, eventually contacted Microsoft and provided them with a test case. In the test case I provided a gradient image that had 128 colors in a 24bit DIB, I then converted that to an 8bit DIB that was created with a color table containing all 128 colors from the 24bit image. After conversion, the 8 bit image had only used 65 of the 128 colors.
To sum up their response:
This is not a bug, GDI does use a close enough calculation when down converting the color depth of an image. This is not really documented anywhere, and the only way to insure all of the original colors will convert exactly is to manually manipulate the pixels yourself.
|
1,957,341 | 1,957,397 | newbie: Determinate CRT lib used by library | I'm developing application using VC++ 6.
I have a 3rd party DLL. This library compiled as Multithreaded DLL (/MD) and my application too.
But I fail to link:
LINK : warning LNK4075: ignoring /EDITANDCONTINUE due to /INCREMENTAL:NO specification
msvcprtd.lib(MSVCP60D.dll) : error LNK2005: "public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)" (??1?$basic_strin
g@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ) already defined in XXXApi.lib(CODbg.obj)
msvcprtd.lib(MSVCP60D.dll) : error LNK2005: "public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<c
har,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z) already defined in XXXApi.lib(Dictionary.obj)
../../Exes/win2k3_oracle11/XXX.exe : fatal error LNK1169: one or more multiply defined symbols found
Error executing link.exe.
From here I see that even though both 3rd library and my code compiled as /MD, there's possibly conflict with old/new iostream beining used.
Is there way to determinate what iostream library old/new is used by 3rd party library?
UPD:
The 3rd party lib is static and not dynamic as I thought before.
The lib is compiled /MD. Dependency Walker works wirh DLLs and not which Libs.
| There is dependency Walker, if you don't know this tool.
http://dependencywalker.com/
Drag and drop your DLL or exe on the main window. It will show all dependencies.
And if you want to link to a 3rd party DLL, all you need is a .lib made for that DLL.
If you don't have that .lib, you can always make one using lib.exe or polib.exe from pelles c tools.
polib is easier to use because you don't need to write a .def file.
http://www.smorgasbordet.com/pellesc/
I hope it helps for your question.
Edit: Do you have the source code for the .lib you are using?
|
1,957,480 | 1,957,542 | How to configure Vim for C++ development? | I'm learning C++ using Vim as an editor on Windows XP, however I found a issue that I have listed below.
I have downloaded and installed c.vim and it is a essential file, however when I start vim it shows the message C/C++ template file 'C:\Program Files\Vim\vimfiles\c-support/templates/Templates' does not exist or is not readable, How do i fix this problem?
How would i make vim compile a C++ STL file?
| For your first problem: I suspect that you didn't extract all the files in the archive (that c.vim came in). The c.vim documentation (README.csupport) says:
The subdirectories in the zip archive
cvim.zip mirror the directory
structure which is needed below the
local installation directory
$HOME/.vim/ for LINUX/UNIX
($VIM/vimfiles/ for Windows)
This means that you need to uncompress the entire archive as it is into your vimfiles directory.
There are some other steps to follow, detailed in the documentation.
As for your second issue: you need a Makefile to do that. If you have never done this before, I suggest using cmake to generate a Makefile. You will also need GNU tools for Windows; Cygwin or MinGW are the most popular choices. I haven't use them, it is easier to do all this on some *nix OS :).
When done, use :cd (if you are not in your working directory), and :make. Use :cl to list the compiler output, :cn to jump to the next error. There are some other useful commands for compiling. You might find these resources useful:
StackOverflow: Recommended plugins for C coding
Compiling from Vim
C editing with Vim
Also, I found the Nerd Commenter a very useful companion.
I found that Vim acts somewhat like alien on Windows; it is designed for an *nix-like operating system. I think it is possible to craft a similar environment for it, and use it mostly successfully, but it is so much easier to do on some linux, as it is "instantly home" there.
Anyway, if you wish to stick with Windows, I think you can find a way to accomplish what you want. Good luck.
|
1,957,495 | 1,957,525 | using C++ IO istream object to read is resulting in infinite loop | The below function results in infinite loop if a string is entered as input.
istream & inputFunc(istream &is)
{
int ival;
// read cin and test only for EOF; loop is executed even if there are other IO failures
while (cin >> ival, !cin.eof()) {
if (cin.bad()) // input stream is corrupted; bail out
throw runtime_error("IO stream corrupted");
if (cin.fail()) { // bad input
cerr<< "bad data, try again"; // warn the user
cin.clear(istream::failbit); // reset the stream
continue; // get next input
}
// ok to process ival
cout << "you entered: " << ival << endl;
}
}
The below function results in infinite loop if a string is entered as input.
OUTPUT:
try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data,
| You need to do two things:
1) clear state like here: cin.clear(istream::goodbit);
2) skip one char at a time after clearing the state, because you don't know where the next number starts:
char c;
cin >> c;
|
1,957,523 | 1,957,554 | interview questions - little help | i ran into thos quesiton in a google search.... they look pretty common, but i couldn't find a decent answer. any tips/links ?
1.Remove duplicates in array in O(n) without extra array
2.Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed.
| (1) isn't possible unless the array is presorted. The basic answer is to keep two pointers into the array, one walking forward searching for unequal elements, and one trailing pointer. When the forward pointer encounters an unequal element, it copies it into the trailing pointer and increments the trailing pointer.
(2) I don't have one handy. This sounds like a pretty terrible interview question. In most interpreted languages, a 0 byte (empty) source file is valid input, and prints out nothing.. that should count.
|
1,957,532 | 1,958,151 | negative precision values in ostream | This is more of a question of curiosity but does anyone know how negative precision values are handled in C++? For example:
double pi = 3.14159265;
cout.precision(-10);
cout.setf(ios::fixed, ios::floatfield);
cout << pi << endl;
I've tried this out and using GCC and it seems that the precision value is ignored but I was curious if there is some official line on what happens in this situation.
| Strangely (and wrongly, IMHO) the C++ Standard specifies a signed type (streamsize) as the parameter for precision, so it won't be converted to a large number. However, the standard is silent on what a negative number might mean, if anything.
|
1,957,581 | 1,998,974 | AntiAlias failed when draw string with certain angle in GDI+ | I am using the following code to draw Strings. In GDI+
Graphics tempFontGr(XXX);
Matrix* myPathMatrix = NULL;
myPathMatrix->Rotate(GetDCAngle(), MatrixOrderPrepend);
cantempFontGr.SetTransform(myPathMatrix);
tempFontGr.SetInterpolationMode(InterpolationModeHighQuality);
tempFontGr.SetSmoothingMode(SmoothingModeAntiAlias);
tempFontGr.DrawString(m_sWords, -1, tempFont.get(), tempRec, NULL, m_pBrush.get());
It is anoying that the string drawn have alias. Is there any method to remove the alias?
Many thanks!
| SetSmoothingMode applies to lines and curves. Try SetTextRenderingHint
|
1,957,593 | 1,957,606 | How to make an ambiguous call distinct in C++? | void outputString(const string &ss) {
cout << "outputString(const string& ) " + ss << endl;
}
void outputString(const string ss) {
cout << "outputString(const string ) " + ss << endl;
}
int main(void) {
//! outputString("ambigiousmethod");
const string constStr = "ambigiousmethod2";
//! outputString(constStr);
} ///:~
How to make distinct call?
EDIT: This piece of code could be compiled with g++ and MSVC.
thanks.
| C++ does not allow you to overload functions where the only difference in the function signature is that one takes an object and another takes reference to an object. So something like:
void foo(int);
and
void foo(int&);
is not allowed.
You need to change the number and/or the type of the parameter.
In your case the function that accepts a reference, you can make it accept a pointer, if you want to allow the function to change its argument.
|
1,957,605 | 1,957,658 | What is a good way of sending data as strings through sockets? | As there several ways to exchange data in the form of strings over sockets, such as:
using functions like:
sprintf() and sscanf()
snprintf() and sscanf()
printf() and strtof()
or converting to char and then passing it as an array
I would appreciate if you could suggest which way and why it is efficient and better than others, or if there is another way not mentioned above. At the moment I am using the simplest way, I mean sprintf() and sscanf() functions. But I read on the web that e.g. using snprintf() function is more safe.
| in C++ you can also use StringStream
stringstream ss;
int i = 1;
float f = "1.0";
char separtor = ';';
ss << i << separtor << f;
you can then extract the string with ss.str().c_str()
ss.str().c_str() will result in the case above with
"
1;1.0
"
|
1,957,644 | 1,957,791 | Which install system to pick when deploying to Windows and Linux? | My company is thinking of dumping InstallShield and move to something else, mainly because of the poor experience it had with it, mostly on Linux.
Our product is a C++ application (binaries, shared libraries) targeted at Windows and Linux (Red Hat).
The installer itself isn't required to do anything special, just dump some binaries and shared libraries and sometime execute an external process. Things like version upgrading through the installer isn't necessary, this is handled after the installer finishes.
I thought of suggesting using NSIS on Windows and RPM on Linux.
What are the recommended installer systems to use when deploying to Windows/Linux? Something that is cross platform to prevent maintaining two installers is a definite plus.
| For Windows I would definitively use NSIS. It's very lightweight, easy to code and very simple to understand. Using msis would just be a killer - it generates guid for every file so you can get upgrades for free and stuff but truth being said, you never end up using any of these.
Regarding Linux I would go for RPM and Deb. They're probably the two biggest packaging system so you'll be targeting most of the Linux users. I've never tried RPM but creating a Deb package is fairly straightforward.
|
1,957,665 | 1,959,879 | Magick++ animation generation via SDL pixel data | I'm trying to generate ImageMagick images from SDL pixel data. Here's what the GIF looks like so far. (This GIF is slower than the one below on purpose.)
http://www.starlon.net/images/combo.gif
Here's what it's supposed to look like. Notice in the above image that the pixels seem to be overlayed on top of other pixels.
http://www.starlon.net/images/combo2.gif
Here's where the GIF is actually created.
void DrvSDL::WriteGif() {
std::list<Magick::Image> gif;
for(std::list<Magick::Blob>::iterator it = image_.begin(); it != image_.end(); it++) {
Magick::Geometry geo(cols_ * pixels.x, rows_ * pixels.y);
Magick::Image image(*it, geo, 32, "RGB");
gif.push_back(image);
LCDError("image");
}
for_each(gif.begin(), gif.end(), Magick::animationDelayImage(ani_speed_));
Magick::writeImages(gif.begin(), gif.end(), gif_file_);
}
And here's where the Blob is packed.
image_.push_back(Magick::Blob(surface_->pixels, rows_ * pixels.y * surface_->pitch));
And here's how I initialize the SDL surface.
surface_ = SDL_SetVideoMode(cols_ * pixels.x, rows_ * pixels.y, 32, SDL_SWSURFACE);
| The top image is normally caused by a misaligned buffer. The SDL buffer is probably not DWORD aligned and the ImageMagick routines expect the buffer to be aligned on a DWORD. This is very common in bitmap processing. The popular image processing library - Leadtools, commonly, requires DWORD aligned data. This is mostly case with monochrome and 32 bit color but can be the case for any color depth.
What you need to do is write out a DWORD aligned bitmap from your SDL buffer or at least create a buffer that is DWORD aligned.
The ImageMagick API documentation may be able to help clarify this further.
|
1,957,667 | 1,976,371 | Why do C++ allow constant to be transformed to reference argument in another method? | void outputString(const string &ss) {
cout << "outputString(const string& ) " + ss << endl;
}
int main(void) {
outputString("constant tranformed to reference argument");
//! outputString(new string("abc")); new only return pointer to object
return 0;
}
Since its prohibited to create temporary object reference transforming to methods,this syntax should be useless but even make things more confusing.So why do C++ bother to support this kind of syntax?
EDIT:To be honest,I didn't understand your representation.Considering the above example,we would normally use void outputString(const string ss) instead of void outputString(const string &ss).I think the normal thing is 'pass by value' methods deal with the constants/variables and 'pass by reference' methods deal with variables only.The only reason we should use const type-id & instead of const type-id for constants is efficiency because 'pass by reference' methods only take the pointers(addresses) of the primitives constants/objects variables but 'pass by value' methods need to do the copy.
thanks.
| What are your alternatives?
void outputString(const string ss);
That will create a copy of any string passed, even if the type matches exactly: Overhead that's not really needed!
void outputString(string &ss);
That will allow changing the passed argument. We don't want to do that, and C++ does not allow us to pass a temporary anymore, to protect us from changing a temporary (where those changes are lost in the next moments anyway).
So, the way you have it fits on two sides: It allows us to pass non-temporary strings without copying them, and it allows us to pass temporary strings. And it protects us from trying to change the argument. Seems like a good compromise.
|
1,957,671 | 1,957,703 | Are there any tools for compile time checking of asserts in c++? | I was writing a function in c++ the other day and it occured to me the compiler could do a lot more to help me guard against mistakes. The essentials of my code were like this -
void method(SomeType* p)
{
assert(p != 0);
p->something();
}
And it was called like this
SomeType p = NULL;
if (SomeCondition)
{
p = some_real_value;
}
method(p);
Clearly it's possible for p to be null at run time and therefore the assertion on the method to fail in a debug build. My mistake.
However it seems possible that that the compiler could have caught this at compile time and issued a warning saying that it has detected it has found a possibility that the assertion could be violated.
Ok this is a simple case and it would be fairly simple for the compiler to spot that the pointer could be NULL at that point based on some flow analysis of the program and tracking of possible ranges of variables at each point.
I know that it would likely be too difficult to determine if many asserts would be violated but if even a small number times the compiler was able to tell me that I've written code where it's possible that an assertion is violated it would help make my programs that much safer.
I'm thinking that it would help with things like off by one errors in array indexing too for example inside a loop :-
assert(index >= 0 && index < array_size);
I'm thinking that in many cases the compiler could prove at compile that the index variable could possibly be outside of those bounds and issue a warning at compile time.
I realise that this is likely to be far too much work for a complier to do normally but perhaps there are some tools that can perform this kind of analysis? I've not been able to find anything with google but I was wondering if anything of this kind exists? Or is it just too hard to do well enough to be useful perhaps?
| Static analysis tools such as PC-lint may be able to detect these issues.
http://www.gimpel.com/html/pcl.htm
With respect to your first example though: my style is to favour references over pointer arguments or return values unless NULL is an acceptable value. This eliminates the need to assert arguments are != NULL.
|
1,957,761 | 1,958,156 | istream from file_descriptor_source (boost::iostreams) or file | I need to do something like this for my program's input:
stream input;
if (decompressed)
input.open(filepath);
else {
file_descriptor=_popen("decompressor "+filepath,"r");
input.open(file_descriptor);
}
input.read(...)
...
I can see one solution - to use _popen in both cases and just copy the file to stdout if it's already decompressed, but this doesn't seem very elegant.
Funny how difficult this is compared with C - I guess the standard library missed it. Now I am lost in the cryptic boost::iostreams documentation. Example code would be great if anyone knows how.
| Is this what you're after:
#include <cstdio>
#include <string>
#include <iostream>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
namespace io = boost::iostreams;
int main()
{
bool flag = false;
FILE* handle = 0;
if (flag)
{
handle = _popen("dir", "r");
}
else
{
handle = fopen ("main.cpp", "r");
}
io::stream_buffer<io::file_descriptor_source> fpstream (fileno(handle));
std::istream in (&fpstream);
std::string line;
while (in)
{
std::getline (in, line);
std::cout << line << std::endl;
}
return 0;
}
|
1,957,914 | 1,958,631 | Access violation when exporting a C++ class to Lua using LuaBind | I'm trying to export a simple class to Lua using LuaBind. I took the code from two sites which showed roughly the same way to do it, but it's still failing.
// Default headers
#include <iostream>
#include <string>
// Lua headers
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#include "luabind/luabind.hpp"
// Sample class
class NumberPrinter
{
public:
NumberPrinter( int number ) : m_number( number ) {}
void print() { std::cout << m_number << "\n"; }
private:
int m_number;
};
int main() {
// Create Lua state and load sample file
lua_State *luaState = lua_open();
luabind::open( luaState );
// Set up bind to number class
luabind::module( luaState ) [
luabind::class_<NumberPrinter>( "NumberPrinter" )
.def( luabind::constructor<int>() )
.def( "print", &NumberPrinter::print )
];
// Use the class in Lua
luaL_dostring( luaState,
"Print2000 = NumberPrinter(2000)\n"
"Print2000:print()\n"
);
// Clean up Lua state
lua_close( luaState );
getchar();
return 0;
}
When running that code, luabind::module causes the following runtime error and has no other information in debug mode:
Unhandled exception at 0x690008f5 in
Lua Playground.exe: 0xC0000005: Access
violation.
| I would encourage you to get this started with the binaries and sample VS2008 solution available from this website. It has the exact same sample code you are trying to run (minus the typos) and it worked well on my machine. If it still doesn't work, you'll need help from the Lua community. A minidump is probably required to help them diagnose this, just the exception message isn't enough.
|
1,957,945 | 1,958,008 | What's a good project tailored to learning strengths of Unix / Linux | I've been developing Microsoft Windows based applications (both desktop and web) for several years using C#, .net, & Visual Studio with a dash of C/C++ & WIN32. I want to broaden my horizons and try out developing in a *NIX environment e.g. using Vim & C++. I have limited UNIX experience from a few school projects.
I'm having trouble thinking of a good project to implement that might reveal some of UNIX's strengths and why some projects / fields prefer to use UNIX. I can think of several interesting things I'd like to build, but don't see compelling reasons to why implementing them in UNIX would be anything more than an exercise in using the UNIX environment.
What project / application could help a developer learn UNIX’s strengths?
Ideally, at some point while I"m coding this project, a light bulb will appear floating above my head, turn on by itself, and I will say "AHA!" when I realize some of the benefits of the UNIX environment compared to things I've done previously in Windows.
Just to be clear, I do not doubt that UNIX has its strengths, I'm just looking for an enticing starting point for Unix development.
| In UNIX/Linux "everything" is files. What about writing a piece of software that reads the disk device, understands the partition tables and file system?
Another possibility is to write a linux kernel module that does "something". It will sure give you a better understanding on how the linux kernel works. As an added benefit it sounds more hardcore than it really is ;)
A good starting point would be Kernel Newbies.
|
1,958,330 | 1,958,339 | Can Global Arrays in C++ Break Binary Compatibility? | Say a shared library contains the following lines:
const char* const arr[] =
{
"one",
"two",
"three"
};
1) Can an application link to this library and use the symbol "arr"?
2) Is binary compatibility broken if a new element is added to the definition?
3) How about if one of the string literals is changed?
4) Why (not)?
Cheers,
Luke
| 1) Yes
2) No
3) Not a problem
4) Why would you think otherwise?
|
1,958,369 | 1,958,455 | What is a good way to connect multiple clients to the server? | As there are several ways of connecting multiclients to the server such as: fork, select, threads, etc. I would be glad if you could describe which is better to connect multiple clients to the server?
| Take a look at the C10K page for a great overview and comparison of I/O frameworks and strategies.
|
1,958,453 | 1,958,649 | How to pass data from client to server when using gSOAP? | I am trying to exchange data between client and server using gSOAP. Actually, I succeeded to send data from client to server but not from server to client. So, could someone please explain what functions to use to pass data from server to client?
Thanks for your time and replies,
| The only way I know is by invoking with a function soap_call
See the example of calc in gsoap package
|
1,958,618 | 1,958,632 | What is the difference between soap_new() and soap_copy()? | What is the difference between:
thread_envs[i] = soap_copy(&env);
and
thread_envs[i] = soap_new();
Sould we use one of them or both?
| From the documentation:
struct soap *soap_new()
Allocates, initializes, and returns
a pointer to a runtime environment
struct soap *soap_copy(struct soap *soap)
Allocates a new runtime environment
and copies contents of the environment
such that the new environment does not
share any data with the original
environment
|
1,958,799 | 1,958,846 | Qt4 QNetworkManager Hangs | I'm trying to write an application using QNetworkManager. I have simplified the code down to the problem. The following code hangs, and I have no idea why:
main.cpp:
#include <QApplication>
#include "post.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
post("http://google.com/search", "q=test");
return app.exec();
}
post.h:
#ifndef _H_POST
#define _H_POST
#include <QNetworkAccessManager>
#include <QNetworkRequest>
class post : public QObject {
Q_OBJECT
public:
post(QString URL, QString data);
public slots:
void postFinished(QNetworkReply* reply);
protected:
QNetworkAccessManager *connection;
};
#endif
post.cpp:
#include <QApplication>
#include <QUrl>
#include "post.h"
post::post(QString URL, QString data) {
connection = new QNetworkAccessManager(this);
connect(connection, SIGNAL(finished(QNetworkReply*)), this, SLOT(postFinished(QNetworkReply*)));
connection->post(QNetworkRequest(QUrl(URL)), data.toAscii());
}
void post::postFinished(QNetworkReply*) {
qApp->exit(0);
}
Some Googling shows it may be because I have everything on one thread, but I have no idea how to change that in Qt... none of the network examples show this.
| I just tried it with the same results. The problem is that you are creating the post object by only calling the constructor. Since you are not specifying an object it is getting destroyed right away (to check this create a destructor and see when it gets called.)
try:
post p("http://google.com/search","q=test");
Then your slot gets called.
|
1,958,984 | 1,959,006 | C++ Templates and accessing namespaces | Let's say I'm using a templated class with something simple like:
template <class T>
class MyClass
I want to use elements from T's namespace, for example T could be string, and I wanted to use
T::const_iterator myIterator;
...or something like that. How do I achieve that?
Probably, it's either not possible or very simple, but I have no idea.
Thanks for answers!
| By default if T is a template parameter like in your example, the T::some_member is assumed not to name a type. You have to explicitly specify that it is, by prefixing it with typename:
typename T::const_iterator myIterator;
This resolves some parsing problems like in the following example
// multiplication, or declaration of a pointer?
T::const_iterator * myIterator;
So that the compiler can parse this even before instantiating the template, you have to give it a hand and use typename, including in those cases where it wouldn't be ambiguous, like in the first case above. The Template FAQ has more insight into this.
|
1,959,102 | 1,959,107 | Tickcount and milliseconds in C++ | How do I convert from TickCounts to Milliseconds?
this is what I used:
long int before = GetTickCount();
long int after = GetTickCount();
I want the difference of it in seconds.
| int seconds = (after - before) /1000;
|
1,959,237 | 1,959,250 | What is a fast efficient way to find an item? | Hi so I need some FAST way to search for a word in a dictionary.
The dictionary has like 500k words in it.
I am thinking about a using a hashmap where each bin has at most 1 word.
Ideas on how to do this or is there something better?
| A Trie is an efficient way to store dictionaries and has very fast lookup characteristics, O(m) where m is the length of the word.
A hashmap will be less efficient memory-wise but lookup time is a constant quantity for a perfect hash, O(1) lookup but you still spend O(m) calculating the hash. An imperfect hash will have a slower worst case than a Trie.
|
1,959,333 | 1,964,212 | In MFC how do I avoid dialog boxes from staying on top of my app window? | I have a dialog box based application (MFC - VS 2008). I have a list control on it. I pop up other dialog boxes, but I also want to be able to get back to the parent app dialog. I can get back to the parent app dilaog box, but the problem is that even if I click on it with the mouse it remains hidden behind the "child" windows.
I want it to come to the front.
There is probably something obvious I am doing wrong. What do I need to do to make the parent window come to the front when it has focus? I assume there is some property on the child dlg that should not be there, or something missing
I can post the rc code if that helps.
EDIT:
here is the .rc code for the two dialog boxes. The first is the mainframe window.
The second is launched with the following code:
HistogramWindow *histwind;
histwind = new HistogramWindow(this);
histwind->Create(IDD_DIALOG_HISTOGRAM);
histwind->ShowWindow(SW_SHOW);
IDD_DTHISTOGRAMDLG_DIALOG DIALOGEX 0, 0, 320, 200
STYLE DS_SETFONT | DS_FIXEDSYS | WS_MINIMIZEBOX | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME
EXSTYLE WS_EX_APPWINDOW
CAPTION "dtHistogramDlg"
FONT 8, "MS Shell Dlg", 0, 0, 0x1
BEGIN
DEFPUSHBUTTON "OK",IDOK,209,179,50,14,NOT WS_VISIBLE
PUSHBUTTON "Cancel",IDCANCEL,263,179,50,14,NOT WS_VISIBLE
CONTROL "",IDC_LIST_SYMBOL_SETS,"SysListView32",LVS_ALIGNLEFT | WS_BORDER | WS_TABSTOP,7,7,60,50
END
IDD_DIALOG_HISTOGRAM DIALOGEX 0, 0, 317, 184
STYLE DS_SETFONT | DS_FIXEDSYS | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME
EXSTYLE WS_EX_APPWINDOW
CAPTION "Histogram"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
DEFPUSHBUTTON "OK",IDOK,205,163,50,14,NOT WS_VISIBLE
PUSHBUTTON "Cancel",IDCANCEL,260,163,50,14,NOT WS_VISIBLE
CONTROL "",IDC_STATIC,"Static",SS_BLACKFRAME,7,7,20,20
END
| A friend of mine suggested the following (and it work)
set the style of the 2nd dlg to WS_CHILD
histwind->SetParent( NULL );
histwind->ModifyStyle( WS_CHILD, 0 );
This works, however thereis a strange behavior when i move the parent window from behind a child. While moving the window is hidden until I release the mouse.
This will work for now.
thanks to all who helped.
|
1,959,418 | 1,959,444 | how to cache a lambda in c++0x? | I'm trying to work with lambda's in C++ after having used them a great deal in C#. I currently have a boost tuple (this is the really simplified version).
typedef shared_ptr<Foo> (*StringFooCreator)(std::string, int, bool)
typedef tuple<StringFooCreator> FooTuple
I then load a function in the global namespace into my FooTuple. Ideally, I would like to replace this with a lambda.
tuplearray[i] = FooTuple([](string bar, int rc, bool eom) -> {return shared_ptr<Foo>(new Foo(bar, rc, eom));});
I can't figure out what the function signature should be for the lambda tuple. Its obviously not a function pointer, but I can't figure out what a lambda's signature should be. The resources for lambda's are all pretty thin right now. I realize C++0x is in flux at the moment, but I was curious about how to get this to work. I also realize there are simpler ways to do this, but I'm just playing around with C++0x. I am using the Intel 11.1 compiler.
| The -> operator sets the return type of the lambda, in the case of no return type it can be omitted. Also, if it can be inferred by the compiler you can omit the return type. Like Terry said, you can't assign a lambda to a function pointer (GCC improperly allows this conversion) but you can use std::function.
This code works on GCC and VC10 (remove tr1/ from the includes for VC):
#include <tr1/tuple>
#include <tr1/functional>
#include <tr1/memory>
using namespace std;
using namespace std::tr1;
class Foo{};
typedef function<shared_ptr<Foo>(string, int, bool)> StringFooCreator;
typedef tuple<StringFooCreator> FooTuple;
int main() {
FooTuple f(
[](string bar, int rc, bool eom) {
return make_shared<Foo>();
}
);
shared_ptr<Foo> pf = get<0>(f)("blah", 3, true);
}
|
1,959,438 | 1,959,508 | Order preserving minimal perfect hash functions | I want to implement an OPMPH function for the words in a dictionary in C++. How do I do it?
Thanks!
| Have you looked at these papers?
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.84.4018&rep=rep1&type=pdf
http://dx.doi.org/10.1016/0020-0190(92)90220-P (the short form link that leads to a very long link at http://www.sciencedirect.com/)
http://eprints.cs.vt.edu/archive/00000248/01/TR-91-01.pdf
|
1,959,555 | 1,959,588 | rectangle disappearing with SDL | So I'm simply trying to make a red 10 x 10 box move vertically back and forth. I compile and run my program and the red box appears starts moving down, then just disappears after it hits the edge of the screen. I used some cout << statements that tell me when the functions are being called and they are all being called when they are supposed to. Even when the box can't be seen the functions are properly being called.
My main loop
while(running)
{
myScreen->Clear();
boxes.Move();
boxes.Draw();
myScreen->Flip();
........
My draw() function
SDL_Color red;
red.r = 255;
red.g = 0;
red.b = 0;
if( SDL_FillRect( my_screen->Get_screen(), &start_dest, SDL_MapRGB(
my_screen->Get_pixel_format(), red.r, red.g, red.b ) ) == -1 )`
cout << "Fill rect in Draw(); failed\n";
My Move() function
start_dest.y += y_step;
if ( start_dest.y >= my_screen->Get_height() )
{
cout << "start_dest.y >= screen height\n";
start_dest.y = my_screen->Get_height();
y_step = -y_step;
}
if ( start_dest.y <= 0 )
{
cout << "start_dest.y <= 0\n";
start_dest.y = 0;
y_step = -y_step;
}
I have been trying to find this bug forever. just leave a comment if anyone wants to see more code. Thanks
| There isn't enough information to give conclusive answer, but here's a hint.
From my experience with SDL, SDL functions can modify your Rect structure when called, especially when rect is partly off-screen. Make sure you set all its properties (x,y,width,height) before each SDL function that uses the rectangle.
|
1,959,581 | 1,959,737 | client-server design | i want to develop a pretty basic client-server program.
one software reads xml (or any data) and send it to the server who in turn will manipulate it a little bit and eventually will write it to the disk.
the thing is that if i have many xml files on disk (on my client side), i want to open multiple connection to the server , and not doint one by one.
my first question is : let's say i have one thread who keeps all the files handles and waitformultipleobjects on them, so it will know when one of them is ready to be read from disk. and for every file i have an appropriate socket who suppose to send that specifi file to the server. for the socket i can use the select function to know which sockets are ready for sent. but is there way to know that both the file and the appropraite socket are ready to be sent ?
second, is there a more efficient way to design the client, cuase on my current design i'm using just one thread which on multi processor computer is rather not efficient enough.
(though i'm sure is till better then laucning new thread for every socket connection)
third, for the server i read about the reactor pattern. it seems appropriate but still ,like my second question, seems not effient enought while using one thread.
maybe i can use something with completion ports ? think they are pretty efficient but never really used them, so don't know exactly how.
any answers and general suggestion would be great.
| Take a look at boost::asio it uses a proactor pattern (see the docs) that basically uses the OS wait operations (waitforsingle/multiple,select,epoll, etc...) to make very efficient use of a single thread in a system like you're looking at implementing.
asio can read/write files as well as sockets. You could sumbit an async read for the file using asio, it would call your callback on completion then you would submit that read buffer as an async write to the socket. Asio would take care of delivering all async writes buffers as the socket completed each pending write operation.
Each of these operations is done asynchronously so the thread is only really busy to initiate reads or writes, sitting idle the rest of the time.
|
1,959,682 | 1,959,696 | If the only thing that changes is the constructor should I still derive? | I have a class that has everything already implemented but its initialization process is different for every child class.
Is there a better idiom to replace the ctor? Is there something more generic/dynamic that I should use?
| Or use static factory methods. This allows you to have different names for the "constructor" that shows the intent.
|
1,959,927 | 1,960,051 | How to see hash items in C++? | Hi so I have the following code and I want to be able to insert words into it and be able to see the stuff I put into the hash by printing it out. Here's what I have:
#include <iostream>
#include <fstream>
#include <string>
#include <hash_map>
#include <set>
#include <windows.h>
using namespace std;
struct nlist{
struct nlist *next;
char *name;
char *defn;
};
#define HASHSIZE 101
static struct nlist *hashtab[HASHSIZE];
unsigned hash(const char *s)
{
unsigned hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31 * hashval;
return hashval % HASHSIZE;
}
struct nlist *lookup(const char *s)
{
struct nlist *np;
for (np = hashtab[hash(s)]; np != NULL; np = np->next)
if (strcmp(s,np -> name) == 0)
return np;
return NULL;
}
struct nlist *install(const char *name, const char *defn)
{
struct nlist *np;
unsigned hashval;
if ((np = lookup(name)) == NULL){
np = (struct nlist *) malloc (sizeof(*np));
if (np == NULL || (np -> name = strdup(name)) == NULL)
return NULL;
hashval = hash(name);
np->next = hashtab[hashval];
hashtab[hashval] = np;
}
else{
free((void *) np->defn);
}
if ((np -> defn = strdup(defn)) == NULL)
return NULL;
return np;
}
int main(){
cout << "yo";
string inline1;
while (1){
getline(cin, inline1);
if (inline1 == "hash"){
getline(cin, inline1);
cout << hash(inline1.c_str()) << '\n';
}
else if (inline1 == "lookup"){
getline(cin, inline1);
cout << lookup(inline1.c_str()) << '\n';
}
else if (inline1 == "install"){
getline(cin, inline1);
string inline2;
getline(cin, inline2);
cout << install(inline1.c_str(), inline2.c_str()) << '\n';
}
}
}
| The problem you are having here is that you are printing out the pointer to the nlist item that you have looked up, rather than the value of the defn string within that item.
In your main loop, you have the following code:
else if (inline1 == "lookup"){
getline(cin, inline1);
cout << lookup(inline1.c_str()) << '\n';
}
What you probably want instead is:
else if (inline1 == "lookup"){
getline(cin, inline1);
cout << lookup(inline1.c_str())->defn << '\n';
}
|
1,960,075 | 1,960,117 | Boost Filesystem createdirectories on Linux replacing "/" with "\" | When using Boost Filesystem's createdirectory (and createdirectories) function in the following example, "/" is being replaced with "\".
boost::filesystem::path path ("/data/configSet");
boost::filesystem::create_directory(path);
This code snipped produces a directory called "data\configSet", instead of creating a subdirectory of "configSet" inside "data". The same problem occurs using createdirectories();
This issue does not occur when the code is executed on a Windows system. I am currently testing on Linux using Ubuntu 9.10
| It looks like for some reason boost::filesystem thinks that you are on Windows, not Linux, and thus is using Windows style pathnames (separated by \). Can you post a bit more information about how you are building Boost and how you're including the headers? Are you perhaps building a Windows version of Boost on Linux?
edit: I have tried setting myself up in a configuration as close to yours as possible. Ubuntu 9.10, libboost1.40-all-dev installed. When I compile and run the following program, it works as expected, creating a directory named configSet in /data.
#include <boost/filesystem.hpp>
int main() {
boost::filesystem::path p("/data/configSet");
boost::filesystem::create_directory(p);
return 0;
}
Can you try compiling and running that program, with the following commands, and see if it gives you different results?
$ g++ -o boost-filesystem -lboost_filesystem boost-filesystem.cpp
$ ./boost-filesystem
|
1,960,243 | 1,960,367 | Threading on bootloader | Where can I find resources/tutorials on how to implement threads on a x86 architecture bootloader... lets say I want to load resources in the background while displaying a progress bar..
| That is a very unusual question...so allow me to provide my opinion on it...
Bootloaders, are really a limited bunch of assembly code, 464 bytes to be exact, 64 bytes for partition information and a final two bytes for the magic marker to indicate the end of the boot loader, that is 512bytes in total.
Bootloaders such as Grub can get around this limitation by implementing a two phase bootloader, the first phase is the 512 bytes as mentioned, then the second phase is loaded in which further options etc are performed.
Generally, the bootloader code is in 16 bit assembly because the original BIOS code is 16bit code, and that is what the processor 386 upwards to the modern processor today, boots up in, real mode.
Using a two phase bootloader, the first 512bytes is 16bit, then the second phase switches the processor into 32bit mode, setting up the registers and gate selectors in preparation, which in turn then jumps to the entry code of the actual program to do the booting up - this is taking into account in having to read from a specific location on disk or reading a configuration file which contains data on where the boot code is stored.
Implmenting threads in 32bit mode is something that will be tricky to produce as you will have to create some kind of a scheduler in Assembly (Since you mentioned implement threads on a x86 architecture bootloader).
You may get around this by implementing a second phase part of the bootloader using C (but the tricky bit is that no standard libraries are to be used as the runtime environment has not been set up yet!)
You may be better by using Grub or even check out this Open source BIOS bootloaders here, nowadays, bios's are flashable so you may be able to get an EFI (Extensible Firmware Interface here) which is pure 32bit bios - this will be dependant on your processor. There is also another website here which might provide further info here.
The progress bar on boot, is unfortunately written in C/C++ which (already, in 32bit, environment set up, tasking scheduler set up, threads included, virtual memory manager loaded etc - this is the kernel level, after boot up procedure is complete), in which is a process where a thread has been created, that runs in the background illustrating hardware detection/further environment set up etc by using a progress bar as a way to tell the user to "wait, the system is loading"
|
1,960,369 | 1,960,833 | Is shared ownership of objects a sign of bad design? | Background: When reading Dr. Stroustrup's papers and FAQs, I notice some strong "opinions" and great advices from legendary CS scientist and programmer. One of them is about shared_ptr in C++0x. He starts explaining about shared_ptr and how it represents shared ownership of the pointed object. At the last line, he says and I quote:
. A shared_ptr represents shared
ownership but shared ownership isn't
my ideal: It is better if an object
has a definite owner and a definite,
predictable lifespan.
My Question: To what extent does RAII substitute other design patterns like Garbage Collection? I am assuming that manual memory management is not used to represent shared ownership in the system.
|
To what extent does RAII substitute other design patterns like Garbage Collection? I am assuming that manual memory management is not used to represent shared ownership in the system
Hmm, with GC, you don't really have to think about ownership. The object stays around as long as anyone needs it. Shared ownership is the default and the only choice.
And of course, everything can be done with shared ownership. But it sometimes leads to very clumsy code, because you can't control or limit the lifetime of an object. You have to use C#'s using blocks, or try/finally with close/dispose calls in the finally clause to ensure that the object gets cleaned up when it goes out of scope.
In those cases, RAII is a much better fit: When the object goes out of scope, all the cleanup should happen automatically.
RAII replaces GC to a large extent. 99% of the time, shared ownership isn't really what you want ideally. It is an acceptable compromise, in exchange for saving a lot of headaches by getting a garbage collector, but it doesn't really match what you want. You want the resource to die at some point. Not before, and not after. When RAII is an option, it leads to more elegant, concise and robust code in those cases.
RAII is not perfect though. Mainly because it doesn't deal that well with the occasional case where you just don't know the lifetime of an object. It has to stay around for a long while, as long as anyone uses it. But you don't want to keep it around forever (or as long as the scope surrounding all the clients, which might just be the entirety of the main function).
In those cases, C++ users have to "downgrade" to shared ownership semantics, usually implemented by reference-counting through shared_ptr. And in that case, a GC wins out. It can implement shared ownership much more robustly (able to handle cycles, for example), and more efficiently (the amortized cost of ref counting is huge compared to a decent GC)
Ideally, I'd like to see both in a language. Most of the time, I want RAII, but occasionally, I have a resource I'd just like to throw into the air and not worry about when or where it's going to land, and just trust that it'll get cleaned up when it's safe to do so.
|
1,960,543 | 1,960,573 | strange SDL memory usage depending on bits per pixel | I have a very simple SDL program that uses only 1MB of memory with 32 bits per pixel, 2.4MB with 24 bits per pixel, 1.9MB with 16 bits per pixel, and 1.4MB with 8 bits per pixel. what is with this strange memory usage? why does the most bits per pixel take up the least amount of memory?
C++
GCC
thanks
| Perhaps internal conversion buffers. If your surface bpp doesn't match your hardware surface you may need to store the full buffer in memory, whereas SDL may be able to use that surface directly otherwise. This is just a guess offhand.
But looking at a process in top or task manager may not be the best way to get a handle on what's using memory. If you're on Linux you can try a tool such as valgrind to get a very good idea of where memory is going.
|
1,960,619 | 1,960,629 | Two calls to destructor | For the following code:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
struct Test
{
string Str;
Test(const string s) :Str(s)
{
cout<<Str<<" Test() "<<this<<endl;
}
~Test()
{
cout<<Str<<" ~Test() "<<this<<endl;
}
};
struct TestWrapper
{
vector<Test> vObj;
TestWrapper(const string s)
{
cout<<"TestWrapper() "<<this<<endl;
vObj.push_back(s);
}
~TestWrapper()
{
cout<<"~TestWrapper() "<<this<<endl;
}
};
int main ()
{
TestWrapper obj("ABC");
}
This was the output that I got on my MSVC++ compiler:
TestWrapper() 0018F854
ABC Test() 0018F634
ABC ~Test() 0018F634
~TestWrapper() 0018F854
ABC ~Test() 003D8490
Why there are two calls to Test destructor although only one Test object is being created. Is there any temporary object created in between? If yes, why there is no call to its corresponding constructor?
Am I missing something?
| Your output doesn't account for the Test's copy constructor, which std::vector is apt to use.
The Test object you see get created is the temporary passed to push_back(), not the one actually in the vector.
|
1,960,740 | 1,960,751 | What is nothrow delete in C++? | This MSDN page mentions that there're nothrow versions of new and delete. nothrow new is quite a known thing - returns null instead of throwing an exception if memory allocation fails. But what is nothrow delete mentioned there?
| They are probably referring to the raw memory allocation functions operator new and operator delete.
When you invoke a specific version of placement new-expression (i.e. new-expression with extra parameters; they all are officially referred to as placement forms of new) and the memory allocation function operator new succeeds, but the process fails later for some other reason (the constructor throws), the implementation has to abort the process and automatically release the allocated memory by calling the appropriate version of operator delete. "Appropriate version" of operator delete in this case is the version that has the same set of parameters as the operator new function previously used for memory allocation (except for the very first parameter, of course).
This applies to nothrow version of operator new as well. When you use a nothrow form of new-expression, it calls a nothrow version of operator new and then constructs the object in the allocated memory. If the constructor fails (throws), the implementation of the new-expression releases allocated memory with the help of nothrow version of operator delete. This is basically the only reason for this version of operator delete to exist.
In other words, the nothrow version of operator delete exists for very specific internal purposes. You should not normally want to call it yourself and, maybe, you don't really need to know about its existence. However, it is worth knowing that for the reasons described above, whenever you create your own version of operator new with extra parameters, it is always a good idea to provide a matching version of operator delete with the same set of extra parameters.
|
1,960,964 | 1,961,126 | Can anyone tell me about the Event Handler or Callback on switching of the front process on Mac? | I need to have the callback or some event handler which can help me, know front process is changed.
Mac: C++/Carbon.
Any help is highly appreciated.
| That would be the kEventAppFrontSwitched event in the kEventClassApplication class. See the Carbon Event Manager reference.
|
1,960,991 | 1,961,237 | Which one to use - memmove() or memcpy() - when buffers don't overlap? | Using memcpy() when source and destination overlap can lead to undefined behaviour - in those cases only memmove() can be used.
But what if I know for sure buffers don't overlap - is there a reason to use specifically memcpy() or specifically memmove()? Which should I use and why?
| Assuming a sane library implementor, memcpy will always be at least as fast as memmove. However, on most platforms the difference will be minimal, and on many platforms memcpy is just an alias for memmove to support legacy code that (incorrectly) calls memcpy on overlapping buffers.
Both memcpy and memmove should be written to take advantage of the fastest loads and stores available on the platform.
To answer your question: you should use the one that is semantically correct. If you can guarantee that the buffers do not overlap, you should use memcpy. If you cannot guarantee that the buffers don't overlap, you should use memmove.
|
1,961,028 | 1,961,143 | Any differences between f(const string &) and f(const string )? | class mystring {
friend ostream& operator<<(ostream &out, const mystring ss) {
out << ss.s;
return out;
}
private:
string s;
public:
mystring(const char ss[]) {
cout << "constructing mystring : " << ss << endl;
s = ss;
}
};
void outputStringByRef(const mystring &ss) {
cout << "outputString(const string& ) " << ss << endl;
}
void outputStringByVal(const mystring ss) {
cout << "outputString(const string ) " << ss << endl;
}
int main(void) {
outputStringByRef("string by reference");
outputStringByVal("string by value");
outputStringByRef(mystring("string by reference explict call mystring consructor"));
outputStringByVal(mystring("string by value explict call mystring constructor"));
} ///:~
Considering the above example,we could not modify the pass-by-reference variable,neither could we modify the pass-by-value variable.The output of each methods is same.Since there is no difference between these two method,why do C++ support both methods?
thanks.
| There is a difference between the two. Consider the following:
#include <iostream>
#include <string>
using std::string;
string g_value;
void callback() {
g_value = "blue";
}
void ProcessStringByRef(const string &s) {
callback();
std::cout << s << "\n";
}
void ProcessStringByValue(const string s) {
callback();
std::cout << s << "\n";
}
int main() {
g_value = "red";
ProcessStringByValue(g_value);
g_value = "red";
ProcessStringByRef(g_value);
}
Output:
red
blue
Just because a reference is const inside a function, doesn't mean that the referand can't be modified via other references (the situation of one object having multiple references or pointers to it is called "aliasing"). Thus there is a different between passing a const reference, and passing a const value - in the case of the reference, the object might change after the call is made. In the case of the value, the callee has a private copy, which will not change.
Since they do different things, C++ lets you choose which you want.
There are consequences for performance either way - when you pass by value, a copy has to be made, which costs. But the compiler then knows that only your function can possibly have any references to that copy, which might allow other optimisations. ProcessStringByRef cannot load the contents of the string for printing until callback() has returned. ProcessStringByValue can, if the compiler thinks doing so is faster.
Usually you care about the copy, not the order of execution of instructions, because usually the copy is way more expensive. So usually, you pass by reference where possible for objects that are non-trivial to copy. But the possibility of aliasing sometimes has really serious consequences for performance, by preventing certain optimisations even though no aliasing actually occurs. That's why "strict aliasing rules" exist, and the restrict keyword in C99.
|
1,961,086 | 1,961,101 | Multiple definitions of `GamepadControll::GamepadControll()' | I got this error message:
multiple definition of `GamepadControll::GamepadControll()'
After being frustrated for hours I reduced the code to:
GamepadControll.h:
#ifndef GAMEPADCONTROLL_H_
#define GAMEPADCONTROLL_H_
#include <iostream>
class GamepadControll {
public:
GamepadControll();
virtual ~GamepadControll();
};
#endif /* GAMEPADCONTROLL_H_ */
GamepadControl.cpp:
#include "GamepadControll.h"
GamepadControll::GamepadControll() {
std::cout << "Hello, I work!" << std::endl;
}
GamepadControll::~GamepadControll() {
// TODO Auto-generated destructor stub
}
But I just get this error message!
//Edit:
Main isn't defined.. Can't I run only a class without mainfiles like in java? Here is the whole eclipse Project: http:/ul.to/m37d2z
| Most mulitply-defined-symbol error situations tend to be caused by including code into two different compilation units.
Are you sure that you're not including GamepadControl.cpp into one of your other source files?
For example, with both your files and a main.cpp holding:
#include "GamepadControll.h"
int main (void) { return 0; }
I get no errors with g++ main.cpp GamepadControll.cpp. If I change that first line to:
#include "GamepadControll.cpp"
and compile with the same command, I get:
/tmp/ccbu52oq.o: In function `GamepadControll::GamepadControll()':
GamepadControll.cpp:(.text+0x0): multiple definition of
`GamepadControll::GamepadControll()'
The only other possibility I can think of is if you're explicitly including the code file twice. Using the error-free version of main.cpp above, I still get the error when I use:
g++ main.cpp GamepadControll.cpp GamepadControll.cpp
If it's neither of those two cases, your best bet is to provide the full details of your situation. That means every source file (including the main one), the compile and link commands you're using, and the environment (e.g., gcc3 under Linux, Code::Blocks on Windows).
|
1,961,158 | 1,961,180 | Where does execution resume following an exception? | In general, where does program execution resume after an exception has been thrown and caught? Does it resume following the line of code where the exception was thrown, or does it resume following where it's caught? Also, is this behavior consistent across most programming languages?
| the execution resumes where the exception is caught, that is at the beginning of the catch block which specifically address the current exception type. the catch block is executed, the other catch blocks are ignored (think of multiple catch block as a switch statement). in some languages, a finally block may also be executed after the catch. then the program proceed with the next instruction following the whole try ... catch ... finally ....
you should note that if an exception is not caught in a block, the exception is propagated to the caller of the current function, and up the call stack until a catch processes the exception. in this case, you can think of function calls like a macro: insert the code of each function where it is called, and you will clearly see the nesting of every try .. catch ... finally ... blocks.
if there is no handler for an exception, the program generally crashes. (some languages may be different on this point).
the behavior for the execution flow is consistent accross every languages i know. the only difference lies in the try ... catch ... finally ... construct: the finally does not exists in every language, some languages does not allow a finally and a catch in the same block (you have to nest two try to use the 2), some languages allows to catch everything (the catch (...) in C++) while some languages don't.
|
1,961,238 | 1,961,246 | Can anyone recommend a good C/C++ RESTful framework | Rather than possibly reinventing the wheel (by "rolling my own") - I thought I'd ask in here first.
Anyone knows where I can download a good C/C++ RESTful framework?. I have had a quick look on google, but there is nothing too impressive so far - maybe someone in here has written one already (that they dont mind sharing), or may know a lik to a good one (preferably, they have already used it before)
| I've just seen this, it may be what I'm looking for. Could be useful for others too
|
1,961,240 | 1,961,269 | List of things to check to prevent VC++ applications from showing fatal error message boxes | Every now and then there's a strong need to write a program in such a way that it never (really never) shows an error message as a message box. For example it can be a program run inside a daily build - if it hangs with a message box the daily build hangs.
Unfortunately VC++ runtime has a lot of ways to trigger message boxes when indicating errors.
First of all, whenever an exception is not handled terminate() is called which calls abort() which causes "This application has requested the Runtime to terminate it in an unusual way." message box. This can be worked around by catching all exceptions and/or using set_terminate() to set a custom terminate() handler without message boxes.
Then, whenever an exception escapes any destrutor during stack unwinding terminate() is also called. set_terminate() helps here as well.
Then, there's a "pure virtual function call" message box that is shown in some hardcore cases of mismatching the number of functions expected by the caller and those implemented by the callee. _set_purecall_handler() should help here.
What else to do to a VC++ program to be absolutely positively sure it doesn't show a message box in some fatal situation?
| I would recommend that you use a helper program to launch it and have this helper limit the time your program can run. This is by far the safest way if you can do it, as it handles every case. Some things you cannot handle in your program directly, such as "This program is not a valid Win32 application" which might happen if you are missing a DLL.
|
1,961,271 | 1,961,279 | Time spent on reading from file | I am doing this in C++:
if (myfile.is_open()){
while (! myfile.eof()){
getline (myfile,line);
DO STUFF
}
myfile.close();
}
else{
cout << "Unable to open file";
}
I am trying to read the lines from a text file and do stuff with it. I am trying to see what the run time of my algorithm would be. Would reading lines from the file slow down my program by much so I won't get an accurate result?
| Yes - if you want to accurately benchmark "DO STUFF" then you shouldn't take into account disk IO also. So one thing you could do is buffer the whole file into memory, and then process it and time that. But if the file is too large or it would make your line handler more difficult, another thing you could do is read the file into memory line by line 10 times or so WITHOUT processing, average the times, and then time the function the way you have it now (including processing and disk I/O), and then subtract the average disk-reading time from the total time.
Edit: I don't know why I didn't think of this before, but you could also just put a timer around the execution of "DO STUFF" and add to a sum after each execution.
|
1,961,370 | 1,961,381 | c++ node list - NULL test not working | I wanted to test the following code (which works fine for a non-null list) to see what would happen in the case of an empty list (in which case the head would be null).
hence the code which applies to filling the list is commented out..
But for some strange reason, the test for NULL in print_nodes() just doesnt seem to work. ive added some debug cout calls to see (and also checked using gdb) but whilst the value does indeed appear to be NULL, any if statements dont seem to test the equivalence properly..
any idea why?
many thanks!
#include <iostream>
using namespace std;
struct node {
char dat;
node *nextPtr;
};
//inserts new node and returns pointer
node* new_node(char data, node* prevNode);
//adds a new node at the head ofthe list
void new_head (node *head_, char dat_);
//inserts new node after *before
void insert_node (node *before, char dat_);
//runs through and prints the list - requires first node (head)
void print_nodes (node *head);
int main() {
cout <<endl << endl;
cout << endl << "*******************RUN******************" <<endl <<endl;
node* head = NULL;
if (head == NULL) {
cout << "head null"; //this works here
}
//head non-standard
// node* head = new node;
// head->dat ='a';
/*
node* b = new_node('b', head);
node* c = new_node('c', b);
node* d = new_node('d', c);
node* e = new_node('e', d);
node* f = new_node('f', e);
*/
print_nodes(head);
insert_node(head,'N');
print_nodes(head);
cout << endl << "*******************END RUN******************" <<endl;
return 0;
}
node* new_node(char data, node* prevNode) {
node* tempPtr = new node;
tempPtr->dat = data;
tempPtr->nextPtr = NULL; //standard
prevNode->nextPtr = tempPtr;
return tempPtr;
}
void new_head (node *head_, char dat_) {
}
void insert_node (node *before, char dat_) {
node* tempPtr = new node;
tempPtr->dat = dat_;
tempPtr->nextPtr = before->nextPtr;
before->nextPtr = tempPtr;
}
void print_nodes (node *head) {
node* tempPtr = head;
cout << "\nPrinting nodes..." <<endl;
if (tempPtr == NULL) { //this test is not working.. why?
cout << "tempPtr is NULL";
return;
} else { //only run in the non null case
for (tempPtr; tempPtr != NULL; tempPtr = tempPtr->nextPtr) {
cout << "Current node content: " << tempPtr->dat <<endl;
}
}
}
| You have a problem: head was not allocated, but insert accesses its "next element":
before->nextPtr = tempPtr;
head is passed in as before, and you didn't allocate memory for head. Hence you dereference a NULL pointer here.
Could it be that your application crashes as a result, and the printout to cout isn't done because cout is buffered?
Try to:
Remove the call to insert
Change cout to cerr (unbuffered)
Report the results of these changes.
|
1,961,376 | 1,961,408 | length of array in c++ | I read to get the length of array in C++, you do this:
int arr[17];
int arrSize = sizeof(arr) / sizeof(int);
I tried to do the same for a string:
where I have
string * arr;
arr = new (nothrow) string [213561];
And then I do
arr[k] = "stuff";
where I loop through each index and put "stuff" in it.
Now I want the size of the array which should be 213561, what's the correct way to do it and why is it so complex in C++?
| The correct way of doing this in C++ is to use a vector. That way you can either specify a size up-front, or resize it as you go.
Specifying size up-front:
using namespace std;
vector<string> arr(213561);
for (vector<string>::iterator p = arr.begin(); p != arr.end(); ++p)
{
*p = "abc";
}
Expanding the vector as you go:
using namespace std;
vector<string> arr; // <-- note, default constructor
for (int i = 0; i < 213561; ++i)
{
// add elements to the end of the array, automatically reallocating memory if necessary
arr.push_back("abc");
}
Either way, the size of the array is found with:
size_t elements = arr.size(); // = 213561
|
1,961,455 | 1,961,517 | How do i use C++ with Flex? | How can i outsource performance critical stuff to C++.
Is there any example ?
| If you're talking about Flex on AIR platform (basically out of browser application), there's a way to interact with native code on the same machine.
You may want to check this out (official doc from Adobe) : http://www.adobe.com/devnet/air/ajax/quickstart/interacting_with_native_process_print.html
If you're talking about flex in the browser, then I would agree with Dmitry, you can use many different things:
- Web Services
- HTTP Request/Response
- RPC calls
- Or even make your own real-time socket (in some cases can be the most performant way to do this)
Now, that would require a C++ Server, listening to those calls, doing the stuff and then replying. => Meaning you need networking.
|
1,961,561 | 1,961,576 | Standard convention for using "std" |
Exact Duplicate: Do you prefer explicit namespaces or ‘using’ in C++?
Which of these is a preferred convention for using any namespace?
using namespace std;
or
using std::cin;
using std::cout;
or
calling the function as and when required in the code?
std::cout<<"Hello World!"<<std::endl;
| A very good explanation is given here.
The first style i.e. using namespace whatever defeats the whole purpose of namespacing. You should never be using it except in small code snippets. (I don't use it there either! :D )
Second one is way too verbose. Not practical.
I personally like the third style i.e. typing out the fully qualified name (e.g. std::cout).
Remember, the code is read much more times than it is written & using fully qualified names IMO makes your code more readable.
|
1,961,604 | 1,961,641 | How much time would it take to write a C++ compiler using flex/yacc? | How much time would it take to write a C++ compiler using lex/yacc?
Where can I get started with it?
| There are many parsing rules that cannot be parsed by a bison/yacc parser (for example, distinguishing between a declaration and a function call in some circumstances). Additionally sometimes the interpretation of tokens requires input from the parser, particularly in C++0x. The handling of the character sequence >> for example is crucially dependent on parsing context.
Those two tools are very poor choices for parsing C++ and you would have to put in a lot of special cases that escaped the basic framework those tools rely on in order to correctly parse C++. It would take you a long time, and even then your parser would likely have weird bugs.
yacc and bison are LALR(1) parser generators, which are not sophisticated enough to handle C++ effectively. As other people have pointed out, most C++ compilers now use a recursive descent parser, and several other answers have pointed at good solutions for writing your own.
C++ templates are no good for handling strings, even constant ones (though this may be fixed in C++0x, I haven't researched carefully), but if they were, you could pretty easily write a recursive descent parser in the C++ template language. I find that rather amusing.
|
1,961,659 | 1,961,779 | Can I use partial template specialization for a (non-member) function? | I'm trying to use partial template specialization on a (non-member) function, and I'm tripping up on the syntax. I've searched StackOverflow for other partial template specialization questions, but those deal with partial specialization of a class or member function template.
For a starting point, I have:
struct RGBA {
RGBA(uint8 red, uint8 green, uint8 blue, uint8 alpha = 255) :
r(red), g(green), b(blue), a(alpha)
{}
uint8 r, g, b, a;
};
struct Grayscale {
Grayscale(uint8 intensity) : value(intensity) {}
uint8 value;
};
inline uint8 IntensityFromRGB(uint8 r, uint8 g, uint8 b) {
return static_cast<uint8>(0.30*r + 0.59*g + 0.11*b);
}
// Generic pixel conversion. Must specialize this template for specific
// conversions.
template <typename InType, typename OutType>
OutType ConvertPixel(InType source);
I can do a complete specialization of ConvertPixel to make an RGBA to Grayscale conversion function like this:
template <>
Grayscale ConvertPixel<RGBA, Grayscale>(RGBA source) {
return Grayscale(IntensityFromRGB(source.r, source.g, source.b));
}
I'll conceivably have more pixel types that offer red, green, and blue, but perhaps in a different format, so what I'd really like to do is a partial specialization by specifying Grayscale for OutType and still allow for a variety of InTypes. I've tried a variety of approaches like this:
template <typename InType>
Grayscale ConvertPixel<InType, Grayscale>(InType source) {
return Grayscale(IntensityFromRGB(source.r, source.g, source.b));
}
But the (Microsoft VS 2008 C++) compiler rejects it.
Is what I'm attempting possible? If so, what's the right syntax?
| It is possible using class partitial specialization:
template<class A, class B>
struct Functor {
static A convert(B source);
};
template<class B>
struct Functor<GrayScale, B> {
static GrayScale convert(B source) {
return Grayscale(IntensityFromRGB(source.r, source.g, source.b));
}
};
// Common function
template<class A, class B>
A Convert(B source) {
return typename Functor<A,B>::convert(source);
}
|
1,961,812 | 1,961,896 | How to implement reference counting for library class whose implementation cant be changed? | I come to know that when many objects shares same data and creation and desturction of objects are expensive then one can go for reference counting .
Can anybody give input about how to achieve it for the library class which cant be changed ?.
| Use a referenced-counted pointer like boost::shared_ptr. No changes to the class pointed to are necessary, but you will be limited to creating class instances dynamically.
|
1,962,029 | 1,962,034 | Destructors called upon program termination | When an object is created in your main() function, is its destructor called upon program termination? I would assume so since main() still has a scope( the entire program ), but I just wanted to make sure.
| It depends on how your program terminates. If it terminates by having main return (either by an explicit return or falling off the end), then yes, any automatic objects in main will be destructed.
But if your program terminates by calling exit(), then main doesn't actually go out of scope and any automatic objects will not be destructed.
|
1,962,103 | 1,962,139 | Can I use Qt as C++ Library without using its UI framework | Does it make sense to use Qt for increasing the productivity in an MFC app, without actually using the Qt user interface system?
I am currently looking or a good productivity library for my MFC based application, with useful container classes, string algorithmus, threading classes, I/O classes and so on. The Qt API is very nice in my opinion. However, since I don't want to switch my UI to Qt (just too much effort), I am wondering whether Qt can be used well in a MFC app without any Qt UI.
Thanks in advance for your opinions.
Fabian
| Qt is divided into several modules (QtGui being one of them). You can hand pick which modules are used by your application by linking only against the libraries you need.
I cannot answer whether Qt will be interopable with MFC. But at the very least, QString offers conversion to std::string and char*/wchar, which should help you quite a bit.
The Qt documentation provides an overview over the modules.
As daniel pointed out below, you have to be aware of the event loop. It is possible however to use the event loop without the GUI module. You can call processEvents on QCoreApplication to process all queued events and then return. There is one caveat with deferred deletions, but the documentation describes the workaround.
|
1,962,281 | 1,962,300 | Get ID from MIDI devices in C++ | I'm a musician and a programmer and would like to create my own program to make music.
I'll start with a console application in C++ before I make a GUI.
I'm quiet new to C/C++ and know how to make a basic console application and have read about the Win32 API.
I was looking into MSDN for multimedia in Win32 applications and I found a lot of functions for MIDI: http://msdn.microsoft.com/en-us/library/dd798495(VS.85).aspx
I can receive how many MIDI devices are plugged in this way:
#include <windows.h>
#include <iostream>
using namespace std;
int main() {
cout << midiInGetNumDevs();
cout << " MIDI devices connected" << endl;
return 0;
}
But now i want to find out how these devices are called, with the midiInGetID function I think and a while loop. Can somebody help me with this? The function requires a HMIDIIN parameter and I don't know how I can get one since almost all the MIDI functions use this parameter.
I know this is not the most obvious topic but it would be great if someone could help me.
Thanks :)
| To get information, you loop calling midiInGetDevCaps, with a first parameter varying from 0 included to the result of midiInGetNumDevs excluded. Each call fills a MIDIINCAPS struct (you pass a pointer to the struct when you call the function) with information about the Nth device. To open a device, and fill the HMIDIIN needed for other calls, you call midiInOpen with the device number (again, 0 to N-1 included) as the second parameter.
The same concept applies to output devices, except that the names have Out instead of In (and for the structures OUT instead of IN).
|
1,962,331 | 1,962,362 | C or C++ - dynamically growing/shrinking disk backed shared memory | I have several fastcgi processes that are supposed to share data.
The data is bound to a session (a unique session id string) and should be able to survive a server reboot. Depending on the number of sessions, the shared data might be too big to fit into main memory. Ideally, in the case when the shared data exceeds a certain threshold, the data bound to sessions that have been the least active should exist on disk only, whereas the most active session data should be available from main memory. After a session has been inactive for some time, the sessions data is to be destroyed.
My question is (being a newbie to C/++):
Are there any approaches or libraries that can help me tackle this quite hairy problem ?
Is it possible to use mmap() with shared memory considering the requirement that inactive session data should be destroyed?
| After your comment to bmargulies I should caution you that I myself tried to do what you are describing, and I found that I was writing a ACID database. To recap, you have asked for :
Statistical Caching
data persistance
data sharing between processes
This is the role of a database system. It is far better to use one written by others. IMO your choices are sqlite and berkeley-db.. Sqlite is not for parallel access, berkeley-db on the other hand is very scaleable however it uses a string - string dictionary as its data model.
BDB can have databases entirely in-memory or the normal way which is serialized to disk and cached in memory. You can also tune the ACID semantics to suite your particular needs -- i.e., you can disable durable writes, and this would give you instant write characteristics while sacrificing bullet-proof data durability.
There are loads of more advanced solutions but these are for real world problems -- i.e., you have to build a cluster.
|
1,962,482 | 1,962,644 | HZ variable not defined | I'm trying to compile someone's code right now and the person is using a variable HZ (which I think stands for Hertz for the hertz of the cpu) but the compiler is complaining that the variable is not defined. My guess is that the person didn't include the correct header file.
So does anyone know which header file, HZ is defined in?
Thanks
Edit: Compilation works on Debian g++ version 4.3.2
The setup I'm using - OSX Leopard 10.5.8, g++ version 4.0.1 is where it fails.
| Paul's answer is correct, but I'll expand a little.
Linux has a compile-time option which determines the frequency of the kernel's timer. At approximately the frequency that HZ is defined to, the kernel scheduler will interrupt processes and begin its scheduling work. (A related feature is the DynTicks option, which elides the HZ value, and changes the interrupt frequency based on the workload.) The most common setting is 100. Highly responsive systems might use 1000. Recent kernel versions use a default of 250. Systems with heavy computational workloads might use a smaller value (to minimize the effect of the scheduler).
Thus it is a very Linux-specific value, and you'll only find it defined in /usr/include/asm/param.h
Since 100 is a common value, you might be safe in simply adding -DHZ=100 to your CXXFLAGS variable. This will by no means mean that the program will actually work on OS X, only that it might compile.
|
1,962,624 | 1,962,637 | How can I write my own 'filesystem' within Windows? | I've recalled using little 'filesystems' before that basically provided an interface to something else. For example, I believe there was a GMail filesystem that created an entry in My Computer and could be used like any other drive on your local computer. How can I go about implementing something like this in C++?
Thank you!
| Try Dokan. It's like FUSE, except for Windows. I think there are certain limitations to namespace extensions, like they cannot be accessed from the command line, but I'm really not sure as of now.
|
1,962,685 | 1,962,921 | Xcode STL C++ Debug compile error | I have some file writing code that works as expected, but prints an error on Debug mode, no output errors in Release.
Code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main (int argc, char * const argv[]) {
string cppfilename;
std::cout << "Please enter the filename to create: ";
while ( cppfilename == "" ) {
getline(cin, cppfilename); // error occurs here
}
cppfilename += ".txt";
ofstream fileout;
fileout.open( cppfilename.c_str() );
fileout << "Writing this to a file.\n";
fileout.close();
return 0;
}
Debug Output:
Please enter the filename to create: Running…
myfile
FileIO(5403) malloc: *** error for object 0xb3e8: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Created: myfile.txt
Release Output:
FileIO implementation C++
Please enter the filename to create: Running…
myfile
Created: myfile.txt
Aside from not checking for the file descriptor being open (for simplicity) what is wrong with this code?
Update: I broke the code down to the following and it still errors:
string cppfilename;
getline(cin, cppfilename); // error here
| This looks to be another case of _GLIBCXX_DEBUG being broken with gcc 4.2 on Mac OS X.
Your best options look to be to drop _GLIBCXX_DEBUG or to switch to gcc 4.0.
|
1,962,880 | 1,962,918 | Is C++ static member variable initialization thread-safe? | According to following resources, in C++(Specially Visual C++) scoped static variable initialization isn't thread safe. But, global static variables are safe.
Thread-safe static variables without mutexing?
http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx
So, is following code with static member variable thread-safe?
class TestClass
{
public:
static MyClass m_instance;
}
Myclass TestClass::m_instance;
Thanks in advance!
| It's more a question of function-scoped static variables vs. every other kind of static variable, rather than scoped vs. globals.
All non-function-scope static variables are constructed before main(), while there is only one active thread. Function-scope static variables are constructed the first time their containing function is called. The standard is silent on the question of how function-level statics are constructed when the function is called on multiple threads. However, every implementation I've worked with uses a lock around the constructor (with a twice-checked flag) to guarantee thread-safety.
|
1,962,959 | 1,964,209 | std::vector reserve method fails to allocate enough memory | I have a buffer class in my C++ application as follows:
class Buffer
{
public:
Buffer(size_t res): _rpos(0), _wpos(0)
{
_storage.reserve(res);
}
protected:
size_t _rpos, _wpos;
std::vector<uint8> _storage;
}
Sometimes using the constructor fails because its unable to allocate the required memory space. For example, once, calling the constructor with res = 37 caused a segfault with the following stack trace that i got from its core dump:
#0 0x00007f916a176ed5 in raise () from /lib/libc.so.6
No symbol table info available.
#1 0x00007f916a1783f3 in abort () from /lib/libc.so.6
No symbol table info available.
#2 0x00007f916a1b33a8 in ?? () from /lib/libc.so.6
No symbol table info available.
#3 0x00007f916a1b8948 in ?? () from /lib/libc.so.6
No symbol table info available.
#4 0x00007f916a1bb17c in ?? () from /lib/libc.so.6
No symbol table info available.
#5 0x00007f916a1bca78 in malloc () from /lib/libc.so.6
No symbol table info available.
#6 0x00007f916ac0c16d in operator new (sz=37)
at ../../.././libstdc++-v3/libsupc++/new_op.cc:52
p = <value optimized out>
#7 0x00000000004e3d11 in std::vector<unsigned char, std::allocator<unsigned char> >::reserve (this=0x7f911bc49cc0, __n=31077)
at /usr/local/lib/gcc/x86_64-unknown-linux-gnu/4.4.2/../../../../include/c++/4.4.2/ext/new_allocator.h:89
__old_size = 0
__tmp = <value optimized out>
I've compiled this application using GCC 4.4.2 as a 64 bit application and I'm using it in Debian 5 x64.
Any help is much appreciated.
Thanks
| If you can't use Valgrind to find out where your memory is corrupted because of the heavy load it implies, you can still test with lighter solutions.
For server application where Valgrind was not applicable (because the platform was on Solaris 8), I had pretty good result with mpatrol ( http://mpatrol.sf.net ) but especially dmalloc ( http://dmalloc.com ).
To some extend, you can use them without recompiling (just relinking for dmalloc, library preloading for mpatrol). They'll replace the memory primitives to perform extra checks on the memory use (bad argument to those primitives, reading off-by-one, heap corruption, ...) Some of those checks will be triggered exactly when the problem occurs while others will be triggered a bit later than the actual bad code. By tuning which checks are enabled, and when applicable the check frequency, you can run at almost full speed while performing basic checks.
I recommend recompiling with dmalloc to get so called 'FUNC_CHECK', for me, this added a lot of accuracy in bug spotting with a negligible performance cost.
|
1,963,040 | 1,963,082 | std::map and 'fat' value objects | What's better from a performance point of view std::map<uint32_t, MyObject> or std::map<uint32_t. MyObject*> if MyObject is 'fat' (that is operator= rather expensive) and I have to insert/update/delete a lot ?
| If you'd prefer to store the objects "by value", but don't want to perform expensive copying, then just don't do the copying at all. For example, you can always insert "empty" objects (which can be copied quickly) and then fill them with actual content after they are already inserted into the map. The latter can be done in more efficient way by employing, for example, move semantics instead of copy semantics. Associative containers are not supposed to perform any copying between the already inserted elements (although in theory it is probably possible), so once you have taken care of the new element insertion, you should not run into any additional issues with expensive copying.
For example, a typical "expensive" insertion scenario might look as follows
MyObject new_value(/* constructor arguments */);
// Maybe do some additional preparations on `new_value`
// ...
// And now: the actual insertion
map[key] = new_value;
// .. which makes a call to the heavy assignment operator
Note, that in this scenario it is you who's making the call to the assignment operator. Since you have the control over the actual copying, you can rewrite it in much less expensive fashion, as follows
MyObject& new_value = map[key];
// Now `new_value` is a reference to a default-constructed object
// Here you should "load" the `new_value` object with whatever information
// you want it to carry. That should cover both the original constructor's
// functionality from the previous piece of code, as well as any
// post-constructor preparations
// ...
Note, that in the second scenario the effort required to build the new value is basically the same as in the first one, but there no extra copying for the actual insertion. Also note, that in this case your object has to be default-consructible, which is not normally a requirement imposed on standard container elements.
If you decide to store the objects "by pointer", a better idea would be to use appropriate smart pointers instead of raw pointers.
|
1,963,099 | 1,963,119 | How to inform the server when a client is interrupted? | How to inform the server if a client is interrupted, and then close the socket?
| If the other end of a socket is closed, your end will be marked as readable and return 0 from read - this is the "end of file" indication.
If you try to write to such a socket, you will recieve the SIGPIPE signal, and the write will return error with errno set to EPIPE ("Broken Pipe"). You must be prepared to handle this event, because the other end can close the socket at any time.
|
1,963,106 | 1,963,134 | Find Even/Odd number without using mathematical/bitwise operator | I was recently asked to write a program, that determines whether a number is even or odd without using any mathematical/bitwise operator!
Any ideas?
Thanks!
| This can be done using a 1 bit field like in the code below:
#include<iostream>
struct OddEven{
unsigned a : 1;
};
int main(){
int num;
std::cout<<"Enter the number: ";
std::cin>>num;
OddEven obj;
obj.a = num;
if (obj.a==0)
cout<<"Even!";
else
cout<<"Odd!";
return 0;
}
Since that obj.a is a one-field value, only LSB will be held there! And you can check that for your answer.. 0 -> Even otherwise Odd..!!
|
1,963,157 | 1,963,166 | OpenGL Video Memory Usage | is there an API or profiler application that can track the video memory usage of my application?
I am using C++/OpenGL on Windows, but I am open to suggestions on other platforms as well.
| On Mac OS X you have OpenGL Profiler.app, which comes with the Developer Tools (on the OS DVD or from http://developer.apple.com)
On Windows you could try gDEBugger - a good commercial OpenGL Profiling tool.
|
1,963,241 | 1,963,680 | IGraphBuilder::RenderFile() failing with VFW_E_BAD_KEY - 0x800403f2 | Continuing investigation on a embedded WindowsMediaPlayer problem, i am trying to do simple file playback via a DirectShow in-process server:
::CoInitializeEx(0, COINIT_MULTITHREADED);
CComPtr<IGraphBuilder> spGraph;
spGraph.CoCreateInstance(CLSID_FilterGraph, 0, CLSCTX_INPROC_SERVER);
CComQIPtr<IMediaControl> spMediaControl(spGraph);
// ... later:
spGraph->RenderFile(L"c:\\foo.wav", 0); // fails with VFW_E_BAD_KEY
spMediaControl->Run();
Interestingly, this runs fine on both systems i tested on (Windows XP 32 & x64) when doing it in a stand-alone application.
It however fails in my real use-case, a NPAPI based browser plugin - i.e. a DLL loaded into Firefox/Chrome/Opera.
Does anyone have an idea what could be going wrong here?
Or ideas on what else to try?
Update: also asked on the Microsoft forums.
Update2:
IGraphBuilder::AddSourceFilter(path,path,&base) already fails with the following registry calls (as seen in process monitor):
"RegOpenKey","HKCU\Software\Classes\c","NAME NOT FOUND","Desired Access: Query Value, Maximum Allowed"
"RegOpenKey","HKCU\Software\Classes\Media Type\Extensions\.wav","NAME NOT FOUND","Desired Access: Read"
"RegOpenKey","HKCU\Software\Classes\Media Type","NAME NOT FOUND","Desired Access: Read"
| It is reading the key from the wrong hive. It should use HKLM, not HKCU. The most likely reason for this is registry virtualization.
|
1,963,269 | 1,963,281 | C++ Force Template Parameter | I want this code to be possible.
template<typename K, typename T, typename Comparer>
class AVLTree
{
...
void foo() {
...
int res = Comparer::compare(key1, key2);
...
}
...
};
Specifically, I want to force Comparer class to have a static int compare(K key1, K key2) function. I was thinking about using derivation, but could not find any ideas that can work with templates.
Thank you.
| You can't. But if use the function and the Comparer doesn't have it, your compile will fail and this is more or less what you want to happen. And yes, like others pointed out you want to call static as static.
|
1,963,366 | 1,963,859 | Callbacks and Delays in a select/poll loop | One can use poll/select when writing a server that can service multiple clients all in the same thread. select and poll, however need a file descriptor to work. For this reason, I am uncertain how to perform simple asynchronous operations, like implementing a simple callback to break up a long running operation or a delayed callback without exiting the select/poll loop. How does one go about doing this? Ideally, I would like to do this without resorting to spawning new threads.
In a nutshell, I am looking for a mechanism with which I can perform ALL asynchronous operations. The windows WaitForMultipleObjects or Symbian TRequestStatus seems a much more suited to generalized asynchronous operations.
| For arbitrary callbacks, maintain a POSIX pipe (see pipe(2)). When you want to do a deferred call, write a struct consisting of a function pointer and optional context pointer to the write end. The read end is just another input for select. If it selects readable, read the same struct, and call the function with the context as argument.
For timed callbacks, maintain a list in order of due time. Entries in the list are structs of e.g. { due time (as interval since previous callback); function pointer; optional context pointer }. If this list is empty, block forever in select(). Otherwise, timeout when the first event is due. Before each call to select, recalculate the first event's due time.
Hide the details behind a reasonable interface.
|
1,963,472 | 1,963,536 | how to create a gui to invoke a .exe or .cpp file? | i have a compiler project and i have used c++ , flex and bison in it
so bison and flex produce .cpp files to me and i can compile and run them
but i want to make a gui to my project
so i want to learn a technique to make a gui (in java or qt)
to write input to my project and get output
| There seems to be a bit of a language barrier, so let me attempt to state what I think I understand before providing my answer.
It appears that you're in a Compilers class, and your project is to write a C++ compiler. You've chosen to program this project using C++, with the help of bison and flex. Now that your project is effectively complete, you'd like to add a GUI to it (I guess in some way making steps towards it becoming an IDE).
Writing a GUI in C++ isn't as easy as I'd like for it to be. From friends that have had to do the same thing in their compilers and graphics classes, I hear that this book is a good start for using Qt to make GUI programs in C++. With regard to programming the GUI in Java, you'll probably be using the swing library; and I always just read the javadocs (linked). But again, I haven't done that since University.
Hope that helps some! Good luck!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.