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 |
|---|---|---|---|---|
6,697,592 | 6,697,675 | No matching function for call to … with dtl-cpp | I am using dtl-cpp to compare the difference of two files line by line.
I have set up this comparator:
class LBCompareNSString : public dtl::Compare<NSString *> {
public:
virtual bool impl(const NSString *& A, const NSString *& B) const {
return [A isEqualToString:B];
}
};
I have two vectors of NSString object... | Aha! I found what I've done wrong.
virtual bool impl(const NSString *& A, const NSString *& B) const
should be
virtual bool impl(NSString *& A, NSString *& B) const
just like the compiler says.
|
6,697,702 | 6,697,861 | Why I cannot access ancestor methods from predecessor templated member functions in gcc? | I have a problem with class member function templates. It seems that gcc is trying to analyze the code semantically too early, without explicit template instantiation.
Let the code speak
A.h (the base class):
#ifndef __A_H__
#define __A_H__
class A {
public:
A* ptr;
template<class T>
void method() {
... | The code incorrectly compiles in Visual Studio due to the way templates are processed (basically they are ignored until they get instantiated). In your code, the identifier B is not dependent on the template arguments (T) and as such, it must be available in the context where the template is defined.
As B inherits from... |
6,697,704 | 6,697,900 | boost interprocess file_lock does not work with multiple processes | I seem to be having an issue with boost::interprocess::file_lock
I have process 1 that is essentially
boost::interprocess::file_lock test_lock("testfile.csv");
test_lock.lock();
sleep(1000);
test_lock.unlock();
When I run a second process while the first process is sleeping, I find that I am still able... | file_lock is not for locking a file. It is a mutual exclusion object that uses a file as its backing technology. The contents of the file are basically irrelevant; what is relevant is that all instances of a file_lock pointing to that file will respect the locking characteristics of the lock.
As with any mutex-type... |
6,697,823 | 6,710,490 | C++ priority queue as binary heap | have been making progress, but still can't figure out where my infinite loop is...
header file:
#include <string>
class priority_queue_overflow{}; //if insert tries to exceed the size of A then throw priority_queue_overflow()
class priority_queue_underflow{}; //if extract_min tries is called on an empty heap the... | ok, finally got it... thanks errbody :-)
/**
* implementing the priority queue as a binary heap
*
*/
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>
#include <map>
#include <algorithm>
#include "binary_heap.hpp"
/***********************
*** inline functions
***********************/
inl... |
6,697,910 | 6,830,330 | Blocking Queue implementation: Where's the race condition? | It's me and my BlockingQueue again... I rewrote it according to this article and this question. It sends some items and then crashes with an access violation. Here's the code:
template <typename T>
bool DRA::CommonCpp::CTBlockingQueue<T>::Push( T pNewValue ){
volatile long oldSize;
::InterlockedExchange( &oldS... | In the end, I went back to my original, less efficient implementation, the one I posted here, with the addition of a Finish() method so that the producer can signal the consumers to end elegantly, and a Restart() method to start producing again without destroying and recreating the queue:
//Template definitions
templat... |
6,698,039 | 6,698,115 | Nested Comments in C/C++ | This is an interview question:-
Write a C program which when compiled and run, prints out a message
indicating whether the compiler that it is compiled with, allows /* */
comments to nest.
The solution to this problem is given below :-
Sol:- you can have an integer variable nest:
int nest = /*/*/0*/**/1;
if ... | If the compiler doesn't allow nesting, the first */ will terminate the opening of the multiline comment, meaning the 0 won't be commented out. Written with some spaces:
int nest = /*/*/ 0 * /**/ 1;
resulting in the code
int nest = 0 * 1; // -> 0
If it allows nesting, it will be
int nest = /*/*/0*/**/ 1;
resulting in... |
6,698,332 | 6,699,641 | Do I need Read-Write lock here | I have writing a multi threaded code. I am not sure, whether I would need a read and write lock mechanism. Could you please go through the usecase and tell me do I have to use read-write lock or just normal mutex will do.
Use case:
1) Class having two variables. These are accessed by every thread before doing operation... | First off, ignore those other answerers talking about volatile. Volatile is almost useless for multithreaded programming, and any false sense of safety given by it is just that - false.
Now, whether you need a lock depends on what you're doing with these variables. You will need a memory barrier at least (locks imply o... |
6,698,485 | 6,698,718 | The iterator is supposed to read an entire number, but it only reads the first digit | I've written this code to extract numbers from a string using a string iterator.
The iterator picks up the first number and decides to call it a day.
Why's it so?
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string myAge = "I am 23 years old";
string::iterator itera... | Just collect the characters into the stringstream and print it afterwards:
for(iterator = myAge.begin();iterator!=myAge.end();iterator++)
{
numberInCharacterForm = *iterator;
if(numberInCharacterForm >= '0' && numberInCharacterForm <='9') {
// note: && instead of & here ^
convertToString << number... |
6,698,657 | 6,698,995 | Why can I only add elements to a QWidget during runtime if the QWidget isn't visible on the screen? | I have a strange problem when trying to add buttons to a QWidget during run-time. I have a window with a QTabWidget, and it has 2 tabs. When I press a button on the window it generates an array of check boxes on the first tab.
The problem is, when I have the first tab open, nothing happens when I press the button, but... | You probably need to show() the newly created widget and let the layout update:
checkBoxVector.last()->show();
ui->dim1->updateGeometry();
|
6,698,735 | 6,699,139 | WIN32: Need Help With stdout Redirect on Hybrid Console + GUI App | I have a C++ Win32 application that runs as a console app if run with command line arguments, but as a windowed app if there are no command line arguments. I do it using this method to create a console using AllocConsole() and STD_OUTPUT_HANDLE:
http://www.halcyon.com/~ast/dload/guicon.htm
My entry point is wWinMain (... | Try to call AttachConsole first with ATTACH_PARENT_PROCESS (value -1) as its argument. That will redirect your app to the console it has been run from, and therefore allow the > output.txt to obtain whatever it outputs. Otherwise, the output isn't caught because two different consoles are used - the one your app has be... |
6,698,740 | 6,699,258 | Java or C++ equivalents to Preon? | Preon is a Java library meant for creating binary codecs: you simply place annotations in a class' data members regarding their correspondence with bit fields (e.g. number of bits to use for certain field) and, based on such class, the library builds a Codec object that is able to create instances of the class reading ... | looking at the license page, the preon library is "GNU General Public License, version 2, with the Classpath Exception", which is important. that allows you to use the library in binary form without your application also being GPL.
|
6,699,066 | 6,699,113 | In which order should floats be added to get the most precise result? | This was a question I was asked at my recent interview and I want to know (I don't actually remember the theory of the numerical analysis, so please help me :)
If we have some function, which accumulates floating-point numbers:
std::accumulate(v.begin(), v.end(), 0.0);
v is a std::vector<float>, for example.
Would it... | Your instinct is basically right, sorting in ascending order (of magnitude) usually improves things somewhat. Consider the case where we're adding single-precision (32 bit) floats, and there are 1 billion values equal to 1 / (1 billion), and one value equal to 1. If the 1 comes first, then the sum will come to 1, since... |
6,699,374 | 6,699,917 | Access to each separate channel in OpenCV | I have an image with 3 channels (img) and another one with a single channel (ch1).
Mat img(5,5,CV_64FC3);
Mat ch1 (5,5,CV_64FC1);
Is there any efficient way (not using for loop) to copy the first channel of img to ch1?
| There is a function called cvMixChannels. You'll need to see implementation in the source code, but I bet it is well optimized.
|
6,699,417 | 6,699,587 | Quick question about using the QTabWidget 'addTab' function | Hopefully a very quick question. In one of my functions I want to generate an 'x' number of tabs for a QTabWidget during run-time ('x' provided by user). I know I have to use the addTab function for the QTabWidget (correct me if I'm wrong), but I am unsure as to how I am supposed to use it. The qt documentation was unc... | If you take a look at the documentation, the addTab function says this :
int QTabWidget::addTab ( QWidget * page, const QString & label )
Adds a tab with the given page and label to the tab widget, and
returns the index of the tab in the tab bar.
So the argument you pass should not be the TabWidget you want to add th... |
6,699,488 | 6,699,775 | BSD Sockets - How to use non-blocking sockets? | I am trying to use non-blocking TCP sockets. The problem is that they are still blocking. The code is below -
server code -
struct sockaddr name;
char buf[80];
void set_nonblock(int socket) {
int flags;
flags = fcntl(socket,F_GETFL,0);
assert(flags != -1);
fcntl(socket, F_SETFL, flags | O_NONBLOCK);
... |
Whenever I run it, the server still waits for me to send something before it will read and output what the client has sent.
Well, that is how you wrote it. You block on IO from stdin, and then and only then do you send/receive.
cin>>out;
cin.get();
Also, you are using a local socket (AF_UNIX) which creates a special... |
6,699,531 | 6,704,814 | Detect clip arts or vectorial images using OpenCV in C++ | I have a process that detects similar images using SURF and I want to add a check to know which images are real camera photos and which ones are vectorial images like logos of map-screenshots.
Examples:
Photo: http://images.gta-travel.com/HH/Images/J/TYO/TYO-NEW3-8.jpg
Logo: http://estaticos.transhotel.com/img/fotos/ho... | Ok, solved it, the next code is cleaning the histogram, getting all colors in grey scale and counting the different colors. Maybe in the future I will test if working with the components histograms improves the algorithm.
CvHistogram* wImage::getHistogram() {
IplImage* gray = cvCreateImage(cvGetSize(this->image), 8... |
6,699,574 | 6,699,653 | same offset in a shared-type uniform buffer object in OpenGL for 4 different floats | I'm currently programming a phong spot-light shader that uses the new ogl3 feature, ubos. My buffer object in the shader is :
`
Uniform Light {
vec3 origin;
vec3 color;
vec3 direction;
float intensity;
float linear_dissipation;
float illu_angle;
float max_illu_angle;
} Light[8];
`
When I cal... | Given that origin, color, and direction are all aligned on 16 bytes, I assume that OpenGL is combining the last four floats into a single vec4.
Did you actually try using one of them to verify that they are or are not aliased?
|
6,699,734 | 6,831,523 | Qt Creator compilation error "::swprintf and ::vswprintf has not been declared" | So far I've written all my code in visual studio and now I need to add some UI to it so I'm going to use Qt. So I added every file In my project (except main class) and then tried compiling it using Qt. since I've used some c++0x features I had to add this line to project file :
QMAKE_CXXFLAGS += -std=c++0x
then I tri... | as Troubadour suggested, it's a problem with mingw, that when you add -std=c++0x flag to compile options, mingw automatically adds -ansi flag too, so to fix that I added -U__STRICT_ANSI__ flag to compile options. problem fixed.
|
6,699,817 | 6,700,669 | Grapheme generation - time vs. memory complexity | I am writing a program to generate 'multigraph' data from text files, which are basically mappings between graphemes and their frequency of occurrence in the text file, for example:
aaaa : 0
aaab : 0
aaac : 0
...
thel : 10
them : 250
...
zzzz : 0
The basic idea is that you can then 'score' a string based on the multig... | Tries offer good time-space tradeoffs. A plain trie, where each node (e.g. for the prefix "iq") has an array of children pointers indexed by the next character in the string (e.g. 'x'), will still have wasted space in the form of nulls in the child pointer array, but you will save space as there is no branch rooted in ... |
6,699,828 | 6,700,097 | C++ server applications | Could someone point to preferred references/books for C++ or language-agnostic server application development?
I do have some experience in this sphere, but I would like to know more and, obviously, knowledge may come from reading the corresponding books :)
| These are the main related topics:
Networking
Disk I/O
Concurrency
Scaling
High availability and fault tolerance
For networking: Stevens' Unix network programming bible is a very good starting point (if you mix it with his TCP Illustrated book you will also get a deep understanding of the topic), but after that you h... |
6,699,854 | 6,699,884 | Why is gcc's option "-Wstrict-prototypes" not valid for C++? | Here is a warning I, and lots of people out there on the web, see when running gcc on C++ code:
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++
The warning text is very clear: 'C++' is not in the set [Ada/C/ObjC ], so I have no question at all about why gcc gives thi... | I suppose it's becuase C++ requires strict prototypes as part of the language, so the option is superfluous. Why that makes it so GCC needs to complain about it is beyond me.
I have that option set in my build script for small sample/test C or C++ programs, and the warning kind of irritates me - it seems like there's ... |
6,699,946 | 6,703,063 | Unresolved overloaded function type when using a template friend function | I have a problem where I'm trying to stuff a friend function of a class template into a boost::function:
#include <boost/function.hpp>
template <int N>
struct Vec{
friend
double dot(Vec, Vec){}
};
template class Vec<2>; //Force multiple instantiations
template class Vec<3>;
int main()
{
boost::function<dou... | In my understanding, if a friend function is defined in a class without other
corresponding declarations, the friend name can be looked-up only through ADL.
§7.3.1.2/3 says:
The name of the friend is not found by simple name lookup until a
matching declaration is provided in that namespace scope
The code will be ab... |
6,700,270 | 6,700,709 | Get a vector from a sql 2008 table | I have a table called test with 6 columns and 6 rows in SQL server 2008:
1att 2att 3att 4att 5att 6att
----------------------------------
467 116 480 477 491 697
NULL 219 481 113 488 466
NULL NULL 477 466 455 480
NULL NULL NULL 527 483 629
NULL NULL NULL NULL 483 48... | From the question: in fact the NULLS are the real problem...
A relatively simple problem indeed. By keeping track of the row and column, and since the vector is filled-in in row order, the values of the cell below the diagonal can be obtained from their transpose location, i.e. in value of data readily in the vector.
M... |
6,700,295 | 6,700,491 | link-time optimization versus. project inlining; limitations on each approach | usually people when designing proper software architectures on c++ that also need to have great performance, enter into the dangerous game of premature optimization, but rather that doing optimization at the architecture level (which is a perfectly good and encouraged form of premature optimization) they do compromises... | The technical name, approaching minor buzzword status, for that approach is unity build.
See for example:
The benefits / disadvantages of unity builds?
The downside is best described here:
http://leewinder.co.uk/blog/?p=394
The short version is it is more or less a choice of languages: you either write in regular-C++ o... |
6,700,480 | 6,700,534 | How to create a std::string directly from a char* array without copying? | Say I have an array of chars, which I have allocated on the heap, and which I want to convert into an std::string. Currently I am doing the following:
char *array = new char[size];
WriteIntoArray(array, size);
std::string mystring(array);
delete[] array;
return mystring; // or whatever
From what I read on the internet... | If you're using a conforming C++0x implementation, or one of the many C++ libraries that guarantee contiguous storage for std::string, then you can get a char* that points directly to the storage used by your std::string.
For example:
std::string mystring;
mystring.resize(size);
WriteIntoArray(&mystring[0], size);
retu... |
6,700,576 | 6,700,757 | C++ Why does my Linked List template class fail when I create an object of a class that has a linked list in it? | I wrote this LinkedList template class, which isn't finished yet- I have yet to add safety features and more methods. As of now it does what I need it to. But it fails in a certain situation and I don't know why.
template<class data_type> class LinkedList {
private:
struct Node {
data_type data;
Node* prev;... | You need to implement an assignment operator. The problem starts in this function here:
void AddToList(const data_type data) {
Node* last = GetLastNode();
Node* newnode = last->next = new Node;
newnode->prev = last;
newnode->data = data; <---------------------------- Right there
}
Since data_type is y... |
6,700,638 | 6,713,008 | Allegro5 - openGL: Major opcode of failed request: 55 (X_CreateGC) | I have been trying to get Allegro5 up and running on my Ubuntu machine. I compiled this code:
#include <stdio.h>
#include <allegro5/allegro.h>
int main(int argc, char **argv)
{
ALLEGRO_DISPLAY *display = NULL;
if (!al_init()) {
fprintf(stderr, "failed to initialize allegro!\n");
return -1;
}
display =... | Configured xorg.conf to use dri and glx.
|
6,700,666 | 6,700,782 | Strange seg fault with function pointer returning a value | While learning C#, I found it fun to reimplement things like List or LinkedList just to understand how it works and potential problems you may have while implementing it.
While learning C++, since I have some experience in C#, I decided to challenge myself and attempt to implement more advanced code than what the end o... | The problem with the statement
ListData[ (this->*NextNumber) () ] = SalesRef; //POINT OF INTEREST TWO
is that there's no sequence point between fetching the value of the field ListData and calling the member function pointed at by NextNumber. So the compiler is perfectly happy doing that load before the function call... |
6,700,670 | 6,700,747 | BSD Sockets Invalid Argument at connection | I keep getting an invalid argument error when I try to connect the client to the server. A couple threads online said this can happen when addrlen is not right, but I tried changing it to a literal value after counting the length and that did not work. I also tried just strlen() with no luck. Anyways, relevant code -
... | Well your big problem is completely misunderstanding the sockaddr struct!
Firstly use sockaddr_in.
You would then write code more like the following:
sockaddr_in sai;
sai.sin_family = AF_INET;
sai.sin_port = htons( 12345 ); /// Or whatever port you wish to use.
inet_aton("127.0.0.1", &sai.sin_addr.s_addr);
Note: ht... |
6,700,797 | 6,700,885 | Go to main() from user defined function | I have 3 functions: my_fun1(), my_fun2(), and my_fun3().
main() calls my_fun1() which calls my_fun2(), which in turn calls my_fun3().
Upon some pre-defined condition in my_fun3(), I would like my program to go directly back to the main() function at the line my_fun1() was called.
Is it possible to go directly from my_f... | Well, there is a way to jump directly to another point in the code using longjmp/setjmp, but I'm not going to tell you how because it is a terrible idea. Just about as bad as it gets. So let's talk about good solutions :-).
The most obvious way is to use exceptions. Like this:
int my_fun3() {
throw 1; // could be a... |
6,700,960 | 6,701,083 | Producer/Consumer design - Share queue variable across threads in Qt | I have tried to create a concurrent queue class, in a producer-consumer pattern.
I based the class off http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
In my main thread, I called the following two methods using Qt::Concurrent
QFutureWatcher<void> *loadwat... | In a scenario like this the producer needs to tell the consumer that no more data will be coming. Typically this is achieved by having something like a Close() method on the queue. Your consumer test would then become:
while (!tiles->empty() || !tiles->closed())
{
... blocking consume
}
|
6,701,381 | 6,701,460 | How stl containers destroy objects | How does stl call the destructors of objects, as in std::vector::erase or std::vector::pop_back?
| Perhaps some additions to Steve's nice answer:
Indeed, internal allocation is done by allocators, which serve two separate purposes: Allocating and releasing memory, and constructing and destroying objects. Objects are always (copy or move) constructed on insert and destroyed on erase, however, the interna vary.
Node-b... |
6,701,435 | 6,709,726 | Scalable server framework in C++ | I am looking to write a server application in C++ that is meant to handle tens of thousands of clients simultaneously. It should run under Windows and Linux. I have been looking around for frameworks and libraries and have come across Boost Asio, which seems like a highly mature and widely used alternative. I just have... | Best 4 choices i know
I really like zeromq.. but libuv seems interesting.. (libev and libevent are very nice too)
zeromq
libevent (as said)
libev
libuv (Its purpose is to abstract
IOCP on windows and libev on Unix systems and it is node.js network layer)
|
6,701,468 | 6,701,513 | Converting bstr_t to double | How to do the transform bstr_t to double in c++?
I was thinking to convert to *char, then *char to double?
| If you have a char* or wchar_t* string, use the strtod/wcstod functions to read a double.
E.g. using @Steve's suggestion:
_bstr_t x;
double q = wcstod(x, NULL); // implicit conversion!
double p = strtod(x, NULL); // same
Apparently _bstr_t has implicit conversion operators both to const char * and const wchar_t*, so y... |
6,701,536 | 6,701,689 | Having typedef std::map<boost::shared_ptr<my_class>,my_description> how to return & shared_ptr from my function? | So I have such function:
boost::shared_ptr<my_class> get_class_by_name(std::string name)
{
typedef std::map<boost::shared_ptr<my_class>, my_description> map_t;
BOOST_FOREACH(map_t::value_type it, some_object.class_map)
{
my_description descr = it.second;
if(descr.name == name)
{
... | OK, I don't know what you're really trying to do, but here's a skeleton idea:
typedef std::shared_ptr<my_class> my_class_ptr;
typedef std::map<my_class_ptr, my_description> my_map_t;
struct FindByName
{
FindByName(cosnt std::string & s) : name(s) { };
inline bool operator()(const my_description & d) { return name ... |
6,701,544 | 6,701,567 | C++ Can't call tskill inside with system call | I can't call taskkill or tskill inside VC++ with system i don't know any alternatives, i have tried writing a .bat file and trying calling tskill, that dind't work either.
system("tskill example");
system("dins.bat");
they don't work.
thanks
| Use TerminateProcess instead. I also recommend reading this.
|
6,701,785 | 6,702,072 | Overloading operator&& and || to create a class that saves dynamic logic | I have a class that is created from an enum that can be tested at any point in the future returning a bool whether it passes, for example:
ConditionObject cnd(CondIsTuesday);
door.setOpenCondition(cnd);
Then the door has a condition that it can use to determine its state.
However I wish to now overload the && and || o... | "Expression Templates" might be of use to you. This seems to be a reasonably thorough take on the subject, but there are others. I'm not overly familiar with the subject, but that should be a good googling point.
The basic idea is that you want a tree, with the leafs being an actual condition, and the branches betwee... |
6,701,917 | 6,704,139 | How to iterate through such a map? How to fix 8 scary C2784 errors? | So I try to compile such code:
bool server_utils::find_service_by_name_iterator_function(std::pair<boost::shared_ptr<service>, server_utils::service_description> const & element, std::string name) const
{
return element.second.name == name;
}
server_utils::service_description server_utils::stop_service_by_name... | Use boost::bind; it's far smarter:
map_t::iterator map_it = std::find_if(
description.service_map.begin(), description.service_map.end(),
boost::bind(&server_utils::find_service_by_name_iterator_function, this, name));
|
6,701,981 | 6,702,049 | Transform an upper triangular matrix into a full matrix C++ | How would look the code that can transform an upper triangular matrix into a full matrix.
The matrix is in a vector, not in a bidimensional array...
so the array
[ 1 2 3 4
0 5 6 7
0 0 8 9
0 0 0 10 ]
would become an array like:
[ 1 2 3 4
2 5 6 7
3 6 8 9
4 7 9 10 ]
could you provide some ideas, I was think... | First, you must understand the fundemtnal nature of a reflected matrix. For any i, j, the following assertion is true:
m[i][j] ≡ m[j][i]
So, you need some algorithm to make that true. May I suggest:
for(int i = 0; i < HEIGHT; ++i)
for(int j = 0; j < i; ++j)
m[i][j] = m[j][i];
Note the condition of the 2nd loop.... |
6,702,039 | 6,702,051 | Getting strings within a getline string | Is there a way to traverse a getline string with a normal string.
string nextLine;
getline(fin, nextLine);
nextLine = "2 BIRTH OCT 30 1998";
string stringTraverse = ?;
stringTraverse needs to be "2", then "BIRTH", until all the words are read.
| you can use sscanf on nextLine.c_str() to get each piece. Alternatively put nextLine into a string stream and then read until the stream is done so
stringstream s(nextLine);
while (s >> some_string)
//do stuff with string piece
|
6,702,100 | 6,702,193 | Polygon Partitioning vs Triangulation | I recently asked this question about how to cut down a concave polygon to convex ones, and I was suggested to do Triangulation or Polygon Partitioning.
The library I'm using (SFML\Box2D) only takes convex shapes.
This is what I want to know:
Is Polygon Partitioning, or Triangulation of Polygons faster?
How does Polyg... | Not a full answer to your question, but if you have a general polygon (concave, convex, whatever) and you are looking to triangulate it (for subsequent openGL style rendering perhaps) you could look into "constrained Delaunay triangulation" packages. One such example is the Triangle package, which is reputed to be fast... |
6,702,236 | 6,703,310 | Closing a thread handle before exiting the associated thread | This is what I am trying to do in my code:
I create an event, create a thread. If something fails in the main thread, I set the event to indicate the associated thread about the failure and instruct it to gracefully exit the associated thread.
My question is, is it safe to close the thread handle, right after the event... | Yes, it's safe. From the CreateThread documentation:
The thread object remains in the system until the thread has terminated and all handles to it have been closed through a call to CloseHandle.
Of course, if you close the thread's handle, then you can no longer wait on it via a call to WaitForSingleObject/WaitForMu... |
6,702,306 | 6,702,319 | What is the life time of a C++ data structure object? | Suppose I have have a Car.h which define a class called Car , and I have implementation Car.cpp which implement my class Car, for example my Car.cpp can be :
struct Helper { ... };
Helper helpers[] = { /* init code */ };
Car::Car() {}
char *Car::GetName() { .....}
What is the life time of the helpers array ?
Do I nee... | Any variable declared/defined in global / namespace scope has a complete life time until the code ends.
If you want your Helper helpers[]; to be accessible only within Car.cpp then only you should declare it as static; otherwise let it be a global. In other words,
Helper helpers[]; // accessible everywhere if `e... |
6,702,426 | 6,702,482 | C++ Heap allocation and reuse of memory | I've got this small snippet:
Action* newAction(Agent& a, ACTION_MODE& m)
{
Action *new_action;
do
{
new_action = new Action(a,m);
}
while (!state->addAction(new_action));
return new_action;
}
state->addAction(Action *a); will return true if *a was added, false if *a not added (checks to see if *a alrea... | You have a potential memory leak in that code in that you are creating a new action every time through the loop but, if it fails to add, you don't free it. Better would be to move the action creation outside of the loop with something like:
Action *newAction (Agent& a, ACTION_MODE& m) {
Action *new_action = new Act... |
6,702,936 | 6,703,195 | plugin for google chrome | I am using windows xp and i want to develop my own plugin for google chrome using cpp like other plugins(flash or silverlite) because i have my own exe file so when particular page is open it find for plugins and if plugin is not installed on the system then it first ask to install that plugin form the server and if pl... | The NPAPI is not an easy API to use directly, IMO. However, there are frameworks that make the creation of plug-ins much easier. See:
FireBreath - "a framework that allows easy creation of powerful browser plugins"
nixysa - "A glue code generation framework for NPAPI plugins"
|
6,703,121 | 6,703,138 | how Inline function code is replaced in calling place? | I want to know how inline function call is replaced by the inline code.
i read in some book saying compiler may treat the inline function as normal function.
can any own explain how inline function works.
| From the C++ FAQ:
When the compiler inline-expands a function call, the function's code
gets inserted into the caller's code stream (conceptually similar to
what happens with a #define macro). This can, depending on a zillion
other things, improve performance, because the optimizer can
procedurally integrate t... |
6,703,128 | 6,703,269 | Benchmarking considerations and deterministic data collection | I am writing a c++ benchmarking program, which involves timing a number of function calls. The functions are called repeatedly and each time is recorded for statistical analysis later. It is required that the functions be run simultaneously on multiple threads and thus to ensure accuracy and fairness of the benchmark, ... | Calling high-frequency timers and writing samples into an output stream is a perfectly sensible way to get performance data. But there are a few tricky gotchas to be careful of.
Indeed you shouldn't use printf and stringstream -- not only because their execution time is variable and poorly defined, but also because th... |
6,703,199 | 6,715,119 | Inheriting template methods | I have a class similar to the following:
class SomeClass
{
public:
template<typename... Args>
void doSomething(Args && ... args);
//... other methods etc.
};
However, what I really want is to have two different kinds of SomeClass. Ideally, I would be able to derive from a common interface... | I think @stijn's answer is correct; you have an ideal case for CRTP. You may choose to alter your logic according to that.
template<class T>
class SomeClass
{
public:
template<typename... Args>
void doSomething(Args && ... args)
{
static_cast<T*>(this)->doSomething(...);
}
//other method can be virtual
... |
6,703,288 | 6,703,484 | Initializing const members of structs in C/C++... compiler dependent? | Recently I ran into a compiler error in a legacy environment using Borland C++ 5.2. I had a .cpp file which included a header from some C source which I don't control. The header contained a struct definition which included const members, and the compiler complained about a "constant member in class without constructo... | The standard is pretty clear. Having a const member doesn't bar a class from being an aggregate.
8.5.1 [dcl.init.aggr]
An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual funct... |
6,703,580 | 6,703,606 | testing c++ iterator | I'm writing a c++ RandomAccessIterator for a custom array type.
Since it doesn't work with std::sort and a simple int array, I'd like to make sure that I have implemented it correctly.
Do you know of any "iterator conformance testing" framework out there?
I have implemented every possible function or operator, and ev... | The Boost.Iterator-library contains classes for concept checking.
|
6,703,788 | 6,703,907 | byte representation of numbers | I use the next way to get the byte representation of numbers in C++:
template< class T >
union u_value
{
T value;
unsigned char bytes[ sizeof( T ) ];
}
Please, tell me is that the true way? And if not why and how should I get it?
| Not true way. This way is not portable and often may result in undefined behavior. Because,
Padding (done by compiler) is ignored
virtual function extra space is not taken care visibly (if T is polymorphic)
|
6,703,840 | 6,703,879 | IDE for MinGW with SVN support | I would like to compile with MinGW on Windows. I am seeking for IDE (Visual Studio 2010 is out, because as far as I know it cannot use MinGW) with integrated SVN support like AnkhSVN plugin for Visual Studio 2010. One candidate is CodeBlocks. Does it have some SVN plugin? Or would you recommend another IDE? Thank you.
| You can use Eclipse IDE for C/C++ Developers.
With the subclipse plugin you have accesses to svn as well
Link: http://eclipse.org/downloads/moreinfo/c.php
|
6,703,880 | 6,703,953 | How to find the middle node of a single linked list in a single traversal (if the length of the list is not given) | I have a problem statement like: "How to find the middle node of a singly linked list in only one traversal, and the twist is we don't know the number of nodes in the linked list?"
I have an answer like "take a vector and start pushing all the nodes' addresses as and when you are traversing the linked list and incremen... | Following are the steps:
Take two pointers *p1 and *p2 pointing to the head of linked
list
Start a loop and increment *p2, 2 times (with null checks)
If *p2 is not null then increment *p1 1 time
When *p2 reaches null; you have got the *p1 at the center
[Note: You can use iterators instead of pointer if you deal with ... |
6,704,237 | 6,704,311 | C++ circular dependency: What should the constructor look like? | I read through a lot of circular dependency topics but all of them seem to be concerned with the declaration. I am interested how to construct the mutually depended objects and if there are potential pitfalls with my approach. Consider this simple example:
#include <iostream>
#include <vector>
using namespace std;
cla... | When you use a type in a standard container, like vector the type needs to be CopyConstructible and Assignable. If your type has pointer members then these will work fine with an implicitly defined copy assignment operator but this is not the case with reference members as references can't be rebound.
If you want your ... |
6,704,332 | 6,704,400 | C++ Resolving the diamond problem | Couldn't the diamond problem be resolved just by using the first inherited declaration found? I mean,
public class A {
public virtual int getInt();
};
public class B : public A {
public int getInt() {return 6;}
};
public class C : public A {
public int getInt() {return 7;}
};
public class D: public B, p... | It's a very buggy solution. Think what will happen in the following case:
public class A {
public int getInt() {return 5;}
public float getFloat() {return 5.0;}
};
public class B {
public int getInt() {return 6;}
public float getFloat() {return 6.0;}
};
public class C {
public int getInt() {return... |
6,704,436 | 6,704,525 | View the "include" tree in a C/C++ project |
Possible Duplicate:
Do you know tool building tree of include files in project\file?
Currently reading the Minix source code (I'm interested in operating system & driver programming), I am looking for a program that would help me understand the tree view of this project.
I found a piece of software called Include Fi... | Try Eclipse CDT. It has Include Browser.
|
6,704,636 | 6,704,712 | can we assign a integer value to a reference variable? | It is not possible to assign an integer value to a reference variable directly, say like:
int &x=10; //not possible
Is there any other way we can modify this statement to make it possible?
But not like this:
int a=10;int &x=a;
This works fine. But I want some other way or modify a little bit my expression and make it... | The reason it doesn't work is because 10 is of the type "const int". You can turn that into a reference, but you can't make it non-const without violating some logic at the least.
const int &a = 10;
that'll work.
int &b = const_cast<int &>(static_cast<const int &>(10));
will also compile, but you can't modify b (as ... |
6,704,780 | 6,704,803 | Using only g++ works, but not "g++ -c" and ld | I have the following source code in main.cpp:
#include <iostream>
#include <iomanip>
int main() {
std::cout << "Hi" << std::endl;
return 0;
}
Using this command works, and creates the executable file:
g++ -o main main.cpp
But this commands don't work:
g++ -c main.cpp
ld -o main main.o
The second one errors ... | I think if you use ld directly it does not include the C++ libraries by default. You can use g++ to do the linking as well, it will call ld with the correct settings.
g++ -c main.cpp
g++ -o main main.o
|
6,704,955 | 6,705,437 | Template specialization fails on linking | I have an issue with template specialization which I would like to understand. I'm working with Visual C++ 10.0 (2010). I have a class like this:
class VariableManager
{
public:
template<typename VarT>
VarT get(std::string const& name) const
{
// Some code...
}
// Th... | Your analysis is correct - an explicitly specialized function template that has any template parameters specified with explicit values provides a complete definition of a function.
If you have properly included the corresponding .cpp file that contains the explicit specialization's definition into your project, then V... |
6,704,982 | 6,705,034 | Unraveling some JNI C++ code from the Android core | I'm not very experience in C++ and JNI so I have real trouble with some parts of this code (which is a part of the Android framework, more precisely comes from the CPP source of the Surface class):
static void Surface_unlockCanvasAndPost(
JNIEnv* env, jobject clazz, jobject argCanvas)
{
jobject canvas = env... | This is constructor call syntax for a reference - it's a bit obfuscatory to write it like this, like writing int i(23); instead of int i = 23;, but it is really equivalent to writing
const sp<Surface>& surface = getSurface(env, clazz);.
|
6,705,255 | 6,705,451 | Why does my app crash at delete? | while(!m_RemoveNodeList.empty())
{
list<CNode *>::const_iterator const it = m_RemoveNodeList.begin();
CNode * const pNode = *it;
ASSERT(pNode != NULL);
m_NodeList.remove( pNode );
delete pNode; // crashing here
m_RemoveNodeList.pop_front();
}
The above sometimes crashes at the delete with a... | There is no apparent crash in your code and looks fine.
It could crash only if there are duplicate CNode* are stored inside the list<CNode*>; which will lead you to multiple delete. (it's mentioned by @pau.estalella in the comments).
You can try following method to catch if there are duplicate CNode*.
map<CNode*, int> ... |
6,705,429 | 6,705,470 | Wake up a QThread that is in sleep? | How can I wake up a QThread when it is sleeping?
I have a thread that is running in the background and now and then wakes up and does some small stuff, however if I would like to stop that thread in a controlled manner I have to wait for him to wake up by him self in order to make him quit. And since he is sleeping qui... | You could use a QWaitCondition rather than a simple sleep. If gives you much more control.
Example usage here: Wait Conditions Example
|
6,705,679 | 6,912,242 | Negative edge weight check in boost's dijkstra_shortest_paths | I am using the boost graph library to make a call to dijkstra_shortest_paths. However, I have something special setup in that the weight_map is actually a functor. Hence, everytime the boost library requires the weight of an edge, my functor is called, makes a complicated computation and delivers the result back to boo... | You are right, even supplying you own visitor the test of negativity will be performed.
void examine_edge(Edge e, Graph& g) {
if (m_compare(get(m_weight, e), m_zero))
boost::throw_exception(negative_edge());
m_vis.examine_edge(e, g);
}
But anyway the weight_map is supposed to be called multiple ti... |
6,705,751 | 6,705,802 | C++ win32 API Message box button clicked | I have just started learning how to program Windows GUI's using the low level Win32 API and C++ so please bear with me.
I have a message box which is displayed at one point and as you can see below it is set to an OK/Cancel box
MessageBox(hWnd, L"Hello", L"Caption", MB_OKCANCEL);
My question is, how do you check w... | Look at the MessageBox description. The return type is the value of the button clicked. For example, IDOK when the user pressed the "OK" button.
|
6,705,778 | 6,705,844 | QUdpSocket: No such file or directory | I try to use the following header file in QT:
#include <QUdpSocket>
but i get the error:
QUdpSocket: No such file or directory
| Did you add
QT += network
in your .pro file?
|
6,705,985 | 6,707,477 | How can I use compression with QHttp? | In a existing application with Qt the QHttp-class is used to access data over the network. This communication is in the moment uncompressed, but the server allows compression (and browsers actually use it). How can I use QHttp to make accept compression?
| QHttp is obsolete class. Try using QNetworkAccessManager. It uses compression by default in responses
|
6,706,059 | 6,706,093 | c++ best way to use for loop | I have this question that runs in my mind...
I have a std::vector to iterate:
which is the best way (the faster) to iterate?
here is the code using an iterator:
// using the iterator
for( std::vector <myClass*>::iterator it = myObject.begin( ); it != myObject.end( ); it++ )
{
(*it)->someFunction( );
}
and here is ... | None of the two will be any faster really, because on most implementations a vector<T>::iterator is just a typedef for T* and size is cached.
But doing ++it instead of it++ is a good habit. The latter involves creating a temporary.
for(std::vector <myClass*>::iterator it = myObject.begin( );
... |
6,706,076 | 6,706,162 | Is there a standard way to determine at compile-time if system is 32 or 64 bit? | I need to set #ifdef - checks for conditional compile. I want to automate the process but cannot specify the target OS/machine. Is there some way that the pre-compiler can resolve whether it it is running on 32-bit or 64-bit?
(Explanation) I need to define a type that is 64 bits in size. On 64bit OS it is a long, on ... | The only compile check you can do reliably would be sizeof(void*) == 8, true for x64 and false for x86. This is a constexpr and you can pass it to templates but you can forget using ifdef with it. There is no platform-independent way to know the address size of the target architecture (at pre-process time), you will ne... |
6,706,097 | 6,706,769 | Need inputs for making a tool to insert preformatted comments in C/C++ source/header file | I am trying to develop a tool that inserts comments in C/C++ source files in pre-defined formats.
The comments could be:
file headers <-> file names required
class comments <-> class name required
function comments <-> function name required
Following points are required to be taken mind:
If the comments are already... | I guess you 've got two choices:
Generate the whole c/c++ code and headers from a template or scripting language and use this one to insert the preformated comments. This is of course not an option if you still got a lot of code.
Or you need a tool to parse the code into sth. you can further use. You could try doxygen... |
6,706,110 | 6,706,182 | Visual Studio C++ Headers | I need to create structure like this:
// file main.h:
#pragma once
#ifndef _MAIN_H
#define _MAIN_H
#include <iostream>
#include "first.h"
#include "second.h"
#endif
// -----------------
// file first.h:
#pragma once
#ifndef _FIRST_H
#define _FIRST_H
#include "main.h" // because of using SomeFunction() in first.c... | int SomeVar; // used in first.cpp
Variables should never be defined in headers. They should be declared with extern:
extern int SomeVar; // used in first.cpp
Then you can actually define them in "first.cpp" with int SomeVar;.
Also, "first.h" does not need to include "main.h". Headers should only include files if the... |
6,706,586 | 6,706,638 | Unresolved external symbol error when compiling cpp-netlib v0.9 | I am trying to build the cpp-netlib library from Visual Studio 2010 but get the following linker error:
error LNK2019: unresolved external symbol "bool __cdecl
boost::network::uri::detail::parse_uri_impl(class
boost::iterator_range,class std::allocator > > &,struct
boost::network::uri::detail::uri_parts_default_... | After a lot of searching I found this post and this one from the creator of the library, mentioning:
An option to turn off the required external library to be linked with a macro (BOOST_NETWORK_NO_LIB). With this macro defined before
any cpp-netlib headers are included (or on the command line) the
functions th... |
6,706,794 | 6,706,854 | Evaluation of type for auto in C++0X | I am playing around with the auto feature in the C++0X standard but I am confused how the decision of the type is made. Consider the following code.
struct Base
{
virtual void f()
{
std::cout << "Base::f" << std::endl;
}
};
struct Derived : public Base
{
virtual void f()
{
std::cout... | In the first case with virtual function(s):
auto b1 = *dp;
auto& b2 = *dp;
First line causes object slicing which means b1 is an object of typeBase, so it prints Base. And the second line is creating an object of type Base& which is a reference to the actual object pointed to by dp. The actual object is of type Derive... |
6,706,901 | 6,706,935 | Reinterpret_cast use in C++ | Just a simple question,having this:
fftw_complex *H_cast;
H_cast = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*M*N);
what is the difference between:
H_cast= reinterpret_cast<fftw_complex*> (H);
and
H_cast= reinterpret_cast<fftw_complex*> (&H);
Thanks so much in advance
Antonio
| Answer to current question
The difference is that they do two completely different things!
Note: you do not tell us what H is, so it's impossible to answer the question with confidence. But general principles apply.
For the first case to be sensible code, H should be a pointer (typed as void* possibly?) to a fftw_compl... |
6,706,908 | 6,707,067 | Returning std::list trough an iterator NOT using templates | refering to this answer, the second code block. My question is:
If I know I will be processing only std::lists<int>, and only <int>.
Is there a way to write this (the second block and the third one) without using templates and without passing the list by reference as suggested in the comments? Could you show it to me?
... | That's my answer!
You can pass a std::back_insert_iterator<std::list<int> > to a function with or without templates. Secretly, you're still passing the list by reference, since the iterator itself holds a reference or pointer to the container.
typedef std::back_insert_iterator<std::list<int> > OutputIterator;
void get... |
6,706,966 | 6,706,996 | What default implementation of new/delete from the std-rtl should I use when overriding new/delete in global namespace? | I'm using the RTL as a dynamic library. This allows for an overridden new/delete operator in global namespace, because the linker would find my implementation first. I could rely on malloc() and free() to do the allocation stuff, but there are things like 'new_handlers' and 'std::nothrow' objects. Standard library temp... | You've replaced, not overridden the default implementation and you no longer can call it. You will have to reimplement it - for example by using malloc() and taking care of its return value, it's not very hard.
|
6,707,148 | 6,707,531 | Foreach macro on macros arguments | I wonder if it is possible to write a macro foreach on macros arguments. Here is what want to do:
#define PRINT(a) printf(#a": %d", a)
#define PRINT_ALL(...) ? ? ? THE PROBLEM ? ? ?
And possible usage:
int a = 1, b = 3, d = 0;
PRINT_ALL(a,b,d);
Here is what I achieved so far
#define FIRST_ARG(arg,...) arg
#define AF... | Since you are accepting that the preprocessor has VA_ARGS (in C99, but not in the current C++ standard) you can go with P99. It has exactly what you are asking for: P99_FOR. It works without the crude ()()() syntax from BOOST. The interface is just
P99_FOR(NAME, N, OP, FUNC,...)
and you can use it with something like... |
6,707,325 | 6,707,462 | Are there web frameworks for Boost::asio? | It sounds a bit strange using C++ for web developing, but with node.js becoming popular I think it's reasonable for C++ to do web stuff.
node.js is similar to Boost::asio, they are both asynchronous and having high performance. I think it is natural for C++ have its own web framework based on Boost::asio.
So are there ... | There is pion, which is a boost::asio based HTTP server written in C++. You could use that as a starting point for a C++ web framework.
|
6,707,475 | 14,114,290 | How can I implement an accurate (but variable) FPS limit/cap in my OpenGL application? | I am currently working on an OpenGL application to display a few 3D spheres to the user, which they can rotate, move around, etc. That being said, there's not much in the way of complexity here, so the application runs at quite a high framerate (~500 FPS).
Obviously, this is overkill - even 120 would be more then enou... | I would suggest using sub-ms precision system timers (QueryPerformanceCounter, gettimeofday) to get timing data. These can help you profile performance in optimized release builds also.
|
6,707,485 | 6,707,541 | Best way to access variables unique to derived class through container of baseclass | So I have a vector of pointers to baseclass, which is used to hold all instances of derived classes.
Base class:
#ifndef BASE_H
#define BASE_H
Class Base
{
public:
virtual void DoSomething();
};
#endif
A derived class:
#ifndef DERIVED_H
#define DERIVED_H
#include "base.h"
Class Derived : public Base
{
pu... | There is no elegant solution to this problem. If you have it, your design is probably flawed, and you should rethink it. Having special cases for sub-classes defeats the purpose of polymorphism (although I admit that sometimes it is the only solution).
|
6,707,701 | 6,708,625 | Reformulate custom predicate as std-predicate | A program I'm working on contains this predicate struct:
struct Unlike {
Unlike(const Vertex& in) : a(in) {}
bool operator()(const Vertex& b) {
return !(a==b);
}
const Vertex& a;
};
Vertices are structs with (among other members) a struct coord with members X, Y, Z. Comparison is done with thes... | std::adjacent_find looking ahead for one item and returns iterator if predicate is true.
(1) For example, if you use not_equal_to for the list of two letters
['a','b'] and your current iterator points to 'a' then predicate
will be positive because 'a' not equal to the next 'b' and std::adjacent_find
re... |
6,707,886 | 6,707,995 | How to write a c++ function what can return either iterator or reverse_iterator | As far as I can tell in c++ there is no common base class that covers both iterator and reverse_iterator.
The only suggestion I have seen so far is to get around this using templates (
How to write a function that takes an iterator or collection in a generic way? )
However this solution doesn't seem to work for me.
cla... | In C++ you can't write a function that returns two different types. In your template case it will return one or the other depending on the instantiation. You could possibly return a base pointer to a polymorphic iterator but that would cause me to ask what you're really trying to do here. Even the standard containers d... |
6,708,042 | 6,708,092 | How do I detect where the program is stuck in an infinite loop? | I am working on a (relatively complex) game. The game freezes in release mode. The freeze happens after 1-2 min. of game-play. The current configuration of the release mode that I have allows me to break (that is go into debug), which is good, but may give me wrong information but that is fine for this particular case ... | If you break and you encounter native code that is not yours, check the call stack. The call stack is the list of functions that got called to reach the current point in the code. Go up some levels in the stack until you encounter the method which is currently running.
|
6,708,293 | 6,708,350 | Is this the correct way of using a void* member pointer? | Can I use the method doSomething like this; first having assigned the pointer to the A class to the void* member of b?
class A
{
public:
A(int);
int m_x;
int doSomething(){};
};
class B
{
public:
void* m_y;
};
#include "x.h"
using namespace std;
A::A(int x)
{
m_x = x;
}
i... | Stay away from void*
Why not have a pointer to A in B (or even, B owns the instance of A), or B holds a smart pointer to an instance of A - there are so many other better ways of doing things.
|
6,708,570 | 6,708,813 | Why C++ cannot initialize a variable of type "derived class" with an rvalue of type "super class"? | Please consider the code below:
class a
{
int a1;
public:
a()
{
printf("foo1\n");
}
};
class b : public a
{
int a2;
public:
b()
{
printf("foo2\n");
}
};
int main (int argc, const char * argv[])
{
b *instance = new a();
return 0;
}
It gives Error: Cannot... | Let's make this a little more concrete:
class Animal
{
int a1;
public:
Animal()
{
printf("Animal\n");
}
};
class Bat : public Animal
{
int a2;
public:
Bat()
{
printf("bat\n");
}
};
int main (int argc, const char * argv[])
{
Bat *instance = new Animal();
... |
6,708,904 | 6,709,237 | c++: Can boost::bind be used to convert member function to expected function pointer signature? | I'm using a 3rd party library that passes function pointers to a method call.
class RTSPClient{
public:
...
typedef void (responseHandler)(RTSPClient* rtspClient,
int resultCode, char* resultString);
...
unsigned sendOptionsCommand(responseHandler* responseHandler,
Authenticator* authenti... | Not out of the box. However, let me sketch how you could do it.
struct Foo : RTSPClient {
boost::function<void(int resultCode, char* resultString)> bound;
Foo(boost::function<void(int resultCode, char* resultString)> bound) : bound(bound) {}
// Need a static method to get a regaulr function pointer
static void... |
6,708,937 | 6,709,489 | intermixing c++ exception handling and SEH (windows) | I have a function in which I call getaddrinfo() to get an sockaddr* which targets memory is allocated by the system.
As many may know, you need to call freeaddrinfo() to free the memory allocated by getaddrinfo().
Now, in my function, there are a few places, where I may throw an exception, because some function failed.... | You could wrap the addrinfo in a class that calls getaddrinfo in the constructor and freeaddrinfo in its destructor.
That way it will always be freed, whether there is an exception thrown or not.
|
6,709,056 | 6,709,945 | Partial template specialisation of a functor that's calling a member method of objects passed to it | I have the following functor and its partial specialisation
template <class _T, typename _Return = void, typename _Arg = void>
struct Caller
{
typedef _Return(_T::*Method)(_Arg);
Caller(Method pm, _Arg a)
: _pMethod(pm),
_arg(a)
{}
_Return operator()(_T& obj)
{
return (ob... | I think the constness of _T in Caller doesn't reflect in this's
constness of Method automatically in MSVC
(If anything, I feel GCC's behaviour you mentioned is strange).
If you want to reflect the constness of _T in the constness of this,
how about preparing auxiliary class Select_Type like the following, and
selecting... |
6,709,066 | 6,712,130 | C++ k shortest paths algorithm | Does someone know if there is any production-ready K-shortest-paths algorithm for C++?
The only available implementation (k-shortest-paths), unfortunately, leaks memory, has counter-intuitive interfaces and another "reinvented wheel" - the Graph class.
I'm looking for something better, probably, boost::graph-based.
The... | There is another one, but you'll have to check if this also leaks memory.
http://sourceforge.net/projects/ksp/files/ksp/ksp-1.0/
|
6,709,356 | 6,709,394 | How do I reinterpret an unsigned long (DWORD) as a signed long in C++? | I want to reinterpret an unsigned long (actually, a DWORD) as a signed long. I tried:
DWORD x;
long y = reinterpret_cast<signed long>(x);
However, VC++2010 intellisense tells me "Invalid type conversion". Why? How do I fix it?
| try static_cast instead. VC generates an error if you try an excessively permissive cast (like using reinterpret_cast when static_cast or const_cast will suffice).
There are 5 types of casts in C++, each of which allows you to do more (grants more permissions). The least permissive casts are const casts (const_cast<... |
6,709,392 | 7,013,416 | Event Handling in Qt | I am new to Qt GUI programming and come from a .NET/Winforms background as far as GUI development goes. I am using the Qt Creator IDE.
How can I handle a button press event in Qt to do something like the following:
if (button.clicked = true)
{
startProgram();
}
Also, how would I browse for a configuration file whi... | In order to access the functions defined in the console application, you need to include the headers (.h/.hpp) that declare these functions, and link their implementation. I you have the source code of the implementations (.cpp), you need to add them to the sources to be compiled (they will be compiled in object files ... |
6,709,405 | 6,709,477 | Is there a trunc function in C++? | I searched around and couldn't find the trunc function for C++. I know I can do this:
int main()
{
double a = 12.566789;
cout << setprecision(2) << fixed << (int)(a * 100) / 100.0 << endl;
return 0;
}
but I'm not sure it's the best way to do this. Thank you.
| trunc is there, in <cmath>:
#include <iostream>
#include <cmath>
int main() {
std::cout << trunc(3.141516) << std::endl;
}
I suppose you're looking for something else?
|
6,709,459 | 6,709,507 | C++ template comprehension | I am trying to understand what would be the meaning of the following code since it is a valid C++ code:
template<class A>
class AT
{
AT();
};
template<class B>
AT<B>::AT()
{}
Can someone help me understand what is the effect of the template instantiation in the constructor? And also if someone can come with a use... | There is no template instantiation here. The later half of this code simply defines the constructor for the AT class. Note that it general practice to use the same names for the template parameters when doing this:
template<class A>
class AT
{
AT();
};
template<class A>
AT<A>::AT()
{}
The use for this syntax woul... |
6,709,552 | 6,710,395 | Getting wrong answer for Project Euler #27 | I'm working on Project Euler #27 in C++:
Euler published the remarkable quadratic formula:
n² + n + 41
It turns out that the formula will produce 40 primes for the
consecutive values n = 0 to 39. However, when n = 40, 40² + 40 + 41 =
40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² +
41 + 41 is... | You are allowing a to be negative, and your formula returns an int. Does calling Helper::isPrime with a negative number even make sense (in other words, does Helper::isPrime take an unsigned int?)
|
6,709,570 | 6,736,542 | drawing a "preview" of line in simple graphical editor | Drawing line with QPainter.
onMousePressed : saving (x0,y0)
onMouseReleased : QPainter.drawLine (x0,y0,x1,y1)
I want to see preview of line onMouseMove. But if will redraw all picture it will be too long.
How to do it?
| I'd go simple for a first shot.
If your are not using any hardware accelerated rendering you can render in a QPixmap that you save as a member of your instance (lets call it buffer).
QPixmap* buffer = new QPixmap( this->size());
QPainter painter( buffer);
painter.draw(...) //draw your stuff in it
Then on paint when ... |
6,709,735 | 6,709,799 | Are there any negative effects to using base class pointers on derived classes in c++? | I generally avoid using class pointers , since references seem way more efficient. But I have been recently forced to use them as they present the only (efficient and easy) solution to binding functions with window ids in my windows api wrapper. I have created an array of class WinControl. in my WinHandler class which ... | What you are storing in the widget set is a pointer. NOT the object. The problem with your design is that it is not clear who is supposed to own the object thus destroy it.
I would change the interface to make ownership explicit.
Option 1:
WinHandler does NOT own the widget:
void AddWidget(Widget& w) { WCount++; Widget... |
6,709,793 | 6,709,891 | How to make class member function as thread function using boost | I am going to write an adapter class. In this class there is an xmlrpc-c server (abyss server). I want to start the server by creating a new thread, and the thread's function is the member function XMLThreadFun().
When I try to use the code below there is an error at the line of the adapter's constructor implementation... | You will need to use boost::bind to call a member function as a thread.
Something like
class MyClass {
public:
void Start();
void DoStuff( int limit );
};
MyClass foo;
boost::thread thread1( boost::bind( &MyClass::Start, &foo ) );
boost::thread thread2( boost::bind( &MyClass::DoStuff, &foo, 30 ) );
// threads ... |
6,709,795 | 6,709,823 | Converting string to ASCII | I was just trying something out and made the following code. It is supposed to take each individual letter in a string and print its ASCII equivalent. However, when there is a space, it stops converting. Here is the code:
#include <iostream>
#include <string>
using namespace std;
void convertToASCII(string letter)
{
... | cin >> plainText reads from the input up to, but excluding, the first whitespace character. You probably want std::getline(cin, plainText) instead.
References:
std::getline
istream& operator>> (istream& is, string& str)
|
6,710,095 | 6,711,335 | boost 1.47 compile error with non_blocking() | Can anyone discern what I'm doing wrong here? According to the documentation in 1.47 basic_datagram_socket inherits from basic_socket so the non_blocking() or non_blocking(bool) should be inherited.
Thanks
Error 1 error C2039: 'non_blocking' : is not a member of 'boost::asio::basic_datagram_socket' c:\DEV\proj... | The member function boost::asio::ip::udp::socket::non_blocking() appears to be new in 1.47. Either it doesn't actually exist in 1.47 or you're actually using an older header. I'd suggest finding the <boost/asio/basic_datagram_socket.hpp> header that's being included to see if it actually has that member function as pa... |
6,710,129 | 6,710,196 | C++: Concurrency and destructors | Suppose you have an object which can be accesed by many threads. A critical section is used to protect the sensitive areas. But what about the destructor? Even if I enter a critical section as soon as I enter the destructor, once the destructor has been called, is the object already invalidated?
My train of thought: S... | In general, you should not destroy an object until you know that no other thread is using it. Period.
Consider this scenario, based on your 'train of thought':
Thread A: Get object X reference
Thread A: Lock object X
Thread B: Get object X reference
Thread B: Block on object X lock
Thread A: Unlock object X
Thread B: ... |
6,710,686 | 6,710,734 | Handling errors while using unmanaged code in a managed one ( C++, C, C++/CLI, C#) | I am using a badly written 3rd party (C/C++) Api. I used it from managed code( C++/ CLI). Get sometimes "access violation errors". And this crash whole application. I know i can not handle those errors[ what can i do if a pointer acess to illegal memory location etc].
But I do not want my application crash as a whole.... | If you're sure that the problems are bugs in the library, and not a result of you passing in bad arguments, then your most robust option is inter-process communication with a hosting process that loads the library. That way your OS process separation keeps the library from bringing down your application.
You can try t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.