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::... |
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;
H... | 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 takin... |
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 ... |
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
... | 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 ... |
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 ... | 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 f... |
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 {
... | 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_tit... | 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", ... |
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 b... |
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++:
t... | 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() {
... |
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;... |
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;
... | 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... |
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;
}
}
... | 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 wan... |
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\MS... | 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\Comm... |
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 currentUnC... |
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 x... |
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 ... | 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 except... |
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 b... |
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(std... | 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 declar... | 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 us... |
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.cp... | 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... |
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... |
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 tha... | 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... |
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 ... | 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 compati... |
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(QMouseE... | 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::... |
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 o... |
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... | 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 o... | 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 se... |
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) {... | 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... |
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 t... | 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. S... |
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... | 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 ... |
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++ ... | 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 -... |
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, s... |
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 ;... | 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 inte... |
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 langu... | 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 straigh... | 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: Fixe... |
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... | 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,... | 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 ... |
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::... | 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... |
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 ... | 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 alloc... |
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... |
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 comp... | 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 soluti... |
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 w... | 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 ... |
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 sid... | 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... |
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 sizeo... | 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(I... | 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 Soc... |
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& ou... | 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, a... | 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 t... | 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 c... |
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). ... | 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 Set... |
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 <... | 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 exam... |
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_()
... | 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... | 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:
Lo... | 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.) Th... |
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(... | 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 (" << th... |
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 he... | 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.
... |
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 workin... | 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 []... |
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 ... |
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... | 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();
}
... | 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();
... |
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;... |
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 debu... |
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 wo... | 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,... |
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 ... | 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 ... |
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 b... | 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 {
... | 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 wid... |
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[... | 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;
}
};
... |
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_... | 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;
XShamPixma... | 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... |
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 ... | 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 l... |
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... | 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 = s... |
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.
... | 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 w... |
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 ... | 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... |
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 i... | 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 o... |
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();
... | 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.bm... |
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:
/... | 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
... |
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... | 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 opera... |
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::... | 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 << "Proc... |
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:
... | 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 p... | 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 Smal... |
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... | 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. ... |
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 Te... | 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 valu... |
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... | 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... |
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 poi... | 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.