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
7,628,231
7,628,259
Can specializations of a template function be virtual?
Something like, for example, class A { template<typename T> T DoStuff(); template<> virtual int DoStuff<int>() = 0; }; Visual Studio 2010 says no, but I get a funny feeling that I simply messed up the syntax. Can explicit full specializations of a member function template be virtual?
Explicit specializations aren't legal within a class. Even if you could make it a partial specialization you would still run into the "templates can't be virtual" problem. n3290, § 14.5.2 states: A member function template shall not be virtual. And gives this example: template <class T> struct AA { template <class ...
7,628,261
7,628,291
Alias Methods and Performance Concerns
In order to improve code readability, sometimes I use "alias methods". These are basically methods that all do the same thing (at least in the base class; derived classes may do it differently) with different names, that enhance code readability for the class user depending on the context. Consider the code below for a...
Assuming the aliased functions are inlined - and they should given the size. There shouldn't be any performance overhead. The code-size won't increase either if the compiler decides to omit the function code and inline all calls to it. (I'm referring to the inlining of bar_alias1(), bar() itself won't necessarily be in...
7,628,333
7,628,345
Constructor with by-value parameter & noexcept
In this example code: explicit MyClass(std::wstring text) noexcept; Is the use of noexcept here correct? wstring can potentially throw on construction but does the throw happen before we are in the constructor or while we are in the constructor? EDIT: Suppose this can be generalised to any function taking a by-value p...
The construction and destruction of function parameters happens in the context of the caller. So no, if the construction of text throws, that is not a violation of noexcept. Soon folks would comment and ask for a spec quote :) So I will give you 5.2.2p4 The initialization and destruction of each parameter occurs with...
7,628,352
7,628,374
Hotswapping / Edit and continue for C/C++, Linux
I'm looking for an IDE that supports a (Visual Studio's) Edit and continue -like feature. I know Netbeans has it for Java (called hotswapping, Fix and continue), but can not find anything about an implementation for C/C++ for Linux systems. Any help would be very much appreciated.
To the best of my knowledge, this feature is not available in the GCC toolchain. The closest you'll get is the gdb's rewind, but that's not the same.
7,628,434
7,628,468
DWORD and unsigned int
I'm getting this error and can't correct it. Any help is appreciated. Thanks. error C2440: '=' : cannot convert from 'DWORD *' to 'unsigned int' IntelliSense: a value of type "DWORD *" cannot be assigned to an entity of type "unsigned int" using namespace std; typedef vector<WIN32_FIND_DATA> tFoundFilesVector; std::wst...
The error is here: curTime = ((_int64) &ftNow.dwHighDateTime << 32) + &ftNow.dwLowDateTime; dwHighDateTime and dwLowDateTime are already of type int. Yet you are taking the address of them. Therefore the assignment to curTime becomes pointer to int. What you want is this: curTime = ((_int64) ftNow.dwHighDateTime << 3...
7,628,451
7,628,536
Does boost::crc_32_type generate any exceptions?
Assuming that BufferLenght is >=0 and *Buffer is a valid buffer will the following code generate exceptions? What about if Buffer is invalid? Are there any cases where it can generate exceptions and how to handle them? unsigned CRC32(const void *Buffer, unsigned BufferLength) { boost::crc_32_type result; re...
Boost CRC looks to be exception neutral. no exceptions are documented no exceptions are thrown from crc.hpp
7,628,476
7,628,598
How to profile a C++ function at assembly level?
I have a function that is the bottleneck of my program. It requires no access to memory and requires only calculation. It is the inner loop and called many times so any small gains to this function is big wins for my program. I come from a background in optimizing SPU code on the PS3 where you take a SPU program and r...
There are some great free tools available, mainly AMD's CodeAnalyst (from my experiences on my i7 vs my phenom II, its a bit handicapped on the Intel processor cause it doesn't have access to the direct hardware specific counters, though that might have been bad config). However, a lesser know tool is the Intel Archit...
7,628,498
7,628,850
boost::variant single storage guarantee
My goal is to guarantee single storage on all my variant types: according to 'never empty' guarantee from Boost::variant, we need to override boost::has_nothrow_copy for each bounded type. But a bit later the documentation mentions something about 'boost::blank' and if that type is bound, variant will set that value ra...
I believe that is made clear. Here is the relevant section from the boost documentation: Accordingly, variant is designed to enable the following optimizations once the following criteria on its bounded types are met: For each bounded type T that is nothrow copy-constructible (as indicated by boost::has_nothrow_co...
7,628,506
7,628,526
How do I pass an argument that was passed to main (in argv) to my function?
How can i pass argv[] to my function?, I am getting the errors when I run my program. I am new to c++ but i think i am not passing it right look at the error and my code. Now dont worry about the Depth First algorithm.. i will get to that later.. I am just trying to make this work.., basically I just want to pass the *...
I think you meant to write opendir(arg_temp). arg_temp[1] is the second character of arg_temp. I wouldn't recommend using global variables to pass things to your function though anyway.
7,628,562
7,628,570
implementation counting sort
here is code for counting sorting #include <iostream> using namespace std; int main(){ int a[]={2,3,1,2,3}; int n=sizeof(int)/sizeof(int); int max=a[0]; for (int i=1;i<n;i++) { if (a[i]>max) { max=a[i]; } } int *output=new int[n]; for (int i=0;i<n;i++) { ...
int n=sizeof(int)/sizeof(int); is wrong. That just assigns 1 to n. You mean int n=sizeof(a)/sizeof(int); I've not looked beyond this. No doubt there are more problems, but this is the most significant. This is the kind of thing you can work out very easily with a debugger.
7,628,569
7,628,587
Two operators simultaneity overload in c++
I want to represent my object like an array. I mean that the programmer can write in his code myobject[3]=2 In the back (in myobject code) there isn't an array at all, it's only representation. So I need to overload [] and = simultaneously. How can this be done? thank you, and sorry about my poor English.
operator[] should return a reference to object you are trying to modify. It may be some kind of metaobject, that overloads operator= to do whatever you wish with your main object. Edit: As the OP clarified the problem, there is a way to do this. Look here: #include <vector> #include <iostream> int & func(std::vector<i...
7,628,614
7,629,067
Listening socket connecting without accept being called on Linux
I am running code on Ubuntu Linux it is supposed to use a Set and select to check when a listening socket has activity (ie someone trying to connect) and let them connect, the trouble is select ALLWAYS returns 0, and when I try to connect it just connects straight away. but on the server Accept is never called as selec...
select() requires the largest fd+1. You give it the largest fd, unmodified. If you see this error on Linux and not Windows, this is the most likely cause.
7,628,653
7,628,701
How can I make my TCP listening app safer?
I’m looking for advice on writing a very safe C/C++ app that will listen to a tcp port. I'd like to peek at what others are trying to do to my machine, but I’d rather not install an elaborate honeypot app if I can do what I need with a very short program. With my goal being simple and safe, I want to make sure I handle...
2) The client(s) should not be able to overload the server with too many connections... Your best options is letting the router limit how many connections an IP address makes, as, by the time your program gets the connection info there are system resources already allocated. 1) The client should not be able to sen...
7,628,779
7,628,810
C++ - Undefined reference to an object
Compiler: MinGW IDE: Code::Blocks Platform: Windows XP External libraries: SDL, SDL_image What I'm trying to do: Cap the framerate at 60 frames per second using a timer that resets after each loop. Just a warning, I AM inexperienced with C++, but I've done research and I can't find this kind of error anywhere else. I'm...
fps is a variable of type timer, declared in data::OnExecute(). However, you also reference fps in another method data::OnLoop(), where fps is out of scope. To fix this, I recommend making fps a member-variable of class data. Then fps will always be available inside all the methods of data. Do this by declaring fps ri...
7,628,841
7,628,879
Stop app window overlapping Windows start bar
On my Win7 PC I have the start-bar running vertically, it's about 60px wide. In my win32 application, the created window always appears overlapping the start bar, which looks bad - I just use (0,0) as the top-left position for the window. How should I be doing it to get (0,0) relative to the desktop, taking the Start B...
There are a few problems here. You don't want to use a hard-coded value like (0,0). That might not even be visible on a multi-monitor system. As you have discovered, you should try to avoid overlapping with the taskbar or other appbars. If there are multiple monitors you should try and start on the monitor where the u...
7,629,139
7,629,226
Printing all the directories using c++
This program is printing the directories at the root level Directory_1 Directory_2 but I want to be able to print the directories within them too Directory_1 Directory_1_2 Directory_1_3 Directory_2 Directory 2_1 Directory_2_1_1 Directory_4 I am trying to do it recursively but I am finding it hard to pa...
Well this should help: #define _XOPEN_SOURCE 500 #include <ftw.h> #include <stdio.h> static int display_info(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) { switch(tflag) { case FTW_D: case FTW_DP: puts(fpath); break; } return 0; /* To tell nftw()...
7,629,155
7,629,906
Cache gauss points for numerical integration in c++
This is a question on what people think the best way to lay out my class structure for my problem. I am doing some numerical analysis and require certain "elements" to be integrated. So I have created a class called "BoundaryElement" like so class BoundaryElement { /* private members */ public: integrate(Point& pt); };...
I had a similar issue once and used a map (as you suggested). What I would do is change the GaussPtsWts to contain the map: typedef std::map<int, std::vector<std::pair<double, double>>> map_type; Here I've taken your two arrays of the points and weights and put them into a single vector of pairs - which should apply ...
7,629,194
7,629,258
How do you lay out your custom binary file format?
Every application has its own custom binary file format (e.g. .mpq, .wad). On top of that, its commonly zipped. So, my question is, how do you artfully/skillfully layout the binary contents of your file. Do you have a "table of contents" like structure at the beginning? Is it better to dump everything in one file? S...
My favorite article on the topic of file formats is at http://www.fadden.com/techmisc/file-formats.htm. Beyond that, it probably comes down to what kind of data you are storing, and how that data will be used (will it be transmitted across a network, primarily? How important is seek access? Etc...). Start with that a...
7,629,230
7,629,328
Using std::vector<boost::function> with boost::bind
While trying to get comfortable with boost, stumbled into problem with using boost::function along with std::vector. I'm trying to do a simple thing: have a list of functions with similair signatures and then use all that functions with std::for_each on sample data. Here is the code: typedef boost::function<int (const ...
The problem with your code is that you are trying to create a functor in place in a way that is not allowed (you cannot just throw code at the third argument of for_each, you need to pass a functor). Without lambda support in the compiler you can use std::transform rather than std::for_each (not tested... but this shou...
7,629,259
7,629,310
Transpose 1 Dimensional Array
So I have a ONE dimensional array with N values, where N is a perfect square. I visualize this one dimensional array as a two dimensional array (although it is not). For example, an array with values int Array = { 0,1,2,3,4,5,6,7,8 } That is int *Array = new int [9]; ...
With n = sqrt(N), you could just try something simple like: for(int i = 0; i < n; ++i) for(int j = i+1; j < n; ++j) std::swap(Array[n*i + j], Array[n*j + i]);
7,629,270
7,629,477
How does std::string allocate memory in GCC with -fwhole-program?
Update: The following problem appears to depend on the -fwhole-program option. I've been playing around a bit with memory allocation, and I encountered a small mystery: In GCC (4.6), how does std::string allocate its memory [edit]when I compile with -fwhole-program[/]? Have this following test program: #include <new> #...
Looking at the output of g++ ... -S with / without -fwhole-program it appears that the whole custom new/delete operators aren't emitted at all when using fwhole-program. I'm starting to suspect we're looking at a bug here.
7,629,490
7,633,000
Allegro5 and MS Visual Studio 2010
recently I treid to add Allegro5 library to Visual Studio 2010. I visited allegro.cc and downloaded package called: allegro-5.0.4-msvc-10.0 (following the name, I think it's correct one) and after extracxtion, and I copied: /bin to C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin /include to C:\Program Files...
Please see the documentation on the wiki for Allegro 5 and Visual Studio 2010. Especially note the bit about not modifying system folders like you have already done. Anyway, the problem here is that you are trying to write Allegro 4 code but you've installed Allegro 5. The two are not compatible. Allegro 5 is completel...
7,629,670
7,629,802
GNU Gettext and wide characters
I'm developing a game (actually I'm porting it from Gosu to SFML) in C++. I'm using GNU Gettext as the i18n system. As you know, gettext returns char * strings using the local encoding, usually UTF8. The problem is that I need to use wide strings for SFML to recognize the special characters such as áéíüñ. So the quest...
To convert between the system's narrow, multibyte encoding and its wide character set (agnostic of any encoding specifics), use the mbstowcs() and wcstombs() standard C functions, found in <cwchar>. Here's a previous post of mine on the subject, and here's some sample code.
7,630,024
7,630,111
How to convert IplImage(OpenCV) to ALLEGRO_BITMAP (A5) fast?
Is there a fastest way to convert a IplImage type from OpenCV to ALLEGRO_BITMAP type from Allegro 5.0.x than just putting every pixel from one to another? Like 2 for loops like this: void iplImageToBitmap(IplImage *source, ALLEGRO_BITMAP* dest) { if(source!= NULL && dest!= NULL) { al_set_target_bitmap(dest...
Use al_lock_bitmap to get an ALLEGRO_LOCKED_REGION, then set the pixel data as described. Then unlock it with al_unlock_bitmap.
7,630,083
7,630,249
Need guidance with template class and understanding line errors
and I am trying to now do a Breadth First Order for files but, when I implement this template class to use a Queue I get this errors?, any idea where this might be?, also I do not understand the way the line number where the error is, is specified (i.e myprogram.c:23:10) no idea where that is program.c:11:10: error: ex...
program.c:11:10: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘attribute’ before ‘<’ token That sounds like you're compiling the C++ source code as C. A simple fix can then be to rename the file as program.cpp. Cheers & hth.,
7,630,113
7,640,960
CXX0030: Error: expression cannot be evaluated
The short question: Why am I see this in the Locals window for my IWICImagingFactory object while in my destructor? The long explanation: I am creating a IWICImagingFactory object in my CreateDeviceIndependentResources() function: if (SUCCEEDED(hr)) { hr = CoCreateInstance( CLSID_WICImagingFactory, ...
Try calling SafeRelease() right after initialization and see if it works. Also, try invoking the clean up explicitly (with some sort of uninitialize function) instead of doing this at the destructor. When you leave clean up to destructors, sometimes you don't have full control over exactly what is being cleaned up when...
7,630,277
7,630,315
Including <queue> in c++ program in Ubuntu OS
I have a small program that uses "trying to use" #include <queue>. I use Ubuntu OS but it says: fatal error: queue: No such file or directory Any ideas why, or what I need to do to make it work? #include <queue> using namespace std; int main() { queue<int> Q; Q.push( 1 ); Q.push( 2 ); Q.push( 3 ); ...
You are compiling your C++ program (which you saved with a .c extension) with a C compiler. This won't work, since you're using the C++ STL (and namespace std). Compile using g++ instead: g++ queuetest.cpp -o queuetest See the docs for compiling C++. Consider changing your extension to .cpp as well. You'll also want t...
7,630,328
7,631,854
Using QBuffer for binary data
I am writing a Qt (4.6) application that is responsible for reading from a usb acm modem device. A mix of raw binary and (ascii) character data is read in from the device. I have a thread that is responsible for constantly reading data from the device into shared memory as it becomes available and second thread that h...
The terminating 0 is transparent to your application. For instance, if you append "ABC" to an array, "ABC\0" will be appended, but size() will still return 3 and if you subsequently append "DEF" the array will contain "ABCDEF\0" (and size() will still return 6, not 7). The terminating 0 may be useful in case you reques...
7,630,382
7,630,398
generic linked list pointer access
I am writing a generic linked list in C++ using templates, and am experiencing Segmentation Faults when accessing Node values. To make the test case simpler, I have implemented a fixed size, two node, linked list. I have two questions: 1a) Why isn't aList.headNodePtr->prevNodePtr set to NULL? 1b) Why isn't aList.tailNo...
You're not actually setting the members, you're setting the locals you declared in the ctor: Node<T>* headNodePtr; // <-- MEMBERS Node<T>* tailNodePtr; LinkedList() { Node<T>* headNodePtr = new Node<T>; // <-- LOCALS Node<T>* tailNodePtr = new Node<T>; Try this instead: Node<T>* headNodePtr; // <-- MEMBERS...
7,630,384
7,630,456
Using Queues as global and working on its contents from main
I am getting errors about the template arguments not being valid and it is not seeing that I declared my queue variables as global.., i tried putting them inside the function (but thats not what I want because i want to deque from main) and does not work either.. Here are my errors and code program.cpp: In function ‘in...
Your while statements are attempting to check the function std::queue::empty() itself, and not the result of a call to the function. The type that appears in your error message is the type of the function. As overcoder's comment says, adding parentheses will fix the code.
7,630,566
7,630,634
Normalizing histograms?
What is normalizing histograms? When and why would I use it? What are its advantages? I don't understand the concept at all- when I try to apply it to my histogram, when I use back projection, I don't get any results. Could someone give me a non-technical explanation of normalization? I am using OpenCV PS: Don't send m...
It's very simple, actually. A normalized histogram is one in which the sum of the frequencies is exactly 1. Therefore, if you express each frequency as a percentage of the total, you get a normalized histogram. What is the use of a normalized histogram? Well, if you studied probability and/or statistics, you might know...
7,630,629
7,631,524
JSONCPP Amalgamated link errors
I am trying to use the amalgamated version of jsoncpp(the latest version), but it is producing unresolved external symbol link errors. The code I am using is #include <json/json.h> int main(){ Json::Value root; return 0; } and it is giving me the error 1>main.obj : error LNK2019: unresolved external symbol "pub...
Probably you didn't include the JSONCPPs *.cpp file into your project (they have to be compiled and linked). If the library gets compiled to a static library, you have to tell the linker what to link.
7,630,806
7,720,103
The actual result of name resolution in the class template is different from the c++ 03 standard
I test the code in the c++ standard ISO/IEC 14882-03 14.6.1/9 on Xcode 4.1 and Visual Studio 2008. The outputs of the two compiler are both different from the expected result of the standard. The code is pasted below. #include <stdio.h> #include <iostream> using namespace std; void f(char); template <class T > void...
As noted in the first example, this is an instance of two-phase name lookup, which both GCC and Clang implement but MSVC does not. And in this case, both GCC and Clang are correct: it's actually the standard that is wrong, as noted in C++ core defect report #197. The C++11 standard contains a different example. This is...
7,630,852
7,630,911
confused on how my code work and want to understand the logic in it
Please dont discourage this question..I am very new to c++ and really want to understand the code I work on. // bintodec.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <string> using namespace std; int main(){ string inp; int dec = 0; ...
They are taking the ASCII input values plugged into inp, and doing a conversion to the actual decimal equivalents by subtracting off the ASCII offset for that character. At that point, they are merely adding each position of the input decimal raised to the power of the base for that decimal's positon. For instance, f...
7,630,868
7,631,904
Segmentation fault when adding a vector. (C++)
So I've got a pretty basic class that has a few methods and some class variables. Everythings working great up until I add a vector to the member variables in the header file: std::vector <std::string> vectorofstuff; If all I do is add this line then my program run perfectly but at the end, after all the output is the...
I was fooling around with it and decided to, just to be sure, do an rm on everything and recompile. And guess what? That fixed it. I have no idea why, in the makefile I do this anyway, but whatever, I'm just glad I can move on and continue working on it. Thanks so much for all the help!
7,631,063
7,631,588
Reading an array<Byte> in unmanaged c++
I have a managed C++ class, with a method whose constructor signature is: tools_package_net::PackageInfo::PackageInfo(array<Byte>^ bytes) Within the constructor I wish to call a method on an unmanaged class with the signature: bool PackageInformation::ReadProject(const unsigned char *data, size_t size) So I want to c...
cli::pin_ptr<unsigned char> pb = &(bytes[0]); unsigned char* p = static_cast<unsigned char*>(pb); According this book.
7,631,908
7,631,981
Library for logging Call Stack at runtime (Windows/Linux)
I need a way to record the function stack trace in a debug log to help me diagnose a defect. The problem is that I need to implement this on Windows and Linux using C++. After a little research, I have found that: For the Windows implementation, I can use StackWalk64 API function and family. Under Linux, I have f...
Google Breakpad handles all of this for you if you want to get crash dumps back from the field.
7,631,996
7,632,021
Remove an element from a vector by value - C++
If I have vector<T> list Where each element in the list is unique, what's the easiest way of deleting an element provided that I don't know if it's in the list or not? I don't know the index of the element and I don't care if it's not on the list.
You could use the Erase-remove idiom for std::vector Quote: std::vector<int> v; // fill it up somehow v.erase(std::remove(v.begin(), v.end(), 99), v.end()); // really remove all elements with value 99 Or, if you're sure, that it is unique, just iterate through the vector and erase the found element. Something like:...
7,632,034
7,632,052
sort vector of struct element
i am trying to sort vector of struct's elements,but i can't construct vector itself here is code #include <string> #include <vector> #include <algorithm> using namespace std; struct student_t{ string name; int age,score; } ; bool compare(student_t const &lhs,student_t const &rhs){ if (lhs.name<rhs.na...
std::vector<student_t> st; for(unsigned i = 0; i < 10; ++i) st.push_back(student_t()); std::sort(st.begin(), st.end(), &compare); You could also use this vector constructor instead of lines 1-2: std::vector<student_t> st (10 /*, student_t() */); Edit: If you want to enter 10 students with the keyboard you can write a...
7,632,120
7,632,130
Scope vs life of variable in C
Could someone exactly explain the concept of scope and life of variable in C. Is it different in C++? I'm confused between scope and life.
Scope is the region where the variable is accessible. Life time is the time span during which an object remains valid. An simple example: #include <iostream.h> void doSomething() { x = 5; //Error! Not Accessible } int main() { int x = 4; std::cout<< x << endl; { int x = 2; ...
7,632,420
7,632,460
What does this specific C++ code mean?
I have this code: Kuvio::Kuvio(Piste& paikka, string& nimi) : paikka(paikka), nimi(nimi) {} Do not care about the words. I'd like to know is that a function definition, a function call or what? I'm not familiar with C++.
It's a definition of the constructor of class Kuvio using an initialization list. It's almost equivalent to: Kuvio::Kuvio(Piste& paikka, string& nimi) { paikka = paikka; nimi = nimi; } , which is redundant. In general however, the difference is that the members are not initialized two times, as it would happ...
7,632,421
7,632,455
overload array operator with templates and pointers
The following code compiles (without warnings) on both clang++-2.9 and g++-4.6. However, the g++ binary Seg Faults, while the clang++ binary runs as intended. What is the proper way to access template class data members through pointers when overloading []? Here's the code: #include <iostream> template <typename T> ...
You are returning a reference to a local variable (res). The reference won't be valid after returning from operator[]. It could be overwritten by other stuff. What really happens is Undefined: that is why compilers are allowed to eat your children or grow a moustache: Undefined Behaviour You probably want to return by ...
7,632,437
7,632,481
Is this possible in C++? toString(ClassName* class)
I'd like to use toString with class argument, but for some reason there is an error. The code is: Animal.h #include "Treatment.h" #include "jdate.h" #include <vector> class Animal{ protected: int id; double weight; int yy; int mm; int dd; double accDose; char sex; vector<Treatment*> tre...
// Animal.h // #include "Treatment.h" remove this class Treatmemt; // forward declaration class Animal { ... }; In your version, Treatment.h and Animal.h include each other. You need to resolve this circular dependency using forward declaration. In .cpp files, include all necessary h-files.
7,632,475
14,190,206
Is there a C++ implementation of Node.js Net API?
Node.js has a very good and well thought Net API. I wonder is there a good C++ only implementation of that API as for example LuaNode do for Lua?
Take a look at node.native - attempt to implement api similar to node.js core lib, but with c++11 (and evented IO is also based on libuv)
7,632,645
7,633,081
How to set non-selectable default text on QComboBox?
Using a regular QComboBox populated with items, if currentIndex is set to -1, the widget is empty. It would be very useful to instead have an initial descriptive text visible in the combo box(e.g. "--Select Country--", "--Choose Topic--", etc.) which is not shown in the dropdown list. I couldn't find anything in the do...
It doesn't appear that case was anticipated in the Combo Box API. But with the underlying model flexibility it seems you should be able to add your --Select Country-- as a first "legitimate" item, and then keep it from being user selectable: QStandardItemModel* model = qobject_cast<QStandardItemModel*>(comboBo...
7,632,812
7,632,830
What is the proper way to work with files in C++?
I'm studying C++, now I'm reading about working with files. As I have read, there is quite a lot of variants. So I wanna ask, what is the right way to work with files in C++? Using fstream(ifstream and ofstream)? I have read some opinions that fopen works much faster, so it is better to use it, but it will be no C++. T...
Use ifstream and ofstream when working in C++. It should not be much slower than FILE*, but is much safer. See this related question.
7,633,029
7,633,049
Why does my large 5D array cause a stack overflow exception only as a member variable?
I'm currently writing a program where I need to run many simulations and speed is the name of the game. I'm currently using one long linear array allocated on heap and working out the dimensions myself and pulling straight from the index I work out. A co-worker has written a similar program and has got a good speed boo...
The static array will be directly mapped into memory, not on the stack. The member variable will be allocated on the stack, which is likely not large enough by default. Also, vector doesn't do any bounds checking in operator[].
7,633,044
7,633,179
Compiler error message with cout
I mistyped the error message before. It is fixed now. I'm currently getting the following compiler error message error: no match for 'operator<<' in 'std::cout << Collection::operator[](int)(j)' The code that the compiler is complaining about is cout << testingSet[j]; Where testingSet is an object of type Collection ...
Probably your operator should be declared as: ostream& operator<<(ostream &strm, const Example &ex) Note the const-reference to Example. Visual Studio has an extension that allows to bind a reference to a non-const r-value. My guess is that your operator[] returns an r-value. Anyway, an operator<< should be const as i...
7,633,201
7,633,263
How to cast void * to float (*)[3] in c++?
This is the code snippet. typedef struct Lib3dsMesh { //.. float (*vertices)[3]; //.. } void* lib3ds_util_realloc_array(void *ptr, int old_size, int new_size, int element_size) { // Do something here. return ptr; } mesh->vertices = lib3ds_util_realloc_array(mesh->vertices, mesh->nvertices, nvertices, 3...
vertices is a pointer to a 3-element array of float. To do a cast from one pointer type to another, you generally use static_cast: void* result = lib3ds_util_realloc_array( mesh->vertices, mesh->nvertices, nvertices, 3 * sizeof(float)); mesh-vertices = static_cast<float (*)[3]>(result);
7,634,093
7,634,118
Iterating over a list of Strings in C++, what's going wrong?
I'm trying to print out a list of strings thus: std::list<String> const &prms = (*iter)->getParams(); std::list<String>::const_iterator i; for(i = prms.begin(); i != prms.end(); ++i){ log.debug(" Param: %s",*i); } But my program crashes saying Illegal Instruction. What am I doing wrong?
*i is a String, not a char *. If log.debug() is a function of the printf family, you want a zero-terminated string. Depending on how your String class is implemented you might have a function that returns a const char *. For example with std::string that function is c_str: for(std::list<std::string>::const_iterator i =...
7,634,292
7,634,421
Game window application with additional console window
My previous demo was an XNA project that had a game window, as well as a console window for debugging information, however, the option is either not there or moved in a C++ project. Does anyone know how to enable a console window that will run alongside a game window in VS2010?
You can use AllocConsole to create a console for you process. Once you do that, you can use std::cout or, perish the thought, printf to write to the console.
7,634,343
7,634,487
Null is type object, so it's truthy? What's going on behind the scenes?
I'm reading in my book, "Elegant JavaScript", that null == true evaluates as false. Using an interpreter, I have confirmed this to be TRUE. However, later in the chapter--in fact, on the same page--, it says that when null is given as the condition of an if, while, or for statement, it will be converted to a Boolean ...
An important distinction to make is that the Type of null is Null. (ignore typeof it returns "object" for null because of bad design and backwards compatibility) 11.9.3 The Abstract Equality Comparison Algorithm # Ⓣ The comparison x == y, where x and y are values, produces true or false. Such a comparison is perf...
7,634,396
7,635,185
Implementing a binary counter using std::bitset
I want to implement a binary counter in C++ using std::bitset. If I explicitly develop an addition function for bitset then the complexity of the algorithm would go up to O(n^2). Is there any way to do this O(n)? Also are there any good descriptions of Horowitz and Sahni's Subset Sum Problem Solution? Except for Wiki...
For your second question, "are there any good descriptions of Horowitz and Sahni's Subset Sum Problem Solution?", I found few articles: Original paper from Horowitz and Sahni: http://www.cise.ufl.edu/~sahni/papers/computingPartitions.pdf Stackoverflow discussion about Horowitz and Sahni's algorithm improvements: Genera...
7,634,419
7,634,630
Doesn't std::piecewise_construct cause a ODR violation?
std::piecewise_construct, defined in <utility>, has internal linkage since it is declared constexpr. I wonder if use of std::piecewise_construct in a header can violate ODR. For example: a.hpp #include <utility> #include <tuple> struct point { point(int x, int y) : x(x), y(y) {} int x, y; }; inline...
It appears that you already have your answer in that boost mailing list posting. Yes, in my opinion it is undefined behavior or at least not sufficiently clear defined behavior. See this usenet discussion for the same matter being discussed.
7,634,445
7,634,481
Error in template: Iterator was not declared in the scope
trying to make a template, but I have an error in gcc4 but not in VS2008. This is the code that fails: #pragma once #ifndef _ZELESTE_ZEL_GPX_GENERALMANAGER_H_ #define _ZELESTE_ZEL_GPX_GENERALMANAGER_H_ #include "../internal/cuCoreLib.h" #include "boost/functional/hash.hpp" #include "boost/ptr_container/ptr_map.hpp" n...
Declare it like this: typename boost::ptr_map<Key,Value>::iterator itr = m_ItemMap.begin(); ^^^^^^^^ The point is that boost::ptr_map<Key,Value>::iterator is a dependent name, so you have to specify that it's a type name (and not a variable name or a template name).
7,634,584
7,634,628
What's an "auto-casting bool"?
On the following answer to a previous question someone mentioned an "auto-casting bool" I guess null has an auto-casting bool that is false. What is it, and what does the code that makes it look like?
The phrase "auto-casting bool" is a poor phrase someone used off hand. I believe what they mean is the internal ToBoolean operation Of special note is the if statement which calls ToBoolean on the expression. I don't know my way around the v8 source code but here is a search for ToBoolean on the v8 repo. For reference ...
7,634,594
7,634,619
How can I use toString and vector between two classes in C++?
Possible Duplicate: Is this possible in C++? toString(ClassName* class) I'm trying to use toString but I have a problem in there. I ask this question second time, because the first time I asked before had insufficient information. I just worried about the length of question. Sorry about that. toString is in the Ani...
You should include Treatment.h in Animal.cpp. EDIT: To expand on the reason, the error message translates to: "I see that you've declared a class called Treatment. But I don't see its implementation!". So to let the compiler see its implementation where you're accessing the members of the class Treatment, you need to...
7,634,740
7,634,779
protected inheritance error
#include<iostream> using namespace std; class base { protected: int a; public: base(int i) { a=i; } }; class derived :protected base { public: derived(){} void show() { cout<<a; } }; int main() { base obj(2); derived obj1; obj1.show(); return 0; } ...
Once you define a constructor for any class, the compiler does not generate the default constructor for that class. You define the parameterized constructor(base(int i)) for base and hence the compiler does not generate the no argument constructor for base. Resolution: You will need to define a constructor taking no...
7,635,348
7,635,407
what's the most efficient way to implement a returned calculated value in C++?
With the advent of rvalue references on top of Return Value Optimization, what would be the most efficient way to implement a core function like this? How can I improve this implementation or should I leave it alone? template <typename T> string to_string(const T& t) { stringstream ss; ss << t; return ss.str(...
Just leave it alone, it is efficient as it is. Even with C++03 compilers, the compiler will optimize the copies away. Basically the compiler will make sure that the object in the calling code to to_string, the return statement of to_string, and the return statement of ss.str() all take exactly the same memory location...
7,635,390
7,635,506
Yield to other threads/tasks in OpenMP
I want to use OpenMP with CUDA to achieve overlapping kernel executions. Ther kernel calls are all asynchronous, but I have very little code between launches so the individual OpenMP threads tend to block as they try to launch another kernel, or do a mem copy (I don't always have mem copys right after the call so async...
If a thread blocks, the operating system's scheduler should automatically switch to another runnable thread (if one is available), so you shouldn't need to do anything. However, if all your OpenMP program is doing is calling CUDA kernels, it's likely that the GPU is the bottleneck, so you won't get much benefit from us...
7,635,517
7,635,554
g++ undefined reference in very simple example
Please help with the following noob question about C++ and g++ compilation and linking. Essentially I have 2 classes in 2 different files, and can compile them but when I attempt to link, one class can't see the methods of the other, even though I am linking both. Order of object files does not help in this case. The...
It doesn't work that way. What you've come across is technically an ODR violation, which roughly means that A in both a.cpp and b.cpp must be the same thing. It isn't. Moreover, the constructor is implicitly inline in a.cpp and therefore its code needn't be emitted. Changing a.cpp to #include <iostream> #include "a.hpp...
7,635,534
8,299,320
How to change the default enums serialization in Boost.Serialization
By default in Boost.Serialization, enum types are serialized as a 32-bit integer. But I need to serialize some enum types as different width integer. I've tried to specialize the boost::serialization::serialize method, but it seems it doesn't work for enums. Here is my attempt: #include <iostream> #include <boost/archi...
This probably doesn't work because enums aren't a real type, I don't think you can in general overload a function for a specific enum. You could accomplish what you want by doing the conversion to char in the serialization of whatever object contains your MyEnum_t. You could also do what Dan suggested and encapsulate t...
7,635,567
7,636,461
Most appropriate way to develop a server on limited resources
I am facing a problem which seems to have few, and especially simple solutions. To get to the point; I have written a client application on Windows using C++. This client application takes input from the user, and is supposed to send this information to a server, which find users who's inputs match each other - like ma...
You can just code your server application in PHP as a webservice. In your client application, instead of connecting through sockets and a using a home-made protocol, you just have to use the HTTP REST webservice you created. It seems to me even easier than coding a whole server. Maybe you absolutely want to use socket ...
7,635,580
7,635,626
Why do I get a warning about possible loss of data when seeding the random number generator from time(NULL)?
am learning vectors and made a bit of code that selects random numbers i can use for buying lottery tickets here in Netherlands. But although it runs, the compiler is warning me about 'conversion from 'time_t' to 'unsigned int, possible loss of data'. Can anyone spot what is causing this? I haven't even defined any uns...
Because time_t happens to be larger in size than unsigned int on your particular platform, you get such a warning. Casting from a "larger" to a "smaller" type involves truncating and loss of data, but in your particular case it doesn't matter so much because you are just seeding the random number generator and overflow...
7,635,684
7,635,741
Template classes c++ friend functions
My code has the same structure as the shown below. I have two container classes defined in a single header file and each one of them has a friend function with parameters of type the other class so I get a compiling error which is something like 'Class2' - undeclared identifier. Tried a few things but didn't work it ou...
Add a forward declaration for Class2 at the beginning of the file: template<class V> class Class2;
7,635,939
7,636,274
How do I write an ADL-enabled trailing return type, or noexcept specification?
Imagine I'm writing some container template or something. And the time comes to specialize std::swap for it. As a good citizen, I'll enable ADL by doing something like this: template <typename T> void swap(my_template<T>& x, my_template<T>& y) { using std::swap; swap(x.something_that_is_a_T, y.something_that_is...
I think I would move it into a separate namespace namespace tricks { using std::swap; template <typename T, typename U> void swap(T &t, U &u) noexcept(noexcept(swap(t, u))); } template <typename T> void swap(my_template<T>& x, my_template<T>& y) noexcept(noexcept(tricks::swap(std::declval<T>(), std::dec...
7,636,015
7,636,078
How can I create getter and setter for vector in C++?
I declared vector<test*> test1; as a private, and I'd like to create getter and setter for this. I tried, void setV(vector<test*> test1) { test1 = test1; } vector<test*> getV() { return test1; } It works, but it works very strange. Is there another way to do it? Thanks
Look at the assignment statement in setV: test1 = test1; The private variable test1 is shadowed by the function parameter of the same name, and you're assigning that parameter to itself. You should define setV like this: void setV(vector<test*> const &newTest1) { test1 = newTest1; } That way you're really assigning...
7,636,169
7,636,236
Function overload resolution trouble
Over the weekend, I had specific problem with function overload resolution that I can't seem to solve. The code below is a distillation of the problem: #include <iostream> using namespace std; template<typename T> void f(const T& t) { cout << "In template function." << endl; } class C { public: void f() { cou...
Look here: http://ideone.com/zs9Ar Output: Test In template function. #include <iostream> using namespace std; template<typename T> void f(const T& t) { cout << "In template function." << endl; } class C { public: void f() { cout << "In class function." << endl; } void g() { using ::f; int i=0; f(i); ...
7,636,177
7,636,665
What is the best API to combine C++11 async/futures with Windows asynchronous IO?
Especially the upcoming Windows 8 (with Metro) will require that any IO is programmed asynchronously. In C#/.Net there seems to be special await and such like constructs for that and the JavaScript API will have its own mechanism for that to work. What will be the C++11-integration for that? Is the a concise example (e...
The Tips and tricks for developing Metro style apps using C++ presentation covers this at 59:13. The raw interface uses callback objects. In practice, people are likely to use the simplified interface offered by PPL.
7,636,226
7,636,249
C++ class operator overloading
It's possible to overload the not operator for a class: class TestA { public: bool Test; const bool operator!(){return !Test;} }; So that... TestA A; A.Test = false; if(!TestA){ //etc } ...can work. However, how does the following work? if(TestA) //Does this have to be overloaded too, or is it the n...
You could write an operator bool(). This takes care of coercion to bool, making statements as your above one possible.
7,636,230
7,636,292
C++ Interview: vtable for a class with a pure virtual function
I was asked this interview question today!! (it was a really awkward telephonic interview..): What is the difference between the vtable for a class with virtual functions and a class with pure virtual functions? Now, I know the C++ standard doesn't specify anything about vtables, or even the existence of a v-table ...
In the case of non-pure virtual functions, each entry in the vtable will refer to the final-overrider or a thunk that adapts the this pointer if needed. In the case of a pure-virtual function, the entry in the vtable usually contains a pointer to a generic function that complains and aborts the program with some sensib...
7,636,323
7,636,417
C++ vector size types
I just started learning C++ and have a question about vectors. The book I'm reading states that if I want to extract the size of a vector of type double (for example), I should do something like: vector<double>::size_type vector_size; vector_size = myVector.size(); Whereas in Java I might do int vector_size; vector_si...
C++ is a language for library writing*, and allowing the author to be as general as possible is one of its key strengths. Rather than prescribing the standard containers to use any particular data type, the more general approach is to decree that each container expose a size_type member type. This allows for greater fl...
7,636,485
7,636,507
How to make a curve vertex on OpenGL C++
I am learning how to make a 2D object with OpenGL. I made a simple rectangle with GL_QUADS with four vertex 3f example vertex1, vertex2, vertex3, vertex4. The question is, is there anyway so I can make a curve sides from that vertex(example : from v1 to v2 is the left side of the rectangle, I just want to know how to m...
Use a Bezier curve or something similar to generate additional vertices.
7,636,531
7,636,850
Is there any way/trick to pass std::set to a C API which expects C Array?
Is there is a way/trick to pass std::set to a C API which expects C Array?
No, but you could fill an array with your set contents pretty quickly. For example, assuming mySet is a set of the same type as YOUR_TYPENAME: YOUR_TYPENAME arr* = new YOUR_TYPENAME[mySet.size()]; std::copy(mySet.begin(), mySet.end(), arr); Then just pass arr into the C API.
7,636,611
7,636,786
Passing in an Object to an abstract type's constructor in C++
I'm trying to create CnD_Message_Handler of parent type i_MessageHandler. i_MessageHandler constructor takes a i_MessageFactory, another abstract class. CnD_Message_Factory inherits from i_MessageFactory. When I try to instantiate the CnD_Message_Handler, I get the following error: error C2664: 'CnD_Message_Handler::C...
CnD_Message_Handler does not redefine the constructor. Constructors are not "inherited" in C++03. You are required to provide constructor arguments for all types you inherit from. Here is an example. struct Arg {}; struct Foo { Foo(Arg arg) {} virtual ~Foo() {} }; struct Bar : public Foo { Bar(Arg arg) : Fo...
7,636,638
10,861,892
large matrix computation
I write a simple code in C++ and I compile it with g++ on linux ubuntu 11.04 and I don't get any errors but when I run the executable file, I get this error "segmentation fault". I know that my code has no problem and tHat this error is related to the compiler. Can somebody help me? My code is : #include <math.h> int ...
This function can help you: double ***alloc3d(int l, int m, int n) { double *data = new double [l*m*n]; double ***array = new double **[l]; for (int i=0; i<l; i++) { array[i] = new double *[m]; for (int j=0; j<m; j++) { array[i][j] = &(data[(i*m+j)*n]); } } retur...
7,636,717
7,636,864
Late binding for const attributes in C++ classes?
I know there is no late binding for class attributes. But i need a good pattern to do this: #include <cstdlib> #include <iostream> using namespace std; class B { public: const int i; B() : i(1) {} }; class D : public B { public: const int i; D() : i(2) {} }; int main() { D d; B *ptr = &d; ...
The version of i that gets output is dependent on the compile-time type definition. You've defined two different variables, so you'll get two different results. The way to fix this is to make sure there's only one version of the variable. You can use a contructor in B to initialize the const variable. class B { public:...
7,636,797
7,636,849
Unicode string literals
C++11 introduces a new set of string literal prefixes (and even allows user-defined suffixes). On top of this, you can directly use Unicode escape sequences to code a certain symbol without having to worry about encoding. const char16_t* s16 = u"\u00DA"; const char32_t* s32 = U"\u00DA"; But can I use the unicode escap...
It would work, but it may not have the desired semantics. \u00DA will expand into as many target characters as necessary for UTF8/16/32 encoding, depending on the size of wchar_t, but bear in mind that wide strings do not have any documented, guaranteed encoding semantics -- they're simply "the system's encoding", with...
7,637,291
7,637,419
measuring wall time in a multi-threaded environment
Is there a way to measure the wall time between two points in a multi-threaded program in milli-seconds resolution? I am familiar with boost time_t, but its resolution is seconds, not milli-seconds. Methods from MKL library are welcome.
On any modern POSIX system (like Linux), call clock_gettime with CLOCK_MONOTONIC. [update] By "wall time", I assume you mean the time that actually elapses between two points. If you mean reading the actual time of day, use CLOCK_REALTIME instead of CLOCK_MONOTONIC. (The difference is how they behave if the user shou...
7,637,382
7,637,520
Is there a more elegant way of doing these bitwise operations?
I built this program that does some bitwise operations on three numbers: 2, 4 and 20: public static void main(String[] args) { int mask = 63; int id = 2; id = (id << 6) | 4; id = (id << 6) | 20; int v3 = id & mask; int v2 = (id >> 6) & mask; int v1 = (id >> 6*2) & mask; System.out.printl...
I'm assuming that your intent is to pack three six-bit values into a single int, in which case: public int pack(int v1, int v2, int v3) { return (v3 & 0x3f) << 0 | (v2 & 0x3f) << 6 | (v1 & 0x3f) << 12; } public void unpack(int n) { int v3 = (n >> 0) & 0x3f; int v2 = (n >> 6) & 0x3...
7,637,634
7,637,772
C++ callback to non-static interface method
I have a class A that should call a non-static class method from an interface class B, with signature expressed by, say, the following function pointer: bool (B::*check)(int) const Such method would be implemented by a set of classes {C} implementing B, each with multiple methods matching the above signature. I therefo...
Massive Edit I think I got what you want, based on some heavy type-casting. Note that I do NOT recommend this technique. Although my example works, I believe there are some big pitfalls here that could really screw things up. As before, Class A can accept both a method of the proper signature and an object (of type B,...
7,637,765
7,637,850
Why FD_SET/FD_ZERO for select() inside of loop?
I am using the select function for communication between my sockets. I have a while loop and I do - while(!done) { FD_ZERO(&read_flags); FD_ZERO(&write_flags); FD_SET(comm_fd1, &read_flags); FD_SET(comm_fd2, &read_flags); FD_SET(STDIN_FILENO, &read_flags); FD_SET(comm_fd1, &write_flags); ...
When select returns, it has updated the sets to show which file descriptors have become ready for read/write/exception. All other flags have been cleared. It's important that you re-enable the file descriptors that were cleared prior to starting another select, otherwise, you will no longer be waiting on those file de...
7,637,950
7,638,626
Declaring Arrays in Private Part of Class
I've got a class, and part of the input into the class is a vector (called Data) of variable length (lets say it has length N). I've included this after the function: N = data_->size(); In the private section of the class, I want to declare an array double A[N][N];. However, when I try to do this, I get somethin...
Hmmm...several issues here... Neither N nor M are declared (either in the constructor or as members of foo) You are trying to initialize a member data that is not declared (and you may mean data_(data) as the syntax is member(expression), not expression(member)) The argument to your constructor is an incomplete type: ...
7,638,133
7,638,216
Which comes first? header guards, namespace and includes
I have been making files like this for awhile: Does the order make sense? or should the namespace and the #includes be swapped and why. #ifndef CLASSNAME_H // header guards #define CLASSNAME_H #include "a.h" // includes in alphabetical order #include "b.h" // user specified includes first #include "c.h" #include <vect...
Yes. That's looks good. Though I order my headers differently (but alphabetically is fine). The only thing I would change is the include guard. I make the include my namspace as well as the class name. As several times I have classes with the same name (but in a different namespace) being used by the same code. #ifndef...
7,638,296
7,638,340
How to write Template class copy constructor
How to write copy constructor for a template class. So that if the template parameter is another user defined class it's copy constructor is also get called. Following is my class template <typename _TyV> class Vertex { public: Vertex(_TyV in) : m_Label(in){ } ~Vertex() { } bool operator < ( const Vertex ...
Assuming _TyV is a value type: Vertex( Vertex const& src ) : m_Label( src.m_Label ) {} Aren't those names within class instances reserved by the implementation, by the way? The C++ standard reserves a set of names for use by C++ implementation and standard libraries [C++ standard 17.6.3.3 - Reserved names]. Those...
7,638,335
7,638,437
How does constructor delegation interact with non-static data member initialization?
Say I have some code like this: class Foo { public: Foo(int v) : value(v) {} Foo() : Foo(42) {} private: int value = 666; }; Does the default ctor set value to 42 or 666? I guess I would hope for 42 since that is an explicit call but I could imagine the other way too. How about with inheritance? class Base { pu...
The in class body member initializer is just a default. If the member initializer list of a constructor initializes the member too, it takes precedence always. This is specified by 12.6.2p9 in the C++11 spec.
7,638,409
7,638,446
C++ redifinition of'..' and previously declared here errors
I have already searched for this type of error and found a few threads, but each one recommended using #ifndef to make sure the header file is only loaded once. I have done this and still get an error. The odd thing is this error: circle.cc:25:6: error: prototype for ‘void circle::populate_classobj(int, int, int)’ do...
Last two parameters are exactly same as shown below. Hence the redefinition error. void circle::populate_classobj(int cx1, int cx2, int cy1, int cy1) ^^^ ^^^ I think you wanted to write: void circle::populate_classobj(int cx1, int cx2, int cy1, int cy2)
7,638,940
7,639,348
can I know which Keyboard Key has been pressed before hitting Enter
can I know which Keyboard Key has been pressed before hitting Enter.is there any way to capture such key pressed event in c++ ??Please provide a short example of it. i'm using VC++ on Windows 32bit.
// See <url: http://en.wikipedia.org/wiki/Conio.h>. #include <iostream> #include <conio.h> // ! Non-standard, but de facto std. on Windows. int main() { using namespace std; for( ;; ) { cout << "OK, should this program stop now..." << endl; cout << "Press Y for Yes or N for No: " << f...
7,639,272
7,639,979
How I do define a class method that accepts a derived class member function pointer as a parameter in C++?
I'm using a Signal-Slot C++ implementation found here: https://github.com/pbhogan/Signals to implement event listeners within a user interface library I'm developing. The user-facing API goes like so: class DialEventListener : public EventListener { void handleEvent(Event event){ … cout << "Event o...
There are two approaches for callbacks, either you provide an interface that has a virtual function that will be called, or else you perform type-erasure to make it fully generic. In the second version you either use a prepacked solution for the type-erasure or you will need to use some templates to implement it yourse...
7,639,309
7,639,414
How to use GDB to find what function a memory address corresponds to
I am using google's heap checker to track down a memory leak. It gives me a stack trace such as: Leak of 21 bytes in 1 objects allocated from: @ 0xf6088241 ...
Use info symbol gdb command. 16 Examining the Symbol Table. info symbol addr Print the name of a symbol which is stored at the address addr. If no symbol is stored exactly at addr, gdb prints the nearest symbol and an offset from it: (gdb) info symbol 0x54320 _initialize_vx + 396 in section .text This is the opposite...
7,639,378
7,639,429
Getting C++ Segmentation Fault error in recursive n-queen program
Basically, I have to write a basic program that solves the n-queen problem, which I have done, but it throws a segmentation fault if I input any number >=11. From what I have read online, this error is usually caused by faulty logic when dealing with memory, but I can't seem to figure out what I have done wrong. void ...
Start debugging at the beginning and then let it run till the segmentation fault. When the fault occurs - look at the stack. I would guess that you're exceeding your stack with the recursion - that's the main problem with recursion programs. You can enlarge your stack and then the fault will occur not with input 11 but...
7,639,457
7,639,488
Calling derived class function from base class Without using virtual functions
Hi suppose I have a code like this // base class class A { public: int CallMyFct(PtrToFCT what){ return what(10); } }; class B : publ...
You have to define the functions to be called as static, and provide additional parameter to pass to them to the object instance (instead of this that they would be getting if called as regular member functions).
7,639,598
7,639,709
Segmentation fault when trying to receive pointer value in Qt
I'm quite new to Qt and c++ but not new to programming at all. I am having trouble using pointers in my program. In my header file I have got the following private variable pointer assignment: private: QString *currentFile; In my program I have got a function that starts by copying the value of the currentFile poi...
This is most probably due to the fact, that you never allocated any storage for the string. The pointer just stores a memory address and if its value is initialized to 0 (or even worse to nothing and contains a completely undefined address), then it doesn't point to a valid string object and trying to use the memory it...
7,639,656
7,639,754
Getting a buffer into a stringstream in hex representation:
If I had a buffer like: uint8_t buffer[32]; and it was filled up completely with values, how could I get it into a stringstream, in hexadecimal representation, with 0-padding on small values? I tried: std::stringstream ss; for (int i = 0; i < 32; ++i) { ss << std::hex << buffer[i]; } but when I take the string ou...
#include <sstream> #include <iomanip> std::stringstream ss; ss << std::hex << std::setfill('0'); for (int i = 0; i < 32; ++i) { ss << std::setw(2) << static_cast<unsigned>(buffer[i]); }
7,639,816
7,648,868
Is it possible to grab a pointer to the default audio endpoint device buffer in Windows 7?
Working with the Win32 API here. I've been scouring through the MSDN documentation for the core audio services in Windows Vista+, and haven't had much luck finding a way to secure the default audio buffer. My goal is to set up a real-time spectrograph data of the audio being played. Is there any way to access the audio...
Good News lads! I figured out a solution. The WASAPI Loopback Recording mode, outlined here: http://msdn.microsoft.com/en-us/library/windows/desktop/dd316551(v=vs.85).aspx, lists in detail a way to "copy the output stream from the audio engine into an application's capture buffer". Its as close to a pointer of the aud...
7,639,843
7,640,923
Interacting with a Service from Internet Explorer
I am attempting to have IE9 interact with a COM service (created using Visual Studio 2010's wizard) while running in protected mode. If I run the service as admin rather than registering it as a service, my BHO's call to spUnk.CoCreateInstance returns S_OK (I am watching AtlTrace's output). The BHO is also able to su...
Another hour of mucking with this and I discovered that calling this code (archive.org) (SetLaunchActPermissions and GetLaunchActPermissionsWithIL) makes it work. From that page: By default, COM will prevent Low IL clients from binding to running instances of any COM servers. To allow the bind, a COM server's Lau...
7,640,059
7,640,091
Can this thread become a zombie
I have a program which starts a thread (using pthreads) that will do some background task for the remainder of the program. The main program is run in a terminal and a common use-case is to close it before it exits by itself using Ctrl-C. Someone asked me to be vary of the threads I spawn to become zombies. I had not t...
Threads don't become zombies; processes do. When you kill a process, this automatically kills all of its threads. In a nutshell, you don't need to do anything special just because you have a second thread running.
7,640,079
7,640,724
How to add your own base unit and conversions using boost::units
I am currently using boost::units to represent torque in si units, however I am given the torque in pound feet. I am attempting thus to create a pound_foot unit of torque and a conversion to support this. My lazy attempt was to simply define: BOOST_STATIC_CONST(boost::si::torque, pound_feet = 1.3558179483314 * si::new...
Pound foot isn't really a base unit, so better go with the clean way and define it in terms of the base units, which are feet and pounds: #include <boost/units/base_units/us/pound_force.hpp> #include <boost/units/base_units/us/foot.hpp> #include <boost/units/systems/si/torque.hpp> #include <boost/units/quantity.hpp> #i...
7,640,089
7,640,237
SIGSEGV with a recursive algorithm
I implemented a recursive algorithm which runs for about 1730 recursions and then crashes with a mysterious SIGSEGV. I tried my gdb and got the following output: Program received signal SIGSEGV, Segmentation fault. 0x000000000040b7da in Town::get_cur_capacity (this=0x61efe0) at ./solver/Darstellung.cpp:54 54 retur...
If you're 1700 levels deep in recursion it's not unbelievable that you overran your stack and corrupted a call parameter which could easily lead to this sort of crash. If you use g++ try adding -fstack-protector-all to see if it helps you get better diagnostics. EDIT: Another indicator is if your backtrace inside gdb b...
7,640,501
7,640,541
How is this conditional parsed?
For some context, the conditional is used in the normal type of algorithm for finding linked list cycles: From link: http://vijayinterviewquestions.blogspot.com/2007/05/how-would-you-detect-loop-in-linked.html p=head; q=head->next; while(p!=NULL && q!=NULL) { if(p==q) { //Loop detected! exit(0); } p=p->next; ...
that can be expanded to: if (q->next) { q = q->next->next; } else { q = q->next; }