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
4,348,392
4,348,461
How do I add to a wstring?
This works with std::string std::string class::something(char* input) { std::string s(input); s = "hai! " + s; return s; } But fails if I try the same thing with wstring std::wstring class::something(wchar_t* input) { std::wstring s(input); s = "hai! " + s; return s; } How do I do the same thi...
The problem here is types. A wstring isn't a string, but a quoted string constant is related to it (it is generally a const char*), so s = "hai! " + s; is actually a problem. The value "hai! " is of type const char*, not type const wchar_t*. Since const char* is a basic type, it's searching for a global operator+ that...
4,348,470
4,348,505
deallocating gsl vectors in structs
Can you explain what's going on with my code here? I'm not sure if I'm using the destructor correctly or not in the struct. With the destructor in there I get: function1: 23 function2: 8.86183e-317 * glibc detected ./a: double free or corruption (fasttop): 0x000000000111b010 ** If I just comment out the destructor I g...
Inside of function1 and function2 you make a copy of the struct1 object that you create in the main() function. These copies have the same pointer x. When the destructor for each of these copies is called, gsl_vector_free is called, so you try to call it three times on the same pointer: once in function1 when s is d...
4,348,642
4,348,770
[C++]function template with static keyword
code from google's v8 js engine, allocation.h: template <typename T> static void DeleteArray(T* array) { delete[] array; } This is a function template (top level, not in any class). But what the static keyword is for?
The static keyword gives the definition "internal linkage", which means it would be legal to give the name DeleteArray another meaning or a different definition in a different source file. (Just as is the case with static void f(); or static int i;.) But I can't imagine anyone would want to do that. Use of static thi...
4,348,804
4,348,936
Determining order of windows opened
Through the windows API I can get the list of all windows which are currently open but it seems that the IntPtr's don't come back in any specific order. I was wondering if there is a way to get the windows in the order in which they were opened. For instance if I open 2 IE windows followed by a notepad window, when I r...
Handle values are obfuscated pointers, you cannot rely on their value at all. And they get recycled. The long distance shot is GetWindowThreadProcessId() to get the ID of the thread that owns the window. OpenThread() to get a handle to it. GetThreadTimes() to find out when that thread was created. CloseHandle() t...
4,348,849
5,333,223
Formatting for failure output of BOOST_CHECK_CLOSE?
I am adding tests to legacy code using the boost test framework. One such test might be double expectedPrice = /*...local computation*/ BOOST_CHECK_CLOSE(expectedPrice, object->price, ACCURACY_THRESHOLD); Where expectedPrice is a double computed locally and the object is retrieved from the system under test. error in ...
This is known issue. With known solution. Just a bit hard to implement, though I still hope to do at some point. Meanwhile you are stuck with whatever output your iostream library produces.
4,348,862
4,349,198
Returning a priority_queue with custom comparator
I have a function that needs to return a sorted list based on some input parameters. I've selected a std::priority_queue to hold this list. But the compiler is giving me an error I don't recognize. Here's the code I have: struct DepthCompare { bool operator() (const struct inst *&lhs, const struct inst *&rh...
You have two problems. To use a custom comparator, you must specify the comparator type as the third template argument: typedef priority_queue<inst*, vector<inst*>, DepthCompare> HeuristicList; HeuristicList ret( DepthCompare ); is interpreted as a function declaration, rather than a variable declaration, giving the ...
4,348,881
4,348,929
Getting the EBP of a thread in a different process
I was wondering if there's a way to obtain the EBP of a thread in a different process (in C++ on windows) other than using "GetThreadContext". I suspect that this method takes too much time (I use it a lot) and if I could get just the EBP and not all the values of CONTEXT, it would be faster. I was thinking of using ...
The running value of EBP of another thread is, of course, in the EBP register if the thread is running. If it's not running, it's saved away by the scheduler in the kernel. GetThreadContext is retrieving what's in the kernel; nothing else will be faster. The performance situation is worse than I understood when I wrote...
4,348,926
4,348,966
Can't compile libpqxx tests using Netbeans
I'm trying to compile a very simple program that makes a connection to a database and prints the database name. I'm able to compile on the command line but am unable to do so in Netbeans. I'm using Netbeans IDE 6.9.1 on Ubuntu 10.04 and am using g++ 4.4.3 and libpqxx 2.6.9 installed using apt-get. Code follows: #incl...
g++ -o dist/Debug/GNU-Linux-x86/cpptest build/Debug/GNU-Linux-x86/main.o You'll notice that Netbeans hasn't added the -L and -l options to the linker command like you did. This is causing the 'undefined reference' errors -- it's not linking your program to the pqxx library. You'll need to edit your Netbeans proje...
4,349,014
4,349,065
Template specialization for a set of types
How do I specialize a template for a set of data types? For example: template<typename T> inline T getRatio(T numer, T denom){ return (numer/denom); } I want to specialize it for a set of data types so it only works with int, long, double and float. So if the user would try to use this function with a char type, t...
As only the three data types long, double and float are relevant and their is no need for an additional generic version, just reject the template and provide three functions for long, double and float.
4,349,187
4,349,342
Problem using AllocConsole() and marshalling
I've got a C# application that calls a native C++ DLL (I control the source of both). I've used AllocConsole() from the managed side, and then call into the native side. But the native code won't output to the console- nothing happens, even though there is most definitely a console available, since I just explicitly al...
If your application is not linked to use the console subsystem, you have to hook it up yourself.
4,349,394
4,350,837
Fastest deskew algorithm?
I am a little overwhelmed by my task at hand. We have a toolkit which we use for TWAIN scanning. Some of our customers are complaining about slower scan speeds when the deskew option is set. This is because if their scanner does not support a hardware deskew, it is done in post-processing on the CPU. I was wondering if...
Are you scanning in Color or B/W ? Deskew is processor intensive. A Group4 tiff or JPEG must be decompressed, skew angle determined, deskewed and then compressed. There are many image processing algorithms out there with deskew and I have evaluated many over the years. There are some huge differences in processing ...
4,349,416
4,349,470
create variable to hold time created
Im creating a contact list program and need to beable to record when the contact was created and list the contacts according to their creation date. what can i use to give a variable a date? i know the time.h file has something inside, but i dont know how to use it with less code as possible. perhaps time.h seconds ...
I know you can use time_t for dates. If you need higher precision, use clock_t You can get the current time as follows. Note that what is stored is an integer value of the number of seconds since January 1st, 1970. #include <time.h> .... time_t s = time(NULL); See this for further details. Hope that helps!
4,349,442
4,349,859
Nikon Camera SDK non-reentrant
The Nikon SDK allows for a request/response system from PC to camera through USB through the C programming language. When creating two camera objects in two seperate threads, it is not possible to send two commands simultaneously to two seperate cameras. One camera will get its command, and send back the response, and ...
Even though you made two copies of the DLL, they are both being loaded into the same address space / process, so any conflicts will still overlap. The first thing I would try is two separate EXEs, each loading the original DLL, so that they are running in different processes. If this allows the two cameras to be contr...
4,349,458
4,350,096
Writing my first blackberry app
I am contemplating writing my first BlackBerry app. I am fundamentally a C/C++ programmer, not Java. Can anyone provide some guidelines on the quickest route, i.e. shallowest learning curve, to writing a BlackBerry app? Any resources/links would be useful. As an aside: In an ideal world, I would like to write once and ...
Skyeagle, With a C/C++ background, I'd suggest you start on the iPhone. Not only will you be more comfortable with the language but it's only a limited range of devices to worry about - in comparison with the BlackBerry market which varies vastly in form factor and ability (and is of course in Java). However, if you we...
4,349,502
4,358,083
How to show progress in windows 7 taskbar (using Qt)?
Is there a way to access the windows 7 progress bar with Qt? I'm currently using Qt 4.7.0 with Qt Creator. I already found Q7Goodies but unfortunately it is not free. So it seems to be possible - how can I access to the progress bar by hand (without Visual Studio)?
I think they used Win7 API functions and encapsulated them in their library. You can include by hand those headers and use them too. Here you can find a help topic and demo project: codeproject.com/KB/vista/SevenGoodiesTaskbarStatus.aspx But its only for win7. Not crossplatform. Good luck update mar 05, 2014 This quest...
4,349,505
4,349,523
Trying to Implement power and factorial functions recursively. C++
All ive got so far are the definitions. double power(double base, int exponent); double factorial(double n); And after this i am completely lost and I'm looking for ideas.
Well, 3^4 is 3 * 3 * 3 * 3. Which is 3 * 3^3. 3^3 is 3 * 3^2. 3^2 is 3 * 3^1. 3^1 is 3. 5! is 5 * 4 * 3 * 2 * 1. Which is 5 * 4!. 4! is 4 * 3!. 3! is 3 * 2!. 2! is 2 * 1!. 1! is 1. That should give you enough to be getting on with...
4,349,734
4,349,785
Problem with fibonacci function. C++
Should return the n place of the array. But instead of the value I'm only getting 0. int fibonacci(int n) { int f[100]; f[0] = 0; f[1] = 1; for (int i=2; i<n; i++) { f[i] = f[i-2] + f[i-1]; } return f[n]; } int main() { cout << fibonacci(3); return 0; } New CODE: New prob...
well, you never set f[n], you only go up to i < n, that is, i == n-1. try returning f[n-1] EDIT: as Chris Lutz pointed out my answer is no good as it would give an invalid result if you called fibonacci(0) Like many have answered already, the best solution is to loop until i <= n Unless, of course, you want fibonacci(3...
4,349,751
4,349,800
How do I write this template specification when I'm outside the 'class' definition
This is something that I never ran into before. Say I have a class that looks like this: template <class T1> class A { void normal_function(); template <class T2> void templated_function(T2); } Because of coding standards, I'm not allowed to put the body of templated_function inside of the class definitions...
This works with g++: template<class T1> template<class T2> void A<T1>::templated_function(T2 t) { ... }
4,349,769
4,350,068
Getting mouse click location of a label in qt
I googled around and found this forum thread in which the OP seems to have had the exact problem I am having. The question is, how would I inherit from QLabel and reimplement the mousepressed event? I'm guessing it would be something like this: class CustomLabel : public QLabel { public: //what about the constructo...
Yes, you can set up a signal on your CustomLabel class and have your overridden version of mousePressEvent emit it. i.e. class CustomLabel : public QLabel { Q_OBJECT signals: void mousePressed( const QPoint& ); public: CustomLabel( QWidget* parent = 0, Qt::WindowFlags f = 0 ); CustomLabel( const QString& t...
4,349,778
4,371,294
The effect of `basic_streambuf::setbuf`
My problem is as follows: Martin York claims in this, this, and this answers that one can make a stringstream read from some piece of memory by using basic_stringbuf::pubsetbuf like this: char buffer[] = "123"; istringstream in; in.rdbuf()->pubsetbuf(buffer, sizeof(buffer)); // calls basic_stringbuf::setbuf int num; in...
I believe it is implementation defined and that you provided the relevant quotes. For the record, this is what Standard C++ IOStreams and locales, not exactly a recent book I have to admit, has to say on the subject in a section titled "The almost semantic free function - setbuf()" : The virtual member function setbuf...
4,349,912
4,349,956
strange error in Eclipse
hello everyone I have this snippet of the code: void* Init(int N) { Hand * DS = new Hand(N); return (void*)DS; //DS is static defined somewhere... every time when I check in Debugger I receive the same error: mi_cmd_var_create: unable to create variable objec can somebody please explain why? P.S. I know ...
This guy with the same problem solved it like: If you have variables in your watch window that you later eliminate from your code then attempt to debug again this error is generated. The fix is to also delete the variable from the watch list. At least this is how it works in Eclipse Europa.
4,350,041
4,350,103
Copying array of ints vs pointers to bools
I'm working on a program that requires an array to be copied many thousands/millions of times. Right now I have two ways of representing the data in the array: An array of ints: int someArray[8][8]; where someArray[a][b] can have a value of 0, 1, or 2, or An array of pointers to booleans: bool * someArray[8][8]; wher...
Which would copy faster is beside the point, The overhead of allocating and freeing entries, and dereferencing the pointer to retrieve each value, for your bool* approach will swamp the cost of copying. If you just have 3 possible values, use an array of char and that will copy 4 times faster than int. OK, that's n...
4,350,258
4,350,425
Testing for infinity in CUDA
In a CUDA program, I recently switched from testing for inifinity using return x==INFINITY || x==-INFINITY; where INFINITY is from math.h, to return !isfinite(x); and was quite surprised to get different results. gnu.org suggests that they actually should behave similarly. Am I missing something? Is it not allowed to...
isfinite(a) is the same as !isnan(a) && !isinf(a). If x is NaN, then both isfinite(x) and isinf(x) are false.
4,350,327
4,350,544
Passing a function pointer into a constructor C++
I'm trying to make a decision tree for my program in which every node has a similar branching function but a different body in the branching method. I've figured out how to get function pointers into the method but now it seems to not want to take the pointer to method outside of the class. This is my node class class...
I don't see any messing with function pointers in your code, so I'm going to attempt to answer best from what I can glean from the question. it seems to not want to take the pointer to method outside of the class My psychic debugging powers sense that you're trying to create pointers to class methods. If so, you don'...
4,350,328
4,350,497
changing the base pointer of a process
I have a more theoretical question with pointers and memory allocation. Lets say for example I have a process running and it has allocated 2 bytes from 0x01 to 0x03. If I want to read from that memory I'll probably use ReadProcessMemory. But what pointer am I specifically supposed to give? Is it a relative or an absol...
OK, but now let's say I want to copy the memory of a process somewhere (HDD maybe?) to clean up my memory for a little while. Then I want to put memory back where it was before, but I cant tell windows 'allocate 2048 bytes from 0x00c to 0x80c'. Simply allocate memory yourself. Windows is a virtual memory system. If i...
4,350,378
4,350,479
Mutual friendship and pointers: What Pattern or anti-pattern is this?
In studying the C++ source of a massive app, I find this pattern (the syntax for the example may be sketchy, but the essential details are there): class A : X friend B; B *parent; ...stuff... class B : Y friend A; A *myhelper; ...stuff... Perhaps it is meaningful that class B is really named AHel...
Depends on what the classes are doing. If it's something like the iterator pattern (i.e. std::vector<t> and std::vector<t>::iterator), then it can be used for something good. On the other hand, if the classes are doing fundamentally different things, it's probably best if they are only exposed to each other using their...
4,350,468
4,356,680
Recognizing alias names of servers
I have a windows service which runs based on the machine name or ip assigned to it. I am facing problems running it when i have a failover server and alias names described below. There is a main server in one subnet with machine name like server_a and a failover server in another subnet with name server_b Both the sys...
Services always show error code as “Unable to read Configuration ! : Code 1” if started in debug mode,if not able to connect. I think you need to dig into the code and find out where this particular error message is coming from, and exactly what it means. I for one have no idea what particular application ("service") ...
4,350,484
4,352,424
SFTP with Non-File Based Keys
I'm planning to write some software using SFTP with public/private key authentication to upload files to a server. I am wondering how people recommend managing the keys (especially the private key). My target platform is Windows with C# or C++. I've looked at a number of libraries: C# (free/open) SharpSSH Granados (com...
I've never used Granados, but that library's SSH2UserAuthKey class has a FromSECSHStyleStream method that loads a user's authentication key from an arbitrary Stream (which could be a MemoryStream if you want to load the key directly from memory). It seems like this would let you bypass the filesystem for key storage. R...
4,350,591
4,350,656
Curve Trajectory object orientation
I have a spaceship in a 3D environnement. I drew a B-Spline curve using control points (converted to a Bezier curve to be able to draw it). Each time the draw event is called, the ship is at the point (0,0,0) and is translated to the next coordinate on the curve. Now, before doing this translation, I would need to make...
Well an orthonormal (ie orientation) matrix is made up of the following: Direction, Tangent, BiTangent (Up vector). So if you have your direction and tangent you can cross product to get your bitangent and form your matrix from the 3 direction vectors (D, T, B) and position vector (P) as follows Tx, Bx, Dx, Px Ty, By...
4,350,624
4,350,693
Qt: mainWindow->show(); does not show the mainWindow
In the code below, I create a window, invoke window.show(), but the window doesn't show up until after window->iterateSolution() is called. Almost as if, app.exec() is the function that shows the window. I'm very new to Qt so I have no idea what is going on. #include <QtGui/QApplication> #include <mainWindow.h> #includ...
That's exactly what's happening. Technically speaking, QMainWindow::show() does not make the window visible, it simply sets a flag in the window, and Qt will make it visible on the next iteration of the event loop. Also, straight from Qt's documentation on QApplication::exec(): It is necessary to call this function ...
4,350,651
4,362,003
Efficient way to convert a 2D bitmap into a 3D cube model?
I want to create cube model of a 32x32 bitmap in opengl. For example, the result should look something like this given a 2D bitmap of Bob-omb from Super Mario: http://fc02.deviantart.net/fs49/f/2009/186/f/a/Bob_omb_in_Minecraft_by_Luafox.png The idea is to represent each 2D pixel from the bitmap as a 3D cube. Each mode...
Regarding storing colors and normals for the faces; I think you have to accept that you need to duplicate vertices in the same position for the different faces. If two vertices share some attributes but differ in others, they are essentially different - even if one attribute that they share is their position. So, you ...
4,350,784
4,350,832
Finding a substring token in a string in C++
OK suppose I'm parsing some XML (the problem exists while reading any "language" but XML is one many people are familar with). The XML looks like the following: <Tag> <[CDATA[ blah blah]]> <Tag2> <Tag3/> </Tag2> <Tag> Now I want to find the various tokens in that stream. The important tokens are as follows ...
You need to track state in the parser - where am I now? what am I expecting next? - in a context-specific way. When you see what you get next, you check it against a list of valid values for current state, and possibly store a completed parsed data item, and possibly change state. Parsing XML only looks easy by the way...
4,350,889
4,350,982
c++ Jobqueue: Is there a rule of thumb for the number of worker threads?
I just implemented a very first simple multithreaded jobqueue in c++ and I thought (and read) that it's a good idea to use one worker thread for each hardware thread (in my case that would be 4). Basically my app just loads alot of images (at the same time) from the internet right now, and I notice that I get a huge sp...
The ideal number of worker threads is equal to the number of CPU cores in the system. However, in reality this is suboptimal because sometimes tasks can block on the network, disk I/O, etc.. resulting in underutilization. That sounds like what is happening here. Often times thread pools will "over schedule" to compens...
4,351,032
4,351,919
Automatic version numbering
I'm adding a functionality to my executable to run it with --version argument. The project is very big and uses multiple classes. I'd like to print out the versions of all of the classes. Right now each of my classes has a function static void print_info() { cout << "information here" << endl; } and the file with a mai...
First off, I recommend you do something other than your print_info() approach, since it's not very flexible - what if you want to actually use the version rather than simple print it to STDOUT, or what if you wish to report the version in an error message to STDERR? A static method returning a const char string would b...
4,351,039
4,372,602
How to declare a templated function with an optional compile-time parameter?
I want a function with this interface. func<Type1,CompileOption>( Type2 value) //or func<Type1>( Type2 value) The first compile-time parameter is a type. It is require in every function call. The second compile time parameter is optional. It is used to modify the behavior of func. The function itself is templated on...
I over thought the problem and confused everyone else as well. It's not possible to write one function unless C++0x extensions are used. However it's quite straight forward to write it with two overloaded functions. template< typename Type1, typename Option, typename Type2 > void func( Type2 t2 ) { /* ... */ } templ...
4,351,077
4,351,213
How/when do I use a virtual destructor?
I'm currently writing a program with the following polymorphic hierarchy: Base: Multinumber. Derived: Pairs, Complex, Rational. Multinumber is a virtual class and is never instantiated. During the course of my program I frequently dynamically manage the base classes so I need a destructor. My question is this: how do I...
Just declaring the virtual destructor in the base, and giving it the empty definition, is sufficient. For the other classes you do not need to do anything at all, unless there's actual work for those destructors to do. The point of the virtual declaration in the base class is to ensure that the destructor can be invoke...
4,351,114
4,351,159
Initializing multidimensional arrays
When ever I try to initialize a multidimensional array I get the following error: (20) : error C2059: syntax error : '{' This is my code: /* * Tic-Tac-Toe * Version 1.0 * Copyright (C) 2010 lolraccoon. All rights reserved. */ #ifndef GAME_H #define GAME_H #include <iostream> using namespace std; cl...
This was not your only error. Classes are not to be used like that. U need a constructor to set values etc etc. Try that : #ifndef GAME_H #define GAME_H #include <iostream> using namespace std; class Game { private: int board[3][3]; char pieces[3]; public: void dispBoard(); Game() { board = { }; pi...
4,351,296
4,351,313
do I need to destroy a string in c++
if I have a string in a class, then memory is allocated. Do I have to destroy the string in the destructor? e.g. class A { string Test; A() { Test = "hello world"; } A(string &name) { Test = name; } ~A() { // do I have to destroy the string here? } } I'm an old c/c++ (pre stl) programmer a...
Yes, std::string's resources are cleaned up automatically. Standard strings and containers allocate/deallocate for you. HOWEVER, a container of pointers doesn't free up what those pointers point to. You have to loop through those yourself.
4,351,371
4,351,484
C++ performance challenge: integer to std::string conversion
Can anyone beat the performance of my integer to std::string code, linked below? There are already several questions that explain how to convert an integer into a std::string in C++, such as this one, but none of the solutions provided are efficient. Here is compile-ready code for some common methods to compete against...
#include <string> const char digit_pairs[201] = { "00010203040506070809" "10111213141516171819" "20212223242526272829" "30313233343536373839" "40414243444546474849" "50515253545556575859" "60616263646566676869" "70717273747576777879" "80818283848586878889" "90919293949596979899" }; std::string& i...
4,351,404
4,351,927
Rabin-Karp String Matching is not matching
I've been working on a Rabin-Karp string matching function in C++ and I'm not getting any results out of it. I have a feeling that I'm not computing some of the values correctly, but I don't know which one(s). Prototype void rabinKarp(string sequence, string pattern, int d, int q); Function Implementation void rabin...
The big gotcha in coding the Rabin Karp is the modulo operator. When two numbers X and Y are congruent modulo Q then (X % Q) should equal (Y % Q) but on the C++ compiler you're using they will only be equal if X and Y are both positive or both negative. If X is positive and Y is negative then (X % Q) will be positive a...
4,351,429
4,351,471
What's going on here: v5 = *(_Byte *)(this + 4)?
I am looking at a code dump from IDA pro. There is a function which as this layout: garbled_name(int this... unsigned int v5 ; v5 = *(_Byte *)(this + 4); ... What I am really curious about is what exactly the '+ 4' is doing? Is this an addition or something else? Thanks
The code takes the integer 'this', adds 4 to it, casts it to a pointer to a byte, and then sets 'v5' to the value of the byte at that address.
4,351,652
4,396,142
Implicit conversion not happening when I templatize
Here's a couple of related, but distinct classes. One contains a list of floats; one contains just one. Sometimes I want to, say, multiply these together. In that case, I want to 'promote' the non-list one to a list. Here's the code, which works just the way I want it to. #define LIST_SZ 4 class Vec1; class Vec1_...
You must declare the operator* as a friend of the Vec1_list class, so that it will be instantiated when the Vec1_list is instantiated and then the conversion will be performed. EDIT: To do so, move the operator* definition to the Vec1_list class template declaration: friend static Vec1_list operator*(const Vec1_list& ...
4,351,718
4,351,807
Writing multiple array pointers to file with ofstream?
I'm having some seriously strange trouble writing multiple arrays of data to a file. Basically, I'm wanting to store all the array sizes at the top of the file, and then the array data following. This way I can just read the sizes and use that to construct arrays to hold the data on import, and I'll know exactly where ...
There's nothing obviously wrong with this code (indeed, I don't see the errors you're encountering when I try running it), except for the fact that you are not checking for errors opening the input/output files. For example, if you don't have permission to write to "test.dat", the open will silently fail, and you'll re...
4,351,817
4,351,900
How do I dynamically allocate memory to a polymorphic data type?
I have a set class that can polymorphically hold and manage anything of type Multinumber. This can be an object of type Pair, Rational, or Complex. The problem that I am running into is that this class requires dynamic memory management and in many cases, such as the function below, I don't know what type to allocate. ...
I don't see why you would be allocating here. But aside from that, use the virtual clone idiom.
4,351,978
4,352,141
An efficient algorithm and code to find cycle in a string in C++?
For example, in "12345123451234512345", what is an efficient algorithm to find "12345"? Coding in C++. Thanks.
Going on your single example: 12345123451234512345 returns 12345 I think what you want is to find the longest possible needle that is repeated to complete the haystack, i.e. 1212121212 => 12, 444 => 4 and so on. The simplest solution would be to pick the first character and run through the string comparing for matches...
4,352,169
4,352,180
Default constructor for an inherited class
I've reduced my problem down to the following example code: class pokemon{ public: pokemon(int n); }; class MewTwo : public pokemon { public: MewTwo(int n); }; MewTwo::MewTwo(int n) {} Which produces an error: no matching function for call to ‘pokemon::pokemon()’ What I think is happening...
Actually what you are looking for is the member initialization list. Change your inherited class constructor to the following: class MewTwo : public pokemon { public: MewTwo(int n) : pokemon(n) {} }; You were correct in identifying what was going on. Basically when you create the inherited class you first ...
4,352,226
4,352,266
Overhead of creating a new class
If I have a class defined as such: class classWithInt { public: classWithInt(); ... private: int someInt; ... } and that someInt is the one and only one member variable in classWithInt, how much slower would it be to declare a new instance of this class than to just declare a new integer? What about when you h...
With a compiler not written by drunk college students in the wee hours of the morning, the overhead is zero. At least until you start putting in virtual functions; then you must pay the cost for the virtual dispatch mechanism. Or if you have no data in the class, in which case the class is still required to take up som...
4,352,278
4,352,299
Checking whether a template argument is of a class type?
How to check using some template hack whether a template argument passed is of class type? Example int main() { CheckIfClass<int>::checkConst ; No it is not of a class type class CLASS{}; CheckIfClass<CLASS>::checkConst ; Yes CLASS is a class. CheckIfClass<std::string>::checkConst ; Yes std::string is a cla...
SFINAE should do your job #include <iostream> template<typename T> struct Check_If_T_Is_Class_Type { template<typename C> static char func (char C::*p); template<typename C> static int func (...); enum{val = sizeof (Check_If_T_Is_Class_Type<T>::template func<T>(0)) == 1}; }; class empty{}; // Defined the cl...
4,352,333
4,352,368
can I build a vector of vectors of structs with vectors of structs? (yes, really)
I am attempting to build a relatively complex data structure (for me). My goal is to read words from text documents and index the words and some specific properties into a hash table. The table is constructed from a vector of vectors of structs: (vector < vector > vecName;). This much I have had luck with. Each unique...
I don't know about design choice of the data structure apart from making it a hasmap but your code is almost correct! Check out my comments: int main() { int Tsize = 20000; wordProps testProps; testProps.theFile = "test1"; testProps.theCount = 1; // create your wordLoc object wordLoc wl; ...
4,352,346
4,352,529
Random shuffle and function pointers
I have the following function, which generates an integer in a given range: 18 int choosecard(){ 19 boost::uniform_int<> dist(0,51); 20 boost::variate_generator< boost::mt19937&, boost::uniform_int<> > cardchoice(gen, dist); 21 return cardchoice(); 22 } I want to use it as an argument to std::random_s...
There are "too many arguments" because std::random_shuffle is trying to pass too many arguments to the callback that you gave it. So it's really too few parameters. Your choosecard is supposed to accept one parameter, of type ptrdiff_t, which tells the function the number of elements, basically. (You are not supposed t...
4,352,421
4,353,362
What is the difference between for(;;) and while(1)?
Possible Duplicate: Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it? I was wondering what is the difference between for(;;) and while(1) when both perform same function? Will there be any difference of speed of compilation
The difference with these is that many compilers will warn about while(true) ("constant expression used as loop expression"), while none I know of warn about for(;;). They should generate the same code, though.
4,352,425
4,352,469
What should I learn first before heading to C++?
I'm learning C, but after that or in the meanwhile, what should I learn first and subsequently before getting into C++ ? Compilers, Data Structures, UML or Design Patterns ?(also when start to learn Win32 API ?) I'm not in a hurry at all, so I can grasp the requirements from the deepest beginning. I just don't want to...
First you should learn that C++ is not a superior language. C has its uses as more than a stepping stone into C++. C, and "C-style" C++ are used because they: Generate smaller binaries Use less memory Compile faster Do not require OS-support Are simpler, and easier to implement Data structures are by far the most use...
4,352,451
4,352,660
Coroutine demo source /2
Can somebody explain why this code doesn't work on codepad? A modified version (with virtual function) actually works though - Working version - http://codepad.org/5rRIg5zT Not working version (below) - http://codepad.org/4PO2rBqS I mean, is that actually valid C++, or codepad compiler is wrong? Update: there's anothe...
In the non-working version, if I change struct index : coroutine<index> { to struct indexX : coroutine<indexX> { then it suddenly compiles (using GCC). Apparently there is an 'index' already defined somewhere in a header file that interferes with the index of your code.
4,352,623
4,352,657
How to read & understand C & C++ Standards and the language grammar used therein?
I often find C and C++ Standards difficult to read and understand, even the simple English sentences and their wordings give terrible experience. On the top of it, the language grammar is totally hell. I'm sure many share the same feeling, at least my friends do. I would like to understand it by some examples. Lets beg...
Here's a description of the C++ grammar for expressions, which defines assignment-expression as assignment-expression: conditional-expression unary-expression assignment-operator assignment-expression In plain English, an assignment-expression can be either a conditional-expression OR a unary-expression, fol...
4,352,656
4,352,700
C++ character array allocation error
I have a function designed to get a file's contents: bool getFileContents(std::string loc, std::string &code) { std::ifstream file(loc.c_str()); if(!file.is_open()) return err("Source file could not be read"); int length; file.seekg(0, std::ios::end); length = file.tellg(); file.seekg(...
Well, the problem is that code = buffer relies on a NUL (\0) character to know where the buffer ends. You may be getting the NUL character by chance sometimes (esp. when the program has just started), but not always. Hence the intermittent behaviour. Try replacing code = buffer with code = std::string(buffer, length).
4,352,668
4,352,695
Can I pass an object to another process just passing its' pointer to a shared memory?
I have a very complicated class(it has unordered_map and so on on inside it) and I want to share an object of it withit two my processes. Can I simply pass just a pointer to it from one process to another? I think, no, but hope to hear "Yes!". If "no", I'd be grateful to see any links how to cope in such cases. I need ...
No, process do not (naturally) share memory. If boost is an option, so you can have a look on Boost.Interprocess for easy memory sharing.
4,352,880
4,352,936
Full specialization of method template from class template
I know this subject should be pretty much dated by now, but I'm having a tough time with this specific case. Straight to the point, this is what I want to do: enum MyEnum { E_1, E_2 }; template <MyEnum T> class MyClass { // method to be fully specialized template <typename U> void myMethod(U value)...
C++03 [$14.7.3/18] says In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member tem...
4,352,903
4,353,039
C++ symbol mangling and exporting => Allow code duplication?
In our project we have something like this: struct PointI { // methods for getting, setting and calculating some point stuff private: int x; int y; }; struct PointD { // methods for getting, setting and calculating some point stuff private: double x; double y; }; I proposed to change that into something...
Your boss (or whatever) is probably right. If you write a library that should be usable from other languages than C++, it is generally a good idea to write the interface in C only. Of course, you can still internally use templates, just don't expose them.
4,352,920
4,353,222
warning: XXXX has different visibility (default) in YYYY and (hidden) in ZZZZ
I am trying to make an iPhone app that uses OpenCV plus another C++ Library. It seems to compile and link fine. It actually works. Is just I want to get rid of this ugly warning: ld: warning: std::vector<int, std::allocator<int> >::_M_insert_aux(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > ...
It seems libcxcore.a and combination.o are compiled with different symbol visibility options. Read about symbol visibility there. So, I guess you just need to compile combination.cpp with -fvisibility=default flag. If you use XCode, check "Symbols Hidden by Default" setting in "GCC - Code Generation" section. It shoul...
4,352,939
4,353,286
OpenCV doesn't report accurate frame rate/count
I have a 33 second video that I'm trying to process with OpenCV. My goal is to determine what instance in time (relative to the start of the video) each frame corresponds to. I'm doing this in order to be able to compare frames from videos of the same scene that have been recorded at different frame rates. What's wor...
Always inform the software version you are using: which OpenCV version are you using for that? Yours might be an old version, so update to the most recent if possible. If your video file is part of some other larger video, this information might actually be correct, since: CV_CAP_PROP_POS_MSEC - film current position i...
4,353,116
4,354,755
Listing the exported functions of a DLL
I'm looking for a way (in C++/Windows) to list the exported functions of a DLL (and maybe even methods which are not exported) using dbgHelp. Does anybody know which method can do it?
There is code here to do this. I have cleaned it up a bit and it worked in the scenario shown below, retrieving function names from Kernel32.Dll. #include "imagehlp.h" void ListDLLFunctions(string sADllName, vector<string>& slListOfDllFunctions) { DWORD *dNameRVAs(0); _IMAGE_EXPORT_DIRECTORY *ImageExportDirec...
4,353,175
4,354,194
Getting position of mouse click in a QLabel
What is the best (as in simplest) way to obtain the pos of a mousePressedEvent in a QLabel? (Or basically just obtain the location of a mouse click relative to a QLabel widget) EDIT I tried what Frank suggested in this way: bool MainWindow::eventFilter(QObject *someOb, QEvent *ev) { if(someOb == ui->label && ev->type()...
You could subclass QLabel and reimplement mousePressEvent(QMouseEvent*). Or use an event filter: bool OneOfMyClasses::eventFilter( QObject* watched, QEvent* event ) { if ( watched != label ) return false; if ( event->type() != QEvent::MouseButtonPress ) return false; const QMouseEvent* const...
4,353,203
4,353,333
Thou shalt not inherit from std::vector
Ok, this is really difficult to confess, but I do have a strong temptation at the moment to inherit from std::vector. I need about 10 customized algorithms for vector and I want them to be directly members of the vector. But naturally I want also to have the rest of std::vector's interface. Well, my first idea, as a l...
Actually, there is nothing wrong with public inheritance of std::vector. If you need this, just do that. I would suggest doing that only if it is really necessary. Only if you can't do what you want with free functions (e.g. should keep some state). The problem is that MyVector is a new entity. It means a new C++ devel...
4,353,436
4,354,830
Iterator issues continue
I have bug checked this code considerably now and made sure I am outputting the 'correct' things to outline the problem. The iterator never points at the list at all, but another bunch of addresses which happily contain the correct data. I have two questions: 1 = given the form of the couts, am I outputting the corre...
Ok it seems to be working ok then (according to the last example). It reaches the last element and then stops (the ones with the while never reach the last element because they fail the condition on the last element). The key here is that .end() and .back() point to different things so that difference of addresses is t...
4,353,519
4,353,552
How to move the parent window in Child window?
Currently, I use: ::SendMessage(GetParent(),WM_NCLBUTTONDOWN,HTCAPTION,0); to put the parent window in moving and sizing modal, but this has some side effects. so i'm looking for another way to let the parent go into the moving and sizing modal.
See WM_SYSCOMMAND. Pass SC_MOVE as the wParam value and 0 or -1 as the lParam value.
4,353,753
4,353,758
Mac and Windows difference header path (/ vs \)
I have a Windows project that also works on XCode. But I had to changed all the source header paths like #include "Adapter\EngineAdapterFactory.hpp" to #include "Adapter/EngineAdapterFactory.hpp" This is quite annoying and I might have to reverse the process for Visual Studio later. How can others solve this problem?...
You should be able to use Adapter/EngineAdapterFactory.hpp on both platforms. (At least that's the case with GCC on Windows.) Actually, that's not just the trait of compilers - even with Windows Explorer you should be able to navigate with / as directory separator. Open up Explorer and insert in your address bar someth...
4,353,778
4,353,799
analyzing assembly code of some c++ code
I were asked to analyze an assembly code, which was generated from following c++ code in Visual studio IDE: here is c++ code: int plus(int a,int b); int main() { cout<<plus(2,4); getchar(); return 0; } int plus(int a,int b) { static int t=2; return a+b+t; } And here is the assembly code (the ...
Here is the complete tutorial: http://www.codeproject.com/KB/cpp/reversedisasm.aspx Please ask a specific question if you have ? Your original question is too broad.
4,353,780
4,353,788
Why floating point value such as 3.14 are considered as double by default in MSVC?
Why do I need to put 3.14f instead of 3.14 to disable all those warnings ? Is there a coherent reason reason for this ?
That's what the C++ (and C) standard decided. Floating point literals are of type double, and if you need them to be floats, you suffix them with a f. There doesn't appear to be any specifically stated reason as to why, but I'd guess it's a) For compatibility with C, and b) A trade-off between precision and storage. 2...
4,353,894
4,407,578
How can I read from memory just like from a file using wistream?
In my previous question I asked how to read from a memory just as from a file. Because my whole file was in memory I wanted to read it similarly. I found answer to my question but actually I need to read lines as a wstring. With file I can do this: wifstream file; wstring line2; file.open("C:\\Users\\Mariusz\\Desktop\...
I assume that your data is already converted into the desired encoding (see @detunized answer). Using my answer to your previous question the conversion is straight forward: namespace io = boost::iostreams; io::filtering_wistream in; in.push(warray_source(array, arraySize)); If you insist on not using boost then the ...
4,354,004
4,354,065
Reducing template complexity in C++
Recently, I've been using one of the lesser-used STL features- custom allocators, and I need some serious help in reducing my semantic overhead. Take for example, the definition of an unordered map, which maps filenames to an unordered map of a pair of ints and a shared_ptr to a Token, but using a custom allocator. typ...
icecrime's solution can also be done with only slightly more ugliness on older compilers via the code below. You also may be able to add factory functions to simplify construction. template<typename K, typename V> struct unordered_map_type { typedef std::unordered_map< K, V, std::hash<K>, ...
4,354,140
4,354,163
C++ symbol referencing error
I've been trying to find what the problem is to this following code part. I've written a custom exception class where I have a base class for stack errors, and then some classes deriving from it one of them called stack_full_error. I have some problem compiling it though, I get the following error. Undefined ...
Pure virtual or not, stack_error must define its destructor because it is implicitly called from stack_full_error destructor. You should add : stack_error::~stack_error() {} in an implementation file.
4,354,152
4,354,243
Multithreading - Disconnect TCP Connection
I create a thread to receive on a blocking socket, It waits until the packets arrive. However when I try to disconnect from primary thread, race conditions occur between the threads which lead to errors. Here the switch occurs at line 5 between threads without actually finishing the disconnect call. void Disconnect() {...
Here are two possible solutions. You can isolate ALL socket access in the socket (non-primary) thread, and instead of disconnecting the socket from the primary thread, have that thread signal the non-primary thread that disconnect (or some other action) is needed. This would require your secondary thread to wait on tw...
4,354,282
4,354,299
C++ method variable declaration
Currently I'm looking into this C++ source code. I'm not a C++ dev. void SomeClass::SomeMethod() const { vector<Thing> things(count); ... //Elements are added or replaced in things but no deallocation of things here } SomeMethod is called a lot of times. Could anyone confirm that there is no leak and t...
The vector is created everytime you enter the function and destroyed (destroying all objects and freeing all the memory) when it leaves scope (when the function ends). There's no leak, but there's a lot of allocations and deallocations if you call that function frequently. You have 2 solutions to avoid that: (preferre...
4,354,337
4,354,632
hijri (islamic) calendar problem!
I would convert Gregorian date to Hijri (Islamic) date. After may search on the web, I found a source code to convert it. I converted the code from Java and PHP to C base. The implement some times working without any problem. But some days has problem. I need your help either fix the implement or a available code that ...
Assuming this is for a Mac (Cocoa) or iOS (Cocoa Touch) app, since that's where you see Objective C most often, then you can just do something like this: // Create a Gregorian Calendar NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // Set up components of a Gregori...
4,354,366
4,354,370
Locked write, unlocked read
Algorithmic question How to allow only the following types of threaded operations on an object? multiple simultaneous reads, no writes single write, no reads Example: wrapper for STL container allowing efficient search from multiple threads. For simplicity, let assume no iterator can be accessed from outside of the ...
Use boost::shared_mutex to handle frequent read, infrequent write access patterns. As you've noted, STL containers are 'leaky' in that you can retrieve an iterator which has to be treated as either an implicit ongoing operation for write (if non-const) or read (if const), until the iterator goes out of scope. Writes...
4,354,411
4,354,419
Debugging native code when called from managed
I've written a C# application, where much of the work is done in a C++ back-end. Now I've been actively developing both sides, and the current iteration of the back end throws an access violation in a specific function. How can I go and debug this? VS won't break on exceptions or breakpoints in native code, nor show th...
VS will debug the native code, too, if you switch on mixed-mode debugging (and recompile your project). See the Microsoft's explanation: http://msdn.microsoft.com/en-us/library/kbaht4dh.aspx
4,354,515
4,354,548
QAbstractItemModel and QTreeView
I need working examples (c++) of show own data model in QtreeView.
There's a pretty good QTreeView/QAbstractItemModel example here. It's fairly straightforward once you get used to QT's ultra-generic model... just don't expect it to be as simple or obvious as Java's TreeModel.
4,354,659
4,357,030
Having a stream's streambuf persist beyond stream's destruction?
Is it possible to have a stream's streambuf persist after the destruction of its originating stream's destruction? streambuf* f() { ifstream my_stream; // ... return my_stream.rdbuf(); } void g() { streambuf *s = f(); // ... ifstream my_new_stream; my_new_stream.rdbuf( s ); } I.e., I want ...
It's not possible. std::ifstream constructs, owns and destroys its buffer. The only reason it's "exported" through rdbuf is to allow redirection of std::cin etc. In the GNU implementation, the buffer is a simple member (not a pointer). std::ifstream does not export the rdbuf() member with an argument. One of its parent...
4,354,873
4,354,930
Intercept close button in Qt console app
I am writing a console server in Qt. I have to run a function when the app is closing however I tried connection to QCoreApplication's aboutToQuit signal but it doesn't get emitted when I press the x on the top of the console. What is a good multiplatform way to run a function just as the console app is about to exit.
I think you should try to use a function "atexit" from C Library. See more here. Good luck.
4,355,094
4,355,130
boost::thread: How to start all threads, but have only up to n running at a time?
In the boost::thread library, is there any mechanism to control how many threads (at most) are running at a time? In my case, it would be most convenient to start N threads all at the same time (N may be hundreds or a few thousand): std::vector<boost::thread*> vec; for (int i = 0; i < N; ++i) { vec.push_back(new bo...
Don't think Boost.Thread has this built in but you can overlay Boost.Threadpool (not an official library) onto Boost.Thread, and that does allow you to control the thread count via SizePolicy. The default is a fixed-size pool which is what you want - specify the initial (and ongoing) thread count on the threadpool cons...
4,355,222
4,355,229
Where should I put documentation comments?
In the header file containing the forward declarations, or in the .cpp file containing the implementations, like this? //header.h /* About foo() */ void foo(); /* About bar() */ int bar(); /* About A */ class A { public: /* About A's constructor */ A(); .... } Or //implementation.cpp /* About foo() */ void...
For usage information, it's nicer to put into the header. That's where people would look first. The documentation is really successful if no one has to examine your .cpp file to figure out how the component should be used.
4,355,330
4,355,340
stringstream::operator>> only read, and not extract next token from stream
How can I just read the first new "token" (standard non-whitespace character sequence, as beautifully extracted by operator>>) without removing it from the stream? Can I extract the string, check if it needs to be put back, and reset the internal stream iterator? I think this might work, but have no idea how to impleme...
Would a tellg and seekg work here before and conditionally after the stream extraction? Yes.
4,355,460
4,355,473
Array index loop variable resets to zero in C, C++
I have declared an array of length N (suppose). Now, I assign some values to the elements of this array using a loop (the loop variable is used as the array's index). The code's as follows: int main() { int arr[4], j; for(j=0; j<10; j++) { printf("%d\n", j); arr[j] = 0; sleep(1); printf("%d\n...
Your array has 4 elements and your index is out of range so you are just stomping on memory. Given the code here, I'd expect arr[4] to reset the array, but since you mentioned that it's of length N and N+2 is what causes it, there might be some padding in your stack. In any case, when you declare the array and j, they...
4,355,468
4,355,485
Is it possible to delete a non-new object?
I have an object with a vector of pointers to other objects in it, something like this: class Object { ... vector<Object*> objlist; ... }; Now, Objects will be added to list in both of these ways: Object obj; obj.objlist.push_back(new Object); and Object name; Object* anon = &name; obj.objlist.push_back(a...
Yes, there will be adverse effects. You must not delete an object that was not allocated with new. If the object was allocated on the stack, your compiler has already generated a call to its destructor at the end of its scope. This means you will call the destructor twice, with potentially very bad effects. Besides cal...
4,355,517
4,355,946
Problem with simple UDP client/server application
Ok. So I have a simple client program sending images over UDP to a specified IP address. At the specified IP a server program is listening and should receive the images. When I try both programs on localhost (i.e. they are both running at 127.0.0.1) it works and the server receives the images. When I try to put the cli...
This is not a solution but your code should be checking iRcvdbytes for error in the same way as the send code checks the result of sendto. A return of 0 means the socket was closed gracefully (if connection-oriented - that should not apply here), SOCKET_ERROR means an error (in WinSock2 at least). The socket on the s...
4,355,562
4,357,674
let the user use a function in c++
Possible Duplicate: Dynamic source code in C++ is it possible to let the user type in a function and then run that function without using a lot of if's or a huge switch?
It is not possible to execute arbitrary c++ code in your program, since you than need a c++ compiler inside your program. But you could try to embed Python to your program. Boost python makes this relatively easy. The user can than write a python function that is executed and can interact with the classes and functions...
4,355,570
4,355,657
Optimize indexed array summation
I have the following C++ code: const int N = 1000000 int id[N]; //Value can range from 0 to 9 float value[N]; // load id and value from an external source... int size[10] = { 0 }; float sum[10] = { 0 }; for (int i = 0; i < N; ++i) { ++size[id[i]]; sum[id[i]] += value[i]; } How should I optimize the loop? I ...
This kind of loop is very hard to optimize using SIMD instructions. Not only isn't there an easy way in most SIMD instruction sets to do this kind of indexed read ("gather") or write ("scatter"), even if there was, this particular loop still has the problem that you might have two values that map to the same id in one ...
4,355,653
4,355,687
How do I allocate memory within this function?
I have the following function and a hierarchy of classes such that Multinumber is inherited by Pairs, Rational, and Complex. All of these share functions which are virtual in Multinumber. My problem is the following code. The way it is written right now, the newElement variable goes out of scope when it is added to my ...
In the real world (I understand from your previous question that this is for homework), you wouldn't implement your own set. The standard library provides this functionality (std::set if you want to keep the elements in order; std::unordered_set if you're using C++0x and/or have the appropriate extensions, and prioriti...
4,355,660
4,355,677
How to declare a friend that is a member function of another not yet defined class in C++?
How I declare B's constructor to be a friend of A? I tried: class A { private: A(); public: friend B::B(); }; class B { public: B(); };
replace B:: with class; class A { private: A(); public: friend class B; }; class B { public: B(); };
4,355,751
4,356,103
OpenGL using GL_STENCIL with a sphere
I'm working with OpenGL and I am trying to create a sphere that has a reflective surface. I have it reflecting but the reflection isn't correct. The object in the reflection should be bent and deformed according to the curve of the surface, instead I'm getting only a straight reflection. I haven't used GL_STENCIL much ...
Have you considered using reflection/environment mapping? There are 2 main forms. Spherical environment mapping usually works by having a pre-calculated environment map. It can, however, been done dynamically. Its main drawback is that it is view dependent. The other system is Cubic Environment mapping. Cubic is ver...
4,355,941
4,356,152
Qt/C++: QTableView contextmenu and passing through information
I want a contextmenu on the cells in my QTableView, so first I connected: connect(ui->tblTimesheet,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(sheetContextMenu(const QPoint &))); And the slot for that connect is below: void wndMyWindow::sheetContextMenu(const QPoint &pos){ QMenu *menu = new QMenu; QMo...
In this regard, Qt signals/slots suck compared to callbacks and other signal/slot mechanisms. You really can't attach extra information. Couple things you can do though: Create an object that stores the information you want to send, give it a slot and attach to the signal you want to respond to, emit a new signal wit...
4,355,979
4,356,006
How many cores do I have?
Possible Duplicate: Programmatically find the number of cores on a machine I have a multi-threaded C++ program that runs on Windows, MacOS and Linux. Is there an easy way to find out how many cores the machine on which I am running currently has? My system runs best when it has 1 thread for each core.
I believe this question may contain your answer: Programmatically find the number of cores on a machine Edit: I just voted up ybungalobill's answer. I love boost!
4,356,004
4,356,073
C++ constructor call - need help figuring how certain calls are made
class PayOffBridge { public: PayOffBridge(); PayOffBridge(const PayOffBridge& original); PayOffBridge(const PayOff& innerPayOff); inline double operator()(double Spot) const; ~PayOffBridge(); PayOffBridge& operator=(const PayOffBridge& original); private: PayOff* ThePayOffPtr; }; and a...
1st answer VanillaOption expects PayOffBridge object as a constructor parameter. But, you pass PayOffCall object instead. Compiler looks for a way to construct temporary PayOffBridge object from given PayOffCall object. It has PayOffBridge(const PayOff& innerPayOff); constructor. So, it needs a reference to PayOff obje...
4,356,074
4,356,124
gdb detected a segmentation fault. How to pinpoint the exact source?
(gdb) s Things:action (this=0x7fffffffdce0, packet=0x62c980) at file:41 41 if( thing->work(data) ) { (gdb) s Program received signal SIGSEGV, Segmentation fault. 0x00000000004040e1 in Things:action (this=0x7fffffffdce0, packet=0x62c980) at file:41 41 if( thing->work(data) ) { In a backtrace, ...
As I said in the comment : I believe that the execution never reached work(data) because the this pointer is invalid (0x7fffffffdce0 looks like garbage). The SIGSEGV is on this->. Has the object been destroyed / deleted at some point, and have you kept a reference or pointer to it ?
4,356,084
4,356,167
why C++ uses DOT to access structure members and -> to access method?
I come from a Delphi/Pascal programming world but I also "play" around with C++ or C once in a while, there is a question that bothers me the most: why does C++ use "." to access a structure member and "->" to access method? in Delphi/Pascal we use "." for any of those even properties... Someone told me it has somethi...
All structure members (fields and methods) are accessed same way. But, in case of pointer to structure, there is two different syntaxes for the same purpose: (*pStruct).member and pStruct->member. In Pascal (or Delphi): var pointerToSomeRecord: ^SomeRecord; pointerToSomeRecord^.field := 42; In C++: SomeStruct* pointe...
4,356,270
4,356,332
How to programmatically open Run c++?
the question is how to open Run programmatically from c++? I know that have some function that can replace that, like shellexec, winexec but for some task I need just Run dialog to appear.
The Run Dialog is located in shell32.dll using the function RunFileDlg. One way show the dialog is to use rundll32.exe to invoke that function. Execute the following command using the CreateProcess Win32 API: rundll32.exe shell32.dll,#61 (where #61 is the ordinal number of the RunFileDlg function). Reference for shell...
4,356,498
4,356,515
Hiding RNG inside class
I am currently implementing a Deck class that represents a 52 card playing deck. It uses the boost Random library to shuffle integers that represent cards. #include <iostream> #include <fstream> #include "constants.hpp" #include <boost/program_options.hpp> #include <vector> #include <boost/random/mersenne_twister.hpp>...
If you're making it a normal class variable, initialize it in the constructor: class Deck { ... public: boost::mt19937 gen; }; Deck::Deck() : gen(std::time(0)) { ... } If you're making it static (it looks like you are, since you're using gen from choosecard, which is static), you still need a decl...
4,356,690
4,356,715
Pass 'this' object to an initialization list
I've reduced the problem down to the following sample code: class Charizard { //truck trainer &myTrainer; public: Charizard(trainer &tMyTrainer); }; class trainer { Charizard myPokemon; public: trainer(); }; Charizard::Charizard(trainer &tMyTrainer) : myTrainer(tMyTrainer) {} Without changing or ...
If you need an instance object instead of a pointer, try: trainer::trainer() : myPokemon(*this) {} Be careful if Charizard tries to call any methods on tMyTrainer in its constructor, because your new trainer object has not yet been fully constructed at that time.
4,356,778
4,356,880
Typedefing pointer types
I've been reading around SO and have come across the following questions which touch on why typedefing pointer types is bad. Opaque C structs: how should they be declared? and Const-correctness and immutable allocated objects I was wondering if someone could expand and explain why typedefing pointer types is bad and pe...
Johannes has already remarked that typedef'ing pointers is not inherently bad, and I agree. Some guidelines, based on my subjective opinion of clarity & maintainability: Generally do typedef function pointer types. Reason: Function pointer declarations can get really messy & unreadable. Generally don't typedef raw obj...
4,356,928
4,357,815
SDL_ttf will not render
I've got a problem with SDL_ttf, no matter what I do with the TTF_RenderText_Solid function, it refuses to render any text what so ever. My source code is a little bit hefty to put in this question (It's like 150 lines or something) so I'm putting the links to them on Pastie. I want to note, that even though I am putti...
Well, since you've not provided any code that makes TTF_RenderText_Solid calls, I can only take shots in the dark. did you call TTF_Init? Have you loaded a font? Are you sure? What does TTF_RenderText_Solid do? "Refuses to render" tells me nothing of value. Does it return NULL? Does it return non-NULL? If it is return...