question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,549,235 | 2,549,346 | Qt Stylesheets with derived classes | Can I use Qt stylesheets with a derived widget? I'd like to be able to define some custom properties on the widget (like various colors) and be able to define their value in a stylesheet.
Is this possible?
| Sure, just declare your properties with Q_PROPERTY.
class MyClass : public QObject
{
Q_OBJECT
Q_PROPERTY( int fun READ getFun WRITE setFun )
public:
MyClass( QObject * parent=0, const char * name=0 );
~MyClass();
void setFun( int x );
int getFun() const;
};
|
2,549,600 | 2,549,653 | C++ Memory Allocation & Linked List Implementation | I'm writing software to simulate the "first-fit" memory allocation schema.
Basically, I allocate a large X megabyte chunk of memory and subdivide it into blocks when chunks are requested according to the schema.
I'm using a linked list called "node" as a header for each block of memory (so that we can find the next block without tediously looping through every address value.
head_ptr = (char*) malloc(total_size + sizeof(node));
if(head_ptr == NULL) return -1; // Malloc Error .. :-(
node* head_node = new node; // Build block header
head_node->next = NULL;
head_node->previous = NULL;
// Header points to next block (which doesn't exist yet)
memset(head_ptr,head_node, sizeof(node));
`
But this last line returns:
error: invalid conversion from 'node*' to 'int'
I understand why this is invalid.. but how can I place my node into the pointer location of my newly allocated memory?
| memset(void* memory, int value, size_t size)
So, it's not to copy the head_node into head_ptr (you are thinking of memcpy),
it's for initializing memory (clearing to 0, marking as freed, etc...).
In this case, you could simply cast the head_ptr to a node*:
node* head_node = (node*)head_ptr;
And now you don't have to delete head_node, or copy the values to head_ptr at all.
|
2,549,618 | 2,550,069 | Is there any g++ option to dump class layout and vtables? | I want to see how g++ lays out memory for classes and virtual tables.
Is there a way to dump this information, using g++'s options?
| g++ -fdump-class-hierarchy -c source_file.cpp
|
2,549,722 | 2,549,734 | Boost C++ Singleton error LNK2001: unresolved external symbol "private: static long Nsp::HL::flag" (?flag@HL@Nsp@@0JA) | I try to create a multi-threaded singleton pattern class.
Header:
class HL{
public:
static HL* getInstance();
.........
private:
static HL* instance;
static boost::once_flag flag;
HL();
static void initOnce();
}
CPP:
HL* HL::instance = NULL;
HL* HL::getInstance(){
if(instance == NULL){
boost::call_once(flag, initOnce);
}
return instance;
}
void HL::initOnce(){
instance = new HL();
}
I get this error:
error LNK2001: unresolved external symbol "private: static long Nsp::HL::flag" (?flag@HL@Nsp@@0JA)
What's wrong?
| You need to define the static member variable in the cpp file:
boost::once_flag Nsp::HL::flag;
You can initialize it if you need to (I've not used boost::once_flag, and can't tell you whether or how it needs to be initialized):
boost::once_flag Nsp::HL::flag = {whatever goes here};
|
2,549,727 | 2,549,751 | C++ instantiating a class within a method, then altering member variables from a different method? | Say I have a method, and within that method it instantiates a Person class:
void methodA()
{
Person personObject;
}
How would I access that object's methods from within another method? I.e. something like:
void methodB()
{
personObject.someMethod();
}
I realise it's a painfully nooby question :P
| Pass a reference to the other function.
void methodB(Person &personObject)
{
personObject.someMethod();
}
void methodA()
{
Person personObject;
methodB(personObject);
}
|
2,549,743 | 3,087,308 | how to get AutoIncrement value after JetUpdate() in Extensible Storage Engine (JetBlue) | after calling JetSetColumns() and then JetUpdate() how do I retrieve the values for any freshly assigned autoincrement values?
| when you call JetUpdate() the third arg is a 'bookmark'. Once JetUpdate() completes you can seek to the bookmark using
JetGotoBookmark() - http://msdn.microsoft.com/en-us/library/ms683554(EXCHG.10).aspx
|
2,549,801 | 2,549,936 | How do interpreters functions written in the class C++ in the main | I'm working on a project about Data structures.
In the first , I wrote everything in main but it sounds like C . But as I learned, I tried to thinkk OOP and do as little as possible in my main() methods.
I've implemented some opertation in my class like add,delet,find.it's too easy to implement its .
class ARB
{
private:
struct BT
{
int data;
BT *l;
BT *r;
};
struct BT *p;
public
ARB();
~ARB();
void del(int n);
void add(int n);
};
void ARB::del(int num)
{
//The code ,don't care about it
};
main()
{
//
BTR T;
T.add(3);
T.add(5);
};
But I arrived to the big program
How can I define a methode which have to use a binary tree and to get a stack
STACK ARB::MyFunct(BT* p)
{
// The code don't care about it
}
How can I apply it in the main programme
main()
{
//
BT T;
T.add(3);
T.add(5);
STACK S;
BT* p
S=T.MyFunct(p); // error C2664 cannot convert parametre 1
};
**mention :I implement STACK class
| There's a few issues here. For one thing, add() is a member function of ARB, not BT. And, BT is a private subclass of ARB, so it can't be accessed from main(). p is a private member of ARB (as it should be), but it should really be a direct variable, not a pointer, so it will be automatically created and destroyed with ARB. As is, p is never initialized and there's no way to do so from outside ARB.
I'm guessing here that ARB uses its internal BT p for internal storage, so the implementations of add() and del() both operate on p, and that MyFunct() is supposed to take that BT and generate a stack from it. If so, MyFunct() should take no parameters and simply reference p directly.
So main() would look something like:
ARB arb;
arb.add(3)
arb.add(5)
STACK s = arb.myFunct(); // which should maybe be makeStack() or such
This is all assuming I've correctly deduced your intentions here.
|
2,549,856 | 2,549,876 | c++ global operator not playing well with template class | ok, i found some similar posts on stackoverflow, but I couldn't find any that pertained to my exact situation and I was confused with some of the answers given. Ok, so here is my problem:
I have a template matrix class as follows:
template <typename T, size_t ROWS, size_t COLS>
class Matrix
{
public:
template<typename, size_t, size_t>
friend class Matrix;
Matrix( T init = T() )
: _matrix(ROWS, vector<T>(COLS, init))
{
/*for( int i = 0; i < ROWS; i++ )
{
_matrix[i] = new vector<T>( COLS, init );
}*/
}
Matrix<T, ROWS, COLS> & operator+=( const T & value )
{
for( vector<T>::size_type i = 0; i < this->_matrix.size(); i++ )
{
for( vector<T>::size_type j = 0; j < this->_matrix[i].size(); j++ )
{
this->_matrix[i][j] += value;
}
}
return *this;
}
private:
vector< vector<T> > _matrix;
};
and I have the following global function template:
template<typename T, size_t ROWS, size_t COLS>
Matrix<T, ROWS, COLS> operator+( const Matrix<T, ROWS, COLS> & lhs,
const Matrix<T, ROWS, COLS> & rhs )
{
Matrix<T, ROWS, COLS> returnValue = lhs;
return returnValue += lhs;
}
To me, this seems to be right. However, when I try to compile the code, I get the following error (thrown from the operator+ function):
binary '+=' : no operator found which takes a right-hand operand of type 'const matrix::Matrix<T,ROWS,COLS>' (or there is no acceptable conversion)
I can't figure out what to make of this. Any help if greatly appreciated!
| Your operator+= here:
Matrix<T, ROWS, COLS> & operator+=( const T & value )
Defines a method of adding a T (a scalar) to a Matrix<T, ROWS, COLS>.
This statement:
return returnValue += lhs;
Attempts to add a Matrix<T, ROWS, COLS> (a matrix, the type of lhs) to a Matrix<T, ROWS, COLS>.
So the compiler is completely correct in saying that you have not defined that operation. You have an operator+= that adds a scalar to a matrix, but not an operator+= that adds a matrix to a matrix.
|
2,549,957 | 2,549,991 | comparing two end() iterators | list<int> foo;
list<int> foo2;
list<int>::iterator foo_end = foo.end();
list<int>::iterator foo2_end = foo2.end();
for (list<int>::iterator it = foo.begin(); it != foo2_end; ++foo) <- notice != comparison here
{
...
it this allowed? will it work correctly.
I am inclined to think that this is implementation dependent, anyone knows if standard says anything about this?
| There was a defect reported about this (LWG defect 446). The defect report asked whether it is valid to compare iterators that refer to elements of different containers.
Notes in the defect report explain that it was certainly the intention that doing so is undefined, but it is not explicitly stated that it is undefined.
The proposed resolution was to add the following to the standard, explicitly stating that it is undefined:
The result of directly or indirectly evaluating any comparison function or the binary - operator with two iterator values as arguments that were obtained from two different ranges r1 and r2 (including their past-the-end values) which are not subranges of one common range is undefined, unless explicitly described otherwise.
Edit: That language is not included in the C++0x FCD. This issue was in fact resolved by changes in N3066; specifically the following addition (§24.2.5/2):
The domain of == for forward iterators is that of iterators over the same underlying sequence.
|
2,550,051 | 2,569,064 | How to acquire still webcam image | I need some help deciding what to use to acquire an image from a webcam. I want to acquire a single image. I know you can typically acquire a still image at a higher resolution than a single video frame.
Currently, I am using MATLAB's image acquisition toolbox.. which apparently only supports obtaining frames in video mode(so lower resolution). Which other libraries do you recommend? Has anyone else encountered this problem?
| Are you referring to the fact that the largest resolution reported by the Image Acquisition Toolbox is (for example) 1024x768 but the webcam claims that it can acquire 6 megapixel still images? If so, every webcam that I have ever seen has a note in very small print somewhere that explains that the higher resolution is achieved via software interpolation.
You can just acquire the image in the largest format supported by the toolbox and then use IMRESIZE to scale the image to whatever resolution that you want.
|
2,550,085 | 2,550,141 | Where is pure virtual function located in C++? | Which virtual table will be pure virtual function located? In the base class or derived class?
For example, what does the virtual table look like in each class?
class Base {
virtual void f() =0;
virtual void g();
}
class Derived: public Base{
virtual void f();
virtual void g();
}
| g++ -fdump-class-hierarchy layout.cpp produces a file layout.cpp.class. The content of layout.cpp.class will show the following:
Vtable for Base
Base::_ZTV4Base: 4u entries
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI4Base)
16 __cxa_pure_virtual
24 Base::g
Class Base
size=8 align=8
base size=8 base align=8
Base (0x7ff893479af0) 0 nearly-empty
vptr=((& Base::_ZTV4Base) + 16u)
Vtable for Derived
Derived::_ZTV7Derived: 4u entries
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI7Derived)
16 Derived::f
24 Derived::g
Class Derived
size=8 align=8
base size=8 base align=8
Derived (0x7ff893479d90) 0 nearly-empty
vptr=((& Derived::_ZTV7Derived) + 16u)
Base (0x7ff893479e00) 0 nearly-empty
primary-for Derived (0x7ff893479d90)
Removing the 'pureness' of f changes the fifth line to:
16 Base::f
|
2,550,229 | 2,567,805 | How to keep only duplicates efficiently? | Given an STL vector, output only the duplicates in sorted order, e.g.,
INPUT : { 4, 4, 1, 2, 3, 2, 3 }
OUTPUT: { 2, 3, 4 }
The algorithm is trivial, but the goal is to make it as efficient as std::unique(). My naive implementation modifies the container in-place:
My naive implementation:
void not_unique(vector<int>* pv)
{
if (!pv)
return;
// Sort (in-place) so we can find duplicates in linear time
sort(pv->begin(), pv->end());
vector<int>::iterator it_start = pv->begin();
while (it_start != pv->end())
{
size_t nKeep = 0;
// Find the next different element
vector<int>::iterator it_stop = it_start + 1;
while (it_stop != pv->end() && *it_start == *it_stop)
{
nKeep = 1; // This gets set redundantly
++it_stop;
}
// If the element is a duplicate, keep only the first one (nKeep=1).
// Otherwise, the element is not duplicated so erase it (nKeep=0).
it_start = pv->erase(it_start + nKeep, it_stop);
}
}
If you can make this more efficient, elegant, or general, please let me know. For example, a custom sorting algorithm, or copy elements in the 2nd loop to eliminate the erase() call.
| Shorter and more STL-ish than previous entries. Assumes sorted input.
#include <algorithm>
#include <functional>
template< class I, class P >
I remove_unique( I first, I last, P pred = P() ) {
I dest = first;
while (
( first = std::adjacent_find( first, last, pred ) )
!= last ) {
* dest = * first;
++ first;
++ dest;
if ( ( first = std::adjacent_find( first, last, std::not2( pred ) ) )
== last ) break;
++ first;
}
return dest;
}
template< class I >
I remove_unique( I first, I last ) {
return remove_unique( first, last,
std::equal_to< typename std::iterator_traits<I>::value_type >() );
}
|
2,550,281 | 2,550,430 | Floating point vs integer calculations on modern hardware | I am doing some performance critical work in C++, and we are currently using integer calculations for problems that are inherently floating point because "its faster". This causes a whole lot of annoying problems and adds a lot of annoying code.
Now, I remember reading about how floating point calculations were so slow approximately circa the 386 days, where I believe (IIRC) that there was an optional co-proccessor. But surely nowadays with exponentially more complex and powerful CPUs it makes no difference in "speed" if doing floating point or integer calculation? Especially since the actual calculation time is tiny compared to something like causing a pipeline stall or fetching something from main memory?
I know the correct answer is to benchmark on the target hardware, what would be a good way to test this? I wrote two tiny C++ programs and compared their run time with "time" on Linux, but the actual run time is too variable (doesn't help I am running on a virtual server). Short of spending my entire day running hundreds of benchmarks, making graphs etc. is there something I can do to get a reasonable test of the relative speed? Any ideas or thoughts? Am I completely wrong?
The programs I used as follows, they are not identical by any means:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <time.h>
int main( int argc, char** argv )
{
int accum = 0;
srand( time( NULL ) );
for( unsigned int i = 0; i < 100000000; ++i )
{
accum += rand( ) % 365;
}
std::cout << accum << std::endl;
return 0;
}
Program 2:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <time.h>
int main( int argc, char** argv )
{
float accum = 0;
srand( time( NULL ) );
for( unsigned int i = 0; i < 100000000; ++i )
{
accum += (float)( rand( ) % 365 );
}
std::cout << accum << std::endl;
return 0;
}
Thanks in advance!
Edit: The platform I care about is regular x86 or x86-64 running on desktop Linux and Windows machines.
Edit 2(pasted from a comment below): We have an extensive code base currently. Really I have come up against the generalization that we "must not use float since integer calculation is faster" - and I am looking for a way (if this is even true) to disprove this generalized assumption. I realize that it would be impossible to predict the exact outcome for us short of doing all the work and profiling it afterwards.
Anyway, thanks for all your excellent answers and help. Feel free to add anything else :).
| Alas, I can only give you an "it depends" answer...
From my experience, there are many, many variables to performance...especially between integer & floating point math. It varies strongly from processor to processor (even within the same family such as x86) because different processors have different "pipeline" lengths. Also, some operations are generally very simple (such as addition) and have an accelerated route through the processor, and others (such as division) take much, much longer.
The other big variable is where the data reside. If you only have a few values to add, then all of the data can reside in cache, where they can be quickly sent to the CPU. A very, very slow floating point operation that already has the data in cache will be many times faster than an integer operation where an integer needs to be copied from system memory.
I assume that you are asking this question because you are working on a performance critical application. If you are developing for the x86 architecture, and you need extra performance, you might want to look into using the SSE extensions. This can greatly speed up single-precision floating point arithmetic, as the same operation can be performed on multiple data at once, plus there is a separate* bank of registers for the SSE operations. (I noticed in your second example you used "float" instead of "double", making me think you are using single-precision math).
*Note: Using the old MMX instructions would actually slow down programs, because those old instructions actually used the same registers as the FPU does, making it impossible to use both the FPU and MMX at the same time.
|
2,550,377 | 2,550,405 | When pass-by-pointer is preferred to pass-by-reference in C++? | I can imagine one case, in which the input parameter could be NULL so that pass-by-pointer is preferred but not pass-by-reference?
Can anybody add more cases?
| Some like pass-by-pointer better in cases where the object being passed is actually going to be modified. They use pass-by-const-reference when the object is being passed by reference in order to avoid a copy of the object, but will not be changed in the function.
In illustration, take the following functions:
int foo(int x);
int foo1(int &x);
int foo2(int *x);
Now in the code, I do the following:
int testInt = 0;
foo(testInt); // can't modify testInt
foo1(testInt); // can modify testInt
foo2(&testInt); // can modify testInt
In calling foo vs foo1, it's not apparent from the callers perspective (or a programmer reading the code) that the function can modify testInt without having to look at the signature of the function. Looking at foo2, a reader can easily see that the function may in fact modify the value of testInt because the function is receiving the address of the parameter. Note that this doesn't guarantee the object is actually modified, but that's where being consistent in the use of references vs. pointers helps. In general, if you want to follow this guideline consistently you should always pass const references when you want to avoid copies, and pass by pointer when you want to be able to modify the object.
|
2,550,628 | 2,654,178 | How to use external makefile in Eclipse | I have a source code of an OpenSource project which I get from SVN. I was able to run autogen --> configure --> and make successfully (through the terminal). But I want to build the same project with Eclipse, and I can't port manually those source files to eclipse though. So, How can I set Eclipse to use external make files ? can anyone please help me ? Thanks.
| Ok, I got it, It was straightforward. Just go to project properties --> C/C++ Build --> Make file generation --> and untick "Generate Make files automatically". In additionally you may have to set the Build location also.
|
2,550,730 | 2,550,742 | i want to know VC++ 6.0 uses .Net frame work or not? | i am doubtful about it that vc++6.0 is .Net framework independent or depends on it help required?
| VC++ 6.0 does not depend on .NET. It shipped as part of the last set of Microsoft development tools before the debut of .NET. You can rest assured, though, that even versions of VC++ since then don't bring in .NET by default--they only use .NET if you compile with managed extensions turned on.
|
2,550,748 | 2,551,438 | How to capture full screen in c using visual studio | Is it possible to capture full screen in visual studio (VC++), so that user don't have to press ATL+Enter. Kindly guide me how I can make it possible.
| If you need to enter fullscreen mode in OpenGL per default, check out NeHe Productions, for instance his second lesson
If you download his example at the bottom of the screen and check out the:
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
.. you will see how it can be made in OpenGL
|
2,550,822 | 2,550,873 | "call" instruction that seemingly jumps into itself | I have some C++ code
#include <cstdio>
#include <boost/bind.hpp>
#include <boost/function.hpp>
class A {
public:
void do_it() { std::printf("aaa"); }
};
void
call_it(const boost::function<void()> &f)
{
f();
}
void
func()
{
A *a = new A;
call_it(boost::bind(&A::do_it, a));
}
which gcc 4 compiles into the following assembly (from objdump):
00000030 <func()>:
30: 55 push %ebp
31: 89 e5 mov %esp,%ebp
33: 56 push %esi
34: 31 f6 xor %esi,%esi
36: 53 push %ebx
37: bb 00 00 00 00 mov $0x0,%ebx
3c: 83 ec 40 sub $0x40,%esp
3f: c7 04 24 01 00 00 00 movl $0x1,(%esp)
46: e8 fc ff ff ff call 47 <func()+0x17>
4b: 8d 55 ec lea 0xffffffec(%ebp),%edx
4e: 89 14 24 mov %edx,(%esp)
51: 89 5c 24 04 mov %ebx,0x4(%esp)
55: 89 74 24 08 mov %esi,0x8(%esp)
59: 89 44 24 0c mov %eax,0xc(%esp)
; the rest of the function is omitted
I can't understand the operand of call instruction here, why does it call into itself, but with one byte off?
| The call is probably to an external function, and the address you see (FFFFFFFC) is just a placeholder for the real address, which the linker and/or loader will take care of later.
|
2,551,491 | 2,551,516 | function pointer error | Can anybody help me with this simple code??
#include <iostream>
using namespace std;
void testFunction(){
cout<<"This is the test function 0"<<endl;
}
void testFunction1(){
cout<<"This is the test function 1"<<endl;
}
void testFunction2(){
cout<<"This is the test function 2"<<endl;
}
void (*fp[])()={testFunction,testFunction1,testFunction2};
int main(){
//fp=testFunction;
(*fp[testFunction1])();
//cout<<"Addrees of the function pointer is:"<<*fp;
}
I am getting the following error:
error: invalid types `void (*[3])()[void ()()]' for array subscript|
| You're trying to use a function pointer as an array index. That won't fly, array indices must be integer.
To call through a function pointer, just call:
(*fp[1])();
or the (even shorter!)
fp[1]();
will work.
|
2,551,539 | 2,552,312 | Generate accessors in Visual C++ 2008 | I'm trying to generate the accessors and mutators for my variables automatically, but just can't find a way. I tried the right-click/refactor... solution, but the refactor item doesn't appear.
I'm not in the mood right now to learn how to write a macro to do this, and I don't have the money to buy a commercial solution (internship student).
Any help is welcome, I don't feel like writing all my get/set by hand.
note : it's C++ so the {get;set} syntax doesn't work (or does it ?).
edit : it's not about "generate a read/write accessor for all variables". I want to be able to generate a bunch of Get accessor without having to write the prototype and declaration for each of them.
| No, C++ doesn't have syntax for accessors. C++ programmers frown on features that are not well supported by the language. Nor does if have many Resharper style tools. If you don't like to type then C++ is not a language you should consider.
Keep Neil happy and avoid the "bad design" put-down by omitting the "get" prefix. Like size(), not getSize().
MSVC supports declaring properties with the __declspec(property) declarator. It is however very non-standard. And takes a lot of typing, you still need to write the accessor functions.
|
2,551,634 | 3,516,270 | Visual studio macro - getting started | copy a definition from .cpp to .h | Is it possible to do a macro that copies a definition of a function to a declaration(, and maybe also the opposite)? For instance
Foo::Foo(int aParameter, int bParameter){
//
}
int Foo::someMethod(char aCharacter) const {
return 0;
}
From the .cpp file would be:
class Foo {
Foo(int aParameter, int bParameter);
int someMethod(char aCharacter) const;
};
In the .cpp file.
Also:
If there are anyone with knowledge of good tutorials or documentation that aims at Visual Studio .Net (and maybe also covers the above problem) I would probably accept that as an answer as well
| So, I found the Automation and Extensibility for Visual Studio, which covers the stuff I am trying to do, with a little help from the object browser and record macro function.
I guess I should be able to solve it from here.
|
2,551,657 | 2,552,540 | C++: how can I test if a number is power of ten? | I want to test if a number double x is an integer power of 10. I could perhaps use cmath's log10 and then test if x == (int) x?
edit: Actually, my solution does not work because doubles can be very big, much bigger than int, and also very small, like fractions.
| A lookup table will be by far the fastest and most precise way to do this; only about 600 powers of 10 are representable as doubles. You can use a hash table, or if the table is ordered from smallest to largest, you can rapidly search it with binary chop.
This has the advantage that you will get a "hit" if and only if your number is exactly the closest possible IEEE double to some power of 10. If this isn't what you want, you need to be more precise about exactly how you would like your solution to handle the fact that many powers of 10 can't be exactly represented as doubles.
The best way to construct the table is probably to use string -> float conversion; that way hopefully your library authors will already have solved the problem of how to do the conversion in a way that gives the most precise answer possible.
|
2,551,667 | 2,551,701 | Trying to write a std::iterator : Compilation error | I am trying to write an std::iterator for the CArray<Type,ArgType> MFC class. This is what I have done till now:
template <class Type, class ArgType>
class CArrayIterator : public std::iterator<std::random_access_iterator_tag, ArgType>
{
public:
CArrayIterator(CArray<Type,ArgType>& array_in, int index_in = 0)
: m_pArray(&array_in), m_index(index_in)
{
}
void operator++() { ++m_index; }
void operator++(int) { ++m_index; }
void operator--() { --m_index; }
void operator--(int) { --m_index; }
void operator+=(int n) { m_index += n; }
void operator-=(int n) { m_index -= n; }
typename ArgType operator*() const{ return m_pArray->GetAt(m_index); }
typename ArgType operator->() const { return m_pArray->GetAt(m_index); }
bool operator==(const CArrayIterator& other) const
{
return m_pArray == other.m_pArray && m_index == other.m_index;
}
bool operator!=(const CArrayIterator& other) const
{
return ! (operator==(other));
}
private:
CArray<Type,ArgType>* m_pArray;
int m_index;
};
I also provided two helper functions to create the iterators like this:
template<class Type, class ArgType>
CArrayIterator<Type,ArgType> make_begin(CArray<Type,ArgType>& array_in)
{
return CArrayIterator<Type,ArgType>(array_in, 0);
}
template<class Type, class ArgType>
CArrayIterator<Type,ArgType> make_end(CArray<Type,ArgType>& array_in)
{
return CArrayIterator<Type,ArgType>(array_in, array_in.GetSize());
}
To test the code, I wrote a simple class A and tried to use it like this:
class A
{
public:
A(int n): m_i(n)
{
}
int get() const
{
return m_i;
}
private:
int m_i;
};
struct Test
{
void operator()(A* p)
{
std::cout<<p->get()<<"\n";
}
};
int main(int argc, char **argv)
{
CArray<A*, A*> b;
b.Add(new A(10));
b.Add(new A(20));
std::for_each(make_begin(b), make_end(b), Test());
return 0;
}
But when I compile this code, I get the following error:
Error 4 error C2784: 'bool
std::operator <(const
std::_Tree<_Traits> &,const
std::_Tree<_Traits> &)' : could not
deduce template argument for 'const
std::_Tree<_Traits> &' from
'CArrayIterator' C:\Program
Files\Microsoft Visual Studio
9.0\VC\include\xutility 1564 Vs8Console
Can anybody throw some light on what I am doing wrong and how it can be corrected? I am using VC9 compiler if it matters.
| You've said that your iterator is a "random access iterator". Part of the requirements for random access iterators is that you provide <, <=, > and >= comparision operators, with < giving a strict weak ordering and the usual relationships between them.
You need to provide the appropriate comparison operators, or you could consider 'downgrading' to a bi-directional iterator.
|
2,551,877 | 2,554,122 | Wrong EOF when unzipping binary file | I tried to unzip a binary file to a membuf from a zip archive using Lucian Wischik's Zip Utils:
http://www.wischik.com/lu/programmer/zip_utils.html
http://www.codeproject.com/KB/files/zip_utils.aspx
FindZipItem(hz, filename.c_str(), true, &j, &ze);
char *content = new char[ze.unc_size];
UnzipItem(hz, j, content, ze.unc_size);
delete[] content;
But it didn't unzip the file correctly. It stopped at the first 0x00 of the file.
For example when I unzip an MP3 file inside a ZIP archive, it will only unzip the first 4 bytes: 0x49443303 (ID3\0) because the 5th to 8th byte is 0x00.
I also tried to capture the ZR_RESULT, and it always return ZR_OK (which means completed without errors).
I think this guy also had the same problem, but no one replied to his question:
http://www.codeproject.com/KB/files/zip_utils.aspx?msg=2876222#xx2876222xx
Any kind of help would be appreciated :)
| It may be unzipping just fine. Keep in mind that many string oriented display functions will stop outputting characters at the first '\0'. Even your debugger will display a char* as if it were a string in your watch window. It can only guess what the data is in a character array... How are you testing how many bytes were unzipping?
You may want to try something like this:
FindZipItem(hz, filename.c_str(), true, &j, &ze);
char *content = new char[ze.unc_size];
memset(content, 0, ze.unc_size); // added so we can say that if it has a bunch of 0 bytes, then the unzip stopped early.
UnzipItem(hz, j, content, ze.unc_size);
// will print in hex all of the bytes in the array
for(int i = 0; i < ze.unc_size; ++i) {
printf("%02x ", content[i]);
}
delete[] content;
|
2,551,891 | 2,713,187 | boost.serialization and lazy initialization | i need to serialize directory tree.
i have no trouble with this type:
std::map<
std::string, // string(path name)
std::vector<std::string> // string array(file names in the path)
> tree;
but for the serialization the directory tree with the content i need other type:
std::map<
std::string, // string(path name)
std::vector< // files array
std::pair<
std::string, // file name
std::vector< // array of file pieces
std::pair< // <<<<<<<<<<<<<<<<<<<<<< for this i need lazy initialization
std::string, // piece buf
boost::uint32_t // crc32 summ on piece
>
>
>
>
> tree;
how can i initialize the object of type "std::pair" in the moment of its serialization?
i.e. read file piece/calculate crc32 summ.
up
| I would replace the std::string in the vector by a custom class, let me say MyFileNames
class MyFileNames : std::string
{
// add forward constructors as needed
};
std::map<
std::string, // string(path name)
std::vector<MyFileNames> // string array(file names in the path)
> tree;
And define the save serialization function for MyFileNames by converting the std::string to a
std::pair<
std::string, // file name
std::vector< // array of file pieces
std::pair< // <<<<<<<<<<<<<<<<<<<<<< for this i need lazy initialization
std::string, // piece buf
boost::uint32_t // crc32 summ on piece
>
>
>
and the serialize this type.
This let you evaluate the lazy part only the data is serialized. For the load you could ignore the lazy data, as I suppose that this data can be calculated.
|
2,552,034 | 2,561,899 | Generate header of view .obj file | Is there a way to generate a c++ header file for an .obj file? Or perhaps is there an utility that can view .obj files. I've already found objconv that converts between formats, but I can't find any .h generator/viewer.
| Given the C++ tag, the situation isn't quite as hopeless as some of the other answers imply.
In particular, at least with most C++ compilers, the name of a function will be mangled (Microsoft calls it "decorated") to indicate the parameters taken by that function. The mangling scheme varies from one compiler to another, but essentially any of them encodes enough information for you to re-create a declaration for the function -- the return type, the name of the function itself, the class name if it's a member function, and the exact number and type of parameters the function expects.
Though it wouldn't have to be done by mangling the name, a C++ system has no real choice but to include parameter information in the object file. When you overload functions, the linker needs some way to sort out which overload to link up with a particular call.
I should add that sorting this all out may be quite a bit of work though -- just for example, if the code includes templates, the symbol name in the object file will expand out all the template parameters (including default parameters). Just for example, consider a trivial bit of code like this:
#include <vector>
#include <string>
std::vector<std::string> x;
When I compile this with VC++, and then do dumpbin /symbols foo.obj, the output is about 75 kilobytes. Even though my source code only appears to define one symbol, the object file contains definitions for around 180 symbols, many of them almost completely unrelated to anything I wrote at all.
It's also worth mentioning that if the object file was compiled with debugging information, that will (normally) produce substantially more type information (and such) in the object file as well.
|
2,552,046 | 2,552,107 | How to pass operators as parameters | I have to load an array of doubles from a file, multiply each element by a value in a table (different values for different elements), do some work on it, invert the multiplication (that is, divide) and then save the data back to file.
Currently I implement the multiplication and division process in two separate methods. Now there is some extra work behind the scenes but apart from the specific statements where the multiplication/division occurs, the rest of the code is identical. As you can imagine, with this approach you have to be very careful making any changes. The surrounding code is not trivial, so its either a case of manually editing each method or copying changes from one method to the other and remembering to change the * and / operators.
After too many close calls I am fed up of this and would like to make a common function which implements the common logic and two wrapper functions which pass which operator to use as a parameter.
My initial approach was to use function pointers:
void MultiplyData(double data)
{ TransformData(data, &(operator *)); }
void DivideData(double data)
{ TransformData(data, &(operator /)); }
void TransformData(double data, double (*func)(double op1, double op2))
{ /* Do stuff here... */ }
However, I can't pass the operators as pointers (is this because it is an operator on a native type?), so I tried to use function objects. Initially I thought that multiplies and divides functors in <functional> would be ideal:
void MultiplyData(double data)
{
std::multiplies<double> multFunct;
TransformData(data, &multFunct);
}
void DivideData(double data)
{
std::divides<double> divFunct;
TransformData(data, &divFunct);
}
void TransformData(double data, std::binary_function<double, double, double> *funct)
{ /* Do stuff here... */ }
As you can see I was trying to use a base class pointer to pass the functor polymorphically. The problem is that std::binary_function does not declare an operator() member for the child classes to implement.
Is there something I am missing, or is the solution to implement my own functor heirarchy (which really seems more trouble than it is worth)?
| Make TransformData a template function:
template <typename F>
typename F::result_type TransformData(double data, F f) { ... }
Call it thus:
double MultiplyData(double data) {
return TransformData(data, std::multiplies<double>());
}
std::binary_function is a tagging class. It's primary purpose is not to provide a base class interface, but to inject some typedefs into functor-style classes (via inheritance), which makes them usable by other parts of the standard library.
|
2,552,165 | 2,552,342 | Finding missing symbols in libstdc++ on Debian/squeeze | I'm trying to use a pre-compiled library provided as a .so file.
This file is dynamically linked against a few librairies :
$ ldd /usr/local/test/lib/libtest.so
linux-gate.so.1 => (0xb770d000)
libstdc++-libc6.1-1.so.2 => not found
libm.so.6 => /lib/i686/cmov/libm.so.6 (0xb75e1000)
libc.so.6 => /lib/i686/cmov/libc.so.6 (0xb7499000)
/lib/ld-linux.so.2 (0xb770e000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb747c000)
Unfortunately, in Debian/squeeze, there is no libstdc++-libc6.1-1.so.* file.
Only a libstdc++.so.* file provided by the libstdc++6 package.
I tried to link (using ln -s) libstdc++-libc6.1-1.so.2 to the libstdc++.so.6 file. It does not work, a batch of symbols seems to be lacking when I'm trying to ld my .o files with this lib.
/usr/local/test/lib/libtest.so: undefined reference to `__builtin_vec_delete'
/usr/local/test/lib/libtest.so: undefined reference to `istrstream::istrstream(int, char const *, int)'
/usr/local/test/lib/libtest.so: undefined reference to `__rtti_user'
/usr/local/test/lib/libtest.so: undefined reference to `__builtin_new'
/usr/local/test/lib/libtest.so: undefined reference to `istream::ignore(int, int)'
What would you do ? How may I find in which lib those symbols are exported ?
| Google says that you need libstdc++2.9-glibc2.1
http://linux.derkeiler.com/Mailing-Lists/Debian/2005-07/0755.html
Although it's from obsolete debian release and I'm not sure if it's such a good idea to install it.
Edit
Actually I tried it out of curiosity. It didn't do any harm and seem to coexist well with standard libstc++.so
debian:/home/dmitry# ll /usr/lib/\*stdc\*
-rw-r--r-- 1 root root 256240 2000-02-19 17:41 /usr/lib/libstdc++-2-libc6.1-1-2.9.0.so
lrwxrwxrwx 1 root root 30 2010-03-31 15:54 /usr/lib/libstdc++-libc6.1-1.so.2 -> libstdc++-2-libc6.1-1-2.9.0.so
lrwxrwxrwx 1 root root 19 2010-01-21 10:13 /usr/lib/libstdc++.so.6 -> libstdc++.so.6.0.13
-rw-r--r-- 1 root root 958628 2010-01-08 11:39 /usr/lib/libstdc++.so.6.0.13
wget http://archive.debian.org/debian/pool/main/e/egcs1.1/libstdc++2.9-glibc2.1_2.91.66-4_i386.deb
dpkg -i libstdc++2.9-glibc2.1_2.91.66-4_i386.deb
|
2,552,172 | 2,552,959 | Thread Synchronisation 101 | Previously I've written some very simple multithreaded code, and I've always been aware that at any time there could be a context switch right in the middle of what I'm doing, so I've always guarded access the shared variables through a CCriticalSection class that enters the critical section on construction and leaves it on destruction. I know this is fairly aggressive and I enter and leave critical sections quite frequently and sometimes egregiously (e.g. at the start of a function when I could put the CCriticalSection inside a tighter code block) but my code doesn't crash and it runs fast enough.
At work my multithreaded code needs to be a tighter, only locking/synchronising at the lowest level needed.
At work I was trying to debug some multithreaded code, and I came across this:
EnterCriticalSection(&m_Crit4);
m_bSomeVariable = true;
LeaveCriticalSection(&m_Crit4);
Now, m_bSomeVariable is a Win32 BOOL (not volatile), which as far as I know is defined to be an int, and on x86 reading and writing these values is a single instruction, and since context switches occur on an instruction boundary then there's no need for synchronising this operation with a critical section.
I did some more research online to see whether this operation did not need synchronisation, and I came up with two scenarios it did:
The CPU implements out of order execution or the second thread is running on a different core and the updated value is not written into RAM for the other core to see; and
The int is not 4-byte aligned.
I believe number 1 can be solved using the "volatile" keyword. In VS2005 and later the C++ compiler surrounds access to this variable using memory barriers, ensuring that the variable is always completely written/read to the main system memory before using it.
Number 2 I cannot verify, I don't know why the byte alignment would make a difference. I don't know the x86 instruction set, but does mov need to be given a 4-byte aligned address? If not do you need to use a combination of instructions? That would introduce the problem.
So...
QUESTION 1: Does using the "volatile" keyword (implicity using memory barriers and hinting to the compiler not to optimise this code) absolve a programmer from the need to synchronise a 4-byte/8-byte on x86/x64 variable between read/write operations?
QUESTION 2: Is there the explicit requirement that the variable be 4-byte/8-byte aligned?
I did some more digging into our code and the variables defined in the class:
class CExample
{
private:
CRITICAL_SECTION m_Crit1; // Protects variable a
CRITICAL_SECTION m_Crit2; // Protects variable b
CRITICAL_SECTION m_Crit3; // Protects variable c
CRITICAL_SECTION m_Crit4; // Protects variable d
// ...
};
Now, to me this seems excessive. I thought critical sections synchronised threads between a process, so if you've got one you can enter it and no other thread in that process can execute. There is no need for a critical section for each variable you want to protect, if you're in a critical section then nothing else can interrupt you.
I think the only thing that can change the variables from outside a critical section is if the process shares a memory page with another process (can you do that?) and the other process starts to change the values. Mutexes would also help here, named mutexes are shared across processes, or only processes of the same name?
QUESTION 3: Is my analysis of critical sections correct, and should this code be rewritten to use mutexes? I have had a look at other synchronisation objects (semaphores and spinlocks), are they better suited here?
QUESTION 4: Where are critical sections/mutexes/semaphores/spinlocks best suited? That is, which synchronisation problem should they be applied to. Is there a vast performance penalty for choosing one over the other?
And while we're on it, I read that spinlocks should not be used in a single-core multithreaded environment, only a multi-core multithreaded environment. So, QUESTION 5: Is this wrong, or if not, why is it right?
Thanks in advance for any responses :)
| Q1: Using the "volatile" keyword
In VS2005 and later the C++ compiler surrounds access to this variable using memory barriers, ensuring that the variable is always completely written/read to the main system memory before using it.
Exactly. If you are not creating portable code, Visual Studio implements it exactly this way. If you want to be portable, your options are currently "limited". Until C++0x there is no portable way how to specify atomic operations with guaranteed read/write ordering and you need to implement per-platform solutions. That said, boost already did the dirty job for you, and you can use its atomic primitives.
Q2: Variable needs to be 4-byte/8-byte aligned?
If you do keep them aligned, you are safe. If you do not, rules are complicated (cache lines, ...), therefore the safest way is to keep them aligned, as this is easy to achieve.
Q3: Should this code be rewritten to use mutexes?
Critical section is a lightweight mutex. Unless you need to synchronize between processes, use critical sections.
Q4: Where are critical sections/mutexes/semaphores/spinlocks best suited?
Critical sections can even do spin waits for you.
Q5: Spinlocks should not be used in a single-core
Spin lock uses the fact that while the waiting CPU is spinning, another CPU may release the lock. This cannot happen with one CPU only, therefore it is only a waste of time there. On multi-CPU spin locks can be good idea, but it depends on how often the spin wait will be successful. The idea is waiting for a short while is a lot faster then doing context switch there and back again, therefore if the wait it likely to be short, it is better to wait.
|
2,552,416 | 2,552,458 | How can I find the user's home dir in a cross platform manner, using C++? | How can I find the user's home directory in a cross platform manner in C++? i.e. /home/user in Linux, C:\Users\user\ on Windows Vista, C:\Documents And Settings\user\ on Windows XP, and whatever it is that Macs use. (I think it's /User/user)
Basically, what I'm looking for is a C++ way of doing this (example in python)
os.path.expanduser("~")
| I don't think it's possible to completely hide the Windows/Unix divide with this one (unless, maybe, Boost has something).
The most portable way would have to be getenv("HOME") on Unix and concatenating the results of getenv("HOMEDRIVE") and getenv("HOMEPATH") on Windows.
|
2,552,940 | 2,553,014 | Executing certain code for every method call in C++ | I have a C++ class I want to inspect. So, I would like to all methods print their parameters and the return, just before getting out.
The latter looks somewhat easy. If I do return() for everything, a macro
#define return(a) cout << (a) << endl; return (a)
would do it (might be wrong) if I padronize all returns to parenthesized (or whatever this may be called). If I want to take this out, just comment out the define.
However, printing inputs seems more difficult. Is there a way I can do it, using C++ structures or with a workaroud hack?
|
However, printing inputs seems more
difficult. Is there a way I can do it,
using C++ structures or with a
workaroud hack?
No.
Update: I'm going to lose some terseness in my answer by suggesting that you can probably achieve what you need by applying Design by Contract.
|
2,553,015 | 2,553,215 | Tangent of a parametric discrete curve | I have a parametric curve, say two vectors of doubles where the parameter is the index, and I have to calculate the angle of the tangent to this curve at any given point (index).
Any suggestion or link about how to do that?
Thanks.
| The tangent to a smooth curve at a point P is the parametric straight line P + tV, where V is the derivative of the curve with respect to "the parameter". But here the parameter is just the index of an array, and numerical differentiation is a difficult problem, hence to approximate the tangent I would use (weighted) least squares approximation.
In other words, choose three or five points of the curve around your point of interest P (i.e. P[i-2], P[i-1], P[i], P[i+1], and P[i+2], if P==P[i]), and approximate them with a straight line, in the least squares sense. The more weight you assign to the middle point P, the more close the line will be to P; on the other hand, the more weight you assign to the extremal points, the more "tangent" the straight line will be, that is, the more nicely it will approximate you curve in the neighborhood of P.
For example, with respect to the following points:
x = [-1, 0, 1]
y = [ 0, 1, 0]
for which the tangent is not defined (as in Anders Abel's answer),
this approach should yield a horizontal straight line close to the point (0,1).
|
2,553,149 | 2,553,208 | Area of a irregular shape | I have set of points which lies on the image. These set of points form a irregular closed shape. I need to find the area of this shape. Does any body which is the normal algorithm used for calculating the area ? Or is there any support available in libraries such as boost? I am using C++.
| If you polygon is simple (it doesn't have any point in common except for the pairs of consecutive segments) then wikipedia comes to help you:
The formula for the area is
(it assumes that the last point is the same of the first one)
You can easily implement it as
float area = 0.0f;
for (int i = 0; i < numVertices - 1; ++i)
area += point[i].x * point[i+1].y - point[i+1].x * point[i].y;
area += point[numVertices-1].x * point[0].y - point[0].x * point[numVertices-1].y;
area = abs(area) / 2.0f;
Of course vertices must be ordered according to their natural following in the polygon..
|
2,553,397 | 2,553,452 | Why does the MSCVRT library generate conflicts at link time? | I am building a project in Visual C++ 2008, which is an example MFC-based app for a static C++ class library I will be using in my own project soon. While building the Debug configuration, I get the following:
warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library
After using the recommended option (by adding "msvcrt" to the "Ignore specific library" field in the project linker settings for the Debug configuration), the program links and runs fine. However, I'd like to find out why this conflict occured, why do I have to ignore a critical library, and if I'm to expect problems later I if add the ignore, or what happens if I don't (because the program builds anyway).
At the same time, the Release configuration warns:
warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:ICF' specification
warning LNK4098: defaultlib 'MSVCRTD' conflicts with use of other libs; use /NODEFAULTLIB:library
I'm guessing that the "D" suffix means this is the debug version of the vc++ runtime, no idea why this gets used this time. Anyway, adding "msvcrtd" to the ignore field causes lots of link errors of the form:
error LNK2001: unresolved external symbol __imp___CrtDbgReportW
Any insight greatly appreciated.
| This usually happens when you link against a static library that uses another version of the VC++ runtime (C++ ->Code Generation->Runtime Library setting in the project properties).
|
2,553,488 | 2,553,736 | How to log when a particular memory location gets written and by which function? | I have a bug which happens very rarely but crashes my C++ program. It's seems I have a buffer overflow problem or something similar. I find that these types of bug are the most difficult to diagnose.
My program always crashes because of the same corrupted memory location. Is there some debugging tool which could detect when a particular memory location get written to and logs the function which does it?
I'm using Visual Leak Detector (VLD) for my memory leak hunting and it works great. It substitutes the original mallocs which its own and logs every allocation. I was wondering if there is something similar for memory?
I know that something like that would cripple a program, but it could be really helpful.
I'm using Visual Studio 2008.
| If you are using Visual C++ then look up data breakpoints.
|
2,553,522 | 2,553,533 | Interview question: Check if one string is a rotation of other string | A friend of mine was asked the following question today at interview for the position of software developer:
Given two string s1 and s2 how will you check if s1 is a rotated version of s2 ?
Example:
If s1 = "stackoverflow" then the following are some of its rotated versions:
"tackoverflows"
"ackoverflowst"
"overflowstack"
where as "stackoverflwo" is not a rotated version.
The answer he gave was:
Take s2 and find the longest prefix that is a sub string of s1, that will give you the point of rotation. Once you find that point, break s2 at that point to get s2a and s2b, then just check if concatenate(s2a,s2b) == s1
It looks like a good solution to me and my friend. But the interviewer thought otherwise. He asked for a simpler solution. Please help me by telling how would you do this in Java/C/C++ ?
Thanks in advance.
| First make sure s1 and s2 are of the same length. Then check to see if s2 is a substring of s1 concatenated with s1:
algorithm checkRotation(string s1, string s2)
if( len(s1) != len(s2))
return false
if( substring(s2,concat(s1,s1))
return true
return false
end
In Java:
boolean isRotation(String s1,String s2) {
return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1);
}
|
2,553,706 | 2,553,838 | What's the difference between starting a process from the dock vs. the command line on OS X | I'm debugging an issue on OS X that only occurs when the application is started from the dock. It does not happen when the app is started from the command line. What is the difference between the two scenarios? The code I'm working with is a c++ based bundled plug-in being loaded in a third party app. I've attached to the process with GDB in both scenarios and the only difference I can see is that a couple of extra dylibs are loaded in the process when running from the command line and that the base address of my library is slightly different in the two scenarios. I've tried changing my linkage to -prebind and/or -bind_at_load to no avail.
| One important difference is that the initial working directory will be different in each case. Applications should never make any assumptions about the working directory and will break in interesting ways if they do.
|
2,554,082 | 2,554,098 | Array performance question | I am very familiar with STL vector (and other container) performance guarantees, however I can't seem to find anything concrete about plain arrays.
Are pointer arithmetic and [] methods constant or linear time?
| They are constant time. (Same as vector.)
When you say a[b], it becomes *(a + b). Both (pointer arithmetic) addition and dereferencing are constant time.
When adding an integer to a pointer, it moves that many elements over:
T* p; size_t i;
T* q = p + i; // same as:
T* q = reinterpret_cast<T*>(reinterpret_cast<char*>(p) + i * sizeof(T));
Every operation in there is constant time.
|
2,554,215 | 2,554,417 | C++: Conceptual problem in designing an intepreter | I'm programming an interpreter for an experimental programming language (educational, fun,...)
So far, everything went well (Tokenizer & Parser), but I'm getting a huge problem with some of the data structures in the part that actually runs the tokenized and parsed code.
My programming language basically has only two types, int and string, and they are represented as C++ strings (std class) and ints
Here is a short version of the data structure that I use to pass values around:
enum DataType
{
Null,
Int,
String
}
class Symbol
{
public:
string identifier;
DataType type;
string stringValue;
int intValue;
}
I can't use union because string doesn't allow me to.
This structure above is beginning to give me a headache.
I have to scatter code like this everywhere in order to make it work, it is beginning to grow unmaintainable:
if( mySymbol.type == Int )
{
mySymbol.intValue = 1234;
} else {
mySymbol.stringValue = "abcde";
}
I use the Symbol data structure for variables, return values for functions and general representation of values in the programming language.
Is there any better way to solve this? I hope so!
| The problem comes from the fact, that your symbol class is a type that contains two different types that you are trying to identify through the single type of the class Symbol.
It would be better to polymorphically create the symbols:
class Symbol
{
public:
virtual Symbol& operator = (int val) = 0; // Pure virtual
virtual Symbol& operator = (string val) = 0; // Pure virtual
private:
string identifier;
};
class IntSymbol : public Symbol
{
public:
virtual Symbol& operator = (int val)
{
this->val = val;
return *this; // to make multiple assignments possible
}
virtual Symbol& operator = (string val)
{
throw new exception("Programm error");
return *this; // to make it compile
}
private:
int val;
};
You do the same for the StringSymbol
|
2,554,221 | 2,554,247 | How to check if memory has been initialized? | Is there a way of checking if memory pointed to by pointer has been initialized?(not necessarily by my program).
Thanks
| No.
Uninitialized memory can contain anything, including bytes that make it look like it has been initialized.
|
2,554,405 | 2,554,450 | Sort a list of pointers | Once again I find myself failing at some really simple task in C++. Sometimes I wish I could de-learn all I know from OO in java, since my problems usually start by thinking like Java.
Anyways, I have a std::list<BaseObject*> that I want to sort. Let's say that BaseObject is:
class BaseObject {
protected:
int id;
public:
BaseObject(int i) : id(i) {};
virtual ~BaseObject() {};
};
I can sort the list of pointer to BaseObject with a comparator struct:
struct Comparator {
bool operator()(const BaseObject* o1, const BaseObject* o2) const {
return o1->id < o2->id;
}
};
And it would look like this:
std::list<BaseObject*> mylist;
mylist.push_back(new BaseObject(1));
mylist.push_back(new BaseObject(2));
// ...
mylist.sort(Comparator());
// intentionally omitted deletes and exception handling
Until here, everything is a-ok. However, I introduced some derived classes:
class Child : public BaseObject {
protected:
int var;
public:
Child(int id1, int n) : BaseObject(id1), var(n) {};
virtual ~Child() {};
};
class GrandChild : public Child {
public:
GrandChild(int id1, int n) : Child(id1,n) {};
virtual ~GrandChild() {};
};
So now I would like to sort following the following rules:
For any Child object c and BaseObject b, b<c
To compare BaseObject objects, use its ids, as before.
To compare Child objects, compare its vars. If they are equal, fallback to rule 2.
GrandChild objects should fallback to the Child behavior (rule 3).
I initially thought that I could probably do some casts in Comparator. However, this casts away constness. Then I thought that probably I could compare typeids, but then everything looked messy and it is not even correct.
How could I implement this sort, still using list<BaseObject*>::sort ?
Thank you
| You are looking at doing double dispatch - that is calling a virtual function depending on the types of two objects rather than one. Take a look at this wikipedia article for a heads-up http://en.wikipedia.org/wiki/Double_dispatch. I have to say that whenever I find myself in this situation, I try to change direction :-)
And can I make a couple of observations about your code. There is nothing precisely wrong with it but:
in C++, the std::list is the container of last resort - you should normally default to using a std:;vector, unless you specifically need a feature that only list provides:
protected data is always a bad idea
|
2,554,447 | 2,554,524 | How to use WaitForSingleObject | In order to try out how to program with the Win32 API, I wrote a program that creates a process.
Then I want to check if my process waits for the newly created process, close the handle and then check WaitForSingleObject again (the second process is sleeping for 700 ms)
First process:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
void main()
{
bool ret;
bool retwait;
STARTUPINFO startupinfo;
GetStartupInfo (&startupinfo);
PROCESS_INFORMATION pro2info;
wchar_t wcsCommandLine[] = L"D:\\betriebssystemePRA1PRO2.exe";
ret = CreateProcess(NULL, wcsCommandLine, NULL, NULL, false, CREATE_NEW_CONSOLE, NULL,
NULL, &startupinfo, &pro2info);
cout<<"hProcess: "<<pro2info.hProcess<<endl;
cout<<"dwProcessId: "<<pro2info.dwProcessId <<endl;
if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true)
cout<<"waitprocess:true"<<endl; //The process is finished
else
cout<<"waitprocess:false"<<endl;
CloseHandle (pro2info.hProcess);//prozesshandle schließen, "verliert connection"
if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true) //When the process has finished
cout<<"waitprocess:true"<<endl;
else
cout<<"waitprocess:false"<<endl;
//cout<<GetLastError()<<endl; //Output the last error.
ExitProcess(0);
}
Second process:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
void main()
{
int b;
b = GetCurrentProcessId();
cout << b << endl;
cout << "Druecken Sie Enter zum Beenden" << endl;
cin.get();
//Wait until the user confirms
Sleep (700);
ExitProcess(0);
cout<<"test";
}
The first process prints false, false ; but it should print true, false.
Instead of the if-else statement, I used this:
//switch(WaitForSingleObject (pro2info.hProcess, INFINITE)){
// case WAIT_OBJECT_0: cout << "ja";
// break;
// case WAIT_FAILED:cout << "nein";
// break;
// case WAIT_TIMEOUT:
// break;
//}
// cout<<"waitprocess:true"<<endl;//prozess ist fertig
//else
// cout<<"waitprocess:false"<<endl;
And this seems to work. What did I do wrong with my if-else statement?
| You really need to pay attention to the meaning for the return value of the API functions. You cannot ignore a FALSE return from CreateProcess(). WaitForSingleObject() can return several values, it returns 0 if the wait completed successfully. Which makes you print "false".
|
2,554,462 | 2,554,547 | c++ template and its element type | This is my template matrix class:
template<typename T>
class Matrix
{
public:
....
Matrix<T> operator / (const T &num);
}
However, in my Pixel class, I didn't define the Pixel/Pixel operator at all!
Why in this case, the compiler still compiles?
Pixel class
#ifndef MYRGB_H
#define MYRGB_H
#include <iostream>
using namespace std;
class Pixel
{
public:
// Constructors
Pixel();
Pixel(const int r, const int g, const int b);
Pixel(const Pixel &value);
~Pixel();
// Assignment operator
const Pixel& operator = (const Pixel &value);
// Logical operator
bool operator == (const Pixel &value);
bool operator != (const Pixel &value);
// Calculation operators
Pixel operator + (const Pixel &value);
Pixel operator - (const Pixel &value);
Pixel operator * (const Pixel &value);
Pixel operator * (const int &num);
Pixel operator / (const int &num);
// IO-stream operators
friend istream &operator >> (istream& input, Pixel &value);
friend ostream &operator << (ostream& output, const Pixel &value);
private:
int red;
int green;
int blue;
};
#endif
| C++ templates are instantiated at the point you use them, and this happens for the Matrix<T>::operator/(const T&), too. This means the compiler will allow Matrix<Pixel>, unless you ever invoke the division operator.
|
2,554,490 | 2,554,530 | Learning C++ as a Perl programmer | I'm a Perl5 programmer for 7 years and I'm trying to learn C++ now.
Some of the C++ syntax is hard for me to understand and to think in C++ way.
For example:
In Perl, you can mix the data in the arrays
@array = (1,"string",5.355);
You can assign any value to a scalar variable:
$var = 1;
$var = "string";
$var = \$reference_to_scalar;
There are many examples.
A friend of mine recommend me the book "Thinking of C++" by Bruce Eckel, but I haven't any C background and it's hard for me to understand some things.
So my question is - could you recommend me a book for this situation. I don't want to learn C. I understand OOP (I'm getting more familiar with C++ oop aswell), I understand the point of the pointers (and some arithmetic) and references (widely used in Perl).
I don't need manuals for dummies (what is int, bool, double, if, while), I just need a direction how to learn C++ from the perspective of a Perl programmer, because I'm sure that there are many like me.
Thank you in advance.
EDIT: Thank you for all the recommended books and the answers, I will try with "Accelerated C++". I will start from the beginning and try to change my mindflow to C++. I have added the "beginner" tag.
| "C++ For Perl Programmers" is a pretty specific request. Given that Perl abstracts away more of the machine than C++ does, I think that a good way to start would be to forget what you know about Perl and get a regular C++ book.
For example, it seems reasonable to you that you should be allowed to have multiple data types in an array, because a Perl array is a higher-level construct than just a series of contiguous words in memory. If I were going to go from an array in C++ to one in Perl, I would say that a Perl array is like a C++ array that holds pointers to data instead of data (if that is even true - I am not a Perl programmer so it may not be. Maybe a Perl array is more like a linked list data structure. In any case, you get the idea.) Going backwards, IMO, is not quite the same.
As far as the book I'd recommend - there are a lot of good ones, so it depends on the style and depth you're looking for. I think Accelerated C++ is great for ramping up - its thorough and covers a lot of ground without inundating you with the tedious details.
|
2,554,867 | 2,561,332 | Changing the system time zone succeeds once and then no longer changes | I'm using the WinAPI to set the time zone on a Windows XP SP3 box. I'm reading the time zone information from the HKLM\Software\Microsoft\WindowsNT\Time Zones\<time zone name> key and then setting the time zone to the specified time zone.
I enumerate the keys under the Time Zones key, grab the TZI value and stuff it into a TIME_ZONE_INFORMATION struct to be passed to SetTimeZoneInformation. All seems to work on the first pass. The time zone changes, no error is returned.
The second time I perform this operation (same user, new session, on login before userinit) the call succeeds but the system does not reflect the time zone change. Neither the clock nor time stamps on files are updated to the new time zone. When I navigate to:
HKLM\System\CurrentControlSet\Control\TimeZoneInformation my new time zone information is present.
A couple strange things are happening when I'm setting my time zone:
Also when I parse the TZI binary value from the registry to store in my TIME_ZONE_INFORMATION struct I'm noticing the struct has the DaylightDate.wDay and StandardDate.wDay field always set to 0
I tried to call GetTimeZoneInformation right after I call SetTimeZoneInformation but the call fails with a 1300 error (Not all privileges or groups referenced are assigned to the caller. )
I'm also making sure to send a WM_BROADCAST message so Explorer knows whats going on.
Think it's the parsing of the byte array to the TIME_ZONE_INFORMATION struct? Or am I missing some thing else important?
EDIT:
Found a document stating why this is happening: here. Privilege was introduced in Vista...thanks MSDN docs...
Per the Microsoft documentation
I'm enabling the SE_TIME_ZONE_NAME
privilege for the current processes
token. But when I attempt to call
LookupPriviledgeValue for
SE_TIME_ZONE_NAME I get a 1313
error (A specified privilege does
not exist. ).
| After messing with this for awhile I've fixed the issue but I'm not quite sure what step fixed it. I added an extra clause to check the OS to verify whether or not to adjust the process token to enable the SE_TIME_ZONE_NAME. It now only does this on post-XP OS's.
I also changed how the TZI registry value was stored into my struct. I realized that on the TIME_ZONE_INFORMATION MSDN document is contained the struct that is used for the registry verison (REG_TZI_FORMAT). Simply reading the binary value straight into the struct eliminated a bit of code.
I also guaranteed that BOTH DaylightName and StandardName were populated.
Finally I called a RegFlushKey(HKEY_LOCAL_MACHINE) right after the SetTimeZoneInformation call. After taking these steps the time zone is changing as expected.
|
2,554,934 | 2,554,940 | Array pointer arithmetic question | Is there a way to figure out where in an array a pointer is?
Lets say we have done this:
int nNums[10] = {'11','51','23', ... }; // Some random sequence
int* pInt = &nNums[4]; // Some index in the sequence.
...
pInt++; // Assuming we have lost track of the index by this stage.
...
Is there a way to determine what element index in the array pInt is 'pointing' to without walking the array again?
| Yes:
ptrdiff_t index = pInt - nNums;
When pointers to elements of an array are subtracted, it is the same as subtracting the subscripts.
The type ptrdiff_t is defined in <stddef.h> (in C++ it should be std::ptrdiff_t and <cstddef> should be used).
|
2,554,957 | 2,560,675 | Inclusion of dshow.h results in definition errors | I am trying to do a few things using DirectShow for audio playback. I have a header file, at the top is:
#pragma once
#include <dshow.h>
#pragma comment(lib, "strmiids.lib")
and then it goes on to define a class.
When including dshow.h I get the following complilation errors:
C:\Program Files\Microsoft SDKs\Windows\v7.0\include\ddraw.h(703) : error C2011: '_DDPIXELFORMAT' : 'struct' type redefinition
c:\program files\microsoft sdks\windows\v7.0\include\ksmedia.h(5749) : see declaration of '_DDPIXELFORMAT'
C:\Program Files\Microsoft SDKs\Windows\v7.0\include\ddraw.h(2249) : error C2079: '_DDSURFACEDESC::ddpfPixelFormat' uses undefined struct '_DDPIXELFORMAT'
C:\Program Files\Microsoft SDKs\Windows\v7.0\include\ddraw.h(2292) : error C2079: '_DDSURFACEDESC2::ddpfPixelFormat' uses undefined struct '_DDPIXELFORMAT'
C:\Program Files\Microsoft SDKs\Windows\v7.0\include\strmif.h(12918) : error C2011: 'tagTIMECODE_SAMPLE' : 'struct' type redefinition
c:\program files\microsoft sdks\windows\v7.0\include\ksmedia.h(5274) : see declaration of 'tagTIMECODE_SAMPLE'
I can't figure out what would cause these errors in this case. The header file is part of an MFC project if that makes any difference. Any advice?
| Fixed this by changing the order of the #include definitions. I moved the header file that the above code was defined in to the top and it works ok now. Must have been a clash with some code in another file, possibly some directSound related stuff.
|
2,555,022 | 2,564,363 | Can shared memory be read and validated without mutexes? | On Linux I'm using shmget and shmat to setup a shared memory segment that one process will write to and one or more processes will read from. The data that is being shared is a few megabytes in size and when updated is completely rewritten; it's never partially updated.
I have my shared memory segment laid out as follows:
-------------------------
| t0 | actual data | t1 |
-------------------------
where t0 and t1 are copies of the time when the writer began its update (with enough precision such that successive updates are guaranteed to have differing times). The writer first writes to t1, then copies in the data, then writes to t0. The reader on the other hand reads t0, then the data, then t1. If the reader gets the same value for t0 and t1 then it considers the data consistent and valid, if not, it tries again.
Does this procedure ensure that if the reader thinks the data is valid then it actually is?
Do I need to worry about out-of-order execution (OOE)? If so, would the reader using memcpy to get the entire shared memory segment overcome the OOE issues on the reader side? (This assumes that memcpy performs it's copy linearly and ascending through the address space. Is that assumption valid?)
| Joe Duffy gives the exact same algorithm and calls it: "A scalable reader/writer scheme with optimistic retry".
It works.
You need two sequence number fields.
You need to read and write them in opposite order.
You might need to have memory barriers in place, depending on the memory ordering guarantees of the system.
Specifically, you need read acquire and store release semantics for the readers and writers when they access t0 or t1 for reading and writing respectively.
What instructions are needed to achieve this, depends on the architecture. E.g. on x86/x64, because of the relatively strong guarantees one needs no machine specific barriers at all in this specific case*.
* one still needs to ensure that the compiler/JIT does not mess around with loads and stores , e.g. by using volatile (that has a different meaning in Java and C# than in ISO C/C++. Compilers may differ, however. E.g. using VC++ 2005 or above with volatile it would be safe doing the above. See the "Microsoft Specific" section. It can be done with other compilers as well on x86/x64. The assembly code emitted should be inspected and one must make sure that accesses to t0 and t1 are not eliminated or moved around by the compiler.)
As a side note, if you ever need MFENCE, lock or [TopOfStack],0 might be a better option, depending on your needs.
|
2,555,033 | 2,555,048 | Linker error: wants C++ virtual base class destructor | I have a link error where the linker complains that my concrete class's destructor is calling its abstract superclass destructor, the code of which is missing.
This is using GCC 4.2 on Mac OS X from XCode.
I saw g++ undefined reference to typeinfo but it's not quite the same thing.
Here is the linker error message:
Undefined symbols:
"ConnectionPool::~ConnectionPool()", referenced from:
AlwaysConnectedConnectionZPool::~AlwaysConnectedConnectionZPool()in RKConnector.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
Here is the abstract base class declaration:
class ConnectionPool {
public:
static ConnectionPool* newPool(std::string h, short p, std::string u, std::string pw, std::string b);
virtual ~ConnectionPool() =0;
virtual int keepAlive() =0;
virtual int disconnect() =0;
virtual sql::Connection * getConnection(char *compression_scheme = NULL) =0;
virtual void releaseConnection(sql::Connection * theConnection) =0;
};
Here is the concrete class declaration:
class AlwaysConnectedConnectionZPool: public ConnectionPool {
protected:
<snip data members>
public:
AlwaysConnectedConnectionZPool(std::string h, short p, std::string u, std::string pw, std::string b);
virtual ~AlwaysConnectedConnectionZPool();
virtual int keepAlive(); // will make sure the connection doesn't time out. Call regularly
virtual int disconnect(); // disconnects/destroys all connections.
virtual sql::Connection * getConnection(char *compression_scheme = NULL);
virtual void releaseConnection(sql::Connection * theConnection);
};
Needless to say, all those members are implemented. Here is the destructor:
AlwaysConnectedConnectionZPool::~AlwaysConnectedConnectionZPool()
{
printf("AlwaysConnectedConnectionZPool destructor call"); // nothing to destruct in fact
}
and also maybe the factory routine:
ConnectionPool* ConnectionPool::newPool(std::string h, short p, std::string u, std::string pw, std::string b)
{
return new AlwaysConnectedConnectionZPool(h, p, u, pw, b);
}
I can fix this by artificially making my abstract base class concrete. But I'd rather do something better. Any idea?
Thanks
| Even if you declare a destructor as a pure virtual function, you must provide an implementation for it. Although you cannot instantiate an abstract class directly, it is always instantiated when you instantiate one of its derived (concrete) classes. And so at some point such instances will be destroyed, thus requiring a destructor. The implementation of the pure virtual destructor can be (and normally is) an empty function:
ConnectionPool::~ConnectionPool() {
}
|
2,555,173 | 2,555,270 | C++ include header conventions | Suppose I have a file X.h which defines a class X, whose methods are implemented in X.cc.
The file X.h includes a file Y.h because it needs Y to define class X. In X.cc, we can refer
to Y because X.h has already included Y.h. Should I still include Y.h in X.cc ?
I understand that I don't need to and I can depend on header guards to prevent multiple inclusions.
But on the one hand, including Y.h makes X.cc a little more independent of X.h (can't be
completely independent of course). What is the accepted practice?
Another example: including <iostream> in both .h and .cc files. I see some people do this
and some don't.
| Be minimal. In headers, prefer forward declarations to full definitions. Use iosfwd instead of ostream, for example.
That said, X.h and X.cc represent the same logical unit. If your dependency on Y.h ever changed (for example, turned it into a forward declaration), you'd be changing the class anyway. So you can move #include "Y.h" to X.cc justifiably.
In other words, X.cc and X.h go hand in hand. X.cc can reliably assume what's in X.h. So there's no need to re-include something if X.h does.
Dependencies where you 'include it anyway' occur with resources other than your own. For example, if you needed Z.h, you'd include it even if Y.h does. X.h does not get to reliably assume the contents of Y.h because X.h doesn't go with Y.h, it uses it.
|
2,555,389 | 2,555,513 | GLSL Error: failed to preprocess the source. How can I troubleshoot this? | I'm trying to learn to play with OpenGL GLSL shaders. I've written a very simple program to simply create a shader and compile it. However, whenever I get to the compile step, I get the error:
Error: Preprocessor error
Error: failed to preprocess the source.
Here's my very simple code:
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <GL/glext.h>
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
const int screenWidth = 640;
const int screenHeight = 480;
const GLchar* gravity_shader[] = {
"#version 140"
"uniform float t;"
"uniform mat4 MVP;"
"in vec4 pos;"
"in vec4 vel;"
"const vec4 g = vec4(0.0, 0.0, -9.80, 0.0);"
"void main() {"
" vec4 position = pos;"
" position += t*vel + t*t*g;"
" gl_Position = MVP * position;"
"}"
};
double pointX = (double)screenWidth/2.0;
double pointY = (double)screenWidth/2.0;
void initShader() {
GLuint shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(shader, 1, gravity_shader, NULL);
glCompileShader(shader);
GLint compiled = true;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if(!compiled) {
GLint length;
GLchar* log;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
log = (GLchar*)malloc(length);
glGetShaderInfoLog(shader, length, &length, log);
std::cout << log <<std::endl;
free(log);
}
exit(0);
}
bool myInit() {
initShader();
glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
glColor3f(0.0f, 0.0f, 0.0f);
glPointSize(1.0);
glLineWidth(1.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble) screenWidth, 0.0, (GLdouble) screenHeight);
glEnable(GL_DEPTH_TEST);
return true;
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(screenWidth, screenHeight);
glutInitWindowPosition(100, 150);
glutCreateWindow("Mouse Interaction Display");
myInit();
glutMainLoop();
return 0;
}
Where am I going wrong? If it helps, I am trying to do this on a Acer Aspire One with an atom processor and integrated Intel video running the latest Ubuntu. It's not very powerful, but then again, this is a very simple shader. Thanks a lot for taking a look!
| If you're just starting out you may be better off by running against the Mesa software renderer, which should provide full (though slow) OpenGL 2.1 support.
|
2,555,522 | 2,555,555 | Can operator= may be not a member? | Having construction in a form:
struct Node
{
Node():left_(nullptr), right_(nullptr)
{ }
int id_;
Node* left_;
Node* right_;
};
I would like to enable syntax:
Node parent;
Node child;
parent.right_ = child;
So in order to do so I need:
Node& operator=(Node* left, Node right);
but I'm getting msg that operator= has to be a member fnc; Is there any way to circumvent this restriction?
| An automatic conversion from value to pointer creates lots of possibilites to make your code hard to understand.
If you still want to do it you can provide a conversion operator on your Node class:
operator Node* () { return this; }
|
2,555,712 | 2,585,471 | C++ visitor pattern handling templated string types? | I'm trying to use the visitor pattern to serialize the contents of objects. However one snag I'm hitting is when I'm visiting strings. My strings are of a templated type, similar to STL's basic_string. So something like:
basic_string<char_type, memory_allocator, other_possible_stuff> \\ many variations possible!
Since I can have very many different templated string types, I can't go and add them to my visitor interface. It would be ridiculous. But I can't add templates to my VisitString method because C++ prevents using templates parameters in virtual methods.
So what are my options to work around this?
EDIT: I've added some basic code
class IVisitor
{
public:
virtual void VisitString(some_kind_of_string_type string) = 0; // this is what I want in theory
};
class MyObject
{
public:
typedef basic_string<char8, myAllocator, some_flag> MyStringType;
Accept(IVisitor* visitor)
{
visitor->VisitString(mString);
}
private:
MyStringType string;
};
class MyOtherObject
{
public:
typedef basic_string<char16, myOtherAllocator, some_other_flag> MyOtherStringType;
Accept(IVisitor* visitor)
{
visitor->VisitString(mString);
}
private:
MyOtherStringType string;
};
class Reader : public IVisitor
{
public:
virtual void VisitString(some_kind_of_string_type string)
{
// read some data, give it to the string
}
}
| In the end, I went with a slightly different approach. Instead of hoping to use a visitor with templated methods (which is, of course, impossible), I decided to pass a visitor-like class as a template parameter to my object's visit method. Totally simplified example:
class SomeKindOfVisitor // doesn't need to derive from a base class.
{
template <class StringClass>
void VisitString(StringClass& string) // I get to keep templated methods
}
class MyObject
{
typedef basic_string<char8, myAllocator, some_flag> MyStringType;
public:
template <class VisitorClass>
void Accept(VisitorClass& visitor)
{
vistior.VisitString<MyStringType>(mMyString);
}
private:
MyStringType mMyString;
}
With this method, I still get to use my templated strings while still being able to pass any kind of "visitor" to my objects.
|
2,555,849 | 2,555,963 | C++ universal data type | I have a universal data type, which is passed by value, but does not maintain the type information. We store only pointers and basic data types(like int, float etc) inside this. Now for the first time, we need to store std::string inside this. So we decided to convert it into std::string* and store it. Then comes the problem of destruction. We don't like to copy the std::string every time. So i am thinking of an approach like this. Say the data type looks like this
class Atom
{
public :
enum flags
{
IS_STRING,
IS_EMPTY,
HAS_GOT_COPIED,
MARKER
};
private:
void* m_value;
std::bitset<MARKER> m_flags;
public:
.....
Atom( Atom& atm )
{
atm.m_flags.set( HAS_GOT_COPIED );
.....
}
.....
~Atom()
{
if( m_flags.test(IS_STRING) && !m_flags.test(HAS_GOT_COPIED) )
{
std::string* val = static_cast<std::string*>(m_value);
delete val;
}
}
};
Is this a good approach to find out whether there is no more reference to std::string*? Any comments..
I have looked at boost::any and poco::DynamicAny. Since i need serialization, i can't use those.
Thanks,
Gokul.
| One major flaw with this approach is that you really need a reference count, not a single bit "has been copied" flag. The bit won't work if you copy the string multiple times. As written, you will get into trouble if you create a copy of an Atom and delete the copy before the original:
Atom a("hello world");
if (...) {
Atom b(a);
// b is destroyed, deleting the string
}
// Uh oh, the string's been deleted but a is still referencing it.
cout << (string) a;
I would not re-invent the wheel. If boost::any doesn't work out of the box you could still use it internally in place of your m_value field to store the data for your Atom class. That would take care of all the construction/copying/destruction details for you.
|
2,556,475 | 2,556,514 | Looking for a good C++/.net book | I have recently started to feel that I need to greatly improve my C++ skills especially in the realm of .net. I graduated from a good four year university with a degree in computer science about 9 months ago and I have since been doing full time contract work for a small software company in my local area. Most of my work has been done using Java/lisp/cocoa/XML and before that most of my programming in my senior year was in java/C#. I did a decent amount of C++ in my Sophomore year and in my free time before that but I feel that my general knowledge of C++/.net is very lacking for the opportunities that are now coming my way. Can anyone recommend a good book that could help me get up too speed? I feel I do not need a very basic introduction to C++ but something that covers the fundamentals of .net would be good for me. So basically what I need is a book or books that would be good for a .net novice and a C++ developer who is just beyond novice. Also, a book that would help bein an interview by giving me a conversional understanding of C++ would be great. Thanks a lot!.
| Depends what you actually want to learn:
If you want to learn about .Net, I would learn C# rather than C++.
If you want to learn C++, do not learn C++/CLI - learn the language described by the C++ Standard. For C++ books, see The Definitive C++ Book Guide and List. I personally would recommend Accelerated C++.
|
2,556,532 | 2,556,563 | How often will a programmer be asked to write a makefile file? | Is makefile an advanced problem or a general problem for a programmer?
For a C++ programmer, how often will he be asked to write a makefile file?
| Nobody ever writes a Makefile. They take an existing Makefile and modify it.
Just be thankful you don't have to deal with IMakefile. (For those of you who were lucky enough to never deal with this, or who have managed to forget, IMakefile was a file that was sort of a meta-Makefile for X Window System based projects which would be used to generate a Makefile that knew where you'd installed all your X Windows libraries and binaries. Needless to say, it sucked.)
|
2,556,945 | 2,556,995 | "this" pointer changes in GDB backtrace | I am examining a core dump, and noticed that in one frame the 'this' pointer is different than in the next frame (in the same thread). Not just a little different, it went from 0x8167428 to 0x200.
I am not that well-versed in using GDB, but this does not seem right to me. Is this problematic, and if so, what could be the cause?
| The this pointer can change between frames in a gdb trace if the function in the next frame is called on a different object (even if the objects are the same type), since this is for the specific instance. This is probably not your problem.
0x200 is not a valid value for this, and almost certainly indicates memory corruption of some type. The this pointer is sometimes stored on the stack and passed as an invisible first argument to a function. So if you have corrupted the stack (by going out of bounds writing to another variable) you could see the this pointer corrupted.
The value 0x200 itself is interesting. Because it is so close to 0, but not actually 0, it indicates that the instance you're looking at is probably part of another object or array, located 0x200 bytes from the beginning of that object/array, and that the object/array's address is actually NULL. Looking at your code you should be able to pretty easily figure out which object has gotten set to NULL, which is causing this to report 0x200.
|
2,556,984 | 2,559,674 | OpenSteer on Xbox 360? | I want to use OpenSteer for my game that I want to be compatible with the Xbox 360. I have heard that since it is a wrapper for a C++ library, it will work in XNA on a PC, but not on the Xbox. Is there no way to make it compatible?
UPDATE: The C++ version may not be, but what about OpenSteerDotNet?
| According to the OpenSteerDotNet homepage:
It should work fine with XNA Game
Studio Express, including the XBox 360
runtime.
|
2,557,007 | 2,557,158 | How do i generate all possible subsets of an binary string? | i have a problem, that i don't know how to solve it.
i have a binary string and i want to generate all possible binary substrings.
Example :
input : 10111
output: 10000, 10100,00111,00001,10110 ...
How can i do this , fast AND Smart ?
| Magic - assumes bitmask though:
subset( int x )
list = ()
for ( int i = x; i >= 0; i = ( ( i - 1 ) & x ) )
list.append( i )
return list
You can use the same logic, though it's a little bit more involved, with a binary string.
|
2,557,248 | 2,559,465 | Encapsulating user input of data for a class | For an assignment I've made a simple C++ program that uses a superclass (Student) and two subclasses (CourseStudent and ResearchStudent) to store a list of students and print out their details, with different details shown for the two different types of students (using overriding of the display() method from Student).
My question is about how the program collects input from the user of things like the student name, ID number, unit and fee information (for a course student) and research information (for research students):
My implementation has the prompting for user input and the collecting of that input handled within the classes themselves. The reasoning behind this was that each class knows what kind of input it needs, so it makes sense to me to have it know how to ask for it (given an ostream through which to ask and an istream to collect the input from).
My lecturer says that the prompting and input should all be handled in the main program, which seems to me somewhat messier, and would make it trickier to extend the program to handle different types of students.
I am considering, as a compromise, to make a helper class that handles the prompting and collection of user input for each type of Student, which could then be called on by the main program. The advantage of this would be that the student classes don't have as much in them (so they're cleaner), but also they can be bundled with the helper classes if the input functionality is required. This also means more classes of Student could be added without having to make major changes to the main program, as long as helper classes are provided for these new classes. Also the helper class could be swapped for an alternative language version without having to make any changes to the class itself.
What are the major advantages and disadvantages of the three different options for user input (fully encapsulated, helper class or in the main program)?
| As mentioned by scv, it is normally better to decouple presentation (view) from internal structure (model).
Here you have a typical case:
the Student class, root of a model hierarchy
the Displayer class, root of another independent hierarchy
The issue with the display is that it varies according to two elements, which calls for a system of double dispatch (using virtual).
This is traditionally solved using the Visitor Pattern.
Let's check the base classes first:
// student.h
class Displayer;
class Student
{
public:
virtual ~Student();
virtual void display(Displayer& d) const = 0; // display should not modify the model
};
// displayer.h
class Student;
class CourseStudent;
class ResearchStudent;
class Displayer
{
public:
virtual ~Displayer();
virtual void display(const Student& s) = 0; // default method for students
// not strictly necessary
virtual void display(const CourseStudent& s) = 0;
virtual void display(const ResearchStudent& s) = 0;
};
And now, let's implement some:
// courseStudent.h
#include "student.h"
class CourseStudent: public Student
{
public:
virtual void display(Displayer& d) const;
};
// courseStudent.cpp
#include "courseStudent.h"
#include "displayer.h"
// *this has static type CourseStudent
// so Displayer::display(const CourseStudent&) is invoked
void CourseStudent::display(Displayer& d) const
{
d.display(*this);
}
// consoleDisplayer.h
#include "displayer.h"
class ConsoleDisplayer: public Displayer
{
public:
virtual void display(const Student& s) = 0; // default method for students
// not strictly necessary
virtual void display(const CourseStudent& s) = 0;
virtual void display(const ResearchStudent& s) = 0;
};
// consoleDisplayer.cpp
#include "consoleDisplayer.h"
#include "student.h"
#include "courseStudent.h"
#include "researchStudent.h"
void ConsoleDisplayer::display(const Student& s) { }
void ConsoleDisplayer::display(const CourseStudent& s) { }
void ConsoleDisplayer::display(const ResearchStudent& s) { }
As you can see, the hard part is that if I wish to add a new derived class of Student, then I need to add a new virtual method in Displayer and override it in every derived class of Displayer... but otherwise it works great.
The advantage is that the logic of display is now decoupled from the model, thus we can add new display logic without ever touching our model.
|
2,557,375 | 2,557,777 | What is the correct Qt idiom for exposing signals/slots of contained widgets? | Suppose I have a MyWidget which contains a MySubWidget, e.g. a custom widget that contains a text field or something. I want other classes to be able to connect to signals and slots exposed by the contained MySubWidget instance. Is the conventional way to do this:
Expose a pointer to the MySubWidget instance through a subWidget() method in MyWidget
Duplicate the signals and slots of MySubWidget in the MyWidget class and write "forwarding" code
Something else?
Choice 1 seems like the least code, but it also sort of breaks encapsulation, since now other classes know what the contained widgets of MyWidget are and might become dependent on their functionality.
Choice 2 seems like it keeps encapsulation, but it's a lot of seemingly redundant and potentially convoluted code that kind of messes up the elegance of the whole signals and slots system.
What is normally done in this situation?
| If you look at Qt's own code they prefer option 2.
For example, look at QTabWidget and QTabBar. They share a number of signals and slots, yet QTabWidget hides the fact that it uses a QTabBar (well, sorta... QTabWidget::tabBar() obviously breaks this even though it's protected).
Although this will result in more code, I think it's worth it for the encapsulation.
Don't forget that you can connect signals to signals like so:
connect(mySubWidget, SIGNAL(internalSignal(int)), this, SIGNAL(externalSignal(int)));
Which will make MyWidget emit externalSignal(int) when MySubWidget emits internalSignal(int). This helps with the signal side of things at least. I don't know of any easy way to do the same for slots, unfortunately.
|
2,557,438 | 2,557,463 | Need to skip newline char (\n) from input file | I am reading in a file into an array. It is reading each char, the problem arises in that it also reads a newline in the text file.
This is a sudoku board, here is my code for reading in the char:
bool loadBoard(Square board[BOARD_SIZE][BOARD_SIZE])
{
ifstream ins;
if(openFile(ins)){
char c;
while(!ins.eof()){
for (int index1 = 0; index1 < BOARD_SIZE; index1++)
for (int index2 = 0; index2 < BOARD_SIZE; index2++){
c=ins.get();
if(isdigit(c)){
board[index1][index2].number=(int)(c-'0');
board[index1][index2].permanent=true;
}
}
}
return true;
}
return false;
}
like i said, it reads the file, displays on screen, just not in correct order when it encounters the \n
| Well in your file format you can simply not save newlines, or you can add a ins.get() the for loop.
You could also wrap your c=ins.get() in a function something like getNextChar() which will skip over any newlines.
I think you want something like this:
for (int index1 = 0; index1 < BOARD_SIZE; index1++)
{
for (int index2 = 0; index2 < BOARD_SIZE; index2++){
//I will leave the implementation of getNextDigit() to you
//You would return 0 from that function if you have an end of file
//You would skip over any whitespace and non digit char.
c=getNextDigit();
if(c == 0)
return false;
board[index1][index2].number=(int)(c-'0');
board[index1][index2].permanent=true;
}
}
return true;
|
2,557,551 | 2,562,302 | How get list of local network computers? | I am trying to get a list of local network computers. I tried to use NetServerEnum and WNetOpenEnum API, but both API return error code 6118 (ERROR_NO_BROWSER_SERVERS_FOUND). Active Directory in the local network is not used.
Most odd Windows Explorer shows all local computers without any problems.
Are there other ways to get a list of computers in the LAN?
| I found solution using interface IShellItem with CSIDL_NETWORK. I get all network PC.
C++: use method IShellFolder::EnumObjects
C#: you can use Gong Solutions Shell Library
using System.Collections;
using System.Collections.Generic;
using GongSolutions.Shell;
using GongSolutions.Shell.Interop;
public sealed class ShellNetworkComputers : IEnumerable<string>
{
public IEnumerator<string> GetEnumerator()
{
ShellItem folder = new ShellItem((Environment.SpecialFolder)CSIDL.NETWORK);
IEnumerator<ShellItem> e = folder.GetEnumerator(SHCONTF.FOLDERS);
while (e.MoveNext())
{
Debug.Print(e.Current.ParsingName);
yield return e.Current.ParsingName;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
|
2,557,562 | 8,095,478 | Using Apple autorelease pools without Objective-C | I am developing an application that needs to work on Linux, Windows and Mac OS X. To that purpose, I am using C++ with Qt.
For many reasons, on Mac OS X, I need to use CoreFoundation functions (such as CFBundleCopyBundleURL) that creates core objects that need to be released with CFRelease. But doing so generate a lots of these warnings:
*** __NSAutoreleaseNoPool(): Object 0x224f7e0 of class NSURL autoreleased with no pool in place - just leaking
All the code I've seen concerning these autorelease pools is written in Objective-C. Does anybody know how to create/use autorelease pools in C or C++?
| id is a C declaration. You can simply add scope based autorelease pools to your cpp program like so:
autorelease_pool.hpp
class t_autorelease_pool {
public:
t_autorelease_pool();
~t_autorelease_pool();
private:
id d_pool; // << you may opt to preprocess this out on other platforms.
private:
t_autorelease_pool(const t_autorelease_pool&);
t_autorelease_pool& operator=(const t_autorelease_pool&);
};
autorelease_pool.mm
t_autorelease_pool::t_autorelease_pool() : d_pool([NSAutoreleasePool new]) {}
t_autorelease_pool::~t_autorelease_pool() { [this->d_pool drain]; }
In a cpp program:
void UpdateUI() {
t_autorelease_pool pool;
// your/their autoreleasing code here
}
An alternative (which can be very easy to use incorrectly) is to use the ObjC runtime directly - which would look like the following C program:
#include <objc/runtime.h>
#include <objc/message.h>
...
id pool = objc_msgSend(objc_getClass("NSAutoreleasePool"), sel_getUid("new"));
/* do stuff */
objc_msgSend(pool, sel_getUid("drain"));
|
2,557,565 | 2,558,120 | HttpAddUrl permissions | I'm trying to run a custom WinHTTP based web-server on Windows Server 2008 machine.
I pass "http://*:22222/" to HttpAddUrl
When I start my executable as Administrator or LocalSystem everything works fine. However if I try to run it as NetworkService to minimize security risks (since there are no legitimate reasons for the app to use admin rights) function fails with "Access Denied" error code.
I wasn't aware of NetworkService having any restrictions on which ports and interfaces it can listen on.
Is there a way to configure permissions in such a way so that I actually can run the app under NetworkService account and connect to it from other internet hosts?
| You must be an administrator to add URLs to the http.sys URL mappings. Network Service does is not a member of the admin group, but the admnistrator's group and the System account are members.
IIS gets around this by having one process, inetinfo.exe, that runs as SYSTEM and sets up the URL mappings for worker processes (w3wp.exe) that run as Network Service.
Hope that clarifies tings.
|
2,557,598 | 2,557,662 | How can I make a fixed hex editor? | So. Let's say I were to make a hex editor to edit... oh... let's say a .DLL file. How can I edit a .DLL file's hex by using C# or C++? And for the "fixed part", I want to make it so that I can browse from the program for a specific .DLL, have some pre-coded buttons on the programmed file, and when the button is pressed, it will automatically execute the requested action, meaning the button has been pre-coded to know what to look for in the .DLL and what to change it to. Can anyone help me get started on this?
Also, preferably C#. Thank you!
| The basics are very simple.
A DLL, or any file, is a stream of bytes.
Basic file operations allow you to read and write arbitrary portions of a file. The term of art is basically "Random Access Files Operations".
In C, the fundamental operations are read(), write(), and lseek().
read allows you to read a stream of bytes in to a buffer, write allows you to write a buffers of bytes to a file, lseek allows you to position anywhere you want in the file.
Example:
int fd = open("test.dat", O_RDWR);
off_t offset = lseek(fd, 200, SEEK_SET);
if (off_t == -1) {
printf("Boom!\n");
exit(1);
}
char buf[1024];
ssize_t bytes_read = read(fd, buf, 1024);
offset = lseek(fd, 100, SEEK_SET);
ssize_t bytes_written = write(fd, buf, 1024);
flush(fd);
close(fd);
This reads 1024 bytes from a file, starting at the 200th byte of the file, then writes it back to the file at 100 bytes.
Once you can change random bytes in a file, it's a matter of choosing what bytes to change, how to change them, and doing the appropriate reads/lseeks/writes to make the changes.
Note, those are the most primitive I/O operations, there are likely much better ones you can use depending on your language etc. But they're all based on those primitives.
Interpreting the bytes of a file, displaying them, etc. That's an exercise for the reader. But those basic I/O capabilities give you the fundamentals of changing files.
|
2,557,638 | 2,557,641 | How to read character from console in c++? | I'm struggling with reading characters from console in c++.
Here is what I tried to do:
char x;
char y;
char z;
cout<<"Please enter your string: ";
string s;
getline(cin,s);
istringstream is(s);
is>> x >> y >> z;
The problem is if the user enter something like this "1 20 100":
x will get 1
y will get 2
z will get 0
What I want to get is x = 1; y = 20; z = 100;
Anybody has suggestions?
| You don't want to read characters but integers.
int x;
int y;
int z;
cout<<"Please enter your string: ";
string s;
getline(cin,s);
istringstream is(s);
is>> x >> y >> z;
|
2,557,664 | 2,557,803 | SDL doesn't detect Arrow Keys | I am working through the SDL tutorials over at http://lazyfoo.net/SDL_tutorials/index.php and I'm stuck on tutorial 8 where I'm working with key presses.
I'm using the following code:
//Our Main application loop
while(!quit){
if(SDL_PollEvent(&curEvents)){
if(curEvents.type == SDL_QUIT){
quit = true;
}
//If a key was pressed
if( curEvents.type == SDL_KEYDOWN )
{
//Set the proper message surface
switch( curEvents.key.keysym.sym )
{
case SDLK_UP:
message = upMessage;
break;
case SDLK_DOWN:
message = downMessage;
break;
case SDLK_LEFT:
message = leftMessage;
break;
case SDLK_RIGHT:
message = rightMessage; break;
default:
message = TTF_RenderText_Solid(font, "Unknown Key", textColor);
break;
}
}
}
if( message != NULL )
{
//Apply the background to the screen
applySurface( 0, 0, background, screen );
//Apply the message centered on the screen
applySurface( ( SCREEN_WIDTH - message->w ) / 2, ( SCREEN_HEIGHT - message->h ) / 2, message, screen );
//Null the surface pointer
message = NULL;
}
//Update the screen
if( SDL_Flip( screen ) == -1 )
{
return 1;
}
}
Where works fine, the default case is reached, for everything BUT pressing the arrow keys. I was wondering if someone could spot what I'm doing wrong.
| I discovered the error which was not in the code posted above. The error was that for the arrow keypress messages, I used RenderText before the font was opened. By the time the posted code block was reached, font had already been opened and is the reason why that message shows.
|
2,557,729 | 2,557,733 | Formatted input in c++ | hey, i'm a noob to c++ (and coding in general)
i'm looking for an easy way to take two doubles (at once) from the keyboard and store them in a struct i've created called "Point" and then ultimately store the Point into a vector of Points that's a member of a class (called "Polygon").
i know i could do it with a scanf but need to know how to do it with cin.
hope that makes sense.
thanks in advance
julz
| You can do:
double d1,d2;
cin>>d1>>d2;
or you can directly read it into your structure variable as:
point p;
cin>>p.x>>p.y;
assuming your structure is defined something like:
struct point {
double x;
double y;
}
|
2,557,832 | 2,730,380 | Can't start gdb.exe in Qt Creator | I have a project in Qt Creator that builds fine, but when I try to debug it I get this message:
Adapter start failed
Unable to start gdb 'C:\Qt\2010.02.1\mingw\bin\gdb.exe':
Process failed to start: The directory name is invalid
If I navigate to the debug build folder and directly run my compiled application, it will run fine, but obviously there's no debugging support. Additionally, gdb.exe is present at C:\Qt\2010.02.1\mingw\bin\gdb.exe, but Qt Creator can't seem to run it. How can I fix this problem?
| Tools->Options->Debugger->Gdb
From
Gdb location you can set the path to your preferred GBD.
|
2,557,846 | 2,557,859 | Checking if parsed date is within a date range | So I am using a scripting language with c++-like syntax, and I am trying to think of the best way to check if a date is within range. The problem I am running into is that if the current day is in a new month, the check is failing.
Here is what my code looks like:
if(iMonth >= iStartMonth && iMonth <= iEndMonth)
{
if(iDay >= iStartDay && iDay <= iEndDay)
{
if(iYear >= iStartYear && iYear <= iEndYear)
{
bEnabled = true;
return;
When I have something like this:
Start date: 3 27 2010
End Date: 4 15 2010
Current Date: 3 31 2010
The day check fails because if (iDay <= iEndDay) does not pass. The scripting language doesn't have a lot of time related functions, and I can't compare timestamps because I'm allowing users to put like "03:27:2010" and "04:15:2010" as start/end dates in a config file. I'm assuming I am just not thinking straight and missing an easy fix.
| You should really use boost::DateTime instead of attempting to rewrite the wheel (which when the wheel is a date/time framework it's not as trivial as it may seem). This only if the code you pasted is C++ and not your scripting language (it wasn't clear). Also may I suggest to use Lua instead? :)
Anyway the problem is here:
if(iDay >= iStartDay && iDay <= iEndDay)
You should only check this if iMonth == iStartMonth, and the same for the end month. Otherwise iDay = 31, iEndDay = 15 and 31 <= 15 will fail.
Also you should check for the year first, then the month, then the day.
|
2,557,866 | 2,557,879 | Reallocating memory via "new" in C++ | Quick question regarding memory management in C++
If I do the following operation:
pointer = new char [strlen(someinput_input)+1];
And then perform it again, with perhaps a different result being returned from strlen(someinput_input).
Does this result in memory being left allocated from the previous "new" statement? As in, is each new statement receiving another block of HEAP memory from the OS, or is it simply reallocating?
Assuming I do a final delete pointer[]; will that deallocate any and all memory that I ever allocated via new to that pointer?
| Every call to new must be matched with a corresponding call to delete.
As an aside, you should probably consider using std::string or even std::vector<char> (depending on the exact situation), rather than trying to allocate char arrays yourself. Then you don't ever need to worry.
|
2,557,950 | 2,557,961 | Why protected superclass member cannot be accessed in a subclass function when passed as an argument? | I get a compile error, which I'm slightly confused about. This is on VS2003.
error C2248: 'A::y' : cannot access protected member declared in class 'A'
class A
{
public:
A() : x(0), y(0) {}
protected:
int x;
int y;
};
class B : public A
{
public:
B() : A(), z(0) {}
B(const A& item) : A(), z(1) { x = item.y;}
private:
int z;
};
The problem is with x = item.y;
The access is specified as protected. Why doesn't the constructor of class B have access to A::y?
| It's because of this:
class base_class
{
protected:
virtual void foo() { std::cout << "base::foo()" << std::endl; }
};
class A : public base_class
{
protected:
virtual void foo() { std::cout << "A::foo()" << std::endl; }
};
class B : public base_class
{
protected:
virtual void foo() { std::cout << "B::foo()" << std::endl; }
public:
void bar(base_class *b) { b->foo(); }
};
If that were legal, you could do this:
A a;
B b;
b.bar(&a);
And you'd be calling a protected member of A from B, which isn't allowed.
|
2,558,153 | 2,558,161 | What is the underlying data structure of a STL set in C++? | I would like to know how a set is implemented in C++. If I were to implement my own set container without using the STL provided container, what would be the best way to go about this task?
I understand STL sets are based on the abstract data structure of a binary search tree. So what is the underlying data structure? An array?
Also, how does insert() work for a set? How does the set check whether an element already exists in it?
I read on wikipedia that another way to implement a set is with a hash table. How would this work?
| You could implement a binary search tree by first defining a Node struct:
struct Node
{
void *nodeData;
Node *leftChild;
Node *rightChild;
}
Then, you could define a root of the tree with another Node *rootNode;
The Wikipedia entry on Binary Search Tree has a pretty good example of how to implement an insert method, so I would also recommend checking that out.
In terms of duplicates, they are generally not allowed in sets, so you could either just discard that input, throw an exception, etc, depending on your specification.
|
2,558,334 | 2,558,353 | a class function with if(this==NULL) test got compiled? | I saw this code snippet during our lab and it actually compiles in MSVC2008 and G++.
void LinkList< class T >::Insert(T n)
{
if (this == NULL)
// some code here
}
As far as I know the this must not be null since you cannot call a class functions in c++ if it wasn't instantiated. Is this a valid code? if so what's the reason behind and where it can be useful?
|
since you cannot call a class functions in c++ if it wasn't instantiated
The thing is, you can, but it leads to undefined behavior.
Such a check should probably be an assert, though such code isn't guaranteed to actually work by the standard. (If this is null, you're already in undefined behavior land.)
The reason it's "useful" is to detect using an object after it's been deleted, or if it was never created:
template <typename T> // I hate this function
void safe_delete(T*& pPtr)
{
delete pPtr;
pPtr = 0;
}
T* p = new T;
safe_delete(p);
p->foo(); // this is null, and we've entered undefined behavior
Within foo, you could assert, "hey, we messed up :/".
In my opinion such use is indicative of bad design. You shouldn't have a pointer lying around that might possibly get invoked again. The last thing you do with a pointer is delete it; if it's still around after that, change your code so it's not.
|
2,558,610 | 2,558,618 | C question: no warning? | main()
{
printf("Hello World.");
}
Why does no warning is produced in gcc compiler even though we declare main() with return type 'int'
| Because you're not using the -Wall flag. When you do, you should get:
foo.c:1: warning: return type defaults to ‘int’
foo.c: In function ‘main’:
foo.c:1: warning: implicit declaration of function ‘printf’
foo.c:1: warning: incompatible implicit declaration of built-in function ‘printf’
foo.c:1: warning: control reaches end of non-void function
|
2,558,613 | 2,559,017 | display multiple errors via bool flag c++ | Been a long night, but stuck on this and now am getting "segmentation fault" in my compiler..
Basically I'm trying to display all the errors (the cout) needed. If there is more than one error, I am to display all of them.
bool validMove(const Square board[BOARD_SIZE][BOARD_SIZE],
int x, int y, int value)
{
int index;
bool moveError = true;
const int row_conflict(0), column_conflict(1), grid_conflict(2);
int v_subgrid=x/3;
int h_subgrid=y/3;
getCoords(x,y);
for(index=0;index<9;index++)
if(board[x][index].number==value){
cout<<"That value is in conflict in this row\n";
moveError=false;
}
for(index=0;index<9;index++)
if(board[index][y].number==value){
cout<<"That value is in conflict in this column\n";
moveError=false;
}
for(int i=v_subgrid*3;i<(v_subgrid*3 +3);i++){
for(int j=h_subgrid*3;j<(h_subgrid*3+3);j++){
if(board[i][j].number==value){
cout<<"That value is in conflict in this subgrid\n";
moveError=false;
}
}
}
return true;
}
| check your indices. As you are using a fixed sized array, it might be an off-by-one error
|
2,558,819 | 2,558,828 | regarding C++ stl container swap function | I recently learned that all stl containers have swap function:
i.e.
c1.swap(c2);
will lead to object underlying c1 being assigned to c2 and vice versa.
I asked my professor if same is true in case of c1 and c2 being references.
he said same mechanism is followed.
I wonder how it happens since c++ references cannot be reseted.
| References are aliases. If you have two references, calling swap will swap what they are referring to, not the references themselves.
C& r1 = c1; // r1 references c1
C& r2 = c2; // r2 references c2
r1.swap(r2); // same as c1.swap(c2)
And it's not the variables that get swapped, it's what make them logically independent that gets swapped. If a container only consists of a pointer, if you swap that pointer with the pointer of another container, you've effectively swapped the containers. The variables themselves remain.
Concrete example:
typedef std::vector<int> vec;
vec c1;
vec c2;
// fill em up
c1.swap(c2);
/*
A vector, internally, has a pointer to a chunk of memory (and some other stuff).
swap() is going to swap the internal pointer (and other stuff) with the other
container. They are logically swapped.
*/
vec& r1 = c1; // r1 is an alias for c1
vec& r2 = c2; // r2 is an alias for c2
r1.swap(r2); // same as c1.swap(c2). they are now unswapped
|
2,559,026 | 2,559,060 | C++ error message output format | If I want to trigger an error in my interpreter I call this function:
Error( ErrorType type, ErrorSeverity severity, const char* msg, int line );
However, with that I can only output
Name error: Undefined variable in line 1
instead of
Name error: Undefined variable 'someVariableName' in line 1
I'm working entirely with strings (except for the error messages as they all are constant at the moment), so sprintf won't work.
What is the best way to create an efficient error function that can output a constant message combined with a string that describes which object, e.g.: a non-existing variable, triggered the error?
| This is C++, so you can overload your function with an extra parameter to provide the variable name. I would then use a std::stringstream to format the message. There is no need to worry about "efficiency" when reporting errors, as they should be rare and don't affect an application's overall performance.
|
2,559,193 | 2,559,241 | is there a way to condense a vector (C++)? | I have a sparsely populated vector that I populated via hashing, so elements are scattered randomly in the vector. Now what I want to do is iterate over every element in that vector. What I had in mind was essentially condensing the vector to fit the number of elements present, removing any empty spaces. Is there a way I can do this?
| Either you save the additionally needed information during insertion of the elements (e.g. links to the previous / next element compared to a linked list) or you make one pass over all the elements and remove the unnecessary ones.
The first solution costs you some space (approx. 8 bytes / entry), the second costs you one pass over all elements. Depending on the scenario, one or both possibilities might not be useful.
|
2,559,204 | 2,559,329 | Problems with making a simple Unix shell | I am trying to create a simple shell in Unix. I read a lot and found that everybody uses the strtok function a lot. But I want to do it without any special functions. So I wrote the code but I can't seem to get it to work. What am I doing wrong here?
void process(char**);
int arg_count;
char **splitcommand(char* input)
{
char temp[81][81] ,*cmdptr[40];
int k,done=0,no=0,arg_count=0;
for(int i=0 ; input[i] != '\0' ; i++)
{
k=0;
while(1)
{
if(input[i] == ' ')
{
arg_count++;
break;
}
if(input[i] == '\0')
{
arg_count++;
done = 1;
break;
}
temp[arg_count][k++] = input[i++];
}
temp[arg_count][k++] = '\0';
if(done == 1)
{
break;
}
}
for(int i=0 ; i<arg_count ; i++)
{
cmdptr[i] = temp[i];
cout<<endl;
}
cout<<endl;
}
void process(char* cmd[])
{
int pid = fork();
if (pid < 0)
{
cout << "Fork Failed" << endl;
exit(-1);
}
else if (pid == 0)
{
cout<<endl<<"in pid";
execvp(cmd[0], cmd);
}
else
{
wait(NULL);
cout << "Job's Done" << endl;
}
}
int main()
{
cout<<"Welcome to shell !!!!!!!!!!!"<<endl;
char input[81];
cin.getline(input,81);
splitcommand(input);
}
| The problem is with the
arg_count++;
inside the if(input[i] == ' ') and if(input[i] == '\0')
when you are parsing the command line and you find a space or you reach the end of the command line you are increment arg_count before you put a \0 at the end of the command you were reading.
So change it to:
if(input[i] == ' ')
{
// arg_count++; REMOVE THIS.
break;
}
if(input[i] == '\0')
{
// arg_count++; REMOVE THIS.
done = 1;
break;
}
temp[arg_count][k++] = input[i++];
}
temp[arg_count][k++] = '\0'; // add null-char at the end.
arg_count++; // increment should happen here.
More bugs:
You are not returning anything from
splitcommand
You cannot just return cmdptr
because they point to local char
arrays(temp) which will not persist
after the function returns. So you'll
have to make sure that the array
temp persists even after function
call by allocating it dynamically or
making it global.
Arguments to execvp look good to
me. Others please take a look.
|
2,559,246 | 2,559,292 | boost::lambda expression doesn't compile | I tried to write a function that calculates a hamming distance between two codewords using the boost lambda library. I have the following code:
#include <iostream>
#include <numeric>
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/if.hpp>
#include <boost/bind.hpp>
#include <boost/array.hpp>
template<typename Container>
int hammingDistance(Container & a, Container & b) {
return std::inner_product(
a.begin(),
a.end(),
b.begin(),
(_1 + _2),
boost::lambda::if_then_else_return(_1 != _2, 1, 0)
);
}
int main() {
boost::array<int, 3> a = {1, 0, 1}, b = {0, 1, 1};
std::cout << hammingDistance(a, b) << std::endl;
}
And the error I am getting is:
HammingDistance.cpp: In function ‘int hammingDistance(Container&, Container&)’:
HammingDistance.cpp:15: error: no match for ‘operator+’ in ‘<unnamed>::_1 + <unnamed>::_2’
HammingDistance.cpp:17: error: no match for ‘operator!=’ in ‘<unnamed>::_1 != <unnamed>::_2’
/usr/include/c++/4.3/boost/function/function_base.hpp:757: note: candidates are: bool boost::operator!=(boost::detail::function::useless_clear_type*, const boost::function_base&)
/usr/include/c++/4.3/boost/function/function_base.hpp:745: note: bool boost::operator!=(const boost::function_base&, boost::detail::function::useless_clear_type*)
This is the first time I am playing with boost lambda. Please tell me where I am going wrong. Thanks.
EDIT:
Thanks a lot guys! Here is the working code (just for reference):
#include <iostream>
#include <numeric>
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/if.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/array.hpp>
using boost::lambda::_1;
using boost::lambda::_2;
template<typename Container>
int hammingDistance(Container & a, Container & b) {
return std::inner_product(
a.begin(),
a.end(),
b.begin(),
0,
(_1 + _2),
boost::lambda::if_then_else_return(_1 != _2, 1, 0)
);
}
int main() {
boost::array<int, 3> a = {1, 0, 1}, b = {0, 1, 1};
std::cout << hammingDistance(a, b) << std::endl;
}
| First problem: when using boost/lambda, include <boost/lambda/bind.hpp> instead of <boost/bind.hpp>
Second problem: you need a using namespace boost::lambda after the #includes
still doesn't compile though
Edit:
Third problem - you need 6 arguments for std::inner_product, you're missing an initialization argument. probably add 0 as the forth argument.
|
2,559,351 | 2,559,391 | Using Qt signals/slots instead of a worker thread | I am using Qt and wish to write a class that will perform some network-type operations, similar to FTP/HTTP. The class needs to connect to lots of machines, one after the other but I need the applications UI to stay (relatively) responsive during this process, so the user can cancel the operation, exit the application, etc. My first thought was to use a separate thread for network stuff but the built-in Qt FTP/HTTP (and other) classes apparently avoid using threads and instead rely on signals and slots. So, I'd like to do something similar and was hoping I could do something like this:
class Foo : public QObject
{
Q_OBJECT
public:
void start();
signals:
void next();
private slots:
void nextJob();
};
void Foo::start()
{
...
connect(this, SIGNAL(next()), this, SLOT(nextJob()));
emit next();
}
void Foo::nextJob()
{
// Process next 'chunk'
if (workLeftToDo)
{
emit next();
}
}
void Bar::StartOperation()
{
Foo* foo = new Foo;
foo->start();
}
However, this doesn't work and UI freezes until all operations have completed. I was hoping that emitting signals wouldn't actually call the slots immediately but would somehow be queued up by Qt, allowing the main UI to still operate.
So what do I need to do in order to make this work? How does Qt achieve this with the multitude of built-in classes that appear to perform lengthy tasks on a single thread?
| If you're doing a length job in the UI thread the UI is going to freeze. One way to avoid this is to call once in a while QCoreApplication::processEvents().
You should be VERY careful however to understand what this does before you decide to do it. Calling this function means that a GUI event can fire in the middle of your operation. If this event can in turn create some more jobs you can end up starting a new job while in the middle of the old job.
I wouldn't be so quick dismissing the worker thread approach. It has the advantage of completely separating the work from the GUI so you are certain that something that began is going to finish.
You should also consider that Windows especially sometimes introduces non trivial delays to GUI loops. If the host is somewhat busy or in a memory thrashing state you'll find that GUI events may take up to several long seconds to finish and return control to your processing.
|
2,559,357 | 2,559,462 | SHLoadImageFile(L"\\Program Files\\TrainingApp\\background.png"); whats that L in the argument for? | ive been working on c++ on linux for the past 2 years,and switched to windows c++ programming recently.
can anyone tell me what that L is there in the argument of the function:
SHLoadImageFile(L"\\Program Files\\TrainingApp\\background.png");
and on viewing certain sample code in MSVS C++ i came across hundereds of typedefs like..
LPARAM// typedef LONG_PTR LPARAM... here LONG_PTR is again typedef as __w64 long
WPARAM// typedef UINT_PTR WPARAM...
so there is a lot of chained typedefs.. I never saw this much of typedef chaining on c++ programming on linux using gcc..
what i want to say is that it just creates more confusion in this way for windows application programming.. while ive seen application programming on linux using frameworks like Qt.. there such things are rarely used.. so is there specific purpose in typedefining again and again on MSVSC++?? for eg.. there are typdefs like
typedef int BOOL;
whats the use of this when normal bool is available already..?? there are hundred other cases ive come across where just to decide what data type to use becomes so difficult.. it becomes difficult to understand a pre written code in this fashion too..
Thanks.
| The L in the argument is standard way of telling the compiler that the following string literal is unicode not single-byte characters. It is equivalent to the postfix L to indicate that a long integer constant.
The windows typedefs do seem confusing but once you get your head around the naming scheme they start to make sense.
You have to remember that this API originated in the early 90's. Thus the typedefs are/were required to handle pointers on different architectures as well as 32/64 bit types and are also required to compile for non-intel windows machines.
The BOOL->int mapping is required asthe interface is C compatible (not c++) and thus can't use the built in bool type.
|
2,559,676 | 2,559,718 | how to open many files simultaneously for reading in c | I'm trying to port some of my c++ code into c. I have the following construct
class reader{
private:
FILE *fp;
alot_of_data data;//updated by read_until() method
public:
reader(const char*filename)
read_until(some conditional dependent on the contents of the file, and the arg supplied)
}
Im then instantiating hundreds of these object and iterate over them using several 'read_until()' for each file until allfiles is at eof.
I'm failing to see any clever way to do this in c, the only solution I can come up with is making an array of FILE pointers, and do the same with all the private member data from my class.
But this seems very messy, can I implement the functionality of my class as a function pointer, or anything better, I think I'm missing a fundamental design pattern?
The files are way to big to have all in memory, so reading everything from every file is not feasible
Thanks
| You create an abstract data type:
typedef struct {
FILE *fp;
alot_of_data data;//updated by read_until() method
} reader;
void init_reader(reader* that, const char* filename);
void read_until(reader* that, some conditional dependent on the contents of the file, and the arg supplied)
Then you can create and use objects of this type just as with objects of the class, except that, instead of obj.func(), you write func(&obj):
reader r;
init_reader(&r, "blah.txt");
read_until(&r, /* ... */);
|
2,559,681 | 2,562,393 | Qt -how to know whether content in child widgets has been changed? | In QMainWindow I have 2 QSplitters. In that splitters I have QTextEdit, QLineEdits, QTableWinget, Ragio buttons and so on... I want to know if somthing has been chaged after pressing File->New menu button. Is there any general method for doing this?
Somwhere I have read that it is recomended to use isWindowModified() function of QMainWindow, but seems it doesn't work.
| The isWindowModified() could be useful here since according to http://doc.trolltech.com/4.6/qwidget.html#windowModified-prop it propagates up to the parent.
However, I think you would need to set this yourself. For example, if you clicked the new button which leads to some text being inserted into a QTextEdit, you still need to call QTextEdit's setWindowModified() function - which will then propagate up to your QMainWindow - and you can just check QMainWindow afterwards. (However, you wouldn't know which children were modified)
|
2,559,724 | 2,577,363 | Unable to load libsctp.so for non root user | I have a Linux application that uses the libsctp.so library. When I run it as root, it runs fine.
But when I run it as an ordinary user, it gives the following error:
error while loading shared libraries: libsctp.so.1: cannot open shared object file: No such file or directory
But, when I do ldd as ordinary user, it is able to see the library:
[sanjeev@devtest6 src]$ ldd myapp
...
...
libsctp.so.1 => /usr/local/lib/libsctp.so.1 (0x00d17000)
[sanjeev@devtest6 src]$ ls -lL /usr/local/lib/libsctp.so.1
-rwxrwxrwx 1 root root 27430 2009-06-29 11:26 /usr/local/lib/libsctp.so.1
[sanjeev@devtest6 src]$
What could be wrong? How is the ldd is able to find libsctp.so, but when actually running the app, it is not able to find the same library?
EDIT: Just observed that this problem appears only if setuid bit is set for myapp.
| Fixed the problem. I added a new file in /etc/ld.so.conf.d with the followng name:
libsctp.so.1.conf
The contents of libsctp.so.1.conf is as follows:
/usr/local/lib/
And then ran
/sbin/ldconfig
, after which my app ran successfully.
Explanation: Since the setuid bit was set, the program is executed as root, for whom LD_LIBRARY_PATH is not available. Hence it is not able to find libsctp.so. I was not aware of this because when I login as root, .bashrc gets executed and LD_LIBRARY_PATH becomes available.
|
2,559,750 | 2,559,882 | private destructor for singleton class | Is it compulsory to have a private destructor for a singleton class.
| This might not be what you are looking for.. But for reference, I use it as follows:
// .h
class Foo {
public:
static Foo* getInstance();
static void destroy();
private:
Foo();
~Foo();
static Foo* myInstance;
};
// .cpp
Foo* Foo::myInstance = NULL;
Foo* Foo::getInstance(){
if (!myInstance){
myInstance = new Foo();
}
return myInstance;
}
void Foo::destroy(){
delete myInstance;
myInstance = NULL;
}
Then at the end of my program, I call destroy on the object. As Péter points out the system will reclaim the memory when your program ends, so there is no real reason. The reason I use a destroy is when Ogre complained that I hadn't released all the memory I allocated. After that I just use it as "good manner", since I like cleaning up after myself.
|
2,559,854 | 2,559,880 | Accessing subclass members from a baseclass pointer C++ | I have an array of custom class Student objects. CourseStudent and ResearchStudent both inherit from Student, and all the instances of Student are one or the other of these.
I have a function to go through the array, determine the subtype of each Student, then call subtype-specific member functions on them.
The problem is, because these functions are not overloaded, they are not found in Student, so the compiler kicks up a fuss.
If I have a pointer to Student, is there a way to get a pointer to the subtype of that Student? Would I need to make some sort of fake cast here to get around the compile-time error?
| You need a dynamic cast:
Student * s = new ...; // Create student of some sort.
if ( ResearchStudent * r = dynamic_cast<ReasearchStudent*>( s ) ) {
r->ResFunc();
}
else if ( CourseStudent * c = dynamic_cast<CourseStudent*>( s ) ) {
c->CourseFunc();
}
else {
throw "Unknown student type.";
}
Note that this uses type information maintained by the compiler, provided the class has at least one virtual function - if all else fails, make the destructor virtual (as it must be in this case anyway). You should always prefer this approach to maintaining your own type information.
|
2,559,896 | 2,559,902 | How are arrays passed? | Are arrays passed by default by ref or value?
Thanks.
| They are passed as pointers. This means that all information about the array size is lost. You would be much better advised to use std::vectors, which can be passed by value or by reference, as you choose, and which therefore retain all their information.
Here's an example of passing an array to a function. Note we have to specify the number of elements specifically, as sizeof(p) would give the size of the pointer.
int add( int * p, int n ) {
int total = 0;
for ( int i = 0; i < n; i++ ) {
total += p[i];
}
return total;
}
int main() {
int a[] = { 1, 7, 42 };
int n = add( a, 3 );
}
|
2,559,967 | 2,563,898 | Determining line orientation using vertex shaders | I want to be able to calculate the direction of a line to eye coordinates and store this value for every pixel on the line using a vertex and fragment shader. My idea was to calculate the direction gradient using atan2(Gy/Gx) after a modelview tranformation for each pair of vertices then quantize this value as a color intensity to pass to a fragment shader. How can I get access to the positions of pairs of vertices to achieve this or is there another method I should use?
Thanks
|
How can I get access to the positions
of pairs of vertices?
You can't do that simply if you are just using a vertex and a fragment shader. Easy way is to use geometry shaders. Inside this shader stage you can have access to the pair of vertices that compose your line segment. Then it's straightforward to determine the line orientation and pass it to the fragment shader.
If geometry shader is not an option (because of your target audience) you could duplicate your geometry (storing in each vertex the actual vertex plus the next vertex) and then do the computation in the vertex shader.
|
2,559,995 | 2,560,293 | Create an instance of an exported C++ class from Delphi | I followed an excellent article by Rudy Velthuis about using C++ classes in DLL's. Everything was golden, except that I need access to some classes that do not have corresponding factories in the C++ DLL. How can I construct an instance of a class in the DLL? The classes in question are defined as
class __declspec(dllexport) exampleClass
{
public:
void foo();
};
Now without a factory, I have no clear way of instantiating the class, but I know it can be done, as I have seen SWIG scripts (.i files) that make these classes available to Python. If Python&SWIG can do it, then I presume/hope there is some way to make it happen in Delphi too.
Now I don't know much about SWIG, but it seems like it generates some sort of map for C++ mangled names? Is that anywhere near right? Looking at the exports from the DLL, I suppose I could access functions & constructor/destructor by index or the mangled name directly, but that would be nasty; and would it even work? Even if I can call the constructor, how can I do the equivalent of "new CClass();" in Delphi?
| The correct way to do it is to write a wrapper DLL that exposes a factory for the class you need.
I am not sure hiw SWIG works, but anything that relies on reverse-engineering the name mangling seems a dubious approach.
Besides a C++ object should be created only in C++ code. You ought to leave the object creation semantics to the C++ runtime.
There is a reason why COM exists. Precisely to make this cross language object metaphor work neatly.
I've written scores of COM objects that are called from Delphi, python and C#
|
2,560,114 | 2,560,232 | Benchmarks used to test a C and C++ allocator? | Please kindly advise on benchmarks used to test a C and C++ allocator? Benchmarks satisfying any of the following aspects are considered:
Speed
Fragmentation
Concurrency
Thanks!
| If you ask about a general allocator for a C/C++ program then I have found this paper Hoard: A Scalable Memory Allocator for Multithreaded Applications which considers this question. This is a quote from this document
There is as yet no standard suite of
benchmarks for evaluating
multithreaded allocators. We know of
no benchmarks that specifically stress
multithreaded performance of server
applications like web servers 1 and
database managers. We chose benchmarks
described in other papers and
otherwise published (the Larson
benchmark from Larson and Krishnan
[22] and the shbench benchmark from
MicroQuill, Inc. [26]), two
multithreaded applications which
include benchmarks (BEMengine [7] and
barnes-hut [1, 2]), and wrote some
microbenchmarks of our own to stress
different aspects of memory allocation
performance (threadtest, active-false,
passive-false).
This paper is sort of old. However I have seen recently an allocator for HP-UX (MallocNextGen) and HP also can't ensure that it is good for all possible applications. It says:
The new allocator is generally
expected to improve the performance of
applications. However, there may be
some applications for which
performance may degrade. Hence users
are advised to benchmark their
applications with the default memory
allocator in libc and with the
allocator in libmallocng before using
the new allocator in a production
environment.
As for speed and concurrency my own experience is that you have to measure performance of your own program in order to compare two different allocators. If we talk about Linux you can use LD_PRELOAD in order to load different allocators.
|
2,560,172 | 2,560,307 | openssl crypto library - base64 conversion | I'm using openssl BIO objects to convert a binary string into a base64 string. The code is as follows:
void ToBase64(std::string & s_in) {
BIO * b_s = BIO_new( BIO_s_mem() );
BIO * b64_f = BIO_new( BIO_f_base64() );
b_s = BIO_push( b64_f , b_s);
std::cout << "IN::" << s_in.length();
BIO_write(b_s, s_in.c_str(), s_in.length());
char * pp;
int sz = BIO_get_mem_data(b_s, &pp);
std::cout << "OUT::" << sz << endl;
s_in.assign(pp,sz);
//std::cout << sz << " " << std::string(pp,sz) << std::endl;
BIO_free (b64_f); // TODO ret error potential
BIO_free (b_s); //
}
The in length is either 64 or 72. However the output is always 65, which is incorrect it should be much larger than that. The documentation isn't the best in the world, AFAIK the bio_s_mem object is supposed to grow dynamically. What am I doing wrong ?
I am probably better off finding a self contained C++ class that doesn't offer streaming support, and supports base64 conversions. Streaming support is not suited to my application. However I just wanted to stick to openSSL since I am allready depending on some of the crypto routines. Anyhow I'll make such a decision after profiling.
| You have two problems:
You need to call BIO_get_mem_data() on the mem bio - but you've lost the reference to it (you overwrite it with the return value from BIO_push, which is equal to b64_f).
You should call BIO_flush() on the base64 bio after you've written all your data to it.
|
2,560,214 | 2,560,236 | Returning an array of tm* structs from a function | Im trying to create an array of tm* structs, and then return them at the end of the function. This is what i have at the moment:
struct tm* BusinessLogicLayer::GetNoResponceTime()
{
struct tm* time_v[3];
struct tm* time_save;
int s = 3;
time_save = LastSavedTime();
time_v[0] = time_save;
sleep(5);
time_save = LastSavedTime();
time_v[1] = time_save;
sleep(5);
time_save = LastSavedTime();
time_v[2] = time_save;
return time_v;
}
I understand that given the code i have now it will not be possible to return the array, because it will be destroyed when the function ends. Can anyone help me with regards to how i would go about being able to access the array from the returned value after the function has ended?
Regards
Paul
| Either allocate the array on the heap, but you will need to remember to delete[] the array when you have finished using it.
tm* time_v = new tm[3];
Or as this is C++, a better option would be to use a vector
std::vector<tm> time_v(3);
The vector itself is allocated on the stack but it holds an array which is allocated on the heap. When you copy the vector (for instance returning it) the contents of the underlying array are also copied.
You could also simplify the function by not using the temp variable time_save
time_v[0] = *LastSavedTime();
sleep(5);
time_v[1] = *LastSavedTime();
sleep(5);
time_v[2] = *LastSavedTime();
The C style struct declarations are also not required in C++
struct tm* time_v[3];
//should be
tm* time_v[3];
|
2,560,651 | 2,560,668 | Compile batch file into an EXE file | I want to compile a batch file into an EXE file using C++. I can get through parsing the batch file and writing a new .cpp file. But I don't know how to compile the new .cpp file into an EXE file for the end user.
OK, here's the thing, I am creating an application in DevC++ that will read in a batch file. Then, one by one parsing it using:
system(getline(myfile,line));
After setting everything up, I save the newly created file as "main.cpp".
The problem is, I want to compile it into an EXE file, from my program, for the end user.
So basically, can I compile a C++ file from a C++ EXE?
| Yes, you can provided that the end user has a C++ compiler installed and you're emitting valid C++.
Depending on the compiler you're using, your C++ executable would have to spawn a process that runs
cl main.cpp
or a similar invocation of the compiler after finishing the translation.
If your user doesn't have a compiler installed, then you're pretty much out of luck - trying to build a C++ compiler yourself is a rather non-trivial exercise.
|
2,560,859 | 2,561,632 | Binding a pointer temporary to a reference | Please refer to the code below. In this code I am storing the const char* returned by test.c_str() into a reference. My question is - Will the data be correctly refering to the contents of test? I am thinking that the ptr returned by test.c_str() will be a temporary and if I bind it to a reference that reference will not be valid.
Is my thinking correct?
class RefPtrTest
{
std::string test;
StoringClass storingClass;
public:
RefPtrTest(): test("hello"), storingClass(test.c_str())
{
}
}
where StoringClass is
class StoringClass
{
const char*& data;
public:
StoringClass (const char*& input): data(input)
{
}
}
EDIT1:
Let's just not consider what std::string is doing. Suppose I am using my own class called mystring
class RefPtrTest
{
const mystring test;
StoringClass storingClass;
public:
RefPtrTest(): test("hello"), storingClass(test.getInternalPointer())
{
}
}
getInternalPointer directly returns the internal pointer. I want to verify this hypothesis, while storingClass(test.getInternalPointer()) ptr returned by test.getInternalPointer() will be a temporary and if I bind it to a reference that reference will not be valid. Is my thinking correct?
EDIT2:
That StoringClass is not under my control. Basically it's a template class where it stores reference to the type. I am using it for const char*. I am aware of all the design issues which you have raised. But I can't change that class, and I have to use it for const char *. there is no other way around it.
| If StoringClass needs a reference to a pointer, then you have to ensure that there is a pointer for it to refer to (and modify, since it's not a const reference), with a lifetime as long as that of the reference.:
#include <string>
#include <iostream>
template <typename T>
class StoringClass {
T& data;
public:
StoringClass (T& input): data(input) { }
void print() const { std::cout << data << "\n"; }
void set(T x) { data = x; }
};
class RefPtrTest {
const std::string test;
const char *ptr;
StoringClass<const char*> storingClass;
public:
RefPtrTest(): test("hello"), ptr(test.c_str()), storingClass(ptr) { }
void print() const { storingClass.print(); }
void set(const char* x) { storingClass.set(x); }
};
int main() {
RefPtrTest t;
t.print();
t.set("world");
t.print();
}
Output:
hello
world
IMO StoringClass is a bit weird. For instance, I could have marked the set functions const too, and it'd still work. But if you have to use it, you have to use it. If you can use a StoringClass<const char *const> instead, that might be better: it will ensure that you don't call any functions of StoringClass which modify the pointer. The way you asked the question suggests that you don't expect that to happen.
Edit:
If test wasn't const, though, RefPtrTest could have a function:
void set_another_way(const char *x) { test = x; set(test.c_str()); }
Which would modify the string and update the pointer to which storingClass refers. The function body is equivalent to test = x; ptr = test.c_str();. Assuming single-threaded code, that also addresses any concerns about the validity of the pointer value returned by test.c_str(), provided that set_another_way is the only means by which test is ever modified.
Frankly, StoringClass shouldn't be called StoringClass. It doesn't store anything ;-p
|
2,561,139 | 2,566,598 | A variation of priority queue | I need some kind of priority queue to store pairs <key, value>. Values are unique, but keys aren't. I will be performing the following operations (most common first):
random insertion;
retrieving (and removing) all elements with the least key.
random removal (by value);
I can't use std::priority_queue because it only supports removing the head.
For now, I'm using an unsorted std::list. Insertion is performed by just pushing new elements to the back (O(1)). Operation 2 sorts the list with list::sort (O(N*logN)), before performing the actual retrieval. Removal, however, is O(n), which is a bit expensive.
Any idea of a better data structure?
| Ok, so I've tested many options and ended up with something based on the idea of Matthieu M.. I'm currently using a std::map<key_type, std::list<value_type> >, where the value_type contains a std::list<value_type>::iterator to itself, which is useful for removal.
Removal must check if the vector is empty, which implies a map query and possibly a call to erase. Worst-case complexity is when keys are distinct, O(logN) for insertion, O(1) for retrieval and O(logN) for removal. I've got very good experimental results comparing to other alternatives on my test machine.
Using a std::vector is less efficient both in terms of theoretical complexity (O(N) worst-case for removal when keys are identical) and experimentation I've been doing.
|
2,561,145 | 2,561,182 | Difference between boost::ref and regular references | What is the difference between boost::ref(i) and & i ? What are the situations where we cannot use regular references and have to go for boost::ref instead? Please include examples if possible.
| From the Boost.Ref Documentation:
The purpose of
boost::reference_wrapper is to
contain a reference to an object of
type T. It is primarily used to "feed"
references to function templates
(algorithms) that take their parameter
by value.
NB: An important difference between boost::reference_wrapper and std::reference_wrapper (at least of Boost 1.52) is the ability of std::reference_wrapper to perfectly wrap function objects.
This enables code like this:
// functor that counts how often it was applied
struct counting_plus {
counting_plus() : applications(0) {}
int applications;
int operator()(const int& x, const int& y)
{ ++applications; return x + y; }
};
std::vector<int> x = {1, 2, 3}, y = {1, 2, 3}, result;
counting_plus f;
std::transform(begin(x), end(x), begin(y),
std::back_inserter(result), std::ref(f));
std::cout << "counting_plus has been applied " << f.applications
<< " times." << '\n';
|
2,561,240 | 2,563,080 | C++ MFC server app with sockets crashes and I cannot find the fault, help! | My program has one dialog and two sockets. Both sockets are derived from CAsyncSocket, one is for listening, other is for receiving data from client. My program crashes when client tries to connect to server application and server needs to initialize receiving socket.
This is my MFC dialog class.
class CFileTransferServerDlg : public CDialog
{
...
ListeningSocket ListenSock;
ReceivingSocket* RecvSock;
void OnAccept(); // called when ListenSock gets connection attempt
...
};
This is my derived socket class for receiving data that calls parent dialogs method when event is signaled.
class ReceivingSocket : public CAsyncSocket
{
...
CFileTransferServerDlg* m_pDlg; // for accessing parent dialogs controls
virtual void OnReceive(int nErrorCode);
...
}
ReceivingSocket::ReceivingSocket()
{
}
This is dialogs function that handles incoming connection attempt when listening socket gets event notification. This is where the crash happens.
void CFileTransferServerDlg::OnAccept()
{
RecvSock = new ReceivingSocket; /* CRASH */
}
OR
void CFileTransferServerDlg::OnAccept()
{
ReceivingSocket* tmpSock = new ReceivingSocket;
tmpSock->SetParentDlg(this);
CString message;
if( ListenSock.Accept(*tmpSock) ) /* CRASH */
{
message.LoadStringW(IDS_CLIENT_CONNECTED);
m_txtStatus.SetWindowTextW(message);
RecvSock = tmpSock;
}
}
My program crashes when I try to create a socket for receiving file sent from client application. OnAccept starts when Listening socket signals incoming connection attempt, but my application then crashes. What could be wrong?
Error in debug mode:
Unhandled exception at 0x009c30e1 in FileTransferServer.exe: 0xC0000005: Access violation reading location 0xccccce58.
UPDATE:
I edited code a little and I've found that inside sockcore.cpp where Accept is defined, program failes on this line of code:
ASSERT(rConnectedSocket.m_hSocket == INVALID_SOCKET);
I don't understand how that can happen. ReceivingSocket class is somehow not getting constructed right. I derive it from CAsyncSock, leave constructor empty, and no matter where I create it, on stack or on heap, it always crashes.
Here is complete project, both client and server, if anyone can take a look at it I would be really grateful. I apologize for the comments, they are in Croatian.
Visual Studio project
| I've looked into your code. The issue seems to be that you never call ListeningSocket::SetParentDlg(CFileTransferServerDlg* parent). Since you also do not initialize the m_pDlg pointer in the ListeningSocket constructor, it has random values and the program might crash here and there when you access this pointer. (I had also a crash but slightly at another location than you pointed out.)
I've changed it this way:
In ListeningSocket.h changed the constructor:
ListeningSocket(CFileTransferServerDlg* parent);
Also in ListeningSocket.cpp:
ListeningSocket::ListeningSocket(CFileTransferServerDlg* parent)
: m_pDlg(parent)
{
}
Constructor of CFileTransferServerDlg changed this way:
CFileTransferServerDlg::CFileTransferServerDlg(CWnd* pParent /*=NULL*/)
: CDialog(CFileTransferServerDlg::IDD, pParent),
ListenSock(this)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
Crash disappeared.
Other ways are possible of course.
Really nice little programs, by the way :) I'll delete them of course now since I can't probably afford the license fees :)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.