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,389,238 | 7,473,500 | How should a constructor report errors? Pointers to external flags? | I am working on refactoring some of the old C-style code to bring it more into line with C++ code. I still am a bit new to C++
An example of the code I am working on is as follows
Errmsg foo{
ErrMsg err = NoError;
/*
Some Processing
*/
err = foo_cleanup(err,/* some parameters*/);
/*
Some More Proc... | Leaving aside that you should if possible fix the calling code so that an exception is OK, you could use the two-phase construction idiom:
struct foo_class {
foo_class() { } // default constructor cannot fail
Errmsg nothrow_init(/* other params */) throw() {
/* initialize other parameters */
}
f... |
7,389,322 | 7,389,399 | Which function should be use to converting string to long double? | Note that in general, double is different from long double.
strtod converts string to double, but which function should be use to converting string to long double?
| In C++03, use boost::lexical_cast, or:
std::stringstream ss(the_string);
long double ld;
if (ss >> ld) {
// it worked
}
In C99, use strtold.
In C89, use sscanf with %Lg.
In C++11 use stold.
There may be subtle differences as to exactly which formats each one accepts, so check the details first...
|
7,389,330 | 7,389,383 | Why cant we use reference in algorithms and data structure? |
As a general rule, use references in function parameters and return
types to define attractive interfaces. Use pointers to implement
algorithms and data structures.
I read this line in an article.I had the doubt of why reference cannot be used in algorithms and datastructures?
Please help me undestand why is it.
| Because a reference can't be made to refer to any other object after it's been initialised to refer to a particular one.
As proof, §8.5.3.2 of the Standard says
A reference cannot be changed to refer to another object after
initialization. Note that initialization of a reference is treated
very differently from as... |
7,389,535 | 7,389,597 | print number in reverse | im simple asking if this is ok. i was asked to do the following. Write a program that will continuously ask the user for positive integers (until the
user enters a negative integer at which the program will be terminated). Every
time the user inputs a positive integer the program will print out this integer in
reverse.... | because of this: return false; - I'll leave it to you to figure out the rest..
|
7,389,707 | 7,390,052 | inheriting from an enable_if'd base | I'm trying to partially specialize a trait for arrays of non-chars:
template<typename T>
struct is_container : std::false_type {};
template<typename T, unsigned N>
struct is_container<T[N]>
: std::enable_if<!std::is_same<T, char>::value, std::true_type>::type {};
Visual Studio 2010 gives me a C2039 (type is no elemen... | Check the topic '3.1 Enabling template class specializations' at
http://www.boost.org/doc/libs/1_47_0/libs/utility/enable_if.html
Edit: in case boost.org link dies...
3.1 Enabling template class specializations
Class template specializations can be enabled or disabled with enable_if. One extra template parameter need... |
7,389,757 | 7,390,166 | Get Text from an Edit Control (Pure Win32 API) | I've been trying to get this to work for like ages but with no avail (sad face).
int iChars = GetWindowTextLength (GetDlgItem(handle,ID))+1; // Room for '\0'
char* pstrText;
pstrText = (char*) malloc (sizeof(char)*iChars);
if (pstrText != NULL) {
//GetWindowText (GetDlgItem(handle,ID), pstrText, iChars);
Ge... | The wParam parameter is wrong here:
SendMessage(handle, WM_GETTEXT, (WPARAM)len, (LPARAM)buffer);
You should pass len+1 because of the zero-terminator.
|
7,389,770 | 7,390,468 | initialising references during declaration | Why is it required to initialise the references during its initialisation. If not initialised it throws errors. Is it const datas should always be initialised with a value. Why is it only with constants and does not require a variable to be initialised during declaration.
EDITED:
#include<stdio.h>
int main()
{
int... | The code you posted can't be compiled as a C program, since there are no references in C.
To make it compile as C, you would have to modify it:
#include<stdio.h>
int main()
{
int a=10,b=12;
int *c=&a;
printf("%d\n",a);
*c=b;
printf("%d\n",a);
printf("%d\n",*c);
return 0;
}
As for C++ refer... |
7,389,930 | 7,390,518 | Overload stream operator for nested template C++ STL | I've got a data file that is a single line consisting of a nested series of doubles eg.
[[0.127279,0.763675,0.636396],[0.254558,0.890955,0.636396],
[0.127279,0.636396,0.763675],[0.254558,0.763675,0.763675],
[0.381838,0.890955,0.763675],[0.127279,0.509117,0.890955],
[0.254558,0.636396,0.890955],[0.509117,0.890955,0.8909... | Actually, the problem with your code that you want to use the same function for both, when T is:
vector<double>
double
But the logic which needs to read the data into vector and double is slightly different. So you cannot do that, at least not with that simple logic:
I would prefer to write two functions, to handle b... |
7,389,937 | 7,389,976 | Accessing private members | I have a class:
class A
{
private:
ComplexClass member1;
public:
getMember1(){return member1;};
};
and I have an implementation that, for code simplification (more easily understandable), needs to retrieve that member1 to work with it. The first thing that would come to my mind would be:
ComplexClass *myComplexClass ... | A const reference will keep them from editing. In my opinion, it makes your intention clearer than a const pointer.
class A
{
private:
ComplexClass member1;
public:
const ComplexClass &getMember1(){return member1;};
};
|
7,389,960 | 7,390,018 | Visual C++ 2010 Express for mac | Is it possible to get Visual C++ 2010 Express for Mac OS X?
If not is there another application, other than Xcode, that will do the same thing?
| Visual Studio C++ is not supported on OS X.
You can use either Eclipse or KDevelop. A complete listing IDEs for C++ is available at
http://en.wikipedia.org/wiki/Comparison_of_integrated_development_environments#C.2FC.2B.2B
|
7,390,007 | 7,390,059 | There are some way to print error log to an external file using g++ C++ compiler? (C++) | i'm trying to compile my code with g++ C++ compiler on Windows and the compiler is returning some errors. Ok, as usual. But it's printing so much errors that the console just goes down to the end and I can't see the first lines of error log. My question is: there are any way to print the error log to an external file s... | You need to redirect stderr, but it is shell dependant.
For example on sh and bash, you can use:
g++ file 2> error.log
On csh and tcsh it would be:
( g++ file ) >& error.log
|
7,390,082 | 7,390,668 | Starting a detached proceess in Qt and dealing with ports | I probably have a mis-understanding of how Qt's startDetached() works but I am witnessing a problem where I have an application that functions as a remote launcher.
The launcher spawns processes off using startDetached which I thought separates the launcher app completely from the new process. However, something fishy... | According to that bug report, all file and socket descriptors opened by Qt (QFile, QTcpSocket...) are flagged with FD_CLOEXEC to prevent them from being shared with child-processes.
So, if you are opening the sockets without Qt, you should probably do the same.
Edit
I am opening sockets with the ICE framework.
You ... |
7,390,126 | 7,390,181 | What should the 'pop()' method return when the stack is empty? |
Possible Duplicate:
C++ STL stack question: Why does pop() not throw an exception if the stack is empty?
When designing a stack in C++, what should the pop() method (or front() method) return when the stack is empty? Which of the following design is better?
Throw an exception
Undefined, but require the user calling... | The programming-by-contract style would be that having a non-empty stack is a precondition of calling pop, and that calling a method without meeting its preconditions has an undefined outcome. My implementation would throw a std::logic_error, but that would not be required. In C, my implementation would abort via asser... |
7,390,171 | 7,402,747 | Where do I place the Unit Testing source and expose the internal components? | I am taking over a project that exposes components via ATL.
I see two major areas for the unit test to cover with this setup:
Testing the internal components (may or may not be exposed via COM)
Testing the external exposed components (aka testing the exposed interface)
Currently the project has all of its internal c... | Someone on another team said that their team placed all of the unit tests in separate projects and were able to expose the internals via static libs. This makes a lot of sense to me in that it helps with modularity and provides alot of other benefits. So each major coupling of code would be a static lib (without going ... |
7,390,174 | 7,390,274 | C++ simple inheritance problem | #include <iostream>
using namespace std;
class A
{
protected:
int a;
};
class B : public A
{
public:
int func(A* p)
{
cout << p->a;
}
};
I really cannot understand why I cant access to 'a' by 'p->a'.
Is there anyway to access p's member 'a' in class B, without changing 'protected' to 'public'?... | On this topic, the C++03 standard states (emphasis mine):
11.5 Protected member access
1 When a friend or a member function of a
derived class references a protected nonstatic member function or
protected nonstatic data member of a base class, an access check
applies in addition to those described earlier in cla... |
7,390,179 | 7,390,892 | Creating a sequence of vectors C++ | In my question a vector means a vector of structures of the form
struct node
{string key;
int a,b; };
I want to code up the following: Given a user specified number say d I want to create a sequence of d vectors v_1, v_2, ...v_d.
v_1 is created from user data, and v_i from v_(i-1) for i>=2 .
The siz... | Use std::vector<std::vector<node> >, but use vector::reserve() intelligently so as to avoid reallocations:
using std::vector;
vector<vector<node>> v(d); // 0 nodes allocated, no wasted space yet
using std::copy;
using std::istream_iterator;
using std::back_inserter;
// Wish I could v[0].reserve(), but we don't have th... |
7,390,420 | 7,390,528 | Why does this code hang at mentioned place? | This is a naive example I have coded to study C++ operator overloading. When I execute it, code hangs at the statement c = a + b; and control never reaches c.display();
As part of debugging if I put a cout << ptr << '\n'; in the assignment operator overloaded function it does print out HelloWorld, so string doesn't see... | I think that what you are getting is a memory error. This line:
c = a + b;
does the following:
c.constructor()
c.operator=(a.operator+(b));
and your operator= fails to allocate memory
void operator =(mystring s)
{
// ptr is allocated enough memory for "", i.e. one byte
strcpy(ptr,s.ptr); // copying more than one ... |
7,390,437 | 7,390,483 | C++ const member functions are modifying member variables | Today I found out that code like that works. That sounds really strange to me, because as far as I always knew you can't modify any of members from const member function. You actually can't do it directly, but you can call non-const member function. if you mark member function as const that means that this pointer pass... | Your member variable is not X, but pointer to X. As long as foo does not modify the pointer, it can be const.
|
7,390,900 | 7,390,938 | template member functions in c++ | I have a problem with generics in c++.I have two Matrix.h and Matrix.cpp files.Here is files:
#pragma once
template<class T>
class Matrix
{
public:
static T** addSub(int size,T** firstMatrix,T** secondMatrix,int operation);
}
and Matrix.cpp
#include "Martix.h"
template<class T>
static T** Matrix<T>::addSub... | Unfortunately, you can't have the declaration of a template class in the *.cpp files. The full definition has to stay in the header file. This is a rule of many C++ compilers.
See this: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12
A template is not a class or a function. A template is a "pattern"
... |
7,391,039 | 7,391,084 | Handling an 'else' type situation within a loop | I have a homework problem for my C++ class and the problem wants us to have the user input a wavelength and then output the correct type of radiation. The point to notice is that there are more Wave Name values than there are Wave Lengths.
My solution is listed below:
const double WAVE_LENGTH[] = { 1e-11, 1e-8, 4e-7, 7... | I think you can simplify your loop to this:
unsigned short i;
for (i = 0U; i < 6U; ++i)
{
if (waveLength < WAVE_LENGTH[i])
{
break;
}
}
std::cout << "The type of radiation is " << WAVE_NAME[i] << std::endl;
|
7,391,057 | 7,391,117 | .mm conversion causes Undefined symbols for architecture i386 errors | I recently imported a c++ file into my obj project that I want to use. In the class I want to use it in I change the file name from MyClass.m to MyClass.mm.
Doing this gives me 20 or so errors. What exactly do these errors mean and how can I change MyClass to an objective c++ class to facilitate the new c++ class I wan... | Sounds like your functions have C linkage, but you haven't declared that properly in their header. So a .mm file (Objective-C++) is going to see them and assume C++ linkage. The easiest fix is to wrap that #include statement in the appropriate extern block:
extern "C" {
#include "..."
}
A better solution is to do ... |
7,391,468 | 7,393,780 | Enforcing contract on concrete instances of an abstact hierarcy | I'm lost and in need of some divine guidance.
First things first: assume you have some nicely-neat interfaces:
class IProduct
{
public:
virtual void DoThings();
}
enum ProductType
{
...
}
class IProducer
{
public:
virtual IProduct* Produce( ProductType type );
}
class IConsumer
{
public:
virtual vo... |
Yet they have that thing in general: DoThings(). Pretend that it is,
like, PackAndSend(), or Serialize(), or Dispose(), whatever you like.
Nothing concrete, yet legit to base a hierarchy on.
Just because they can be in some hierarchy, doesn't mean they should. They are unrelated. I can't even fathom what value ... |
7,391,649 | 7,391,706 | Creating a vector of specific size in a map C++ | Hi suppose I want to create a map of the form map<int, vector<node> > where node is defined
as
struct node{
string key;
double pnum;
node():key(""),pnum(0) {}
};
Now If someone gives me a map key, say "Element_1" and a vector size 2 is it alright/safe to create
the vector under the key "Element_1" as it ... |
If someone gives me a map key, say "Element_1" and a vector size 2 is it alright/safe to create the vector under the key "Element_1" as it has been done below?
Yes, my friend. If the key already exists, then it updates the associated value, otherwise it creates a new entry with the key with default value [i.e vecto... |
7,391,737 | 7,391,775 | Dynamically Allocated Array of a Class | I've declared
private:
Comment *commentArray;
int arrSize;
in the header for the class in which it is used, called CommentManager. These are initialized in the constructer, as follows:
arrSize = 1;
commentArray = new Comment[arrSize];
If I'm understanding this correctly, this should create an "array" of one... | commentArray[arrSize].setComment(commText,start,end);
arrsize is one step too much.
An array with say size 10 is indexed from 0 to 9, using 10 will be out of bound.
|
7,391,758 | 7,391,861 | A way to protect data being sent over a network? | I have just finished an application, a simple messenger client and I am looking to encrypt all of the data, whether a phrase of 3 or 200 letters.
What's the best algorithm for this type of app? At this moment I am trying to use 3DES with crypto++ (on VC10), but padding and others things seem a bit difficult.
I am not ... | One important factor is how reliable the network connection is expected to be. If you don't expect many dropped packets, or packets that arrive quite late, then you can use a stream cipher, or a symmetric block cipher in chaining mode. If you expect more network unreliability, then a symmetric block cipher in ECB mode ... |
7,391,920 | 7,392,616 | boost thread destroys polymorphism | duplicate of: "pure virtual method called" when implementing a boost::thread wrapper interface
I am trying to create a more object oriented version of the threads using boost threads.
So I created a Thread class:
class Thread {
public:
Thread() {}
virtual ~Thread() { thisThread->join(); }
void start() { th... | The answer is in that question:
"pure virtual method called" when implementing a boost::thread wrapper interface
Basically, when the boost::thread object begins running, the object it was run against had the
time to be deleted.
You have to implement a join method that you call manually before destroying the object.
|
7,392,057 | 7,393,666 | Why can't a constant pointer be a constant expression? | The following program compiles:
template <const int * P>
class Test{};
extern const int var = 42; //extern needed to force external linkage
int main()
{
Test<&var> test;
}
This one, however, doesn't, which is a surprise for me:
template <const int * P>
class Test{};
extern const int var = 42; //extern needed to... | It's a bit more complicated. In C++03 and C++11, &var is a constant expression if var is a local static / class static or namespace scope variable. This is called an address constant expression. Initializing a class static or namespace scope pointer variable with that constant expression is guaranteed to be done before... |
7,392,164 | 7,393,095 | Very strange GetOpenFileName problem | I seem to be having a very strange problem with GetOpenFileName.
It errors for no apparent reason, however, if I call CommDlgExtendedError() in the error check, the error never happens in the first place.
Here is my code:
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdL... | OPENFILENAME fm;
char flnm[MAX_PATH]; // nobody initialized me ...
ZeroMemory(&fm, sizeof(fm));
fm.lStructSize = sizeof(OPENFILENAME);
fm.hwndOwner = NULL;
fm.lpstrFilter = "Text Files (*.txt)\0*.txt\0";
fm.lpstrFile = flnm; // ... who knows what I am?
fm.nMaxFile = MAX_PATH;
fm.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIS... |
7,392,198 | 7,392,499 | If conditioning and String | I am very new at C++ and deeply appreciate your help!
I am trying to make a 'If' condition for a string, that is, for example:
#include <iostream>
using namespace std;
int main()
{
string message = "HELP";
int password;
cout<<"Please enter password";
cin<<password;
if (password = message);
}
else {
cout<<"Please try ... | What you probably want to do is:
#include <iostream>
// using namespace std; don't do this (its just lazy)
// Also its a bad habit to get into.
int main()
{
std::string message = "HELP";
// int password; I assume you want a password to be a string
std::string password;
std::cout << "Please enter pa... |
7,392,302 | 7,394,827 | Build parser from grammar at runtime | Many (most) regular expression libraries for C++ allow for creating the expression from a string during runtime. Is anyone aware of any C++ parser generators that allow for feeding a grammar (preferably BNF) represented as a string into a generator at runtime? All the implementations I've found either require an explic... | It should be pretty easy to build a recursive descent, backtracking parser that accepts a grammar as input. You can reduce all your rules to the following form (or act as if you have):
A = B C D ;
Parsing such a rule by recursive descent is easy: call a routine that corresponds to finding a B, then one that finds a ... |
7,392,439 | 7,392,558 | How do I force to input before termination? | Here is an excerpt of my code, where the problem lies.
long long user_largest_plus;
long long user_largest_minus;
cout << "Input the largest+1 in decimal: " << endl;
cin >> user_largest_plus;
//cout << endl;
// cout << "Input the largest-1 in decimal: " << endl;
cin >> user_largest_minus;
c... | Try replacing
cin >> user_largest_plus;
with
if( !( cin >> user_largest_plus ) ) {
user_largest_plus = 0;
cin.clear();
cout << "Bad input. Using zero instead\n";
}
When the input text is not a valid long long, two interesting things happen:
user_largest_plus is never set, and
the bad bit is set in cin.... |
7,392,726 | 7,392,758 | Is there a limit to the length of identifier names in C++? | Is there a length limit to the names of variables in C++? What is it? Does this have anything to do with the "64/32-bitness" of the machine?
EDIT: Specifically, what is GCC's limit?
| section lex.name of the C++ standard says
An identifier is an arbitrarily long sequence of letters and digits.
However, variable names which share a very large number of initial characters may not be treated as separate variables, the exact number of initial characters used is implementation-specific. Annex B says:
... |
7,393,051 | 7,393,098 | What is the difference between int and long? |
Possible Duplicate:
What is the difference between an int and a long in C++?
difference in long vs int data types in C++
In c++ which is the diference between the int and long data type. Wrote the following code:
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Int_Max = "<<INT_MAX<<endl;
cout<<"Int_Min = "<<IN... | According to the standard, int is guaranteed to be at least 16 bits and long is at least 32 bits. On most 32-bit compilers they are just the same, both 32 bits. But you shouldn't count on this as there are 64-, 16- and even 8-bit compilers too.
|
7,393,056 | 7,393,147 | std::for_each usage on member function with two args | Here's a general idea of how my class is defined as ( it performs other operations than what is mentioned below)
struct Funktor
{
Funktor(int val):m_val(val){}
bool operator()(int arg1, int arg2) { return m_val==arg1*arg2; }
int m_val;
};
And now I have a vector of the above objects, and I am trying to cal... | C++03 Solution (without boost):
Write another functor as:
struct TwoArgFunctor
{
int arg1, arg2;
TwoArgFunctor(int a, int b) :arg1(a), arg2(b) {}
template<typename Functor>
bool operator()(Functor fun)
{
return fun(arg1, arg2); //here you invoke the actual functor!
}
};
Then use it as:... |
7,393,458 | 7,393,550 | C++ Double Dispatch for Equals() | Imagine I have abstract base class Shape, with derived classes Circle and Rectangle.
class Shape {};
class Circle : public Shape {};
class Rectangle : public Shape {};
I need to determine if two shapes are equal, assuming I have two Shape* pointers. (This is because I have two instances of vector<Shape*> and I want to... | When you create methods like this:
virtual bool is_equal(Shape& circle) { return false; };
And in the subclass,
virtual bool is_equal(Circle& circle) { return true; };
These are not the same method. You have two separate virtual methods, neither of which is overridden (they are overloaded not even overloaded, as Ben... |
7,393,672 | 7,393,815 | Library for Python: How to call C++ functions from Python program? | There is a library for Python that enables the calling ability (can call functions in C++ format without extern "C". Please, could you remind me the name of the library? I forgot it's name and can't find it.
It's not Boost.Python.
Thank you very much. Your answer will be rewarded.
| Perhaps you are thinking of SWIG.
|
7,393,879 | 7,413,672 | Trouble calling on a Java method from a native thread using JNI (C++) | I have a JNI problem which I hope someone can help me out with.
I'm trying to call on a constructor of a Java class called LUSOutputJNI from a native thread.
It keeps failing on FindClass(...) of this specific class.
Here is the code:
LOGE("1");
JNIEnv *env = NULL;
LOGE("2");
int res = -1;
res = g_vm-... | Found the answer \ work around in here. (Look for FAQ: "FindClass didn't find my class" in
JNI tips)
I basicaly saved a global ref to the needed jclass objects.
Did however had to overcome some evil JNI changes between C/JNI and C++/JNI in order for the code to compile.
This is how I got the NewGlobalRef to compile an... |
7,393,998 | 7,394,056 | Sscanf in a C++ (Read in values and assign simultaneously) | Can I do something like this in C++ ?
//int i,Data[];
//malloc Data[];
$sscanf(line,"Data[%d]=0x%d",i,Data[i]);
Data[] is an int array and I am trying to read in random indices according to the value of 'i' I read in in one shot.
| You can do it this way:
int index, value;
sscanf(line, "Data[%d]=%d", &index, &value);
// Check if index is within bounds of the array here
Data[index] = value;
You need the '&' because sscanf takes pointers as arguments.
|
7,394,174 | 7,394,225 | How to deallocate pointer-to-pointer-types that point to pointer-types in heap that point to other objects in heap? | So I decided to have some pointer fun tonight :)
CursorHBList::CursorHBList(UINT iNumHB)
:m_ppCursorHB(nullptr)
,m_iNumHB(iNumHB)
{
if (iNumHB != 0) {
m_ppCursorHB = new CursorHitBox* [iNumHB];
}
}
so you can see, I've now dynamically allocated pointer-types.
Those pointers will each point t... | As suggested, a better way would be using a container of smart pointers.
However, since you can't use smart pointers (I don't know why because all a smart pointer is is a very simple class, you could write your own), you'll need to loop through the array and delete each pointer, then delete[] the array, in that order. ... |
7,394,250 | 7,401,512 | Possible heap corruption issue when deleting an object | I'm working on a framework and have run into an issue. I noticed that I was leaking memory by not deleting an object. When I tried to delete this object just before exiting the application I get an error, this one to be exact:
After I got this I grabbed Application Verifier
When running the code it set a breakpoint on... | Fixed the problem, the last buffer I was deleting was buffer in video ram, I obviously can't delete this one. No heap corruption going on at all just a logical thinking flaw.
Thank you to the people that tried to answer this one and help me.
|
7,394,260 | 7,394,524 | Passing function template specializations to a variadic template function | I have no problem passing the address of a function template specialization to a regular template function:
template <typename T>
void f(T) {}
template <typename A, typename B>
void foo(A, B) {}
int main()
{
foo(&f<int>, &f<float>);
}
However, when I try to pass the same specializations to a variadic template:
t... | Looks like it might be a bug in GCC that is possibly fixed in GCC 4.6.2 (I say possibly because it's not exactly the same, but does involve getting the address of a variadic template function).
|
7,394,338 | 10,951,103 | Asynchronous Agents and window messages | I'm currently playing with the Asynchronous Agents Library in Microsoft's Concurrency Runtime. I have not yet found an obvious way to signal that a task is finished by using window messages, or some other means of notifying the UI thread that the work is finished.
I know I can pass window handles and message values (WM... | You can create one monitor thread with sole function of monitoring an unbounded_buffer for a windows message and dispatching that message appropriately. Have your agents know about this buffer.
|
7,394,367 | 7,394,422 | Is using boost::bind to pass more arguments than expected safe? | Using boost-bind, the resulting boost-function may receive more arguments than the bound object expects. Conceptually:
int func() { return 42; }
boost::function<int (int,int,int)> boundFunc = boost::bind(&func);
int answer = boundFunc(1,2,3);
In this case, func() receives 1,2, and 3 on the stack even though its signat... | Yes, this is safe and portable – as mentioned explicitly in the documentation, the bind-expression returned by boost::bind silently ignores extra arguments.
I.e., in your first example, func does not receive the values 1, 2, and 3 – boundFunc receives the values 1, 2, and 3 and forwards them to the contained bind-expre... |
7,394,492 | 7,408,582 | Does inheriting constructors work with templates in C++0x? | In C++0x, you can use the using keyword to inherit constructors, like so:
class B { B(int) {} };
class A : public B { using B::B; };
Which will implicitly declare an A(int) constructor. Does this work with templates?
class B { B(int) {} };
template<class T> class A : public T { using T::T; };
Within T::T, I expect ... | Yes it works, and the reason is the name lookup mechanism. The mechanism a inheriting-constructors declaration works is simple: If the using declaration's name refers to base class constructors, that's an inheriting constructors declaration. At 3.4.3.1[class.qual]p2 we find:
In a lookup in which the constructor is an ... |
7,394,503 | 7,478,886 | framework not found issue when linking a framework within a framework | I have a framework(FRAME1) that includes versions a b and c this is then included as a dependency within another framework(FRAME2).
However when I build FRAME2 it dies out with: ld:framework not found <nameofframework>
I have made the install location of the frame1 to /Library/Frameworks and I have also set it as @rp... | So the problem was Xcode 3.2.6. If I down reved to 3.2.5 it worked. I have logged a bug against apple in their Radar system.
Problem ID: 10139645
|
7,394,660 | 7,398,231 | Check if a Key is Down with Qt | I am playing around with some graphics, and I have implemented simple camera movement with the arrow keys. My first approach was to override keyPressEvent to do something like this:
switch(key)
{
case up: MoveCameraForward(step); break;
case left: MoveCameraLeft(step); break;
...
}
This doesn't work as I wish... |
So, I need to poll the keyboard in my Paint() routine. I haven't found
how to do it with Qt. I thought of having a map which would
be updated in keyPressEvent and keyReleaseEvent and poll that map in
Paint().
Your second method is what I would have done, except that I would use a continuous, periodic QTimer eve... |
7,395,072 | 20,232,857 | JSON <-> XML in C/C++ | I've been searching to no avail for a set of routines to do conversion between JSON and XML. I have found such routines in Javascript, Java, PHP, and Python, but not in C or C++.
FWIW, my json library is json-spirit. I am currently processing JSON, and would like to add XML support via a conversion layer (convert incom... | By far, the only specifically designed C++ library that directly converts XML to JSON I found on the Internet is xml2json: https://github.com/Cheedoong/xml2json
You can also convert JSON to XML if following the same rules.
|
7,395,113 | 7,395,139 | is recursive explicit template instantiation possible? | Given a template like
template<int dim> class Point { ... };
this template can be instantiated explicitly like
template class Point<0>;
template class Point<1>;
template class Point<2>;
template class Point<3>;
instead of instantiating every template individually like above, I would like to instantiate them recursive... | You could make a little Instantiator class:
template <unsigned int N> struct Instantiator
{
Point<N> p;
Instantiator<N-1> i;
};
template <> struct Instantiator<0>
{
Point<0> p;
};
Then simply add one explicit instantiation: template struct Instantiator<81>;
You can extend this idea lexicographically to any numb... |
7,395,160 | 7,395,203 | Declaring a member variable that takes a constructor parameter | // In A.h
class A
{
public:
enum eMyEnum{ eOne, eTwo, eThree };
public:
A(eMyEnum e);
}
// In B.h
#include "A.h"
class B
{
B();
private:
A memberA;
}
// In B.cpp
#include "B.h"
B::B(void) : memberA(A::eOne)
{}
The declaration to 'memberA' gives me a compile error using the g++ ... | It sounds like you are trying to initialise a member variable. You could do something like:
class B
{
public:
B() : memberA(A::eOne) {} // Initializer list in constructor
private:
A memberA;
};
|
7,395,441 | 7,395,592 | The application was unable to start correctly (0xc0000013). Click OK to close the application | I suddenly had this problem when starting up my (previous boots) working VS 2010 project.
The application was unable to start correctly (0xc0000013). Click OK to close the application.
Debug output:
`The program '[5940] myapp.exe: Native' has exited with code -1073741805 (0xc0000013).`
| STATUS_NO_MEDIA_IN_DEVICE, "There is no disk in the drive". Your debugging working directory is probably set to a USB emulated disk that's unavailable.
|
7,395,479 | 7,395,561 | VST host - Leaked objects - Juce/C++ | I am a PHP programmer learning C++ as I build a VST host. I may have bitten off more than I can chew but I am making some progress (I think)!
I'm using the Steinberg VST SDK and the JUCE library in Visual Studio 2010. I'm encountering a leaked object error and I don't quite understand the solutions I've found when I've... | Several things:
You're mixing wide strings and Microsoft ("T") strings. Pick one (whichever fits your API).
Don't say new in C++. It's almost always not what you need. Instead, just use automatic objects:
File fileHard("C:\\creative\\midi\\m1.mid");
FileInputStream * fileInputStream = fileHard.createInputStream();
... |
7,395,547 | 7,395,785 | What is the window class name assigned by Visual Studio when creating .NET form? | As in VC++ when creating a window we need to create a window class and use RegisterClass or RegisterClassEx to register. But in .NET we don't have this step.
So I wonder what the default window class name assigned by Visual Studio when creating a form?
As I've tracked out, the window class name assigned by Visual Studi... | Window class names are automatically generated. You cannot change them, even though CreateParams lets you set the ClassName property. Nor can an external program ever guess the auto-generated name correctly, part of it is generated from AppDomain.CurrentDomain.GetHashCode().
You'll need another way to identify the wi... |
7,395,570 | 7,395,654 | Replace Version Info Resource |
I'm Loading a certain Exe in My Program and I'm trying to replace It's Version Info Resource.
I'm Using UpdateResource() but for some reason It isn't replacing the original resource as it is supposed to do.
UpdateResource(hHandle,RT_VERSION,"1",MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),pRsrcMemory,rsrcSize)
When Th... | Resource IDs can be either strings or numbers. Which is the problem here, it is not resource ID "1", it is MAKEINTRESOURCE(1).
Fun puzzler.
|
7,395,700 | 7,395,749 | Reason for using non-type template parameter instead of regular parameter? | In C++ you can create templates using a non-type template parameter like this:
template< int I >
void add( int& value )
{
value += I;
}
int main( int argc, char** argv )
{
int i = 10;
add< 5 >( i );
std::cout << i << std::endl;
}
Which prints "15" to cout. What is the use for this? Is there any reason for usi... | There are many applications for non-type template arguments; here are a few:
You can use non-type arguments to implement generic types representing fixed-sized arrays or matrices. For example, you might parameterize a Matrix type over its dimensions, so you could make a Matrix<4, 3> or a Matrix<2, 2>. If you then def... |
7,395,898 | 7,395,936 | C++ / SDL encapsulation design help | So I am semi-new to C++, and completely new to SDL. Most of my conceptual knowledge of OOP comes from Java and PHP. So bear with me.
I am trying to work out some simple design logic with my program / soon to be side-scroller. My problem lies with trying to make my 'screen' layer (screen = SDL_SetVideoMode(...)) accessi... | Passing Game.screen around is more OO (though it might be better to have a getter function) than having one instance of it that can be accessed from any class, because if you have one global version, you can't have more than one Game.screen at any one time.
However if you know you'll only ever need one in the entire li... |
7,396,509 | 7,396,589 | C++ method template specialization for only one index | I'd like to perform a template specialization for only one index of a class. For example, in the following code I want to create a specialization whenever the first class is int, regardless of what the second class is. Is there a way to implement this?
template <class K, class V>
class myclass {
public:
v... | You can, but you need to specialize the whole class "myclass", not just single method "myfunc". Here is an example:
#include <iostream>
template <typename K, typename V>
class myclass {
public:
void myfunc(K key, V value)
{
std::cout << "non-specialized " << key << "->" << value << std:... |
7,396,649 | 7,397,814 | Recursive member function can't access its own variables | I start with the top node of a tree 5 layers deep, and recursively call getvalue() on each one. Each node is linked to two nodes on the next layer. I'm pretty sure that this is not my issue since I double checked the algorithm on paper. Once I get to layer 3, however, it gives me a segmentation fault. With valgrind, I ... | vector<Node> children;
I have the same opinion as Andrey; that I also don't like the use of vector as child nodes container. If your data structure is a simple binary tree, why not simply use
Node* leftChild;
Node* rightChild;
as the data members of class Node?
Also, please provide the code for the creation of your t... |
7,396,718 | 7,397,001 | C++ window creation / SDL | Simple enough question. Is there a way to achieve 'custom' windows with SDL? By this I mean, the ability to customize the application's frame / GUI / close / minimize buttons etc. Examples would be Steam, AIM/Pidgin/Hamachi. I am new to the language, and if someone could point me in the correct direction I would much a... | With SDL, you can remove the frame by passing in SDL_NOFRAME to SDL_SetVideoMode as one of the flags.
|
7,396,721 | 7,400,947 | Checkerboard w/ openGL glRecti | I have a pretty straightforward question. We are asked to make a checkerboard using glRecti in c++ using visual basic 2010. Here's what I have so far and was wondering if anyone can point me in the right direction.
#include <gl/glut.h>
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white backgrou... | You should try
for (i = 0; i < 8 ; ++i) {
for (j = 0; j < 8; ++j) {
if((i + j)%2 == 0) // if i + j is even
glColor3f( 0.4, 0.2, 0.6);
else
glColor3f( 0.2, 0.3, 0.4);
glRecti(i*size, j*size, (i+1)*size, (j+1)*size); // draw the rectangle
}
}
You should think if... |
7,396,746 | 7,396,785 | How to handle integer overflows with atomic increment and compare-and-swap operations? | I am writing a bit of code that implements an (unsigned) integer counter.
It is used from an arbitrary number of threads.
A thread should get a unique value every time until overflow.
If integer type range is overflown, zero should be returned.
I have at my disposal atomic increment function (returns old value), and a... | You can build everything from compare-and-swap. The general algorithm is
int DoSomeAtomicCalculation()
{
static int value;
int capture, newValue;
do {
capture = value;
newValue = some_function_based_on(capture);
} while (!compare_and_swap(value, capture, newValue));
return newValue;
... |
7,396,846 | 7,396,862 | With a private modifier, why can the member in other objects be accessed directly? | I have the following code:
class A
{
private:
int x;
public:
A()
{
x = 90;
}
A(A a1, A a2)
{
a1.x = 10;
a2.x = 20;
}
int getX()
{
return this->x;
}
};
I know that code might be weird but I don't understand why a1 and a2 can access private data me... | Good question. The point is that protection in C++ is class level, not object level. So a method being invoked on one object can access private members of any other instance of the same class.
This makes sense if you see the role of protection being to allow encapsulation to ensure that the writer of a class can build ... |
7,396,856 | 7,397,384 | luabind 0.9.1 uses stl iterator only show one element | I got a strange problem while used luabind to return a stl::vector::iterator to lua script.
Below is the code:
1) I created two function they are called by lua script:
std::vector<car*> get_car_list()
{
std::vector<car*>* vec = new std::vector<car*>();
vec->push_back(new car("I'm the 1st"));
vec->push_back... | I see two problems:
You use pointers and new like if we were in Java but it's C++. You will have clear memory leaks if you use C++ this way.
Except if you have particular reasons, it should be:
std::vector<car> get_car_list() {
std::vector<car> vec;
vec->push_back( car("I'm the 1st"));
vec->push_back( car(... |
7,397,000 | 7,397,137 | What's a Good Way to Test that Identifiers aren't Being Truncated and Thereby Mixed Up? | In C++ class today, we discussed the maximum possible length of identifiers, and how the compiler will eventually stop treating variables as different, after a certain length. (My professor seems to have implied that really long identifiers are truncated.) I posted another question earlier, hoping to see if the limit i... | I don't think you need to even generate any operations on the variables.
The following code will generate a redefinition error at compilation time;
int name;
int name;
I'd expect you'd get the same error with
int namewithlastsignificantcharacterhere_abc;
int namewithlastsignificantcharacterhere_123;
I'd use a macro s... |
7,397,019 | 7,402,616 | Problem reading from boost basic_streambuf with an istream | I'm having some problems reading from a streambuf which is being filled through an asyc_read(). When stepping through my code in VS i can see that the correct data is in the buffer but when i go to read it with:
std::istream is = std::istream(&buffer_);
unsigned short type;
unsigned short size;
is >> type;
is >> size... | If type remains in its initialized value, it's apparent that is >> type; failed: check the status of the stream (if(is) {...}) to be sure.
And, seeing as you have a transfer_at_least(4), I suspect that you're transferring binary data, not whitespace-separated strings of ASCII characters. If that is the case, use read()... |
7,397,034 | 7,397,045 | Issue with Infite Loop | I have a problem. This code is not giving the results it should. It should out number to large to the console and for some reason it is ignoring the if the statement when doing this. Also, in this program InputNum should remain of the long data type.
#include <iostream>
#include <fstream>
using namespace std;
/*
Func... | CalculateBinary(InputNum) does NOT modify the value of InputNum, so its value would be always the same (300000000) and the while loop never end.
|
7,397,257 | 7,397,592 | Lua and fake Typecast | I'm working with Lua and C++ (using LuaWrapper) and I'm having trouble with something. Let's say I have these classes:
class Bar{...};
class Foo
{
...
std::map<std::string,Bar*> _barlist;
...
Bar* getBar(std::string key)
{
return _barlist[key];
}
}
class BarDerived1 : public Bar{...}
cl... | The purpose of polymorphism, in any language, is to not have to care exactly what type something is. If you give someone, whether Lua or C++, a Bar object, then Bar should have the interfaces that the people need to do whatever they need to do.
That's the purpose of virtual functions. A virtual function defined in Bar ... |
7,397,296 | 7,399,061 | Linking HDF5 library into Visual C++ DLL project: unresolved external symbol __imp__* | I'm building a plug-in with MS Visual C++ 2010 Express, and I would like to include capabilities from the HDF5 library. I have tried both building HDF5 from source with CMake, and installing the precompiled library (HDF5-1.8.7_CMake_x86_shared.zip for VC 2008). For either build directory/method, I've modified my projec... |
Linker > General > Additional Library Directories: you should add the
path to the directory containing the .lib file here
Linker > General > Input: you should add the name of the .lib file here
|
7,397,302 | 7,397,351 | Why can't I link a mixed C/C++ static library that has a C interface using gcc? | I have a mixed C/C++ library.
On the outside it provides a C interface using extern C. Internally there are templates and classes. Creating the library with "ar" posed no problems. The file is called libo-client.a.
However, when linking the .a file using gcc (not g++) I get lots of errors that look like this:
libo-cli... | The simplest way around your problem it is to link with g++; this gets the correct libraries in place.
The problem is that C++ has a lot of requirements that C does not, and does more work before calling main() to ensure that things are properly initialized.
If you insist on linking with the C compiler, at the very lea... |
7,397,390 | 7,397,617 | Does delete [] deallocate memory allocated by pointers to pointers | I have an array of pointers to other objects called Comparable* array (inside a template for a class).
I understand that delete deletes memory referenced by a pointer, and that delete [] deallocates the memory assigned to each pointer in an array.
My question is if I have an array that contains pointers to other object... |
if I have an array that contains pointers to other objects, how do I deallocate the memory referenced by each pointer in the array AND the array itself?
The way you just described :) Loop through the array to delete every object and then delete the array:
for (int i = 0; i < n; ++i)
delete array[i];
delete[] arra... |
7,397,645 | 7,397,678 | Redefining a typedef in derived class? | So after searching a lot for an answer to my question, I finally gave up on my Google skills.
I have an base class Base, and a derived class Derived. I want to override a type in the Base class with one in the Derived class. Here's an example:
class Apple {
public:
Apple() { }
// ...
};
class Orange {
public... | First of all, look at this syntax :
fruit func() override { return Orange(); }
What is override? In C++03, there is no such keyword. It's only in C++11. So make sure that you're using a compiler which knows of this keyword.
Second, in the derived class, fruit is indeed Orange. Redefining the typedef is not a problem.... |
7,397,659 | 7,397,895 | I can't run camshift demo in openCV | I install openCV2.3.1 in VS2010. I can read image in openCV without any error. But when I run camshiftdemo from folder open/samples/cpp. It show this error.
1> All outputs are up-to-date.
1>main.obj : error LNK2019: unresolved external symbol "class cv::RotatedRect __cdecl cv::CamShift(class cv::_InputArray const &,cl... | The CamShift and meanShift methods are part of the video\tracking module so you probably forgot to link the opencv_videoXXX.lib
|
7,397,660 | 7,397,852 | Calling ASM function in C++ | Trying to call ASM function in C++.. regular function
you may ask what type of function this is.. __cdecl, __stdcall, or __thiscall
I think i'm missing something like
push ebp
mov ebp, esp
although i don't think i need this, someone once told me but I forgot so I am stuck at same problem. I usually would attach debug... | firstly, your function is __fastcall (as EDX is used), so this means you can typedef it in C:
typedef void (__fastcall * function_t)(int buffer, int key);
function_t pfTheFunc = (function_t)0x00421520;
you should then notice that the push edx and push ecx are unneeded (they are also volatile registers and thus don't n... |
7,397,768 | 7,397,862 | Choice between vector::resize() and vector::reserve() | I am pre-allocating some memory to my a vector member variable. Below code is minimal part
class A {
vector<string> t_Names;
public:
A () : t_Names(1000) {}
};
Now at some point of time, if the t_Names.size() equals 1000. I am intending to increase the size by 100. Then if it reaches 1100, again increase by 100 a... | The two functions do vastly different things!
The resize() method (and passing argument to constructor is equivalent to that) will insert or delete appropriate number of elements to the vector to make it given size (it has optional second argument to specify their value). It will affect the size(), iteration will go ov... |
7,397,799 | 7,397,932 | C++ Multiple Condition Statements - Merging | I have written a program according to a specification.
The Specification has about 3 types and each type gets handled differently on every single point.
That means more or less for code readability, I have written it like shown below, now my question is, if you have 200 such statements, wouldn't it be worth to merge th... | Basic polymorphic approach:
enum Type { tX, tY, tZ};
struct Data
{
Type type;
int data_;
};
class Processor
{
public:
virtual void fillCustomersBDate(const Data& data) = 0;
virtual void fillCustomersCash(const Data& data) = 0;
};
class XProcessor : public Processor
{
virtual void fillCustome... |
7,397,934 | 7,397,972 | Calling template function within template class | Disclaimer: The following question probably is so easy that I might be shocked seeing the first answer. Furthermore, I want to apologize for any duplicate questions - syntactic problems are not always easy to identify be verbal explanation and thus searching for them is not as easy...
But enough of that. I have a two t... | obj.bar<double>(1,2); // This line is faulty.
The template keyword is required here, as obj is an instance of a type Foo<T> which depends on the template parameter T, and so the above should be written as:
obj.template bar<double>(1,2); //This line is corrected :-)
Read @Johannes's answer here for detail explanation:... |
7,398,038 | 7,632,921 | XP embedded CRT version issue.. LoadLibraryEx failing | I am using a third party dll in my application which is destined to be run on a Windows XP embedded SP1 system.
It runs fine on my dev box however, but when I try to run it on target platform it fails with following event. This event occurs when I call LoadLibraryEx to load the third party DLL.
Event Type: Error
Event... | I found the solution and posting it here for someone struggling with similar problem.
I copied the folders and files related to CRT 80 from my work computer WinSxS directory to target platform and it worked.
I copied directory named "x86_Microsoft.VC80.CRT_1fc8b3b9a1e18e3b_8.0.50727.4053_x-ww_e6967989" which contains C... |
7,398,670 | 7,398,700 | A library to convert svg to images? | I am looking for a library written either in C or C++ which can convert the svg to image formats.
I came across inkscape which converts svg to images. but to use this I must run inkscape as a process and this not the solution I am after.
I need the library to run on both Windows and Linux as well.
I am after a C or C++... | The canonical library to render SVG is librsvg. You may want to check that out.
|
7,398,895 | 7,399,057 | Qt QWebView and passing data from JavaScript | I've got a Qt program where a user can select the location by Google Maps. I'm using a simple HTML file for creating the map and load this file in the QWebView control:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html
... | Yes, extending the window-object is the way to go.
I found a question which explains the process quite nicely: Qt 4.6 Adding objects and sub-objects to QWebView window object (C++ & Javascript)
|
7,398,902 | 7,399,018 | ABI compatibility of interfaces (abstract classes) with other virtual changes | Does the ABI of the view of a class remain stable even if other changes, involving virtuals, are made in the derived class?
That is, say I have an interface InterfaceA (abstract class with many pure virtual functions) and a class DerivedB that inherits from it. I write a library that has a function taking a InterfaceA... | Yes, as long as the name, arguments, and order of virtual functions in InterfaceA does not change, it will stay binary compatible. Note that this allows you to add functions at the end of the class declaration.
(It is possible this is not explicitly guaranteed by the C++ spec, but COM relies on this so the big C++ comp... |
7,398,934 | 7,399,020 | Enumeration type with some same values | Why declaration of two enums type with same values in same block is not allowed in C++?
enum math_students {A,B,C};
enum comp_students {D,E,A}; // illegal
| C++03 enum doesn't have tighter type checking under their scopes. So both math_students::A and comp_students::A can be simply referred as A. That's why they are not allowed in the same scope.
To overcome that you can enclose them in namespace or class.
namespace math_students {
enum { A, B, C };
}
namespace comp_stud... |
7,398,964 | 7,399,473 | Recursive explicit template instantiation to export symbols for a library | In my previous question I asked is recursive explicit template instantiation possible. I saw that it is indeed possible; however, this instantiation turns out to be effective locally only, the symbols of the recursively instantiated template are not exported to the object file and thus do not appear in the (shared) lib... | Seems like a job for Boost.Preprocessor:
#include <boost/preprocessor/repetition/repeat.hpp>
#define INSTANTIATE(_, n, type) template class type<n>;
BOOST_PP_REPEAT(3, INSTANTIATE, Point)
Of course, you can embed this into another macro to make it look better:
#define INSTANTIATE(_, n, type) template class type<n>;
... |
7,399,086 | 7,403,400 | Cleaning up a VC++ 6 project | I'm working with a very old and large VC6++ project and it's all messed up. There are unused files and folders everywhere, copies of folders and it's just a mess to clean it up by hand in its current state.
It will be done eventually, but is there any simple way to check what files and folders are used when it does a c... | VC6 will produce a makefile for you:
http://msdn.microsoft.com/en-us/library/aa233950%28v=vs.60%29.aspx
You can use the generated makefile (and the associated .dep file) as a starting point and edit it down to the list of files that get used in a build.
This will let you see the header files that the project depends ... |
7,399,316 | 7,399,461 | Running method while destroying the object | A few days ago my friend told me about the situation, they had in their project.
Someone decided, that it would be good to destroy the object of NotVerySafeClass in parallel thread (like asynchronously). It was implemented some time ago.
Now they get crashes, because some method is called in main thread, while object i... | No, no and no. This is a fundamental design issue, and it shows a common misconception in thinking about multithreaded situations and race conditions in general.
There is one thing that can happen equally likely, and this is really showing that you need an ownership concept: The function calling thread could call the ... |
7,399,521 | 7,399,977 | Is there a way to safely bind texture using OpenGL in a worker thread of Qt GUI application? | I am currently working on a GUI software project for visualizing 3D scenes using Qt. The GUI allows user to load batches of 3D data files such as .obj with some .mtl support and .stl as well as 2D image files into the scene as SceneObject-class objects which is rendered on a QGLWidget-derived widget.
When I load them i... |
I will also perform binding using OpenGL glBindtexture() immediately after loading each image or texture so that I only need to save texture IDs in each SceneObject instance. When I tried to perform the load in a worker thread, the whole program would just crash.
A OpenGL context may be active in only one thread at a... |
7,399,711 | 7,399,909 | Start new thread without blocking/waiting of main operation | Maybe there is a really simple solution for my problem, but I'm really confused with all the boosts around me.
Here's my problem:
I want to start a task (calculation, file system operations, etc.), raised by a callback system which calls the CallbackReceived function and I want to pass this operation to a thread, typic... | What do you want to do with the result of calculate?
Your main thread is blocked in the .join().
If you want to handle other callbacks, you have to return to the normal execution flow, waiting for another call.
Then you have to ask yourself what do you do with the result of calculate when it's finished. Maybe the threa... |
7,400,127 | 7,401,680 | libCurl. Cancel request while proceed | UPDATED: Problem was not in libcurl. The right way to cancel request if to return from callback non-zero value. I used curl_progress_callback function, and everything works fine.
| What you need to understand is that CURL is a C library. In general, you cannot pass pointers to C++ objects or functions because C does not know anything about C++'s classes and calling convention.
For example, this line is incorrect:
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
CURL setopt CURLOPT_ERROR... |
7,400,697 | 7,403,146 | suggestion of function prototypes in Eclipse | Is there any functionality in Eclipse which would generate empty function implementations by their prototypes in the included headers ?
That is say I create some *.c file and write #include something.h in it, and I want Eclipse to suggest/generate empty functions which prototypes are defined in something.h.
Or at least... | The closest thing available in current Eclipse is the menu option Source/Implement method.
Which is, admittedly, not all that close. See:
http://wiki.eclipse.org/CDT/C_editor_enhancements/Source/header_synchronization
You could also look at an external tool like
http://www.radwin.org/michael/projects/stubgen/
|
7,400,762 | 10,394,480 | What do the time measurements presented near curly braces in Very Sleepy profiler represent? | I'm using Very Sleepy to profile some C++ code, and I notice that in the Source view, where it shows the red line-by-lime time-spent measurements, there are always measurement on the lines that only have the method's open or close curly brace, in some cases these were pretty high compared to the other lines of code in ... | I got an answer to this from Richard Mitton (@grumpydev), the maintainer of Very Sleepy, on twitter: "Most likely the function has been optimized, so the line number isn't matched up exactly to the code any more. i.e. all the time gets lumped at the start, instead of being spread out over the course of the function."
|
7,400,833 | 7,401,065 | php extension how to return a string from a method? | I have in [example.cc] a method :
std::string Car::accelerate (std::string n)
{
cout<<n<<endl;
return n;
}
I would like to call this method from a php extension
I wrote this in my [test_php.cc] extension:
char *strr=NULL;
int strr_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &strr, &strr_len) == ... | Given your recent comment I'll propose this as an (uneducated) answer.
RETURN_STRING() takes a const char* in it's first parameter. That's what you call a "C-String", and there is no automatic conversion from std::string to const char * (at least for the compiler).
What you want to do is pass a const char* as the first... |
7,400,834 | 7,400,855 | Creating a Triangle wave from a Sine wave in C++ | I am having trouble finding out how to form a triangle (not sawtooth) wave from a sine wave.
I understand how to create it for a Square wave:
if( sineValue >= 0 )
value = amp;
else
value = -amp;
But I am not sure how to change this to accommodate for a triangle wave.
| A triangle wave is the integral of a square wave. So you need to integrate (sum) your square wave over time:
if (sineValue >= 0)
{
value += delta;
}
else
{
value -= delta;
}
Note that this can be written more succinctly as:
value += (sineValue >= 0) ? delta : -delta;
|
7,401,172 | 7,401,214 | Printing hexadecimal values in C++ |
Possible Duplicate:
Converting an uint64 into a (full)hex string, C++
I am trying to print the hexadecimal equivalent of an integer in C++,
int value=2;
cout<<hex<<value;
I am getting 2 as output, i want 0x00000002 as output (i.e. with the non significant zeroes),
can someone please help me out with this?
| This is more of a formatting problem. You want to use setw and setfill in addition to hex, since you want a the left padded with 0s and the 0x prefix.
cout << "0x" << setw(8) << setfill('0') << right << hex << value;
|
7,401,306 | 7,401,353 | Equivalent of C++ std::setprecision(20) using printf in C | I want to print doubles in decimal notation with full precision (but without extra zeros at the end of the number). In C++ I can use:
std::setprecision(20);
cout << d; // Here d is a double
What would be the equivalent C code using printf?
| You can use the "%.20g" specifier. g is IMHO usually better than f since it doesn't print trailing zeros, and handles large/small values sensibly (changing to e format).
Also note that with the "g" specifier, the precision (the "20" in this case) specifies the number of significant digits rather than the number of dig... |
7,401,478 | 7,410,840 | GL VBO issues: First and final strip of triangles not being displayed correctly | I'm not new to C++ nor OpenGL however I am new to using VBOs. Until now I've been lazy and just used display lists for mostly everything.
My problem is most likely quite simple but it's annoying! It seems that the first, and final list of triangles are not being displayed properly, in this example I am loading a sphere... | OK, I figured my problem. It's quite silly and embarrassing. WFObject files store the indices like 1st, 2nd, etc., etc., rather than 0th, 1st, etc.
While yes, I loaded in the vertices exactly the same in both my display list and VBO, the difference was that in my DL I was drawing at m_Vertices[m_Vindices[i]-1]
Obviousl... |
7,401,521 | 7,401,764 | Can copy elision occur in catch statements? | Consider an exception class with a copy constructor with side-effects.
Can a compiler skip calling the copy constructor here:
try {
throw ugly_exception();
}
catch(ugly_exception) // ignoring the exception, so I'm not naming it
{ }
What about this:
try {
something_that_throws_ugly_exception();
}
catch(ugly_exc... | Yes, it can be elided both during throwing and catching. For catching it can be elided only when the type specified in the catch clause is the same (save for cv-qualifications) as the type of the exception object. For more formal and detailed description see C++11 12.8/31.
...This elision of copy/move operations, call... |
7,401,829 | 7,405,763 | wxWidgets and X11 issues in Ubuntu? | I'm trying to make a simple Dialog Based GUI using wxWidgets. I am using X11/Xlib.h for image capturing (printscreen). Problems start when I change anything in GUI using wxSmith (e.g. drag and drop new button) because it automatically changes button names to Button1,Button2...
Button1 = new wxButton(this, ID_BUTTON1, _... | Are you changing the var name in the GUI designer, or editing the cpp file directly?
If you edit stuff between //(*Initialize(PanelName) and //*) in the cpp then any changes you make will be wiped out (not just the change to the button name).
If you are looking at the Resources tab (which you should be if you're using ... |
7,401,888 | 7,471,843 | Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times? | When I write the following program and use the GNU C++ compiler, the output is 1 which I think is due to the rotation operation performed by the compiler.
#include <iostream>
int main()
{
int a = 1;
std::cout << (a << 32) << std::endl;
return 0;
}
But logically, as it's said that the bits are lost if the... | This is caused due to a combination of an undefined behaviour in C and the fact that code generated for IA-32 processors has a 5 bit mask applied on the shift count. This means that on IA-32 processors, the range of a shift count is 0-31 only. 1
From The C programming language 2
The result is undefined if the right op... |
7,402,160 | 7,415,007 | referencing mupdf in Qt4 project | I have libfitz.a and libmupdf.a in /usr/local/lib (previously compiled).
then I included the headers:
#include <fitz.h>
#include <mupdf.h>
then I put:
INCLUDEPATH +=/home/pc/sviluppo/mupdf-0.9
INCLUDEPATH +=/home/pc/sviluppo/mupdf-0.9/fitz
INCLUDEPATH +=/home/pc/sviluppo/mupdf-0.9/pdf
LIBS += -L/usr/local/... | This is a C library, and they didn't use extern "C" to allow the headers to be included easily in C++. So you have to do it yourself:
extern "C" {
#include <fitz.h>
#include <mupdf.h>
}
According to mupdf MakeFile, you should put the libraries in that order in your .pro (the more dependent static library shoul... |
7,402,203 | 7,402,255 | What C++ IDE / approach would you recommend me? | I know this question has been asked countless times before, but the other threads appear to be rather old, so I decided to make a new one.
Im starting my bachelor thesis in november and am writing a programm in C++ for that. The program will be available on Linux and Windows (possibly Mac) so ideally Ill just have to r... | If you want to port, make sure your code compiles on all relevant platforms at each milestone. Don't expect to easily retrofit compatibility at the end!
Qt is great. So is CMake, which generates a build environment for various platforms; it's also SVN-friendly.
I generally avoid Mircosoft but Visual Studio has great in... |
7,402,345 | 7,402,605 | Should I use const to make objects thread-safe? | I wrote a class which instances may be accessed by several threads. I used a trick to remember users they have to lock the object before using it. It involves keeping only const instances. When in the need to read or modify sensitive data, other classes should call a method (which is const, thus allowed) to get a non-c... | This is clever, but unfortunately doomed to fail.
The problem, underlined by spraff, is that you protect against reads but not against writes.
Consider the following sequence:
unsigned getAverageSalary(Employee const& e) {
return e.paid() / e.hired_duration();
}
What happens if we increment paid between the two func... |
7,402,347 | 7,402,540 | How do I get the font color from a piece of HTML source code? | I have a piece of HTML source like this:
<FONT color=#5a6571>Beverly Mitchell</FONT> <FONT color=#5a6571>Shawnee Smith</FONT> <FONT color=#5a6571>Glenn Plummer</FONT> <NOBR>more >></NOBR>
I tried to retrieve the "color" value, like this:
MSHTML::IHTMLDocument2Ptr htmDoc1 = NULL;
SAFEARRAY *psaStrings1 = SafeArra... | You shouldn't be getting style on pChElem1 because the color is not part of style in your case. Color is part of Font element.
Instead you must call pChElem1->getAttribute("color" . . .)
This will return #5a6571
The following code is in MFC. But you can easily convert to regular Win32 if you are not using MFC.
COLORREF... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.