question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,652,198 | 2,652,223 | Difference between a virtual function and a pure virtual function | What is the difference between a pure virtual function and a virtual function?
I know "Pure Virtual Function is a Virtual function with no body", but what does this mean and what is actually done by the line below:
virtual void virtualfunctioname() = 0
| A virtual function makes its class a polymorphic base class. Derived classes can override virtual functions. Virtual functions called through base class pointers/references will be resolved at run-time. That is, the dynamic type of the object is used instead of its static type:
Derived d;
Base& rb = d;
// if Base::f() is virtual and Derived overrides it, Derived::f() will be called
rb.f();
A pure virtual function is a virtual function whose declaration ends in =0:
class Base {
// ...
virtual void f() = 0;
// ...
A pure virtual function implicitly makes the class it is defined for abstract (unlike in Java where you have a keyword to explicitly declare the class abstract). Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions. If they do not, they too will become abstract.
An interesting 'feature' of C++ is that a class can define a pure virtual function that has an implementation.
(What that's good for is debatable.)
Note that C++11 brought a new use for the delete and default keywords which looks similar to the syntax of pure virtual functions:
my_class(my_class const &) = delete;
my_class& operator=(const my_class&) = default;
See this question and this one for more info on this use of delete and default.
|
2,652,265 | 2,652,321 | Bizarre C++ compiler problem | I have the following C++ code:
typedef istream_iterator<string> isi;
// (1)
vector<string> lineas(isi(cin), isi());
// (2)
//vector<string> lineas;
//copy(isi(cin), isi(), back_inserter(lineas));
typedef vector<string>::iterator vci;
for (vci it = lineas.begin(); it != lineas.end(); ++it)
cout << *it << endl;
However, I get the error while compiling:
test.cpp: In function 'int main(int, char**)':
test.cpp:16: error: request for member 'begin' in 'lineas', which is of non-class type 'std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >(main(int, char**)::isi, main(int, char**)::isi (*)())'
test.cpp:16: error: request for member 'end' in 'lineas', which is of non-class type 'std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >(main(int, char**)::isi, main(int, char**)::isi (*)())'
However, if I replace (1) by (2), it compiles.
I'm using g++ 4.4.0
What's wrong?
| The compiler and you are interpreting this line differently:
vector<string> lineas( isi(cin), isi() );
For you it is defining and initializing a variable lineas of type vector<string> with the constructor that takes two iterators.
For the compiler you are defining a function lineas returning a vector<string> and taking two arguments the first of which is an isiand the second of which is a function taking no arguments and returning an isi... With time you will get used to reading compiler errors and what it is reading from your code.
The simplest solution is adding an extra pair of parenthesis:
vector<string> lineas( (isi(cin)), isi() );
You can find a longer explanation in the C++ FAQ Lite here.
|
2,652,375 | 2,652,405 | Differences in variable declarations in C++ | Class A
{
};
What is the difference between A a , A* a and A* a = new A().
| A a;
Creates an instance of an A that lives on the stack using the default constructor.
A *a;
Is simply a uninitialized pointer to an A. It doesn't actually point to an A object at this point, but could. An initialized pointer (in this case, set to NULL) would look like so:
A *a = 0;
The difference here is that a null pointer does not point to any object while an uninitialized pointer might point anywhere. Initializing your pointers is a good practice to get into lest you find yourself wondering why your program is blowing up or yielding incorrect results.
Similarly, you don't want to attempt to dereference either a NULL pointer or an uninitialized pointer. But you can test the NULL pointer. Testing an uninitialized pointer yields undetermined and erroneous results. It may in fact be != 0 but certainly doesn't point anywhere you intend it to point. Make sure you initialize your pointers before testing them and test them before you attempt to dereference them.
A a = new A();
should be written as
A *a = new A();
and that creates a new A object that was allocated on the heap. The A object was created using the default constructor.
Where a default constructor is not explicitly written for a class, the compiler will implicitly create one though I don't believe the standard does not specify the state of data members for the object implicitly instantiated. For a discussion about implicit default constructors, see Martin York's response to this SO question.
|
2,652,692 | 2,653,714 | News feed APIs for general news | I'm building a database + tool that scours news feeds for a certain term. For example "food poisoning from nuts". I want to scour social media sites, news sites, major news aggregators, etc... for that term.
Question 1: What are some of the news
aggregator APIs out there?
Question 2: How Would you go about coding and
receiving only the latest news from
the API?
Edit Added schematic:
alt text http://koopics.com/news_parser.jpg
| Do you know Yahoo! Pipes? It's a very flexible feed aggregator, and you can manipulate it using YQL, which is quite powerful and has a Python librabry, python-yql :). YQL also has specific "tables" for Twitter and other services and news sources, so, depending on what you want, you might not even need Pipes.
There's a quick example of Pipes + YQL usage at http://blog.ouseful.info/2009/04/27/using-yql-with-yahoo-pipes/ , but you can play around with them at the YQL Console.
So, that's your "Question 1". But, using YQL, "Question 2" (if I understood it correctly) comes naturally, as you use it almost like regular SQL, imposing limits, ordering etc.
|
2,652,694 | 2,652,720 | Could this C cast to avoid a signed/unsigned comparison make any sense? | I'm reviewing a C++ project and see effectively the following:
std::vector<SomeType> objects;
//then later
int size = (int)objects.size();
for( int i = 0; i < size; ++i ) {
process( objects[i] );
}
Here's what I see. std::vector::size() returns size_t that can be of some size not related to the size of int. Even if sizeof(int) == sizeof(size_t) int is signed and can't hold all possible values of size_t. So the code above could only process the lower part of a very long vector and contains a bug. The right way would be to use size_t for both the size variable and the loop index.
That said I'm curious of why the author might have written this?
My only guess is that first he omitted the (int) cast and the compiler emitted something like Visual C++ C4018 warning:
warning C4018: '<' : signed/unsigned mismatch
so the author though that the best way to avoid the compiler warning would be to simply cast the size_t to int thus making the compiler shut up.
Is there any other possible sane reason for that C cast?
| No, that is probably the reason. Plus the fact that the vector would probably never be so long that it would risk truncating the size (the app. developer would know that).
And... maybe in some parts of the program he actually compared "size" with something else that was int-typed, so making size a "size_t" type would fix it in one place, but break it somewhere else.
|
2,652,738 | 2,653,125 | C++: inheritance problem | It's quite hard to explain what I'm trying to do, I'll try: Imagine a base class A which contains some variables, and a set of classes deriving from A which all implement some method bool test() that operates on the variables inherited from A.
class A {
protected:
int somevar;
// ...
};
class B : public A {
public:
bool test() {
return (somevar == 42);
}
};
class C : public A {
public:
bool test() {
return (somevar > 23);
}
};
// ... more classes deriving from A
Now I have an instance of class A and I have set the value of somevar.
int main(int, char* []) {
A a;
a.somevar = 42;
Now, I need some kind of container that allows me to iterate over the elements i of this container, calling i::test() in the context of a... that is:
std::vector<...> vec;
// push B and C into vec, this is pseudo-code
vec.push_back(&B);
vec.push_back(&C);
bool ret = true;
for(i = vec.begin(); i != vec.end(); ++i) {
// call B::test(), C::test(), setting *this to a
ret &= ( a .* (&(*i)::test) )();
}
return ret;
}
How can I do this? I've tried two methods:
forcing a cast from B::* to A::*, adapting a pointer to call a method of a type on an object of a different type (works, but seems to be bad);
using std::bind + the solution above, ugly hack;
changing the signature of bool test() so that it takes an argument of type const A& instead of inheriting from A, I don't really like this solution because somevar must be public.
EDIT:
Solution (1) is:
typedef bool (A::*)() mptr;
std::vector<mptr> vec;
vec.push_back(static_cast<mptr>(&T::test));
std::vector<mptr>::iterator i;
for(i = vec.begin(); i != vec.end(); ++i) {
(a .* (*i))();
}
I'm not sure the static cast is safe.
| This is the cleanest solution so far. It uses static:
struct A {
int somevar;
};
struct B {
static bool test(const A& a) {
return (a.somevar == 42);
}
};
std::vector<bool (*)(const A&)> vec;
template<typename T>
void push(const T&) {
vec.push_back(&T::test);
}
|
2,652,826 | 2,652,862 | Sort data in GtkTreeView non-alphabetically? | I'm trying to sort a column of data in a GTK tree view non-alphabetically. I can't seem to find a function in the GTK+ libraries that cant do such a thing.
Does anyone here know of a way to do this?
UPDATE:
Below is the code im currently trying to use:
column = gtk_tree_view_column_new();
gtk_tree_view_column_set_title(column, "Memory");
gtk_tree_view_column_set_resizable(column, TRUE);
gtk_tree_view_column_set_reorderable(column, TRUE);
gtk_tree_view_column_set_sort_indicator(column, TRUE);
/**********************************************************
gtk_tree_view_column_set_sort_column_id(column, 3);
gtk_tree_sortable_set_sort_column_id(column, 3, GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID);
**********************************************************/
gtk_tree_view_append_column(GTK_TREE_VIEW(rendered_view), column);
c_renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start(column, c_renderer, TRUE);
gtk_tree_view_column_add_attribute(column, c_renderer, "text", MEMORY);
| See the GtkTreeSortable interface, which allows you to set your custom sorting function.
Notice that the commonly used standard GtkListStore model implements GtkTreeSortable.
You might also need to call gtk_tree_sortable_set_sort_column_id() to select which column to sort on. This uses the concept of "sort column id", which is not the same as column index. You need to set the proper column id on the individual GtkTreeViewColumns when you create them, using gtk_tree_view_column_set_sort_column_id().
This tutorial might be good reading, to get a better understanding of the concepts involved.
|
2,652,944 | 2,653,043 | How to find which thread caused SEGFAULT in a post-mortem gdb session? | In my application, I handle SIGSEG to produce a backtrace and call abort() to generate a core dump.
If I now run a gdb-post-mortem analysis of the core, the thread which caused the SEGFAULT is no longer visible. Is there anything I can do so I see the cause for the SEGFAULT?
| You can use command thread apply all bt or thread apply all bt full to get backtraces of all threads. Might be useful.
By the way if you get rid of you handler will your OS create a core file?
|
2,653,130 | 2,653,167 | How to get size and location of a control placed on a dialog in MFC? | I've got the pointer to the control with function
CWnd* CWnd::GetDlgItem(int ITEM_ID)
so i've got CWnd* pointer which points to the control,
but simply can't find any method within CWnd class that will
retrieve the size and location of a given control.
Any help?
| CRect rect;
CWnd *pWnd = pDlg->GetDlgItem(YOUR_CONTROL_ID);
pWnd->GetWindowRect(&rect);
pDlg->ScreenToClient(&rect); //optional step - see below
//position: rect.left, rect.top
//size: rect.Width(), rect.Height()
GetWindowRect gives the screen coordinates of the control. pDlg->ScreenToClient will then convert them be relative to the dialog's client area, which is usually what you need.
Note: pDlg above is the dialog. If you're in a member function of the dialog class, just remove the pDlg->.
|
2,653,182 | 2,653,212 | derived class as default argument g++ | Please take a look at this code:
template<class T>
class A
{
class base
{
};
class derived : public A<T>::base
{
};
public:
int f(typename A<T>::base& arg = typename A<T>::derived())
{
return 0;
}
};
int main()
{
A<int> a;
a.f();
return 0;
}
Compiling generates the following error message in g++:
test.cpp: In function 'int main()':
test.cpp:25: error: default argument for parameter of type
'A<int>::base&' has type 'A<int>::derived'
The basic idea (using derived class as default value for base-reference-type argument) works in visual studio, but not in g++. I have to publish my code to the university server where they compile it with gcc. What can I do? Is there something I am missing?
| You cannot create a (mutable) reference to an r-value. Try to use a const-reference:
int f(const typename A<T>::base& arg = typename A<T>::derived())
// ^^^^^
Of course you can't modify arg with a const-reference. If you have to use a (mutable) reference, use overloading.
int f(base& arg) {
...
}
int f() {
derived dummy;
return f(dummy);
}
|
2,653,334 | 2,653,397 | Memory leaks detected using type char pointers in std::list | why i'm getting the memory leak errors without allocating or adding any elements to list below. should i just ignore it?
#define CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <list>
using std::list;
int main()
{
list <char*> roots;
_CrtDumpMemoryLeaks();
}
| You are not giving the roots variable a chance to be destroyed before checking for memory leaks. If roots is destroyed first, you should notice that everything is cleaned up. Try this instead.
#define CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <list>
using std::list;
int main()
{
{
list <char*> roots;
}
_CrtDumpMemoryLeaks();
}
|
2,653,555 | 2,653,795 | Can g++ fill uninitialized POD variables with known values? | I know that Visual Studio under debugging options will fill memory with a known value.
Does g++ (any version, but gcc 4.1.2 is most interesting) have any options that would
fill an uninitialized local POD structure with recognizable values?
struct something{ int a; int b; };
void foo() {
something uninitialized;
bar(uninitialized.b);
}
I expect uninitialized.b to be unpredictable randomness; clearly a bug and easily
found if optimization and warnings are turned on. But compiled with -g only, no
warning. A colleague had a case where code similar to this worked because it
coincidentally had a valid value; when the compiler upgraded, it started failing.
He thought it was because the new compiler was inserting known values into the structure
(much the way that VS fills 0xCC). In my own experience, it was just different
random values that didn't happen to be valid.
But now I'm curious -- is there any setting of g++ that would make it fill
memory that the standard would otherwise say should be uninitialized?
| I don't think such option/feature exists in gcc/g++.
For instance, all global (and static) variables reside in the .bss section, which is always initialised to zeroes. However, uninitialised ones are put in a special section within the .bss, for sake of compatibility.
If you want the them to be zeroed too, you can pass -fno-common argument to the compiler. Or, if you need it on a per-variable basis, use __attribute__ ((nocommon)).
For heap, it's possible to write your own allocator to accomplish what you described. But for stack, I don't think there's an easy solution.
|
2,653,791 | 2,653,838 | Two dimensional strings in C++ | I want to write something like 2d strings in C++.
I tried with :
vector< vector<string> > table;
int m,n,i,j;
string s;
cin>>n>>m;
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
cin>>s;
table[i][j] = s;
}
}
cout << "\n\n\n\n";
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
cout<<table[i][j]<<" ";
}
cout<<"\n";
}
no compile errors, but when i enter input like:
10 20
.....#..............
.....#..............
.....#..............
.....#..............
######..............
.......###..........
.......#.#..........
.......###...#######
.............#.....#
.............#######
It gives me segmentation fault. Why ? What's wrong ? And how it should be done so it would work correctly ? Thank you.
| The question seems to imply that the data structure needed is a set of n lines with m characters each. There are two ways to think of this -- as an nxm char matrix, or as n m-character vectors (and a string is similar but not identical to vector<char>).
So it seems you don't want a vector of vectors of strings, you want either a vector of vectors of chars, or just a vector of strings.
In any event, you have to allocate the appropriate amount of space before using table[i][j] or (slightly more idiomatic c++, but not necessary in this case since m and n are known beforehand) use something like push_back to add to the end.
Note also that the cin>>s reads an entire line from stdin (which makes the vector<string> solution a bit easier to deal with, I think).
|
2,653,797 | 2,654,004 | Why does CoUninitialize cause an error on exit? | I'm working on a C++ application to read some data from an Excel file. I've got it working, but I'm confused about one part. Here's the code (simplified to read only the first cell).
//Mostly copied from http://www.codeproject.com/KB/wtl/WTLExcel.aspx
#import "c:\Program Files\Common Files\Microsoft Shared\OFFICE11\MSO.DLL"
#import "c:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB"
#import "C:\Program Files\Microsoft Office\Office11\excel.exe" rename ("DialogBox","ExcelDialogBox") rename("RGB","ExcelRGB") rename("CopyFile", "ExcelCopyFile") rename("ReplaceText", "ExcelReplaceText") exclude("IFont", "IPicture")
_variant_t varOption((long) DISP_E_PARAMNOTFOUND, VT_ERROR);
int _tmain(int argc, _TCHAR* argv[])
{
DWORD dwCoInit = 0;
CoInitializeEx(NULL, dwCoInit);
Excel::_ApplicationPtr pExcel;
pExcel.CreateInstance(_T("Excel.Application"));
Excel::_WorkbookPtr pBook;
pBook = pExcel->Workbooks->Open("c:\\test.xls", varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption);
Excel::_WorksheetPtr pSheet = pBook->Sheets->Item[1];
Excel::RangePtr pRange = pSheet->GetRange(_bstr_t(_T("A1")));
_variant_t vItem = pRange->Value2;
printf(_bstr_t(vItem.bstrVal));
pBook->Close(VARIANT_FALSE);
pExcel->Quit();
//CoUninitialize();
return 0;
}
I had to comment out the call to CoUninitialize for the program to work. When CoUninitialize is uncommented, I get an access violation in the _Release function in comip.h on program exit.
Here's the code from comip.h, for what it's worth.
void _Release() throw()
{
if (m_pInterface != NULL) {
m_pInterface->Release();
}
}
I'm not very experienced with COM programming, so there's probably something obvious I'm missing.
Why does the call to CoUninitialize cause an exception?
What are the consequences of not calling CoUninitialize?
Am I doing something completely wrong here?
| The problem you are having is one of scope. The short answer is to move the CoInit and CoUninit into an outer scope from the Ptrs. For example:
//Mostly copied from http://www.codeproject.com/KB/wtl/WTLExcel.aspx
#import "c:\Program Files\Common Files\Microsoft Shared\OFFICE11\MSO.DLL"
#import "c:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB"
#import "C:\Program Files\Microsoft Office\Office11\excel.exe" rename ("DialogBox","ExcelDialogBox") rename("RGB","ExcelRGB") rename("CopyFile", "ExcelCopyFile") rename("ReplaceText", "ExcelReplaceText") exclude("IFont", "IPicture")
_variant_t varOption((long) DISP_E_PARAMNOTFOUND, VT_ERROR);
int _tmain(int argc, _TCHAR* argv[])
{
DWORD dwCoInit = 0;
CoInitializeEx(NULL, dwCoInit);
{
Excel::_ApplicationPtr pExcel;
pExcel.CreateInstance(_T("Excel.Application"));
Excel::_WorkbookPtr pBook;
pBook = pExcel->Workbooks->Open("c:\\test.xls", varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption);
Excel::_WorksheetPtr pSheet = pBook->Sheets->Item[1];
Excel::RangePtr pRange = pSheet->GetRange(_bstr_t(_T("A1")));
_variant_t vItem = pRange->Value2;
printf(_bstr_t(vItem.bstrVal));
pBook->Close(VARIANT_FALSE);
pExcel->Quit();
}
CoUninitialize();
return 0;
}
The longer answer is that the Ptrs destructors (which calls Release) are being called on exit from main. This is after CoUnit which, basically, shuts down the communication channel between your app and the COM object.
What are the consequences of not calling CoUnit? For short lived in-process COM servers, there really isn't any negative consequence.
|
2,654,030 | 2,656,583 | How to uncompress in QT/C++ the data compressed in PHP (gzcompres) | I have a compressed string written by PHP gzcompress($string)
I need to read it with C++ on QT.
Any help is very appreciated!
| You can use qUncompress: http://doc.trolltech.com/4.6/qbytearray.html#qUncompress
Please note that you need to prepend the expected uncompressed length.
Sample code (in C++):
QByteArray aInCompBytes;
QByteArray aInUnCompBytes;
QByteArray aInCompBytesPlusLen;
int currentCompressedLen = <<read_this>>;
int currentUnCompressedLen = <<read_this>>;
aInCompBytes.resize(currentCompressedLen);
char slideStr[currentCompressedLen];
int slideByteRead = in.readRawData(slideStr, currentCompressedLen);
aInCompBytes = QByteArray(slideStr, slideByteRead);
aInCompBytesPlusLen = aInCompBytes;
aInCompBytesPlusLen.prepend(QByteArray::number(currentUnCompressedLen));
aInUnCompBytes.resize(currentUnCompressedLen);
aInUnCompBytes = qUncompress(aInCompBytesPlusLen);
The uncompressed data will be in aInUnCompBytes.
You need to read/know the compressed len and uncompressed len.
It wasn't tested, as I don't have Qt in my machine right now.
Best regards,
T.
|
2,654,183 | 2,654,214 | Checking for a variable in the executable | Is there a way to know whether a variable is defined, by looking at the executable.
Lets say I declare
int i;
in the main function. By compiling and linking I get an executable my_program.exe.
Now, by looking inside my_program.exe, can I say if it has an int eger variable i ?
| Not unless you compile with debugging enabled.
|
2,654,378 | 2,654,395 | How can char* be a condition in for loop? | In a book I am reading there is a piece of code :
string x;
size_t h=0;
for(const char* s=x.c_str();*s;++s)
h=(h*17)^*s;
Regarding this code, I have two questions:
how can *s be a condition? what does it mean?
what does "h=(h*17)^*s" mean?
Thanks for help!
|
how can *s be a condition? what does it mean?
It means "while the value pointed to by s is not zero." C strings are null-terminated, so the last character in the string returned by c_str() will be the null character (\0, represented by all bits zero).
what does "h=(h*17)^*s" mean?
It multiplies h by 17 then xors it with the value pointed to by s.
|
2,654,415 | 2,654,607 | Proper way to reassign pointers in c++ | EDIT: I know in this case, if it were an actual class i would be better off not putting the string on the heap. However, this is just a sample code to make sure i understand the theory. The actual code is going to be a red black tree, with all the nodes stored on the heap.
I want to make sure i have these basic ideas correct before moving on (I am coming from a Java/Python background). I have been searching the net, but haven't found a concrete answer to this question yet.
When you reassign a pointer to a new object, do you have to call delete on the old object first to avoid a memory leak? My intuition is telling me yes, but i want a concrete answer before moving on.
For example, let say you had a class that stored a pointer to a string
class MyClass
{
private:
std::string *str;
public:
MyClass (const std::string &_str)
{
str=new std::string(_str);
}
void ChangeString(const std::string &_str)
{
// I am wondering if this is correct?
delete str;
str = new std::string(_str)
/*
* or could you simply do it like:
* str = _str;
*/
}
....
In the ChangeString method, which would be correct?
I think i am getting hung up on if you dont use the new keyword for the second way, it will still compile and run like you expected. Does this just overwrite the data that this pointer points to? Or does it do something else?
Any advice would be greatly appricated :D
| If you must deallocate the old instance and create another one, you should first make sure that creating the new object succeeds:
void reset(const std::string& str)
{
std::string* tmp = new std::string(str);
delete m_str;
m_str = tmp;
}
If you call delete first, and then creating a new one throws an exception, then the class instance will be left with a dangling pointer. E.g, your destructor might end up attempting to delete the pointer again (undefined behavior).
You could also avoid that by setting the pointer to NULL in-between, but the above way is still better: if resetting fails, the object will keep its original value.
As to the question in the code comment.
*str = _str;
This would be the correct thing to do. It is normal string assignment.
str = &_str;
This would be assigning pointers and completely wrong. You would leak the string instance previously pointed to by str. Even worse, it is quite likely that the string passed to the function isn't allocated with new in the first place (you shouldn't be mixing pointers to dynamically allocated and automatic objects). Furthermore, you might be storing the address of a string object whose lifetime ends with the function call (if the const reference is bound to a temporary).
|
2,654,480 | 2,654,491 | Writing BMP image in pure c/c++ without other libraries | In my algorithm, I need to create an information output. I need to write a boolean matrix into a bmp file.
It must be a monocromic image, where pixels are white if the matrix on such element is true.
Main problem is the bmp header and how to write this.
| Without the use of any other library you can look at the BMP file format. I've implemented it in the past and it can be done without too much work.
Bitmap-File Structures
Each bitmap file contains a
bitmap-file header, a
bitmap-information header, a color
table, and an array of bytes that
defines the bitmap bits. The file has
the following form:
BITMAPFILEHEADER bmfh;
BITMAPINFOHEADER bmih;
RGBQUAD aColors[];
BYTE aBitmapBits[];
... see the file format for more details
|
2,654,504 | 2,654,701 | Trying to read keyboard input without blocking (Windows, C++) | I'm trying to write a Windows console application (in C++ compiled using g++) that will execute a series of instructions in a loop until finished OR until ctrl-z (or some other keystroke) is pressed. The code I'm currently using to catch it isn't working (otherwise I wouldn't be asking, right?):
if(kbhit() && getc(stdin) == 26)
//The code to execute when ctrl-z is pressed
If I press a key, it is echoed and the application waits until I press Enter to continue on at all. With the value 26, it doesn't execute the intended code. If I use something like 65 for the value to catch, it will reroute execution if I press A then Enter afterward.
Is there a way to passively check for input, throwing it out if it's not what I'm looking for or properly reacting when it is what I'm looking for? ..and without having to press Enter afterward?
| Try ReadConsoleInput to avoid cooked mode, and GetNumberOfConsoleInputEvents to avoid blocking.
|
2,654,556 | 2,654,572 | error C2440: 'initializing' : cannot convert from 'classname *' to 'classname' | I have a class defined called extBlock.
I then make an instance of that class with this
extBlock mainBlock = new extBlock(1, 1024);
I get this error:
error C2440: 'initializing' : cannot convert from 'extBlock *' to 'extBlock'
Can anyone help me with why I am getting this error.
I have seen examples online of declaring it like this with a pointer
extBlock *mainBlock = new extBlock(1, 1024);
But if I do it this way it does not let me call the functions of mainBlock
| This isn't C#: new extBlock returns a pointer to an extBlock, and you're trying to assign that pointer to a value type (which would be an incompatible cast).
What you want to write here is
extBlock mainBlock(1, 1024);
And the reason you couldn't call methods on the second code snippet was probably because you were using the . operator instead of the -> (arrow) operator needed to dereference a pointer.
|
2,654,613 | 2,654,724 | Erasing and modifying elements in Boost MultiIndex Container | I'm trying to use a Boost MultiIndex container in my simulation. My knowledge of C++ syntax is very weak, and I'm concerned I'm not properly removing an element from the container or deleting it from memory. I also need to modify elements, and I was hoping to confirm the syntax and basic philosophy here too.
// main.cpp
...
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/tokenizer.hpp>
#include <boost/shared_ptr.hpp>
...
#include "Host.h" // class Host, all members private, using get fxns to access
using boost::multi_index_container;
using namespace boost::multi_index;
typedef multi_index_container<
boost::shared_ptr< Host >,
indexed_by<
hashed_unique< const_mem_fun<Host,int,&Host::getID> >
// ordered_non_unique< BOOST_MULTI_INDEX_MEM_FUN(Host,int,&Host::getAge) >
> // end indexed_by
> HostContainer;
typedef HostContainer::nth_index<0>::type HostsByID;
int main() {
...
HostContainer allHosts;
Host * newHostPtr;
newHostPtr = new Host( t, DOB, idCtr, 0, currentEvents );
allHosts.insert( boost::shared_ptr<Host>(newHostPtr) );
// allHosts gets filled up
int randomHostID = 4;
int newAge = 50;
modifyHost( randomHostID, allHosts, newAge );
killHost( randomHostID, allHosts );
}
void killHost( int id, HostContainer & hmap ){
HostsByID::iterator it = hmap.find( id );
cout << "Found host id " << (*it)->getID() << "Attempting to kill. hmap.size() before is " << hmap.size() << " and ";
hmap.erase( it ); // Is this really erasing (freeing from mem) the underlying Host object?
cout << hmap.size() << " after." << endl;
}
void modifyHost( int id, HostContainer & hmap, int newAge ){
HostsByID::iterator it = hmap.find( id );
(*it) -> setAge( newAge ); // Not actually the "modify" function for MultiIndex...
}
My questions are
In the MultiIndex container allHosts of shared_ptrs to Host objects, is calling allHosts.erase( it ) on an iterator to the object's shared_ptr enough to delete the object permanently and free it from memory? It appears to be removing the shared_ptr from the container.
The allhosts container currently has one functioning index that relies on the host's ID. If I introduce an ordered second index that calls on a member function (Host::getAge()), where the age changes over the course of the simulation, is the index always going to be updated when I refer to it?
What is the difference between using the MultiIndex's modify to modify the age of the underlying object versus the approach I show above?
I'm vaguely confused about what is assumed/required to be constant in MultiIndex.
Thanks in advance.
Update
Here's my attempt to get the modify syntax working, based on what I see in a related Boost example.
struct update_age {
update_age():(){} // have no idea what this really does... elicits error
void operator() (boost::shared_ptr<Host> ptr) {
ptr->incrementAge(); // incrementAge() is a member function of class Host
}
};
and then in modifyHost, I'd have hmap.modify(it,update_age). Even if by some miracle this turns out to be right, I'd love some kind of explanation of what's going on.
| shared_ptr will remove actual Host object in its destructor (if there is no other instances of shared_ptr). All objects in MultiIndex are considered constant. To modify the object you should use method modify of MultiIndex. In that case indexes will be updates if necessary.
You could use the following functor to change age field:
struct change_age
{
change_age(int age) : age_(age) {}
void operator()(boost::shared_ptr<Host> h) // shared_ptr !!!
{
h->age = age_;
}
private:
int age_;
};
Then use it as follows:
testHosts.modify( it, Host::change_age( 22 ) ); // set age to 22
|
2,654,752 | 2,654,762 | C++ equivalent of java.lang.Integer.MIN_VALUE | How can I get an equivalent of java.lang.Integer.MIN_VALUE on C++?
| #include <limits>
std::numeric_limits<int>::min();
|
2,655,157 | 2,655,296 | Is there some common way to write and read config files? | I need my program to create and edit a config file, which would contain information about set of objects, and than read it at every execution. Is there some sort of guideline for config style that i can use?
I'm using C++ on windows.
| It largely depends on the language, platform and the scope of your config files. There's for example the properties files in Java world for configuration, and others already mentioned here such as YAML.
XML is generally frowned upon for configuration, since it's very verbose. You still find it in many applications, Web frameworks, etc.
I think the best practice would be to choose the right configuration format for the job at hand. You can evaluate and try them for yourself, while considering these pointers:
What's the standard? (e.g. ini files in Windows, properties files in Java)
Is there native support in my language, or do I have to roll my own implementation?
Can my configuration format easily describe what I want to store as configuration?
I'm sure you could think of other considerations. If you update your question to clarify the scope, you'll get more useful answers.
|
2,655,374 | 2,655,406 | How to redirect the output of a system call to inside the program in C/C++? | I'm writing a program in C++ which do some special treatment for all the files in the current directory on Linux OS.
So i was thinking of using system calls such as system("ls") to get the list of all files.
but how to store it then inside my program ? ( how to redirect the output of ls to let's say a string that i declared in the program )
Thanks
| I suggest you don't call out to ls - do the job properly, using opendir/readdir/closedir to directly read the directory.
Code example, print directory entries:
// $ gcc *.c && ./a.out
#include <stdlib.h> // NULL
#include <stdio.h>
#include <dirent.h>
int main(int argc, char* argv[]) {
const char* path = argc <= 1 ? "." : argv[1];
DIR* d = opendir(path);
if (d == NULL) return EXIT_FAILURE;
for(struct dirent *de = NULL; (de = readdir(d)) != NULL; )
printf("%s/%s\n", path, de->d_name);
closedir(d);
return 0;
}
|
2,655,405 | 2,657,347 | win32 read java preference from c++ code | One of our program writes program information(window title, memory etc) in Java Preferences. On windows this is available under registry. How can I read the values written by Java program using c (or c++).
Looks like API I should use is RegGetValue. Is this guaranteed to work on Windows XP 32 bit?
The String written by java is UTF-8 encoded. How do I read such strings in windows (win32 or vc++)
Cheers,
Jayan
| I dug into this a bit. RegGetValue() is a new registry call that takes care of some underlying nastiness of the traditional way of querying the registry (RegQueryValueEx). There's some good info about the difference here: http://blogs.msdn.com/larryosterman/archive/2006/01/12/512115.aspx
If you need backwards compatibility, RegGetValue() isn't going to work, so you should be using RegQueryValueEx to read data from the registry.
And now on to what I think is the real question:
What do you get back when you use RegQueryValueEx() ?
How do you know that the values stored in the registry are in utf-8 encoding? Is it stored as a byte array in the registry, or as a REG_SZ?
Have you looked at the value using regedit? What do you see?
So if the question is how to convert a UTF-8 encoded string to an ascii null terminated string, then you should probably change the title of your question. For reference, I found this library that may be of use:
http://utfcpp.sourceforge.net
When I tried the link a few minutes ago, the server timed out - probably SF maintenance going on.
But I would suggest that you make real sure that the values in the registry aren't stored as REG_SZ entries already.
|
2,655,414 | 2,656,842 | Qt: Force QWebView to click on a web element, even one not visible on the window | So let's say I'm trying to click a link in the QWebView, here is what I have:
// extending QWebView
void MyWebView::click(const QString &selectorQuery)
{
QWebElement el = this->page()->mainFrame()->findFirstElement(selectorQuery);
if (!el)
return;
el.setFocus();
QMouseEvent pressEvent(QMouseEvent::MouseButtonPress, el.geometry().center(),
Qt::MouseButton::LeftButton, Qt::LeftButton, Qt::NoModifier);
QCoreApplication::sendEvent(this, &pressEvent);
QMouseEvent releaseEvent(QMouseEvent::MouseButtonRelease,
el.geometry().center(), Qt::MouseButton::LeftButton,
Qt::LeftButton, Qt::NoModifier);
QCoreApplication::sendEvent(this, &releaseEvent);
}
And you call it as so:
myWebView->click("a[href]"); // will click first link on page
myWebView->click("input[type=submit]"); // submits a form
THE ONLY PROBLEM IS: if the element is not visible in the window, it is impossible to click. What I mean is if you have to scroll down to see it, you can't click it. I imagine this has to do with the geometry, since the element doesn't show up on the screen it can't do the math to click it right.
Any ideas to get around this? Maybe some way to make the window behave like a billion x billion pixels but still look 200x200?
| I think calling el.evaluateJavaScript("click()"); should work. I say should work because in the past I've been using QWebElement::function() with "click" argument with success. This method did not become part of QWebElement API, however. I think authors came to conclusion it was superfluous in presence of QWebElement::evaluateJavaScript().
My similar question - How to follow a link in QWebKit? - still without answer :(
I came up with the same workaround like you here - Problem with evaluateJavaScript()
|
2,655,510 | 2,655,530 | Looking for: C/C++ Regex library that supports Named Captures | I'm thinking about writing a small application that will help me mass rename files. I currently use an application named 'RegexRenamer', which (I'm assuming) uses the .NET regex engine. The application is fine, but is sort of clunky.
So what I'm looking for is a C/C++ regex library that I can build my custom program off of. Anything that is small and lightweight is preferred (.Net seems heavy).
Thanks.
|
Perl Compatible Regular Expressions provided by the library PCRE
Oniguruma which is used by Ruby 1.9, PHP 5, and TextMate
|
2,655,612 | 2,655,633 | forward declare static function c++ | I want to forward declare a static member function of a class in another file. What I WANT to do looks like this:
BigMassiveHeader.h:
class foo
{
static void init_foos();
}
Main.cpp:
class foo;
void foo::init_foos();
int main(char** argv, int argc)
{
foo::init_foos()
}
This fails out with "error C2027: use of undefined type 'foo'"
Is there a way to accomplish what I want to do with out making init_foos a free function, or including BigMassiveHeader.h? (BigMassiveHeader.h is noticeably effecting compile time, and is included everywhere.)
| You cannot forward declare members of a class, regardless of whether they are static or not.
|
2,655,901 | 2,655,969 | C++, using one byte to store two variables | I am working on representation of the chess board, and I am planning to store it in 32 bytes array, where each byte will be used to store two pieces. (That way only 4 bits are needed per piece)
Doing it in that way, results in a overhead for accessing particular index of the board.
Do you think that, this code can be optimised or completely different method of accessing indexes can be used?
c++
char getPosition(unsigned char* c, int index){
//moving pointer
c+=(index>>1);
//odd number
if (index & 1){
//taking right part
return *c & 0xF;
}else
{
//taking left part
return *c>>4;
}
}
void setValue(unsigned char* board, char value, int index){
//moving pointer
board+=(index>>1);
//odd number
if (index & 1){
//replace right part
//save left value only 4 bits
*board = (*board & 0xF0) + value;
}else
{
//replacing left part
*board = (*board & 0xF) + (value<<4);
}
}
int main() {
char* c = (char*)malloc(32);
for (int i = 0; i < 64 ; i++){
setValue((unsigned char*)c, i % 8,i);
}
for (int i = 0; i < 64 ; i++){
cout<<(int)getPosition((unsigned char*)c, i)<<" ";
if (((i+1) % 8 == 0) && (i > 0)){
cout<<endl;
}
}
return 0;
}
I am equally interested in your opinions regarding chess representations, and optimisation of the method above, as a stand alone problem.
Thanks a lot
EDIT
Thanks for your replies. A while ago I created checkers game, where I was using 64 bytes board representation. This time I am trying some different methods, just to see what I like. Memory is not such a big problem. Bit-boards is definitely on my list to try. Thanks
| That's the problem with premature optimization. Where your chess board would have taken 64 bytes to store, now it takes 32. What has this really boughten you? Did you actually analyze the situation to see if you needed to save that memory?
Assuming that you used one of the least optimal search method, straight AB search to depth D with no heuristics, and you generate all possible moves in a position before searching, then absolute maximum memory required for your board is going to be sizeof(board) * W * D. If we assume a rather large W = 100 and large D = 30 then you're going to have 3000 boards in memory at depth D. 64k vs 32k...is it really worth it?
On the other hand, you've increased the amount of operations necessary to access board[location] and this will be called many millions of times per search.
When building chess AI's the main thing you'll end up looking for is cpu cycles, not memory. This may vary a little bit if you're targeting a cell phone or something, but even at that you're going to worry more about speed before you'll ever reach enough depth to cause any memory issues.
As to which representation I prefer...I like bitboards. Haven't done a lot of serious measurements but I did compare two engines I made, one bitboard and one array, and the bitboard one was faster and could reach much greater depths than the other.
|
2,656,047 | 2,656,130 | How do I simplify this templated vector initializer loop using lambdas or STL transform? | How do I simplify this templated vector initializer loop using lambdas or some kind of STL transform?
template<typename T>
template<typename... Args>
void InitToRandomValues(vector<T>* retval, int n, RNG& rng, Args const&... args) {
retval->resize(n);
for (auto it = retval->begin(); it != retval->end(); ++it) {
typename T::CPDDist cpd(rng, args...);
*it = T(cpd);
}
}
| I think this would work:
template<typename T>
template<typename... Args>
void InitToRandomValues(vector<T>* retval, int n, RNG& rng, Args const&... args) {
retval->resize(n);
std::generate(retval->begin(), retval->end(), [] -> T() {
typename T::CPDDist cpd(rng, args...);
return T(cpd); });
}
It isn't much of a simplification though.
|
2,656,168 | 2,656,377 | gametutorials.com questions and reviews DirectX tutorials | Just curious to know if anyone has ever used gametutorials.com products for learning directX. I was debating on whether I should buy it or not. I read online that most of his tutorials were written in the source code. It's nice to heavily comment your code but if most of the tutorial is in his code then I don't think that is necessarily the best way to do a tutorial. But anyhow, I am not sure about that, I am just checking for clarification. and checking to see if it would be a good investment.
| The problem is that the site is trying to teach you C++ and game programming at the same time. I think trying to do both at the same time is a terrible idea. Game programming is tough, and if you don't know C++ you're just setting yourself up to either fail, or get by with sloppy (and sometimes downright awful) code. So don't do both at the same time: you must learn C++ first, then get into making games. And GameTutorials isn't a resource to help you do that.*
If you don't know C++ yet, do not learn it from any online resource. Books are always a better choice here. I recommend C++ Primer or Accelerated C++. There's a more complete list here.
Both of those costs half as much, and give you a full fleshed-out C++ learning experience. The site I can't speak for, but it doesn't appear to give too fleshed out a tutorial, partly because it keeps mixing it with gaming stuff. You're better off getting tried-and-true books.
If you know C++, then you'd be wasting money on stuff you already know. Get a good Direct3D book. I don't have any modern books on me to recommend, but here's a big list. :) The two (one for DX10, one for DX9) by Luna seem to be good looking, but I don't really know. In any case, a bit more research will tell you what Direct3D book to buy.
*I don't like to speak against things that mean well, but I think the site is really just in a poor position. Teaching C++ and Game Programming shouldn't go hand-in-hand.
|
2,656,183 | 2,656,197 | Rationale in selecting Hash Key type | Guys, I have a data structure which has 25 distinct keys (integer) and a value. I have a list of these objects (say 50000) and I intend to use a hash table to store/retrieve them. I am planning to take one of these approaches.
Create a integer hash from these 25 integer keys and store it on a hash table. (Yeah! I have some means to handle collisions)
Make a string concatenation on the individual keys and use it as a hash key for the hash table. For example, if the key values are 1,2,4,6,7 then the hash key would be "12467".
Assuming that I have a total of 50000 records each with 25 distinct keys and a value, then will my second approach be a overkill when it comes to the cost of string comparisons it needs to do to retrieve and insert a record?
Some more information!
Each bucket in the hash table is a balanced binary tree.
I am using the boost library's hash_combine method to create the hash from the 25 keys.
| Absolutely use the first method, because if you use the second , you will require a hash table which has 1x10^(25m), where x is the maximum length of a key slots available.
For example, if the maximum number a key can be is 9999, m would be 4 and you'd need 1x10^100 slots in your table.
Explanation:
The idea behind a hash table is that you can randomly access any element with an efficiency of O(1) (collisions aside) because any element's hash is infact its position in the hash table. So for example, if I hash Object X and a hash of 24 is returned (or some string hash which is converted to a number, which turns out to be 24), I simply go to slot 24 of my table (often implemented as an array), and can retrieve Object X.
But if you were using your second method (concatenating 25 numbers - we'll say digits to simplify things here - together to make the hash), the largest hash would be 9999999999999999999999999. Therefore to retrieve that object from the hash table, you'd have to retrieve it from position 9999999999999999999999999 - which means your table must have at least that many spots.
And remember, with the first one - since you're using a binary tree, collisions won't really be that big a deal. Worst case scenario will be a retrieval/insertion efficiency of O(log(n)) which isn't really that bad anyways.
|
2,656,215 | 2,656,242 | Linux, static lib referring to other static lib within an executable | I am creating an application, which consists of two static libs and an executable.
Let's call the two static libs:
libusefulclass.a
libcore.a
And the application:
myapp
libcore instantiates and uses the class defined in libusefulclass (let's call it UsefulClass)
Now, if I link the application in the following way:
g++ -m64 -Wl,-rpath,/usr/local/Trolltech/Qt-4.5.4/lib -o myapp src1.o src2.o srcN.o -lusefulclass -lcore
The linker complains about the methods in libusefulclass not being found:
undefined reference to `UsefulClass::foo()'
etc.
I found a workaround for this:
If UsefulClass is also instantiated within the source files of the executable itself, the application is linked without any problems.
My question is: is there a more clean way to make libcore refer to methods defined in libusefulclass, or static libs just cannot be linked against eachother?
TIA
P.S.: In case that matters: the application is being developed in C++ using Qt, but I feel this is not a Qt problem, but a library problem in general.
| You need to specify the libraries in reverse order of dependencies, so use
g++ -m64 -Wl,-rpath,/usr/local/Trolltech/Qt-4.5.4/lib -o myapp src1.o src2.o srcN.o -lcore -lusefulclass
If there's a cyclic dependency, you might even need to specify the library twice,
g++ -m64 -Wl,-rpath,/usr/local/Trolltech/Qt-4.5.4/lib -o myapp src1.o src2.o srcN.o -lusefulclass -lcore -lusefulclass
|
2,656,278 | 2,656,305 | What's wrong with the following code? | #include <iostream>
#include <string>
using namespace std;
int main(void)
{
string a;
cin>>a;
a.erase(a.end()-1);
a.erase(a.begin()+1);
string ge = "oae";
a.insert(a.begin()+1, ge);
cout<<a<<endl;
return 0;
}
It doesn't compile and i don't know why. Can you tell me what's wrong
| http://www.cplusplus.com/reference/string/string/insert/
string& insert ( size_t pos1, const string& str );
string& insert ( size_t pos1, const string& str, size_t pos2, size_t n );
string& insert ( size_t pos1, const char* s, size_t n);
string& insert ( size_t pos1, const char* s );
string& insert ( size_t pos1, size_t n, char c );
iterator insert ( iterator p, char c );
void insert ( iterator p, size_t n, char c );
template<class InputIterator>
void insert ( iterator p, InputIterator first, InputIterator last );
Your call to std::basic_string<t>::insert does not match any of the above overloads.
a.insert(a.begin()+1, ge);
needs to be
a.insert(a.begin()+1, ge.begin(), ge.end());
or
a.insert(1, ge);
Otherwise that code is not valid.
|
2,656,345 | 2,656,414 | Writing my own implementation of stl-like Iterator in C++ | I'm currently trying to understand the intrinsics of iterators in various languages i.e. the way they are implemented.
For example, there is the following class exposing the list interface.
template<class T>
class List
{
public:
virtual void Insert( int beforeIndex, const T item ) throw( ListException ) =0 ;
virtual void Append( const T item ) =0;
virtual T Get( int position ) const throw( ListException ) =0;
virtual int GetLength() const =0;
virtual void Remove( int position ) throw( ListException ) =0;
virtual ~List() =0 {};
};
According to GoF, the best way to implement an iterator that can support different kinds of traversal is to create the base Iterator class (friend of List) with protected methods that can access List's members. The concrete implementations of Iterator will handle the job in different ways and access List's private and protected data through the base interface.
From here forth things are getting confusing. Say, I have class LinkedList and ArrayList, both derived from List, and there are also corresponding iterators, each of the classes returns. How can I implement LinkedListIterator? I'm absolutely out of ideas. And what kind of data can the base iterator class retrieve from the List (which is a mere interface, while the implementations of all the derived classes differ significantly) ?
| STL doesn't really employ abstract base classes and virtual functions. Instead it is knowingly designed not to be OO (in the sense of GoF) and built entirely on templates, aiming for "compile-time polymorphism". Templates don't care about abstract interfaces. Things work as long as they have a sufficiently similar interface (e.g if you were to call Append push_back instead, more code expecting STL compliant containers would work for you, such as std::back_insert_iterator).
A STL compliant iterator would have to overload lots of operators to behave like a pointer (as far as possible, given the limitations of the container), including *, ->, ++, -- (if bidirectional - doubly linked), == and !=.
|
2,656,366 | 2,656,693 | What's the best way to mix Ruby and other languages? (Especially C++) | I'm learning Ruby, and I'm starting to play with building extensions in C. I have Programming Ruby The Pragmatic Programmers' Guide and so I can follow that for the basic nuts and bolts. What I was wondering is if there already existed some nifty frameworks/whatever to help interoperability between Ruby and other languages, with C++ being the most important for me. I've tried googling, but the results focus on language comparisons, rather than language interoperability.
TIA,
Andy
| Take a look at SWIG. It's a nice framework for integrating C and C++ programs with other programs written in higher level languages. It was originally written to support Python, TCL, and Perl, but has been expanded to support Ruby as well.
|
2,656,373 | 2,656,388 | Using pipes inside a class in C++ | I'm trying to use this tutorial to make plots with Gnuplot in C++. However I will be using the pipe to Gnuplot from within a class, but then I run into some problems:
I've got a header file where I declare all variables etc. I need to declare the pipe-variable here too, but how do I do that?
I've tried doing it straight away, but it doesn't work:
Logger.h:
class Logger {
FILE pipe;
}
Logger.cpp:
Logger::Logger() { //Constructor
*pipe = popen("gnuplot -persist","w");
}
Gives the error Logger.cpp:28: error: no match for ‘operator=’ in ‘*((Logger*)this)->Logger::pipe = popen(((const char*)"gnuplot -persist"), ((const char*)"w"))’
Suggestions?
| your FILE needs to be a pointer to FILE
FILE *pipe;
then
pipe = popen(...)
|
2,656,382 | 2,656,386 | How do i get readdir ignore directories in C/C++? | I am reading the content of the current library with readdir, but I would like to treat only files and not directories. How do I know that I am pointing to a directory and not to a file?
| You can use lstat, and the S_ISDIR macro.
E.g. without error-checking:
struct stat buffer;
int status;
char path[PATH_MAX];
DIR *dir = opendir(dir_name);
...
struct dirent *de = readdir(dir);
sprintf(path, "%s/%s", dir_name, de->d_name);
status = lstat(path, &buffer);
if(S_ISDIR(buffer.st_mode))
{
...
}
EDIT: Fixed to include directory in lstat path (per el.pescado). As noted by R Samuel Klatchko, you may want to take a whitelist approach (S_ISREG) instead of blacklisting types as they come up.
|
2,656,494 | 2,661,727 | Java/C++ communication via pipe on Windows | I have two separate programs, one in Java and one in C++, both running on Windows.
We need to do bidirectional interprocess communication between the two.
Up until now, we were using this awkward solution of writing to text files and reading them on the other side, where the producer would generate a .lock file when it's done writing and the consumer would remove that when it's done reading... like I said, awkward.
If we were on *nix, we would use a pipe using popen() on the C++ and RadomAccessFile on the Java side. It seems to work well.
What can we do on Windows? Can we use named pipes?
Thank you.
| Take a look at google's protocol buffers: http://code.google.com/apis/protocolbuffers/docs/overview.html
This provides a serialization mechanism between Java and C++.
And then google for a C++ stream implementation for sockets and send messages between java and C++ via TCP.
|
2,656,551 | 2,656,602 | C++ stack memory still valid? | If I create an object on the stack and push it into a list, then the object loses scope (outside of the for loop in the example below) will the object still exist in the list? If the list still holds the object, is that data now invalid/possibly corrupt?
Please let me know, and please explain the reasoning..
Thanks,
jbu
class SomeObject{
public:
AnotherObject x;
}
//And then...
void someMethod()
{
std::list<SomeObject> my_list;
for(int i = 0; i < SOME_NUMBER; i++)
{
SomeObject tmp;
my_list.push_back(tmp);
//after the for loop iteration, tmp loses scope
}
my_list.front(); //at this point will my_list be full of valid SomeObjects or will the SomeObjects no longer be valid, even if they still point to dirty data
}
EDIT: so what if it were a std::list<SomeObject*> my_list; instead of list...in that case would it be invalid?
| All containers make a copy of what they store. It's a requirement that an object be copy-constructible and assignable, if it is to be used in a container.
So yes, vector, list, etc. all make a copy of your object.
An even shorter example:
struct foo {};
std::vector<foo> v;
v.push_back(foo());
// makes a copy of the temporary, which dies at the semicolon.
If it didn't make a copy, the above code would be bad.
The following code is not ok:
struct foo {};
std::vector<foo*> v;
{
foo f;
v.push_back(&f); // fine, but...
} // ...now f stops existing and...
v.front(); // ...points to a non-existent object.
|
2,656,618 | 2,656,684 | How to std::find using a Compare object? | I am confused about the interface of std::find. Why doesn't it take a Compare object that tells it how to compare two objects?
If I could pass a Compare object I could make the following code work, where I would like to compare by value, instead of just comparing the pointer values directly:
typedef std::vector<std::string*> Vec;
Vec vec;
std::string* s1 = new std::string("foo");
std::string* s2 = new std::string("foo");
vec.push_back(s1);
Vec::const_iterator found = std::find(vec.begin(), vec.end(), s2);
// not found, obviously, because I can't tell it to compare by value
delete s1;
delete s2;
Is the following the recommended way to do it?
template<class T>
struct MyEqualsByVal {
const T& x_;
MyEqualsByVal(const T& x) : x_(x) {}
bool operator()(const T& y) const {
return *x_ == *y;
}
};
// ...
vec.push_back(s1);
Vec::const_iterator found =
std::find_if(vec.begin(), vec.end(),
MyEqualsByVal<std::string*>(s2)); // OK, will find "foo"
| find can't be overloaded to take a unary predicate instead of a value, because it's an unconstrained template parameter. So if you called find(first, last, my_predicate), there would be a potential ambiguity whether you want the predicate to be evaluated on each member of the range, or whether you want to find a member of the range that's equal to the predicate itself (it could be a range of predicates, for all the designers of the standard libraries know or care, or the value_type of the iterator could be convertible both to the predicate type, and to its argument_type). Hence the need for find_if to go under a separate name.
find could have been overloaded to take an optional binary predicate, in addition to the value searched for. But capturing values in functors, as you've done, is such a standard technique that I don't think it would be a massive gain: it's certainly never necessary since you can always achieve the same result with find_if.
If you got the find you wanted, you'd still have to write a functor (or use boost), since <functional> doesn't contain anything to dereference a pointer. Your functor would be a little simpler as a binary predicate, though, or you could use a function pointer, so it'd be a modest gain. So I don't know why this isn't provided. Given the copy_if fiasco I'm not sure there's much value in assuming there are always good reasons for algorithms that aren't available :-)
|
2,656,700 | 2,656,790 | C++ Pointers, objects, etc | It may be a bit confusing, but...
Let's say I have a vector type member in a class, something like vector<Operator*> ( I have methods on my class to return Operators from this container).
Now lets say that I have a method on my class that receives an Operator object op and inserts it on the vector. What I want to know is: will I have any trouble by insert it directly into the vector (push_back(&op))? Or should I use the copy constructor to create a new Operator and then put this new one on the vector (with push_back(new Operator(op)))?
(Operator is a class I created)
| OK, let me see if I follow what you are trying to do.
You've got a class you've created called Operator.
You've got a vector <Operator *> and you're wondering if there will be issues with this.
Short answer is yes, there could be. It is about the scope of the vector because when it goes out of scope, the memory allocated on the heap for all those Operator objects that you've got pointers to in the vector will NOT be cleaned up by the vector. In an unmanaged language like c++, unless you are using a specialized class that takes care of things for you, you've got to be keenly aware of scoping and potential memory leaks.
Two questions you need to ask yourself are "Who owns the Operator objects?" and "Who is responsible for cleaning up the Operator objects that were allocated on the heap and are pointed to by the pointers in the vector?"
You can clean that memory up yourself when the destructor is called for the object that owns the vector.
I think you might want to look at this SO question that is similar. There are other solutions - using boost classes, for instance, that might be better.
|
2,656,722 | 2,656,750 | Is there a limit of stack size of a process in linux | Is there a limit on the stack size of a process in Linux? Is it simply dependent on the RAM of the machine?
I want to know this in order to limit the depth of recursive calls to a function.
| The stack is normally limited by a resource limit. You can see what the default settings are on your installation using ulimit -a:
stack size (kbytes, -s) 8192
(this shows that mine is 8MB, which is huge).
If you remove or increase that limit, you still won't be able to use all the RAM in the machine for the stack - the stack grows downward from a point near the top of your process's address space, and at some point it will run into your code, heap or loaded libraries.
|
2,656,768 | 2,656,807 | VC7.1 C1204 internal compiler error | I'm working on modifying Firaxis' Civilization 4 core game DLL. The host application is built using VC7, hence the constraint (source not provided for the host EXE).
I've been working on rewriting a large chunk of the code (focusing on low-hanging performance issues & memory leaks). I recently ran into an internal compiler error when trying to mod the code to use an array class instead of dynamically allocated 2-d arrays, I was going to use matrices from the boost lib (Civ4 is already using boost, so why not?).
Basically, the issue comes down to: if I include "boost/numeric/ublas/matrix.hpp", I run into an internal compiler error C1204.
MSDN has this to say: MSDN C1204
KB has this to say: KB 883655
So, I'm curious, is it possible to solve this error without a KB/SP being applied and dramatically reducing the complexity of the code?
Additionally, as VC7 is no longer "supported", does anyone have a valid (supported) link for a VC7 service pack?
Update:
I do not have VS2003 installed; I only have the VS2003 toolkit (i.e. the freely downloaded compiler & SDK, not the full IDE).
| The fix for KB 883655 is available in VS 2003 SP1:
VS 2003 SP1 Info
VS 2003 SP1 download
|
2,656,773 | 2,656,793 | Limiting max speed of sockets | I'm using raw sockets on windows and I'm trying to find a way to limit the max connection speed over a group of sockets.
For example I have 3 sockets to 3 servers and want to limit total download speed to 1mb.
I googled and cant find any thing related. Any ideas?
| If you want to limit the download speed to 1 MB per second, manage your recv() calls in such a way that you do not recv() more than 1 MB in a single second. Once you have read the maximum 1 MB, throttle the thread (using ThreadSleep) until the next second. That's just a simple approach.
|
2,656,802 | 2,656,831 | Copy constructor, objects, pointers | Let's say I have this:
SolutionSet(const SolutionSet &solutionSet) {
this->capacity_ = solutionSet.capacity_;
this->solutionsList_ = solutionSet.solutionsList_; // <--
}
And solutionsList_ is a vector<SomeType*> vect*. What is the correct way to copy that vector (I suppose that way I'm not doing it right..)?
| What you do now is a "shallow copy" of your solutions list - the original vector contains a list of references to solutions, and the copied vector will contain references to the same solutions. It might be exactly what you need here.
If it is not and you really need a deep copy, i.e. you would like to have every solution duplicated when creating a second solutionset, you will need to ensure your SomeType has a well-defined copy constructor and then either manually walk through all items in the new vector and do the copying:
for (int i = 0; i < solutionsList.size(); i++)
solutionsList[i] = new SomeType(solutionsList[i]);
or use pointer containers, as suggested already (which might be an overkill though).
|
2,656,809 | 2,656,945 | How do you implement syntax highlighting? | I am embarking on some learning and I want to write my own syntax highlighting for files in C++.
Can anyone give me ideas on how to go about doing this?
To me it seems that when a file is opened:
It would need to be parsed and decided what type of source file it is. Trusting the extension might not be fool-proof
A way to know what keywords/commands apply to what language
A way to decide what color each keyword/command gets
I want to do this on OS X, using C++ or Objective-C.
Can anyone provide pointers on how I might get started with this?
| Assuming that you are using Cocoa frameworks you can use UTIs to determine the file type.
For an overview of the api:
http://developer.apple.com/mac/library/documentation/FileManagement/Conceptual/understanding_utis/understand_utis_intro/understand_utis_intro.html#//apple_ref/doc/uid/TP40001319-CH201-SW1
For a list of known UTIs:
http://developer.apple.com/mac/library/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html#//apple_ref/doc/uid/TP40009259-SW1
The two keys are you probably most interested in would be kUTTypeObjectiveCPlusPlusSource and kUTTypeCPlusPlusHeader.
For the highlighting you might find the information on this page helpful as it discusses syntax highlighting with an NSView and temporary attributes:
http://www.cocoadev.com/index.pl?ImplementSyntaxHighlightingUsingTemporaryAttributes
|
2,656,943 | 2,657,184 | 2D Platformer Collision Problems With Both Axes | I'm working on a little 2D platformer/fighting game with C++ and SDL, and I'm having quite a bit of trouble with the collision detection.
The levels are made up of an array of tiles, and I use a for loop to go through each one (I know it may not be the best way to do it, and I may need help with that too). For each side of the character, I move it one pixel in that direction and check for a collision (I also check to see if the character is moving in that direction). If there is a collision, I set the velocity to 0 and move the player to the edge of the tile.
My problem is that if I check for horizontal collisions first, and the player moves vertically at more than one pixel per frame, it handles the horizontal collision and moves the character to the side of the tile even if the tile is below (or above) the character. If I handle vertical collision first, it does the same, except it does it for the horizontal axis.
How can I handle collisions on both axes without having those problems? Is there any better way to handle collision than how I'm doing it?
| XNA's 2D platformer example uses tile-based collision as well. The way they handle it there is pretty simple and may useful for you. Here's a stripped down explanation of what's in there (removing the specific-to-their-demo stuff):
After applying movement, it checks for collisions.
It determines the tiles the player overlaps based on the player's bounding box.
It iterates through all of those tiles...
If the tile being checked isn't passable:
It determines how far on the X and Y axes the player is overlapping the non-passable tile
Collision is resolved only on the shallow axis:
If Y is the shallow axis (abs(overlap.y) < abs(overlap.x)), position.y += overlap.y; likewise if X is the shallow axis.
The bounding box is updated based on the position change
Move on to the next tile...
It's in player.cs in the HandleCollisions() function if you grab the code and want to see what they specifically do there.
|
2,656,970 | 2,656,985 | Why can I do "delete p;", but not "delete (p+1);"? Why does delete require an lvalue? | On this page, it's written that
One reason is that the operand of
delete need not be an lvalue.
Consider:
delete p+1;
delete f(x);
Here, the
implementation of delete does not have
a pointer to which it can assign zero.
Adding a number to a pointer shifts it forward in memory by those many number of sizeof(*p) units.
So, what is the difference between delete p and delete p+1, and why would making the pointer 0 only be a problem with delete p+1?
| You can't do p + 1 = 0. For the same reason, if you do delete p + 1 then delete cannot zero out its operand (p+1), which is what the question on Stroustrup's FAQ is about.
The likelihood that you'd ever write delete p+1 in a program is quite low, but that's beside the point...
|
2,657,040 | 2,657,231 | udp can not receive any data | Here is my code
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.Bind(new IPEndPoint(IPAddress.Any, 0));
// Broadcast to find server
string msg = "Imlookingforaserver:" + udp_listen_port;
byte[] sendBytes4 = Encoding.ASCII.GetBytes(msg);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("255.255.255.255"), server_port);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
sck.SendTo(sendBytes4, groupEP);
//Wait response from server
Socket sck2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck2.Bind(new IPEndPoint(IPAddress.Any, udp_listen_port));
byte[] buffer = new byte[128];
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, udp_listen_port);
sck2.ReceiveFrom(buffer, ref remoteEndPoint); //<<< I never pass this line
I use above code to try find a server. First I broadcast a message and then I wait for a response from the server.
A test I made with the server written in C++ and running in Windows Vista, client written in C# and run on the same machine with server.
Problem is: The server can receive message which client broadcast, but client can not receive anything from server.
I try to write a client with C++ and it work like a charm, I think my problem is in C# client.
| I would start listening on that port before you broadcast. You're using UDP which is connectionless so you could be missing your packet.
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.Bind(new IPEndPoint(IPAddress.Any, 0));
//Wait response from server
Socket sck2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck2.Bind(new IPEndPoint(IPAddress.Any, udp_listen_port));
byte[] buffer = new byte[128];
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, udp_listen_port);
// Broadcast to find server
string msg = "Imlookingforaserver:" + udp_listen_port;
byte[] sendBytes4 = Encoding.ASCII.GetBytes(msg);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("255.255.255.255"), server_port);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
sck.SendTo(sendBytes4, groupEP);
sck2.ReceiveFrom(buffer, ref remoteEndPoint);
|
2,657,082 | 2,657,084 | Why does this cast to Base class in virtual function give a segmentation fault? | I want to print out a derived class using the operator<<. When I print the derived class, I want to first print its base and then its own content.
But I ran into some trouble (see segfault below):
class Base {
public:
friend std::ostream& operator<<(std::ostream&, const Base&);
virtual void Print(std::ostream& out) const {
out << "BASE!";
}
};
std::ostream& operator<<(std::ostream& out, const Base& b) {
b.Print(out);
return out;
}
class Derived : public Base {
public:
virtual void Print(std::ostream& out) const {
out << "My base: ";
//((const Base*)this)->Print(out); // infinite, calls this fct recursively
//((Base*)this)->Print(out); // segfault (from infinite loop?)
((Base)*this).Print(out); // OK
out << " ... and myself.";
}
};
int main(int argc, char** argv){
Derived d;
std::cout << d;
return 0;
}
Why can't I cast in one of these ways?
((const Base*)this)->Print(out); // infinite, calls this fct recursively
((Base*)this)->Print(out); // segfault (from infinite loop?)
| Try Base::Print(out)
|
2,657,100 | 2,657,153 | boost thread, test if thread is ready to join | I would like to know if there is a way to test whenever thread finished execution and is waiting for joining. My guess was the use time_join.
is there explicit way to test it?
| There's no API for that in boost::thread. I think the reason is that a thread can be detached and made not-joinable. Your best recourse is probably a wrapper and a flag.
|
2,657,178 | 2,657,183 | Returning 'c_str' from a function | This is from a small library that I found online:
const char* GetHandStateBrief(const PostFlopState* state)
{
static std::ostringstream out;
// ... rest of the function ...
return out.str().c_str()
}
In my code I am doing this:
const char *d = GetHandStateBrief(&post);
std::cout<< d << std::endl;
Now, at first d contained garbage. I then realized that the C string I am getting from the function is destroyed when the function returns because std::ostringstream is allocated on the stack. So I added:
return strdup( out.str().c_str());
And now I can get the text I need from the function.
I have two questions:
Am I understanding this correctly?
I later noticed that out (of type std::ostringstream) was allocated with static storage. Doesn't that mean that the object is supposed to stay in memory until the program terminates? And if so, then why can't the string be accessed?
| strdup allocates a copy of the string on the heap, which you have to free manually later (with free() I think). If you have the option, it would be much better to return std::string.
The static storage of out doesn't help, because .str() returns a temporary std::string, which is destroyed when the function exits.
|
2,657,228 | 2,677,283 | How can I send an std::vector<std::string> over a UNIX socket? | For my application, I need to be able to send an std::vector<std::string> over a UNIX socket(local), and get a copy of the vector on the other end of the socket. What's the easiest way to do this with O(1) messages relative to the size of the vector(i.e. without sending a message for each string in the vector)?
Since this is all on the same host, and because I control both ends of the socket, I'm not concerned with machine-specific issues such as endinness or vector/string representation.
I'd like to avoid using any external libraries for a variety of reasons.
| The solution I ended up taking was serializing the vector of strings in the form <string1>\0<string2>\0...<stringN>\0 (sending the length of the aforementioned string beforehand). While David correctly points out that this will not work for cases where std::string contains a null, I can guarantee this will not be the case for my application.
|
2,657,298 | 2,657,335 | Learning C++ from Java , trying to make a linked list | I just started learning C++ (coming from Java) and am having some serious problems with doing anything :P Currently, I am attempting to make a linked list, but must be doing something stupid cause I keep getting "void value not ignored as it ought to be" compile errors (I have it marked where it is throwing it below). If anyone could help me with what I'm doing wrong, i would be very grateful :)
Also, I am not used to having the choice of passing by reference, address, or value, and memory management in general (currently I have all my nodes and the data declared on the heap).
If anyone has any general advice for me, I also wouldn't complain :P
Key code from LinkedListNode.cpp
LinkedListNode::LinkedListNode()
{
//set next and prev to null
pData=0; //data needs to be a pointer so we can set it to null for
//for the tail and head.
pNext=0;
pPrev=0;
}
/*
* Sets the 'next' pointer to the memory address of the inputed reference.
*/
void LinkedListNode::SetNext(LinkedListNode& _next)
{
pNext=&_next;
}
/*
* Sets the 'prev' pointer to the memory address of the inputed reference.
*/
void LinkedListNode::SetPrev(LinkedListNode& _prev)
{
pPrev=&_prev;
}
//rest of class
Key code from LinkedList.cpp
#include "LinkedList.h"
LinkedList::LinkedList()
{
// Set head and tail of linked list.
pHead = new LinkedListNode();
pTail = new LinkedListNode();
/*
* THIS IS WHERE THE ERRORS ARE.
*/
*pHead->SetNext(*pTail);
*pTail->SetPrev(*pHead);
}
//rest of class
| The leading * in
*pHead->SetNext(*pTail);
*pTail->SetPrev(*pHead);
are not needed.
pHead is a pointer to a node and you call the SetNext method on it as pHead->SetNext(..) passing an object by reference.
-> has higher precedence than *
So effectively you are trying to dereference the return value of the function SetNext which does not return anything, leading to this error.
|
2,657,318 | 2,663,981 | How can I CURL POST a file using file pointer in C++ | I have a file pointer, such as the following:
FILE* f = tmpfile()
How do I use libcurl to do a HTTP POST to a URL as a field named F1?
I tried reading the file contents into a char* array but and used the following to upload:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
char* dump_buffer(void *buffer, int buffer_size){
int i;
char *ch = malloc(buffer_size);
for(i = 0;i < buffer_size;++i){
ch[i] = ((char *)buffer)[i];
//printf("%c",((char *)buffer)[i]);
}
return ch;
}
char* readFileBytes(const char *name){
FILE *file;
char *buffer;
unsigned long fileLen;
int i;
file = fopen("index.tar", "rb");
if (!file)
{
fprintf(stderr, "can't open file %s", "1.m4v");
exit(1);
}
fseek(file, 0, SEEK_END);
fileLen=ftell(file);
fseek(file, 0, SEEK_SET);
buffer=(char *)malloc(fileLen+1);
if (!buffer)
{
fprintf(stderr, "Memory error!");
fclose(file);
exit(1);
}
fread(buffer, fileLen, 1, file);
fclose(file);
char* ret = dump_buffer(&buffer, fileLen);
for(i = 0;i < fileLen;++i){
//printf("%c",ret[i]);
}
return ret;
}
int main(int argc, char *argv[])
{
CURL *curl;
CURLcode res;
struct curl_httppost *formpost=NULL;
struct curl_httppost *lastptr=NULL;
struct curl_slist *headers=NULL;
headers = curl_slist_append(headers, "Content-Type: multipart/form-data");
curl_global_init(CURL_GLOBAL_ALL);
/* Fill in the filename field */
char* p = readFileBytes("index.tar");
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "F2",
CURLFORM_FILE, "index.tar",
CURLFORM_END);
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "F1",
CURLFORM_COPYCONTENTS, (char*)p,
CURLFORM_END);
curl = curl_easy_init();
/* initalize custom header list (stating that Expect: 100-continue is not
wanted */
if(curl) {
/* what URL that receives this POST */
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_URL, "http://oceanfizz.usc.edu/upload.php");
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
/* then cleanup the formpost chain */
curl_formfree(formpost);
/* free slist */
}
return 0;
}
The output that I get is
guest-wireless-207-151-246-070:Desktop ankurcha$ ./postit2
* About to connect() to oceanfizz.usc.edu port 80 (#0)
* Trying 128.125.49.29... * connected
* Connected to oceanfizz.usc.edu (128.125.49.29) port 80 (#0)
> POST /upload.php HTTP/1.1
Host: oceanfizz.usc.edu
Accept: */*
Content-Length: 20770
Expect: 100-continue
Content-Type: multipart/form-data; boundary=----------------------------e04b6194f620
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Date: Mon, 19 Apr 2010 03:51:04 GMT
< Server: Apache/2.2.12 (Ubuntu)
< X-Powered-By: PHP/5.2.10-2ubuntu6.4
< Vary: Accept-Encoding
< Content-Length: 335
< Content-Type: text/html
<
array(1) {
["F2"]=>
array(5) {
["name"]=>
string(9) "index.tar"
["type"]=>
string(24) "application/octet-stream"
["tmp_name"]=>
string(14) "/tmp/phpyOiqXh"
["error"]=>
int(0)
["size"]=>
int(20480)
}
}
array(1) {
["F1"]=>
string(0) ""
}
Sorry, there was a problem uploading your file.
* Connection #0 to host oceanfizz.usc.edu left intact
* Closing connection #0
I was expecting F1 to have binary content.
| A HTTP POST can be done in many ways so there's not a single answer unless you specify more details in the question. One way to do POST programmatically with libcurl is as shown in this example:
http://curl.haxx.se/libcurl/c/post-callback.html
If you rather want to do a multipart formpost upload, possibly a better example is this:
http://curl.haxx.se/libcurl/c/postit2.html
|
2,657,322 | 2,657,338 | C++ catch constructor exception | I do not seem to understand how to catch constructor exception.
Here is relevant code:
struct Thread {
rysq::cuda::Fock fock_;
template<class iterator>
Thread(const rysq::cuda::Centers ¢ers,
const iterator (&blocks)[4])
: fock_()
{
if (!fock_) throw;
}
};
Thread *ct;
try { ct = new Thread(centers_, blocks); }
catch(...) { return false; } // catch never happens,
So catch statement do not execute and I get unhandled exception.
What did I do wrong? this is straight C++ using g++.
| You have to throw an object, e.g.,
throw std::exception();
throw with no operand is only used inside of a catch block to rethrow the exception being handled by the catch block.
|
2,657,501 | 2,657,513 | C++ Map of Vector of Structs? | So here's a snippet of my code:
struct dv_nexthop_cost_pair
{
unsigned short nexthop;
unsigned int cost;
};
map<unsigned short, vector<struct dv_nexthop_cost_pair> > dv;
I'm getting the following compiler error:
error: ISO C++ forbids declaration of `map' with no type
What's the proper way to declare this?
| Either you forgot to #include the right headers or didn't import the std namespace. I suggest the following:
#include <map>
#include <vector>
std::map<unsigned short, std::vector<struct dv_nexthop_cost_pair> > dv;
|
2,657,623 | 2,657,628 | Null pointer to struct which has zero size (empty)... It is a good practice? | I have some null struct, for example:
struct null_type
{
null_type& someNonVirtualMethod()
{
return *this;
}
};
And in some function i need to pass reference to this type.
Reason:
template <typename T1 = null_type, typename T2 = null_type, ... >
class LooksLikeATupleButItsNotATuple
{
public:
LooksLikeATupleButItsNotATuple(T1& ref1 = defParamHere, T2& ref2 = andHere..)
: _ref1(ref1), _ref2(ref2), ...
{
}
void someCompositeFunctionHere()
{
_ref1.someNonVirtualMethod();
_ref2.someNonVirtualMethod();
...
}
private:
T1& _ref1;
T2& _ref2;
...;
};
It is a good practice to use null reference as a default parameter?:
*static_cast<NullType*>(0)
It works on MSVC, but i have some doubts...
| Any attempts to create a null-reference result in undefined behavior. So, it is never a good practice, even if it might seem to "work".
If you really need to have a reserved value for a default parameter of reference type, declare a "dummy" object of corresponding type and use it as default value for your references.
|
2,657,691 | 2,657,747 | What is the biggest numerical primitive datatype in C++ (old/new standard) | I am a bit confused about old/new so that's my question.
What is the biggest numerical primitive datatype in the old and in the new C++ standard?
(integer and floatingpoint)
regards & many thanks in advance
Oops
| In the 1998 standard, long int and unsigned long int are the types that are at least as big as any of the standard's other integral types (§3.9.1/2-3). (They may or may not be "the biggest" types. It's possible for long int to be the same size as int, for instance. For that matter, char could be the same size, too.) The floating-point long double provides at least as much precision as the other two floating-point types (§3.9.1/8).
In the draft standard for C++0x (n3092), the types are long long int and unsigned long long int (§3.9.1/2-3). The most precise floating-point type remains long double (§3.9.1/8).
Implementations may provide bigger types beyond what the standard calls for. Check the documentation for details on that.
|
2,657,752 | 2,657,779 | extraneous calls to copy-constructor and destructor | [a follow up to this question]
class A
{
public:
A() {cout<<"A Construction" <<endl;}
A(A const& a){cout<<"A Copy Construction"<<endl;}
~A() {cout<<"A Destruction" <<endl;}
};
int main() {
{
vector<A> t;
t.push_back(A());
t.push_back(A()); // once more
}
}
The output is:
A Construction // 1
A Copy Construction // 1
A Destruction // 1
A Construction // 2
A Copy Construction // 2
A Copy Construction // WHY THIS?
A Destruction // 2
A Destruction // deleting element from t
A Destruction // deleting element from t
A Destruction // WHY THIS?
| To clearly see what's going on, I recommend include the this pointer in the output to identify which A is calling the method.
A() {cout<<"A (" << this << ") Construction" <<endl;}
A(A const& a){cout<<"A (" << &a << "->" << this << ") Copy Construction"<<endl;}
~A() {cout<<"A (" << this << ") Destruction" <<endl;}
The output I've got is
A (0xbffff8cf) Construction
A (0xbffff8cf->0x100160) Copy Construction
A (0xbffff8cf) Destruction
A (0xbffff8ce) Construction
A (0x100160->0x100170) Copy Construction
A (0xbffff8ce->0x100171) Copy Construction
A (0x100160) Destruction
A (0xbffff8ce) Destruction
A (0x100170) Destruction
A (0x100171) Destruction
So the flow can be interpreted as:
The temporary A (…cf) is created.
The temporary A (…cf) is copied into the vector (…60).
The temporary A (…cf) is destroyed.
Another temporary A (…ce) is created.
The vector is expanded, and the old A (…60) in that vector is copied to the new place (…70)
The other temporary A (…ce) is copied into the vector (…71).
All unnecessary copies of A (…60, …ce) are now destroyed.
The vector is destroyed, so the A's (…70, …71) inside are also destroyed.
Step 5 will be gone if you do
vector<A> t;
t.reserve(2); // <-- reserve space for 2 items.
t.push_back(A());
t.push_back(A());
The output will become:
A (0xbffff8cf) Construction
A (0xbffff8cf->0x100160) Copy Construction
A (0xbffff8cf) Destruction
A (0xbffff8ce) Construction
A (0xbffff8ce->0x100161) Copy Construction
A (0xbffff8ce) Destruction
A (0x100160) Destruction
A (0x100161) Destruction
|
2,657,768 | 2,660,112 | C++ DLL-Linking UnResolved Externals | I have a rather big Core project that I'm working with, I'm attempting to adapt it to use a DLL Engine I've built, I'm getting a bunch of errors like:
unresolved external symbol "private: static class
When including some of the headers from the Core in the DLL, the class is exported via __declspec(dllexport) but any header with static members throws out a crapload of errors regarding the static members.
This is a rather big project, I can't exactly run around removing every static class member I see, is there anyway around this kind of thing?
A basic example of a class that's being imported:
class __declspec(dllexport) MyClass
{
public:
static bool m_someVar;
}
For clarity sake I'd just like to address that m_someVar is defined/declared (forget the term) in the classes implementation file
| When you compile the Core you want these functions to be dllexport; However, when you compile the DLL, you want them to be dllimport. In your case, you're always defining them as dllexport, thus when you link the DLL it complains that you've declared a function (and even said you'd export it) without ever defining it.
The solution is simple. Instead of manually __declspecing, create a macro based on whether you're the Core or the DLL:
#ifndef I_AM_A_DLL
#define EXPORT __declspec(dllexport)
#define IMPORT __declspec(dllimport)
#else
#define EXPORT __declspec(dllimport)
#define IMPORT __declspec(dllexport)
#endif
Use EXPORT for functions in the Core and IMPORT for functions in external DLLs:
class EXPORT MyClass
{
public:
static bool m_someVar;
}
|
2,657,819 | 2,657,829 | What does "|=" operation mean in C++? | I have the following code and I can't understand what does it mean:
var1 |= var2>0 ? 1 : 2;
Anyone can help me please!
| if (var2 > 0)
var1 = var1 | 1;
else
var1 = var1 | 2;
It's bitwise-or.
|
2,658,106 | 2,658,119 | How to protect code from crashes in this situation | int arr[ 5 ] = { 0 };
int i = 8; // out of bounds
arr[ i ] = 8;
I know that I can just check i like this if( i < 0 || i > 5 ) ....
I also know about SEH in Visual Studio, but it looks like not working solution.
__try { /* code */ }
__except(GetExceptionCode() == EXCEPTION_ARRAY_BOUNDS_EXCEEDED)
This is not working. As I see SEH working in situations like divide to 0, access protected pages ... How can I protect my program from crashes?
| There is no guarantee that SEH will catch this - it depends on your hardware detecting the access , which does not happen for all invalid array accesses. If you want to be sure of catching it, use the standard C++ std::vector container instead of an array, and access it via its at() member function, rather than the [] operator - this will raise a standard C++ exception if the access is invalid.
|
2,658,215 | 36,107,046 | How do I create both a .lib file and an .exe file in Visual C++? | I currently have a console project which creates an .exe file; I want it to also create a .lib file so other projects, compiled as DLLs, would be able to call functions from the original project.
I know it is possible, but I couldn't find how to do that. How do I tell the linker to also link a .lib?
| Posting this just as a reference I know the original post was posted long time ago but this still applies to anyone who needs a solution to this problem.
Go to the project you want to make a .lib file for and follow these steps:
Right click on the project.
Select Properties.
Select Build Events.
Select Pre-Link Event .
Finally in the Command Line paste this:
@ECHO ON
@ECHO "$(VC_ExecutablePath_x86)\lib.exe" /out:"$(OutDir)$(ProjectName).lib" "$(IntermediateOutputPath)*.obj"
"$(VC_ExecutablePath_x86)\lib.exe" /out:"$(OutDir)$(ProjectName).lib" "$(IntermediateOutputPath)*.obj"
This will call the lib tool to generate the lib file out of the generated object files.
|
2,658,413 | 2,659,153 | How to enable nullptr from C++0x in the Visual C++ 2010? | I wonder how can I enable the nullptr in the just released Visual Studio 2010. (C++ project, not managed).
This is one of the new features but it is not available by default and looking inside the documentation at http://msdn.microsoft.com/en-us/library/4ex65770(VS.100).aspx it seams that it is enabled by /clr but this is managed!
Is this a feature added only for .NET?
| I simply created a new C++ Win32 console project in VS2010RC and nullptr keyword was just available to use as they have shown in the examples.
|
2,658,556 | 2,658,598 | Why is there ambiguity in this diamond pattern? | #include <iostream>
using namespace std;
class A { public: void eat(){ cout<<"A";} };
class B: public A { public: void eat(){ cout<<"B";} };
class C: public A { public: void eat(){ cout<<"C";} };
class D: public B,C { public: void eat(){ cout<<"D";} };
int main(){
A *a = new D();
a->eat();
}
I am not sure this is called diamond problem or not, but why doesn't this work?
I have given the defination for eat() for D. So, it doesn't need to use either B's or C's copy (so, there should be no problem).
When I said, a->eat() (remember eat() is not virtual), there is only one possible eat() to call, that of A.
Why then, do I get this error:
'A' is an ambiguous base of 'D'
What exactly does A *a = new D(); mean to the compiler??
and
Why does the same problem not occur when I use D *d = new D();?
| Imagine a slightly different scenario
class A { protected: int a; public: void eat(){ a++; cout<<a;} };
class B: public A { public: void eat(){ cout<<a;} };
class C: public A { public: void eat(){ cout<<a;} };
class D: public B,C { public: void eat(){ cout<<"D";} };
int main(){
A *a = new D();
a->eat();
}
If this would work, would it increment the a in B or the a in C? That's why it's ambiguous. The this pointer and any non-static data member is distinct for the two A subobjects (one of which is contained by the B subobject, and the other by the C subobject). Try changing your code like this and it will work (in that it compiles and prints "A")
class A { public: void eat(){ cout<<"A";} };
class B: public A { public: void eat(){ cout<<"B";} };
class C: public A { public: void eat(){ cout<<"C";} };
class D: public B, public C { public: void eat(){ cout<<"D";} };
int main(){
A *a = static_cast<B*>(new D());
// A *a = static_cast<C*>(new D());
a->eat();
}
That will call eat on the A subobject of B and C respectively.
|
2,658,711 | 2,658,736 | Warning about data loss c++/c | I am getting a benign warning about possible data loss
warning C4244: 'argument' : conversion from 'const int' to 'float', possible loss of data
Question
I remember as if float has a larger precision than int. So how can data be lost if I convert from a smaller data type (int) to a larger data type (float)?
| Because float numbers are not precise. You cannot represent every possible value an int can hold into a float, even though the maximum value of a float is much higher.
For instance, run this simple program:
#include <stdio.h>
int main()
{
for(int i = 0; i < 2147483647; i++)
{
float value = i;
int ivalue = value;
if(i != ivalue)
printf("Integer %d is represented as %d in a float\n", i, ivalue);
}
}
You'll quickly see that there are thousands billions of integers that can't be represented as floats. For instance, all integers between the range 16,777,219 and 16,777,221 are represented as 16,777,220.
EDIT again Running that program above indicates that there are 2,071,986,175 positive integers that cannot be represented precisely as floats. Which leaves you roughly with only 100 millions of positive integer that fit correctly into a float. This means only one integer out of 21 is right when you put it into a float.
I expect the numbers to be the same for the negative integers.
|
2,658,983 | 2,663,324 | Best C++ development environment in Linux | I have some experience with Eclipse and Qt creator and am somewhat disappointed in their debuggers, less so in their editors. On Windows, I like Visual Studio for debugging and SlickEdit for editing (SE is also available on Linux). Is there an IDE that is somehow better than the two mentioned?
| I definitely recommend Eclipse and the CDT plugin. Emacs would be my preferred choice if you only need a good editor and not a full IDE.
I use Eclipse almost every day on Linux, mostly for C++ programming these days. The CDT plugin is really good because it is very well integrated with the g++ compiler and the gdb debugger. On top of that, the really strong feature of CDT is the code indexer - i.e. what Microsoft calls "intellisense" for Visual Studio. The CDT Indexer is so sophisticated it is almost like a compiler, in that it really understands your code as you type it. Very often it allows me to find errors even before I build my project. Also Eclipse can handle very large source trees, especially if you run it with a 64-bit JVM.
Eclipse is a great IDE with a lot of users, and if you don't know any other IDE you may want to start with it. Because it supports many languages and has so many tools, even if you switch to another project with different technologies you can still keep your IDE. So you only need to learn one tool (the same can be said for Emacs).
|
2,659,065 | 2,659,079 | C++ boost thread reusing threads | I am trying to accomplish something like this:
thread t; // create/initialize thread
t.launch(); // launch thread.
t.wait(); // wait
t.launch(); // relaunch the same thread
How to go about implementing something like this using boost threads?
in essence, I need persistent relaunch-able thread.
I would like to avoid work queue, as implemented in my case is somewhat difficult
Thanks
| You would just make the thread run in a loop. It attempts to take a unit of "work" from a queue, carries out the work, and then goes back to the queue. When the queue is empty it waits.
Then from another thread you can insert work items into the queue so that the thread will carry them out.
Reading your question again, are you saying that you want your master thread to notify the worker thread to begin working, but then the master thread must immediately begin waiting for the worker to finish? This would mean that only one thread is ever running at a time. There would be no point to that. Threads are designed for concurrent execution.
Assuming that isn't what you want, then I'm wondering what could be simpler than a simple worker thread running off a queue. A thread is either working or waiting. So you need some data structure that allows communication between master and worker, such that the worker can wait for a work item to arrive and the master can send a work item, which will wake up the worker, and then when the work item is completed, the worker waits for another one.
|
2,659,116 | 2,659,142 | How does virtual inheritance solve the "diamond" (multiple inheritance) ambiguity? | class A { public: void eat(){ cout<<"A";} };
class B: virtual public A { public: void eat(){ cout<<"B";} };
class C: virtual public A { public: void eat(){ cout<<"C";} };
class D: public B,C { public: void eat(){ cout<<"D";} };
int main(){
A *a = new D();
a->eat();
}
I understand the diamond problem, and above piece of code does not have that problem.
How exactly does virtual inheritance solve the problem?
What I understand:
When I say A *a = new D();, the compiler wants to know if an object of type D can be assigned to a pointer of type A, but it has two paths that it can follow, but cannot decide by itself.
So, how does virtual inheritance resolve the issue (help compiler take the decision)?
| You want: (Achievable with virtual inheritance)
A
/ \
B C
\ /
D
And not: (What happens without virtual inheritance)
A A
| |
B C
\ /
D
Virtual inheritance means that there will be only 1 instance of the base A class not 2.
Your type D would have 2 vtable pointers (you can see them in the first diagram), one for B and one for C who virtually inherit A. D's object size is increased because it stores 2 pointers now; however there is only one A now.
So B::A and C::A are the same and so there can be no ambiguous calls from D. If you don't use virtual inheritance you have the second diagram above. And any call to a member of A then becomes ambiguous and you need to specify which path you want to take.
Wikipedia has another good rundown and example here
|
2,659,134 | 2,659,147 | C++ problem with string stream istringstream | I am reading a file in the following format
1001 16000 300 12.50
2002 24000 360 10.50
3003 30000 300 9.50
where the items are: loan id, principal, months, interest rate.
I'm not sure what it is that I am doing wrong with my input string stream, but I am not reading the values correctly because only the loan id is read correctly. Everything else is zero. Sorry this is a homework, but I just wanted to know if you could help me identify my error.
if( inputstream.is_open() ){
/** print the results **/
cout << fixed << showpoint << setprecision(2);
cout << "ID " << "\tPrincipal" << "\tDuration" << "\tInterest" << "\tPayment" <<"\tTotal Payment" << endl;
cout << "---------------------------------------------------------------------------------------------" << endl;
/** assign line read while we haven't reached end of file **/
string line;
istringstream instream;
while( inputstream >> line ){
instream.clear();
instream.str(line);
/** assing values **/
instream >> loanid >> principal >> duration >> interest;
/** compute monthly payment **/
double ratem = interest / 1200.0;
double expm = (1.0 + ratem);
payment = (ratem * pow(expm, duration) * principal) / (pow(expm, duration) - 1.0);
/** computer total payment **/
totalPayment = payment * duration;
/** print out calculations **/
cout << loanid << "\t$" << principal <<"\t" << duration << "mo" << "\t" << interest << "\t$" << payment << "\t$" << totalPayment << endl;
}
}
| You are not reading linewise. Replace the condition by
while( getline(inputstream, line) )
If you use operator>> it will extract only the first word to line.
|
2,659,149 | 2,659,154 | How to inherit methods from a parent class in C++ | When inheriting classes in C++ I understand members are inherited. But how does one inherit the methods as well?
For example, in the below code, I'd like the method "getValues" to be accessible not through just CPoly, but also by any class that inherits it. So one can call "getValues" on CRect directly.
class CPoly {
private:
int width, height;
public:
void getValues (int* a, int* b)
{ *a=width; *b=height;}
};
class CRect: public CPoly {
public:
int area ()
{ return (width * height); }
};
In other words, is there any way to inherit methods for simple generic methods like getters and setters?
| You can call getValues by using CRect, because getValues is inherited. The term "methods" is not defined by C++. If you refer to non-static member functions - they are members and are inherited to derived classes.
Your error is not that getValues isn't inherited, but that you try to access the inaccessible members width and height.
|
2,659,248 | 2,659,275 | How can I find the minimum value in a map? | I have a map and I want to find the minimum value (right-hand side) in the map. Here is how I did it:
bool compare(std::pair<std::string ,int> i, pair<std::string, int> j) {
return i.second < j.second;
}
////////////////////////////////////////////////////
std::map<std::string, int> mymap;
mymap["key1"] = 50;
mymap["key2"] = 20;
mymap["key3"] = 100;
std::pair<char, int> min = *min_element(mymap.begin(), mymap.end(), compare);
std::cout << "min " << min.second<< " " << std::endl;
The code above works fine and I'm able to get the minimum value. However, when I put this code inside my class as follows, it doesn't seem to work:
int MyClass::getMin(std::map<std::string, int> mymap) {
std::pair<std::string, int> min = *min_element(mymap.begin(), mymap.end(),
(*this).compare);
// Error probably due to "this".
return min.second;
}
bool MyClass::compare(
std::pair<std::string, int> i, std::pair<std::string, int> j) {
return i.second < j.second;
}
How can I make the code work with my class? Also, is there a better solution which doesn't require writing the additional compare function?
| You have a few options. The "best" way to do this is with a functor, this is guaranteed to be the fastest to call:
typedef std::pair<std::string, int> MyPairType;
struct CompareSecond
{
bool operator()(const MyPairType& left, const MyPairType& right) const
{
return left.second < right.second;
}
};
int MyClass::getMin(std::map<std::string, int> mymap)
{
std::pair<std::string, int> min
= *min_element(mymap.begin(), mymap.end(), CompareSecond());
return min.second;
}
(You can also nest the CompareSecond class inside MyClass.
With the code you have now, you can easily modify it to work, however. Just make the function static and use the correct syntax:
static bool
MyClass::compare(std::pair<std::string, int> i, std::pair<std::string, int> j)
{
return i.second < j.second;
}
int MyClass::getMin(std::map<std::string, int> mymap)
{
std::pair<std::string, int> min = *min_element(mymap.begin(), mymap.end(),
&MyClass::compare);
return min.second;
}
|
2,659,450 | 2,659,458 | Internal class and access to external members | I always thought that internal class has access to all data in its external class but having code:
template<class T>
class Vector
{
template<class T>
friend
std::ostream& operator<<(std::ostream& out, const Vector<T>& obj);
private:
T** myData_;
std::size_t myIndex_;
std::size_t mySize_;
public:
Vector():myData_(nullptr),
myIndex_(0),
mySize_(0)
{ }
Vector(const Vector<T>& pattern);
void insert(const T&);
Vector<T> makeUnion(const Vector<T>&)const;
Vector<T> makeIntersection(const Vector<T>&)const;
class Iterator : public std::iterator<std::bidirectional_iterator_tag,T>
{
private:
T** itData_;
public:
Iterator()//<<<<<<<<<<<<<------------COMMENT
{ /*HERE I'M TRYING TO USE ANY MEMBER FROM Vector<T> AND I'M GETTING ERR SAYING:
ILLEGAL CALL OF NON-STATIC MEMBER FUNCTION*/}
Iterator(T** ty)
{
itData_ = ty;
}
Iterator operator++()
{
return ++itData_;
}
T operator*()
{
return *itData_[0];
}
bool operator==(const Iterator& obj)
{
return *itData_ == *obj.itData_;
}
bool operator!=(const Iterator& obj)
{
return *itData_ != *obj.itData_;
}
bool operator<(const Iterator& obj)
{
return *itData_ < *obj.itData_;
}
};
typedef Iterator iterator;
iterator begin()const
{
assert(mySize_ > 0);
return myData_;
}
iterator end()const
{
return myData_ + myIndex_;
}
};
See line marked as COMMENT.
So can I or I can't use members from external class while in internal class?
Don't bother about naming, it's not a Vector it's a Set.
Thank you.
| You need to pass an instance of the external class to the internal class. In other words, your Iterator class must have a reference (or pointer) to an instance of Vector handy. The best way to do this is to have the Iterator constructor take a reference to a Vector.
Iterator(Vector& v) : vec_(v)
{
vec_.do_something();
}
|
2,659,513 | 2,659,529 | How to get source code of a Windows executable? | I've got some old Windows executable files. How can I edit them with Visual Studio 2010? What are the ways to see an exe's source code?
| You can't get the C++ source from an exe, and you can only get some version of the C# source via reflection.
|
2,659,625 | 2,747,185 | how to clear XFixes regions | I'm writing some low level code for X11 platform. To achieve best data copying performance I use XFixes/XDamage extensions.
How can I clear the contents of XFixes region after one refresh cycle? Or do they clean themselves after I use XFixesSetPictureClipRegion?
My code is something like that:
Display xdpy;
XShamPixmap pixmap_;
XFixesRegion region_;
damage_event_callback(damage_geometry_t geometry, XDamage damage,...) {
unsigned curr_region = XFixesCreateRegion(xdpy, 0, 0);
XDamageSubtract(xdpy, damage, None, curr_region);
XFixesTranslateRegion( xdpy, curr_region, geometry.left(), geometry.top() );
XFixesUnionRegion (xdpy, region_, region_, curr_region);
}
process_damage_events(...) {
XFixesSetPictureClipRegion( xdpy, pixmap_, 0, 0, region_);
XCopyArea (xdpy, window_->id(),
pixmap_, XDefaultGC(xdpy, XDefaultScreen(xdpy)),
0,0,width(),height(),0,0);
/*Should clear region_ here
*/
...
}
Currently I clear the region by deleting and recreating, but I guess it's not the best way to do that.
| I'm not sure what you mean by clearing the region; you mean unsetting the clip on your picture, or freeing the region?
To unset the clip my guess is you'd set the clip region to None
To free the region XFixesDestroyRegion()
To make the region empty you can probably XFixesSetRegion(dpy, region, NULL, 0) but I'm not sure that will change the clip on the picture unless you XFixesSetPictureClipRegion again.
|
2,659,704 | 2,659,750 | How does sizeof calculate the size of structures | I know that a char and an int are calculated as being 8 bytes on 32 bit architectures due to alignment, but I recently came across a situation where a structure with 3 shorts was reported as being 6 bytes by the sizeof operator. Code is as follows:
#include <iostream>
using namespace std ;
struct IntAndChar
{
int a ;
unsigned char b ;
};
struct ThreeShorts
{
unsigned short a ;
unsigned short b ;
unsigned short c ;
};
int main()
{
cout<<sizeof(IntAndChar)<<endl; // outputs '8'
cout<<sizeof(ThreeShorts)<<endl; // outputs '6', I expected this to be '8'
return 0 ;
}
Compiler : g++ (Debian 4.3.2-1.1) 4.3.2. This really puzzles me, why isn't alignment enforced for the structure containing 3 shorts?
| That's because int is 4 bytes, and has to be aligned to a 4-bytes boundary. This means that ANY struct containing an int also has to be aligned to at least 4-bytes.
On the other hand, short is 2 bytes, and needs alignment only to a 2-bytes boundary. If a struct containing shorts does not contain anything that needs a larger alignment, the struct will also be aligned to 2-bytes.
|
2,659,779 | 2,659,907 | C++ Converting image to integer array | How would I go about converting the pixels in an image (.png file) to an integer array, where each pixel is converted to its ARGB integer equivalent? Not a 2D integer array by the way, a 1D one (where access is through array[row*width+col]).
Thanks.
| Once you have read image data to some buffer, ordinary cast should do the trick:
GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file ("image.png", NULL);
unsigned char *pixels = gdk_pixbuf_get_pixels (pixbuf);
int *array = reinterpret_cast<int*>(pixels);
Example uses GdkPixbuf library, but other libraries should be similar.
|
2,659,815 | 2,663,598 | Qt double click check left button mouse | I need to run slot only on doubleClick with left button mouse, instead of both.
// this->myComponent is a QTableView
connect(this -> myComponent, SIGNAL (doubleClicked (const QModelIndex & )), this,
SLOT (performSomeAction(const QModelIndex & )));
With this event, double click works in both cases, but needed only with left button click.
How I can do it?
this -> myComponent => QTableView
| I found the following solution:
this -> myComponent -> viewport() -> installEventFilter(this);
bool MyClass::eventFilter(QObject *obj, QEvent *event) {
this -> event = event;
return QWidget::eventFilter(obj, event);
}
...
if (this -> event -> type() == QEvent::MouseButtonDblClick) {
QMouseEvent * mouseEvent = static_cast <QMouseEvent *> (event);
if (mouseEvent -> button() == Qt::LeftButton) {
// do something....
}
}
|
2,659,834 | 2,659,848 | How to determine magnitude of trigonometric function? C++ | > if (((test>=0) && (test<=90)) || ((test>270) && (test<=360))){n_y=1;}
> else {n_y=-1;}
I need the magnitude of trigonometric function in order to determine the sign of the trigonometric function for an angle falling into a particular quadrant.
My plan is to replace the code above with something equivalent.
Here is what I want to do in pseudo-code.
n_y = cos(test) / (magnitude of cos (test));
This will give me same thing. Abs() only takes integers. Any help is appreciated.
| I don't know what Abs() you're using, fabs from the C++ standard takes doubles just fine.
But you don't really want magnitude, because then you're stuck doing an expensive division.
Instead just use a signum function.
|
2,659,895 | 2,659,985 | What does a compiler add to an empty class declaration? | Suppose, I write
class A { };
The compiler should provide (as and when needed)
a constructor
a destructor
a copy constructor
= operator
Is this all the compiler provides? Are there any additions or deletions to this list?
| It's complete. But there are two points you should note:
It's the copy =operator. Just like there is a copy constructor, there is a copy assignment operator.
They are only provided if actually used.
Some explanation for 2:
struct A { private: A(); };
struct B : A { };
That's fine! Providing a default constructor would be ill-formed for "B", because it would not be able to call the base-class' constructor. But the default constructor (and the other special functions) is only provided (we say it's implicitly defined) if it's actually needed.
|
2,659,916 | 2,661,096 | Inheritance - initialization problem | I have a c++ class derived from a base class in a framework.
The derived class doesn't have any data members because I need it to be freely convertible into a base class and back - the framework is responsible for loading and saving the objects and I can't change it. My derived class just has functions for accessing the data.
But there are a couple of places where I need to store some temporary local variables to speed up access to data in the base class.
mydata* MyClass::getData() {
if ( !m_mydata ) { // set to NULL in the constructor
m_mydata = some_long_and complex_operation_to_get_the_data_in_the_base()
}
return m_mydata;
}
The problem is if I just access the object by casting the base class pointer returned from the framework to MyClass* the ctor for MyClass is never called and m_mydata is junk.
Is there a way of only initializing the m_mydata pointer once?
| It doesn't have members and you must maintain bit-for-bit memory layout compatibility… except it does and C++ doesn't have a concept of freely-convertible.
If the existing framework allocates the base objects, you really can't derive from it. In that case, I can think of two options:
Define your own class Cached which links to Base by reference. Make the reference public and/or duplicate Base's interface without inheritance.
Use a hash table, unordered_map< Base *, mydata > mydata_cache;. This seems most appropriate to me. Use free functions to look up cache data before delegating to the Base *.
|
2,659,920 | 2,659,940 | Strange error that I've never encounter in c++ before, anyone know what it means? | I won't post any code, because there is too much that could be relevant. But When I run my program it prints
Internal Bad Op Name!
: Success
Anybody even know what that means? I'm using g++ to compile my code and nowhere in my code do I cout anything even remotely close to something like that. I don't know where it's coming from. Also, any suggestions as to figure out where in the code it's coming from, maybe using gdb somehow to do that?
Thanks!
| It's not a message I've seen, and Googling for it doesn't show anything obviously related.
You can identify where it comes from by stepping through the program with gdb until the message appears. Alternatively, one can sprinkle some timing delays, "I am here" statements, or input prompts to discover suspect portions of the logic.
< < < (edit) > > >
To use gdb, first be sure to compile and link with debug symbols. With either gcc or g++, just add -g to the command line. It's also often helpful to eliminate any compiler optimizations since those can sometimes make stepping through the program non-intuitive.
[wally@lf ~]$ gdb program
GNU gdb Fedora (6.8-32.fc10)
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...
(gdb) break main
Breakpoint 1 at 0x8048c3c: file rtpsim.cpp, line 30.
(gdb) run
Starting program: ~/program
Breakpoint 1, main () at rtpsim.cpp:30
30 rtp_io (&obj, INIT_CYCLE);
(gdb) next
31 printf ("- - - - - init complete - - - - -\n");
(gdb) <---- pressed "enter" to repeat last command
- - - - - init complete - - - - -
33 for (int j = 0; j < 10; ++j)
(gdb)
35 sleep (1);
(gdb)
36 rtp_io (&obj, SCAN_CYCLE);
(gdb)
37 printf ("- - - - - scan %d complete - - - - -\n", j+1);
...
|
2,659,932 | 2,978,927 | How to read the screen pixels? | I want to read a rectangular area, or whole screen pixels. As if screenshot button was pressed.
How i do this?
Edit: Working code:
void CaptureScreen(char *filename)
{
int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
HWND hDesktopWnd = GetDesktopWindow();
HDC hDesktopDC = GetDC(hDesktopWnd);
HDC hCaptureDC = CreateCompatibleDC(hDesktopDC);
HBITMAP hCaptureBitmap = CreateCompatibleBitmap(hDesktopDC, nScreenWidth, nScreenHeight);
SelectObject(hCaptureDC, hCaptureBitmap);
BitBlt(hCaptureDC, 0, 0, nScreenWidth, nScreenHeight, hDesktopDC, 0,0, SRCCOPY|CAPTUREBLT);
BITMAPINFO bmi = {0};
bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
bmi.bmiHeader.biWidth = nScreenWidth;
bmi.bmiHeader.biHeight = nScreenHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
RGBQUAD *pPixels = new RGBQUAD[nScreenWidth * nScreenHeight];
GetDIBits(
hCaptureDC,
hCaptureBitmap,
0,
nScreenHeight,
pPixels,
&bmi,
DIB_RGB_COLORS
);
// write:
int p;
int x, y;
FILE *fp = fopen(filename, "wb");
for(y = 0; y < nScreenHeight; y++){
for(x = 0; x < nScreenWidth; x++){
p = (nScreenHeight-y-1)*nScreenWidth+x; // upside down
unsigned char r = pPixels[p].rgbRed;
unsigned char g = pPixels[p].rgbGreen;
unsigned char b = pPixels[p].rgbBlue;
fwrite(fp, &r, 1);
fwrite(fp, &g, 1);
fwrite(fp, &b, 1);
}
}
fclose(fp);
delete [] pPixels;
ReleaseDC(hDesktopWnd, hDesktopDC);
DeleteDC(hCaptureDC);
DeleteObject(hCaptureBitmap);
}
| Starting with your code and omitting error checking ...
// Create a BITMAPINFO specifying the format you want the pixels in.
// To keep this simple, we'll use 32-bits per pixel (the high byte isn't
// used).
BITMAPINFO bmi = {0};
bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
bmi.bmiHeader.biWidth = nScreenWidth;
bmi.bmiHeader.biHeight = nScreenHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
// Allocate a buffer to receive the pixel data.
RGBQUAD *pPixels = new RGBQUAD[nScreenWidth * nScreenHeight];
// Call GetDIBits to copy the bits from the device dependent bitmap
// into the buffer allocated above, using the pixel format you
// chose in the BITMAPINFO.
::GetDIBits(hCaptureDC,
hCaptureBitmap,
0, // starting scanline
nScreenHeight, // scanlines to copy
pPixels, // buffer for your copy of the pixels
&bmi, // format you want the data in
DIB_RGB_COLORS); // actual pixels, not palette references
// You can now access the raw pixel data in pPixels. Note that they are
// stored from the bottom scanline to the top, so pPixels[0] is the lower
// left pixel, pPixels[1] is the next pixel to the right,
// pPixels[nScreenWidth] is the first pixel on the second row from the
// bottom, etc.
// Don't forget to free the pixel buffer.
delete [] pPixels;
|
2,660,027 | 2,660,042 | C++ delete not working? | I am having a problem with delete and destructor (I am sure I am making a stupid mistake here, but haven't been able to figure it out as of yet).
When I step through into the destructor, and attempt to call delete on a pointer, the message shows up "Cannot access memory at address some address."
The relevant code is:
/*
* Removes the front item of the linked list and returns the value stored
* in that node.
*
* TODO - Throws an exception if the list is empty
*/
std::string LinkedList::RemoveFront()
{
LinkedListNode *n = pHead->GetNext(); // the node we are removing
std::string rtnData = n->GetData(); // the data to return
// un-hook the node from the linked list
pHead->SetNext(n->GetNext());
n->GetNext()->SetPrev(pHead);
// delete the node
delete n;
n=0;
size--;
return rtnData;
}
and
/*
* Destructor for a linked node.
*
* Deletes all the dynamically allocated memory, and sets those pointers to 0.
*/
LinkedListNode::~LinkedListNode()
{
delete pNext; // This is where the error pops up
delete pPrev;
pNext=0;
pPrev=0;
}
| It seems that you are deleting the next and previous nodes of the list from the destructor. Which, if pNext and pPrev are LinkedListNode*, means that you are recursively deleting the whole list :-(
Try this:
std::string LinkedList::RemoveFront()
{
LinkedListNode *n = pHead->GetNext(); // the node we are removing
std::string rtnData = n->GetData(); // the data to return
// un-hook the node from the linked list
pHead->SetNext(n->GetNext());
n->GetNext()->SetPrev(pHead);
n->SetNext(0);
n->SetPrev(0);
// delete the node
delete n;
n=0;
size--;
return rtnData;
}
LinkedListNode::~LinkedListNode()
{
}
(Actually you don't even need to reset the prev and next pointers to 0 since you are going to delete the node anyway. I left those statements in because they at least put the node into a consistent state, which is a good idea in general. It may make a difference if you later e.g. change your memory management strategy and decide to store unused nodes for later reuse.)
|
2,660,076 | 2,660,086 | returning aligned memory with new? | I currently allocate my memory for arrays using the MS specific mm_malloc. I align the memory, as I'm doing some heavy duty math and the vectorization takes advantage of the alignment. I was wondering if anyone knows how to overload the new operator to do the same thing, as I feel dirty malloc'ing everywhere (and would eventually like to also compile on Linux)? Thanks for any help
| First of all, it's important to note that new and delete can be overloaded either globally, or just for a single class. Both cases are shown in this article. Also important to note is that if you overload new you almost certainly also want to overload delete.
There are a few important notes about operator new and operator delete:
The C++ standard requires that a valid pointer is returned even if the size passed to it is 0.
There's also operator new[] and operator delete[], so don't forget about overloading those.
Derived classes inherit operator new and its brethren, so make sure to override those.
In Effective C++, item 8, Scott Meyers includes some pseudocodish examples:
void * operator new(size_t size) // your operator new might
{ // take additional params
if (size == 0) { // handle 0-byte requests
size = 1; // by treating them as
} // 1-byte requests
while (1) {
attempt to allocate size bytes;
if (the allocation was successful)
return (a pointer to the memory);
// allocation was unsuccessful; find out what the
// current error-handling function is (see Item 7)
new_handler globalHandler = set_new_handler(0);
set_new_handler(globalHandler);
if (globalHandler) (*globalHandler)();
else throw std::bad_alloc();
}
}
void operator delete(void *rawMemory)
{
if (rawMemory == 0) return; // do nothing if the null
// pointer is being deleted
deallocate the memory pointed to by rawMemory;
return;
}
For more information, I'd definitely pick up Effective C++.
|
2,660,276 | 2,660,308 | How to treat Base* pointer as Derived<T>* pointer? | I would like to store pointers to a Base class in a vector, but then use them as function arguments where they act as a specific class, see here:
#include <iostream>
#include <vector>
class Base {};
template<class T>
class Derived : public Base {};
void Foo(Derived<int>* d) {
std::cerr << "Processing int" << std::endl;
}
void Foo(Derived<double>* d) {
std::cerr << "Processing double" << std::endl;
}
int main() {
std::vector<Base*> vec;
vec.push_back(new Derived<int>());
vec.push_back(new Derived<double>());
Foo(vec[0]);
Foo(vec[1]);
delete vec[0];
delete vec[1];
return 0;
}
This doesn't compile:
error: call of overloaded 'Foo(Base*&)' is ambiguous
Is it possible to make it work? I need to process the elements of the vector differently, according to their int, double, etc. types.
| You'll need to use method polymorphism, as it's dynamic, rather than function overloading, which is static (compile-time). To overload on a templated type, you'll need to use template specialization.
Example:
#include <iostream>
#include <vector>
class Base {
public:
virtual void Foo() {
std::cerr << "Processing base" << std::endl;
}
};
template<class T>
class Derived : public Base {};
template <>
class Derived <int> : public Base {
public:
void Foo() {
std::cerr << "Processing int" << std::endl;
}
};
template <>
class Derived <double> : public Base {
public:
void Foo() {
std::cerr << "Processing double" << std::endl;
}
};
int main() {
std::vector<Base*> vec;
vec.push_back(new Derived<int>());
vec.push_back(new Derived<double>());
vec[0]->Foo();
vec[1]->Foo();
delete vec[0];
delete vec[1];
return 0;
}
|
2,660,281 | 2,660,347 | How to compile different extension files as C++ in Visual Studio C++ 2010? | In my Visual Studio 2010 project I have files with .mm file extension, that need to be compiled as normal C++ files. Is there a way to make a build rule for new extensions or something like that? In VS 2008 there were options for that, but they are gone in 2010.
| For an individual file: Right click on the file > Properties > Configuration Properties - General > Item Type : C/C++ compiler.
In general for a project: How to: Select the Files to Build, Walkthrough: Using MSBuild, Walkthrough: Creating an MSBuild Project File from Scratch.
|
2,660,400 | 2,660,405 | Copy Constructors and calling functions | I'm trying to call an accessor function in a copy constructor but it's not working. Here's an example of my problem:
A.h
class A {
public:
//Constructor
A(int d);
//Copy Constructor
A(const A &rhs);
//accessor for data
int getData();
//mutator for data
void setData(int d);
private:
int data;
};
A.cpp
#include "A.h"
//Constructor
A::A(int d) {
this->setData(d);
}
//Copy Constructor
A::A(const A &rhs) {
this->setData(rhs.getData());
}
//accessor for data
int A::getData() {
return data;
}
//mutator for data
void A::setData(int d) {
data = d;
}
When I try to compile this, I get the following error:
error: passing 'const A' as 'this' argument of 'int A::getData()' discards qualifiers
If I change rhs.getData() to rhs.data, then the constructor works fine. Am I not allowed to call functions in a copy constructor? Could somebody please tell me what I'm doing wrong?
| The problem is rhs is declared as const, but getData() isn't, so it could be modifying rhs when you call it even though rhs is supposedly const. As getData() is an accessor, it should be const too:
//accessor for data
int getData() const;
|
2,660,554 | 2,660,587 | C++ interpreter conceptual problem | I've built an interpreter in C++ for a language created by me.
One main problem in the design was that I had two different types in the language: number and string. So I have to pass around a struct like:
class myInterpreterValue
{
myInterpreterType type;
int intValue;
string strValue;
}
Objects of this class are passed around million times a second during e.g.: a countdown loop in my language.
Profiling pointed out: 85% of the performance is eaten by the allocation function of the string template.
This is pretty clear to me: My interpreter has bad design and doesn't use pointers enough. Yet, I don't have an option: I can't use pointers in most cases as I just have to make copies.
How to do something against this? Is a class like this a better idea?
vector<string> strTable;
vector<int> intTable;
class myInterpreterValue
{
myInterpreterType type;
int locationInTable;
}
So the class only knows what type it represents and the position in the table
This however again has disadvantages:
I'd have to add temporary values to the string/int vector table and then remove them again, this would eat a lot of performance again.
Help, how do interpreters of languages like Python or Ruby do that? They somehow need a struct that represents a value in the language like something that can either be int or string.
| I suspect many values aren't strings. So the first thing you can do is to get rid of the string object if you don't need it. Put it into an union. Another thing is that probably many of your strings are only small, thus you can get rid of heap allocation if you save small strings in the object itself. LLVM has the SmallString template for that. And then you can use string interning, as another answer says too. LLVM has the StringPool class for that: Call intern("foo") and get a smart pointer refering to a shared string potentially used by other myInterpreterValue objects too.
The union can be written like this
class myInterpreterValue {
boost::variant<int, string> value;
};
boost::variant does the type tagging for you. You can implement it like this, if you don't have boost. The alignment can't be gotten portably in C++ yet, so we push some types that possibly require some large alignment into the storage union.
class myInterpreterValue {
union Storage {
// for getting alignment
long double ld_;
long long ll_;
// for getting size
int i1;
char s1[sizeof(string)];
// for access
char c;
};
enum type { IntValue, StringValue } m_type;
Storage m_store;
int *getIntP() { return reinterpret_cast<int*>(&m_store.c); }
string *getStringP() { return reinterpret_cast<string*>(&m_store.c); }
public:
myInterpreterValue(string const& str) {
m_type = StringValue;
new (static_cast<void*>(&m_store.c)) string(str);
}
myInterpreterValue(int i) {
m_type = IntValue;
new (static_cast<void*>(&m_store.c)) int(i);
}
~myInterpreterValue() {
if(m_type == StringValue) {
getStringP()->~string(); // call destructor
}
}
string &asString() { return *getStringP(); }
int &asInt() { return *getIntP(); }
};
You get the idea.
|
2,660,633 | 2,660,643 | Declaring pointers; asterisk on the left or right of the space between the type and name? |
Possible Duplicates:
What makes more sense - char* string or char *string?
Pointer declarations in C++: placement of the asterisk
I've seen mixed versions of this in a lot of code. (This applies to C and C++, by the way.) People seem to declare pointers in one of two ways, and I have no idea which one is correct, of if it even matters.
The first way it to put the asterisk adjacent the type name, like so:
someType* somePtr;
The second way is to put the asterisk adjacent the name of the variable, like so:
someType *somePtr;
This has been driving me nuts for some time now. Is there any standard way of declaring pointers? Does it even matter how pointers are declared? I've used both declarations before, and I know that the compiler doesn't care which way it is. However, the fact that I've seen pointers declared in two different ways leads me to believe that there's a reason behind it. I'm curious if either method is more readable or logical in some way that I'm missing.
| It's a matter of preference, and somewhat of a holy war, just like brace style.
The "C++" style
someType* somePtr;
is emphasizing the type of the pointer variable. It is saying, essentially, "the type of somePtr is pointer-to-someType".
The "C" style
someType *somePtr;
is emphasizing the type of the pointed-to data. It is saying, essentially, "the type of data pointed to by somePtr is someType".
They both mean the same thing, but it depends on if a given programmer's mental model when creating a pointer is "focused", so to speak, on the pointed-to data or the pointer variable.
Putting it in the middle (as someType * somePtr) is trying to avoid committing to either one.
|
2,660,640 | 2,663,931 | How to read CD audio data in Windows? | What is the Microsoft-approved way to extract the raw audio data from an audio CD? I'm hoping to do this with C++ or C.
It's ironic because in XP/Vista/7, there is the IMAPI (Image Mastering API) for writing data, but not for reading it.
Is there a set of API functions for this? Or do I need to send SCSI commands?
| Here are a couple of code samples...
http://www.codeproject.com/KB/audio-video/SimpleAudioCD.aspx
http://www.codeproject.com/KB/cs/csharpripper.aspx
|
2,660,644 | 2,660,655 | LHS state after exception is thrown | I am learning C++ exceptions and I would like some clarification of the scenario:
T function() throw(std::exception);
...
T t = value;
try { t = function(); }
catch (...) {}
if the exception is thrown, what is the state of variable t?
unchanged or undefined?
| Unchanged. t can't be assigned until function() returns a value, and function() never returns normally
|
2,660,652 | 2,660,658 | C++ trouble with pointers to objects | I have a class with a vector of pointers to objects. I've introduced some elements on this vector, and on my main file I've managed to print them and add others with no problems. Now I'm trying to remove an element from that vector and check to see if it's not NULL but it is not working.
I'm filling it with on class Test:
Other *a = new Other(1,1);
Other *b = new Other(2,2);
Other *c = new Other(3,3);
v->push_back(a);
v->push_back(b);
v->push_back(c);
And on my main file I have:
Test t;
(...)
Other *pointer = t.vect->at(0);
delete t.vect->at(0);
t.vect->erase(t.vect->begin());
if (pointer == NULL) { cout << "Nothing here.."; } // Never enters here..
| The deletion of memory pointed by a pointer, doesn't set the pointer to NULL.
|
2,660,743 | 2,660,811 | C++ equivalent of Java Enum.valueOf() |
Possible Duplicate:
Is it possible to define enumalpha?
Is there any equivalent of Java Enum.valueOf(string) on C++?
| There's no table of names generated by the compiler (unless you count debug information), but if you create one (or use e.g. doxygen which parses the source code and can output such lists in XML format) then you can use a dictionary of some type, such as std::map<string, int> to turn an identifier into its numeric value.
|
2,661,053 | 2,661,055 | Isn't an Iterator in c++ a kind of a pointer? | Ok this time I decided to make a list using the STL. I need to create a dedicated TCP socket for each client. So everytime I've got a connection, I instantiate a socket and add a pointer to it on a list.
list<MyTcp*> SocketList; //This is the list of pointers to sockets
list<MyTcp*>::iterator it; //An iterator to the list of pointers to TCP sockets.
Putting a new pointer to a socket was easy, but now every time the connection ends I should disconnect the socket and delete the pointer so I don't get a huge memory leak, right? well.. I thought I was doing ok by setting this:
it=SocketList.begin();
while( it != SocketList.end() ){
if((*it)->getClientId() == id){
pSocket = it; // <-------------- compiler complains at this line
SocketList.remove(pSocket);
pSocket->Disconnect();
delete pSocket;
break;
}
}
But the compiler is saying this:
error: invalid cast from type ‘std::_List_iterator<MyTcp*>’ to type ‘MyTcp*’
Can someone help me here? i thought I was doing things right, isn't an iterator at any given time just pointing to one of the elements of the set? how can I fix it?
| Try this:
pSocket = *it;
Iterators act a lot like pointers, but in reality they can be a pointer or a full-fledged class that acts like one. The important thing in this case, is that when you dereference one, you get whatever item is being stored in the container. Since you are storing MyTcp*s in the list, when you dereference the iterator you get a MyTcp*. pSocket is of type MyTcp* so the assignment above succeeds. The assignment you are trying to do is not dereferencing the iterator -- you are trying to assign the iterator itself to pSocket.
It's kind of like the following case:
void foo()
{
MyTcp *array[10]; // An array full of MyTcp pointers
MyTcp **iterator = NULL; // pointers make good iterators for arrays (but not for std::lists)
for (iterator = array; iterator != array + 10; ++iterator)
{
// This fails to compile (cannot assign MyTcp** to MyTcp*:
MyTcp *wrong = iterator;
// This succeeds:
MyTcp *current = *iterator; // important to dereference the iterator
}
}
|
2,661,293 | 5,855,563 | Is there an Open XML parser for C++? | I want to scan a PowerPoint 2007 file, but I'm trying to do it with C++. Is there any Open XML parser for C++?
| Here's a newly released C library called libOPC which has the same intent as the Open XML SDK, but can be used in all of Linux/Windows/Mac/etc. You can read about it here: libOPC version 0.0.1 released and get the code from CodePlex (be sure to check the documentation page for demo videos).
|
2,661,621 | 2,663,372 | WebKit and npapi and mingw-w64 | The problem is the following:
On Windows x64, pointers are 64-bit, but type long is 32-bit.
MSVC doesn't seem to care, and even omits warnings about pointer truncation on the default warning level.
Since recently, there is a GCC that targets x86_64-w64-mingw32, or better native Windows x64. GCC produces errors when pointers are truncated (which is the logical thing to do...), and this is causing trouble in WebKit and more specifically, the Netscape Plugin API:
First, there's the files (I can only post one hyperlink...):
http://trac.webkit.org/browser/trunk/WebCore/
bridge/npapi.h --> defines uint32 as 32-bit int type (~line 145)
plugins/win/PluginViewWin.cpp --> casts Windows window handles to 32-bit int, truncating them (~line 450)
My proposed fix was to change the uint32 casts to uintptr_t, which makes GCC happy, but still puts a 64-bit value in a uint32 (=unsigned long). I have no clue how to solve this, because clearly WebKit is happy truncating pointers on Win64...
How can I solve this the right way? Thanks!
| For anyone interested, I have changed the uint32 lparam, wparam to uintptr_t's. It is a cange only visible in Windows, where it is certainly the correct fix IMHO.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.