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 |
|---|---|---|---|---|
3,031,413 | 3,031,433 | Bitwise operators and converting an int to 2 bytes and back again | My background is php so entering the world of low-level stuff like char is bytes, which are bits, which is binary values, etc is taking some time to get the hang of.
What I am trying to do here is sent some values from an Ardunio board to openFrameWorks (both are c++).
What this script currently does (and works well for one sensor I might add) when asked for the data to be sent is:
int value_01 = analogRead(0); // which outputs between 0-1024
unsigned char val1;
unsigned char val2;
//some Complicated bitshift operation
val1 = value_01 &0xFF;
val2 = (value_01 >> 8) &0xFF;
//send both bytes
Serial.print(val1, BYTE);
Serial.print(val2, BYTE);
Apparently this is the most reliable way of getting the data across.
So now that it is send via serial port, the bytes are added to a char string and converted back by:
int num = ( (unsigned char)bytesReadString[1] << 8 | (unsigned char)bytesReadString[0] );
So to recap, im trying to get 4 sensors worth of data (which I am assuming will be 8 of those serialprints?) and to have int num_01 - num_04... at the end of it all.
Im assuming this (as with most things) might be quite easy for someone with experience in these concepts.
| Write a function to abstract sending the data (I've gotten rid of your temporary variables because they don't add much value):
void send16(int value)
{
//send both bytes
Serial.print(value & 0xFF, BYTE);
Serial.print((value >> 8) & 0xFF, BYTE);
}
Now you can easily send any data you want:
send16(analogRead(0));
send16(analogRead(1));
...
|
3,031,438 | 3,031,448 | error: typedef name may not be a nested-name-specifier | I am trying to do something along the lines of this answer, and struggling:
$ gcc --version
gcc (GCC) 4.2.4 (Ubuntu 4.2.4-1ubuntu4)
file.cpp:7: error: template argument 1 is invalid
file.cpp:7: error: typedef name may not be a nested-name-specifier
And the offending part of the file:
template <class R, class C, class T0=void, class T1=void, class T2=void>
struct MemberWrap;
template <class R, class C, class T0>
struct MemberWrap<R, C, T0>{
typedef R (C::*member_t)(T0);
typedef typename boost::add_reference<typename T0>::type> TC0; // <---- offending line
MemberWrap(member_t f)
: m_wrapped(f){
}
R operator()(C* p, TC0 p0){
GILRelease guard;
return (p->*(this->m_wrapped))(p0);
}
member_t m_wrapped;
};
| Drop typename from typename T0 in
typedef typename boost::add_reference<typename T0>::type> TC0;
and probably drop the second angle bracket as well. I.e.
typedef typename boost::add_reference<T0>::type TC0;
|
3,031,453 | 3,031,504 | Way Cross Compile C/C++ code to run on Windows, Linux, and Mac OS? | Is there a way to take my C++ code and cross compile it to run on Windows, Mac OS, and Linux? Is there a tool to do this, or does it have to be manually compiled on each OS via Terminal/Cygwin?
| You can cross compile with what is known as a cross-compiler. Mingw can be installed as such. I believe MacOS just uses g++ so you can probably make a cross compiler for it as well. Never done it myself. You can scour the web for directions. Here's the top link I got from google:
http://linux.bytesex.org/cross-compiler.html
|
3,031,489 | 3,031,495 | Call C methods from C++/Java/C# code? | Many of today's programming languages are based on C; like C++, C#, Java, Objective-C. So could I call a C method from C++ code? Or call C from Java or C#? Or is this goal out of reach and unreasonable? Please include a quick code sample for my and everyone else's understanding.
| C++,C#, Objective-C, and Java can all call C routines. Here are a few links that will give you an overview of the process needed to call C from each language you asked about.
Calling C from Java
Calling C
from C++
Calling C from C#
Calling C from Objective-C
|
3,031,491 | 3,031,552 | Read number from text file using C++ stream | I have a text file like below
2 1 2
5 10 13 11 12 14
2 0 1
2 99 2
200 2
1 5
5 1 2 3 4 5
1 0
0 0
I want to read file line by line, and read the umbers from each line. I know how to use the stream to read a fixed field line, but what about the non-fixed line?
Best Regards,
| Use a stringstream. In outline:
string line;
while( getline( cin, line ) ) { // read each line:
istringstream is( line );
int n;
while( is >> n ) { // read each number in line
// do something with each number:
}
}
|
3,031,605 | 3,031,696 | Statically initialize anonymous union in C++ | I am trying to statically initialize the following structure in Visual Studio 2010:
struct Data
{
int x;
union
{
const Data* data;
struct {int x; int y; };
};
};
The following is fails with error C2440: 'initializing' : cannot convert from 'Data *' to 'char'.
static Data d1;
static Data d = {1, &d1};
static Data d2 = {1, {1, 2}};
I have found references to some ways this can be initialized properly but none of them work in VS2010. Any ideas?
| Can you do it by defining overloaded constructors? Untested code ahead:
struct Data
{
int x;
union
{
const Data* data;
struct {int a; int b; } z;
} y;
Data()
{
x = 0;
y.data = 0;
y.z.a = 0;
y.z.b = 0;
}
Data(int x_, Data* data_)
{
x = x_;
y.data = data_;
}
Data(int x_, int a_, int b_)
{
x = x_;
y.z.a = a_;
y.z.b = b_;
}
};
static Data d1;
static Data d(1, &d1);
static Data d2(1, 1, 2);
|
3,031,610 | 3,031,611 | Simultaneous execution of both if and else blocks | In C or C++
if ( x )
statement1;
else
statement2;
For what value of x will both statements be executed?
I know we can execute if-else together like this:
if(1){
goto ELSE;
}
else{
ELSE:
}
Is there any way, like a value?
(Which I think is not possible. Asking because someone is arguing!)
|
for what value of x both statements will be executed?
There is no such value: either the value evaluates to true (something != 0), or it evaluates to false) (0). No other possible values exist.
I know we can execute if-else together like this: if(1){ goto ELSE; } else{ ELSE: }
That works but it isn’t depending of the value of the if condition at all.
|
3,031,649 | 3,031,700 | In c++ is there any Events/delegates/interfaces/notifications! anything? | Say i have these classes
ViewA and ViewB
In objective C using the delegate pattern I could do
@protocol ViewBDelegate{
- (void) doSomething();
}
then in ViewB interface:
id<ViewBDelegate> delegate;
then in ViewA implementation i set the delegate:
viewB.delegate = self;
and now I can call in doSomething from viewB onto any that unknown type delegate.
[delegate doSomething];
"C++ How to Program" has been the worse read an can't find simple examples that demonstrates basic design patterns.
What i'm looking for in C++ is:
events ActionScript and java
or delegates or NSNotifications in Objective C
anything that allows class A, Class B and Class C to know that ClassX
didSomething()!!!
thanks
| If I were you, I wouldn't use function pointers to accomplish this task. Leave this option to the gurus ;)
In Boost, there is a beautiful library called signals. It makes your life easier! This is an example of usage:
#include <iostream>
#include <boost/bind.hpp>
#include <boost/signal.hpp>
using namespace std;
using namespace boost;
struct A
{ void A_action() { cout << "A::A_action();" << endl; } };
struct B
{ void B_action() { cout << "B::B_action();" << endl; } };
struct C
{ void C_action() { cout << "C::C_action();" << endl; } };
struct X
{
// Put all the functions you want to notify!
signal<void()> list_of_actions;
void do_something()
{
std::cout << "Hello I am X!" << endl;
list_of_actions(); // send notifications to all functions in the list!
}
};
int main()
{
X x;
A a;
B b;
C c;
x.list_of_actions.connect(bind(&A::A_action, a));
x.list_of_actions.connect(bind(&B::B_action, b));
x.list_of_actions.connect(bind(&C::C_action, c));
x.do_something();
}
This will print:
Hello I am X!
A::A_action();
B::B_action();
C::C_action();
Here is how it works.
First, you declare the place that holds the delegates:
signal<void()> list_of_actions;
Then, you "connect" it to what ever group of functions/functors/callable things you want to call.
x.list_of_actions.connect(bind(&A::A_action, a));
x.list_of_actions.connect(bind(&B::B_action, b));
x.list_of_actions.connect(bind(&C::C_action, c));
Note, that I have used bind. So, that the type of functions in the list_of_actions is the same, but we can connect it to different type of classes. So:
bind(&A::A_action, a)
This thing, produces a callable thing, of type void () as we declared the type of list_of actions earlier. Of course, you specify the instance you want to apply this member function on in the second parameter..
If you are doing multi-threaded stuff, then use its sister signals2.
Hope that helps.
|
3,031,751 | 3,031,786 | Simple binary File I/O problem with cstdio(c++) | The c++ program below fails to read the file. I know using cstdio is not good practice but that what I am used to and it should work anyway.
$ ls -l l.uyvy
-rw-r--r-- 1 atilla atilla 614400 2010-04-24 18:11 l.uyvy
$ ./a.out l.uyvy
Read 0 bytes out of 614400, possibly wrong file
code:
#include<cstdio>
int main(int argc, char* argv[])
{
FILE *fp;
if(argc<2)
{
printf("usage: %s <input>\n",argv[0]);
return 1;
}
fp=fopen(argv[1],"rb");
if(!fp)
{
printf("erör, cannot open %s for reading\n",argv[1]);
return -1;
}
int bytes_read=fread(imgdata,1,2*IMAGE_SIZE,fp); //2bytes per pixel
fclose(fp);
if(bytes_read < 2*IMAGE_SIZE)
{
printf("Read %d bytes out of %d, possibly wrong file\n",
bytes_read, 2*IMAGE_SIZE);
return -1;
}
return 0;
}
| I resolved the issue by initializing the pointer. Interestingly, reading fails instead of giving a segfault when you try to read into an uninitialized pointer, that was confusing.
|
3,031,871 | 3,031,883 | determining if value is in range with 0=360 degree problem | I am making a piece of code for DirectX app. It's meaning is to not show faces that are not visible. Normaly it would be just using Z-buffer, but I'm making many moves and rotations of mesh, so I would like to not do them and save computing power. I will describe this on cube. You are looking from the front so you see just one face and you don't need to rotate the 5 that left. If you would have one side of cube from 100*100 meshes, it would be great to not have to turn around 50k meshes that you really don't need. So I have stored X,Y,Z rotation of camera(the Z rotation I'm not using), and also X,Y,Z rotation of faces. In this cube simplified I would see faces that makes this statement true:
cRot //camera rotation in degrees
oRot //face rotation in degrees
if(oRot.x > cRot.x-90 && oRot.x < cRot.x+90
&& oRot.y > cRot.y-90 && oRot.y < cRot.y+90)
But there comes a problem. If I will rotate arround, the camera can get to value 330 for exapmple. In this state, I would see front and right side of cube. Right side have rotation 270 so that's allright in IF statement. Problem is with 0 rotation of front face, which is also 360 degrees.
So my question is how to make this statement to work, because when I use modulo, it will be failing for that right side and in this way it won't work for 0=360.
| You mean to check if oRot differs from cRot at least by 90 degree?
//integral
if ((360 + cRot - oRot) % 360 >= 90) ...
//floating point
diff = abs(cRot - oRot);
if (diff >= 90 && diff <= 270) ...
|
3,031,923 | 3,031,946 | difference between erase and remove/remove_if algorithms? | What is really the difference between the algorithms remove and remove_if and the member function erase?
Does both of them result in a call to the removed objects destructor?
| No, std::remove_if will move the elements that don't match the predicate to the end of list and will return an iterator to the new "end". Erase will effectively drop the element (call the dtor) from the container.
The difference is perfectly illustrated by the examples here and here.
|
3,031,971 | 3,033,321 | I'm new to C++. Please Help me with the Linked List (What functions to add)? | DEAR All;
Hi, I'm just beginner to C++;
Please help me to understand:
What functions should be in the Linked list class ?
I think there should be overloaded operators << and >>;
Please help me to improve the code (style, errors, etc,)
Thanks for advance. Igal.
Edit:
This is only first stage, the next one will be (hopefully) with templates.
Please review the small code for the integer List (enclosed MyNODE.h and ListDriver1.cpp);
MyNODE.h
// This is my first attempt to write linked list. Igal Spector, June 2010.
#include <iostream.h>
#include <assert.h>
//Forward Declaration of the classes:
class ListNode;
class TheLinkedlist;
// Definition of the node (WITH IMPLEMENTATION !!!, without test drive):
class ListNode{
friend class TheLinkedlist;
public:
// constructor:
ListNode(const int& value, ListNode *next= 0);
// note: no destructor, as this handled by TheLinkedList class.
// accessor: return data in the node.
// int Show() const {return theData;}
private:
int theData; //the Data
ListNode* theNext; //points to the next node in the list.
};
//Implementations:
//constructor:
inline ListNode::ListNode(const int &value,ListNode *next)
:theData(value),theNext(next){}
//end of ListNode class, now for the LL class:
class TheLinkedlist
{
public:
//constructors:
TheLinkedlist();
virtual ~TheLinkedlist();
// Accessors:
void InsertAtFront(const &);
void AppendAtBack(const &);
// void InOrderInsert(const &);
bool IsEmpty()const;//predicate function
void Print() const;
private:
ListNode * Head; //pointer to first node
ListNode * Tail; //pointer to last node.
};
//Implementation:
//Default constructor
inline TheLinkedlist::TheLinkedlist():Head(0),Tail(0) {}
//Destructor
inline TheLinkedlist::~TheLinkedlist(){
if(!IsEmpty()){ //list is not empty
cout<<"\n\tDestroying Nodes"<<endl;
ListNode *currentPointer=Head, *tempPtr;
while(currentPointer != 0){ //Delete remaining Nodes.
tempPtr=currentPointer;
cout<<"The node: "<<tempPtr->theData <<" is Destroyed."<<endl<<endl;
currentPointer=currentPointer->theNext;
delete tempPtr;
}
Head=Tail = 0; //don't forget this, as it may be checked one day.
}
}
//Insert the Node to the beginning of the list:
void TheLinkedlist::InsertAtFront(const int& value){
ListNode *newPtr = new ListNode(value,Head);
assert(newPtr!=0);
if(IsEmpty()) //list is empty
Head = Tail = newPtr;
else { //list is NOT empty
newPtr->theNext = Head;
Head = newPtr;
}
}
//Insert the Node to the beginning of the list:
void TheLinkedlist::AppendAtBack(const int& value){
ListNode *newPtr = new ListNode(value, NULL);
assert(newPtr!=0);
if(IsEmpty()) //list is empty
Head = Tail = newPtr;
else { //list is NOT empty
Tail->theNext = newPtr;
Tail = newPtr;
}
}
//is the list empty?
inline bool TheLinkedlist::IsEmpty() const
{ return (Head == 0); }
// Display the contents of the list
void TheLinkedlist::Print()const{
if ( IsEmpty() ){
cout << "\n\t The list is empty!!"<<endl;
return;
}
ListNode *tempPTR = Head;
cout<<"\n\t The List is: ";
while ( tempPTR != 0 ){
cout<< tempPTR->theData <<" ";
tempPTR = tempPTR->theNext;
}
cout<<endl<<endl;
}
//////////////////////////////////////
The test Driver:
//Driver test for integer Linked List.
#include <iostream.h>
#include "MyNODE.h"
// main Driver
int main(){
cout<< "\n\t This is the test for integer LinkedList."<<endl;
const int arraySize=11,
ARRAY[arraySize]={44,77,88,99,11,2,22,204,50,58,12};
cout << "\n\tThe array is: "; //print the numbers.
for (int i=0;i<arraySize; i++)
cout<<ARRAY[i]<<", ";
TheLinkedlist list; //declare the list
for(int index=0;index<arraySize;index++)
list.AppendAtBack( ARRAY[index] );//create the list
cout<<endl<<endl;
list.Print(); //print the list
return 0; //end of the program.
}
|
0 should be NULL
inline only in the case that you don't care that your code will be public, usually implementation puts in separate file Mylist.cpp file.
Why your destructor virtual, do you have inheritance ?
You can just define struct node instead separate class its better define your list for practice like in stl. http://www.sgi.com/tech/stl/List.html http://www.cplusplus.com/reference/stl/list/
In C++ common to use vector vs linked list in Java
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html
|
3,032,076 | 3,032,123 | How to convert from string to a number, and vice-versa in C++? | DEAR All
I'm new to the C++, so maybe someone can say what the proper way to write a function that gets a string char (represents number) and converts it to the integer number.
For example : input : Sixty five, output: 65.
Maybe it should use by cin.getline() ?
Well, vice-versa is little bit simlper...
Thanks for advance.
Igal
| Here's an illustration of a key part of a solution:
const char* digits[] = {"zero", "one", "two", ...};
const char* tens[] = {"ten", "twenty", "thirty", ...};
// Loop to compare input text tokens against above
...
The idea is to simplify conversion from text to digits by using the array index for the corresponding text token as the means for converting to the digit, adjusting for any array index start differences.
Use either the strcmp C function or the == C++ string comparison operator depending on what datatypes you have for the input text tokens.
|
3,032,348 | 3,480,833 | Boost Test dynamically or statically linked? | We use Boost statically linked with our app but now I want to use Boost Test with an external test runner and that requires the tests themselves to link dynamically with Boost.Test through the use of the required BOOST_TEST_DYN_LINK define.
Is this going to be a problem or is the way Boost Test links completely unrelated to the way the other Boost libraries are linked?
| I believe Boost Test does not depend on any other compiled libraries, so dynamically linking it while statically linking the other Boost libraries should not be a problem. Our linking rules don't show any dependency of Boost Test on anything other than headers, nor do the rules in the boost.jam file (though the latter is out of date).
|
3,032,386 | 3,039,119 | glGenBuffers not defined? | I'm using windows and I notice that a lot of functions are grayed out because I guess #ifdef GL_GLEXT_PROTOTYPES is not defined. One of these is the VBO extension. Should I just define GL_GLEXT_PROTOTYPES? Otherwise how else can I use VBOs since im using OpenGL32.dll (I want my application to have no dll dependencies not included in Windows by default.) Thanks
| I recommend that you use GLEW to get rid of that problem.
It's a long story, but resuming, Windows' OpenGL library only exposes OpenGL 1.1 entry points, so all functions beyond that version are loaded with wglGetProcAddress. GLEW solves this problem by doing that.
http://glew.sourceforge.net/
Just link to GLEW and GLU/GLUT (if you use them).
|
3,032,421 | 3,032,456 | On Memory Allocation and C++ | And I quote from MSDN http://msdn.microsoft.com/en-us/library/aa366533(VS.85).aspx:
The malloc function has the
disadvantage of being run-time
dependent. The new operator has the
disadvantage of being compiler
dependent and language dependent.
Now the questions folks:
a) What do we mean that malloc is run-time dependent? What kind of dynamic memory allocation functions can be independent of run-time? This statement sounds real strange.
b) new is language dependent? Of course it should be right? Are HeapAlloc, LocalAlloc etc language independent?
c) From a pure performance perspective are the MSVC provided routines preferable?
Arpan
| a) In this case I think they're eliding "run-time library" to "run-time". In other words it depends on the implementation in your C library.
b) Indeed new is C++ specific. HeapAlloc, etc are technically usable in C and C++.
c) They can't be used to create C++ objects because they won't call constructors so the point is pretty moot. In C++ you should use new and delete.
|
3,032,502 | 3,032,515 | OpenGL 3 equivalent of GLUTesselator? | I was wondering, since things like display lists are now deprecated, I'm thinking the GLU polygon tesselator is probably also deprecated. What is the new and correct way of creating concave or complex polygons and complying with the new GL 3 standard? Thanks.
| GLUT is not and was never a part of OpenGL.
If you need this functionality then use another library that provides it and can use VBOs or write it yourself.
Starting with OpenGL 4 there is also hardware tesselation support.
|
3,032,726 | 3,032,868 | rand() generating the same number – even with srand(time(NULL)) in my main! | So, I'm trying to create a random vector (think geometry, not an expandable array), and every time I call my random vector function I get the same x value, though y and z are different.
int main () {
srand ( (unsigned)time(NULL));
Vector<double> a;
a.randvec();
cout << a << endl;
return 0;
}
using the function
//random Vector
template <class T>
void Vector<T>::randvec()
{
const int min=-10, max=10;
int randx, randy, randz;
const int bucket_size = RAND_MAX/(max-min);
do randx = (rand()/bucket_size)+min;
while (randx <= min && randx >= max);
x = randx;
do randy = (rand()/bucket_size)+min;
while (randy <= min && randy >= max);
y = randy;
do randz = (rand()/bucket_size)+min;
while (randz <= min && randz >= max);
z = randz;
}
For some reason, randx will consistently return 8, whereas the other numbers seem to be following the (pseudo) randomness perfectly. However, if I put the call to define, say, randy before randx, randy will always return 8.
Why is my first random number always 8? Am I seeding incorrectly?
| The issue is that the random number generator is being seeded with a values that are very close together - each run of the program only changes the return value of time() by a small amount - maybe 1 second, maybe even none! The rather poor standard random number generator then uses these similar seed values to generate apparently identical initial random numbers. Basically, you need a better initial seed generator than time() and a better random number generator than rand().
The actual looping algorithm used is I think lifted from Accelerated C++ and is intended to produce a better spread of numbers over the required range than say using the mod operator would. But it can't compensate for always being (effectively) given the same seed.
|
3,032,859 | 3,032,869 | Performance Cost of a Memcopy in C/C++ | So whenever I write code I always think about the performance implications. I've often wondered, what is the "cost" of using a memcopy relative to other functions in terms of performance?
For example, I may be writing a sequence of numbers to a static buffer and concentrate on a frame within the buffer, in order to keep the frame once I get to the end of the buffer, I might memcopy all of it to the beginning OR I can implement an algorithm to amortize the computation.
| memcpy is generally optimized to maximize memory bandwidth of large copies. Of course, it's not as fast as avoiding a copy completely, and for short copies of fixed size, direct assignment may be faster since memcpy has extra code to deal with odd lengths.
But when you need to copy a block of memory, it's hard to beat memcpy. It's highly portable and most compilers go to great lengths to make it fast, whether that's using SIMD instructions or maybe inlining.
|
3,032,965 | 3,034,865 | C++ program infile won't open in xcode? | alt text http://img638.imageshack.us/img638/5731/screenshot20100613at121.png
Why does the c++ program produce the error shown? I'm especially confused since outfile opens without error yet infile displays the error? Both are defined in xcode exactly the same!! I've altering the "path type" setting without success. The open on infile always fails! Any suggestions would be very much appreciated!!
For those who responded thanks but as you can see but infile and outfile exist and are in the same location:
alt text http://img709.imageshack.us/img709/9316/screenshot20100613at123.png
|
In Xcode, expand the "Targets" node and find your target. Given what I've seen, it'll be the only one there.
Next, right-click on your project and add a new "Copy Files" build phase. When the dialog box comes up, make sure you set the Destination to "Products Directory".
The new build phase will appear beneath your target with whatever name you gave it. Drag your in_file and out_file there.
Compile and run.
|
3,033,058 | 3,033,226 | a question in NS c++ programming | I added a new patch to my NS and I've seen these two errors. Does anyone know what I can do?
error: specialization of 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = _AlgorithmTime]' in different namespace
from definition of 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = _AlgorithmTime]'
and the errors are from this code
typedef struct _AlgorithmTime {
// Round.
int round;
// Fase.
int fase;
// Valore massimo di fase.
int last_fase;
public:
_AlgorithmTime() {
round = 0;
fase = 0;
last_fase = 0;
}
// Costruttore.
_AlgorithmTime(int r, int f, int l) {
round = r;
fase = f;
last_fase = l;
}
// Costruttore.
_AlgorithmTime(const _AlgorithmTime & t) {
round = t.round;
fase = t.fase;
last_fase = t.last_fase;
}
// Operatore di uguaglianza.
bool operator== (struct _AlgorithmTime & t) {
return ((t.fase == fase) && (t.round == round));
}
// Operatore minore.
bool operator < (struct _AlgorithmTime & t) {
if (round < t.round)
return true;
if (round > t.round)
return false;
if (fase < t.fase)
return true;
return false;
}
// Operatore maggiore.
bool operator > (struct _AlgorithmTime & t) {
if (round > t.round)
return true;
if (round < t.round)
return false;
if (fase > t.fase)
return true;
return false;
}
void operator++ () {
if (fase == last_fase) {
round++;
fase = 0;
return;
}
fase++;
}
void operator-- () {
if (fase == 0) {
round--;
fase = last_fase;
return;
}
fase--;
}
}AlgorithmTime;
template<>
bool
std::less<AlgorithmTime>::operator()(const AlgorithmTime & t1, const AlgorithmTime & t2)const
{
if (t1.round < t2.round)
return true;
if (t1.round > t2.round)
return false;
if (t1.fase < t2.fase)
return true;
return false;
}
Thanks
| You could just specify the namespace of the template you are trying to specialize:
namespace std
{
template<>
bool
std::less<AlgorithmTime>::operator()(const AlgorithmTime & t1, const AlgorithmTime & t2)const
{
...
}
}
But as Michael Burr points out, there's no reason to specialize std::less, if all you intend to do is duplicate the code of AlgorithmTime::<.
|
3,033,329 | 3,033,379 | Why are Python Programs often slower than the Equivalent Program Written in C or C++? | Why does Python seem slower, on average, than C/C++? I learned Python as my first programming language, but I've only just started with C and already I feel I can see a clear difference.
| Python is a higher level language than C, which means it abstracts the details of the computer from you - memory management, pointers, etc, and allows you to write programs in a way which is closer to how humans think.
It is true that C code usually runs 10 to 100 times faster than Python code if you measure only the execution time. However if you also include the development time Python often beats C. For many projects the development time is far more critical than the run time performance. Longer development time converts directly into extra costs, fewer features and slower time to market.
Internally the reason that Python code executes more slowly is because code is interpreted at runtime instead of being compiled to native code at compile time.
Other interpreted languages such as Java bytecode and .NET bytecode run faster than Python because the standard distributions include a JIT compiler that compiles bytecode to native code at runtime. The reason why CPython doesn't have a JIT compiler already is because the dynamic nature of Python makes it difficult to write one. There is work in progress to write a faster Python runtime so you should expect the performance gap to be reduced in the future, but it will probably be a while before the standard Python distribution includes a powerful JIT compiler.
|
3,033,364 | 3,063,940 | Visual C++ Compiler Option To Dump Class Hierarchy | Is there any compiler option in MS Visual C++ equivalent to GCC's -fdump-class-hierarchy? i.e. showing the virtual function table layout.
| try
cl.exe /d1reportAllClassLayout test.cpp
The output is something like:
class request_handlerAttribute size(8):
+---
0 | name
4 | sdl
+---
class perfmonAttribute size(8):
+---
0 | name
4 | register
| (size=3)
+---
Found doing:
+ findstr /i class c1xx.dll > c1xx.txt
+ and then manually inspecting c1xx.txt
Hope it can help,
Benedetto
PS: This obviously is an undocumented and unsupported switch.
Look also here for a similar switch.
|
3,033,405 | 3,033,412 | Is there any difference these two pieces of code? | #include<stdio.h>
class A {public: int a; };
class B: public A {private: int a;};
int main(){
B b;
printf("%d", b.a);
return 0;
}
#include<stdio.h>
class A {public: int a; };
class B: private A {};
int main(){
B b;
printf("%d", b.a);
return 0;
}
I ask because I get different errors:
error: 'int B::a' is private
error: 'int A::a' is inaccessible
Apart from what the errors might reveal, is there any difference at all in the behaviour of these two pieces of code?
| They are different. In the first instance, you are creating two instances of the variable 'a'. One in the base class, one in the child class. In both examples you can't get access to the variable.
If you have:
A *pA = new B();
pA->a; // This will refer to A::a, which is allowed as it was defined public.
B *pB = new B();
pB->a; // This will refer to B::a, which you can't get access to.
If you want to hide access to the 'a' variable, I suggest the second example, using private inheritance. Be aware that private inheritance will also make any functions defined in the base class private.
|
3,033,419 | 3,033,566 | Re-ordering C++ template functions | In C++, I have a certain template function that, on a given condition, calls a template function in another class. The trouble is that the other class requires the full definition of the first class to be implemented, as it creates the second class and stores them and manages them in similar fashions.
The trouble is that naturally, they fall as one class, and thus have some tight interop, except that I need them to be two classes for threading reasons. A sort of, master for all threads, one child per thread, system.
Any advice on how this can be implemented?
Edit@comment:
I have a problem that looks a little like this:
class Master {
public:
Child* CreateChild() {
return new Child();
}
template<typename T> T* GetSomething(int arg) {
return NULL;
}
};
class Child {
Master* master;
template<typename T> T* GetSomething(int arg) {
if (arg) return master->GetSomething<T>(arg);
else return NULL;
}
};
Those obviously aren't the actual implementations, but similar enough to demonstrate. PIMPL would only help if these were non-template functions, but since they are, then the IMPL needs to be right here.
The Master class manages all the Children (why did I pick Master and Child instead of Parent/Child or Master/Slave?), their memory, lifetimes, etc, and a few other system-wide necessities. But the Child class provides the majority of access and in some cases must fall back to the Master class.
Also, there's no way in hell that I'm going to move to dynamic bindings. The rest of my system already thoroughly abuses dynamic bindings to the absolute max, and I simply can't afford the performance of using them again in this fashion. The Child function in question is called very, very, very often.
| For your example, the fact that the classes have a template function makes no real difference; just have a forward reference to the Child class and put the definition of the CreateChild function after the declaration of the Child class:
class Child;
class Master {
public:
Child* CreateChild() ;
template<typename T> T* GetSomething(int arg) {
return NULL;
}
};
class Child {
public:
Master* master;
template<typename T> T* GetSomething(int arg) {
if (arg) return master->GetSomething<T>(arg);
else return NULL;
}
};
Child* Master::CreateChild() {
return new Child();
}
|
3,033,483 | 3,033,490 | How can I construct or return the underlying deque from a stack? | I want to be able to convert a std::stack<> to a std::deque<>. Is there a straightforward conversion?
| You'll need to do it manually:
while (!stk.empty())
{
deq.push_back(stk.top());
stk.pop();
}
|
3,033,583 | 3,033,630 | Refactor C++ code to use a scripting language? | Background:
I have been working on a platformer game written in C++ for a few months. The game is currently written entirely in C++, though I am intrigued by the possibility of using Lua for enemy AI and possibly some other logic. However, the project was designed without Lua in mind, and I have already written working C++ code for much of the AI. I am hoping Lua can improve the extensibility of the game, but don't know if it would make sense to convert existing C++ code into Lua.
The question:
When, if ever, is it appropriate to take fully functional C++ code and refactor it into a scripting language like Lua?
The question is intentionally a bit vague, so feel free give answers that are not relevant to the given background.
| Scripting languages are useful for things that might change frequently or be extended, and can afford the trade from speed.
It wouldn't make sense to use a scripting language in your core libraries, because those are relatively static (all they do is process stuff over and over) and need to be quick. But for things like AI, it's a perfect idea. You may tweak the AI without recompiling, and allow future changes quite nicely. Once you ship, you can pre-compile the scripting language and call it good.
It's also best for extensibility. Provide a Lua interface to your game and anybody can write plugins using a simple language, without the need for compiling. The more fleshed out your Lua interface, the more expressive and powerful those plugins can be.
If you've already got everything working, unless you intend on trying to improve it or allow extensions I don't really see a reason to strip it out; you're done. It would be something to keep in mind for your next game engine.
That said, if you're not completely done and this is a hobby/practice kind of thing, I would recommend you do. It will be your introduction into adding scripting capabilities to the game engine. When you get to making larger and more complex engines you won't need to worry about something new.
|
3,033,593 | 3,033,628 | C++ inheritance: scoping and visibility of members | Can you explain why this is not allowed,
#include <stdio.h>
class B {
private:
int a;
public:
int a;
};
int main() {
return 0;
}
while this is?
#include <stdio.h>
class A {
public:
int a;
};
class B : public A{
private:
int a;
};
int main() {
return 0;
}
In both the cases, we have one public and one private variable named a in class B.
edited now!
|
In both the cases, we have one public
and one private variable named a in
class B.
No, thats not true.
In the first case, you can't have two identifiers with the same name in the same scope. While in the second case, B::a hides A::a, and to access A::a you have to fully qualify the name:
b.a = 10; // Error. You can't access a private member.
b.A::a = 10; // OK.
|
3,033,807 | 3,033,815 | What is the difference between these two uses of const in C++? |
Possible Duplicate:
what is the difference between const int*, const int * const, int const *
What is the difference between
A const * pa2 = pa1;
and
A * const pa2 = pa1;
(I have some class A for example).
| Read the type from right to left:
A const * pa2 = pa1;
pa2 is a pointer to a read-only A (the object may not be changed through the pointer)
A * const pa2 = pa1;
pa2 is a read-only pointer to A (the pointer may not be changed)
This does not mean that A cannot change (or is actually constant) const is misleading, understand it always as read-only. Other aliased pointers might modify A.
|
3,033,885 | 3,033,889 | difference between containers | I'm a little bit confused, can somebody please explain the main difference between those types of containers:
map
list
set
array
I'm asking about C++.
| http://cplusplus.com/reference/stl/
Maps are a kind of associative containers that stores elements formed by the combination of a key value and a mapped value.
Lists are a kind of sequence containers. As such, their elements are ordered following a linear sequence.
Sets are a kind of associative containers that stores unique elements, and in which the elements themselves are the keys.
Arrays are also a kind of sequence containers, just much lower level than list. Their size is fixed, they don't manage memory dynamically and aren't generic. They are inherited from C.
|
3,033,969 | 3,034,407 | Fastest python/C++ multimedia library | I'm using pyglet for my OpenGL based game but is it the fastest library out there which has a python wrapper? I could create a C++ extension and use any C++ multimedia library. Are there any C++ libraries that are worth investing time into or is it not worth the extra work?
Thank you.
| Pygame is a python wrapper for the SDL library, which is widely used in game developing and provides OpenGL, sound and input management. To my knowledge at least SDL is quite fast, and the wrapper just encapsulates the binary functionality for python usage. Depending on your usage you can accomplish high speed.
|
3,034,043 | 3,034,097 | Include Obj-C++ header from C++ source file | Consider the followng situation:
MacFont.h
struct MacFont : Font
{
// ...
NSFont* font;
};
MacFont will be implemented in MacFont.mm
FontEngine.cpp:
#if defined(OS_MAC)
#include "MacFont.h"
#elif
// ...
#endif
//...
In order to make it compiling, I should rename FontEngine.cpp to FontEngine.mm but I'm not allowed to.
So what now?
| If you cannot change the filename, don't fret. Consult your compiler manual for an option to force the filetype, and tell the compiler that this file, regardless of extension, is an Objective-C++ file.
|
3,034,096 | 3,034,123 | Linux, C++ audio capturing (just microphone) library | I'm developing a musical game, it's like a singstar but instead of singing, you have to play the recorder. It's called oFlute, and it's still in early development stage.
In the game, I capture the microphone input, then run a simple FFT analysis and compare the results to typical recorder's frequencies, thus getting the played note.
At the beginning, the audio library I was using was RtAudio, but I don't remember why I switched to PortAudio, which is what I'm currently using. The problem is that, from time to time, either it crashes randomly or stops capturing, like if there were no sound coming from the microphone.
My question is, what's the best option to capture microphone input on Linux? I just need to open, read, and close a flow of bytes from the microphone.
I've been reading this guide, and (un)surprisingly it says:
I don't think that PortAudio is very good API for Unix-like operating systems.
So, what do you recommend me?
| PortAudio is a strange choice given the other options.
I would personally abstract away from everything and use GStreamer. Audio can be a horrible mess on Linux (speaking as a long term sufferer). Letting Gstreamer deal with that lets you forget about it, move along and not have to think about it again.
OpenAL is probably the most popular for game dev though and it should support most systems (although you will have "fun" getting it playing nice with PulseAudio).
I'd certainly make sure you're developing for the most popular setup (which is PulseAudio at the moment, I reckon) so you don't end up in a situation where you release and you're plunged into a pool of people moaning about the sound not working.
And don't listen to the nonsense about PulseAudio - it might be new and it might take up a few more resources than a barebones ALSA system but it's certainly not mired with latency issues. Asking people to remove it isn't an option with modern desktop distros as it's so tightly integrated (and useful too).
|
3,034,285 | 3,034,476 | How does implementing multiple COM interfaces work in C++? | I am trying to understand this example code regarding Browser Helper Objects.
Inside, the author implements a single class which exposes multiple interfaces (IObjectWithSite, IDispatch).
His QueryInterface function performs the following:
if(riid == IID_IUnknown) *ppv = static_cast<BHO*>(this);
else if(riid == IID_IObjectWithSite) *ppv = static_cast<IObjectWithSite*>(this);
else if (riid == IID_IDispatch) *ppv = static_cast<IDispatch*>(this);
I have learned that from a C perspective, interface pointers are just pointers to VTables. So I take it to mean that C++ is capable of returning the VTable of any implemented interface using static_cast.
Does this mean that a class constructed in this way has a bunch of VTables in memory (IObjectWithSite, IDispatch, etc)? What does C++ do with the name collisions on the different interfaces (they each have a QueryInterface, AddRef and Release function), can I implement different methods for each of these?
| Yes, there are multiple v-tables, one for each inherited interface. The static_cast<> returns it. The compiler makes sure that common methods in the inherited interfaces are shared, it fills each v-table slot with the a pointer to the same function. So you only need one implementation of AddRef, Release, QueryInterface. Just what you want. None of this is an accident.
This is only ever a problem when a coclass implements multiple interfaces with the same method that you don't want to give the same implementation. The IConnectionPoint::Advise() method is a notorious example. Or was it DAdvise()? Unfortunately, I don't remember what it clashed with and how it was solved, it was covered by ATL Internals. Very good book btw.
|
3,034,296 | 3,034,356 | Const-Qualification of Main's Parameters in C++ | The C++ standard mandates that all conforming implementations support the following two signatures for main:
int main();
int main(int, char*[]);
In case of the latter signature, would the addition of (top-level) const-ness break any language rules?
For example:
int main(const int argc, char** const argv);
From my understanding, top-level const qualification doesn't affect the function's signature hash, so it should be legal as far as the specification is concerned.
Also, did anyone ever encounter an implementation which rejected this type of modification?
| This is a known issue in the Standard. Also see this usenet discussion on the topic.
|
3,034,477 | 3,034,911 | C++ "if then else" template substitution | I would like to declare a template as follows:
template <typename T>
{
if objects of class T have method foo(), then
const int k=1
else
if class has a static const int L then
const int k=L
else
const int k=0;
}
How can I do this? In general, I would like a mechanism for setting static consts
based on properties of T (or typedef defined inside T).
| The outer part is of course quite easy. Use boost::mpl::if_ to decide which int_ type to return from your metafunction and then access the value in it. No big deal.
The part where you try to find out if type X has a function f() is still fairly straight forward but unfortunately you'll not find a generic answer. Every time you need this kind of inspection you'll have to write a custom metafunction to find it out. Use SFINAE:
template < typename T >
struct has_foo
{
typedef char (&no) [1];
typedef char (&yes) [2];
template < void (T::*)() >
struct dummy {};
template < typename S >
static yes check( dummy<&S::foo> *);
template < typename S >
static no check( ... );
enum { value = sizeof(check<T>(0)) == sizeof(yes) };
};
Edit: Oh, and create a checker for your static const L with BOOST_MPL_HAS_XXX()
|
3,034,632 | 3,034,646 | Inheritance inside a template - public members become invisible? | I'm trying to use inheritance among classes defined inside a class template (inner classes). However, the compiler (GCC) is refusing to give me access to public members in the base class.
Example code:
template <int D>
struct Space {
struct Plane {
Plane(Space& b);
virtual int& at(int y, int z) = 0;
Space& space; /* <= this member is public */
};
struct PlaneX: public Plane {
/* using Plane::space; */
PlaneX(Space& b, int x);
int& at(int y, int z);
const int cx;
};
int& at(int x, int y, int z);
};
template <int D>
int& Space<D>::PlaneX::at(int y, int z) {
return space.at(cx, y, z); /* <= but it fails here */
};
Space<4> sp4;
The compiler says:
file.cpp: In member function ‘int& Space::PlaneX::at(int, int)’:
file.cpp:21: error: ‘space’ was not declared in this scope
If using Plane::space; is added to the definition of class PlaneX, or if the base class member is accessed through the this pointer, or if class Space is changed to a non-template class, then the compiler is fine with it.
I don't know if this is either some obscure restriction of C++, or a bug in GCC (GCC versions 4.4.1 and 4.4.3 tested). Does anyone have an idea?
| It should be a problem related to c++'s two-phase name lookup:
http://gcc.gnu.org/onlinedocs/gcc-4.4.3/gcc/Name-lookup.html#Name-lookup
|
3,034,686 | 3,034,694 | Mathematics errors in basic C++ program | I am working with a basic C++ program to determine the area and perimeter of a rectangle. My program works fine for whole numbers but falls apart when I use any number with a decimal. I get the impression that I am leaving something out, but since I'm a complete beginner, I have no idea what.
Below is the source:
#include <iostream>
using namespace std;
int main()
{
// Declared variables
int length; // declares variable for length
int width; // declares variable for width
int area; // declares variable for area
int perimeter; // declares variable for perimeter
// Statements
cout << "Enter the length and the width of the rectangle: "; // states what information to enter
cin >> length >> width; // user input of length and width
cout << endl; // closes the input
area = length * width; // calculates area of rectangle
perimeter = 2 * (length + width); //calculates perimeter of rectangle
cout << "The area of the rectangle = " << area << " square units." <<endl; // displays the calculation of the area
cout << "The perimeter of the rectangle = " << perimeter << " units." << endl; // displays the calculation of the perimeter
system ("pause"); // REMOVE BEFORE RELEASE - testing purposes only
return 0;
}
| Change all your int type variables to double or float. I would personally use double because they have more precision than float types.
|
3,035,035 | 3,035,100 | initialization of objects in c++ | I want to know, in c++, when does the initialization of objects take place?
Is it at the compile time or link time?
For ex:
//file1.cpp
extern int i;
int j=5;
//file2.cpp ( link with file1.cpp)
extern j;
int i=10;
Now, what does compiler do : according to me, it allocates storage for variables.
Now I want to know :
does it also put initialization value in that storage or is it done at link time?
| Actually there are different cases:
global variables or static variables (not classes): these values are stored in an init section of the exe/dll. These values are created by the linker based on the compiled object files information. (initialization on loading + mapping the dll/exe into memory)
local non static variables: these values are set by the compiler by putting these values on the stack (push/pop on x86) (compiler initialization)
objects: memory is reserved on the stack, the actual setting of values is deferred to the call to the constructor (run-time initialization)
pointers to objects (not actually a new case): space is reserved for the pointer only. The object pointed to exists only after a call to new that reserves memory and calls the constructor to initialize it (run-time initialization)
|
3,035,052 | 3,051,432 | Festival TTS showing SIOD:ran out off storage message | i am designing a front end for Festival TTS using it's C++ API
Everything is working fine in my programme but i have a problem that i am giving a drop down
option to user to select other languages when user select a language from drop down then
festival tts shows a message on console saying:
SIOD:ran out of storage
This message only shows if the text given to festival TTS is greater then 5 or 6 lines.
i think this message comes because SIOD's heap is not free when i am going to call a new language.
So please tell me the solution of this problem.
Thanks
| This post (from the festival mailing list, 2007) suggests you may simply have to increase the heap to a size which can contain all the languages one might select.
I don't know how they ended up resolving this problem (the conversation thread appears to end after this email), whether it frees the memory or whether it keeps all used voices around... my guess is the latter.
Alternatively, if you can kill festival (i don't know your program structure) and reinitialise it from scratch when a new voice is selected, that may avoid having to set a very large heap...?
|
3,035,114 | 3,035,125 | C++: use array of strings wrapped in namespace? | I got the following code, wishing to wrap a group of strings nicely in a namespace:
namespace msgs {
const int arr_sz = 3;
const char *msg[arr_sz] = {"blank", "blank", "blank" };
msg[0] = "Welcome, bla bla string 1!\n";
msg[1] = "Alright, bla bla bla..";
msg[2] = "etc.";
}
The code inside works nicely inside a function, but I don't know how to return an array from it. The namespace idea LOOKS fine, but it returns on the last three lines:
error: expected constructor, destructor, or type conversion before ‘=’ token
Why can't I define the array inside a namespace, do I need to do something first?
It's nice because I can call it like printf(msgs::msg[1]) etc. I want to do this I just can't wrap my head around what's wrong :(
| You can define the array inside the namespace:
// this is legal
namespace msgs {
const char *msg[] = {"blank", "blank", "blank" };
}
What you can't do is have a statement outside of a function:
// this is a statement, it must be inside a function
msg[0] = "Welcome, lets start by getting a little info from you!\n";
So to fix your code, just use the correct string in the definition:
namespace msgs {
const char *msg[] = {
"Welcome, lets start by getting a little info from you!\n",
"Alright, bla bla bla..",
"etc."
};
}
|
3,035,292 | 3,035,441 | How to use an overloaded function as an argument of function template? | I think everyone has experience working with a code like the following:
void fun(Type1&);
void fun(Type2&);
vector<Type1> vec;
for_each(vec.begin(), vec.end(), fun);
Of course that won't compile, because it's not clear which function to be passed. And what's your commonly-used solution to the problem?
I know this will work:
for_each(vec.begin(), vec.end(), (void(*)(Type1&))fun);
But any better ideas?
| One solution is to use template function:
template<typename T>
void fun(T&);
// specialize fun for Type1 and Type2
...
for_each(vec.begin(), vec.end(), fun<Type1>);
The better way is to use functor with template operator():
struct fun
{
template<typename T>
void operator()(T&) const;
};
...
for_each(vec.begin(), vec.end(), fun()); // T for operator() will be deduced automatically
|
3,035,348 | 3,036,533 | Consistency in placing operator functions | I have a class like this:
class A {
...private functions, variables, etc...
public:
...some public functions and variables...
A operator * (double);
A operator / (double);
A operator * (A);
...and lots of other operators
}
However, I want to also be able to do stuff like 2 * A instead of only being allowed to do A * 2, and so I would need functions like these outside of the class:
A operator * (double, A);
A operator / (double, A);
...etc...
Should I put all these operators outside of the class for consistency, or should I keep half inside and half outside?
| So what you are saying is that because you must put some operators (the ones that don't have A as the first param) outside the class, maybe you should put them all there so people know where to find them? I don't think so. I expect to find operators inside the class if at all possible. Certainly put the "outside" ones in the same file, that will help. And if the outside ones need access to private member variables, then adding the friend lines is a huge hint to look elsewhere in the file for those operators.
Would I go so far as to include the friend lines even if my implementation of the operators could actually be done with public getters and setters? I think I would. I think of those operators as really being part of the class. It's just that the language syntax requires them to be free functions. So generally I use friend and I write them as though they were member functions, not using getters and setters. It's a pleasant side effect that the resulting need for friend statements will cause them all to be listed in the definition of the class.
|
3,035,367 | 3,035,379 | Can I assign a object to a integer variable? | Let say I have a object. I'm assigning that to an integer.
MyClass obj1 = 100;//Not valid
Let's say, I have a parameterized constructor which accepts an integer.
MyClass(int Num)
{
// .. do whatever..
}
MyClass obj1 = 100;//Now, its valid
Likewise on any circumstance, does the vice-versa becomes valid?!.
eg) int Number = obj1;//Is it VALID or can be made valid by some tweeks
EDIT:
I found this to be possible using Conversion Functions.
Conversion functions are often called "cast operators" because they (along with constructors) are the functions called when a cast is used.
Conversion functions use the following syntax:
operator conversion-type-name ()
eg) Many have explained it neatly below
| Yes, provided that the object is implicitly convertible to an int, either directly or through an intermediate object.
E.g. If your class have a conversion operator int it would work:
MyClass
{
public:
operator int() const { return 200; }
};
|
3,035,376 | 3,035,403 | Convert char array to int array c++ | I`m having problems converting a char array read from file to an int array. Maybe someone can help me. This is my code:
char vectorPatron[67];
int iPatrones[67];
archivo = fopen("1_0.txt", "r");
for(i=0;i<67;i++){
fscanf(archivo, "%c", &vectorPatron[i]);
printf("%c",vectorPatron[i]);
}
fclose(archivo);
for(i=0;i<67;i++){
iPatrones[i] = atoi(&vectorPatron[i]);
printf("%d",iPatrones[i]);
}
| That's because atoi receives a null-delimited string, while you are passing it a pointer to a single char (both are essentially char *, but the intent and use are different).
Replace the call to atoi with iPatrons[i] = vectorPatron[i] - '0';
Also, you can remove the vectorPatrons array, simply read into a single char in the first loop and then assign to the appropriate place in the iPatrons array.
|
3,035,422 | 3,035,673 | static initialization order fiasco | I was reading about SIOF from a book and it gave an example :
//file1.cpp
extern int y;
int x=y+1;
//file2.cpp
extern int x;
int y=x+1;
Now My question is :
In above code, will following things happen ?
while compiling file1.cpp, compiler leaves y as it is i.e doesn't allocate storage for it.
compiler allocates storage for x, but doesn't initialize it.
While compiling file2.cpp, compiler leaves x as it is i.e doesn't allocate storage for it.
compiler allocates storage for y, but doesn't initialize it.
While linking file1.o and file2.o, now let file2.o is initialized first, so now:
Does x gets initial value of 0? or doesn't get initialized?
| The initialization steps are given in 3.6.2 "Initialization of non-local objects" of the C++ standard:
Step 1: x and y are zero-initialized before any other initialization takes place.
Step 2: x or y is dynamically initialized - which one is unspecified by the standard. That variable will get the value 1 since the other variable will have been zero-initialized.
Step 3: the other variable will be dynamically initialized, getting the value 2.
|
3,035,455 | 3,035,498 | Printing the address of a struct object | I have a struct like this
typedef struct _somestruct {
int a;
int b;
}SOMESTRUCT,*LPSOMESTRUCT;
I am creating an object for the struct and trying to print it's address like this
int main()
{
LPSOMESTRUCT val = (LPSOMESTRUCT)malloc(sizeof(SOMESTRUCT));
printf("0%x\n", val);
return 0;
}
..and I get this warning
warning C4313: 'printf' : '%x' in
format string conflicts with argument
1 of type 'LPSOMESTRUCT'
So, I tried to cast the address to int like this
printf("0%x\n", static_cast<int>(val));
But I get this error:
error C2440: 'static_cast' : cannot
convert from 'LPSOMESTRUCT' to 'int'
What am I missing here? How to avoid this warning?
Thanks.
| %x expects an unsigned. What you're printing is a pointer. To do that correctly, you normally want to use %p. To be pedantically correct, that expects a pointer to void, so you'll need to cast it:
printf("%p\n", (void *)val);
In reality, most current implementations use the same format for all pointers, in which case the cast will be vacuous. Of course, given the C++ tag, most of the code you've included becomes questionable at best (other than the parts like LPSOMESTRUCT, which are questionable regardless). In C++, you normally want something more like:
struct somestruct {
int a;
int b;
};
somestruct *val = new somestruct; // even this is questionable.
std::cout << val;
|
3,035,582 | 3,035,606 | Static Variables in Overloaded Functions | I have a function which does the following:
When the function is called and passed a true bool value, it sets a static bool value to true
When the function is called and passed a string, if the static bool value is set to true, it will do something with that string
Here is my concern -- will a static variable remain the same between two overloaded functions? If not, I can simply create a separate function designed to keep track of the bool value, but I try to keep things simple.
| No, it creates two separate static variables - one for each function. The name of any C++ function is made op of its apparent name and its parameter types, and the name of the static is (conceptually at least) tacked on to that. Rather than add yet another function, you could consider making the variable static with respect to the class containing the functions, although this does not give you exactly the same behaviour, or place it in an anonymous namespace:
namespace {
int myvar = 0;
}
int f( bool b ) {
return myvar;
}
int f( const string & s ) {
return myvar;
}
To make the functions members of a class:
// a.h
class A {
public:
static int f( bool b ) {
return myvar;
}
static int f( const string & s ) {
return myvar;
}
private:
static int myvar;
};
// a.cpp
int A::myvar = 0;
// main.cpp
#include <iostream>
#include <a.h>
int main() {
std::cout << A::f(false) << A::f( string("foobar") ) << std::endl;
}
|
3,035,609 | 3,035,694 | C++/g++: Concurrent program | I got a C++ program (source) that is said to work in parallel. However, if I compile it (I am using Ubuntu 10.04 and g++ 4.4.3) with g++ and run it, one of my two CPU cores gets full load while the other is doing "nothing".
So I spoke to the one who gave me the program. I was told that I had to set specific flags for g++ in order to get the program compiled for 2 CPU cores. However, if I look at the code I'm not able to find any lines that point to parallelism.
So I have two questions:
Are there any C++-intrinsics for multithreaded applications, i.e. is it possible to write parallel code without any extra libraries (because I did not find any non-standard libraries included)?
Is it true that there are indeed flags for g++ that tell the compiler to compile the program for 2 CPU cores and to compile it so it runs in parallel (and if: what are they)?
| AFAIK there are no compiler flags designed to make a single-threaded application exploit parallelism (it's definitely a nontrivial operation), with the exception of parallelization of loops iterations (-ftree-parallelize-loops), that, still, must be activated carefully; still, even if there's no explicit threads creation, there may be some OpenMP directives to parallelize several instruction sequences.
|
3,035,614 | 3,035,909 | Getting list of all existing vtables | In my application I have quite some void-pointers (this is because of historical reasons, application was originally written in pure C). In one of my modules I know that the void-pointers points to instances of classes that could inherit from a known base class, but I cannot be 100% sure of it. Therefore, doing a dynamic_cast on the void-pointer might give problems. Possibly, the void-pointer even points to a plain-struct (so no vptr in the struct).
I would like to investigate the first 4 bytes of the memory the void-pointer is pointing to, to see if this is the address of the valid vtable. I know this is platform, maybe even compiler-version-specific, but it could help me in moving the application forward, and getting rid of all the void-pointers over a limited time period (let's say 3 years).
Is there a way to get a list of all vtables in the application, or a way to check whether a pointer points to a valid vtable, and whether that instance pointing to the vtable inherits from a known base class?
|
I would like to investigate the first
4 bytes of the memory the void-pointer
is pointing to, to see if this is the
address of the valid vtable.
You can do that, but you have no guarantees whatsoever it will work. Y don't even know if the void* will point to the vtable. Last time I looked into this (5+ years ago) I believe some compiler stored the vtable pointer before the address pointed to by the instance*.
I know this is platform, maybe even
compiler-version-specific,
It may also be compiler-options speciffic, depending on what optimizations you use and so on.
but it could help me in moving the
application forward, and getting rid
of all the void-pointers over a
limited time period (let's say 3
years).
Is this the only option you can see for moving the application forward? Have you considered others?
Is there a way to get a list of all
vtables in the application,
No :(
or a way to check whether a pointer
points to a valid vtable,
No standard way. What you can do is open some class pointers in your favorite debugger (or cast the memory to bytes and log it to a file) and compare it and see if it makes sense. Even so, you have no guarantees that any of your data (or other pointers in the application) will not look similar enough (when cast as bytes) to confuse whatever code you like.
and whether that instance pointing to
the vtable inherits from a known base
class?
No again.
Here are some questions (you may have considered them already). Answers to these may give you more options, or may give us other ideas to propose:
how large is the code base? Is it feasible to introduce global changes, or is functionality to spread-around for that?
do you treat all pointers uniformly (that is: are there common points in your source code where you could plug in and add your own metadata?)
what can you change in your sourcecode? (If you have access to your memory allocation subroutines or could plug in your own for example you may be able to plug in your own metadata).
If different data types are cast to void* in various parts of your code, how do you decide later what is in those pointers? Can you use the code that discriminates the void* to decide if they are classes or not?
Does your code-base allow for refactoring methodologies? (refactoring in small iterations, by plugging in alternate implementations for parts of your code, then removing the initial implementation and testing everything)
Edit (proposed solution):
Do the following steps:
define a metadata (base) class
replace your memory allocation routines with custom ones which just refer to the standard / old routines (and make sure your code still works with the custom routines).
on each allocation, allocate the requested size + sizeof(Metadata*) (and make sure your code still works).
replace the first sizeof(Metadata*) bytes of your allocation with a standard byte sequence that you can easily test for (I'm partial to 0xDEADBEEF :D). Then, return [allocated address] + sizeof(Metadata*) to the application. On deallocation, take the recieved pointer, decrement it by `sizeof(Metadata*), then call the system / previous routine to perform the deallocation. Now, you have an extra buffer allocated in your code, specifically for metadata on each allocation.
In the cases you're interested in having metadata for, create/obtain a metadata class pointer, then set it in the 0xDEADBEEF zone. When you need to check metadata, reinterpret_cast<Metadata*>([your void* here]), decrement it, then check if the pointer value is 0xDEADBEEF (no metadata) or something else.
Note that this code should only be there for refactoring - for production code it is slow, error prone and generally other bad things that you do not want your production code to be. I would make all this code dependent on some REFACTORING_SUPPORT_ENABLED macro that would never allow your Metadata class to see the light of a production release (except for testing builds maybe).
|
3,035,625 | 3,035,958 | Coordinate confusion | I subclassed QGraphicsItem and reimplemented paint.
In paint I wrote something like this for labeling the item:
painter->drawText("Test",10,40);
After some time I think It may be useful to handle labeling with seperate item. So I wrote something like this.
QGraphicsTextItem *label = new QGraphicsTextItem("TEST",this);
setPos(10,40);
But two "TEST" drawing do not appear in the same place on screen. I guess difference may be related with item coordinates - scene coordinates. I tried all mapFrom... and mapTo... combinations inside QGraphicsItem interface but no progress. I want to drawings to appear in the same place on screen.
What I miss?
| I assume that you are using the same font size and type in both cases. If the difference in position is very small the reason can be the QGraphicTextItem is using some padding for the text it contains. I would try to use QGraphicsSimpleTextItem that is not going to add fancy stuff internally and see if you still have the same problem. The coordinates system is the same one if you use painter or setPost so that is not the problem. If this doesn't help I will suggest to specify the same rect for both to avoid Qt adding it owns separation spaces.
|
3,035,975 | 3,036,824 | Best approach to synchronising properties across threads | I'm looking for some advice on the best approach to synchronising access to properties of an object in C++. The application has an internal cache of objects which have 10 properties. These objects are to be requested in sets which can then have their properties modified and be re-saved. They can be accessed by 2-4 threads at any given time but access is not intense so my options are:
Lock the property accessors for each object using a critical section. This means lots of critical sections - one for each object.
Return copies of the objects when requested and have an update function which locks a single critical section to update the object properties when appropriate.
I think option 2 seems the most efficient but I just want to see if I'm missing a hidden 3rd option which would be more appropriate.
Thanks,
J
| Firstly, I think you are worrying about the wrong thing. How do you know locking or copying causes bottlenecks in your code? Critical sections are fairly lightweight and don't cause much overhead, or, at least, not as much as you think. Just use the most lightweight locking primitive available. If you anticipate your system to be run on multi-processor hardware, you can even use a spinlock.
Secondly, do worry about simplicity of your concurrency model, before performance (hint: simpler model is easier to understand, to get right and to optimize). So if you can afford it, take copies of objects, this will ease the pain of dealing with TOCTOU race conditions in case you are doing complex transformations on the object set that depend on a number of previous values.
|
3,036,027 | 3,036,182 | Features that require Q_OBJECT macro in Qt 4 other than signal - slots mechanism | I am using Qt 4.5 in windows XP. I know we have to use Q_OBJECT macro for signal - slot connection mechanism. But besides that, is there are any other reasons to use the Q_OBJECT macro? I recently come to know that for some other meta-object features we require the Q_OBJECT declaration. What are those features beside the Signal-slots? I tried for documentation regarding that but couldn't find anything helpful. Any pointers regarding this are welcome.
| You can find all you need to know about when Q_OBJECT macro is needed here:
http://doc.qt.digia.com/4.6/metaobjects.html
In resume you need it for signals and slots, to use tr for translation, to retrieve class name in real time from a QObject, to know if it inherits from other class (instrospection) to set properties and to be able to call newInstance.
Hope it helps.
|
3,036,134 | 3,036,589 | Encrypting password in compiled C or C++ code | I know how to compile C and C++ Source files using GCC and CC in the terminal, however i would like to know if its safe to include passwords in these files, once compiled.
For example.. i check user input for a certain password e.g 123, but it appears compiled C/C++ programs is possible to be decompiled.
Is there anyway to compile a C/C++ source file, while keeping the source completely hidden..
If not, could anyone provide a small example of encrypting the input, then checking against the password e.g: (SHA1, MD5)
| It is not recommended to keep any sensitive static data inside code. You can use configuration files for that. There you can store whatever you like.
But if you really want to do that first remember that the code can be easily changed by investigating with a debugger and modifying it. Only programs that user doesn't have access to can be considered safer (web sites for example).
The majority of login passwords (of different sites) are not stored in clear in the database but encrypted with algorithms MD5, SHA1, Blowfish etc.
I'd suggest you use one of these algorithms from OpenSSL library.
What I would do is using some public-key cryptographic algorithm. This will probably take a little longer to be cracked because in my opinion there is nothing 100% sure when talking about software protection.
|
3,036,221 | 3,036,990 | SendMessage (F4) fails when sending it to window | Working with Visual Studio 6 (VC++ 6.0) I'm using an ActiveX datepicker control which I fail to show expanded by default (3006216). Alternatively I'm trying to send a keyboard message (F4) to my window to open up the control, but nothing happens when I do so...
// try 1: use the standard window handle
LRESULT result = ::SendMessage(m_hWnd,VK_F4, 0, 0);
// try 2: use just use the SendMessage
result = SendMessage(VK_F4);
result is always 0 - what can I do to test/verify the message sending?
Thanks in acvance a lot...
Olli
| Okay - there's two approaches on this issue (thanks for all the help, guys!):
First: Use "::SendMessage" with correct message AND correct handle:
::SendMessage(m_wndDatePicker.m_hWnd, WM_KEYDOWN, VK_F4, 0);
Alternatively use "SendInput":
// important: set focus to control first
m_wndDatePicker.SetFocus();
INPUT *key;
key = new INPUT;
key->type = INPUT_KEYBOARD;
key->ki.wVk = VK_F4;
key->ki.dwFlags = 0;
key->ki.time = 0;
key->ki.wScan = 0;
key->ki.dwExtraInfo = 0;
SendInput(1,key,sizeof(INPUT));
|
3,036,282 | 3,036,389 | Corrupted mysql table, cause crash in mysql.h (c++) | i've created a very simple mysql class in c+, but when happen that mysql crash , indexes of tables become corrupted, and all my c++ programs crash too because seems that are unable to recognize corrupted table and allowing me to handle the issue ..
Q_RES = mysql_real_query(MY_mysql, tmp_query.c_str(), (unsigned int) tmp_query.size());
if (Q_RES != 0) {
if (Q_RES == CR_COMMANDS_OUT_OF_SYNC) cout << "errorquery : CR_COMMANDS_OUT_OF_SYNC " << endl;
if (Q_RES == CR_SERVER_GONE_ERROR) cout << "errorquery : CR_SERVER_GONE_ERROR " << endl;
if (Q_RES == CR_SERVER_LOST) cout << "errorquery : CR_SERVER_LOST " << endl;
LAST_ERROR = mysql_error(MY_mysql);
if (n_retrycount < n_retry_limit) { // RETRY!
n_retrycount++;
sleep(1);
cout << "SLEEP - query retry! " << endl;
ping();
return select_sql(tmp_query);
}
return false;
}
MY_result = mysql_store_result(MY_mysql);
B_stored_results = true;
cout << "b8" << endl;
LAST_affected_rows = (mysql_num_rows(MY_result) + 1); // coult return -1
cout << "b8-1" << endl;
the program terminate with a "segmentation fault" after doing the "b8" and before the "b8-1"
, Q_RES have no issue even if the table is corrupted.. i would like to know if there is a way to recognize that the table have problems and so then i can run a mysql repair or mysql check ..
thanks,
Francesco
| You need to check the return value of mysql_store_result() - it might be NULL.
http://dev.mysql.com/doc/refman/5.0/en/mysql-store-result.html
mysql_store_result() returns a null
pointer if the statement didn't return
a result set (for example, if it was
an INSERT statement).
mysql_store_result() also returns a
null pointer if reading of the result
set failed. You can check whether an
error occurred by checking whether
mysql_error() returns a nonempty
string, mysql_errno() returns nonzero,
or mysql_field_count() returns zero.
It's probably not a problem with the database being corrupted.
|
3,036,284 | 3,036,332 | Releasing memory from map. C++ | std::map<int, int> * mp = new std::map<int, int>;
for(int i = 0; i < 999999; i++){
mp->insert(std::pair<int, int>(i, 999999-i ));
}
p("created");
//mp->clear(); - doesn't help either
delete mp;
p("freed");
The problem is: "delete mp" doesn't do anything. To compare:
std::vector<int> * vc = new std::vector<int>;
for(int i = 0; i < 9999999; i++){
vc->push_back(i);
}
p("created");
delete vc;
p("freed");
releases memory. How to release memory from map?
PS: p("string") just pauses program and waits for input.
| The RAM used by the application is not a precise way to tell if the memory has been semantically freed.
Freed memory is memory that you can reuse. Sometimes though, you don't observe this freed memory directly in what the OS reports as memory used by our app.
You know that the memory is freed because the semantics of the language say so.
|
3,036,300 | 3,036,328 | Equivalent of C# 'as' command in C++? | In C# you can use as to convert a type or get null:
Object o = Whatever();
String s = o as String;
Is there a similar easy way to achieve this in C++?
I'm using Visual Studio 2010, if that's important.
[Update]: Remember, there is a very important difference between casting and using as. Casting (at least in C#) will throw an exception if the type does not match:
Object o = null;
String s = (String)o; // Will crash.
| In C++, this would be a dynamic_cast, if you had a hierarchy where Object is the parent and String is the child.
Object * p = createMyObject();
String * s = dynamic_cast<String *>(p);
if(s)
{
...
}
Dynamic casting a pointer will return a pointer to the object if the cast is possible, or a null pointer if not.
Also, dynamic casting a reference will return a reference to the object if the cast is possible, or throw an exception.
|
3,036,334 | 3,036,391 | How do I dynamically allocate memory for arrays in Qt C++? | I'm having some issues in allocating memory for an array dynamically in C++ within Qt SDK ... Here's for I'm doing:
int dx = 5;
QPoint * qPoint;
qPoint = new QPoint[dx+1];
However when I try to debug the code, the programs just crashes when it tries to execute the third line .... any clues ?
| If you want to use Qt SDK properly you have to use QVector instead of C++ arrays or std arrays. You can use QVector as a pointer or not, it doesn't really matter since internally it will allocate the memory dynamically.
For example:
int dx = 5;
QVector<QPoint> points;
points.resize(dx + 1);
You can also do:
QVector<QPoint> * points = new QVector<QPoint>(dx + 1);
In case you want the vector as a pointer. But Qt uses implicit memory sharing for vectors so you can use the first approach most of the times.
http://doc.qt.io/qt-5/implicit-sharing.html#implicit-data-sharing
|
3,036,469 | 3,036,483 | static initialization confusion | I am getting very confused in some concepts in c++. For ex: I have following two files
//file1.cpp
class test
{
static int s;
public:
test(){s++;}
};
static test t;
int test::s=5;
//file2.cpp
#include<iostream>
using namespace std;
class test
{
static int s;
public:
test(){s++;}
static int get()
{
return s;
}
};
static test t;
int main()
{
cout<<test::get()<<endl;
}
Now My question is :
1. How two files link successfully even if they have different class definitions?
2. Are the static member s of two classes related because I get output as 7.
Please explain this concept of statics.
| They link because the linker knows almost nothing about the C++ language. However, if you do this, you have broken the One Definition Rule, and the behaviour of your program will be undefined. writing invalid code is not a good way of learning C++. Also, you seem to be having a lot of questions about static variables - the concept is really not all that complex - which C++ textbook are you using that does not explain it well?
|
3,036,565 | 3,036,576 | GCC: Compile to assembly with clarified correspondence to code? | When you break into the debugger in VS and open the disassembly window, each assembly fragment is displayed below it's corresponding code section (more or less). GCC with -S outputs only the stripped down assembly.
Is there an option in GCC to show some correspondence to the original code?
Source code is C++.
| Compile your code with gcc -g, then you can disassemble with objdump -S yourfile. this will give you a disassembly interspersed with the source.
|
3,036,773 | 3,036,779 | How to not #include <windows.h> | Using MSVC2008, 32bit on 64bit system.
I was once advised to never include windows.h as 'its a real monster and will slow down my compile times significantly'.
I tried leaving it out and obviously get compile errors. I included windef.h to define all the DWORDs etc, but I quickly come unstuck knowing what else to define to get the code to compile.
I now get:
2>c:\program files\microsoft sdks\windows\v7.0\include\winnt.h(6361) : error C2146: syntax error : missing ';' before identifier 'ContextRecord'
2>c:\program files\microsoft sdks\windows\v7.0\include\winnt.h(12983) : error C2065: 'PCONTEXT' : undeclared identifier
Can anyone suggest the right approach here?
Thanks
Simon
| Internally, windows.h respects many defines, like NOMINMAX or WIN32_LEAN_AND_MEAN.
It reduces the times significantly.
|
3,037,076 | 3,037,108 | How to encapsulate a WinAPI application into a C++ class | There is a simple WinAPI application. All it does currently is this:
register a window class
register a tray icon with a menu
create a value in the registry in order to autostart
and finally, it checks if it's unique using a mutex
As I'm used to writing code mainly in C++, and no MFC is allowed, I'm forced to encapsulate this into C++ classes somehow. So far I've come up with such a design:
there is a class that represents the application
it keeps all the wndclass, hinstance, etc variables, where the hinstance is passed as a constructor parameter as well as the icmdshow and others (see WinMain prototype)
it has functions for registering the window class, tray icon, reigstry information
it encapsulates the message loop in a function
In WinMain, the following is done:
Application app(hInstance, szCmdLIne, iCmdShow);
return app.exec();
and the constructor does the following:
registerClass();
registerTray();
registerAutostart();
So far so good. Now the question is : how do I create the window procedure (must be static, as it's a c-style pointer to a function) AND keep track of what the application object is, that is, keep a pointer to an Application around.
The main question is : is this how it's usually done? Am I complicating things too much? Is it fine to pass hInstance as a parameter to the Application constructor? And where's the WndProc?
Maybe WndProc should be outside of class and the Application pointer be global? Then WndProc invokes Application methods in response to various events.
There's one more possible solution : make the application class a singleton. Then it's trivial to obtain the handle to that object from the WndProc.
| The answer is SetWindowLongPtr. It allows you to associate a void* with a given hWnd. Then, in the WndProc, you just extract said void*, cast, and call the member method. Problemo solvo. There's a few ups/downs with SetWindowLongPtr, you must call some other function to see the effects or somesuch BS, and Windows sends messages before CreateWindowEx returns, so you must be prepared for GetWindowLongPtr(hWnd, GWL_USERDATA) to return NULL.
This of course means that for a given WindowProc, all instances that use it must have a common interface, since there's not much you can do with a void*.
And, yes, it's fine to pass HINSTANCE to the App constructor. I've seen samples that do something strange to avoid this but I never made it work myself.
Edit:
Don't confuse Get/SetWindowLong with Get/SetWindowLongPtr. Get/SetWindowLong is deprecated and unsafe.
|
3,037,636 | 3,037,686 | VERY strange stack overflow in C++ program | I wrote a program some time ago (Mac OS X, C++, SDL, FMOD) and it perfomed rather good. But lately I wanted to extend its functionality and added some more code to it. And now, when I run it and try to test the new functionality, the program crashes with SIGABRT.
Looking into debugger, on function stack I see:
_kill
kill$UNIX2003
raise
__abort
__stack_chk_fail
odtworz <-- my function that was was modified
As far as I know, "__stack_chk_fail" indicates a stack overflow. But that's not the weirdest thing about it. In this function "odtworz", I have some code like this:
...
koniec = 0;
while ( koniec == 0 ) {
...
if (mode == 1) {
...
}
else if (mode == 2) {
...
}
else if (mode == 3) {
piesniOrkiestrowe[0] = '\0';
while ( piesniOrkiestrowe[0] == '\0' ) {
losowaPiesn();
char * piesnOrkiestrowa = szukajPiesniOrkiestrowej();
if ( piesnOrkiestrowa != NULL )
strcpy(piesniOrkiestrowe, piesnOrkiestrowa);
}
char nowyPiesnPlik[25];
sprintf(nowyPiesnPlik, "%sorch/%s", PIESNI_DIR.c_str(), piesniOrkiestrowe);
}
}
mode is a global variable and is set to value "2" in a function before. And now imagine - if I delete the third if statement (mode == 3) which never gets executed in this mode, the program doesn't crash! Deleting code that doesn't even get to be executed helps the situation!
Now, I don't want to delete this code because it's for other mode of my program. And it works fine there. So any hints where I can search? What could be possibly wrong with this?
| It is not a stack overflow error. __stack_chk_fail is called when stack frame corruption is detected. The traditional way to smash the stack is a buffer overflow. The code that causes it is not in your snippet, it is in the dots.
After updating the question with code from a comment: both the strcpy and the sprintf calls are excellent candidates for stack corruption. The buffer overflow problem I mentioned in my original answer. Taking a guess: nowyPiesnPlik looks very small. The sprintf() function will write too many characters to the buffer and overwrite the "canary". When the canary gets stomped on, the runtime will whistle fowl :)
You could make the array bigger. Not a real solution, use safe alternatives for these functions, like snprintf(). I'll avoid mentioning strncpy().
|
3,037,846 | 3,037,894 | Mapping integers to types using C++ template fails in a specific case | I am attempting to compile the following template based code in VC++ 2005.
#include <iostream>
using namespace std;
/*
* T is a template which maps an integer to a specific type.
* The mapping happens through partial template specialization.
* In the following T<1> is mapped to char, T<2> is mapped to long
* and T<3> is mapped to float using partial template specializations
*/
template <int x>
struct T
{
public:
};
template<>
struct T<1>
{
public:
typedef char xType;
};
template<>
struct T<2>
{
public:
typedef long xType;
};
template<>
struct T<3>
{
public:
typedef float xType;
};
// We can easily access the specific xType for a specific T<N>
typedef T<3>::xType x3Type;
/*!
* In the following we are attempting to use T<N> inside another
* template class T2<R>
*/
template<int r>
struct T2
{
//We can map T<r> to some other type T3
typedef T<r> T3;
// The following line fails
typedef T3::xType xType;
};
int main()
{
T<1>::xType a1;
cout << typeid(a1).name() << endl;
T<2>::xType a2;
cout << typeid(a2).name() << endl;
T<3>::xType a3;
cout << typeid(a3).name() << endl;
return 0;
}
There is a particular line in the code which doesn't compile:
typedef T3::xType xType;
If I remove this line, compilation goes fine and the result is:
char
long
float
If I retain this line, compilation errors are observed.
main.cpp(53) : warning C4346: 'T<x>::xType' : dependent name is not a type
prefix with 'typename' to indicate a type
main.cpp(54) : see reference to class template instantiation 'T2<r>' being compiled
main.cpp(53) : error C2146: syntax error : missing ';' before identifier 'xType'
main.cpp(53) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
I am not able to figure out how to make sure that T::xType can be treated as a type inside the T2 template. Any help is highly appreciated.
| Since T3 in your template class depends on the template parameter, the compiler can't known for sure what T3::xType will refer to (that might depend on the actual type r in each instantiation T2<r>).
To tell the compiler that T3::xType will be a type, you need to add the typename keyword:
typedef typename T3::xType xType;
|
3,037,946 | 3,115,993 | how can i store xml in buffer using xmlite? | I'm trying to write xml data with XmlLite on buffer but couldn't got any api. writing a xml file works perfect but on a memory stream I can't figure
i am working on follwong link api
http://msdn.microsoft.com/en-us/library/ms752901(v=VS.85).aspx
| You can use either SHCreateMemStream or CreateStreamOnHGlobal to create an memory stream. Here is the sample code for your reference:
CComPtr<IStream> spMemoryStream;
CComPtr<IXmlWriter> spWriter;
CComPtr<IXmlWriterOutput> pWriterOutput;
// Opens writeable output stream.
spMemoryStream.Attach(::SHCreateMemStream(NULL, 0));
if (spMemoryStream == NULL)
return E_OUTOFMEMORY;
// Creates the xml writer and generates the content.
CHKHR(::CreateXmlWriter(__uuidof(IXmlWriter), (void**) &spWriter, NULL));
CHKHR(::CreateXmlWriterOutputWithEncodingName(spMemoryStream,
NULL, L"utf-16", &pWriterOutput));
CHKHR(spWriter->SetOutput(pWriterOutput));
CHKHR(spWriter->SetProperty(XmlWriterProperty_Indent, TRUE));
CHKHR(spWriter->WriteStartDocument(XmlStandalone_Omit));
CHKHR(spWriter->WriteStartElement(NULL, L"root", NULL));
CHKHR(spWriter->WriteWhitespace(L"\n"));
CHKHR(spWriter->WriteCData(L"This is CDATA text."));
CHKHR(spWriter->WriteWhitespace(L"\n"));
CHKHR(spWriter->WriteEndDocument());
CHKHR(spWriter->Flush());
// Allocates enough memeory for the xml content.
STATSTG ssStreamData = {0};
CHKHR(spMemoryStream->Stat(&ssStreamData, STATFLAG_NONAME));
SIZE_T cbSize = ssStreamData.cbSize.LowPart;
LPWSTR pwszContent = (WCHAR*) new(std::nothrow) BYTE[cbSize + sizeof(WCHAR)];
if (pwszContent == NULL)
return E_OUTOFMEMORY;
// Copies the content from the stream to the buffer.
LARGE_INTEGER position;
position.QuadPart = 0;
CHKHR(spMemoryStream->Seek(position, STREAM_SEEK_SET, NULL));
SIZE_T cbRead;
CHKHR(spMemoryStream->Read(pwszContent, cbSize, &cbRead));
pwszContent[cbSize / sizeof(WCHAR)] = L'\0';
wprintf(L"%s", pwszContent);
One pretty thing about XmlLite is it works with IStream interface. It really doesn't care what exactly the stream looks like behind the scene.
|
3,038,045 | 3,038,073 | How does compiler understand the pointer type? | How does the C++ compiler understand the pointer type? As I know pointer has a size equal to WORD of the OS (32 or 64). So does it store some info in that 32 (or 64) bits about type? Just because you can not have a pointer on one type and assign to that pointer another pointer with a different type.
| A pointer is usually just a memory address on x86 based architectures (I don't know about other architectures). The compiler enforces type safety with different pointers at compile time - since it makes no sense to assign a pointer-to-char to a pointer-to-int, for example, especially since the objects pointed to are different sizes (so you'd be grabbing random memory if you accessed them). You can explicitly override this and assign any pointer to any other pointer with a reinterpret_cast<T>, or with other types of cast like static_cast<T> and dynamic_cast<T> (the latter two are generally recommended due to being 'safer' but each have their uses).
So at the machine level a memory address is just a memory address and the CPU will dutifully carry out any accesses or calls on that. However it's dangerous, since you can get types mixed up and possibly not know about it. The compile time checks help avoid that, but there is not usually any information about the actual types stored inside the pointer itself at runtime.
An advantage of using iterators (pointer wrappers provided by the STL) is that many implementations have a lot of additional checks which can be enabled at runtime: like checking you're using the right container, that when you compare them they're the same type of iterator, and so on. This is a major reason to use iterators over pointers - but it's not required by the standard, so check your implementation.
|
3,038,074 | 4,293,112 | Parsing simple MIME files from C/C++? | I have searched the web for days now but I can't seem to find a good solution to my problem:
For one of my projects I'm looking for a good (lightweight) MIME parser. My customer provides MIME formatted files (linear, no hierarchy) which contain 3-4 "parts". The application must be able to split those parts and process them independently.
Basically those MIME files are like raw E-Mail messages, but without the SMTP-headers. Instead they begin with the MIME-Header "MIME-Version: 1.0" and after that the parts follow.
I am using C++ for the application, so a C++ library is welcome. A standard C library is welcome, too; but it should fit the following criteria:
Be open (at least LGPL), not properiaty
Compact - I just need the parser, no SMTP/POP3 support
Cross-Platform (targeting Windows, Mac OS X and Linux)
After days of searching I found the following libs and reasons why to not use them:
mimetic (C++) --- Although this library seems complete and for C++ usage, it is based on glib, which won't properly compile on Windows.
Vmime (C++) --- Seems complete, but there is no official Windows support. Also they provide "dual licensing" ("commerical LGPL" + GPL). Seems to be included with Ubuntu and Debian, but the licensing is confusing.
mime++ --- Commerical, no Mac support.
Chilkat Software MIME C++ Library --- Commerical and focused on Windows.
I don't really want to write my own MIME parser. MIME is so widespread that there must be some open library to handle this file format in a sane way.
So, do you guys have any ideas, suggestions or links?
Thanks in advance!
| It's been a while. So I'll just answer my own question.
After spending some more time on this, I ended up writing my own implementation. MIME is quite simple indeed, and if you read the documentation, you have something up and running in a short time.
However, I think there should be something like vMime, but open source. I can't believe that so few people have to deal with MIME structures as it's a real standard.
|
3,038,085 | 3,038,108 | Get executing directory in C++ | I have a .CAB file that runs as part of an installer process on a Windows CE box. The CAB is written in C++.
The CAB file is ran twice as part of an upgrade process but in different locations at different times. How can I find out what directory the .CAB file is being executed from (executing directory) using C++ only?
Thanks
| If by "C++ only" you mean without using Windows API, I don't think the standard library has a function to do that.
If you can call a Win32 API, you just have to call GetModuleFileName() with NULL as the first parameter, and you will get the path of the current executable.
Now, the problem is: we you run the .CAB, what is the executable? The install DLL extracted from the .CAB, or the shell component that is running the .CAB?
You can also try GetCommandLine(), as the first entry should be the executable path/name (it is actually the string passed to CreateProcess(), so you can't be 100% sure about it).
|
3,038,151 | 3,038,312 | VSC++, virtual method at bad address, curious bug | This guy:
virtual phTreeClass* GetTreeClass() const { return (phTreeClass*)m_entity_class; }
When called, crashed the program with an access violation, even after a full recompile. All member functions and virtual member functions had correct memory addresses (I hovered mouse over the methods in debug mode), but this function had a bad memory address: 0xfffffffc.
Everything looked okay: the 'this' pointer, and everything works fine up until this function call. This function is also pretty old and I didn't change it for a long time. The problem just suddenly popped up after some work, which I commented all out to see what was doing it, without any success.
So I removed the virtual, compiled, and it works fine. I add virtual, compiled, and it still works fine! I basically changed nothing, and remember that I did do a full recompile earlier, and still had the error back then.
I wasn't able to reproduce the problem. But now it is back. I didn't change anything. Removing virtual fixes the problem.
| Don't ever use C-style casts with polymorphic types unless you're seriously sure of what you're doing. The overwhelming probability is that you cast it to a type that it wasn't. If your pointers don't implicitly cast (because they cast to a base class, which is safe) then you're doing it wrong.
|
3,038,280 | 3,038,384 | Convert void* representation of a dword to wstring | I am having dumb monday so my apologies for posting such a newbie-like question.
I am using CRegKey.QueryValue to return a dword value from the registry. QueryValue writes the value into void* pData and the length into ULONG* pnBytes.
Now there is a way of getting it from pData into a wstring probably via stringstream. The closest I came was getting the result as a hex string. I was about to work on converting the hex representation to a dword and then from there to a wstring when I decided that was just dumb and ask on here instead of wasting another hour of my life on the problem.
| Why don't you use CRegKey::QueryDWORDValue instead?
Then you could just swprintf_s to print it into a string (if you wish to).
|
3,038,302 | 3,038,539 | Why do ZeroMemory, etc. exist when there are memset, etc. already? | Why does ZeroMemory(), and similar calls exist in the Windows API when there are memset and related calls in the C standard library already? Which ones should I call? I can guess the answer is "depends". On what?
| In C and C++, ZeroMemory() and memset() are the exact same thing.
/* In winnt.h */
#define RtlZeroMemory(Destination,Length) memset((Destination),0,(Length))
/* In winbase.h */
#define ZeroMemory RtlZeroMemory
Why use ZeroMemory() then? To make it obvious. But I prefer memset() in C or C++ programs.
|
3,038,336 | 3,038,415 | Linux / C++: Get Internet IP Address (not local computer's IP) | How can I programmatically get the Internet IP address?
1) If the computer is directly connected to the Internet using a USB modem.
2) If the computer is connected to the internet via another computer or a modem/router.
I there a way to do both?
P.S. This link gives exactly the Internet IP, but how can I use it in my program?
|
You can write socket code to send an http request to that link.
Under unix/linux/cygwin you can use system("wget http://www.whatismyip.com/automation/n09230945.asp"); then open the file "n09230945.asp" and read its contents.
Here is an example of how to make the request using sockets (I modified an online example for this specific purpose). NOTE: It is an example and a real implementation would need to handle the errors better:
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define RCVBUFSIZE 1024
int main(int argc, char *argv[])
{
int sock; // Socket descriptor
struct sockaddr_in servAddr; // server address
unsigned short servPort; // server port
char const *servIP; // Server IP address (dotted quad)
char const *request; // String to send to server
char recvBuffer[RCVBUFSIZE]; // Buffer for response string
unsigned int requestLen; // Length of string to send
int bytesRcvd; // Bytes read in single recv()
bool status = true;
// Initialize port
servIP = "72.233.89.199";
servPort = 80;
request = "GET /automation/n09230945.asp HTTP/1.1\r\nHost: www.whatismyip.com\r\n\r\n";
std::cout << request << std::endl;
/* Create a reliable, stream socket using TCP */
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
status = false;
}
if (status)
{
// Convert dotted decimal into binary server address.
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(servIP);
servAddr.sin_port = htons(servPort);
// Connect to the server.
if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
{
status = false;
}
}
if (status)
{
// Calculate request length.
requestLen = strlen(request);
// Send the request to the server.
if (send(sock, request, requestLen, 0) != requestLen)
{
status = false;
}
}
if (status)
{
std::cout << "My IP Address: ";
if ((bytesRcvd = recv(sock, recvBuffer, RCVBUFSIZE - 1, 0)) <= 0)
{
status = false;
}
if (status && (bytesRcvd >0) && (bytesRcvd < (RCVBUFSIZE-1)))
{
recvBuffer[bytesRcvd] = '\0';
std::cout << recvBuffer << std::endl;
}
}
close(sock);
return 0;
}
|
3,038,351 | 3,038,546 | Check whether a string is a valid filename with Qt | Is there a way with Qt 4.6 to check if a given QString is a valid filename (or directory name) on the current operating system ? I want to check for the name to be valid, not for the file to exist.
Examples:
// Some valid names
test
under_score
.dotted-name
// Some specific names
colon:name // valid under UNIX OSes, but not on Windows
what? // valid under UNIX OSes, but still not on Windows
How would I achieve this ? Is there some Qt built-in function ?
I'd like to avoid creating an empty file, but if there is no other reliable way, I would still like to see how to do it in a "clean" way.
Many thanks.
| I don't think that Qt has a built-in function, but if Boost is an option, you can use Boost.Filesystem's name_check functions.
If Boost isn't an option, its page on name_check functions is still a good overview of what to check for on various platforms.
|
3,038,375 | 3,038,525 | Convert Decimal to ASCII | I'm having difficulty using reinterpret_cast. Lets just say right off the bat that I'm not married ot reinterpret_cast. Feel free to suggest major changes. Before I show you my code I'll let you know what I'm trying to do.
I'm trying to get a filename from a vector full of data being used by a MIPS I processor I designed. Basically what I do is compile a binary from a test program for my processor, dump all the hex's from the binary into a vector in my c++ program, convert all of those hex's to decimal integers and store them in a DataMemory vector which is the data memory unit for my processor. I also have instruction memory. So When my processor runs a SYSCALL instruction such as "Open File" my C++ operating system emulator receives a pointer to the beginning of the filename in my data memory. So keep in mind that data memory is full of ints, strings, globals, locals, all sorts of stuff. When I'm told where the filename starts I do the following:
Convert the whole decimal integer element that is being pointed to to its ASCII character representation, and then search from left to right to see if the string terminates, if not then just load each character consecutively into a "filename" string. Do this until termination of the string in memory and then store filename in a table. My difficulty is generating filename from my memory.
Here is an example of what I'm trying to do:
C++ Syntax (Toggle Plain Text)
1.Index Vector NewVector ASCII filename
2.0 240faef0 128123792 'abc7' 'a'
3.0 240faef0 128123792 'abc7' 'ab'
4.0 240faef0 128123792 'abc7' 'abc'
5.0 240faef0 128123792 'abc7' 'abc7'
6.1 1234567a 243225 'k2s0' 'abc7k'
7.1 1234567a 243225 'k2s0' 'abc7k2'
8.1 1234567a 243225 'k2s0' 'abc7k2s'
9. //EXIT LOOP//
10.1 1234567a 243225 'k2s0' 'abc7k2s'
Here is the code that I've written so far to get filename (I'm just applying this to element 1000 of my DataMemory vector to test functionality. 1000 is arbitrary.):
C++ Syntax (Toggle Plain Text)
1.int i = 0;
2.int step = 1000;//top->a0;
3.string filename;
4.char *temp = reinterpret_cast<char*>( DataMemory[1000] );//convert to char
5.cout << "a0:" << top->a0 << endl;//pointer supplied
6.cout << "Data:" << DataMemory[top->a0] << endl;//my vector at pointed to location
7.cout << "Data(1000):" << DataMemory[1000] << endl;//the element I'm testing
8.cout << "Characters:" << &temp << endl;//my temporary char array
9.
10.while(&temp[i]!=0)
11.{
12. filename+=temp[i];//add most recent non-terminated character to string
13. i++;
14. if(i==4)//when 4 characters have been added..
15. {
16. i=0;
17. step+=1;//restart loop at the next element in DataMemory
18. temp = reinterpret_cast<char*>( DataMemory[step] );
19. }
20. }
21. cout << "Filename:" << filename << endl;
So the issue is that when I do the conversion of my decimal element to a char array I assume that 8 hex #'s will give me 4 characters. Why isn't this this case? Here is my output:
C++ Syntax (Toggle Plain Text)
1.a0:0
2.Data:0
3.Data(1000):4428576
4.Characters:0x7fff5fbff128
5.Segmentation fault
| If your strings are null-terminated, don't you want to do
10. while(temp[i]!=0)
instad of
10. while(&temp[i]!=0)
Not sure I understand the DataMemory structure though...
|
3,038,391 | 3,038,619 | Function pointers usage |
Possible Duplicate:
How does dereferencing of a function pointer happen?
Hi All,
Why these two codes give the same output,
Case 1:
#include <stdio.h>
typedef void (*mycall) (int a ,int b);
void addme(int a,int b);
void mulme(int a,int b);
void subme(int a,int b);
main()
{
mycall x[10];
x[0] = &addme;
x[1] = &subme;
x[2] = &mulme;
(x[0])(5,2);
(x[1])(5,2);
(x[2])(5,2);
}
void addme(int a, int b) {
printf("the value is %d\n",(a+b));
}
void mulme(int a, int b) {
printf("the value is %d\n",(a*b));
}
void subme(int a, int b) {
printf("the value is %d\n",(a-b));
}
Output:
the value is 7
the value is 3
the value is 10
Case 2 :
#include <stdio.h>
typedef void (*mycall) (int a ,int b);
void addme(int a,int b);
void mulme(int a,int b);
void subme(int a,int b);
main()
{
mycall x[10];
x[0] = &addme;
x[1] = &subme;
x[2] = &mulme;
(*x[0])(5,2);
(*x[1])(5,2);
(*x[2])(5,2);
}
void addme(int a, int b) {
printf("the value is %d\n",(a+b));
}
void mulme(int a, int b) {
printf("the value is %d\n",(a*b));
}
void subme(int a, int b) {
printf("the value is %d\n",(a-b));
}
Output:
the value is 7
the value is 3
the value is 10
| I'll simplify your question to show what I think you want to know.
Given
typedef void (*mycall)(int a, int b);
mycall f = somefunc;
you want to know why
(*f)(5, 2);
and
f(5.2);
do the same thing. The answer is that a function name both represent a "function designator". From the standard:
"A function designator is an expression that has function type. Except when it is the
operand of the sizeof operator or the unary & operator, a function designator with
type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to
function returning type’’."
When you use the indirection operator * on a function pointer, that dereference is also a "function designator". From the standard:
"The unary * operator denotes indirection. If the operand points to a function, the result is
a function designator;..."
So f(5,2) becomes essentially (*f)(5,2) by the first rule. This becomes call to function designated by f with parms (5,2) by the second. The result is that f(5,2) and (*f)(5,2) do the same thing.
|
3,038,500 | 3,040,577 | How to create a compact Qt4 vBoxLayout | I've got a vBoxLayout which contains 3 simple buttons, when I increase the size of the widget containing the layout, the spacing between the buttons increases. I would like to stop this behaviour and keep the buttons in a consistent and compact layout, regardless of the size of the parent widget. This is what I've got so far, but it doesn't change the spacing, any suggestions?, thanks.
button_layout = new QVBoxLayout ;
button_layout -> setSpacing(0);
button_layout -> setContentsMargins(0,0,0,0);
| You'll want to add a stretchable spacer to the layout:
button_layout = new QVBoxLayout ;
button_layout -> setSpacing(0);
button_layout -> setContentsMargins(0,0,0,0);
button_layout -> addStretch();
button_layout -> addWidget(button_1);
button_layout -> addWidget(button_2);
button_layout -> addWidget(button_3);
This would cause the buttons to always be on the bottom of the containing widget. Note that the horizontal portion would still stretch if your widget expanded that way; to fix that, you need to either wrap in another (HBox) layout or switch to a grid layout.
|
3,038,693 | 3,038,754 | Using UIKit from C/C++ | The questions might have been already asked, but I want to understand if iPhone's frameworks limited only to Objective-C use or it could also be accessed from C/C++ code?
For example, is it possible to use standard iPhone controls from C/C++ code? Are standard classes like NSArray, NSSet accessible from C/C++ code?
If they are, could any one give a link to some examples how to do it?
| You can mix Objective C with C++. Just rename your source file to .mm.
Some Foundation classes such as NSArray and NSSet are toll-free bridges to CoreFoundation objects like CFArray and CFSet. The latter is a pure C library that you can use without ObjC.
UIKit is a pure Objective-C framework. You could use UIKit with C and C++ as the Objective-C runtime is accessible from pure C functions such as objc_msgSend, e.g.
id UIView = objc_getClass("UIView");
SEL alloc = sel_registerName("alloc");
id view = objc_msgSend(UIView, alloc);
// ...
but it is not reliable, e.g.
objc_msgSend(view, sel_registerName("setAlpha:"), 0.4);
will not do what you want.
You could isolate the UI part and write ObjC just for that part. Create a C interface between the UI and the backend, which you may use C++ or any (allowed) languages.
|
3,038,851 | 3,038,861 | C++ Virtual Destructors | When creating prototype classes I lay out the destructor as such:
virtual ~MyClass();
When finalizing the class in a library I noticed that I cannot add 'virtual'. Is this normal, and is virtual taken into consideration or am I do something wrong?
For example; when I try to do this I get a compiler error:
virtual MyClass::~MyClass() { }
Instead doing this works:
MyClass::~MyClass() { }
My question is since I do not have to include virtual in the final code write of the destructor does the destructor still behave as a virtual destructor (since it is virtual as a prototype)?
| The virtual keyword is only used as part of the member function declaration inside of the class definition.
If the member function is defined outside of the class definition, the virtual keyword is not placed there.
|
3,039,133 | 3,039,177 | Boost::Mutex & Malloc | I'm trying to use a faster memory allocator in C++. I can't use Hoard due to licensing / cost. I was using NEDMalloc in a single threaded setting and got excellent performance, but I'm wondering if I should switch to something else -- as I understand things, NEDMalloc is just a replacement for C-based malloc() & free(), not the C++-based new & delete operators (which I use extensively).
The problem is that I now need to be thread-safe, so I'm trying to malloc an object which is reference counted (to prevent excess copying), but which also contains a mutex pointer. That way, if you're about to delete the last copy, you first need to lock the pointer, then free the object, and lastly unlock & free the mutex.
However, using malloc to create a boost::mutex appears impossible because I can't initialize the private object as calling the constructor directly ist verboten.
So I'm left with this odd situation, where I'm using new to allocate the lock and nedmalloc to allocate everything else. But when I allocate a large amount of memory, I run into allocation errors (which disappear when I switch to malloc instead of nedmalloc ~ but the performance is terrible). My guess is that this is due to fragmentation in the memory and an inability of nedmalloc and new to place nice side by side.
There has to be a better solution. What would you suggest?
| Google's malloc replacement is quite fast, thread safe by default, and easy to use. Simply link it into your application at it will replace the behavior or malloc/free and new/delete. This makes it particularly easy to re-profile your app to verify the new allocator is actually speeding things up.
|
3,039,156 | 3,039,208 | gcc c++ command line error-message parser | Are there any programs for parsing and displaying in a nice format the c++ error messages generated by gcc.
I'm really looking for something like less that I can pipe my errors into that will collapse the template parameter lists by default, maybe with some nice highlighting so that my errors are actually readable.
(Yes, it's boost's fault I have such incomprehensible errors, in case you were wondering)
| STL Error Decryptor (AKA STLFilt) can help decode them. I've had mixed results.
|
3,039,308 | 3,039,351 | Obtaining the Button Clicked after a Clicked() is emitted in Qt (C++) | I was wondering, once a clicked() is emitted by a button is there any way of finding out what button emitted it without overloading the click() function? (I have a bunch of buttons with almost the same function but different text, which is the defining element of each button).
Thanks in advance!
| Within your slot, you can call the sender() function to get the QObject that sent you the clicked() signal. It returns a QObject *. Use qobject_cast to cast the QObject * to QPushButton *.
Documentation here.
|
3,039,328 | 3,039,354 | Problem with "not declared in this scope" error | I've got:
error a1 was not declared in this scope
Can somebody please explain why this code causes that?
quiz.h
#ifndef QUIZ_H_
#define QUIZ_H_
#include "quiz.cpp" // I deleted this row
// and wrote void quiz(int i);
class A {
private:
int player;
public:
A(int initPlayer); // wrote here = 0
~A();
void foo();
};
#endif /* QUIZ_H_ */
quiz.cpp
#include "quiz.h"
#include <iostream>
using std::cout;
using std::endl;
A::A(int initPlayer = 0){ // deleted = 0
player = initPlayer;
}
A::~A(){
}
void A::foo(){
cout << player;
}
main function
#include "quiz.h"
int main()
{
quiz(7);
return 0;
}
quiz function
#include "quiz.h"
void quiz(int i)
{
A a1(i);
a1.foo();
}
after my modifications I have an error multiple definition of quiz(int)
| You should not be including the .cpp file in the header. Remove:
#include "quiz.cpp"
Also, the default value in:
A::A(int initPlayer = 0){
should be in the header file instead.
And edit your question provide the names of all your files, so we can tell you how to compile and link them.
|
3,039,456 | 3,039,594 | How to run multiple arguments in Cygwin | I've been trying to run a program that will invert the order of a string and to run it, I have to type a second argument in prompt.
int main(int argc, char* argv[])
{
string text = argv[2];
for (int num=text.size(); num>0; num--)
{
cout << text.at(num);
}
return 0;
}
e.g. ./program lorem result: merol
| #include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string text = argv[1];
for (int num=text.size() - 1; num >= 0; num--)
{
cout << text.at(num);
}
return 0;
}
You missed the includes and used string::at wrong. There are size() chars in the string but you start counting at 0. Then the loop has to run until num >= 0 and not num > 0. You also used the wrong index into argv.
This would still be an abomination of C++. A clearer way would be:
#include <iostream>
#include <string>
#include <algorithm>
int main(int argc, char* argv[])
{
std::string text = argv[1];
for(std::string::reverse_iterator it = text.rbegin(); it != text.rend(); ++it) {
std::cout << *it;
}
std::cout << std::endl;
//or if you want further usage of the reversed string
std::reverse(text.begin(), text.end());
std::cout << text;
return 0;
}
|
3,039,615 | 3,039,688 | Exceptional C++[Bug]? | I have been reading Exceptional C++ by Herb Sutter. On reaching Item 32
I found the following
namespace A
{
struct X;
struct Y;
void f( int );
void g( X );
}
namespace B
{
void f( int i )
{
f( i ); // which f()?
}
}
This f() calls itself, with infinite recursion. The reason is that the only visible f() is B::f() itself.
There is another function with signature f(int), namely the one in namespace A. If B had written "using namespace A;" or "using A::f;", then A::f(int) would have been visible as a candidate when looking up f(int), and the f(i) call would have been ambiguous between A::f(int) and B::f(int). Since B did not bring A::f(int) into scope, however, only B::f(int) can be considered, so the call unambiguously resolves to B::f(int).
But when I did the following..
namespace A
{
struct X;
struct Y;
void f( int );
void g( X );
}
namespace B
{
using namespace A;
void f( int i )
{
f( i ); // No error, why?
}
}
That means Herb Sutter has got it all wrong? If not why dont I get an error?
| There's a subtle difference between a using declaration (using A::f) and a using directive (using namespace A).
A using declaration introduces a name into the scope in which it is used so using A::f makes the call to f in the definition of B::f(int) ambiguous.
A using definition makes members of the namespace visible in the scope in which it is used, but they appear as if the name comes from the nearest common scope of the namespace introduced and the namespace in which the using directive was used. This means that using namespace A; in this case make the other f appear as if it was declared at the global scope but it is still hidden by B::f(int).
(ISO/IEC/BS 14882:2003 7.3.4 [namespace.udir] / 1 for all the standard junkies.)
|
3,039,647 | 3,039,715 | What does 'Conditional expressions can be only boolean, not integral.' mean? | What does 'Conditional expressions can be only boolean, not integral.' mean? I do not know Java and I know C++ deffenetly not enought to understend what it means.. Please help (found in http://www.javacoffeebreak.com/articles/thinkinginjava/comparingc++andjava.html in Comparing C++ and Java item 7 sub item 1)
| Conditional expressions are used by the conditional and loop control structures to determine the control flow of a program.
// conditional control structure
if (conditionalExpression) {
codeThatRunsIfConditionalExpressionIsTrue();
} else {
codeThatRunsIfConditionalExpressionIsFalse();
}
// basic loop control structure
while (conditionalExpression) {
codeThatRunsUntilConditionalExpressionIsFalse();
}
// run-at-least-once loop control structure
do {
codeThatRunsAtLeastOnceUntilConditionalExpressionIsFalse();
} while (conditionalExpression);
From a logical point of view, conditional expressions are inherently boolean (true or false). However, some languages like C and C++ allow you to use numerical expressions or even pointers as conditional expressions. When a non-boolean expression is used as a conditional expression, they are implicitly converted into comparisions with zero. For example, you could write:
if (numericalExpression) {
// ...
}
And it would mean this:
if (numericalExpression != 0) {
// ...
}
This allows for concise code, especially in pointer languages like C and C++, where testing for null pointers is quite common. However, making your code concise doesn't necessarily make it clearer. In high-level languages like C# or Java, using numerical expressions as conditional expressions is not allowed. If you want to test whether a reference to an object has been initialized, you must write:
if (myObject != null) /* (myObject) alone not allowed */ {
// ...
}
Likewise, if you want to test whether a numeric expression is zero, you must write:
if (numericalExpression != 0) /* (numericalExpression) alone not allowed */ {
// ...
}
|
3,039,767 | 3,039,802 | Learn C++ after learning C# | I'm developing a library in C# at the moment and recently bought a great book to help me out but the code snippets are in C++.
Does anyone have a link to a site/PDF that'll give me a crash course in C++? (mainly the syntax rather than pros/cons etc) because I'll be developing in C# but things like ->, ::, &, **, are giving me the shivers. Obviously the languages aren't 100% compatible but if I know what the C++ is doing from a 'theoretical' point of view I can make a stab at rewriting it in C#.
I've had a Google to find the answer but all the sites seem to be "Should I use C++ or C#?", which isn't any good to me.
Thanks in advance.
| May be too simple for you but http://www.cplusplus.com/doc/tutorial/ is a good place for people who have never seen code before to start.
|
3,039,823 | 3,039,870 | boost::unordered_map is... ordered? | I have a boost::unordered_map, but it appears to be in order, giving me an overwhelming feeling of "You're Doing It Wrong". Why is the output to this in order? I would've expected the underlying hashing algorithm to have randomized this order:
#include <iostream>
#include <boost/unordered_map.hpp>
int main()
{
boost::unordered_map<int, int> im;
for(int i = 0; i < 50; ++i)
{
im.insert(std::make_pair(i, i));
}
boost::unordered_map<int, int>::const_iterator i;
for(i = im.begin(); i != im.end(); ++i)
{
std::cout << i->first << ", " << i->second << std::endl;
}
return 0;
}
...gives me...
0, 0
1, 1
2, 2
...
47, 47
48, 48
49, 49
Upon examination of boost's source code:
inline std::size_t hash_value(int v)
{
return static_cast<std::size_t>(v);
}
...which would explain it. The answers below hold the higher level thinking, as well, which I found useful.
| While I can't speak to the boost internals as I'm not a C++ guy, I can propose a few higher-level questions that may alleviate your concerns:
1) What are the guarantees of an "unordered" map? Say you have an ordered map, and you want to create a map that does not guarantee ordering. An initial implementation may simply use the ordered map. It's almost never a problem to provide stronger guarantees than you advertise.
2) A hash function is something that hashes X -> int. If you already have an integer, you could use the identity function. While it may not be the most efficient in all cases, it could explain the behavior you're seeing.
Basically, seeing behavior like this is not necessarily a problem.
|
3,039,960 | 3,042,488 | Boost::asio::endpoint::size() and resize() | I was reading the boost endpoint documentation and saw
size() and resize() member funcs.
the documentation says: Gets the underlying size of the endpoint in the native type.
what does this size represent and where can it be used/resized ?
thanks.
| As the docs state, a boost::asio::ip::basic_endpoint is an object that:
describes an endpoint for a
version-independent IP socket.
In this case, "endpoint" usually refers to an IP address and port. Depending on the OS and the protocol you're using, the "native" representation of the endpoint (the one used by the OS for the lower-level sockets API) may be different, so basic_endpoint serves as a wrapper for the native endpoint type.
To address your question as to what size() and resize() actually do, the answer I think is "not much," other than to serve as a portable way to get the size of the underlying endpoint representation.
On UNIX-like systems (sorry, I've no details for Windows :o), the underlying endpoint type is usually struct sockaddr_in for IPv4 and struct sockaddr_in6 for IPv6 (defined in netinet/in.h). So size() would return the sizeof one of those structures, depending on how the basic_endpoint was constructed. For more info on the sockaddr family of structs, see here: http://www.retran.com/beej/sockaddr_inman.html
In fact, the code for size() is surprisingly simple if you look at it (~line 180 in boost/asio/ip/basic_endpoint.hpp). It merely calls sizeof on a typedef representing the underlying native endpoint type for the protocol of the instance. Interestingly, the resize() method seems to do pretty much nothing, other than throw an exception if the requested size is greater than the size of the underlying sockaddr_storage struct (sockaddr_storage is a struct that contains enough storage space for either sockaddr_in or sockaddr_in6). It possibly exists for future use in Asio or to adapt to future protocols, since basic_endpoint is a templated class. I'm not really sure...
As for why you'd want to use these methods of an endpoint object in day-to-day Asio programming, I can't really think of a reason.
|
3,039,986 | 3,040,154 | What Parallel computing APIs make good use of sockets? | My program uses sockets, what Parallel computing APIs could I use that would help me without obligating me to go from sockets to anything else?
When we are on a cluster with a special, non-socket infrastructure system this API would emulate something like sockets but using that infrastructure (so programs perform much faster than on sockets, but still use the sockets API).
| Are you familiar with the Message Passing Interface (MPI)? That's generally the way to go for scaling your code on parallel computers. As you noted it's not compatible with most socket APIs, but the benefits in scaling will almost certainly outweigh the costs in converting your code.
|
3,040,095 | 3,040,118 | C++ vector and struct problem win32 | I have a structure defined in my header file:
struct video
{
wchar_t* videoName;
std::vector<wchar_t*> audio;
std::vector<wchar_t*> subs;
};
struct ret
{
std::vector<video*> videos;
wchar_t* errMessage;
};
struct params{
HWND form;
wchar_t* cwd;
wchar_t* disk;
ret* returnData;
};
When I try to add my video structure to a vector of video* I get access violation reading 0xcdcdcdc1 (videoName is @ 0xcdcdcdcd, before I allocate it)
//extract of code where problem is
video v;
v.videoName = (wchar_t*)malloc((wcslen(line)+1)*sizeof(wchar_t));
wcscpy(v.videoName,line);
p->returnData->videos.push_back(&v); //error here
| I would guess that either p or p->returnData is an uninitialized/invalid pointer.
Also, this isn't causing your crash, but it will once you fix the current problem: beware of returning the pointer to a local variable. Once your function goes out of scope the local vector will be destroyed and &v will be an invalid pointer. If you want your vector to exist beyond the scope of the current function then you will need to allocate it on the heap:
vector *v = new video();
...
p->returnData->videos.push_back(v);
|
3,040,125 | 3,042,874 | How do I correlate build configurations in dependant vcproj files with different names? | I have a solution file that requires a third party library (open source). The containing solution uses the typical configuration names of "Debug" and "Release".
The third-party one has debug and release configurations for both DLL and static libraries - their names are not "Debug" and "Release".
How do I tell the solution to build the dependency first and how do I correlate which configuration to the dependent configuration?
That is, MyProject:Debug should build either 3rdParty:debug_shared or 3rdParty:debug_static.
UPDATE:
I do not wish to correlate from one to many. I just want to be able to pick one and stick with it. So in my case I would correlate Debug in the main project to 3rdParty:shared_debug.
How do I do that?
When I say build for the solution for debug I want the third-party stuff to build as well.
| In the IDE there is "configuration manager" where you can stick project configurations with solution configurations. Also there is "build dependencies" tool to choose which project should be compiled first.
|
3,040,140 | 3,040,241 | protocol buffers with C++ client and C# back-end? | How do you connect C# back-end with a C++ front-end via HTTP or web-service equivalent?
| There are three parts here; the server (sounds like C#), the client (sounds like C++) and the transport. Taking them separately, and starting with the most important:
the transport: big decision here is what shape you want the data to be in. You mention protocol buffers, so we're talking binary - but that could be:
a raw octet-stream (think: downloading an image from a web-server)
a SOAP web-service returning a stream or byte[]
the same SOAP web-service returning MTOM
Any should work; which to choose depends on the tools available. The important thing is : get a chunk of binary over the wire.
You also need to think about the data definition at this point; a .proto file can define your schema, and most protocol buffers implementations include a tool to generate matching classes.
the server: depending on the choice above, this is either going to be a handler (IHttpHandler) or a web-service class. Either way, their job is really to run some logic and return a byte stream. How you get your data is up to you, then ultimately the job is to
populate the DTO types (generated from .proto in many cases, but not strictly necessary) and run it through the serialization API, writing the result to the stream
the client: same in reverse; generate your DTOs from the .proto, and run it through the deserialization API
The various protobuf implementations (C++, C#, etc) are listed here.
|
3,040,201 | 3,040,222 | Specializing a template member function of a template class? | I have a template class that has a template member function that needs to be specialized, as in:
template <typename T>
class X
{
public:
template <typename U>
void Y() {}
template <>
void Y<int>() {}
};
Altough VC handles this correctly, apperantly this isn't standard and GCC complains: explicit specialization in non-namespace scope 'class X<T>'
I tried:
template <typename T>
class X
{
public:
template <typename U>
void Y() {}
};
template <typename T>
// Also tried `template<>` here
void X<T>::Y<int>() {}
But this causes both VC and GCC to complain.
What's the right way to do this?
| Very common problem. One way to solve it is through overloading
template <typename T>
struct type2type { typedef T type; };
template <typename T>
class X
{
public:
template <typename U>
void Y() { Y(type2type<U>()); }
private:
template<typename U>
void Y(type2type<U>) { }
void Y(type2type<int>) { }
};
|
3,040,442 | 3,040,467 | How do I convert byte to string? | Is there any fast way to convert given byte (like, by number - 65) to it's text hex representation?
Basically, I want to convert array of bytes into (I am hardcoding resources) their code-representation like
BYTE data[] = {0x00, 0x0A, 0x00, 0x01, ... }
How do I automate this Given byte -> "0x0A" string conversion?
| In C++, you can use stringstream, and ssprintf.
Some compilers may have an itoa method that will convert an integer into its textual representation.
These are portable functions. You can always add an integer to '0' to get a textual digit and likewise with 'A' and 'a'.
|
3,040,465 | 3,040,494 | Program won't compile | So below I have a code in C++ that is supposed to invert the arguments in a vector, but not the sequence. I have listed my problems as sidenotes in the code below. The invert function is supposed to invert each argument, and then the main function just outputs the inverted words in same order
For instance, program("one two three four")=ruof eerth owt eno
#include <iostream>
#include <string>
using namespace std;
int invert(string normal)
{
string inverted;
for (int num=normal.size()-1; num>=0; num--)
{
inverted.append(normal[num]); //I don't know how to get each character
//I need another command for append
}
return **inverted**; <----
}
int main(int argc, char* argv[])
{
string text;
for (int a=1; a<argc; a++)
{
text.append(invert(argv[a])); //Can't run the invert function
text.append(" ");
}
cout << text << endl;
return 0;
}
| The problem is that normal[num] is a character. append() doesn't have an overload for characters.
You can use inverted.push_back(normal[num]);
See the string API.
I should add a couple other notes:
0) Why are you returning int from invert()? inverted is a string, so you should return a string:
`string invert(string normal);`
1) Rather than using num to iterate, you can use reverse_iterators:
for (string::reverse_iterator c = normal.rbegin(); c!=normal.rend(); ++c) {
inverted.push_back(*c);
}
2) When passing strings to functions that do not get modified in the function, you should pass by reference to avoid extra string copies.
string invert(const string &normal);
3) You're traversing 0..argc, so your reversed strings will be backwards from what is expected, if I understand your requirements correctly.
|
3,040,472 | 3,040,526 | How to do HTTP transfers with MFC/C++? | How do you do HTTP transfers in MFC?
Which library would you use to access HTTP resources in MFC?
| See the MFC wrappers for the WinInet library.
|
3,040,475 | 3,040,692 | question about smart pointers | I have this snippet of the code and I must write appropriate code with class A (constructor, destructor, copy constructor, operator =), my question is do I need write smart pointers if I want that this code will work perfectly, if no, can you explain where writing smart pointers will be useful, thanks in advance
A *pa1 = new A(a2);
A const * pa2 = pa1;
A const * const pa3 = pa2;
| A smart pointer is not needed, as non of the operations following new can throw. You just need:
A *pa1 = new A(a2);
A const * pa2 = pa1;
A const * const pa3 = pa2;
delete pa1;
If this isn't what you are asking about, please clarify your question.
|
3,040,480 | 3,040,706 | C++ template function compiles in header but not implementation | I'm trying to learn templates and I've run into this confounding error. I'm declaring some functions in a header file and I want to make a separate implementation file where the functions will be defined.
Here's the code that calls the header (dum.cpp):
#include <iostream>
#include <vector>
#include <string>
#include "dumper2.h"
int main() {
std::vector<int> v;
for (int i=0; i<10; i++) {
v.push_back(i);
}
test();
std::string s = ", ";
dumpVector(v,s);
}
Now, here's a working header file (dumper2.h):
#include <iostream>
#include <string>
#include <vector>
void test();
template <class T> void dumpVector(const std::vector<T>& v,std::string sep);
template <class T> void dumpVector(const std::vector<T>& v, std::string sep) {
typename std::vector<T>::iterator vi;
vi = v.cbegin();
std::cout << *vi;
vi++;
for (;vi<v.cend();vi++) {
std::cout << sep << *vi ;
}
std::cout << "\n";
return;
}
With implementation (dumper2.cpp):
#include <iostream>
#include "dumper2.h"
void test() {
std::cout << "!olleh dlrow\n";
}
The weird thing is that if I move the code that defines dumpVector from the .h to the .cpp file, I get the following error:
g++ -c dumper2.cpp -Wall -Wno-deprecated
g++ dum.cpp -o dum dumper2.o -Wall -Wno-deprecated
/tmp/ccKD2e3G.o: In function `main':
dum.cpp:(.text+0xce): undefined reference to `void dumpVector<int>(std::vector<int, std::allocator<int> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: ld returned 1 exit status
make: *** [dum] Error 1
So why does it work one way and not the other? Clearly the compiler can find test(), so why can't it find dumpVector?
| The problem you're having is that the compiler doesn't know which versions of your template to instantiate. When you move the implementation of your function to x.cpp it is in a different translation unit from main.cpp, and main.cpp can't link to a particular instantiation because it doesn't exist in that context. This is a well-known issue with C++ templates. There are a few solutions:
1) Just put the definitions directly in the .h file, as you were doing before. This has pros & cons, including solving the problem (pro), possibly making the code less readable & on some compilers harder to debug (con) and maybe increasing code bloat (con).
2) Put the implementation in x.cpp, and #include "x.cpp" from within x.h. If this seems funky and wrong, just keep in mind that #include does nothing more than read the specified file and compile it as if that file were part of x.cpp In other words, this does exactly what solution #1 does above, but it keeps them in seperate physical files. When doing this kind of thing, it is critical that you not try to compile the #included file on it's own. For this reason, I usually give these kinds of files an hpp extension to distinguish them from h files and from cpp files.
File: dumper2.h
#include <iostream>
#include <string>
#include <vector>
void test();
template <class T> void dumpVector( std::vector<T> v,std::string sep);
#include "dumper2.hpp"
File: dumper2.hpp
template <class T> void dumpVector(std::vector<T> v, std::string sep) {
typename std::vector<T>::iterator vi;
vi = v.begin();
std::cout << *vi;
vi++;
for (;vi<v.end();vi++) {
std::cout << sep << *vi ;
}
std::cout << "\n";
return;
}
3) Since the problem is that a particular instantiation of dumpVector is not known to the translation unit that is trying to use it, you can force a specific instantiation of it in the same translation unit as where the template is defined. Simply by adding this: template void dumpVector<int>(std::vector<int> v, std::string sep); ... to the file where the template is defined. Doing this, you no longer have to #include the hpp file from within the h file:
File: dumper2.h
#include <iostream>
#include <string>
#include <vector>
void test();
template <class T> void dumpVector( std::vector<T> v,std::string sep);
File: dumper2.cpp
template <class T> void dumpVector(std::vector<T> v, std::string sep) {
typename std::vector<T>::iterator vi;
vi = v.begin();
std::cout << *vi;
vi++;
for (;vi<v.end();vi++) {
std::cout << sep << *vi ;
}
std::cout << "\n";
return;
}
template void dumpVector<int>(std::vector<int> v, std::string sep);
By the way, and as a total aside, your template function is taking a vector by-value. You may not want to do this, and pass it by reference or pointer or, better yet, pass iterators instead to avoid making a temporary & copying the whole vector.
|
3,040,484 | 3,040,556 | Need help in optimizing a drawing code ... | I needed some help in trying to optimize this code portion ... Basically here's the thing .. I'm making this 'calligraphy pen' which gives the calligraphy effect by simply drawing a lot of adjacent slanted lines ... The problem is this: When I update the draw region using update() after every single draw of a slanted line, the output is correct, in the sense that updates are done in a timely manner, so that everything 'drawn' using the pen is immediately 'seen' the drawing.. however, because a lot (100s of them) of updates are done, the program slows down a little when run on the N900 ...
When I try to do a little optimization by running update after drawing all the slanted lines (so that all lines are updated onto the drawing board through a single update() ), the output is ... odd .... That is, immediately after drawing the lines, they lines seem broken (they have vacant patches where the drawing should have happened as well) ... however, if I trigger a redrawing of the form window (say, by changing the size of the form), the broken patches are immediately fixed !! When I run this program on my N900, it gets the initial broken output and stays like that, since I don't know how to enforce a redraw in this case ...
Here is the first 'optimized' code and output (partially correct/incorrect)
void Canvas::drawLineTo(const QPoint &endPoint)
{
QPainter painter(&image);
painter.setPen(QPen(Qt::black,1,Qt::SolidLine,Qt::RoundCap,Qt::RoundJoin));
int fx=0,fy=0,k=0;
qPoints.clear();
connectingPointsCalculator2(qPoints,lastPoint.x(),lastPoint.y(),endPoint.x(),endPoint.y());
int i=0;
int x,y;
for(i=0;i<qPoints.size();i++)
{
x=qPoints.at(i).x();
y=qPoints.at(i).y();
painter.setPen(Qt::black);
painter.drawLine(x-5,y-5,x+5,y+5); **// Drawing slanted lines**
}
**//Updating only once after many draws:**
update (QRect(QPoint(lastPoint.x()-5,lastPoint.y()-5), QPoint(endPoint.x()+5,endPoint.y()+5)).normalized());
modified = true;
lastPoint = endPoint;
}
Image right after scribbling on screen:
http://img823.imageshack.us/img823/8755/59943912.png
After re-adjusting the window size, all the broken links above are fixed like they should be ..
Here is the second un-optimized code (its output is correct right after drawing, just like in the second picture above):
void Canvas::drawLineTo(const QPoint &endPoint)
{
QPainter painter(&image);
painter.setPen(QPen(Qt::black,1,Qt::SolidLine,Qt::RoundCap,Qt::RoundJoin));
int fx=0,fy=0,k=0;
qPoints.clear();
connectingPointsCalculator2(qPoints,lastPoint.x(),lastPoint.y(),endPoint.x(),endPoint.y());
int i=0;
int x,y;
for(i=0;i<qPoints.size();i++)
{
x=qPoints.at(i).x();
y=qPoints.at(i).y();
painter.setPen(Qt::black);
painter.drawLine(x-5,y-5,x+5,y+5); **// Drawing slanted lines**
**//Updating repeatedly during the for loop:**
update(QRect(QPoint(x-5,y-5), QPoint(x+5,y+5)).normalized());//.adjusted(-rad,-rad,rad,rad));
}
modified = true;
int rad = (myPenWidth / 2) + 2;
lastPoint = endPoint;
}
Can anyone see what the issue might be ?
| As I understand you should find min and max of x and y processed in your for-loop and use them in update(QRect(QPoint(minX-5, minY-5), QPoint(maxX+5, maxY+5)).normalized());
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.