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,751,862 | 1,752,119 | Need help understanding using C++ map as an associative array | I was going through Josuttis's "Using Map's as associative arrays" (from The C++ Standard Library - A Tutorial and Reference, 2nd Edition) and came across Using a std::map as an associative array on Stack Overflow. Now I have more questions on the constructors that are called when inserting into a map.
Here is my sample program (not using best coding practices; please excuse me for that):
class C
{
public:
string s;
C() { cout << "default " << endl;}
C(const string& p) : s(p)
{ cout << "one param" << endl;}
C(const C& obj)
{
if (this != &obj)
{
s = obj.s;
}
cout << "copy constr" << endl;
}
C& operator = (const C& obj)
{
if (this != &obj)
{
s = obj.s;
}
cout << "copy initializer" << endl;
return *this;
}
};
int main()
{
map<int,C> map1;
C obj("test");
cout << "Inserting using index" << endl;
map1[1] = obj;
cout << "Inserting using insert / pair" << endl;
map1.insert(make_pair(2,obj));
}
The output for this program is:
one param
Inserting using index
default
copy constr
copy constr
copy initializer
Inserting using insert / pair
copy constr
copy constr
copy constr
copy constr
I was assuming that initializing the map by index should call the default constructor and followed by the assignment operator.
But executing map1[1] = obj creates following output;
Inserting using index
default
copy constr
copy constr
copy initializer
Can someone help me to understand the initialization better?
| If you read the specification for std::map, it says that operator[] is equivalent to (in this case)
(*((this->insert(make_pair(1,C()))).first)).second
So this explains all the constructor calls you see. First it calls the default constructor C(). Then it calls make_pair, which copies the C object. Then it calls insert, which makes a copy of the pair object you just made, calling the C copy constructor again. Finally it calls the assignment operator to set the inserted object to the one you are assigning it to.
|
1,751,915 | 1,751,979 | Template function with dependent type parameters within template class | I've been trying to do this simple stuff and Visual studio 2008 does not seems to like it.
template <class CharType>
class SomeClass
{
public:
template <class T1, class T2>
static bool SomeOperator(const typename T1::const_iterator& p_Begin1,
const typename T1::const_iterator& p_End1,
const typename T2::const_iterator& p_Begin2,
const typename T2::const_iterator& p_End2)
{
// do some stuff..
}
};
And call it with something like this:
std::wstring a;
OtherString b;
SomeClass<wchar_t>::SomeOperator(a.begin(), a.end(), b.begin(), b.end());
What I get is compiler errors stating that it can't deduce template parameter T1 and T2
error C2783: 'bool SomeClass<CharType>::SomeOperator(const T1::const_iterator &,const T1::const_iterator &,const T2::const_iterator &,const T2::const_iterator &)' : could not deduce template argument for 'T1'
error C2783: 'bool SomeClass<CharType>::SomeOperator(const T1::const_iterator &,const T1::const_iterator &,const T2::const_iterator &,const T2::const_iterator &)' : could not deduce template argument for 'T2'
| The compiler is simply unable to deduce types from this context.
Suppose std::wstring::const_iterator is actually const wchar_t*, which is likely. In that case, how does the compiler know it should substitute std::wstring rather than any other type T with T::const_iterator being const wchar_t* (perhaps vector<wchar_t>)?
It's impossible for the compiler to tell exactly. For similar reasons, you cannot deduce some_template<T>::type in function calls.
In your case, the workaround is easy. You don't actually need the container type - templating on the iterator types will work fine:
template <typename I1, typename I2>
static bool SomeOperator(const I1& p_Begin1, const I1& p_End1,
const I2& p_Begin2, const I2& p_End2)
{ /* stuff */ }
If you find yourself in a situation where you need the container type, you will have to either pass the container around or explicitly specify the type in the function call.
|
1,752,261 | 1,753,271 | Memory leak using multiple boost::connect on single slot_type | I'm using boost::signals and leaking memory when I try to connect multiple signals to a single slot_type. I've seen this same leak reported on various forums, but can't find any that mention the correct way to do this, or any workaround.
What I am trying to do:
I am trying to pass the result of boost::bind() into a function. In this function, I want to connect multiple signals to that result. The first connect works fine, but every connect after the first will leak a handle.
Here is some sample code:
typedef boost::signal0<void> LeakSignalType;
class CalledClass
{
/* ... */
void connectToSlots(LeakSignalType::slot_type &aSlot)
{
LeakSignalType *sig;
std::list<LeakSignalType*> sigList;
std::list<LeakSignalType*>::iterator sigIter;
for(int i = 0; i < 50; i++)
{
/*Connect signals to the passed slot */
sig = new LeakSignalType;
sig->connect(aSlot);
sigList.push_back(sig);
}
for(sigIter = sigList.begin(); sigIter != sigList.end(); sigIter++)
{
/* Undo everything we just did */
delete *sigIter;
}
sigList.clear();
/*Everything should be cleaned up now */
}
/* ... */
}
class CallingClass : public boost::signals::trackable
{
CalledClass calledInstance;
/* ... */
void boundFunction(int i)
{
/*Do Something*/
}
void connectSignals()
{
calledInstance.connectToSlots(boost::bind( &CallingClass::boundFunction, this, 1));
}
/* ... */
};
Now call CallingClass::connectSignals().
I expect that the call to connectToSlots will connect 50 signals to a single slot, then disconnect and clean up all of those signals. What actually happens is that 1 signal completely cleans up, then the remaining 49 partially clean up, but leak some memory.
What is the correct way to pass a slot into a function to use multiple times? Any help would be appreciated.
Thanks,
Chris
| I'm pretty sure it's a bug. If you collapse it down to a tiny example, e.g.:
void boundFunction(int) { }
typedef boost::signal0<void> LeakSignalType;
LeakSignalType::slot_type aSlot = boost::bind(&::boundFunction, 1);
LeakSignalType sig1, sig2;
sig1.connect(aSlot);
sig2.connect(aSlot);
and trace the allocations, you'll find that one object (a boost::signals::detail::signal_base_impl::iterator) allocated at line 75 of boost/lib/signals/src/signal_base.cpp is not freed up.
// Allocate storage for an iterator that will hold the point of
// insertion of the slot into the list. This is used to later remove
// the slot when it is disconnected.
std::auto_ptr<iterator> saved_iter(new iterator);
On the first connect, this iterator is attached to a fresh connection object, where signal_data is NULL:
data->watch_bound_objects.get_connection()->signal_data =
saved_iter.release();
On the second connect, however, the same connection object is reused, and the same line blindly overwrites the original pointer value. The second object is cleaned up, but the first is not.
As verification, a breakpoint in signal_base_impl::slot_disconnected, the only place where signal_data is cleaned up, is only triggered once.
I tracked this down in 1.39.0, but it looks like it's the same in 1.40.0.
You could modify boost::signals::detail::signal_base_impl::connect_slot to clean up any previous iterator value it finds in the signal_data field of an existing connection, if you're comfortable making such a change and running a custom build of Boost.
It might be better to just make sure you're only setting these up a fixed number of times and live with a few small memory leaks that you know won't grow over time.
Update:
I was going to submit this to the Boost bug tracker, but it's already there. This is a much smaller test case, however.
https://svn.boost.org/trac/boost/ticket/738
Opened 3 years ago, not assigned to any milestone :-[
|
1,752,319 | 1,752,875 | How best to manage Linux's buffering behavior when writing a high-bandwidth data stream? | My problem is this: I have a C/C++ app that runs under Linux, and this app receives a constant-rate high-bandwith (~27MB/sec) stream of data that it needs to stream to a file (or files). The computer it runs on is a quad-core 2GHz Xeon running Linux. The filesystem is ext4, and the disk is a solid state E-SATA drive which should be plenty fast for this purpose.
The problem is Linux's too-clever buffering behavior. Specifically, instead of writing the data to disk immediately, or soon after I call write(), Linux will store the "written" data in RAM, and then at some later time (I suspect when the 2GB of RAM starts to get full) it will suddenly try to write out several hundred megabytes of cached data to the disk, all at once. The problem is that this cache-flush is large, and holds off the data-acquisition code for a significant period of time, causing some of the current incoming data to be lost.
My question is: is there any reasonable way to "tune" Linux's caching behavior, so that either it doesn't cache the outgoing data at all, or if it must cache, it caches only a smaller amount at a time, thus smoothing out the bandwidth usage of the drive and improving the performance of the code?
I'm aware of O_DIRECT, and will use that I have to, but it does place some behavioral restrictions on the program (e.g. buffers must be aligned and a multiple of the disk sector size, etc) that I'd rather avoid if I can.
| You can use the posix_fadvise() with the POSIX_FADV_DONTNEED advice (possibly combined with calls to fdatasync()) to make the system flush the data and evict it from the cache.
See this article for a practical example.
|
1,752,347 | 1,752,565 | Define a struct in a midl generated header file | I am in the process of automating the build of a legacy product and have hit a wall...
I have a .idl file that is compiled in VC++ 6.0 using midl to generate a .tlb, .h and .c file that has a manual build step to add:
struct StructDef;
Just ahead of an MIDL_INTERFACE in the generated .h file. The rest of the .h file uses the definition, and I cannot compile until this is added.
I am looking for a way to autogenerate the header file with the struct definition (preferred), or at least a way to automate this code adding step through a custom build step.
| #pragma midl_echo instructs MIDL to insert an arbitrary piece of text into the generated header file. You can use it like this:
#pragma midl_echo("struct StructDef;")
It appears that the cpp_quote attribute provides similar functionality.
Alternatively, if you have Cygwin installed, you may find it simpler (or just preferable) to post-process the header file with sed in a custom build step. That would work as well.
|
1,752,557 | 1,752,804 | Is it possible to compile ImageMagick with custom libxml2 on the Mac | It always seems to pick up the version from /usr/lib and there doesn't seem to be a ./configure parameter to override it.
./configure --prefix=$PREFIX --with-quantum-depth=8 --disable-installed --without-x --without-perl --enable-static --disable-shared --with-jpeg --with-tiff CPPFLAGS="$CPPFLAGS" LDFLAGS="$LDFLAGS" CFLAGS="$CFLAGS" --disable-openmp --disable-openmp-slow
Thanks,
Rui
| Generally, an installation of libxml2 includes a configuration script xml2-config that users of the library use to find the correct paths to its components and other build info. The Apple-supplied version of libxml2 has xml2-config in /usr/bin. If you've installed another version of libxml2, make sure your $PATH is set such that its xml2-config will be found first by the ImageMagick configure script: so ensuring most likely one of /usr/local/bin, /opt/local/bin (MacPorts), or /sw/bin (Fink) comes before /usr/bin on $PATH.
A simpler solution might be to just let MacPorts install it all for you:
$ sudo port install ImageMagick
|
1,752,589 | 1,752,653 | Question about send / recv | New to socket programming. Got a couple questions:
My program is really inconsistent with its output. Sometimes my client receives, sometimes it doesnt. I am also using the same input each time.
Just need confirmation: Can the number of bytes received be less than the number of bytes sent from the server?
How do I make it so that I stop receiving once I have all the bytes I need?
Is there a way for a client to know how much bytes it is "going" to receive so that I may put the recv in a while loop?
Thanks for everyones time :) Doing this in C++ / non blocking if that matters at all.
|
Assuming this is TCP (not UDP), you can think of the socket as a stream of bytes. The sender can put them in in whatever way he wants, and you can get them out in whatever way you want. So the sender could write a 1k chunk in one call, and you can receive them a byte at a time if you want.
There are a number of ways, but here are two fairly simple ones:
if the sender closes the socket after sending all of its data, the receiver will receive all the data sent, and the next call to recv will return 0, indicating that there is nothing more to receive. This is how HTTP/1.0 works.
You can change your protocol to send some kind of header containing the length of the data you are about to send, and then recv will know how many bytes to expect. With the Content-length header, this is how HTTP/1.1 works (well, for the most part).
You can use select to tell you whether there is anything there, though it doesn't tell you how much. See question 2.
|
1,752,897 | 1,752,949 | What is the most efficient implementation of a java like object monitor in C++? | In Java each object has a synchronisation monitor. So i guess the implementation is pretty condensed in term of memory usage and hopefully fast as well.
When porting this to C++ what whould be the best implementation for it. I think that there must be something better then "pthread_mutex_init" or is the object overhead in java really so high?
Edit: i just checked that pthread_mutex_t on Linux i386 is 24 bytes large. Thats huge if i have to reserve this space for each object.
| The Sun Hotspot JVM implements thin locks using compare and swap. If an object is locked, then the waiting thread wait on the monitor of thread which locked the object. This means you only need one heavy lock per thread.
|
1,753,029 | 1,753,117 | Sun Raster images: Why 1 byte row padding when width is odd? | This may be waaay to specific for SO, but there seems to be a dearth of info on the sun raster standard. (Even JWZ is frustrated by this!)
Intro: The Sun raster standard says that rows of pixels have padding at the end such that the number of bits in a row is a factor of 16 (i.e. an even number of bytes). For example, if you had a 7-pixel-wide 24-bit image, a row would normally take 7 * 3 = 21 bytes, but sun raster would pad it to 22 bytes so the number of bits is divisible by 16. The code below achieves this for 24-bit images of arbitrary width:
row_byte_length = num_cols * 3;
row_byte_length += width_in_bytes % 2;
Here's my question: both Imagemagick and Gimp follow this rule for 24-bit images, but for 32-bit images it does something weird that I don't understand. Since the bit depth gives 4-byte pixels, any image width would take an even number of bytes per row, which always complies with the "16-bit alignment" rule. But when they compute the row length, they add an extra byte for images with odd widths, making the row length odd (i.e. the number of bits for the row is not divisible by 16). The code below describes what they're doing for 32-bit images:
row_byte_length = num_cols * 4 + num_cols % 2;
Adding one appears to go against the "16-bit alignment" rule as specified by the sun format, and is done with no apparent purpose. However, I'm sure if Gimp and Imagemagick do it this way, I must be misreading the sun raster spec.
Are there any Sun raster experts out there who know why this is done?
Edit
My mistake, Gimp only outputs up to 24 bit Sun raster. Looks like this is only an Imagemagick issue, so probably a bug. I'm labeling this for closure; better to discuss on the ImageMagick forums.
| I'd say the image loading code in Gimp and ImageMagick has a bug. Simple as that.
Keep in mind that the SUN-Raster format isn't that widely used. It's very possible that you're one of the first who actually tried to use this format, found out that it doesn't work as expected and not ignored it.
If the spec. sais something along the lines: Regardless of width, the stored scanlines are rounded up to multiples of 16 bits, then there isn't much room for interpretation.
|
1,753,094 | 1,753,123 | C++ segmentation fault when trying to output object functions | I am attempting to output functions common to a set of objects that share a base class and I am having some difficulty. When the objects are instantiated they are stored in an array and then I am attempting with the following code to execute functionality common to all the objects in this loop:
if ( truck <= v ) // all types of trucks
vptr is an array of objects and the functions in the loop are common to all the objects. The code compiles fine but when I run it I get a segmentation fault when it enters this loop. I'm fairly confident that the call to the first function in this loop is what is causing the problem.
this is how I have instantiated the objects in a previous loop:
vptr[ i ] = new Vehicle( sn, pc );
I should also mention, I'm sorry I forgot to be clear from the beginning, that in this array each object is of a different class. They all share a base class but they are derived objects of that class. Sorry for forgetting that probably important piece of information.
thanks
nmr
| dynamic_cast to a pointer type returns a null pointer (aka 0, NULL) if the object isn't of the specified type. You must check the pointer before using it, or use a reference type (which throws an exception on failure instead):
if (Truck* p = dyanmic_cast<Truck*>(vptr[i])) {
// use the pointer here
}
else {
// vptr[i] doesn't point to a Truck
}
(Notice the nice effect of the correctly-typed pointer being scoped for you, take advantage of this when you can to improve readability.)
|
1,753,182 | 1,753,350 | How to read structured data from file in C++? | I have a data file where I need to read a datum from each line and store it. And then depending on the value of one of those datums store that data in an array so that I can then calculate the median value of all of these data.
The line of data is demographic information and depending on the geographic location, address of a person. I need to capture their age and then find the median of the people that live on a particular street for example.
So the data set is 150,000 records and each record has 26 fields, a lot of those fields are segments of an address and then the other fields are just numbers, age, street number and that sort of thing.
So what I need to do is read through the line and then if a particular field in the record meets a certain condition I need to capture a field from the record and store it in an array so that I can calculate the median of people that live on "Oak Street" for example.
I have the conditional logic and can work the sort out but I'm uncomfortable with the iostream objects in C++, like instantiating an ifstream object and then reading from the file itself.
Oh I forgot that the data was a comma separated value file.
| For comma-delimited input:
using namespace std;
ifstream file;
string line;
while(getline(file, line)) {
istringstream stream(line);
string data[3];
for(int ii = 0; ii < sizeof data / sizeof data[0]; ++ii)
if(!getline(stream, data[ii], ','))
throw std::runtime_error("invalid data");
// process data here
}
For whitespace-delimited input (original answer):
using namespace std;
ifstream file;
string line;
while(getline(file, line)) {
int datum1;
string datum2;
double datum3;
istringstream stream(line);
if(!(line >> datum1 >> datum2 >> datum3))
throw std::runtime_error("invalid data");
// process data here
}
These methods won't win any prizes for performance, but hopefully they're fairly reliable and easy to understand.
|
1,753,357 | 1,753,403 | Per-file enabling of scope guards | Here's a little problem I've been thinking about for a while now that I have not found a solution for yet.
So, to start with, I have this function guard that I use for debugging purpose:
class FuncGuard
{
public:
FuncGuard(const TCHAR* funcsig, const TCHAR* funcname, const TCHAR* file, int line);
~FuncGuard();
// ...
};
#ifdef _DEBUG
#define func_guard() FuncGuard __func_guard__( TEXT(__FUNCSIG__), TEXT(__FUNCTION__), TEXT(__FILE__), __LINE__)
#else
#define func_guard() void(0)
#endif
The guard is intended to help trace the path the code takes at runtime by printing some information to the debug console. It is intended to be used such as:
void TestGuardFuncWithCommentOne()
{
func_guard();
}
void TestGuardFuncWithCommentTwo()
{
func_guard();
// ...
TestGuardFuncWithCommentOne();
}
And it gives this as a result:
..\tests\testDebug.cpp(121):
Entering[ void __cdecl TestGuardFuncWithCommentTwo(void) ]
..\tests\testDebug.cpp(114):
Entering[ void __cdecl TestGuardFuncWithCommentOne(void) ]
Leaving[ TestGuardFuncWithCommentOne ]
Leaving[ TestGuardFuncWithCommentTwo ]
Now, one thing that I quickly realized is that it's a pain to add and remove the guards from the function calls. It's also unthinkable to leave them there permanently as they are because it drains CPU cycles for no good reasons and it can quickly bring the app to a crawl. Also, even if there were no impacts on the performances of the app in debug, there would soon be a flood of information in the debug console that would render the use of this debug tool useless.
So, I thought it could be a good idea to enable and disable them on a per-file basis.
The idea would be to have all the function guards disabled by default, but they could be enabled automagically in a whole file simply by adding a line such as
EnableFuncGuards();
at the top of the file.
I've thought about many a solutions for this. I won't go into details here since my question is already long enough, but let just say that I've tried more than a few trick involving macros that all failed, and one involving explicit implementation of templates but so far, none of them can get me the actual result I'm looking for.
Another restricting factor to note: The header in which the function guard mechanism is currently implemented is included through a precompiled header. I know it complicates things, but if someone could come up with a solution that could work in this situation, that would be awesome. If not, well, I certainly can extract that header fro the precompiled header.
Thanks a bunch in advance!
| Add a bool to FuncGuard that controls whether it should display anything.
#ifdef NDEBUG
#define SCOPE_TRACE(CAT)
#else
extern bool const func_guard_alloc;
extern bool const func_guard_other;
#define SCOPE_TRACE(CAT) \
NppDebug::FuncGuard npp_func_guard_##__LINE__( \
TEXT(__FUNCSIG__), TEXT(__FUNCTION__), TEXT(__FILE__), \
__LINE__, func_guard_##CAT)
#endif
Implementation file:
void example_alloc() {
SCOPE_TRACE(alloc);
}
void other_example() {
SCOPE_TRACE(other);
}
This:
uses specific categories (including one per file if you like)
allows multiple uses in one function, one per category or logical scope (by including the line number in the variable name)
compiles away to nothing in NDEBUG builds (NDEBUG is the standard I'm-not-debugging macro)
You will need a single project-wide file containing definitions of your category bools, changing this 'settings' file does not require recompiling any of the rest of your program (just linking), so you can get back to work. (Which means it will also work just fine with precompiled headers.)
Further improvement involves telling the FuncGuard about the category, so it can even log to multiple locations. Have fun!
|
1,753,469 | 5,132,081 | How to hook up Boost serialization & iostreams to serialize & gzip an object to string? | I've been using the Boost serialization library, which is actually pretty nice, and lets me make simple wrappers to save my serializable objects to strings, like so:
namespace bar = boost::archive;
namespace bio = boost::iostreams;
template <class T> inline std::string saveString(const T & o) {
std::ostringstream oss;
bar::binary_oarchive oa(oss);
oa << o;
return oss.str();
}
template <class T> inline void saveFile(const T & o, const char* fname) {
std::ofstream ofs(fname, std::ios::out|std::ios::binary|std::ios::trunc);
bar::binary_oarchive oa(ofs);
oa << o;
}
template <class T> inline void loadFile(T & o, const char* fname) {
std::ifstream ifs(fname, std::ios::in|std::ios::binary);
assert(ifs.good()); // XXX catch if file not found
bar::binary_iarchive ia(ifs);
ia >> o;
}
The thing is, I just found the need to compress my serialized data, too, so I'm looking at doing that with the filters in boost::iostreams. I figured out how to do it successfully with files:
template <class T> inline void saveGZFile(const T & o, const char* fname) {
std::ofstream ofs(fname, std::ios::out|std::ios::binary|std::ios::trunc);
bio::filtering_streambuf<bio::output> out;
out.push(boost::iostreams::gzip_compressor());
out.push(ofs);
bar::binary_oarchive oa(out);
oa << o;
}
template <class T> inline void loadGZFile(T & o, const char* fname) {
std::ifstream ifs(fname, std::ios::in|std::ios::binary);
assert(ifs.good()); // XXX catch if file not found
bio::filtering_streambuf<bio::input> in;
in.push(bio::gzip_decompressor());
in.push(ifs);
bar::binary_iarchive ia(in);
ia >> o;
}
But can't figure out how to save correctly to a compressed string. The problem is that I'm not flushing the chain of filters, but I've tried popping and syncing and nothing seems to work. Here's my broken code:
template <class T> inline std::string saveGZString(const T & o) {
std::ostringstream oss;
bio::filtering_streambuf<bio::output> out;
out.push(bio::gzip_compressor());
out.push(oss);
bar::binary_oarchive oa(out);
oa << o;
// XXX out.pop() twice? out.strict_sync()?? oss.flush()??
return oss.str();
}
As a result some data gets stuck in the stream buffer somewhere, and I always end up with a a few complete blocks (16K or 32K) of compressed data when I know it should be 43K or so given the (valid) output I get from using my saveGZFile method. Apparently hooking up the ofstream closes and flushes properly, but hooking up the ostringstream doesn't.
Any help? (This is my first stackoverflow question — help me, guys, you're my only hope!)
| Returning to this question, I realized I must've fixed it sometime last year (as I'm using saveGZString right now). Digging to see how I fixed it, it was pretty silly/simple:
namespace bar = boost::archive;
namespace bio = boost::iostreams;
template <typename T> inline std::string saveGZString(const T & o) {
std::ostringstream oss;
{
bio::filtering_stream<bio::output> f;
f.push(bio::gzip_compressor());
f.push(oss);
bar::binary_oarchive oa(f);
oa << o;
} // gzip_compressor flushes when f goes out of scope
return oss.str();
}
Just let the whole chain go out of scope and it works! Neat! Here's my loader for completeness:
template <typename T> inline void loadGZString(T & o, const std::string& s) {
std::istringstream iss(s);
bio::filtering_stream<bio::input> f;
f.push(bio::gzip_decompressor());
f.push(iss);
bar::binary_iarchive ia(f);
ia >> o;
}
|
1,753,486 | 1,753,494 | Copy constructor for a binary tree C++ | I have a Tree class with the following definition:
class Tree {
Tree();
private:
TreeNode *rootPtr;
}
TreeNode represents a node and has data, leftPtr and rightPtr.
How do I create a copy of a tree object using a copy constructor? I want to do something like:
Tree obj1;
//insert nodes
Tree obj2(obj1); //without modifying obj1.
Any help is appreciated!
| Pseudo-code:
struct Tree {
Tree(Tree const& other) {
for (each in other) {
insert(each);
}
}
void insert(T item);
};
Concrete example (changing how you walk the tree is important to know, but detracts from showing how the copy ctor works, and might be doing too much of someone's homework here):
#include <algorithm>
#include <iostream>
#include <vector>
template<class Type>
struct TreeNode {
Type data;
TreeNode* left;
TreeNode* right;
explicit
TreeNode(Type const& value=Type()) : data(value), left(0), right(0) {}
};
template<class Type>
struct Tree {
typedef TreeNode<Type> Node;
Tree() : root(0) {}
Tree(Tree const& other) : root(0) {
std::vector<Node const*> remaining;
Node const* cur = other.root;
while (cur) {
insert(cur->data);
if (cur->right) {
remaining.push_back(cur->right);
}
if (cur->left) {
cur = cur->left;
}
else if (remaining.empty()) {
break;
}
else {
cur = remaining.back();
remaining.pop_back();
}
}
}
~Tree() {
std::vector<Node*> remaining;
Node* cur = root;
while (cur) {
Node* left = cur->left;
if (cur->right) {
remaining.push_back(cur->right);
}
delete cur;
if (left) {
cur = left;
}
else if (remaining.empty()) {
break;
}
else {
cur = remaining.back();
remaining.pop_back();
}
}
}
void insert(Type const& value) {
// sub-optimal insert
Node* new_root = new Node(value);
new_root->left = root;
root = new_root;
}
// easier to include simple op= than either disallow it
// or be wrong by using the compiler-supplied one
void swap(Tree& other) { std::swap(root, other.root); }
Tree& operator=(Tree copy) { swap(copy); return *this; }
friend
ostream& operator<<(ostream& s, Tree const& t) {
std::vector<Node const*> remaining;
Node const* cur = t.root;
while (cur) {
s << cur->data << ' ';
if (cur->right) {
remaining.push_back(cur->right);
}
if (cur->left) {
cur = cur->left;
}
else if (remaining.empty()) {
break;
}
else {
cur = remaining.back();
remaining.pop_back();
}
}
return s;
}
private:
Node* root;
};
int main() {
using namespace std;
Tree<int> a;
a.insert(5);
a.insert(28);
a.insert(3);
a.insert(42);
cout << a << '\n';
Tree<int> b (a);
cout << b << '\n';
return 0;
}
|
1,753,745 | 1,753,757 | Making render method virtual? | I'm starting with C++ in more depth while building a simple 2d game engine. In my engine I have (or want to have) an "Abstract" GameEntity class, which carries the methods draw, update, and maybe position (x, y). I will add more stuff while it occurs to me.
Classes to inherit from GameEntity would be anything that could be drawn on screen (ParticleSystem, MovingSprite, StaticSprite, GuiMenu, etc...)
My problem is that to achieve that, I have declared GameEntity draw() and update() methods virtual:
virtual draw()=0;
virtual update()=0;
So ParticleSystem has it's own draw and MovingSprite also has it's own draw() (and update()).
I know virtual functions are expensive, or at least more expensive than regular methods. Do you think that what I'm doing is awful? Or too bad? If you do, I would really appreciate a better way to do this.
Thanks!
| No, this isn't bad; the overhead isn't that significant (you might consult this answer to another question).
This is, for example, the general approach taken by OpenSceneGraph, an open source scene graph based on OpenGL. OSG has a Node class, from which all node types used in the scene graph are derived, and it uses a plethora of virtual functions.
|
1,753,785 | 1,754,202 | Combining function bodies at runtime | This is going to sound super hackish but does anyone know of a way to combine method bodies at runtime in C++? I'm currently on the path of grabbing the address of the functions then memcopy to executable memory but it has the problem of unwanted prolog/epilog.
Essentially I've got a few dozen simple operations that take the same arguments and return nothing and i want to build a function at runtime out of these simple operations.
| I can't see any practical use for this, except for the heck of it :-)
So first you should decide for a platform.
There is no way in hell you can do this in a cross-platform way.
It might actually be quite difficult to do it in a way that works across several compilers, even on the same platform.
Then the processor type, of course :-)
Then you should somehow check that the code you are copying can be relocated. Not everything can be moved around as you feel like.
You have to understand very well the calling conventions, so that you make sure you don't mess up the stack.
Know how the prolog/epilog generated by your compiler. You can probably cheat by adding at the beginning and end of the functions some code sequences that does nothing, but you can use as signature then look for (ie. nop; nop; nop; xor ax, ax; nop; push ax; pop ax; nop; nop; nop; ). Make sure is not optimized-out by the compiler :-)
Make sure you can write/execute that code. The modern CPUs and OSes don't normally allow one to write in a code segment, or to execute a non-code segment. So you will have to find out what are the ways to change the rights (100% OS specific).
Then have fun fighting stuff like "Address space layout randomization," "Stack Randomization," "Data Execution Prevention," "Heap Randomization."
Anyway, a lot of work. And pointless, except to enjoy a good challenge and in the process learn some assembly and OS internals.
Or for proving yourself as "1337," but then, asking on stackoverflow how to do it is not quite "1337," if you ask me :-)
Anyway, good luck.
|
1,754,037 | 1,754,814 | How to add picture box in win32 API using visual c++ | I have a Window (win32 API) Application in visual c++. I am not using MFC. I have to add a picutre box to my application and Change the image of this picture box periodically. Can any one help me out in achieving the above task? Thanks in advance.
| This is quite a complex task to post full code here, but I will try to give a few guidelines on how to do it:
First method is to load the image and paint it
Load your image (unfortunately the plain Win32 API has support for quite a few image formats BMP, ICO ...).
HBITMAP hImage = (HBITMAP)LoadImage(NULL, (LPCSTR)file, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_LOADTRANSPARENT);
Store the handle above somewhere in your application where you can access it from your WindowProcedure
In the WinProc on the WM_PAINT message you will need to paint the image. The code is something like:
HDC hdcMem = CreateCompatibleDC(hDC); // hDC is a DC structure supplied by Win32API
SelectObject(hdcMem, hImage);
StretchBlt(
hDC, // destination DC
left, // x upper left
top, // y upper left
width, // destination width
height, // destination height
hdcMem, // you just created this above
0,
0, // x and y upper left
w, // source bitmap width
h, // source bitmap height
SRCCOPY); // raster operation
Should work.
Now, the second way of doing it is to create a static control, with type being SS_BITMAP and set its image as:
hImage = LoadImage(NULL, file, IMAGE_BITMAP, w, h, LR_LOADFROMFILE);
SendMessage(hwnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hImage);
where hwnd is the handle of your static control.
|
1,754,042 | 1,754,059 | was not declared in this scope C++ | Why do I get this error in the code below?
class ST : public Instruction{
public:
ST (string _name, int _value):Instruction(_name,_value){}
void execute(int[]& anArr, int aVal){
//not implemented yet
cout << "im an st" <<endl;
anArr[value] = aVal;
}
virtual Instruction* Clone(){
return new ST(*this);
}
};
classes.h:81: error: ‘anArr’ was not declared in this scope
classes.h:81: error: ‘aVal’ was not declared in this scope
| You have a problem with the type of the first parameter of your execute function. Read this up to know more about how to pass arrays around.
|
1,754,295 | 1,754,384 | Search string parser in C/C++ | I work on an open source project focused around Biblical texts. I would like to create a standard string format to build up a search string. I would then need to parse the search string and run the search with the options given. There are a number of different options, from scope of the search, to searching multiple texts, to wildcards, etc.
I'm thinking that using something like lex/yacc to generate a parser for this format might be a good idea. I think the Xapian project uses lemony to achieve a similar goal. My question is, is using one (or more) of these tools the best way to accomplish this?
In addition to the question, I would appreciate any links to resources on these tools (and any others that might be options). The biggest problem I've run into so far is that most of the examples and tutorials are either geared towards a programming language or something simple like a calculator rather than parsing a string format.
| Tools like Lex and Yacc are suitable for your purposes. A parser for a search string is not that different from a parser for a programming language (the big difference is that a search string parser generates rules guiding the search, while the programming language parser generates a parse tree from where code is generated)
I assume your syntax will contain rules like the following:
expression : word
| expression AND expression
| expression OR expression
| NOT expression
| '(' expression ')'
all of which are easy to express in Yacc.
You can look at A Compact Guide to Lex & Yacc which I've found very useful for learning Lex and Yacc
|
1,754,417 | 1,767,521 | Accessing tabs on Firefox with a C++ XPCOM extension | What XPCOM interfaces should I use to detect opening, closing and switching of tabs and also get their associated URL from a firefox extension?
I have seen instances of code that manage tabs in JS, but how about from C++ ?
| You can write small JS component that will reroute tab events to your C++ component using nsIObserverService.
In C++ code you can use this snippet to register your component as observer to user defined events that is used for rerouting tab events.
NS_IMETHODIMP MyCppComponent::Observe(nsISupports *aSubject,
const char *aTopic,
const PRUnichar *aData)
{
if( !strcmp( aTopic, "xpcom-startup" ) )
{
nsCOMPtr<nsIObserverService> observerService =
do_GetService( "@mozilla.org/observer-service;1" );
observerService->AddObserver( this, "my-tab-open", false );
observerService->AddObserver( this, "my-tab-close", false );
observerService->AddObserver( this, "my-tab-select", false );
}
else if( !strcmp( aTopic, "my-tab-open" ) )
{
/* . . . */
}
else if( !strcmp( aTopic, "my-tab-close" ) )
{
/* . . . */
}
else if( !strcmp( aTopic, "my-tab-select" ) )
{
/* . . . */
}
/* . . . */
}
And in helper JS component you should to subscribe to tab events and in event handlers you can extract desired data and raise user defined events to execute C++ code.
function tabOpened(event) {
var obsSvc = CC["@mozilla.org/observer-service;1"].
getService(CI.nsIObserverService);
obsSvc.notifyObservers(event.target.linkedBrowser.contentWindow,
"my-tab-open", "some data");
}
function tabClosed(event) {
var obsSvc = CC["@mozilla.org/observer-service;1"].
getService(CI.nsIObserverService);
obsSvc.notifyObservers(event.target.linkedBrowser.contentWindow,
"my-tab-close", "some data");
}
function tabSelected(event) {
var obsSvc = CC["@mozilla.org/observer-service;1"].
getService(CI.nsIObserverService);
obsSvc.notifyObservers(event.target.linkedBrowser.contentWindow,
"my-tab-select", "some data");
}
function contentWndLoad(event) {
var obsSvc = CC["@mozilla.org/observer-service;1"].
getService(CI.nsIObserverService);
var browser = getMostRecentBrowserWindow().getBrowser();
browser.tabContainer.addEventListener("TabOpen", tabOpened, false);
browser.tabContainer.addEventListener("TabClose", tabClosed, false);
browser.tabContainer.addEventListener("TabSelect", tabSelected, false);
}
MyJsComponent.prototype = {
/* . . . */
observe: function(aSubject, aTopic, aData) {
switch(aTopic) {
case "xpcom-startup":
var obsSvc = CC["@mozilla.org/observer-service;1"].
getService(CI.nsIObserverService);
obsSvc.addObserver(this, "toplevel-window-ready", false);
break;
case "toplevel-window-ready":
aSubject.addEventListener("load", contentWndLoad, false);
break;
}
}
/* . . . */
}
Also there are some additional code that you should add to handle specific cases. For instance when user close browser window you won't receive TabClose events for opened tabs in that window... And don’t forget to unregister your observers when you longer need them.
|
1,754,503 | 1,755,103 | Logging safely from a worker thread? | In one of my worker threads I want to do some logging. The log messages are channeled to a GUI textarea, which should only be accessed from the main thread. So the problem is: how do I log messages safely from a worker thread?
My current solution is to have the logging function check whether we are currently in the main thread. If yes, then just log. If no, then add the message to a queue of pending messages (this queue is protected by a mutex). The main thread also has a timer who's callback function (which also executes in the main thread) takes care of dequeueing and logging any pending messages.
Above solution is just my own little invention. Are there better or more standard solutions to this problem?
| If you have one rule for logging in one thread ("just do it now") and another rule for other threads ("add it to a queue for later") then your logging will get out of order. I can't imagine this being a good thing. Have one rule for all your logging - add it to the queue.
|
1,754,541 | 1,754,580 | Error with parsing string and trying to find '\0' character | I'm trying to get one side to send an error message to client, but client isn't able to parse it correctly.
My error is >>>>> in my parseString function, it lets index = 0 and therefore I get an out of range for my 'substr' call.
Server Side:::
#define ERRBUFSIZE 51
string error = "Error - Already Registered: ";
error.append(name);
char err[ERRBUFSIZE];
err[0] = 0;
std::copy(error.begin(), error.end(), err+1);
err[error.size() + 2] = '\0';
if (send(sock, &err, ERRBUFSIZE, 0) < 0)
{
DieWithError("send() failed");
}
Client side ( who is receiving )::
char msgBuffer[ERRBUFSIZE];
int bytesRcvd = 0;
int totalRcvd = 0;
while(totalRcvd != ERRBUFSIZE)
{
// Get Message from Server
if ((bytesRcvd = recv(sock, msgBuffer, ERRBUFSIZE, 0)) < 0)
DieWithError("recv() failed or connection closed prematurely");
totalRcvd += bytesRcvd;
}
cout << "Bytes received: " << totalRcvd << endl;
msgBuffer[totalRcvd] = '\0';
string rcvMsg( msgBuffer , msgBuffer + totalRcvd);
cout << rcvMsg << endl;
rcvMsg = parseString(rcvMsg);
return rcvMsg;
where....
string TCPClient::parseString(string message)
{
cout << "parsing new string" << endl;
int index = message.find('\0');
string result = message.substr(0, index);
cout << "THE RESULT :: " << result << endl;
return result;
}
| Why not change your parseString to the following:
string TCPClient::parseString(const string& message, int strLength )
{
cout << "parsing new string" << endl;
string result = message.substr( 0, strLength );
cout << "THE RESULT :: " << result << endl;
return result;
}
And then change the calling code to:
rcvMsg = parseString(rcvMsg, totalRcvd );
Failing that you could even use the string's "size()" function.
Edit: Its also worth noting that find will advance through the string until the '\0' character is found but WON'T actually look for it. It seems a bit of an odd plan to put a string into a string object (Which stores length) and then try and calculate length yourself through a, slow, iterative process.
Edit2: If you just want to do it with a character array you can do a manual search as follows.
int index = 0;
while( *charString++ != '\0' ) index++;
Its that simple :)
|
1,754,787 | 2,318,307 | WMI Error in Windows Server 2008 (WMI Provider) | I've implemented a WMI provider (Window service, Instance, Methods and Properties provider).
It works fine on Windows Server 2003, but when it run on Windows Server 2008 with non-local administrator user, I cannot query it.
The error I get is 0x8004101d - unexpected error.
When the service user is a local admin everything is OK.
What could it be???
Thanks!
| OK, the problem was that I didn't specify the HostingModel, so it defaulted to NetworkServiceHost. The one needed one is LocalSystemHostOrSelfHost (that is the default in prior to Vista OSs).
|
1,754,972 | 1,873,160 | Launching applications silently? | My C++ application calls VLC as a subprocess. Is there a way to avoid having the GUI pop-up? I am looking for a Mac and a Windows solution. Hackish workarounds are welcome too.
PS: I know there is such a thing as cvlc (command-line version of VLC), but I haven't found any builds for it online. You do get it when you make the build yourself, but that hasn't worked out yet on my Snow Leopard machine. I also need a Windows version, but I don't feel courageous enough to attempt making a VLC build myself on this platform.
Solved
All I had to do was add the "-I dummy" parameters.
| I found the answer. VLC allows you to start without GUI by using:
VLC -I dummy
Starts the "dummy" interface.
VLC -I rc
Starts the "remote control" interface, which allows you to send commands using the stdin channel.
|
1,755,000 | 1,755,070 | Passing around fixed-size arrays in C++? | Basically I'd like to do something like that:
int[3] array_func()
{
return {1,1,1};
}
int main(int argc,char * argv[])
{
int[3] point=array_func();
}
But that doesn't seem legal in C++. I know I can use vectors, but since I know the size of the array is a constant, it seems like a loss of performance is likely to occur.
I'd also like to avoid a new if I can, because allocating stuff on the stack is easier and also likely to improve performance.
What's the solution here?
| Using C++0x, the almost finalized new C++ standard (already implemented in latest gcc and msvc IIRC), you can do it exactly as you want! Simply use std::array instead of int[3].
std::array<int, 3> array_func()
{
return {1,1,1};
}
int main(int argc,char * argv[])
{
std::array<int, 3> point = array_func();
}
|
1,755,010 | 1,755,380 | Best way to return early from a function returning a reference | Let us say we have a function of the form:
const SomeObject& SomeScope::ReturnOurObject()
{
if( ! SomeCondition )
{
// return early
return ;
}
return ourObject;
}
Clearly the code above has an issue, if the condition fails then we have a problem as to how to return from this function.
The crux of my question is what is the best way to handle such a situation?
| This isn't a syntactic issue, but a design issue. You have to specify what ReturnOurObject() is supposed to return when SomeCondition is true. That depends mainly on what the function is going to be used for. And that you haven't told us.
Depending on the design issues, I see a few possible syntactic ways out of this:
return a reference to some other object; you would have to have some ersatz object somewhere
have a special "no-object-to-return" object somewhere that you return a reference to; clients can check for this; if they don't check they get reasonable default behavior
return a pointer, not a reference; clients would have to always check the return value of the function
throw an exception; if SomeCondition is something exceptional which clients can not deal with that would be appropriate
assert; if SomeCondition should always hold, it should be asserted
|
1,755,196 | 1,775,247 | Receive WM_COPYDATA messages in a Qt app | I am working on a Windows-only Qt application, and I need to receive data from a Microsoft OneNote plugin. The plugin is written in C#, and can send WM_COPYDATA messages. How do I receive these messages in a C++ Qt app?
I need to:
Be able to specify the "class name" a window registers as when it calls RegisterClassEx, so that I can make sure the plugin sends WM_COPYDATA messages to the correct window.
Have access to the message id to check if it's WM_COPYDATA and lParam, which contains the COPYDATASTRUCT with the actual data. This information is passed in WndProc, but I am unable to find a hook where I can intercept these messages.
| This can all be handled within Qt:
Extend QWidget with a class that will capture the WM_COPYDATA messages:
class EventReceiverWindow : public QWidget
{
Q_OBJECT
public:
EventReceiverWindow();
signals:
void eventData(const QString & data);
private:
bool winEvent ( MSG * message, long * result );
};
Generate a GUID to set as the QWidget's windowTitle:
EventReceiverWindow::EventReceiverWindow()
{
setWindowTitle("ProjectName-3F2504E0-4F89-11D3-9A0C-0305E82C3301::EventReceiver");
}
Override winEvent to handle the WM_COPYDATA structure and emit a signal when you get it:
bool EventReceiverWindow::winEvent ( MSG * message, long * result )
{
if( message->message == WM_COPYDATA ) {
// extract the string from lParam
COPYDATASTRUCT * data = (COPYDATASTRUCT *) message->lParam;
emit eventData(QString::fromAscii((const char *)data->lpData, data->cbData));
// keep the event from qt
*result = 0;
return true;
}
// give the event to qt
return false;
}
In another class, you can use this class to receive the message strings:
EventReceiverWindow * eventWindow = new EventReceiverWindow;
QObject::connect(eventWindow, SIGNAL(eventData(const QString &)), this, SLOT(handleEventData(const QString &)));
...
void OneNoteInterface::handleEventData(const QString &data)
{
qDebug() << "message from our secret agent: " << data;
}
And in the program that is sending the messages, simply find the window by the unique window caption. Here's an example in C#:
private struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}
private const int WM_COPYDATA = 0x4A;
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);
private void sendMessageTo(IntPtr hWnd, String msg)
{
int wParam = 0;
int result = 0;
if (hWnd != IntPtr.Zero )
{
byte[] sarr = System.Text.Encoding.Default.GetBytes(msg);
int len = sarr.Length;
COPYDATASTRUCT cds;
cds.dwData = IntPtr.Zero;
cds.lpData = msg;
cds.cbData = len + 1;
result = SendMessage(hWnd, WM_COPYDATA, wParam, ref cds);
}
}
then you can:
IntPtr hwnd = FindWindowByCaption(IntPtr.zero, "ProjectName-3F2504E0-4F89-11D3-9A0C-0305E82C3301::EventReceiver");
sendMessageTo(hwnd, "omg hai");
|
1,755,392 | 1,755,400 | Supressing warnings for a codeblock using gcc 4.1.2? | I have a section of code that uses a Boost library that results in a lot of these type of warning messages:
class x has virtual functions but non-virtual destructor
Using g++ 4.1.2, how do I temporarily disable warnings for this codeblock then enable them again after it.
Everything I try (pragma gcc diagnostic, etc) seems to only be supported by a later version of g++.
How do I suppress just these warnings?
| Take a look at the -Wno-non-virtual-dtor.
You can restrict this option to affect only certain files.
Can you move your "bad" code to separate c++ file? If so, turn this option only for that file.
|
1,755,639 | 1,756,989 | Is every application using anything dependent on VC++9 runtime required to have a manifest embedded? | I don't get what this article on R6034 says. Looks like it states that every application dependent on VC++9 runtime must have a manifest.
Now we have a DLL that we ship to customers, that depends on VC++9 runtime and has a manifest embedded. Does every application using our DLL also need to have a manifest embedded?
| No, your customers do not need manifests. The loader deals with manifests for every image it loads... so if your DLL has a manifest it will be parsed/applied properly, regardless of how your DLL is loaded.
|
1,756,062 | 1,843,666 | Anyone used libvlc on Mac? | Edit
I've been able to simplify the reproduction of the error:
When trying to build this sample:
$ cc example.c -arch i386 -lvlc.2 -L/Applications/VLC.app/Contents/MacOS/lib/ -I/Applications/VLC.app/Contents/MacOS/include/ -o example
$ ./example
dyld: Library not loaded: @loader_path/lib/libvlc.2.dylib
Referenced from: /Users/francis/src/playground/libvlc/./example
Original Post
I am experiencing the following behavior:
Create new XCode project (Cocoa or command line tool)
Link with libvlc.2.dylib found in /Applications/VLC.app/Contents/MacOS/lib
Run the application
=> Crashes with stack-trace pointing pointing to __dyld_dyld_fatal_error at the top and __dyld__dyld_start at the bottom.
What am I doing wrong here? Maybe I need to link with a fresh VLC build, but I haven't yet succeeded building it on Snow Leopard and the MacPort doesn't work as well (fails during build phase).
Can anyone point me in the right direction for getting it to work?
| Check with otool -L if your programm is correctly linked with all your libs.
relink every dylib with install_name_tools
|
1,756,242 | 1,757,024 | Enumerating all IDispatch implementing objects on a machine | I'd like to enumerate all IDispatch supporting objects on a machine. At the moment I need to know what the class id or prog id is but, for inspecting my machine, I'd like to know if I can just enumerate all the objects that implement IDispatch.
Is this even possible?
Any help would be much appreciated :)
| That's a very odd request. The rub is in the "all" stipulation. Simple enumeration through the HKCR\Typelib key and LoadTypeLib() isn't enough, a COM server is not required to publish a type library. You would actually have to CoCreateInstance() the coclass and QueryInterface for IDispatch. Not only is this slow, it is also risky.
You might get a better answer if you explain why you would actually contemplate doing something like this. Calling IDispatch::Invoke() without having some kind of idea what the arguments mean or what the side-effects might be is a recipe for disaster. Stay away from method names like "ReformatDrive".
|
1,756,285 | 1,756,419 | Stack Size Estimation | In multi-threaded embedded software (written in C or C++), a thread must be given enough stack space in order to allow it to complete its operations without overflowing. Correct sizing of the stack is critical in some real-time embedded environments, because (at least in some systems I've worked with), the operating system will NOT detect this for you.
Usually, the stack size for a new thread (other than the main thread) is designated at the time that thread is created (i.e. in an argument to pthread_create() or the like). Often, these stack sizes are hard-coded to values that are known to be good at the time the code was originally written or tested.
However, future changes to the code often break the assumptions on which the hard-coded stack sizes were based, and one fateful day, your thread enters one of the deeper branches of its call graph and overflows the stack -- bringing down the whole system or silently corrupting memory.
I have personally seen this problem in the case where code executed in the thread declares struct instances on the stack. When the struct is augmented to hold additional data, the stack size inflates accordingly, potentially allowing stack overflows to occur. I imagine this could be a huge problem for established codebases where the full effects of adding fields to a structure cannot be known immediately (too many threads/functions to find all the places where that struct is used).
Since the usual response to "stack sizing" questions is "they're not portable", let's assume that the compiler, operating system, and processor are all known quantities for this investigation. Let's also assume recursion isn't used, so we're not dealing with the possibility an "infinite recursion" scenario.
What are some reliable ways to estimate the necessary stack size for a thread? I'd prefer methods that are offline (static analysis) and automatic, but all ideas are welcome.
| Runtime-Evaluation
An online method is to paint the complete stack with a certain value, like 0xAAAA (or 0xAA, whatever your width is). Then you can check how large the stack has maximally grown in the past by checking how much of the painting is left untouched.
Have a look at this link for an explanation with illustration.
The advantage is that it's simple. A disadvantage is that you cannot be certain that your stack size won't eventually exceed the amount of used stack during your testing.
Static Evaluation
There are some static checks and I think there even exists a hacked gcc version that tries to do this. The only thing I can tell you is that static checking is very difficult to do in the general case.
Also have a look at this question.
|
1,756,700 | 1,757,368 | Compile Qt application for Windows Mobile 5 | I'm trying to compile a small Qt application for windows Mobile 5.
so I've few questions:
currently i'm using ubuntu 9.10, I've hear some thing about cross-compilation but I din't found a real example of have to do it. Will it be possible to compile from linux?
How to compile an application for mobile anywhere(windows(VS, mingw,etc), linux(cmake,qmake, etc))
tnx,
| In order to compile applications for Windows Mobile 5 you will need either:
at least Visual Studio 2005 Standard or Visual Studio 2008 Professional (Microsoft has moved Windows Mobile support in the Professional Version).
Note: You cannot use the Express versions of Visual Studio to create applications for Windows Mobile platform.
CeGCC which can be crosscompiled from Linux.
Regarding Qt on Windows Mobile, you should read this Dr. Dobb's Article: Qt and Windows CE
|
1,756,867 | 1,756,903 | Qt moc_ include file problem | I'm trying to compile the basic tutorial program at http://doc.trolltech.com/4.4/mainwindows-application.html and running into a problem.
Doing things the way the tutorial program does them, gives a compile error:
In file included from debug\moc_mainwindow.cpp:10:
debug\../mainwindow.h:2: error: expected class-name before '{' token
debug\../mainwindow.h:5: error: ISO C++ forbids declaration of `Q_OBJECT' with no type
The problem is the need for
#include <QtGui>
The tutorial program puts this in mainwindow.cpp which is the desirable way to do it, but then it doesn't get copied into the moc file.
If I put it into mainwindow.h instead, everything works fine, but doing that in every header file is inelegant and will extend compile times once the program gets large.
Is this something that changed since the tutorial was written? (I'm using the latest Qt 4.5.3, Windows SDK install, compiling from the command line.) Am I missing something, or is there any known fix for this problem?
| Your header file has to know about Qt stuff. So there is no way to avoid including QtGui.
Edit: You shouldn't worry too much about compilation time. The inclusions will happen anyways. Maybe you can split your header into none Qt-related parts if it really gets annoying.
|
1,757,093 | 1,757,806 | Obtain the true name of the currently select file in the common file dialog? | One can get the text of the selected item in the list-view of a common dialog. But one can NOT get its PIDL, and if the user has chosen to hide known extensions (the default), then one cannot really tell what file was selected without either its extension or its PIDL.
So possible ways to solve this might be:
Obtain an IShellView from the
standard open file dialog. The
underlying IShellView can tell what
the PIDL is for the current
selection. So if I could simply get
ahold of the IShellView, I'd be
golden. Unfortunately, I see no
CDM_xxx that would do it. And I
can't think off the top of my head
of anything that might achieve it!!!
:(
Some other idea?!
We used to rely upon the fact that the Windows 9x, 2000, and XP version of the common file dialog stored each item's PIDL in the LVITEM data (original credit to Paul DiLascia):
LPCITEMIDLIST pidlItem = (LPCITEMIDLIST)pListCtrl->GetItemData(nItem);
However, starting with Vista's common controls and above, that technique fails :(
Any thoughts?
EDIT: I need to be able to obtain this information not only for the currently selected item in the list view, but for all items in the list view.
EDIT2: The reason I need to dig so deep:
In prior versions of our app we provide the ability to: (1) Press a custom button "Preview" that closes the dialog, but transfers to the app the list of items currently displayed in the view, in their visible order, along with the index of the one currently highlighted. This list must be fully specified - seeing 3 files that are all "J1329192" (when there are really 3 files "J1329192.xyz" "J1329192.xzy" and "J1329192.zyx" [in that order) is not useful.
Users are allowed to type a partial filename filter into the "file name:" field, and the common dialog will show only files that match the given partial filter, in the sort-order that the user has chosen. So to report back to the app exactly what the user wanted to preview requires that we be able to query that information from the list view control (or the common dialog itself).
We do other enhancements to the file dialog as well - including an in-place preview pane that shows the user's current selection as a thumbnail, as well as have a custom recent-places interface, etc. All of this was possible (with a lot of work) prior to Vista. Post Vista, I have run into wall upon wall. For the time being, we use a standard file dialog with only a very few features of our own, which doesn't sit well with customers (what happened to feature X?!)
There are other enhancements, but that's a good rough overview. And they all boil down to requiring the knowledge of "really, honestly, what file specifically is in the view at index X?" And for unknown reasons - Microsoft doesn't seem to feel the need to provide such an interface. In fact they never did. Only through some hacking and reverse engineering were we able to figure out how things worked under the hood and get the needed info. And yes, that's unsupported, and yes, MS inevitably broke our code. I don't really blame them for that - what I do find obnoxious is that their newer, spiffier interface is far more closed than their older one - and they did not provide more up-front interfaces - supported interfaces - for doing these dialog enhancements. Its like they took a big couple of steps backwards - and none forwards (in the name of progress).
| Send WM_USER+7 to get the browser, and then get its active shell view's IShellView interface.
You know the usual consequence of using undocumented behavior right?
|
1,757,110 | 1,758,163 | How could running code in the debugger makes it faster? | It never happened to me. In Visual Studio, I have a part of code that is executed 300 times, I time it every iteration with the performance counter, and then average it.
If I'm running the code in the debugger I get an average of 1.01 ms if I run it without the debugger I get 1.8 ms.
I closed all other apps, I rebooted, I tried it many times: Always the same timing.
I'm trying to optimize my code, but before throwing me into changing the code, I want to be sure of my timings. To have something to compare with.
What can cause that strange behaviour?
Edit:
Some clarification:
I'm running the same compiled piece of code: the release build. The only difference is (F5 vs CTRL-F5)
So, the compiler optimization should not be invoved.
Since each calcuated times were verry small, I changed the way I benchmark: I'm now timing the 300 iterations and then divide by 300. I have the same result.
About caching: The code is doing some image cross correlation, with different images at each iterations. The steps of the processing are not modified by the data in the images. So, I think caching is not the problem.
| I think I figured it out.
If I add a Sleep(3000) before running the tests, they give the same result.
I think it has something to do with the loading of misc. dlls. In the debugger, the dlls were loaded before any code was executed. Outside the debugger, the dlls were loaded on demand, and one or more were loaded after the timer was started.
Thanks all.
|
1,757,159 | 1,757,191 | the compiler doesn't seem to accept Agent class | probably the answer is quite silly but I need a pair fresh of eyes to spot the problem, if you will. this is the excerpt from _tmain:
Agent theAgent(void);
int m = theAgent.loadSAG();
and this is agent.h, which I included in _tmain:
#ifndef AGENT_H
#define AGENT_H
class Agent {
public:
Agent(void);
int loadSAG(void);
~Agent(void);
};
#endif
and agent.cpp relevant function:
int Agent::loadSAG(void) {
return 3;
}
so why in the world I get this error: error C2228: left of '.loadSAG' must have class/struct/union ?
Thanks in advance.
| Agent theAgent(void);
This is a function declaration, just change it to:
Agent theAgent;
|
1,757,448 | 1,757,482 | How do I properly return a char * from an Unmanaged DLL to C#? | Function signature:
char * errMessage(int err);
My code:
[DllImport("api.dll")]
internal static extern char[] errMessage(int err);
...
char[] message = errMessage(err);
This returns an error:
Cannot marshal 'return value': Invalid managed/unmanaged type combination.
What am I doing wrong? Thanks for any help.
| try this:
[DllImport("api.dll")]
[return : MarshalAs(UnmanagedType.LPStr)]
internal static extern string errMessage(int err);
...
string message = errMessage(err);
I believe C# is smart enough to handle the pointer and return you a string.
Edit: Added the MarshalAs attribute
|
1,757,785 | 1,759,052 | Problem statically linking MFC libraries | I have a Visual Studio 6 workspace I'm trying to convert to a Visual Studio 2008 solution. The output of said solution is a .dll. It has to be a .dll and it needs to statically link MFC as I can't redistribute MFC to existing customers.
The solution consists of three projects, say A, B, C. C is the Active Project, outputs the .dll and depends on B. B outputs a .lib and depends on A. A outputs a .lib.
In the General configuration properties I have A and B set to Static Library (.lib) and C set to Dynamic Library (.dll). All three projects are set to "Use MFC in a Static Library." Also, all three projects are set to "Multi-threaded" for Runtime Library and none of them have _AFXDLL defined.
Everything builds correctly up until the final linking stage where I see this:
1>nafxcw.lib(wincore.obj) : error LNK2005: _IsPlatformNT already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _InitMultipleMonitorStubs already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _xGetSystemMetrics@4 already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _xMonitorFromPoint@12 already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _xMonitorFromRect@8 already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _xMonitorFromWindow@8 already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _xGetMonitorInfo@8 already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _xEnumDisplayMonitors@16 already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _xEnumDisplayDevices@16 already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _g_pfnGetSystemMetrics already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _g_pfnMonitorFromWindow already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _g_pfnMonitorFromRect already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _g_pfnMonitorFromPoint already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _g_pfnGetMonitorInfo already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _g_pfnEnumDisplayMonitors already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _g_pfnEnumDisplayDevices already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _g_fMultiMonInitDone already defined in A.lib(Globals.obj)
1>nafxcw.lib(wincore.obj) : error LNK2005: _g_fMultimonPlatformNT already defined in A.lib(Globals.obj)
1>nafxcw.lib(viewprnt.obj) : error LNK2005: "public: virtual int __thiscall CPrintingDialog::OnInitDialog(void)" (?OnInitDialog@CPrintingDialog@@UAEHXZ) already defined in B.lib(ImagePropertiesDlg.obj)
1>nafxcw.lib(viewprnt.obj) : error LNK2005: "public: __thiscall CPrintingDialog::CPrintingDialog(class CWnd *)" (??0CPrintingDialog@@QAE@PAVCWnd@@@Z) already defined in B.lib(ImagePropertiesDlg.obj)
1>nafxcw.lib(viewprnt.obj) : error LNK2005: "public: virtual void __thiscall CPrintingDialog::OnCancel(void)" (?OnCancel@CPrintingDialog@@UAEXXZ) already defined in B.lib(ImagePropertiesDlg.obj)
I've Googled the problem to death and seen other people with a similarish issue, but can't seem to solve it. I tried adding nafxcw.lib to the Ignored libraries for C, but that turned this batch of linker errors into 1500+ unresolved symbol errors. I can get it to compile/link if I make it dynamically link MFC, but like I said, I need it to statically link. I feel like I'm missing something rather simple but can't seem to wrap my head around it. Any and all random thoughts and ideas will be greatly appreciated.
| As is often the case, the solution turned out to be so mundane and obvious, I'm still kicking myself for banging my head on it for so long.
Basically, project A referenced above was not a project I directly pulled from the old VS6 workspace, but rather a project that had previously been converted by another team for use in another application. I assumed it was functionally equivalent to the original one, but that is very much not the case. These linking errors are actual, valid multiply defined linking errors. When I started digging in, I found that the first batch of errors was from including multimon.h in project A (something I don't even need, just removed it) and the second batch is from a class that is actually defined in both A and B.
Like I said, I'm still groaning over here, but at least I should be able to fix my problem now. Thanks for the help and always remember to NEVER assume ANYTHING.
|
1,757,791 | 1,757,845 | C++ template partial specialization - specializing one member function only | Bumped into another templates problem:
The problem: I want to partially specialize a container-class (foo) for the case that the objects are pointers, and i want to specialize only the delete-method. Should look like this:
The lib code
template <typename T>
class foo
{
public:
void addSome (T o) { printf ("adding that object..."); }
void deleteSome (T o) { printf ("deleting that object..."); }
};
template <typename T>
class foo <T *>
{
public:
void deleteSome (T* o) { printf ("deleting that PTR to an object..."); }
};
The user code
foo<myclass> myclasses;
foo<myclass*> myptrs;
myptrs.addSome (new myclass());
This results into the compiler telling me that myptrs doesnt have a method called addSome.
Why ?
Thanx.
Solution based on tony's answer here the fully compilable stuff
lib
template <typename T>
class foobase
{
public:
void addSome (T o) { printf ("adding that object..."); }
void deleteSome (T o) { printf ("deleting that object..."); }
};
template <typename T>
class foo : public foobase<T>
{ };
template <typename T>
class foo<T *> : public foobase<T *>
{
public:
void deleteSome (T* o) { printf ("deleting that ptr to an object..."); }
};
user
foo<int> fi;
foo<int*> fpi;
int i = 13;
fi.addSome (12);
fpi.addSome (&i);
fpi.deleteSome (12); // compiler-error: doesnt work
fi.deleteSome (&i); // compiler-error: doesnt work
fi.deleteSome (12); // foobase::deleteSome called
fpi.deleteSome (&i); // foo<T*>::deleteSome called
| Second solution (correct one)
template <typename T>
class foo
{
public:
void addSome (T o) { printf ("adding that object..."); }
void deleteSome(T o) { deleteSomeHelper<T>()(o); }
protected:
template<typename TX>
struct deleteSomeHelper { void operator()(TX& o) { printf ("deleting that object..."); } };
template<typename TX>
struct deleteSomeHelper<TX*> { void operator()(TX*& o) { printf ("deleting that PTR to an object..."); } };
};
This solution is valid according to Core Issue #727.
First (incorrect) solution: (kept this as comments refer to it)
You cannot specialize only part of class. In your case the best way is to overload function deleteSome as follows:
template <typename T>
class foo
{
public:
void addSome (T o) { printf ("adding that object..."); }
void deleteSome (T o) { printf ("deleting that object..."); }
void deleteSome (T* o) { printf ("deleting that object..."); }
};
|
1,757,942 | 1,760,924 | Interlocked and Memory Barriers | I have a question about the following code sample (m_value isn't volatile, and every thread runs on a separate processor)
void Foo() // executed by thread #1, BEFORE Bar() is executed
{
Interlocked.Exchange(ref m_value, 1);
}
bool Bar() // executed by thread #2, AFTER Foo() is executed
{
return m_value == 1;
}
Does using Interlocked.Exchange in Foo() guarantees that when Bar() is executed, I'll see the value "1"? (even if the value already exists in a register or cache line?) Or do I need to place a memory barrier before reading the value of m_value?
Also (unrelated to the original question), is it legal to declare a volatile member and pass it by reference to InterlockedXX methods? (the compiler warns about passing volatiles by reference, so should I ignore the warning in such case?)
Please Note, I'm not looking for "better ways to do things", so please don't post answers that suggest completely alternate ways to do things ("use a lock instead" etc.), this question comes out of pure interest..
| The usual pattern for memory barrier usage matches what you would put in the implementation of a critical section, but split into pairs for the producer and consumer. As an example your critical section implementation would typically be of the form:
while (!pShared->lock.testAndSet_Acquire()) ;
// (this loop should include all the normal critical section stuff like
// spin, waste,
// pause() instructions, and last-resort-give-up-and-blocking on a resource
// until the lock is made available.)
// Access to shared memory.
pShared->foo = 1
v = pShared-> goo
pShared->lock.clear_Release()
Acquire memory barrier above makes sure that any loads (pShared->goo) that may have been started before the successful lock modification are tossed, to be restarted if neccessary.
The release memory barrier ensures that the load from goo into the (local say) variable v is complete before the lock word protecting the shared memory is cleared.
You have a similar pattern in the typical producer and consumer atomic flag scenerio (it is difficult to tell by your sample if that is what you are doing but should illustrate the idea).
Suppose your producer used an atomic variable to indicate that some other state is ready to use. You'll want something like this:
pShared->goo = 14
pShared->atomic.setBit_Release()
Without a "write" barrier here in the producer you have no guarantee that the hardware isn't going to get to the atomic store before the goo store has made it through the cpu store queues, and up through the memory hierarchy where it is visible (even if you have a mechanism that ensures the compiler orders things the way you want).
In the consumer
if ( pShared->atomic.compareAndSwap_Acquire(1,1) )
{
v = pShared->goo
}
Without a "read" barrier here you won't know that the hardware hasn't gone and fetched goo for you before the atomic access is complete. The atomic (ie: memory manipulated with the Interlocked functions doing stuff like lock cmpxchg), is only "atomic" with respect to itself, not other memory.
Now, the remaining thing that has to be mentioned is that the barrier constructs are highly unportable. Your compiler probably provides _acquire and _release variations for most of the atomic manipulation methods, and these are the sorts of ways you would use them. Depending on the platform you are using (ie: ia32), these may very well be exactly what you would get without the _acquire() or _release() suffixes. Platforms where this matters are ia64 (effectively dead except on HP where its still twitching slightly), and powerpc. ia64 had .acq and .rel instruction modifiers on most load and store instructions (including the atomic ones like cmpxchg). powerpc has separate instructions for this (isync and lwsync give you the read and write barriers respectively).
Now. Having said all this. Do you really have a good reason for going down this path? Doing all this correctly can be very difficult. Be prepared for a lot of self doubt and insecurity in code reviews and make sure you have a lot of high concurrency testing with all sorts of random timing scenerios. Use a critical section unless you have a very very good reason to avoid it, and don't write that critical section yourself.
|
1,757,962 | 1,757,989 | C++ boost shared array swapping pointers (simple question) | I'm new to boost shared arrays.
There is existing code that declares two arrays:
boost::shared_array<unsigned char> src;
boost::shared_array<unsigned char> dest;
All I want to do is swap what each array is pointing to (src becomes dest, and dest becomes src). As I understand it, the shared_array.get() method returns a pointer to one of its elements (can be of any type).
So my added declaration is:
boost::shared_array<unsigned char> temp;
And my added code is:
temp.get() = src.get();
src.get() = dest.get();
dest.get() = temp.get();
Each of these lines fail; compile error is C2016: '=' : left operand must be l-value.
I am a C++ newbie, so I googled the error and see that that error message means that the left hand operand is not assignable. Yet the left hand sides are all pointers and pointers can be assigned to other pointers.
So I'm not sure what I'm doing wrong. Can someone please help me out?
Thanks in advance.
jbu
| The correct way to swap two shared_arrays (or most other Boost shared pointer types) is to use the swap member function:
src.swap(dest);
This swaps the pointers and reference counts used by each of the shared_arrays:
void swap(shared_array<T> & other)
{
std::swap(px, other.px);
pn.swap(other.pn);
}
|
1,758,026 | 1,759,114 | Format the output of qDebug for QMaps | i am currently in the process of maintaining a legacy app. This has quite a few structures like:
QMap<QString, QMap<QString, QMap<QString, QMap<QString, QVariant> > > > Dep;
As interfaces are hardly used and I only need to make minor adjustments, I would like to keep the structure as it is, although some refactoring might be needed anyway.
But to be able to understand what is going on, currently I just put some qDebug() << Dep; in there, and try to understand the output.
Problem is that it has no formatting at all. Does anyone know of a little script to create a better understandable display format? Or maybe of some patches to Qt?
To give you an example for my suffering:
QMap(("Test enable|test enable block", QMap(("disabled", QMap(("testblock1", QMap(("enableblock", QVariant(QString, "false") ) ) ) ) ) ( "enabled" , QMap(("testblock1", QMap(("enableblock", QVariant(QString, "true") ) ) ) ) ) ) ) ( "Test enable|test enable key" , QMap(("disabled", QMap(("testblock1|testkey", QMap(("enablekey", QVariant(QString, "false") ) ) ) ) ) ( "enabled" , QMap(("testblock1|testkey", QMap(("enablekey", QVariant(QString, "true") ) ) ) ) ) ) ) ( "testinsertitems|Insert item" , QMap(("test1", QMap(("testinsertitems|testinsert", QMap(("insertitems", QVariant(QVariantMap, QMap(("test1", QVariant(QString, "test1") ) ) ) ) ) ) ( "testinsertitems|testremove" , QMap(("removeitems", QVariant(QVariantMap, QMap(("test1", QVariant(QString, "test1") ) ) ) ) ) ) ) ) ( "test2" , QMap(("testinsertitems|testinsert", QMap(("insertitems", QVariant(QVariantMap, QMap(("test2", QVariant(QString, "test2") ) ) ) ) ) ) ( "testinsertitems|testremove" , QMap(("removeitems", QVariant(QVariantMap, QMap(("test2", QVariant(QString, "test2") ) ) ) ) ) ) ) ) ) ) ( "testsetminmax|test setmin" , QMap(("2", QMap(("testsetminmax|testkey1", QMap(("setmin", QVariant(int, 2) ) ) ) ( "testsetminmax|testkey2" , QMap(("setmax", QVariant(int, 2) ) ) ) ) ) ( "3" , QMap(("testsetminmax|testkey1", QMap(("setmin", QVariant(int, 3) ) ) ) ( "testsetminmax|testkey2" , QMap(("setmax", QVariant(int, 3) ) ) ) ) ) ) ) ( "testsetvalue|test set value" , QMap(("2", QMap(("testsetvalue|testkey1", QMap(("setvalue", QVariant(QString, "2") ) ) ) ( "testsetvalue|testkey2" , QMap(("setvalue", QVariant(QString, "2") ) ) ) ( "testsetvalue|testkey3" , QMap(("setvalue", QVariant(QString, "2") ) ) ) ) ) ( "3" , QMap(("testsetvalue|testkey1", QMap(("setvalue", QVariant(QString, "3") ) ) ) ( "testsetvalue|testkey2" , QMap(("setvalue", QVariant(QString, "3") ) ) ) ( "testsetvalue|testkey3" , QMap(("setvalue", QVariant(QString, "3") ) ) ) ) ) ) ) )
Thanks
| This one is for n-dimensions and will use the standard qDebug output for known types:
template<class NonMap>
struct Print
{
static void print(const QString& tabs, const NonMap& value)
{
qDebug() << tabs << value;
}
};
template <class Key, class ValueType >
struct Print<class QMap<Key, ValueType> >
{
static void print(const QString& tabs, const QMap< Key, ValueType>& map )
{
const QString extraTab = tabs + "\t";
QMapIterator<Key, ValueType> iterator(map);
while(iterator.hasNext())
{
iterator.next();
qDebug() << tabs << iterator.key();
Print<ValueType>::print(extraTab, iterator.value());
}
}
};
template<class Type>
void printMe(const Type& type )
{
Print<Type>::print("", type);
};
|
1,758,608 | 1,758,623 | Is there an Non-Short circuited logical "and" in C++? | tl;dr: Is there a non-short circuit logical AND in C++ (similar to &&)?
I've got 2 functions that I want to call, and use the return values to figure out the return value of a 3rd composite function. The issue is that I always want both functions to evaluate (as they output log information about the state of the system)
IE:
bool Func1(int x, int y){
if( x > y){
cout << "ERROR- X > Y" << endl;
}
}
bool Func2(int z, int q){
if( q * 3 < z){
cout << "ERROR- Q < Z/3" << endl;
}
}
bool Func3(int x, int y, int z, int q){
return ( Func1(x, y) && Func2(z, q) );
}
Of course, the conditionals aren't quite that simple in the functions, and yes, I realize that I could use temporary variables to store the returns of the two functions and then do the "short-circuit" logic on the temporary variables, but I was wondering if there was an "elegant" language solution to keep the one-line return in Func3 while still getting the logging messages from both functions.
Summary of responses:
The "bitwise" operators | and & can be used to get the effect, but only if the return type is bool. I found no mention of this in the ANSI C++ spec. From what I can tell, this works because the "bool" is converted to an int (true = 1, false = 0), and then the bitwise operator is used, then it is converted back to a bool.
The Operators "+" and "*" can also be used. This is not mentioned in the ANSI C++ Spec, but probably works because of the same reason as above. "+" give "or" because true is converted to 1, and then anything other than 0 is converted back to true. "*" works for "and" because 1 (true) * 0 (false) == 0(false) and 1(true) * 1(true) == 1(true)
Both of these seem to rely on implicit type conversion to integer and then back to bool. Both of these will likely mess up whomever tries to maintain the code.
Other responses boil down to "Just use temporaries" or "Implement your own" which was not the question. The goal was to see if there was already an operator implemented in the C++ standard to do it.
| The & operator performs logical "and" operation for bool operands and is not short circuited.
It's not a sequence point. You cannot rely on the order of evaluation of the operands. However, it's guaranteed that both operands are evaluated.
I do not recommend doing this. Using temporary variables is a better solution. Don't sacrifice readability for "clever code".
|
1,758,664 | 1,759,089 | java.util.concurrent vs. Boost Threads library | How do the Boost Thread libraries compare against the java.util.concurrent libraries?
Performance is critical and so I would prefer to stay with C++ (although Java is a lot faster these days). Given that I have to code in C++, what libraries exist to make threading easy and less error prone.
I have heard recently that as of JDK 1.5, the Java memory model was changed to fix some concurrency issues. How about C++? The last time I did multithreaded programming in C++ was 3-4 years ago when I used pthreads. Although, I don't wish to use that anymore for a large project. The only other alternative that I know of is Boost Threads. However, I am not sure if it is good. I've heard good things about java.util.concurrent, but nothing yet about Boost threads.
| Boost threads are a lot easier to use than pthreads, and, in my opinion, slightly easier to use than Java threads. When a boost thread object is instantiated, it launches a new thread. The user supplies a function or function object which will run in that new thread.
It's really as simple as:
boost::thread* thr = new boost::thread(MyFunc());
thr->join();
You can easily pass data to the thread by storing values inside the function object. And in the latest version of boost, you can pass a variable number of arguments to the thread constructor itself, which will then be passed to your function object's () operator.
You can also use RAII-style locks with boost::mutex for synchronization.
Note that C++0x will use the same syntax for std::thread.
|
1,758,946 | 1,759,112 | Setting static const char[] to a predefined static const char[] fails | Hey guys! When I try to do the following in a header file
static const char FOOT[] = "Foot";
static const char FEET[] = FOOT;
I get a compiler error of error: initializer fails to determine size of FEET. I was wondering what the cause of this is, and if there is a way to rectify it. Thanks!
| Even though why you get this error has been answered, there's more to the story. If you really need for FEET to be an array, then you can make it a reference instead of a pointer:
char const foot[] = "foot";
char const (&feet)[sizeof foot] = foot;
// reference to array (length 5) of constant char
// (read the declarations "from the inside-out")
char const* const smelly_feet = foot;
// constant pointer to const char
int main() {
cout << sizeof feet << ' ' << feet << '\n';
cout << sizeof smelly_feet << ' ' << smelly_feet << '\n';
cout << sizeof(void*) << " - compare to the above size\n";
return 0;
}
(More examples of the inside-out rule.)
Secondly, static at file and namespace scope means internal linkage; so when you use it in a header, you'll get duplicate objects in every TU using that header. There are cases when you want this, but I see no reason for it in your code, and it's a common error.
Regarding array size: The sizeof operator returns the memory-size of an object or instance of a type. For arrays this means the total memory-size of all of its items. Since C++ guarantees that sizeof(char) is 1, the memory-size of a char array is the same as its length. For other array types, you can divide by the memory-size of one item to get the length of an array:
void f() {
int array[5];
assert((sizeof array / sizeof *array) == 5);
}
And you can generalize it to a function template:
template<class T, int N>
int len(T (&)[N]) {
return N;
}
// use std::size_t instead of int if you prefer
This exists in boost as boost::size.
You may see code that uses sizeof array / sizeof *array, either through a macro or directly, either because it's old or doesn't want to complicate matters.
|
1,759,300 | 1,759,575 | When should I write the keyword 'inline' for a function/method? | When should I write the keyword inline for a function/method in C++?
After seeing some answers, some related questions:
When should I not write the keyword 'inline' for a function/method in C++?
When will the compiler not know when to make a function/method 'inline'?
Does it matter if an application is multithreaded when one writes 'inline' for a function/method?
| Oh man, one of my pet peeves.
inline is more like static or extern than a directive telling the compiler to inline your functions. extern, static, inline are linkage directives, used almost exclusively by the linker, not the compiler.
It is said that inline hints to the compiler that you think the function should be inlined. That may have been true in 1998, but a decade later the compiler needs no such hints. Not to mention humans are usually wrong when it comes to optimizing code, so most compilers flat out ignore the 'hint'.
static - the variable/function name cannot be used in other translation units. Linker needs to make sure it doesn't accidentally use a statically defined variable/function from another translation unit.
extern - use this variable/function name in this translation unit but don't complain if it isn't defined. The linker will sort it out and make sure all the code that tried to use some extern symbol has its address.
inline - this function will be defined in multiple translation units, don't worry about it. The linker needs to make sure all translation units use a single instance of the variable/function.
Note: Generally, declaring templates inline is pointless, as they have the linkage semantics of inline already. However, explicit specialization and instantiation of templates require inline to be used.
Specific answers to your questions:
When should I write the keyword 'inline' for a function/method in C++?
Only when you want the function to be defined in a header. More exactly only when the function's definition can show up in multiple translation units. It's a good idea to define small (as in one liner) functions in the header file as it gives the compiler more information to work with while optimizing your code. It also increases compilation time.
When should I not write the keyword 'inline' for a function/method in C++?
Don't add inline just because you think your code will run faster if the compiler inlines it.
When will the compiler not know when to make a function/method 'inline'?
Generally, the compiler will be able to do this better than you. However, the compiler doesn't have the option to inline code if it doesn't have the function definition. In maximally optimized code usually all private methods are inlined whether you ask for it or not.
As an aside to prevent inlining in GCC, use __attribute__(( noinline )), and in Visual Studio, use __declspec(noinline).
Does it matter if an application is multithreaded when one writes 'inline' for a function/method?
Multithreading doesn't affect inlining in any way.
|
1,759,312 | 1,759,390 | Single file compilation and execution in Visual C++ 2008? | I am doing a tutorial on C++ (learning it). The best way to learn is by example. I have little .cpp files with not much in them. I am using the best C++ IDE (Visual C++). Is there a way where I can have a project called "Tutorial Guide" and make my .cpp and .h files, BUT when I run them, it only runs the current file. I have heard that the debug runs ALL the files in the project and that would be a chaos in a tutorial type project. Please respond with Visual C++ answers only. No "make the .cpp and compile with Cygwin" or "use this ide instead". I would like to familiarize myself with the Visual C++ IDE.
| You cannot do it like you seem to want, a project implies a single output executable. What you can do is create an empty solution first then for each .cpp file you create a new project (right click the solution icon in the solution explorer and select new project).
You can then right click each project and select "Set as startup project" this will change which one runs when you hit debug.
|
1,759,397 | 1,759,463 | the quake 2 md2 file format (theory) | i am trying to load md2 files in opengl but i noticed that most example programs just use a
precompiled list of normals. something like this.....
//table of precalculated normals
{ -0.525731f, 0.000000f, 0.850651f },
{ -0.442863f, 0.238856f, 0.864188f },
{ -0.295242f, 0.000000f, 0.955423f },
{ -0.309017f, 0.500000f, 0.809017f },
...
...
Ok this may sound abit dumb, but i thought each model is made of different triangles, how then is it possible that you can use one set of precompiled normals to render all models?
It seems abit strange and any ideas will be appreciated.
| You could use a precompiled table of normals, and use a lookup table to select one that is 'good enough' for a particular case. Each triangle is on a distinct plane, and it's that plane that has a normal, not the triangle itself.
For instance, lets imagine we have a point. Expand that point into a sphere for the purposes of this discussion, makes it a little easier to grasp conceptually. If you draw a perfect circle around that sphere on the y axis, then rotate that circle in the x axis 1 degree each time, you'll end up with 360 circles. If you take a normal at 1 degree intervals along each of those circles, you'll end up with 360 ** 2 points. From there, your normal is the vector from the center of the sphere to that point on the sphere, and it is a normal for a plane constructed tangential to point on the sphere. What you end up with if you calculate these two for every point on that sphere is a precalculated table of normals, which will almost certainly be good enough for most situations. Now you just need to design a lookup scheme for that data (plane -> normal).
|
1,759,475 | 1,759,589 | gcov creates .gcov files in the current directory. Is there any way to change this? | I'm running gcov/gcc 4.1.2 on RHEL.
When I want to specify a directory for the gcov files. Any ideas on how to do this?
| Run gcov from the directory where you want its files to be created. You'll have to use the -o argument to tell it where to look for the .gcno/.gcda files. See gcov's docs for more info.
|
1,759,612 | 1,759,658 | How to set the culture info in unmanaged C++? | I got a program written in unmanaged C++, I need to get the cultural info from the system and set that info to the current execution thread in my c++ application.
Thanks.
| In unmanaged C++ on windows, what you need is the Locale. Culture is a term defined in .NET, as a replacement for that term.
There's a whole host of functions, but the one where you need to start is called SetThreadLocale.
SetThreadLocale Function (Windows) @ MSDN
Within the documentation at MSDN, it appears that there are quirks in Vista. You may wish to consult the following function as well.
SetThreadUILanguage Function (Windows) @ MSDN
The other functions of interest are available here.
National Language Support Functions (Windows) @ MSDN
Multilingual User Interface Functions (Windows) @ MSDN
edit:
If you are developing an application with really basic support, setlocale() may also be of interest.
setlocale (C/C++) @ MSDN
|
1,759,613 | 1,759,666 | What C++ idioms should C++ programmers use? | What C++ idioms should C++ programmers know?
By C++ idioms, I mean design patterns or way of doing certain things that are only applicable for C++ or more applicable for C++ than most other languages.
Why one should use the idioms, and what do the idioms accomplish?
| Here is one list. If I had to pick a couple I might go with the Curiously Recurring Template Pattern or Virtual Contstructors.
|
1,759,794 | 1,759,846 | How to print pthread_t | Searched, but don't come across a satisfying answer.
I know there's no a portable way to print a pthread_t.
How do you do it in your app?
Update:
Actually I don't need pthread_t, but some small numeric id, identifying in debug message different threads.
On my system (64 bit RHEL 5.3) it's defined as unsigned long int, so it's big number and just printing it eats a valuable place in debug line. How does gdb assign short tids?
| This will print out a hexadecimal representation of a pthread_t, no matter what that actually is:
void fprintPt(FILE *f, pthread_t pt) {
unsigned char *ptc = (unsigned char*)(void*)(&pt);
fprintf(f, "0x");
for (size_t i=0; i<sizeof(pt); i++) {
fprintf(f, "%02x", (unsigned)(ptc[i]));
}
}
To just print a small id for a each pthread_t something like this could be used (this time using iostreams):
void printPt(std::ostream &strm, pthread_t pt) {
static int nextindex = 0;
static std::map<pthread_t, int> ids;
if (ids.find(pt) == ids.end()) {
ids[pt] = nextindex++;
}
strm << ids[pt];
}
Depending on the platform and the actual representation of pthread_t it might here be necessary to define an operator< for pthread_t, because std::map needs an ordering on the elements:
bool operator<(const pthread_t &left, const pthread_t &right) {
...
}
|
1,759,991 | 1,760,043 | Regular expressions performance: Boost vs. Perl | I'm looking for a performance comparison between perl and boost regular expression.
I need to design a piece of code which relies very heavily on regular expressions, and can choose between:
running it through a boost regex
dispatching a perl interpreter and do the work in perl
I know perl is known for it's optimized string processing. However, I can't find a performance comparison to boost regex library.
Do you know of any such comparison?
Thanks
| The startup cost of running a Perl interpreter from within your application (via the system function I presume) will outweigh any benefits you gain over using Perl's regex engine. The exception would be if you have a VERY complicated regular expression that Perl's regex implementation happens to be optimised for but boost's regex engine isn't.
The real answer is that I do not know of any such comparison, but Perl's regular expression facilities are not necessarily the fastest. See here for some information about an algorithm that beats Perl's regular expression for some expressions.
EDIT: It is possible to overcome the startup cost of starting a full perl interpreter by linking to libperl or using libPCRE. And using boost will probably give you more flexibility and performance tuning options if you need them.
Final Note: There are no known direct comparisons between boost.regex and Perl's regex in terms of performance. The solution is to try both and see which is more performant for the OP's specific situation.
(Edit : There is now a good comparison between Boost and PCRE. See http://www.boost.org/doc/libs/1_41_0/libs/regex/doc/gcc-performance.html)
|
1,760,083 | 1,760,320 | How to resolve this Shift/Reduce conflict in YACC | I have a grammar like this:
"Match one or more rule1 where rule1 is one or more rule2, where rule2 is one or more rule3, etc. etc. each seperated by newlines". Look at the following example.
start: rule1_list
;
rule1_list: rule1
| rule1_list NEWLINE rule1
;
rule1: rule2
| rule2 NEWLINE rule3_list
;
rule2: TERMINAL2
;
rule3_list: rule3
| rule3_list NEWLINE rule3
;
rule3 : TERMINAL3
;
I get shift/reduce conflicts doing this, how can I change the grammar to stop? Essentially it needs to branch after a new line and look if the next thing is a TERMINAL2 or TERMINAL3.
| Ambiguous grammar, not LALR(1), unparsable by default yacc mode
To make a long story short, you can "fix" this with a %glr-parser declaration as follows:
%glr-parser
%%
start: rule1_list
. . .
. . .
To make a long story kind of medium-length...
Shift-reduce conflicts are normally not errors. The conflict is resolved by always doing the shift which is usually what you want. Most or all real-world grammars have shift-reduce conflicts. And if you wanted the reduction you can arrange for that with precedence declarations.
However, in a truely ambiguous grammar, doing the shift will send the parser down one of two paths, only one of which will ultimately find a string in the grammar. In this case the S/R conflict is a fatal error.
Analyzing the first one, when the parser sees the newline in the | rule2 NEWLINE rule3_list case, it can either shift to a new state where it will be expected a rule3_list, or it can reduce a rule1 using rule1: rule2. It will always look for a rule3_list due to the default choice of shift.
The second conflict occurs when it sees a newline in rule3_list: rule3_list . NEWLINE rule3. Now it can either shift and start looking for rule3 or reduce a rule1 using | rule2 NEWLINE rule3_list.
The result is that as written, and assuming '2' and '3' for the terminals, you can only parse a 2 line followed by 3 lines. If you fiddle with the precedence you can only parse '2' lines and never '3' lines.
Finally, I should add that going with a yacc-generated GLR parser is something of a kludge. I imagine it will work just fine but it's pure BFI, the parser splits, keeps two stacks, continues down both paths until one finds a string in the grammar. Sadly, the other fixes are kludges too: 1. reformulate the grammar as LALR(1), 2. add extra lookahead in the scanner and return a composite token, 3. Experiment with the rules for the grammar you have, perhaps yacc can handle a variation.
This is why I don't actually like yacc and prefer hand-written recursive descent or something more modern like PEG. (See Treetop.)
I tried something with (the preferred) left-recursive rules that simply ignored the newlines (which complicate your grammar, making whitespace tokens...) .. and this "works", although I'm not sure if it's what you want...
%%
start: stmtList
;
stmtList: /* nothing */
| stmtList '2' threeList;
;
threeList: /* nothing */
| threeList '3'
;
%%
int yylex() { int c; do { c = getchar (); } while (c == '\n'); return c; }
|
1,760,291 | 1,760,497 | Is compiler allowed to ignore inline in case of template specialization? | Lets say you have simple template function (not class member for the sake of simplicity) with type specific specialization in the same .h file...
template <class TYPE>
void some_function(TYPE& val)
{
// some generic implementation
}
template <>
inline void some_function<int>(int& val)
{
// some int specific implementation
}
Unless you explicitly direct you compiler to inline the specialization (inline keyword) you will get linking error if .h file is included more than once (at least I do in Visual C++ 2008).
We all know that inline is just a suggestion to the compiler, which it can ignore. In this particular case is compiler allowed to ignore this suggestion and let linker to fail?
| You are misunderstanding the meaning of the often-mentioned "ignore inline" possibility.
No compiler is ever allowed to ignore the inline specifier used in function declaration and the consequences this specifier has with respect to One Definition Rule (ODR).
When someone says that compiler are allowed to "ignore inline", it only means that compilers are not required to actually inline the calls to the function in question. To "ignore inline" means to generate an ordinary (non-inlined) function call to an inline function.
In any case, even if the compiler decided to always generate ordinary calls to an inline function (i.e. to always "ignore inline"), it is still required to treat the function as inline for the purposes of ODR. How the compiler is going to do it is the problem of the compiler. You are not supposed to worry about it.
In your original example you should not not get any linker errors.
|
1,760,365 | 1,760,403 | Possible to Use typeid to Determine Parent-Child Relationship | all the while, I am using dynamic_cast to determine Parent-Child relationship of an object.
#include <iostream>
class A {
public:
virtual ~A() {}
};
class B : public A {
};
class C : public A {
};
int main()
{
B b;
std::cout<< typeid(b).name()<< std::endl; // class B
A* a = dynamic_cast<A *>(&b);
if (a) {
std::cout<< "is child of A"<< std::endl; // printed
}
C* c = dynamic_cast<C *>(&b);
if (c) {
std::cout<< "is child of C"<< std::endl; // Not printed
}
getchar();
}
May I know is it possible that I can determine parent-child relationship, of an object, through typeid? For example, how I can know B is the child of A, by using typeid checking?
Thanks.
| I don't think you can do that in current C++ using the information in typeinfo only. I know of boost::is_base_of (Type Traits will be part of C++0x):
if ( boost::is_base_of<A, B>::value ) // true
{
std::cout << "A is a base of B";
}
|
1,760,455 | 1,876,991 | Convert latex to html in Java or C++? | There are many tools for converting latex into html. I'm looking for a Java or C++ program to do this. It will need to run on multiple operating systems. The solution will be used on academic papers, so it should ideally also be able to interpret things like bibtex.
I found htmltolatex which is a "Java program for converting HTML pages into LaTeX", but it doesn't seem to operate in the other direction.
Related questions:
what-is-the-best-way-to-embed-latex-in-a-webpage
how-best-to-write-documentation-ideally-in-latex-targeting-both-the-web-html
Update:
Just to clarify a little further: I want to distribute a package in another language that will accept any LaTeX document and produce HTML output (mostly of academic papers). I can't expect anything else to be installed (e.g. ghostscript, perl, latex2html, tth) on the machines already, and it needs to run cross platform. In other words, if I can find something that has compilable source code (or code in Java or C++) then I would rather go down that route so that the application is self contained. Alternatively, I will just use latex2html or tth and require the user to install those separately (although that's not ideal).
| Latex2html is the way to go. You say that you don't want any dependency, but any library you'll pick will be something you'll depend on. Latex2html:
works great,
it's part of TeX
it's relatively small that you can bundle the executable with your app
it's open source (GPL), so you might also try to link it within your program and not have an external dependency (you need to release with a GPL-compatible license, though)
support bibtex out of the box,
understand hyperlinks (if you convert from a postscript, you'll lose the hyperlinks)
I believe it compiles on all the major platforms (Linux, Windows, Mac) - but honestly I only have Linux so I can't say for sure.
|
1,760,594 | 1,760,604 | Abstract Base Class with Data Members | If I'm creating an abstract base class, and the classes derived from it are going to have some of the same data members, is it better practice to make those members private in the abstract base class and give protected access to them? Or to not bother and just put the data members in the derived classes. This is in C++.
| If the data belongs to the derived class, let the derived class do what it wants to contain that data.
By placing that data in the base class (not privately), you force every derived class to have it. The derived classes shouldn't be forced to do anything unless they need to fill out the data member, for example. The base class defines what derived classes must do, not how they should do it.
If you find there might be a common theme, you can make a derived class that has those members and implementations, which is then intended to be the base class for those that want to use it. For example:
struct car
{
virtual ~car(){}
virtual unsigned year(void) const = 0;
virtual const std::string make(void) const = 0;
}
// Dodge cars can feel free to derive from this instead, it's just a helper
struct dodge_car
{
virtual ~car(){}
virtual unsigned year(void) const = 0;
const std::string make(void) const
{
static const std::string result = "Dodge";
return result;
}
}
And so on. But you see, any derived classes still have the choice of implementing the entire car interface. This also improves code cleanliness. By keeping your interface a real interface, implementation details won't get in the way.
Any variables your base class uses should be private, because derived classes don't need to know how it works, in the same way users of your derived class don't need to know how the internals of the derived class work.
|
1,760,663 | 1,760,683 | What does this error message mean? | In C++, on this site: http://msdn.microsoft.com/en-au/visualc/bb985511.aspx
I downloaded the code sample and went to Debug and it came up with a messagebox with 2 textboxes in it and told me to specify the executable file to debug. So I did, and then I clicked browse, but there is NO executable because the stupid thing hasn't created one yet.
I'm using visual studio c++ 2008; what's up with that weird message?
| This message generally comes up when you try to debug into a system DLL or 3rd party code. Set a breakpoint with F9 and hit F5 and see if stop in your code in debug. Also make sure you are building the debug version.
happy coding.
|
1,760,726 | 1,763,484 | How can I compose output streams, so output goes multiple places at once? | I'd like to compose two (or more) streams into one. My goal is that any output directed to cout, cerr, and clog also be outputted into a file, along with the original stream. (For when things are logged to the console, for example. After closing, I'd like to still be able to go back and view the output.)
I was thinking of doing something like this:
class stream_compose : public streambuf, private boost::noncopyable
{
public:
// take two streams, save them in stream_holder,
// this set their buffers to `this`.
stream_compose;
// implement the streambuf interface, routing to both
// ...
private:
// saves the streambuf of an ios class,
// upon destruction restores it, provides
// accessor to saved stream
class stream_holder;
stream_holder mStreamA;
stream_holder mStreamB;
};
Which seems straight-forward enough. The call in main then would be something like:
// anything that goes to cout goes to both cout and the file
stream_compose coutToFile(std::cout, theFile);
// and so on
I also looked at boost::iostreams, but didn't see anything related.
Are there any other better/simpler ways to accomplish this?
| You mention having not found anything in Boost.IOStreams. Did you consider tee_device?
|
1,760,957 | 1,763,123 | Binary Search Tree C++ | Im a little confused. Im wondering if an array based Binary Search tree is implemented this way?
void BST::insert(item &items, const data & aData )
{//helper function.
Parent++;
data *new_data = new data(aData);
this->insert(*new_data);
}
// insert a new item into the BST
void BST::insert(const data &aData )
{
if ( items[Parent].empty )
{
items[Parent].theData = aData;
items[Parent].empty = false;
}
else if ( aData < items[Parent].theData )
{
if ( Parent >= maxSize ) this->reallocate();
this->insert(items[2*Parent+1], aData);
}
else
{
this->insert(items[2*Parent+2], aData);
}
}
// ctor where i make my intiailizations.
BST::BST(int capacity) : items(new item[capacity]),
Parent(0), leftChild(0), rightChild(0), maxSize(capacity)
{
}
| I'm not sure a binary tree based on an array is the best idea, as it:
prevents node-balancing (optimizing lookups for unbalanced trees)
wastes space - tons of it, especially if the tree is unbalanced.
Having said that, it is a valid approach, with a minor change:
Change
if ( Parent >= maxSize ) this->reallocate();
to
if ( 2*Parent >= maxSize ) this->reallocate();
|
1,761,047 | 1,761,083 | C++, Can't use an array or vectors, how do I use a pointer to get through this mess? | I need help with pointers and memory management.
I need to store different objects, all derived from the same base class, and have been using an array to do this but it is causing a segmentation fault when the array is populated with different objects.
My program works fine when the array is full of objects of the same derived type. When the array is populated with different objects it works as it is supposed to through the object stored at the first position but then when it switches to output the second object it gives me the segmentation fault. I know that this is a memory access issue but I am unclear how I'm supposed to manage a variable amount of objects dependent on user input.
thx,
nmr
| I won't post a complete solution because you have identified the question as homework, but I hope I can help you out with the problem a little bit:
Arrays are designed to hold many objects of the same size. The problem with storing different objects in the array (even if they are derived from the same base class) is that the objects are likely to have different sizes.
You're definitely on the right track by thinking about pointers.
edit (in response to comments):
You would be looking at something like this:
BaseClass * array[size];
array[0] = new DerivedClass(...);
array[1] = new OtherDerivedClass(...);
...
A pitfall of this approach would be that there is no built-in deletion of the objects in the array. You would have to loop through and call delete manually:
for (int index = 0; index < size; index++) { delete array[index]; }
|
1,761,125 | 1,769,619 | GCC memory leak detection equivalent to Microsoft crtdbg.h? | After many years of working on a general-purpose C++ library using the Microsoft MSVC compiler in Visual Studio, we are now porting it to Linux/Mac OS X (pray for us). I have become accustomed and quite fond of the simple memory leak detection mechanism in MSVC:
#ifdef DEBUG
#define _CRTDBG_MAP_ALLOC
#define NEW new( _NORMAL_BLOCK, __FILE__, __LINE__)
#include <stdlib.h>
#include <crtdbg.h>
#else
#define NEW new
#endif
Every memory allocation is done using this NEW macro. Whenever a process using our library terminates, any memory leaks (blocks that have not been de-allocated) are reported on the console along with the file and line # where the memory was originally allocated.
The part about this that I like is that I don't have to actively "run with performance tool" or otherwise indicate that I am looking for leaks. Leaks are reported to me in the regular course of development, every time a process terminates.
Now that we are moving to the GCC world, I find that the memory leak detection tools, many of which are quite sophisticated, require that I explicitly indicate that I'm in leak hunting mode. My IDE is Xcode and I've looked into some of the allocation/leak detection tools (like Instruments and MallocDebug) but I admit I haven't spent the time to get my head around them fully yet. I keep getting put off by the fact that I actually have to specify that I'm looking for a leak ahead of time, instead of being alerted to it automatically.
I am using Xcode 3.2 and I hear that there's now nifty integration with a static analysis tool, but again I haven't looked into this. I'm looking for some idea of what my options are. Is there a comparable mechanism built into GCC and/or Xcode? Is there a simple third-party library or tool that performs the very basic functionality that I know and love? Or should I suck it up and learn the new way of doing things?
| You should have a look at "Cross-Platform Memory Leak Detector", looks very similar to the crtdbg.h technique.
|
1,761,173 | 1,761,191 | send SIGINT to child process | I am trying to create a child process and then send SIGINT to the child without terminating the parent. I tried this:
pid=fork();
if (!pid)
{
setpgrp();
cout<<"waiting...\n";
while(1);
}
else
{
cout<<"parent";
wait(NULL);
}
but when I hit C-c both process were terminated
| You could try implementing a SIGINT signal handler which, if a child process is running, kills the child process (and if not, shuts down the application).
Alternatively, set the parent's SIGINT handler to SIG_IGN and the child's to SIG_DFL.
|
1,761,379 | 1,761,389 | Is Returning String Reference The Best Case In Below | Let say I am designing an interface, to return the name of the child class. Note that, for different instance of a child class, their name shall remain the same.
For speed and memory efficient, I would say 3rd method signature is probably the best (based on some comment from char* vs std::string in c++)
virtual const std::string& name2() const = 0;
I was wondering is there any better alternative?
#include <cstdio>
#include <string>
class baby_interface {
public:
virtual const char* name0() const = 0;
virtual std::string name1() const = 0;
virtual const std::string& name2() const = 0;
};
class baby : public baby_interface {
public:
virtual const char* name0() const
{
return "My Baby";
}
virtual std::string name1() const
{
return "My Baby";
}
virtual const std::string& name2() const
{
return std::string("My Baby");
}
};
int main()
{
baby b;
// Refer to same char array address.
printf("%x\n", b.name0());
printf("%x\n\n", b.name0());
// Refer to different char array address.
printf("%x\n", b.name1().c_str());
printf("%x\n\n", b.name1().c_str());
// Refer to same char array address.
printf("%x\n", b.name2().c_str());
printf("%x\n\n", b.name2().c_str());
getchar();
}
| It can be if you do it correctly. What you have now is undefined:
virtual const std::string& name2() const
{
return std::string("My Baby"); // constructs temporary string!
}
You're returning a reference to a temporary. For this to work, it must be an l-value. You could make it static:
virtual const std::string& name2() const
{
static const std::string result = "My Baby";
return result;
}
Or a member of the class, etc. Now it returns a usable variable.
I don't have much experience in what's common, but I'd guess number one is common if these interfaces are being used between modules. (i.e., the interface as allocated from a shared library/dll). This is because the implementation of strings is likely differ between compilers, and sometimes even different versions of the same compiler. If the program was made with one implementation, while the derived's was made in another, transferring between the two could fail.
By using a const char * (which is the same in all compilers), you avoid that. However, const char * can look unsightly to some.
The second options seems to be what I would use, because forcing derived classes to make a static/l-value variable might not be what you should do. The copy is likely to be very quick anyway.
|
1,761,626 | 1,761,646 | Weighted random numbers | I'm trying to implement a weighted random numbers. I'm currently just banging my head against the wall and cannot figure this out.
In my project (Hold'em hand-ranges, subjective all-in equity analysis), I'm using Boost's random -functions. So, let's say I want to pick a random number between 1 and 3 (so either 1, 2 or 3). Boost's mersenne twister generator works like a charm for this. However, I want the pick to be weighted for example like this:
1 (weight: 90)
2 (weight: 56)
3 (weight: 4)
Does Boost have some sort of functionality for this?
| There is a straightforward algorithm for picking an item at random, where items have individual weights:
1) calculate the sum of all the weights
2) pick a random number that is 0 or greater and is less than the sum of the weights
3) go through the items one at a time, subtracting their weight from your random number, until you get the item where the random number is less than that item's weight
Pseudo-code illustrating this:
int sum_of_weight = 0;
for(int i=0; i<num_choices; i++) {
sum_of_weight += choice_weight[i];
}
int rnd = random(sum_of_weight);
for(int i=0; i<num_choices; i++) {
if(rnd < choice_weight[i])
return i;
rnd -= choice_weight[i];
}
assert(!"should never get here");
This should be straightforward to adapt to your boost containers and such.
If your weights are rarely changed but you often pick one at random, and as long as your container is storing pointers to the objects or is more than a few dozen items long (basically, you have to profile to know if this helps or hinders), then there is an optimisation:
By storing the cumulative weight sum in each item you can use a binary search to pick the item corresponding to the pick weight.
If you do not know the number of items in the list, then there's a very neat algorithm called reservoir sampling that can be adapted to be weighted.
|
1,761,806 | 1,761,881 | What’s An Algorithm or code for the obtaining ordinal position of an element in a list sorted by value in c++ | This is similar to a recent question.
I will be maintaining sorted a list of values. I will be inserting items of arbitrary value into the list. Each time I insert a value, I would like to determine its ordinal position in the list (is it 1st, 2nd, 1000th). What is the most efficient data structure and algorithm for accomplishing this? There are obviously many algorithms which could allow you to do this but I don't see any way to easily do this using simple STL or QT template functionality. Ideally, I would like to know about existing open source C++ libraries or sample code that can do this.
I can imagine how to modify a B-tree or similar algorithm for this purpose but it seems like there should be an easier way.
Edit3:
Mike Seymour pretty well confirmed that, as I wrote in my original post, that there is indeed no way to accomplish this task using simple STL. So I'm looking for a good btree, balanced-tree or similar open source c++ template which can accomplish without modification or with the least modification possible - Pavel Shved showed this was possible but I'd prefer not to dive into implementing a balanced tree myself.
(the history should show my unsuccessful efforts to modify Mathieu's code to be O(log N) using make_heap)
Edit 4:
I still give credit to Pavel for pointing out that btree can give a solution to this, I have to mention that simplest way to achieve this kind of functionality without implementing a custom btree c++ template of your own is to use an in-memory database. This would give you log n and is fairly easy to implement.
| Binary tree is fine with this. Its modification is easy as well: just keep in each node the number of nodes in its subtree.
After you inserted a node, perform a search for it again by walking from root to that node. And recursively update the index:
if (traverse to left subtree)
index = index_on_previous_stage;
if (traverse to right subtree)
index = index_on_previous_stage + left_subtree_size + 1;
if (found)
return index + left_subtree_size;
This will take O(log N) time, just like inserting.
|
1,762,043 | 1,769,068 | C++ - string.compare issues when output to text file is different to console output? | I'm trying to find out if two strings I have are the same, for the purpose of unit testing. The first is a predefined string, hard-coded into the program. The second is a read in from a text file with an ifstream using std::getline(), and then taken as a substring. Both values are stored as C++ strings.
When I output both of the strings to the console using cout for testing, they both appear to be identical:
ThisIsATestStringOutputtedToAFile
ThisIsATestStringOutputtedToAFile
However, the string.compare returns stating they are not equal. When outputting to a text file, the two strings appear as follows:
ThisIsATestStringOutputtedToAFile
T^@h^@i^@s^@I^@s^@A^@T^@e^@s^@t^@S^@t^@r^@i^@n^@g^@O^@u^@t^@p^@u^@t^@
t^@e^@d^@T^@o^@A^@F^@i^@l^@e
I'm guessing this is some kind of encoding problem, and if I was in my native language (good old C#), I wouldn't have too many problems. As it is I'm with C/C++ and Vi, and frankly don't really know where to go from here! I've tried looking at maybe converting to/from ansi/unicode, and also removing the odd characters, but I'm not even sure if they really exist or not..
Thanks in advance for any suggestions.
EDIT
Apologies, this is my first time posting here. The code below is how I'm going through the process:
ifstream myInput;
ofstream myOutput;
myInput.open(fileLocation.c_str());
myOutput.open("test.txt");
TEST_ASSERT(myInput.is_open() == 1);
string compare1 = "ThisIsATestStringOutputtedToAFile";
string fileBuffer;
std::getline(myInput, fileBuffer);
string compare2 = fileBuffer.substr(400,100);
cout << compare1 + "\n";
cout << compare2 + "\n";
myOutput << compare1 + "\n";
myOutput << compare2 + "\n";
cin.get();
myInput.close();
myOutput.close();
TEST_ASSERT(compare1.compare(compare2) == 0);
| It turns out that the problem was that the file encoding of myInput was UTF-16, whereas the comparison string was UTF-8. The way to convert them with the OS limitations I had for this project (Linux, C/C++ code), was to use the iconv() functions. To keep the compatibility of the C++ strings I'd been using, I ended up saving the string to a new text file, then running iconv through the system() command.
system("iconv -f UTF-16 -t UTF-8 subStr.txt -o convertedSubStr.txt");
Reading the outputted string back in then gave me the string in the format I needed for the comparison to work properly.
NOTE
I'm aware that this is not the most efficient way to do this. I've I'd had the luxury of a Windows environment and the windows.h libraries, things would have been a lot easier. In this case though, the code was in some rarely used unit tests, and as such didn't need to be highly optimized, hence the creation, destruction and I/O operations of some text files wasn't an issue.
|
1,762,088 | 1,762,110 | Common reasons for bugs in release version not present in debug mode | What are the typical reasons for bugs and abnormal program behavior that manifest themselves only in release compilation mode but which do not occur when in debug mode?
| Many times, in debug mode in C++ all variables are null initialized, whereas the same does not happen in release mode unless explicitly stated.
Check for any debug macros and uninitialized variables
Does your program uses threading, then optimization can also cause some issues in release mode.
Also check for all exceptions, for example not directly related to release mode but sometime we just ignore some critical exceptions, like mem access violation in VC++, but the same can be a issue at least in other OS like Linux, Solaris. Ideally your program should not catch such critical exceptions like accessing a NULL pointer.
|
1,762,206 | 1,762,559 | Anchor buttons in a dialog when using SW_MAXIMIZE | This should be a simple one:
I have a CDialog with 2 buttons.
The dialog is always opened in full screen (No title bar \ Status, etc...) using m_pMainWnd->ShowWindow(SW_MAXIMIZE);
I want my buttons to snap to the edge of the screen.
There are no resizing or anything.
| You know the width of the dialog (GetClientRect). You know the width of the buttons.
Assuming you are snapping to the right edge ...
Inside your CDialog::OnSize:
// Grab the CDialog's rect.
CRect winRect;
GetClientRect( &winRect );
// Grab the button's rect.
CRect buttonRect;
button.GetClientRect( &buttonRect );
// Now we need to set the top, left of the button to the right edge - the button width.
// The y position will remain the same.
button.SetWindowPos( NULL, winRect.right - buttonRect.Width(), buttonRect.top, 0, 0, SWP_NOZORDER | SWP_NOMOVE );
|
1,762,363 | 1,762,440 | Line segment in a triangle | How can we check if a line segment falls partially or fully inside a triangle?
Cheers.
| Get the function for the line from the end points of the line segment. Check where this line crosses any of the sides of the triangle.
If any part of the line segment is inside the triangle, the line will either pass in through one side and out through another, or it will pass exactly along one side of the triangle and pass through two of it's corners.
If the line passes through the triangle, you compare the points where the line crosses the triangle sides (or corners) with the end points of the segment, to see if the segment is part of the line that crosses the triangle.
|
1,762,386 | 1,762,431 | Is this proper use of dynamic_cast? | I have three classes: Generic, CFG, and Evaluator.
Here's Generic:
class Generic: public virtual Evaluator, public CFG, public LCDInterface {
Here's CFG:
class CFG : public virtual Evaluator {
And Evaluator subclasses nothing.
I'm providing a DLL named PluginLCD, and it has a method called Connect:
void PluginLCD::Connect(Evaluator *visitor) {
visitor_ = dynamic_cast<Generic *>(visitor);
if(!visitor_)
return;
type_ = visitor_->GetType();
}
Here's how I'm compiling the DLL through scons:
env.SharedLibrary(['PluginLCD.cpp', 'Evaluator.cpp', 'Generic.cpp', 'CFG.cpp'])
Now, there are two scenarios in my code. One is in class LCDControl, which subclasses CFG. The other scenario is above where Generic subclasses Evaluator and CFG. Evaluator has a method called LoadPlugins, which does what its name suggests, passing this through to the DLL via method Connect. Well, in the first scenario the cast to Generic * in Connect should return NULL. However, in the second scenario, as far as I know, a valid pointer should be returned. It doesn't seem to be happening this way. Am I wrong about this?
| dynamic_cast is known to break across module boundaries with many compilers (including MSVC and gcc). I don't know exactly why that is, but googling for it yields many hits. I'd recommend trying to get rid of the dynamic_cast in the first place instead of trying to find out why it returns null in your second scenario.
|
1,762,390 | 1,762,515 | How to explain C++ templates to junior developers? | One could break the question into two: how to read and to write templated code.
It is very easy to say, "it you want an array of doubles, write std::vector<double>", but it won't teach them how the templates work.
| I'd probably try to demonstrate the power of templates, by demonstrating the annoyance of not using them.
A good demonstration would be to write something simple like a stack of doubles (hand-written, not STL), with methods push, pop, and foldTopTwo, which pops off and adds together the top two values in the stack, and pushes the new value back on.
Then tell them to do the same for ints (or whatever, just some different numeric type).
Then show them how, by writing this stack as a template, you can significantly reduce the number of lines of code, and all of that horrible duplication.
|
1,762,535 | 1,762,587 | terminate called after throwing an instance of 'Poco::SystemException' | Sometimes (about 1 out of 100 runs), my program terminates with this message:
terminate called after throwing an instance of 'Poco::SystemException'
what(): System exception
my code is not the one catching the exception (all my catches are more verbose), and I am not sure where it's caught.
it's very likely that the exception does contain a useful message, but it's not returned through the what() method but by the displayText() method.
The string "terminate called after throwing an instance of" has ~600k in Google, so it's probably printed by code inserted by the compiler or by some common library (pthread?).
I only seen this error message when the program ran on Linux (never on Windows).
anyone knows in what code this uncaught exception is caught?
|
anyone knows in what code this uncaught exception is caught?
An uncaught exception is—by definition—not caught anywhere.
If an exception cannot be handled, the C++ exception mechanism will call std::terminate() (see include header <exception>), which will call a customizable termination handler. On your platform, the standard termination handler prints the output of std::exception::what() (which Poco's exceptions inherit from). Unfortunately, the way Poco's exceptions are designed, this will not contain any useful information.
There are multiple ways an exception cannot be handled:
No suitable catch() handler is found and the unwinding mechanism exits main(). You can try wrapping your main() code in try...catch to print the exception's displayText().
A function exits with an exception that does not match its exception specification (... functionname(...) throw(...)). This will call std::unexpected() which in turn will call std::terminate() (by default).
An exception is thrown from within a destructor that is called during the unwinding process of another exception. Never throw exceptions in destructors!
An exception is thrown while trying to create the original exception object. Never throw exceptions in custom exception classes!
When using Poco threads and a thread is terminated by an unhandled exception, Poco will invoke its internal ErrorHandler and the program will not exit, so I doubt that this is a threading issue.
|
1,762,666 | 1,762,741 | pass a string from managed C# to managed C++ | what is the preferred method to pass a string between C++ and C#?
i have a c++ class where one of the functions takes a char const * const as parameter.
how would i call this function in C#? just using a c#-string doesnt seem to work as the function in C# requires a sbyte*
C++ class:
public ref class MyClass
{
public:
void Sample(char const * const Name);
}
Error 2 Argument '1': cannot convert from 'string' to 'sbyte*'
thanks!
| If you are using managed C++, you can use System.String class
|
1,762,933 | 1,762,972 | Loop through MFC Child Dialogs, MDIFrames etc | Is there a way to loop through all MFC Child Dialogs, MDI frames and etc? And is there a way to find out which dialog or window I am looping through?
| You could use EnumChildWindows to iterate through child windows of certain window.
|
1,762,941 | 1,763,028 | c++ Mysql C API Connection Question | I'm building an application which uses Mysql, I was wondering what would be the best way to manage the connection to the actual Mysql server?
I'm still in the design phase, but currently I have it Connecting (or aborting if error) before every query and disconnecting after which is just for testing as right now I'm only running 1 query to see if the code I've setup so far works.
My App might be performing a few queries every 5/10/20/30 minutes depending on settings and doesn't really need to do anything with SQL until that time.
So I'm wondering if its more beneficial to use a continuous connection that exists for the lifetime of the application (if possible) or to simply connect to sql before I intend to use it, do what the app needs to do then disconnect?
| Connecting once and performing many queries will naturally be more efficient.
However, if performance isn't a major concern for your project, maybe aiming for simplicity in your code might be a better option (especially if you are the only connection to the database).
If you want to get clever, then maybe connect as and when you need to, then keep the connection alive until you stop making queries. Eg, drop the connection if there have been no queries for 30 seconds or something like that.
|
1,763,082 | 1,763,171 | Recovering from stack overflow on Mac OS X | I am implementing a cross platform scripting language for our product. There is a requirement to detect and properly handle stack overflow condition in language VM. Before you jump in and say make sure there is no stack overflow in the first place, re-read my first sentence - this is a scripting language and end users may write incorrect programs in this language, which may overflow the stack via for example endless recursion.
Now I know how to detect and recover from stack overflow in Windows (see http://support.microsoft.com/kb/315937). However I am unable to find any solution for Mac OS X.
The VM is implemented in C++: MSVC++ on Windows, GCC on Mac OS X.
Ideally the mechanism must be based on UNIX capabilities since we also plan to port to Linux.
Thanks.
| OCaml has the same constraints as you ("scripting" language where the programmer may cause a stack overflow). Its native compiler uses the system stack for function calls -- as you do -- and it handles stack overflows (materializing them as exceptions).
If you do not receive a more explicit answer, I suggest you look at how it's done in the OCaml sources.
~/ppc $ cat >> t.ml
let rec f x = (f x) + (f x) ;;
f 0 ;;
~/ppc $ ocamlopt t.ml
~/ppc $ ./a.out
Fatal error: exception Stack_overflow
The above is on Mac OS X Leopard. Search for #ifdef HAS_STACK_OVERFLOW_DETECTION in the source files.
|
1,763,135 | 1,763,295 | C# DllImport MFC Extension DLL & Name Mangling | I have a MFC extension DLL which I want to use in a C# application. The functions I'm exposing are C functions, i.e. I'm exporting them like this
extern "C"
{
__declspec(dllexport) bool Initialize();
}
The functions internally uses MFC classes, so what do I have to do to use the DLL in C# using P/Invoke.
Secondly, I want to use function overloading, but as far as I know C doesn't supports function overloading and if I export C++ functions they will be mangled. So what can I do remedy this problem? Can we import C++ mangled functions using DllImport.
| Having this declaration in the header:
__declspec(dllexport) int fnunmanaged(void);
__declspec(dllexport) int fnunmanaged(int);
You could use dumpbin.exe to get the exact name of the function:
dumpbin.exe /exports unmanaged.dll
Microsoft (R) COFF/PE Dumper Version 9.00.30729.01
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file unmanaged.dll
File Type: DLL
Section contains the following exports for unmanaged.dll
00000000 characteristics
4B0546C3 time date stamp Thu Nov 19 14:23:15 2009
0.00 version
1 ordinal base
2 number of functions
2 number of names
ordinal hint RVA name
1 0 0001106E ?fnunmanaged@@YAHH@Z = @ILT+105(?fnunmanaged@@YAHH@Z)
2 1 00011159 ?fnunmanaged@@YAHXZ = @ILT+340(?fnunmanaged@@YAHXZ)
Summary
1000 .data
1000 .idata
2000 .rdata
1000 .reloc
1000 .rsrc
4000 .text
10000 .textbss
And use this name when declaring the function:
[DllImport(@"D:\work\unmanaged.dll",
EntryPoint = "?fnunmanaged@@YAHH@Z",
ExactSpelling = true)]
static extern int fnunmanaged();
[DllImport(@"D:\work\unmanaged.dll",
EntryPoint = "?fnunmanaged@@YAHXZ",
ExactSpelling = true)]
static extern int fnunmanaged(int a);
Another alternative is to use a module definition file:
LIBRARY "unmanaged"
EXPORTS
fn1=?fnunmanaged@@YAHH@Z
fn2=?fnunmanaged@@YAHXZ
In this case you no longer need to use __declspec(dllexport) and your header file might look like this:
int fnunmanaged(void);
int fnunmanaged(int);
And finally import them:
[DllImport(@"D:\work\unmanaged.dll")]
static extern int fn1();
[DllImport(@"D:\work\unmanaged.dll")]
static extern int fn2(int a);
|
1,763,166 | 1,763,315 | How to efficiently generate random subsets of rows from a matrix | I have a large matrix M implemented as vector<vector<double> with m rows, i.e. the matrix is a vector of m vectors of n column elements.
I have to create two subsets of the rows of this matrix, i.e. A holds k rows, and B the other m-k rows. The rows must be selected at random.
I do not want to use any libraries other than STL, so no boost either.
Two approaches that I considered are:
generate a std::random_shuffle of row indices, copy the rows indicated by the first k indices to A and the rows indicated by the other m-k to B
do a std::random_shuffle of M. copy k rows to A, and m-k rows to B
Are there other options, and how do the two options above compare in terms of memory consumption and processing time?
Thanks!
| If you don't need B to be in random order, then random_shuffle does more work than you need.
If by "STL" you mean SGI's STL, then use random_sample.
If by "STL" you mean the C++ standard libraries, then you don't have random_sample. You might want to copy the implementation, except stop after the first n steps. This will reduce the time.
Note that these both modify a sequence in place. Depending where you actually want A and B to end up, and who owns the original, this might mean that you end up doing 2 copies of each row - once to get it into a mutable container for the shuffle, then again to get it into its final destination. This is more memory and processing time than is required. To fix this you could maybe swap rows out of the temporary container, and into A and B. Or copy the algorithm, but adapt it to:
Make a list of the indexes of the first vector
Partially shuffle the list of indexes
Copy the rows corresponding to the first n indexes to A, and the rest to B.
I'm not certain this is faster or uses less memory, but I suspect so.
The standard for random_shuffle says that it performs "swaps". I hope that means it's efficient for vectors, but you might want to check that it is actually using an optimised swap, not doing any copying. I think it should mean that, especially since the natural implementation is as Fisher-Yates, but I'm not sure whether the language in the standard should be taken to guarantee it. If it is copying, then your second approach is going to be very slow. If it's using swap then they're roughly comparable. swap on a vector is going to be slightly slower than swap on an index, but there's not a whole lot in it. Swapping either a vector or an index is very quick compared with copying a row, and there are M of each operation, so I doubt it will make a huge difference to total run time.
[Edit: Alex Martelli was complaining recently about misuse of the term "STL" to mean the C++ standard libraries. In this case it does make a difference :-)]
|
1,763,322 | 1,764,960 | Is there any way that Enter/LeaveCriticalSection could leave a handle behind | I have the following code in my program:
EnterCriticalSection(&critsec[x]);
// stuff
LeaveCriticalSection(&critsec[x]);
It works fine 99.999% of the time but occasionally a handle seems to get left behind. Now I have done the obvious things like make sure that x did not change value between the enter and make sure that there isn't any "return" or "break" inside "// stuff" but I was wondering if there could be something else that would cause an enter/leave pair to leave a handle behind. Perhaps running out of memory or overflowing some counter in the OS or whatever.
EDIT: I am new to C++, the program has only recently been converted from C. It has no exceptions anywhere in the entire program.
| If you don't explicitly delete the critical section and if there was ever contention on the critical section, you will leak a handle. Some implementations of critical sections on Windows allocate a semaphore when two or more threads overlap in their attempts to enter a single critical section.
It's not a leak. Or rather, it isn't a leak if the number of "leaked" handles is less than or equal to the number of global critical sections you are using.
|
1,763,368 | 1,763,424 | Is it possible to debug core dumps when using Java JNI? | My application is mostly Java but, for certain calculations, uses a C++ library. Our environment is Java 1.6 running on RedHat 3 (soon to be RedHat 5).
My problem is that the C++ library is not thread-safe. To work around this, we run multiple, single-threaded "worker" processes and give them work to do from a central Work Manager, also written in C++. Our Java application calls the C++ Work Manager via a third-party product.
For various reasons, we want to re-write the C++ Work Manager and workers. I'm in favour of writing them all in Java, using JNI in each worker to call the C++ library.
The main problem is what happens if the C++ library core dumps. Unfortunately, this is quite common, and we need to be able to see which line in our C++ library caused the problem, e.g. by examining a backtrace in something like GDB.
My colleagues believe that it will be impossible to analyse the core dumps, because tools like GDB don't understand core files produced by Java.
I hope that they're wrong, but I need to be sure before pushing my ideas further.
What is the best way to analyse a core dump produced from Java/JNI?
| Yes, there is. Everytime JVM crashes because of a SIGSEGV in the JNI part, you'll get a file with core dump in $JAVA_HOME/bin directory. It usually name hs_err_PID.log.
You can get more info here, and here. Here is a somewhat related stackoverflow question.
|
1,763,739 | 1,763,874 | Problem retuning a vector from a c++ dll to another c++ exe | I have a function foo() in dll A.dll, whose definition is as follows
vector<CustomObject> foo()
{
vector<CustomObject> customObjectCollection;
//code which populates customObjectCollection goes here
return customObjectCollection;
}
I am referring this method vector foo() of dll A from exe B
When i make a call to the function foo from B, I get an unhandled exception which says
"unhandled exception at
0x10487b3f(msvcp90d.dll) in B.exe"
0xC0000005: Access violation while
writing to the location 0xfdfdfdfd".
Note:type CustomObject does not implement copy constructor
When i tried to debug by attaching B.exe to A.dll, I found that inside method vector foo(), the vector gets populated without any problem but when the control returns to B.exe the valves in vector doesnot get copied !!!
Also, if method foo returns vector by reference , exception doesnot occur and B.exe receives an empty vetor.
what is the issue ?? Is it happening as I have not implemented copy constructor for CustomObject.
Any help is greatly appreciated
(Apologies for not articulating the question properly)
Thanks
jeel
| This is a classic symptom of mismatched runtime libraries. You have to make sure that both the EXE and the DLL are linked to the dynamic C++ library (DLL version).
If one (or both) are linked with the static C++ runtime (LIB version), you'll get memory violations since there will be two instances of the runtime library with different address spaces.
|
1,764,079 | 1,764,086 | Why do you prefer char* instead of string, in C++? | I'm a C programmer trying to write c++ code. I heard string in C++ was better than char* in terms of security, performance, etc, however sometimes it seems that char* is a better choice. Someone suggested that programmers should not use char* in C++ because we could do all things that char* could do with string, and it's more secure and faster.
Did you ever used char* in C++? What are the specific conditions?
| It's safer to use std::string because you don't need to worry about allocating / deallocating memory for the string. The C++ std::string class is likely to use a char* array internally. However, the class will manage the allocation, reallocation, and deallocation of the internal array for you. This removes all the usual risks that come with using raw pointers, such as memory leaks, buffer overflows, etc.
Additionally, it's also incredibly convenient. You can copy strings, append to a string, etc., without having to manually provide buffer space or use functions like strcpy/strcat. With std::string it's as simple as using the = or + operators.
Basically, it's:
std::string s1 = "Hello ";
std::string s2 = s1 + "World";
versus...
const char* s1 = "Hello";
char s2[1024]; // How much should I really even allocate here?
strcpy(s2, s1);
strcat(s2, " World ");
Edit:
In response to your edit regarding the use of char* in C++: Many C++ programmers will claim you should never use char* unless you're working with some API/legacy function that requires it, in which case you can use the std::string::c_str() function to convert an std::string to const char*.
However, I would say there are some legitimate uses of C-arrays in C++. For example, if performance is absolutely critical, a small C-array on the stack may be a better solution than std::string. You may also be writing a program where you need absolute control over memory allocation/deallocation, in which case you would use char*. Also, as was pointed out in the comments section, std::string isn't guaranteed to provide you with a contiguous, writable buffer *, so you can't directly write from a file into an std::string if you need your program to be completely portable. However, in the event you need to do this, std::vector would still probably be preferable to using a raw C-array.
* Although in C++11 this has changed so that std::string does provide you with a contiguous buffer
|
1,764,082 | 1,764,754 | boost filtering_istream gzip_decompressor uncompressed file size | I am using the boost filtering stream object to read gzipped files. Works great!
I would like to display a progress bar for the amount of the file that has been processed. I need find the input uncompressed file size. Does the gzip decompressor have access to the original file size from the gzipped file? I couldn't find it on the boost gzip_decompressor reference page. Really the progress dialog is the goal, is there another way to figure out position in the compressed file?
// gets compressed file size, need uncompressed size
boost::uintmax_t fs = boost::filesystem::file_size (
boost::filesystem::path (fname)
);
std::ifstream file (fname, std::ios_base::in | std::ios_base::binary);
boost::iostreams::filtering_istream in;
in.push (boost::iostreams::gzip_decompressor());
in.push (file);
std::string line;
size_t bytes_read = 0;
while (in)
{
std::getline (in, line);
bytes_read += line.size ();
// progress dlg with bytes_read / uncompressed size
}
| The information you are after is definitely there (uncompressed data size is recorded into the last 4 bytes of a gzip file, (see GZIP spec) but taking a look at the headers for the boost library (seen here) it is not exposed anywhere. The only place it seems to be even looked at is when doing checks to make sure there was no corruption in read_footer.
You could read the value yourself directly out of the file (just assemble the last 4 bytes into an int, being mindful of their ordering (see GZIP spec again)), or use a different library to do the unzipping.
|
1,764,179 | 1,764,237 | Passing around base class pointers | Scenario: I have the following defined classes.
class Baseclass { };
class DerivedTypeA : public Baseclass { };
class DerivedTypeB : public Baseclass { };
// ... and so on ...
class Container
{
list<Baseclass*> stuff;
list<DerivedTypeA*> specific_stuff;
// ... initializing constructors and so on ...
public:
void add(Baseclass * b)
{
stuff.add(b);
}
void add(DerivedTypeA * a)
{
stuff.add(a);
specific_stuff.add(a);
}
};
class ContainerOperator
{
Container c;
// ... initializing constructors and so on ...
public:
void operateOnStuff(Baseclass * b)
{
// This will always use "void add(Baseclass * b)" no matter what object b really is.
c.add(b);
}
};
// ...
containerOperator.operateOnStuff(new DerivedTypeA());
So, what I want to do is to handle a certain derived class in some special way in Container.
Problem: void add(DerivedTypeA * a) is never called. I'm obviously doing something wrong. What is the correct way of doing what I am trying to achieve here?
| Overload resolution in C++ happens at compile-time, not run-time. The "usual" way to solve problems like this is to use Visitor pattern.
You can reduce the amount of boilerplate copy-paste by implementing Visitor with CRTP.
If you use CRTP for Base::accept, you don't need to define it any more in derived classes.
Here is a similar program to yours, but a little simpler:
#include <iostream>
class Base; class Derived;
struct Operation {
void add(Base *b) {
std::cout << "Base\n";
}
void add(Derived *b) {
std::cout << "Derived\n";
}
void visit(Base *b); // need to define this after Base class
};
struct Base {
virtual ~Base() {}
virtual void accept(Operation &o)
{
o.add(this);
}
};
void Operation::visit(Base *b) {
b->accept(*this);
}
struct Derived : public Base {
void accept(Operation &o)
{
o.add(this);
}
};
int main() {
Operation o;
Base b;
Derived d;
Base *ptrb = &b;
Base *ptrd = &d;
o.add(ptrb); // These two print "Base"
o.add(ptrd);
o.visit(ptrb); // "Base"
o.visit(ptrd); // "Derived"
}
|
1,764,239 | 1,764,270 | Class composed of other, larger, classes problem | Imagine you have a class with dozens of private member variables. Each member variable has a public getter and a setter function:
class Foo
{
public:
int GetA() const { return m_a; }
:
int GetZ() const { return m_z; }
void SetA(int val) { m_a = val; }
:
void SetZ(int val) { m_z = val; }
private:
int m_a;
:
int m_z
};
Now we have a second class, which is composed of Foo (amongst other things):
class Bar
{
private:
// some instances of other classes of about the same complexity as Foo
Foo m_foo;
};
So Bar is essentially a class which binds together instances of other classes in a single entity.
Functions which are passed an instance of Bar will want to access m_foo so that they can call its getter and setter functions. Mindful of Scott Meyers advice in Effective C++ (3rd edition - item #28), I'm reluctant to add something which return a 'handle' to m_foo, e.g.
Foo& GetFoo() const { return m_foo; } // dubious const, I know
Do I have any other options though other than replicating every single getter and setter in Bar?
I'm working with some legacy code which is lazy enough to make 'm_foo' public! But this goes against some other of Scott's advice (item #22 in this case - "declare data members private").
Any way out of this bind?
| You should make the data member public.
It already is conceptually public, anyway, if you give Bar getters and setters like you describe. This applies similarly to any getter/setter pair where the getter returns a reference. (Except you can include pre/post hooks, but that's a separate issue than encapsulation.)
|
1,764,624 | 1,764,760 | C++ singleton design: using inheritance to call only some implemented methods | I have a singleton that is the main engine container for my game.
I have several abstract classes that make the developer implement the different calls to what that specific object needs.
What I want to do is to make my singleton call those methods upon each given object, but avoiding unecessary calls.
Example so you can understand better:
Imagine one object that requires both Render() and Update() methods.
class IRender() : public IBase
{
virtual bool Render() = 0;
};
class IUpdate() : public IBase
{
virtual bool Update( long time_delta ) = 0;
};
class Sprite : public IRender, public IUpdate
{
bool Render(){ render stuff; }
bool Update( long time_delta(){ update stuff; }
};
Now I want to add that Sprite object to my singleton engine but I want the engine to call each loop to ONLY whatever that object inherited (there are other things beside Render and Update, like checking for input, etc):
_engine::getInstance()->Add( _sprite );
Thing is, for this to work I have to inherit all the interfaces from a base interface so I can call Add() with whatever objects were created, so the Add() method receives a base interface object.
Now the problem here is the base interface has to at least abstract all the methods that can be inherited like Render(), Update(), CheckInput(), Etc() and each loop my singleton has to call all the possibilities for every object, even if CheckInput() is empty for the sprite class.
Like so in my singleton:
bool loop(){
for every object saved in my container:
CheckInput(); Update(); Render(); etc(); }
Is my design wrong? Is there a way I can avoid this?
I hope you understand what I mean, my engine is in a pretty advanced state and I'm trying to avoid rewriting it all.
Thanks in advance.
| If you don't need to call the chain CheckInput(), Update(), .... on each object before moving on to the next one, make a call to to the object, and make the object register which actions it supports on the singleton.
class Singleton {
void Add(Base& object) {
object.register(this);
}
void registerForInput(IInput& object) {
addToInputList(object);
}
}
class Some : public Base, public IInput {
void register(Singleton *target) {
target->registerForInput(*this);
}
}
However if you need to call all of them on one object before moving to the next make a method on the object which performs all the calls it supports.
class Singleton {
void loop() {
for all objects:
object.performActions();
}
}
class Some : public Base {
void performActions() {
checkForInput();
render();
}
}
|
1,764,665 | 1,764,714 | .Net performance on Virtual Machines | We need to develop an application which is going to be installed on Virtual Machine running Windows.
We all know the performance of the .Net is about the same as the native C/C++ code. Is it also true for Virtual Machines?
| .net apps running on a VM compared to non .net apps running on the same VM will perform equivalently to comparing .net and non .net apps running on a real machine.
What I'm trying to say is that .net apps are no more or less disadvantages than native apps by running them on a VM. If you have 2 apps (one .net and one native), and they perform equally on a real PC, then will perform the same as each other on a VM.
Performance of the VM however will heavily depend on the resources you make available to it. If you give your VM plenty of ram, and don't run anything else on the host OS, you'll find VM performance to be very good. (Particularly if you are using one of the direct-on-the-metal VMs like vmware esx). If however you are running 6 VMs sharing the same host, and/or running lots of apps on the host, don't expect each VM to perform as if it was a native machine.
|
1,764,680 | 1,764,766 | Can I extract C++ template arguments out of a template class? | Basically, given a template class like this:
template< class Value > class Holder { };
I would like to be able to discover the type Value for a given Holder class. I thought that I would be able to make a simple metafunction that takes a template template argument, like this:
template< template< class Value > class Holder > class GetValue
{
typedef Value Value;
};
And then extract out the Value type like this:
GetValue< Holder< int > >::Value value;
But instead I just get an error message pointing to the metafunction declaration:
error: ‘Value’ does not name a type
Is there any way to accomplish this kind of thing? Thanks.
[EDIT] I also get the error messages:
error: type/value mismatch at argument 1 in template parameter list for ‘template<template<class Value> class Holder> class GetValue’
error: expected a class template, got ‘Holder<int>’
Which leads me to conclude that Phil Nash is right, you can't pass a class as a template template argument.
| Why don't you simply change your holder class to
template< class Value > class Holder {
typedef Value value_type;
value_type m_val; // member variable
};
In any method that consumes an object of type Holder< T > you can access the contained type like that:
template< class THolder >
void SomeMethod( THolder const& holder ) {
typename THolder::value_type v = holder.m_val;
}
This approach follows the pattern all STL classes use, e.g., std::vector< int >::value_type is int.
I think you're trying to do partial template specialization:
template<class T>
class GetValue {
};
template<class Value>
class GetValue< Holder<Value> > {
public:
typedef Value value_type;
};
In your code, you could then do the following:
template<class THolder>
void SomeMethod( THolder const& h ) {
typename GetValue< THolder >::value_type v = h.m_v;
}
In general, I'd prefer the first solution though.
|
1,764,831 | 1,764,851 | C++ Object without new | this is a really simple question but I havn't done c++ properly for years and so I'm a little baffled by this. Also, it's not the easiest thing (for me at least) to look up on the internet, not for trying.
Why doesn't this use the new keyword and how does it work?
Basically, what's going on here?
CPlayer newPlayer = CPlayer(position, attacker);
| This expression:
CPlayer(position, attacker)
creates a temporary object of type CPlayer using the above constructor, then:
CPlayer newPlayer =...;
The mentioned temporary object gets copied using the copy constructor to newPlayer. A better way is to write the following to avoid temporaries:
CPlayer newPlayer(position, attacker);
|
1,764,920 | 1,764,976 | std::ostream not formatting const char* correctly the first time it's used | I've been writing a custom std::streambuf as part of a logging system. However, I'm having problems with the first piece of output from a stream not being formatted correctly.
Here's a reduced test-case that doesn't use any custom streambuf or ostream classes:
#include <iostream>
int main()
{
std::streambuf *coutbuf = std::cout.rdbuf();
std::ostream(coutbuf) << "test" << ": writing to cout using a separate ostream." << std::endl;
return 0;
}
Compiling this using g++:
$ g++ --version
g++ (Ubuntu 4.4.1-4ubuntu8) 4.4.1
$ g++ -o fail reduced-case.cpp
$ ./fail
0x400c80: writing to cout using a separate ostream.
Note that the first string literal ("test") is being formatted as a generic pointer (the address of the string is output in hex), while the second string literal is formatted correctly.
The only thing I can think of is that it's invalid to directly use a newly constructed std::ostream like that (ie, without putting it into a variable). If this is the case, I'd very much like to know what exactly makes it invalid (I assume it's nothing to do with iostreams specifically, but rather order-of-evaluation or interactions with constructors or something). If that's not the problem, then what is?
| The problem is that you must not write to a temporary stream object. This:
std::ostream(coutbuf) << "blah";
doesn't work as expected, since the left-hand argument for operator<<() is an rvalue. However, all the operators overloaded as a free function take a non-const reference to a stream as their left-hand argument:
std::ostream& operator<<(std::ostream&, ...);
Since rvalues do not bind to non-const references, they cannot be called.
I suspect that your std lib implementation implements << for const char* as a free function and has thus to fall back to some << that's a member of std::ostream. It seems in your implementation that's the one outputting any pointer as a void*.
Bottom line: Don't attempt to write to temporary stream objects.
|
1,764,980 | 1,765,125 | 'Safe' DLL Injection | Not a terribly good question, sorry.
I have a program that needs to be alerted when a file is opened from explorer (i.e. ShellExecute(A/W) is called).
Unfortunately, Microsoft removed the COM interface (IShellExecuteHook) that allows you to hook these events in Vista and up, supposedly because older code could cause a crash due to changes. There was a work-around to re-enable this feature, but it no longer works.
I've done some research and it looks like the only way to catch calls to ShellExecute is to re-route the call to shell32.dll. At the moment, I'm looking at injecting my own DLL into the explorer process, then copying the IAT entry for ShellExecute to some address allocation in my DLL, and finally modifying the IAT entry for ShellExecute to point to my function, which will notify the program that a file was opened and jump to the original ShellExecute function, whose address we stored earlier.
My biggest concern here is antiviruses. Will they care that I'm injecting into explorer? Will they care that I'm modifying the IAT?
Another concern is whether this is safe; is it possible (or rather likely) for explorer's security priveleges to not allow injection via CreateRemoteThread? If so, is there a better way to do this injection?
Is there a better way to do this in general?
EDIT: For anyone who comes across this in the future, explorer.exe has no IAT for shell32.dll; it has a header, but the thunk is full of junk values, so there's no way (as far as I can tell) to retrieve the entry for any imported functions.
Looks like code tunneling is the only way to hook this.
| Most good antivirus heuristics should pick up on import table patching as being a red flag for a trojan.
The online documentation for madcodehook has some extended articles on various code injection techniques, their benefits/drawbacks, and the API provides some options for specifying "safe" hooking:
http://www.madshi.net/madCodeHookDescription.htm
|
1,765,014 | 1,765,088 | Convert string from __DATE__ into a time_t | I'm trying to convert the string produced from the __DATE__ macro into a time_t. I don't need a full-blown date/time parser, something that only handles the format of the __DATE__ macro would be great.
A preprocessor method would be nifty, but a function would work just as well. If it's relevant, I'm using MSVC.
| Edit: the corrected function should look something like this:
time_t cvt_TIME(char const *time) {
char s_month[5];
int month, day, year;
struct tm t = {0};
static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
sscanf(time, "%s %d %d", s_month, &day, &year);
month = (strstr(month_names, s_month)-month_names)/3;
t.tm_mon = month;
t.tm_mday = day;
t.tm_year = year - 1900;
t.tm_isdst = -1;
return mktime(&t);
}
|
1,765,119 | 1,765,200 | What Is a Good Introduction and Tutorial on Internationalization and Localization? | My company uses an internally developed package to support internationalization/localization. However, it was developed some twenty years ago, and the libraries are restricted to one product line. I'm interested in where the state of the art stands. Is Unicode the base character set for all international efforts today? Do people still use gettext() and family? If using C++, should I be concentrating on the locale support in that language?
I've looked at the Wikipedia entry on Internationalization and Localization, which includes links to other sites and related topics. But there's a lot out there, and what I'd like is a source, especially a book, which serves as a good introduction to the topic on Linux/Unix in the current software scene. If the implementation uses C++, that's fine.
For example, years and years ago I read a book called Understanding Japanese Information Processing, by Ken Lunde, and much later, his revised book, CJKV Information Processing. Both were interesting, but of course focussed on Asian languages. Is there a book on the current art that is (spoken/written) language agnostic?
| This article seems quite interesting and provides you with some interesting bibliography in the end.
Also, you may want to take a look at the ICU Project's website.
|
1,765,122 | 1,765,187 | Equality Test for Derived Classes in C++ |
Possible Duplicate:
What’s the right way to overload operator== for a class hierarchy?
In C++, how can derived classes override the base class equality test in a meaningful way?
For example, say I have a base class A. Classes B and C derive from A. Now given two pointers to two A objects, can I test if they are equal (including any subclass data)?
class A {
public: int data;
};
class B : public A {
public: float more_data; bool something_else;
};
class C : public A {
public: double more_data;
};
A* one = new B;
A* two = new B;
A* three = new C;
//How can I test if one, two, or three are equal
//including any derived class data?
Is there a clean way of doing it? What's my best bet?
Thanks!
| I remember reading a succinct description of the public-non-virtual/non-public-virtual idiom and its advantages, but not where. This wikibook has an okay description.
Here is how you apply it to op==:
struct A {
virtual ~A() {}
int a;
friend
bool operator==(A const& lhs, A const& rhs) {
return lhs.equal_to(rhs);
}
// http://en.wikipedia.org/wiki/Barton-Nackman_trick
// used in a simplified form here
protected:
virtual bool equal_to(A const& other) const {
return a == other.a;
}
};
struct B : A {
int b;
protected:
virtual bool equal_to(A const& other) const {
if (B const* p = dynamic_cast<B const*>(&other)) {
return A::equal_to(other) && b == p->b;
}
else {
return false;
}
}
};
struct C : A {
int c;
protected:
virtual bool equal_to(A const& other) const {
if (C const* p = dynamic_cast<C const*>(&other)) {
return A::equal_to(other) && c == p->c;
}
else {
return false;
}
}
};
|
1,765,301 | 1,766,035 | fcntl() for thread or process synchronization? | Is it possible to use fcntl() system call on a file to achieve thread/process synchronization (instead of semaphoress)?
| Yes. Unix fcntl locks (and filesystem resources in general) are system-wide, so any two threads of execution (be they separate processes or not) can use them. Whether that's a good idea or not is context-dependent.
|
1,765,310 | 1,765,604 | What are the limitations of C++ running on the iPhone? | I like C++ a lot and to be honest the Objective-C "super set" of C is more of a "super fail". Can an iPhone application be written in pure C++? Are there parts of the API that are unavailable from C++?
| You can't code purely in C++. For one, the UIApplicationDelegate class every application needs to inherit is Objective-C.
However, nothing is stopping you from coding everything that isn't framework related in Objective-C++. You'll still need to use the Objective-C calls for UIKit and other frameworks, but all of your application logic can be in C++.
From the Objective-C++ section of the Objective-C programming guide, these are the main limitations:
Objective-C++ does not add C++
features to Objective-C classes, nor
does it add Objective-C features to
C++ classes. For example, you cannot
use Objective-C syntax to call a C++
object, you cannot add constructors or
destructors to an Objective-C object,
and you cannot use the keywords this
and self interchangeably. The class
hierarchies are separate; a C++ class
cannot inherit from an Objective-C
class, and an Objective-C class cannot
inherit from a C++ class. In addition,
multi-language exception handling is
not supported. That is, an exception
thrown in Objective-C code cannot be
caught in C++ code and, conversely, an
exception thrown in C++ code cannot be
caught in Objective-C code. For more
information on exceptions in
Objective-C, see “Exception Handling.”
|
1,765,431 | 1,765,489 | C++ Comparing Member Function Pointers | In C++, is it possible to define a sort order for pointers to member functions? It seems that the operator< is undefined. Also, it's illegal to cast to void*.
class A
{
public:
void Test1(){}
void Test2(){}
};
int main()
{
void (A::* const one)() = &A::Test1;
void (A::* const two)() = &A::Test2;
bool equal = one == two; //Equality works fine.
bool less = one < two; //Less than doesn't.
return 0;
}
Thanks!
| Function pointers are not relationally comparable in C++. Equality comparisons are supported, except for situations when at least one of the pointers actually points to a virtual member function (in which case the result is unspecified).
Of course, you can always introduce an ordering by implementing a comparison predicate and comparing the pointers explicitly (won't look too elegant though, since you can only use equality comparisons). Other possible solutions would cross into the territory of the various implementation-specific "hacks".
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.