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 |
|---|---|---|---|---|
3,193,024 | 3,193,881 | Inheritance problem when binding C++ native methods in Chaiscript | I use this code to validate some properties of a set of Qt objects in ChaiScript:
/// initialize the engine
boost::shared_ptr<chaiscript::ChaiScript> chai;
chai.reset(new chaiscript::ChaiScript());
std::cout << "ChaiScript engine created!!!" << std::endl;
///
/// register elements
//
assert(ui->checkBox);
chai->add(chaiscript::var(ui->checkBox), "checkBox");
///
/// adapt elements
/// QCheckBox
chai->add(chaiscript::fun(&QCheckBox::isTristate), "isTristate");
chai->add(chaiscript::fun(&QCheckBox::isChecked), "isChecked");
/// validate some properties
try
{
chai->eval("print(\"Starting evaluation...\")");
int answer_i = 0;
bool answer_b = false;
//answer_b = chai->eval<bool>("checkBox.isTristate()");
answer_b = chai->eval<bool>("checkBox.isChecked()");
std::cout << "ChaiScript::: " << answer_b << " :: " << answer_i << std::endl;
}
catch(std::exception e)
{
std::cout << "ChaiScript@Exception::: " << e.what() << std::endl;
}
The problem is that the "isTristate()" call works, because this is a native method of QCheckBox. On the other hand, the "isChecked()" call fails, I think because this is an inherited method from the QAbstractButton class.
What am I doing wrong?
| The problem has been solved in the following way:
/// method binding
chai->add(chaiscript::fun<bool (QCheckBox *)>(&QCheckBox::isChecked), "isChecked");
It is necessary to specify that the bound method belongs to the QCheckBox class, in order not to bind the reference to the parent method.
Cheers!!!
|
3,193,201 | 3,193,269 | How does shared_ptr<> safely allow casting to bool? | I was looking into how std::tr1::shared_ptr<> provides the ability to cast to bool. I've got caught out in the past when trying to create a smart pointer that can be casted to bool as the trivial solution, ie
operator bool() {
return m_Ptr!=0;
}
usually ends up being implicitly castable to the pointer type (presumably by type promotion), which is generally undesirable. Both the boost and Microsoft implementations appear to use a trick involving casting to an unspecified_bool_type(). Can anyone explain how this mechanism works and how it prevents implicit casting to the underlying pointer type?
| The technique described in the question is the safe bool idiom.
As of C++11, that idiom is no longer necessary. The modern solution to the problem is to use the explicit keyword on the operator:
explicit operator bool() {
return m_Ptr != nullptr;
}
|
3,193,571 | 3,193,676 | C++ alter private member variable from static member function | I noticed while reading through my code that I have a static member function which alters a private member of its class through a pointer to an instance of said class.
It compiles and functions without issue, but I just wanted to know whether or not it was kosher to edit a private variable in this way, from a member but static function, or if I should be implmenting a public setVar function.
Note that I'm not trying to bypass standard coding practice by editing member variables from a static function - the function is necessarily static so that it can be run as a thread using the POSIX pthread library.
Cheers,
Wyatt
| Yes, this is valid.
Although having a non-static member is better in most cases, static members are sometimes used in cases where you need to pass a function-pointer to an external library, like in your case for the pthread library.
If it makes sense to change this private variable in other situations as well, and if you want to separate your class from the fact that it uses the pthread library, you could split up the class in two:
one class that handles the functionality (like your class now)
one class that handles the interfacing to pthread
The second class will then set the variable in the first class via a public method.
Example: this is probably your original code:
class MyClass
{
public:
static void someMethod(MyClass *);
private:
type myMember;
};
and this is how you could also write it:
class MyClass
{
public:
void setMember(type value) {myMember = value; /* other other logic */}
private:
type myMember;
}
class MyClassPThreadInterface
{
public:
static void someMethod(MyClass *myclass) {myclass->...();}
}
That way, you completely separate your class from the fact that it is being used by the PThread library. It makes it usable in other cases as well (where the static-method is rather pointless) and it is also easy to add another thread-library (e.g. Windows threads) without polluting the original class.
|
3,193,657 | 3,193,677 | What permissions does a file written with fstream have? | Suppose I create a file for writing like this:
std::ofstream my_file("filename", std::ios_base::out | std::ios_base::trunc);
How are the permissions of this file determined? I've had a program running overnight generating files about once a minute - some are 0644 but others are 0660, and there's nothing in my code that should make it change. (I've seen that some implementations allow a third argument to set the file permissions - I'm using gcc 4.1.2 which doesn't appear to support this).
| It depends on the umask.
|
3,194,024 | 3,194,071 | How to preserve formatting for C++ streams? | I have the following code (simplified):
ostringstream oss;
oss << "Text ";
oss << hex << uppercase;
oss.width(8);
oss.fill('0');
oss << var1 << " ";
oss << var2 << " ";
oss << dec << nouppercase;
oss.width(1);
oss << var3 << " another text." << endl;
string result = oss.str();
// work with result...
Where var1, var2 are unsigned int's and var3 is an int. The idea is to create a string where var1 and var2 are formated like a hex number (but without the 0x) and var3 as a regular integer. What i found out that only the first number is correctly formated, the second one is not padded with zeroes:
Text 000AF00C 3B7FF 1 another text.
After a while i found out that setting the width and fill parameters AGAIN fixes this. Is there a way how to avoid specifying these formating rules over and over again for each number? The amount of formatted variables is much higher than 2, this was just a simplified example. Wrapping all this into a function is an option, but i would really like to learn how to preserve the formatting with ostringstream.
| Sorry some settings for stream formatting are called volatile (has nothing to do with the keyword), you have to set it each time. See here for explanation.
It will be best to create your own functions.
|
3,194,119 | 3,194,770 | Function pointers working as closures in C++ | Is there a way in C++ to effectively create a closure which will be a function pointer? I am using the Gnu Scientific Library and I have to create a gsl_function. This function needs to effectively "close" a couple of parameters available when I create it. Is there a nice trick to create a closure so that I don't have to pass all of them as params in the gsl_function structure? If not, should I just pass in a pointer to an array containing these parameters?
EDIT
I have tried to use boost::bind like this:
#include <gsl/gsl_integration.h>
#include <boost/bind.hpp>
#include "bondpricecalculator.h"
#include "functions.h"
double integrand (double xi, double t, double x, void * p) {
Functions *functions = (Functions *) p;
double vx = functions->v(x);
return functions->rho0(x)*exp(vx * xi - 0.5 * vx * vx * t);
}
double BondPriceCalculator::value(double t, double T, double xi)
{
gsl_integration_workspace * w
= gsl_integration_workspace_alloc (10000);
gsl_function F;
F.function = &boost::bind(integrand, xi, t, _1, _2);
F.params = &functions;
double integral_t;
double integral_T;
double error;
int res = gsl_integration_qags(&F, T, 1e+14, 0, 1e-7, 10000, w, &integral_T, &error);
if(res)
{
throw "Error intgrating";
}
int res = gsl_integration_qags(&F, T, 1e+14, 0, 1e-7, 10000, w, &integral_t, &error);
if(res)
{
throw "Error intgrating";
}
return integral_T/integral_t;
}
but I got the following error message:
/home/ga/svn/PhD/inflation/cpp/ioi/bondpricecalculator.cpp:20: error: cannot convert ‘boost::_bi::bind_t<double, double (*)(double, double, double, void*), boost::_bi::list4<boost::_bi::value<double>, boost::_bi::value<double>, boost::arg<1>, boost::arg<2> > >*’ to ‘double (*)(double, void*)’ in assignment
| I found below code at.
http://bytes.com/topic/c/answers/657124-interface-problem
// Use in combination with boost::bind.
template<class F>
static double gslFunctionAdapter( double x, void* p)
{
// Here I do recover the "right" pointer, safer to use static_cast
// than reinterpret_cast.
F* function = static_cast<F*>( p );
return (*function)( x );
}
template<class F>
gsl_function convertToGslFunction( const F& f )
{
gsl_function gslFunction;
const void* p = &f;
assert (p != 0);
gslFunction.function = &gslFunctionAdapter<F>;
// Just to eliminate the const.
gslFunction.params = const_cast<void*>( p );
return gslFunction;
}
and use this like
gslFunction gslF = convertToGslFunction( boost::bind( &Sde::drift, &sde, _1 ) );
|
3,194,120 | 3,194,161 | Does "make" know how to search sub-dirs for include files? | This is a question for experienced C/C++ developpers.
I have zero knowledge of compiling C programs with "make", and need to modify an existing application, ie. change its "config" and "makefile" files.
The .h files that the application needs are not located in a single-level directory, but rather, they are spread in multiple sub-directories.
In order for cc to find all the required include files, can I just add a single "-I" switch to point cc to the top-level directory and expect it to search all sub-dirs recursively, or must I add several "-I" switches to list all the sub-dirs explicitely, eg. -I/usr/src/myapp/includes/1 -I/usr/src/myapp/includes/2, etc.?
Thank you.
| This question appears to be about the C compiler driver, rather than make. Assuming you are using GCC, then you need to list each directory you want searched:
gcc -I/foo -I/foo/bar myprog.c
|
3,194,434 | 3,195,119 | C/C++ Dynamic loading of functions with unknown prototype | I'm in the process of writing a kind of runtime system/interpreter, and one of things that I need to be able to do is call c/c++ functions located in external libraries.
On linux I'm using the dlfcn.h functions to open a library, and call a function located within. The problem is that, when using dlsysm() the function pointer returned need to be cast to an appropriate type before being called so that the function arguments and return type are know, however if I’m calling some arbitrary function in a library then obviously I will not know this prototype at compile time.
So what I’m asking is, is there a way to call a dynamically loaded function and pass it arguments, and retrieve it’s return value without knowing it’s prototype?
So far I’ve come to the conclusion there is not easy way to do this, but some workarounds that I’ve found are:
Ensure all the functions I want to load have the same prototype, and provide some sort mechanism for these functions to retrieve parameters and return values. This is what I am doing currently.
Use inline asm to push the parameters onto the stack, and to read the return value. I really want to steer clear of doing this if possible!
If anyone has any ideas then it would be much appreciated.
Edit:
I have now found exactly what I was looking for:
http://sourceware.org/libffi/
"A Portable Foreign Function Interface Library"
(Although I’ll admit I could have been clearer in the original question!)
| I believe the ruby FFI library achieves what you are asking. It can call functions
in external dynamically linked libraries without specifically linking them in.
http://wiki.github.com/ffi/ffi/
You probably can't use it directly in your scripting language but perhapps the ideas are portable.
--
Brad Phelan
http://xtargets.heroku.com
|
3,194,540 | 3,194,616 | Can scanf/sscanf deal with escaped characters? | int main()
{
char* a = " 'Fools\' day' ";
char* b[64];
sscanf(a, " '%[^']s ", b);
printf ("%s", b);
}
--> puts "Fools" in b
Obviously, I want to have "Fools' day" in b. Can I tell sscanf() not to consider escaped apostrophes as the end of the character sequence?
Thanks!
| No. Those functions just read plain old characters. They don't interpret the contents according to any escaping rules because there's nothing to escape from — quotation marks, apostrophes, and backslashes aren't special in the input string.
You'll have to use something else to parse your string. You can write a little state machine to read the string one character at a time, keeping track of whether the previous character was a backslash. (Don't just scan to the next apostrophe and then look one character backward; if you're allowed to escape backslashes as well as apostrophes, then you could end up re-scanning all the way back to the start of the string to see whether you have an odd or even number of escape characters. Always parse strings forward, not backward.)
|
3,194,705 | 3,194,802 | Setting a pointer to null crashes my C++ program | I have a constructor, that receives a character pointer. If it is empty, I need to set its member variable to NULL, however, the program crashes on exit when I try to.
I have verified that it gets to the line where it sets it to NULL and that is the cause of the crash.
I've tried the following:
val = NULL;
val = 0;
val = "";
Those all cause a crash, however if I used:
val = new Char[1];
val = "o";
it didn't crash.
Is there something that I'm not doing?
Update:
Here is a quick update to my problem.
The destructor I'm using is:
~LField() {
if (val)
delete[] val;
}
If I take out:
if (val)
delete[] val;
then the program doesn't crash on exit with:
val = "";
Here is some more code as requested:
LField(int rowNumVal, int colNumVal, int widthVal, const char *valVal = "", bool canEditVal = true) {
if(strlen(valVal) > 0) {
//doesn't jump in here since valVal is empty
}
else {
val = ""; // this is where I'm trying to set a NULL value
}
}
LField(const LField &clone) {
if (val)
delete[] val;
val = new char[strlen(clone.val)];
strcpy(val, clone.val);
rowNum = clone.rowNum;
colNum = clone.colNum;
width = clone.width;
canEdit = clone.canEdit;
index = clone.index;
}
LField& operator=(const LField &lfieldobj) {
if (this != &lfieldobj) {
if (val)
delete[] val;
val = new char[strlen(lfieldobj.val)];
strcpy(val, lfieldobj.val);
rowNum = lfieldobj.rowNum;
colNum = lfieldobj.colNum;
width = lfieldobj.width;
canEdit = lfieldobj.canEdit;
index = lfieldobj.index;
}
return *this;
}
Modified:
LField(int rowNumVal, int colNumVal, int widthVal, const char *valVal = NULL, bool canEditVal = true) {
if(valVal != NULL) {
}
else {
val = NULL;
}
}
LField(const LField &clone) {
delete[] val;
if (clone.val != NULL) {
val = new char[strlen(clone.val) + 1];
strcpy(val, clone.val);
}
else
val = NULL;
rowNum = clone.rowNum;
colNum = clone.colNum;
width = clone.width;
canEdit = clone.canEdit;
index = clone.index;
}
LField& operator=(const LField &lfieldobj) {
if (this != &lfieldobj) {
delete[] val;
if (lfieldobj.val != NULL) {
val = new char[strlen(lfieldobj.val) + 1];
strcpy(val, lfieldobj.val);
}
else
val = NULL;
rowNum = lfieldobj.rowNum;
colNum = lfieldobj.colNum;
width = lfieldobj.width;
canEdit = lfieldobj.canEdit;
index = lfieldobj.index;
}
return *this;
}
~LField() {
delete[] val;
}
I've updated the code. Now val is either allocated memory with new[] or it is NULL, so there shouldn't be a problem with delete[]. However, it still crashes on exit.
| In the copy constructor you try to delete[] an uninitialized pointer:
LField(const LField &clone) {
//good code here, then...
if (val) //<+ some random address here
delete[] val;//<-undefined behavior
}
just don't do that, skip the whole construct. The copy constructor is invoked on an unitilialized object, there're no resources to "free" yet.
Also you try to delete[] a string literal, that's undefined behavior. Try the following change:
LField(int rowNumVal, int colNumVal, int widthVal, const char *valVal = "", bool canEditVal = true) {
if(strlen(valVal) > 0) {
//doesn't jump in here since valVal is empty
}
else {
val = new char[1];
*val = 0;
}
}
also the following is a buffer overrun:
val = new char[strlen(whatever)]; <-forgot to +1 for the null terminator
strcpy(val, whatever);
also checking for a null pointer before delete[] is unnecessary - delete[] on a null pointer is legal and has no effect.
|
3,194,725 | 3,194,781 | Cross-platform way of constructing an FS path with Qt |
Possible Duplicate:
Qt equivalent of PathAppend?
Short story: does Qt 4 have an analog of Python's os.path.join?
Long story: I need to add a relative path to the application directory, QCoreApplication::applicationDirPath() in the Right Way (TM), so that the code doesn't depend on the file system directory separator character.
Is merely joining QStrings and using "/" as the separator a good solution?
| You can either use "/" directly or use QDir::separator(). But in general use a QDir for this (which translates "/" to the platform specific path separator for you).
|
3,194,730 | 3,263,115 | unordered_map throws bad_alloc in VS10 but not in VS9, is this a bug? | While writing a post about project euler's 14th problem I ran into a difference in behaviour between VC9 and VC10.
The following code runs OK in VC9 but in VC10 std::unordered_map throws a bad_alloc exception.
The strange thing is that if I recover from the exception future allocations will succeed (the size of the container continues to grow). Also if I use boost::unordered_map it works fine in both compilers.
Regarding the actual memory usage, I'm running on a machine with 4GB RAM, (1.7 in use) the VC9 version gets up to ~810MB of memory before completing the task and the VC10 one crashes at ~658MB.
Is this a bug in VC10? I'm running on the same machine what else could cause memory to consistently run out in one version and not in the other when the amount of work done is identical?
<edit>
Some more information: The first time the exception takes place is when calculating 7,718,688 with a stack depth of 1 (no recursion just main->length). After that it seems to happen for each number that is added to the cache. The cache had 16,777,217 elements in it before the exception happened (according to cache.size()). The interesting thing is that even when insert fails the cache size grows by one so it appears that it doesn't supply the strong exception guarantee (in violation of §23.2.1.11).
</edit>
Code follows:
#include <iostream>
#include <unordered_map>
typedef std::unordered_map<_int64, int> cache_type;
_int64 collatz(_int64 i)
{
return (i&1)? i*3+1 : i/2;
}
int length(_int64 n, cache_type& cache)
{
if (n == 1)
return 1;
cache_type::iterator found = cache.find(n);
if (found != cache.end())
return found->second;
int len = length(collatz(n), cache) + 1;
cache.insert(std::make_pair(n, len)); // this sometimes throws
return len;
}
int main(int argc, char** argv)
{
const int limit = 10000000;
cache_type cache;
std::pair<int, int> max = std::make_pair(0, 0);
for (int i = 2; i <= limit; ++i) {
int len = length(i, cache);
if (len > max.second)
max = std::make_pair(i, len);
}
std::cout<< "Number with longest orbit is " << max.first
<< " with a lenght of " << max.second
<< " cache size is " << cache.size() << std::endl;
}
<edit>
Also can anyone reproduce this behaviour, at one time it disappeared (and re-appeared) so there may be something special about my configuration.
</edit>
| It might be incidental, but changing the value of _SECURE_SCL causes the behavoir you describe.
i.e Compiling with:
cl /EHa /MD /D_SECURE_SCL=1 /Ox /c t1.cpp
link /LIBPATH:"c:/Program Files/Microsoft Visual Studio 10.0/VC/lib" /LIBPATH:"C:/Program Files/Microsoft SDKs/Windows/v7.0A/Lib" t1.obj
crashes, but the same commands with _SECURE_SCL=0 runs to completion on my XP 32bit machine. The msdn page for _SECURE_SCL says it's enabled for debug builds, but not release, which might be important if you're building under the IDE.
|
3,195,261 | 3,195,337 | Call a c++ method that returns a string, from c# | Please help,
my c++ function:
extern "C" REGISTRATION_API void calculate(char* msg)
{
//some calculation here
msg = "some text";
}
my c# call:
[DllImport("thecpp.dll")]
static extern void calculate(StringBuilder sMsg);
private void button4_Click(object sender, EventArgs e)
{
StringBuilder msg = new StringBuilder();
calculate(msg);
MessageBox.Show(msg.ToString());
}
No matter what i put in msg, the stringbuilder is always empty? why? whats wrong? any ideas? please share
| You are correct that you should use string for LPCTSTR buffers and StringBuilder for LPTSTR buffers.
But you need 2 changes:
1) Set the capacity on your StringBuilder
2) You should be doing strcpy into that buffer, changing what memory address that variable holds won't do anything as you have it now. You need to change what is at the memory address.
So you want in your C/C++ code:
extern "C" REGISTRATION_API void calculate(LPSTR msg)
{
//Also consider refactoring this function to take in the buffer length
strcpy(msg, "some text");
}
and in C#:
[DllImport("thecpp.dll", CharSet=CharSet.Ansi)]
static extern void calculate(StringBuilder sMsg);
private void button4_Click(object sender, EventArgs e)
{
StringBuilder msg = new StringBuilder(1024);
calculate(msg);
MessageBox.Show(msg.ToString());
}
Note: You really should pass in the length of the buffer that you are passing in to the calculate function as well.
|
3,195,330 | 3,195,356 | C++: Overwrite an element in a new-created array | If I have an array created like this:
MyType *array = new MyType[10];
And I want to overwrite one of the elements, do I have to delete first the old element like this:
delete &array[5];
array[5] = *(new MyType());
Or is this completely wrong and do I have to work with something like "pointers to pointers" to fix this job? If so, how please....
Thanks
| It's an array of values, not of pointers. So you'd just do
array[5] = MyType();
This requires MyType to support the assignment operator.
Incidentally, there's rarely a need for manual array allocation like this in C++. Do away with the new and delete and use std::vector instead:
std::vector<MyType> array(10);
array[5] = MyType();
Note, there's no need to delete anything.
|
3,195,379 | 3,195,427 | VS 2008 : See the elements referred to pointer | This seems to be a rather stupid question, but I create a pointer to an array of doubles :
double* tab = new double[10];
Then I fill the double array, but when I expand the tab pointer in Debug Mode, I only *tab which gives me the value of first element, which is normal. But how do I see the other elements?
thanks
| If you write in the watch window tab,10 you'll see it as if its a 10 element array.
Be careful though because this can also show you stuff beyond the allocated length of the array.
|
3,195,504 | 3,195,536 | drawing rainbow palettes | I have a 8-bit color palette, therefore I am having 256 colors.
The palette is basically an array of [256 * 3] {r, g, b} values, Now I need to draw a color spectrum out of it. So basically I have to select 256 out of total 256*256*256 values possible which would enable me to draw the rainbow as closely as possible.
Similar questions here on SO point to HSV based approach, but I am looking for an RGB implementation coz I have APIs defined that way.
Any help is much appreciated.
| The HSV solution is still correct, because that pretty much captures your problem. A "rainbow" is by definition a series of colors with constant S and V, but varying H.
|
3,195,788 | 3,195,887 | Algorithm for Audio - Video Encryption | I want to perform encryption - decryption of certain audio - video files.
Can anyone suggest me some suitable algorithms in cocoa, objective- c, c, or c++ to accomplish it?
You can suggest me some link and/ or third party software for it.
Thanks,
Miraaj
| Any stream cipher should work for you. I would suggest AES. Numerous FOSS implementations are available.
Here's a quick link that might help: http://iphonedevelopment.blogspot.com/2009/02/strong-encryption-for-cocoa-cocoa-touch.html
|
3,195,973 | 3,196,065 | set_union with multiset containers? | What's the return of the algorithm std:set_union when one or both input containers are multisets with duplicated objects? Do dups get lost?
Let's suppose for example:
multiset<int> ms1;
ms1.insert(1);
ms1.insert(1);
ms1.insert(1);
ms1.insert(2);
ms1.insert(3);
multiset<int> ms2;
ms2.insert(1);
ms2.insert(1);
ms2.insert(2);
ms2.insert(2);
ms2.insert(4);
vector<int> v(10);
set_union( ms1.begin(), ms1.end(), ms2.begin(), ms2.end(), v.begin() );
What would the output be?
| From the standard, 25.3.5:
The semantics of the set operations are generalised to multisets in a standard way by defining union() to contain the maximum number of occurrences of every element, intersection() to contain the minimum, and so on.
So in your example, the result will be (1,1,1,2,2,3,4,0,0,0), since you initialised the vector with length 10.
|
3,196,054 | 3,197,807 | Setting a Texture in a shader's constant buffer in D3D10 | Ok I have a shader compiled up under D3D10.
I am obtaining a shader reflection to get details of all the constants/globals in the shader. However I'm a little confused on something ... how do I set a texture to a constant buffer?
I assume I don't just Map the constant buffer and copy the ID3D10Texture pointer into it ... I assume I use an ID3D10ShaderResourceView but I'm just unsure of how I set it in the constant buffer.
Any help would be much appreciated!
| You don't bind a texture to a constant buffer. You bind textures, via views, to a stage (here GS stage) using method:
void GSSetShaderResources(
[in] UINT StartSlot,
[in] UINT NumViews,
[in] ID3D10ShaderResourceView *ppShaderResourceViews
);
Views and CBs are actually two separate things.
|
3,196,230 | 3,196,298 | file handling routines on Windows | Is it allowed to mix different file handling functions in a one system e.g.
fopen() from cstdio
open() from fstream
CreateFile from Win API ?
I have a large application with a lot of legacy code and it seems that all three methods are used within this code. What are potential risks and side effects ?
| Yes, you can mix all of that together. It all boils down to the CreateFile call in any case.
Of course, you can't pass a file pointer to CloseHandle and expect it to work, nor can you expect a handle opened from CreateFile to work with fclose.
Think of it exactly the same way you think of malloc/free vs new/delete in C++. Perfectly okay to use concurrently so long as you don't mix them.
|
3,196,341 | 3,196,362 | Is there a C# equivalent to C++'s std::set_difference? | If so, what is it?
EDIT: In response to comment below:
var tabulatedOutputErrors = from error in outputErrors
group error by error into errorGroup
select new { error = errorGroup.Key, number = errorGroup.Count() };
var tabulatedInputErrors = from error in inputErrors
group error by error into errorGroup
select new { error = errorGroup.Key, number = errorGroup.Count() };
var problems = tabulatedOutputErrors.Except(tabulatedInputErrors);
You can expand out the counts if you need to.
| LINQ has the Enumerable.Except extension method, which seems to be what you're looking for.
Example:
var list1 = new int[] {1, 3, 5, 7, 9};
var list2 = new int[] {1, 1, 5, 5, 5, 9};
var result = list1.Except(list2); // result = {3, 7}
Alternative:
From .NET 3.5 onwards there also exists the HashSet<T> class (and also the similar SortedSet<T> class in .NET 4.0. This class (or rather the ISet<T> interface in .NET 4.0) has an ExceptWith method which could also do the job.
Example:
var set1 = new HashSet<int>() {1, 3, 5, 7, 9};
var set2 = new HashSet<int>() {1, 1, 5, 5, 5, 9};
set1.ExceptWith(set2); // set1 = {3, 7}
Of course, it depends on the context/usage whether this approach is more desirable. The efficiency benefit (doing the difference operation in-place and using hash codes) in most cases is probably negligible. Either way, take your pick. :)
|
3,196,395 | 3,196,962 | Is boost::interprocess ready for prime time? | I was working on a thread safe queue backed by memory mapped files which utilized boost interprocess fairly heavily. I submitted it for code review and a developer with more years of experience than I have on this planet said he didn't feel that boost::interprocess was "ready for prime time" and that I should just use pthreads directly.
I think that's mostly FUD. I personally think it's beyond ridiculous to go about reimplementing things such as upgradable_named_mutex or boost::interprocess::deque, but I'm curious to know what other people think. I couldn't find any data to back up his claim, but maybe I'm just uninformed or naive. Stackoverflow enlighten me!
| I attempted to use boost::interprocess for a project and came away with mixed feelings. My main misgiving is the design of boost::offset_ptr and how it handles NULL values -- in short, boost::interprocess can make diagnosing NULL pointers mistakes really painful. The issue is that a shared memory segment is mapped somewhere in the middle of the address space of your process, which means that "NULL" offset_ptr's, when dereferenced, will point to a valid memory location, so your application won't segfault. This means that when your application finally does crash it may be long after the mistake is made, making things very tricky to debug.
But it gets worse. The mutexes and conditions that boost:::interprocess uses internally are stored at the beginning of the segment. So if you accidentally write to some_null_offset_ptr->some_member, you will start overwriting the internal machinery of the boost::interprocess segment and get totally weird and hard to understand behavior. Writing code that coordinates multiple processes and dealing with the possible race conditions can be tough on its own, so it was doubly maddening.
I ended up writing my own minimal shared memory library and using the POSIX mprotect system call to make the first page of my shared memory segments unreadable and unwritable, which made NULL bugs appear immediately (you waste a page of memory but such a small sacrifice is worth it unless you're on an embedded system). You could try using boost::interprocess but still manually calling mprotect, but that won't work because boost will expect it can write to that internal information it stores at the beginning of the segment.
Finally, offset_ptr's assume that you are storing pointers within a shared memory segment to other points in the same shared memory segment. If you know that you are going to have multiple shared memory segments (I knew this would be the case because for me because I had one writable segment and 1 read only segment) which will store pointers into one another, offset_ptr's get in your way and you have to do a bunch of manual conversions. In my shared memory library I made a templated SegmentPtr<i> class where SegmentPtr<0> would be pointers into one segment, SegmentPtr<1> would be pointers into another segment, etc. so that they could not be mixed up (you can only do this though if you know the number of segments at compile time).
You need to weigh the cost of implementing everything yourself versus the extra debugging time you're going to spend tracking down NULL errors and potentially mixing up pointers to different segments (the latter isn't necessarily an issue for you). For me it was worth it to implement things myself, but I wasn't making heavy use of the data structures boost::interprocess provides, so it was clearly worth it. If the library is allowed to be open source in the future (not up to me) I'll update with a link but for now don't hold your breath ;p
In regards to your coworker though: I didn't experience any instability or bugs in boost::interprocess itself. I just think its design makes it harder to find bugs in your own code.
|
3,196,464 | 3,196,476 | Pointer to an Element of a Vector | If I have a pointer that is pointing to an element in a vector, say element 2, and then that element gets swapped with element 4 of the same vector. Is the pointer now pointing to element 2, element 4, or neither? Example:
vector a is equal to [1,2,3,4,5]
create pointer that points to the element 2, which is equal to 3 in this case
swap elements 2 and 4
vector a is now [1,2,5,4,3]
where is the vector pointing to?
| You mean, "where is the pointer pointing to?". If that's the case, it'll point to the same location in memory as before which is now occupied by the value 5.
Also, by swapping I assume you meant swapping the values between two locations.
Why?
Simply because your pointer points to a memory location. What's stored there doesn't matter --- it could be a value, or it could be garbage. When you dereference it (to see what the value is) it will return the value stored at that location.
Since you've swapped the values, the value at that location is 5 not 3 hence, the pointer is still pointing to the same location and is unchanged but the value at the location has changed.
Sample Code:
// Create the vector
int a[] = {1,2,3,4,5};
int* ptr = &a[2];
// Display original status
std::cout<<"Original Value: "<<*ptr<<std::endl;
std::cout<<"Address: "<<ptr<<std::endl;
// Swap values
std::swap(a[2],a[4]);
// Check
std::cout<<"New Value: "<<*ptr<<std::endl;
std::cout<<"Address: "<<ptr<<std::endl;
Note:
I've used an array of integers in the example but if by vector you meant std::vector, the same will hold assuming no reallocation has taken place (check out this SO answer).
|
3,196,585 | 3,196,694 | C++: References as constructor arguments, help | I have a base class(Base) whose constructor takes a reference as argument. In my derived class its constructor, I call the superclass-constructor and of course I need to pass a reference as argument. But I have to obtain that argument from a method of which the return type is by value...
I will give a short example:
class Base
{
public:
Base(MyType &obj) { /* do something with the obj */}
};
class Derived : public Base
{
public:
Derived(MyOtherType *otherType) :
Base(otherType->getMyTypeObj()) // <--- Here is the error because (see *)
{
// *
// getMyTypeObj() returns a value and
// the Base constructor wants a reference...
}
};
class MyOtherType
{
public:
MyType getMyTypeObj()
{
MyType obj;
obj.setData( /* blah, blah, blah... Some data */);
return obj; // Return by value to avoid the returned reference goes out of scope.
}
};
How can I solve this problem?
| Change the Base class to:
class Base
{
public:
Base(const MyType &obj) { /* do something with the obj */}
};
Update: If you want to modify obj you cannot obviously have a const reference. In that case you can either:
1)Pass the parameter by value. That will have the overhead for the copy but avoid having to free it explicitly later.
2) Change MyOtherType::getMyTypeObj() to
MyType& MyOtherType::getMyTypeObj()
{
MyType* obj = new MyType();
obj->setData( /* blah, blah, blah... Some data */);
return *obj;
}
In this case, remember to delete the object after you are done with it.
|
3,196,600 | 3,196,826 | Windows Hashed Password | Is there a way to get the hashed value of Windows password for a specific local user? Which Win32 API would that be? I don't want to know what the actual password is, just the hash value of the password.
I'd like to be able to tell which workstations/servers don't have the same password for a specific user.
Please advise, thanks.
| I haven't tried this technique recently, so I'm not sure it still works, but at one time it definitely did, and I'd guess it probably still does.
Call NetUserChangePassword for that user's account on each of the target computers, but do it from an account that does not have the right to change that users password (e.g., another normal user account). When you call this, you have to pass (among other things) the user's old password. Since you're calling it from an account that isn't allowed to change that user's password, this call will always fail.
What you're interested in is the error code when it fails. If what you passed as the old password is recognized by the system (i.e., is the correct password for the account), the call will fail with ERROR_ACCESS_DENIED. If the password you pass is incorrect (i.e., not recognized for that account), it'll fail with ERROR_INVALID_PASSWORD.
|
3,196,968 | 3,197,112 | 3D Graph plotting for C++ | I need to plot my simulation (which I do in a C++ application) for use in a Latex document (so I would prefer some vector output like EPS). My function is of 2 arguments, so I am after a 3D plot, ideally with colouring indicating the function value (similar to what Mathematica does). Could anyone recommend any library?
| Why not use gnuplot? I use it for this sort of thing. If you really need a library, then I'd look at gnuplot++
|
3,196,983 | 3,197,088 | Structure alignment in C++ | struct Vector
{
float x, y, z;
};
func(Vector *vectors) {...}
usage:
load float *coords = load(file);
func(coords);
I have a question about the alignment of structures in C++. I will pass a set of points to the function func(). Is is OK to do it in the way shown above, or is this relying on platform-dependent behavior? (it works at least with my current compiler) Can somebody recommend a good article on the topic?
Or, is it better to directly create a set of points while loading the data from the file?
Thanks
| Structure alignment is implementation-dependent. However, most compilers give you a way of specifying that a structure should be "packed" (that is, arranged in memory with no padding bytes between fields). For example:
struct Vector {
float x;
float y;
float z;
} __attribute__((__packed__));
The above code will cause the gcc compiler to pack the structure in memory, making it easier to dump to a file and read back in later. The exact way to do this may be different for your compiler (details should be in your compiler's manual).
I always list members of packed structures on separate lines in order to be clear about the order in which they should appear. For most compilers this should be equivalent to float x, y, z; but I'm not certain if that is implementation-dependent behavior or not. To be safe, I would use one declaration per line.
If you are reading the data from a file, you need to validate the data before passing it to func. No amount of data alignment enforcement will make up for a lack of input validation.
Edit:
After further reading your code, I understand more what you are trying to do. You have a structure that contains three float values, and you are accessing it with a float* as if it were an array of floats. This is very bad practice. You don't know what kind of padding that your compiler might be using at the beginning or end of your structure. Even with a packed structure, it's not safe to treat the structure like an array. If an array is what you want, then use an array. The safest way is to read the data out of the file, store it into a new object of type struct Vector, and pass that to func. If func is defined to take a struct Vector* as an argument and your compiler is allowing you to pass a float* without griping, then this is indeed implementation-dependent behavior that you should not rely on.
|
3,197,025 | 3,197,123 | End of File(EOF) of Standard input stream (stdin) | Does stdin have any EOF? For example, if I start reading from stdin using fread or read, then will the following loop end?
while ((c = read(0, buffer, BUFSIZ)) > 0) {
.
.
.
}
If the answer to this question is no, then is there any way to add EOF to stdin?
| Speaking about EOF in stdin: when you redirect input from file, e.g.:
program <input.txt
the file already has an EOF, so this is not a problem. In console you can simulate EOF flag. In UNIX systems it is Ctrl+D, in Windows Ctrl+Z. When you type this in the console, program will behave like it has just reached end of input file.
Edit
According to a question asked by OP:
So does it means that stdin don't have EOF and we have to insert them manually using Ctrl+Z or Ctrl+D?
Actually -- yes. One may consider stdin (not redirected, but taken from the console) as infinite file -- no one can tell where does it end. The end of input file, where input ist stdin, must be told literally by Ctrl+D or Ctrl+Z.
|
3,197,028 | 3,238,529 | How to split audio or write demuxer filter in directshow? | I need to split a PCM audio stream with up to 16 channels into several stereo streams.
As I haven't found anything capable of doing that, I'm trying to write my first directshow filter.
Anything capable of splitting the audio would be very welcomed but I'm assuming that I must do it so there's what I've done:
At first, I tried to create a filter based on ITransformFilter. However, it seems that it's made thinking of filters with only one input pin and one output pin. As I need several output pins, I disregarded it, however perhaps it can be adapted more easily than I thought, so any advice is highly appreciated.
Then, I begin basing on IBaseFilter. I managed to do something. I create the necessary output pins when the input pin gets connected, and destroy them when the input gets disconnected. However, when I connect any output pin to an ACM Wrapper (just to test it), the input tries to reconnect, destroying all my output pins.
I tried to just not destroy them, but then I checked the media type of my input pin and it had changed to a stereo stream. I'm not calling QueryAccept from my code.
How could I avoid the reconnection, or what's the right way to do a demuxer filter?
Edit 2010-07-09:
I've come back to ITransformFilter, but I'm creating the necessary pins. However I've encountered the same problem as with IBaseFilter: When I connect my output pin to an ACM Wrapper, the input pins changes its mediatype to 2 channels.
Not sure how to proceed now...
| You can take a look at the DMOSample in the Windows Server 2003 R2 Platform SDK. It is also included in older directx sdk's, but not in newer windows sdk's. You can locate it in Samples\Multimedia\DirectShow\DMO\DMOSample. Here is the documentation of this sample.
I have seen someone create a filter based on this which had a stereo input and two mono outputs. Unfortunately I cannot post the sourcecode.
|
3,197,292 | 3,197,361 | Avoid global variables/methods name clashes when using C headers in C++ | I recently spent some time chasing an annoying little bug and I'm looking for suggestions for those of you who have either encountered the same problem or know the best way to avoid it.
I have a situation where I am developing in C++ and using strerror and as a result I am using something similar to
extern "C" {
#include <string.h>
}
(Same situation for #include <cstring>, btw). Now, there is a function defined in that file as follows: extern char *index (__const char *__s, int __c) This function lead to the fun I had where I originally had a construct similar to:
for (int index = 0; index != condition (); ++index) {
// do something with buffer[index] here
}
log->write ("Final value of index: %d\n", index); // <- Ooops!!!
But instead of getting a compile error I get bogus output. I have my compiler (g++) flags set pretty high and the following did not catch this:
-W -Wall -Wextra -Werror -Wshadow -Wformat -pedantic -ansi
I can also not use an #undef trick like in <cstring> because this is not a macro.
My question is whether or not others have encountered this same problem and what is the best solution to it? Ideally, I'd love to hear about some obscure g++ functionality like -use-the-force-luke=... ;)
Note that I'm not asking how to solve this exact problem; I could just change the variable name. I'm looking for tips on how to avoid this situation in the future.
EDIT:
Due James Curran's reply I think I should clarify a bit. I'm not looking at why this should not happen. I understand that in the absence of local variables the scope space is extended. What I am surprised about is that there is no flag I can set that warns about this. I'd think that -Wshadow would catch it since it catches variable/method shadowing within a class scope, but I digress.
What I am interested in is a way to have a notification that a local name is in conflict with a non-local scope. There is mention that I would have caught this particular bug had I used stream operations instead of variadic calls. True enough, but even the following will not produce warnings/errors with g++ (GCC) 4.1.1 20070105 (Red Hat 4.1.1-51) and the following flags -W -Wall -Wextra -Werror -Wshadow -ansi -pedantic.
#include <iostream>
#include <cstring>
int main () {
int index = 42;
std::cerr << index << std::endl;
return 0;
}
That is curious to me.
| First, it looks like you are using printf style variadic argument list which causes an immediate loss of type safety. You should probably avoid this sort of design in C++.
If you have to do this, then you could consider decorating the function declaration to tell gcc that it is a printf-like function and it will then give you warnings if your argument list doesn't match your format string as it does for the standard *printf functions.
E.g.
void write(const char* f, ...) __attribute__((format (printf, 2, 3)));
|
3,197,293 | 3,210,761 | DSSCL_EXCLUSIVE not giving exclusive audible output. DirectSound | Very simple question. In the MSDN documentation for the DirectSound API they state that when my application is in focus it will be the only audible program. This is exactly what I want to happen, however when setting this flag and playing sound through my application, I can still hear the background music on my computer.
So the question is, why? Is it because the application playing the background music using a different low level API, and thus different mixing buffers? Or is there some other little trick i need to tweak in order to become the only audible application.
I asked a similar/related question here, with no response. But once again if you don't know the answer to the specific DirectSound question, but you know a way of becoming the only audible application with a different API let me know!
Thanks, I'm on Windows XP 32Bit Professional, if it makes a difference.
| A long time ago, the Windows developers realized that allowing one application to have total control of the audio system (whereby muting other apps) was a bad idea. And then they subsequently deprecated many of these "exclusive" and foreground/background mode flags. I believe this behavior change goes all the way back to DirectX 7.1 (WinME) and then formally everywhere on DX 8. This was 10 years ago.
Imagine your video conferencing app becoming muted when you switched the foreground application to an app that ran audio in some sort of exclusive mode. Not being able to reliably hear anyone when switching between apps is not a great experience.
As a matter of fact, prior to DX 8, many popular voice-comm apps for multi-player gaming would continually sniff for the foreground window handle and use that for the call to SetCooperativeLevel such that they wouldn't get muted.
I think it would be interesting to know, "what is that you really want to do?" that makes you assume you need total control of the audio output.
On Vista and higher, there is the WASAPI api for low-level audio. I believe there is a concept of "exclusive" mode but I don't know if trumps other apps using the sound card. YMMV.
|
3,197,375 | 3,197,464 | using variables to decide type of class or namespace | Alright, so i had the bright idea of using namespaces and an if statement to change the outcome of variables, in PHP i imagine i could've used concatenation however c++ doesnt seem to have concatenation as far as i can see so far.
so is there a way to get this code to work?
namespace Blue
{
int seven = 7;
int eight = 8;
}
namespace Red
{
int seven = 1;
int eight = 2;
}
and here is the main cpp file
int choice;
cin >> choice;
if(choice == 1)
{
char A[] = "Blue";
}else if(choice == 2){
char A[] = "Red";
}
cout << A::seven << endl;
cout << A::eight << endl;
| I don't think there is a way to do this, and if there were, it's probably a bad idea. You would normally accomplish this behavior in C++ using polymorphism, e.g.:
class Color {
virtual int seven() = 0;
virtual int eight() = 0;
};
class Blue : public Color {
int seven() { return 7; }
int eight() { return 8; }
};
class Red : public Color {
int seven() { return 1; }
int eight() { return 2; }
};
and then:
int choice;
Color* color;
cin << choice;
if (choice == 1)
color = new Blue;
else
color = new Red;
cout << color->seven() << endl;
cout << color->eight() << endl;
delete color;
|
3,197,434 | 3,197,454 | C++: Initialize a member pointer to null? | I have a class that looks like:
class Foo
{
public:
Foo();
virtual ~Foo();
private:
Odp* bar;
};
I wish to initialize bar to NULL. Is this the best way to do it?
Foo::Foo() : bar(NULL)
{
}
Also, is it necessary that the destructor is virtual? (If that is true, then must the constructor be virtual as well?)
|
I wish to initialize bar to NULL. Is this the best way to do it?
It is the correct way. So, yes.
Also, is it necessary that the destructor is virtual?
No. The destructor only needs to be virtual if you will be inheriting from the Foo class and will be using a Foo pointer to delete those derived classes (although as a general rule of thumb, it should be virtual if there are any other virtual members).
(If that is true, then must the constructor be virtual as well?)
No. Constructors neither need to be virtual, nor can they.
|
3,197,634 | 3,200,109 | risk related to using winPcap in place of socket | What I have read so far, winPcap allows you to bypass OS and bypass application and transport layer processing for TCP and provides direct access to the link layer.
I am planning to use winpcap to do some user application stuff and not just sniffing. I will be receiving and sending critical information using pcap which I am currently doing via sockets.
Does bypassing OS, and according to my understanding application and transport layers on my side, involve any risks?
As a side question the winpcap documentation I have found so far talks about how to programatically implement it but does'nt tell in detail what it is bypassing and how does it do that. Any link to that will be helpful.
Also, I'd like to know if anyone is using winpcap for any purposes other than network sniffing for monitoring reasons and msn.
| Sure, there are plenty of risks:
The OS won't know about your privately-managed TCP connections, so it won't know that the port(s) you've chosen is/are in use. This means that it might try to use the same port for another application's connection, leading to chaos.
The OS won't know about your privately-managed TCP connections, so unless you prevent it from seeing those packets, it will send RST packets to reset the apparently bogus connection.
Your application won't automatically be notified of changes to relevant OS-managed data, configured IP addresses and routing tables. You'll likely have to poll for updates.
Properly implementing the TCP protocol is non-trivial. Most implementations, even very well-used ones, had dormant bugs that weren't found for years. Not all the necessary information is in the RFCs, either; there are places where established practice differs from the documented behaviour, usually for good reason. There's also plenty of code in modern TCP stacks specifically to deal with historical buggy behaviour in other stacks, and replicating all that work isn't simple.
There's a substantial risk of bad interactions with third party network security software installed on the host, which will expect all TCP connections to be made via the OS.
It seems like a support nightmare to me.
|
3,197,647 | 3,197,675 | C++: Where to start when my application crashes at random places? | I'm developing a game and when I do a specific action in the game, it crashes.
So I went debugging and I saw my application crashed at simple C++ statements like if, return, ... Each time when I re-run, it crashes randomly at one of 3 lines and it never succeeds.
line 1:
if (dynamic) { ... } // dynamic is a bool member of my class
line 2:
return m_Fixture; // a line of the Box2D physical engine. m_Fixture is a pointer.
line 3:
return m_Density; // The body of a simple getter for an integer.
I get no errors from the app nor the OS...
Are there hints, tips or tricks to debug more efficient and get known what is going on?
That's why I love Java...
Thanks
| Random crashes like this are usually caused by stack corruption, since these are branching instructions and thus are sensitive to the condition of the stack. These are somewhat hard to track down, but you should run valgrind and examine the call stack on each crash to try and identify common functions that might be the root cause of the error.
|
3,197,681 | 3,199,716 | Length of boost::iostream::basic_array_sink/source | I'm using to do some serialization stuff "as it can be seen here". That worked fine, but I couldn't figure how to get the size of the written buffer.I've searched on boost documentation and apparently there is no way to do this aside of building a sink/source by myself?
Thanks
| boost::iostreams::basic_array_sink models a SinkDevice only, which gives you write-only semantics and no way of telling how many bytes have been written.
OTOH, its sibling boost::iostreams::basic_array models a SeekableDevice allowing to utilize the seek() member function of your stream:
namespace io = boost::iostreams;
char buffer[4096];
io::stream<io::basic_array<char> > source(buffer, buffer_size);
boost::archive::binary_oarchive oa(source);
oa << serializable_object;
// move current stream position to the end, io::seek() returns new position
std::cout << "Bytes written: "
<< io::seek(source, 0, std::ios_base::end)
<< std::endl;
|
3,197,910 | 3,198,014 | Convert Float to Integer Equivalent | I want to convert a floating point user input into its integer equivalent. I could do this by accepting an input string, say "-1.234" and then I could just explicitly convert each character to it's decimal representation. (big endian by the way). So I would just say for the example I gave,
-1.234 = 1|01111111|00111011111001110110110
sign bit = 1 = 128<<31
exponent bits = 01111111 = 127<<23
mantissa bits = 00111011111001110110110 = 1962934
decimal equivalent = 1962934 + 127<<23 + 128<<31
This is easy enough but unwieldy. Is there a better way to do this? Maybe some sort of type casting I can do?
| float a = -1.234;
int b = *(int*)&a;
Also, in C++ there's this conversion operator that doesn't do any checks, reinterpret_cast. It's probably better here.
int b = *reinterpret_cast<int*>(&a);
|
3,197,913 | 3,197,919 | Size of #define values | If a value is defined as
#define M_40 40
Is the size the same as a short (2 bytes) or is it as a char (1 byte) or int (4 bytes)?
Is the size dependent on whether you are 32-bit or 64-bit?
| #define has no size as it's not a type but a plain text substitution into your C++ code. #define is a preprocessing directive and it runs before your code even begins to be compiled .
The size in C++ code after substitution is whatever the size is of what C++ expression or code you have there. For example if you suffix with L like 102L then it is seen a long, otherwise with no suffix, just an int. So 4 bytes on x86 and x64 probably, but this is compiler dependent.
Perhaps the C++ standard's Integer literal section will clear it up for you (Section 2.13.1-2 of the C++03 standard):
The type of an integer literal depends
on its form, value, and suffix. If it
is decimal and has no suffix, it has
the first of these types in which its
value can be represented: int, long
int; if the value cannot be
represented as a long int, the
behavior is undefined. If it is octal
or hexadecimal and has no suffix, it
has the first of these types in which
its value can be represented: int,
unsigned int, long int, unsigned long
int. If it is suffixed by u or U, its
type is the first of these types in
which its value can be represented:
unsigned int, unsigned long int. If it
is suffixed by l or L, its type is the
first of these types in which its
value can be represented: long int,
unsigned long int. If it is suffixed
by ul, lu, uL, Lu, Ul, lU, UL, or LU,
its type is unsigned long int
|
3,197,928 | 3,198,033 | Are empty initializers preferred for default initializing integral members? | I just read a comment by GMan that
class A
{
public:
A() :
m_ptr() // m_ptr is implicitly initialized to NULL
{ }
};
should be preferred over
class A
{
public:
A() :
m_ptr(NULL) // m_ptr is explicitly initialized to NULL
{ }
};
Notice the lack of NULL in the first example.
Is GMan right? This might kinda subjective, so "Do you prefer empty initializers for default initialization?" might be more appropriate.
Also if you prefer empty initializers, do does this apply to other integral members?
class B
{
public:
B() :
m_count(),
m_elapsed_secs()
{}
private:
std::size_t m_count;
float m_elapsed_secs; //the elapsed time since instantiation
};
Of course, please defend your view point with a description of why one should be preferred over the other.
| I prefer the explicitness. As some of the wrong answers to this question have demonstrated, it's not obvious to everyone that, say, int() and int(0) are equivalent.
I suppose not supplying an explicit value has the advantage that you won't need to revisit the initialization list if you ever change the type.
|
3,197,953 | 3,198,015 | When is the const operator[] called and when is the non-const operator[] called? | I have two very different behaviors for reads and writes. In the event of reads, I want to copy a buffer of a rather hard to extract data structure. On writes, I will just write unbuffered to the structure.
Up to now, I have been using operator[] to do access, so for the sake of polymorphism I'd like to continue doing so.
So my question is this: When a access is made, which version is called? My notion is that the const is called for reads, and the non-const for writes. In that case, this is a simple thing to implement. Otherwise, it may be more tricky.
| To accomplish what you want, you generally need to have operator[] return a proxy, and overload operator= and operator T (where T is the original type) for that proxy type. Then you can use operator T to handle reads, and operator = to handle writes.
Edit: the basic idea of a proxy is pretty simple: you return an instance of an object that acts in place of the original object. For the moment, this is going to have really trivial semantics (just read and write a char at a specified index in a vector); in your case, the logic inside of the operator= and (especially) operator T will apparently be more complex, but that has little or no effect on the basic structure.
#include <vector>
class X {
std::vector<char> raw_data;
class proxy {
X &parent;
int index;
public:
proxy(X &x, int i) : parent(x), index(i) {}
operator char() const { return parent.raw_data[index]; }
proxy &operator=(char d) {
parent.raw_data[index] = d;
return *this;
}
};
public:
X() : raw_data(10) {}
proxy operator[](int i) { return proxy(*this, i); }
};
#ifdef TEST
#include <iostream>
int main() {
X x;
for (int i=0; i<10; i++)
x[i] = 'A' + i;
for (int i=0; i<10; i++)
std::cout << x[i] << "\n";
return 0;
}
#endif
|
3,198,031 | 3,198,143 | Float to String Arduino Compile Error | I'm using this library to convert a float to a string: http://www.arduino.cc/playground/Main/FloatToString?action=sourceblock&ref=1 .
This is the snippet of code, where printing out flt looks like "29.37":
float flt = tempSensor.getTemperature();
char buffer[25];
char str[20];
Serial.print(floatToString(str, flt, 2, 10));
This should work out of the box, but doesn't - what did I do wring? These are my compile errors:
.../floatToString.h:11: error: expected primary-expression before ',' token
.../floatToString.h: In function 'char* floatToString(char*, float, int, int, bool)':
.../floatToString.h:11: error: default argument missing for parameter 5 of 'char* floatToString(char*, float, int, int, bool)'
.../floatToString.h:73: error: 'itoa' was not declared in this scope
.../floatToString.h:89: error: 'itoa' was not declared in this scope
| In C++ only all last parameters are allowed to have a default value:
BAD rightjustify MUST have a default value:
char * floatToString(char * outstr, float value, int places,
int minwidth=0, bool rightjustify) {
OK: no default values, last or two last parameters have default values
char * floatToString(char * outstr, float value, int places,
int minwidth, bool rightjustify) {
char * floatToString(char * outstr, float value, int places,
int minwidth, bool rightjustify=false) {
char * floatToString(char * outstr, float value, int places,
int minwidth=0, bool rightjustify=false) {
Check your header, I guess the one you linked is not the one you currently use.
There is another pointer to an issue: ito is unknown to the compiler. It should be in cstdlib, so an #include <cstdlib> is missing, I would put it in the header, because it depends on it.
|
3,198,107 | 3,198,251 | C++: Difficulty with removing an item from a vector | I'm trying to remove an element from a vector.
vector<Foo> vecFoo;
Foo f1;
Foo f2;
Foo f3;
vecFoo.push_back(f1);
vecFoo.push_back(f2);
vecFoo.push_back(f3);
Foo* pF1 = &f1;
vecFoo.erase(std::remove(vecFoo.begin(), vecFoo.end(), *pF1), vecFoo.end());
That last line produces a huge amount of C2784 errors. What am I doing wrong?
(Yes, this example is bit contrived, but the essence is that I've got a pointer to an element in the vector, and I want to remove that element.)
| Are you missing the comparison operator?
class Foo
{
public:
bool operator==(Foo const& rhs) const { return true;}
... Other stuff
};
|
3,198,249 | 3,198,376 | Sharing static members between template instantiations? (impossible?) | I am doing something that is probably silly, but it would be nice if it worked.
I am attempting to specialize types in a way that I need my own lookup structure that is essentially global (but ideally encapsulated as a class variable), but I want the objects to be type safe, so they are parameterized.
Consequently, I have, essentially
template<class T, int N>
class SpecialArray
{
//...
private:
static map<string, internal_t> lookupTable
}
and for whatever reason, I didn't think until such time as I went to initialize lookupTable
that when I say
template <class T, int N>
SpecialArray<T,N>::lookupTable;
there are going to be many different lookupTables running around attached to the various instantiations of SpecialArray.
I suspect it may just be a pipe dream and that the correct answer is just making it a separate global singleton object, but is there anyway to make it such that there is just one lookupTable for all the SpecialArrays?
Like, in the C++ in my mind (which is not real C++), this would go something like
template <class T, int N>
SpecialArray<*,*>::lookupTable;
... but sadly GCC does not compile the C++ in my mind
Is there any actual way to get what I want (somewhere in C++0x-land or something)? I am likely to run into this problem also with some static methods that manipulate this lookup table (which does not keep track of types or Ns).
... sorry if that didn't make any sense.
Thanks in advance for any help or sympathy you can render.
| You could add a non-templated base class and move lookupTable into that class:
class Base
{
protected:
static map<string, internal_t> lookupTable
};
template<class T, int N>
class SpecialArray : Base
{
//...
};
|
3,198,302 | 3,198,323 | C++ MySQL and multithreading - 1 DB connection per user? | Is in multithreaded application suitable to have 1 connection per 1 connected client? To me it seems ineffective but if there is not connection pooling, how it could be done when one wants to let each connection communicate with DB?
Thanks
| If you decide to share a connection amongst threads, you need to be sure that one thread completely finishes with the connection before another uses it (use a mutex, semaphore, or critical section to protect the connections). Alternately, you could write your own connection pool. This is not as hard as it sounds ... make 10 connections (or however big your pool needs to be) on startup and allocate/deallocate them on demand. Again protecting with mutex/cs/sema.
|
3,198,521 | 3,198,583 | What to do with template typenames for optional arguments? | First of all, the code:
template<typename Func, typename Func2>
void ForEachField(Func normalHandler, Func2 arrayHandler = NULL, bool skipUnknowns = true)
{
for(int i = 0; i < mFields.size(); ++i)
{
Field *f = mFields[i];
if(skipUnknowns && f->IsUnknown())
continue;
if(f->GetCount() == 1 || !arrayHandler)
normalHandler(f);
else
arrayHandler(f);
}
}
And an example of usage:
df->ForEachField(
[&](Field *field) { f << "\t" << format("public $%s;\n") % field->GetName(); },
[&](Field *field) { f << "\t" << format("public $%s;\n") % field->GetName() % field->GetSize(); }
); // Works
df->ForEachField(
[&](Field *field) { WriteLine(f, format("\t\t'%s' => array('type' => '%s'),") % field->GetName() % field->GetTypeInfo()->Name);
}); // Doesn't work
The second call doesn't work because it says:
OutputPhp.cpp(27): error C2783: 'void
DataFile::ForEachField(Func,Func2,bool)'
: could not deduce template argument
for 'Func2'
see declaration of 'DataFile::ForEachField'
Is there any way I can make the second parameter optional, while still using templates, and while not having to manually specify the second template argument?
| You could add an overload for ForEachField:
template<typename Func>
void ForEachField (Func normalHandler)
{
ForEachField<Func, void *>(normalHandler, NULL, true);
}
|
3,198,569 | 3,198,613 | Reverse doubly-link list in C++ | I've been trying to figure out how to reverse the order of a doubly-linked list, but for some reason, in my function void reverse() runs while loop once and then crashes for some reason. To answer some questions ahead, I'm self-teaching myself with my brothers help. This isn't all of the code, but I have a display() function which prints all nodes chronologically from start_ptr and a switch which activates certain functions like
case 1 : add_end(); break;
case 2 : add_begin(); break;
case 3 : add_index(); break;
case 4 : del_end(); break;
case 5 : del_begin(); break;
case 6 : reverse(); break;
This is the geist of my code:
#include <iostream>
using namespace std;
struct node
{
char name[20];
char profession[20];
int age;
node *nxt;
node *prv;
};
node *start_ptr = NULL;
void pswap (node *pa, node *pb)
{
node temp = *pa;
*pa = *pb;
*pb = temp;
return;
}
void reverse()
{
if(start_ptr==NULL)
{
cout << "Can't do anything" << endl;
}
else if(start_ptr->nxt==NULL)
{
return;
}
else
{
node *current = start_ptr;
node *nextone = start_ptr;
nextone=nextone->nxt->nxt;
current=current->nxt;
start_ptr->prv=start_ptr->nxt;
start_ptr->nxt=NULL;
//nextone=nextone->nxt;
while(nextone->nxt!= NULL)
{
pswap(current->nxt, current->prv);
current=nextone;
nextone=nextone->nxt;
}
start_ptr=nextone;
}
}
| Try this:
node *ptr = start_ptr;
while (ptr != NULL) {
node *tmp = ptr->nxt;
ptr->nxt = ptr->prv;
ptr->prv = tmp;
if (tmp == NULL) {
end_ptr = start_ptr;
start_ptr = ptr;
}
ptr = tmp;
}
|
3,198,750 | 3,198,775 | new types may not be defined in a return type - C++ | I am confused I think on C++ class structure.
I have a .h called FxMathFunctions.h and a .cpp called FxMathFunctions.cpp
the .h starts like:
class FxMathFunctions
{
public:
FxMathFunctions();
~FxMathFunctions();
and in the .cpp
I have:
#include "FxBasicTypes.h"
#include "FxMathFunctions.h"
FxMathFunctions::FxMathFunctions() {}
FxMathFunctions::~FxMathFunctions() {}
I am getting errors like:
error: new types may not be defined in a return type
error: return type specification for constructor invalid
This must be something to do with definition someplace, but I just dont see where this might occur.
| What does your .h file end with? I'm guessing that the end of your class defnition does not have a ";". The class is being interpreted as the return type of the first function in your cpp file.
|
3,198,904 | 3,202,333 | D3D10 HLSL: How do I bind a texture to a global Texture2D via reflection? | Ok so assuming I have, somewhere in my shader, a statement as follows (Note I am enabling legacy support to share shaders between DX9 and DX10):
Texture2D DiffuseMap;
I can compile up the shader with no problems but I'm at a slight loss as to how I bind a ShaderResourceView to "DiffuseMap". When I "Reflect" the shader I rather assumed it would turn up amongst the variable in a constant buffer. It doesn't. In fact I can't seem to identify it anywhere. So how do I know what texture "stage" (to use the DX9 term) that I should bind the ShaderResourceView too?
Edit: I've discovered I can identify the sampler name by using "GetResourceBindingDesc". I'm not sure that helps me at all though :(
Edit2: Equally I hadn't noticed that its the same under DX9 as well ... ie I can only get the sampler.
Edit3: My Texture2D and Sampler look like this:
Texture2D DiffuseMap : DiffuseTexture;
sampler DiffuseSampler = sampler_state
{
Texture = (DiffuseMap);
MinFilter = Linear;
MaxFilter = Linear;
};
Now in the effect frame work I could get the Texture2D by the semantic "DiffuseTexture". I could then set a ResourceView(D3D10)/Texture(D3D9) to the Texture2D. Alas there doesn't seem to be any way to handle "semantics" using bog standard shaders (It'd be great to know how D3D does it but studying the D3D11 effect framework has got me nowhere thus far. It seems to be reading it out of the binary, ie compiled, data and I can only see "DiffuseSampler" in there myself).
| Hmm let me rephrase that. On the C++ side you have a bunch of loaded textures and associated SRVs. Now you want to set a shader (that comes from DX9) and without looking at how the shader is written, bind SRVs (diffuse to diffuse slot, specular, normal maps—you name it). Right?
Then I think as you said that you best bet is using GetResourceBindingDesc:
HRESULT GetResourceBindingDesc(
[in] UINT ResourceIndex,
[in] D3D10_SHADER_INPUT_BIND_DESC *pDesc
);
I think you have to iterate each ResourceIndex (starting at 0, then 1, 2 etc), if HRESULT is S_OK then you have pDesc.BindPoint that will represent the position of associated SRV in ppShaderResourceViews array of a *SetShaderResources call. And pDesc.Name (like "DiffuseMap") gives you the association information.
|
3,198,965 | 3,198,992 | How to call execute command line in C++ | For example, I have a script ./helloworld.sh
I would like to call it in C++, how do I do that? Which library can be used?
| try
system("./helloworld.sh");
|
3,199,067 | 3,264,887 | C++ catching dangling reference | Suppose the following piece of code
struct S {
S(int & value): value_(value) {}
int & value_;
};
S function() {
int value = 0;
return S(value); // implicitly returning reference to local value
}
compiler does not produce warning (-Wall), this error can be hard to catch.
What tools are out there to help catch such problems
| There are runtime based solutions which instrument the code to check invalid pointer accesses. I've only used mudflap so far (which is integrated in GCC since version 4.0). mudflap tries to track each pointer (and reference) in the code and checks each access if the pointer/reference actually points to an alive object of its base type. Here is an example:
#include <stdio.h>
struct S {
S(int & value): value_(value) {}
int & value_;
};
S function() {
int value = 0;
return S(value); // implicitly returning reference to local value
}
int main()
{
S x=function();
printf("%s\n",x.value_); //<-oh noes!
}
Compile this with mudflap enabled:
g++ -fmudflap s.cc -lmudflap
and running gives:
$ ./a.out
*******
mudflap violation 1 (check/read): time=1279282951.939061 ptr=0x7fff141aeb8c size=4
pc=0x7f53f4047391 location=`s.cc:14:24 (main)'
/opt/gcc-4.5.0/lib64/libmudflap.so.0(__mf_check+0x41) [0x7f53f4047391]
./a.out(main+0x7f) [0x400c06]
/lib64/libc.so.6(__libc_start_main+0xfd) [0x7f53f358aa7d]
Nearby object 1: checked region begins 332B before and ends 329B before
mudflap object 0x703430: name=`argv[]'
bounds=[0x7fff141aecd8,0x7fff141aece7] size=16 area=static check=0r/0w liveness=0
alloc time=1279282951.939012 pc=0x7f53f4046791
Nearby object 2: checked region begins 348B before and ends 345B before
mudflap object 0x708530: name=`environ[]'
bounds=[0x7fff141aece8,0x7fff141af03f] size=856 area=static check=0r/0w liveness=0
alloc time=1279282951.939049 pc=0x7f53f4046791
Nearby object 3: checked region begins 0B into and ends 3B into
mudflap dead object 0x7089e0: name=`s.cc:8:9 (function) int value'
bounds=[0x7fff141aeb8c,0x7fff141aeb8f] size=4 area=stack check=0r/0w liveness=0
alloc time=1279282951.939053 pc=0x7f53f4046791
dealloc time=1279282951.939059 pc=0x7f53f4046346
number of nearby objects: 3
Segmentation fault
A couple of points to consider:
mudflap can be fine tuned in what exactly it should check and do. read http://gcc.gnu.org/wiki/Mudflap_Pointer_Debugging for details.
The default behaviour is to raise a SIGSEGV on a violation, this means you can find the violation in your debugger.
mudflap can be a bitch, in particular when your are interacting with libraries that are not compiled with mudflap support.
It wont't bark on the place where the dangling reference is created (return S(value)), only when the reference is dereferenced. If you need this, then you'll need a static analysis tool.
P.S. one thing to consider was, to add a NON-PORTABLE check to the copy constructor of S(), which asserts that value_ is not bound to an integer with a shorter life span (for example, if *this is located on an "older" slot of the stack that the integer it is bound to). This is higly-machine specific and possibly tricky to get right of course, but should be OK as long it's only for debugging.
|
3,199,139 | 3,199,155 | Nested NameSpaces in C++ | I am confused what to do when having nested namespaces and declarations of objects.
I am porting some code that links against a static library that has a few namespaces.
Example of what I am talking about:
namespace ABC {
namespace XYZ {
//STUFF
}
}
In code what do I do to declare an object that is in namespace XYZ?
if I try:
XYZ::ClassA myobject;
or:
ABC::XYZ::ClassA myobject;
or:
ABC::ClassA myobject;
I get
does not name a type
errors, even though ClassA definitely exists.
What is proper here?
| It depends on the namespace you already are:
If you're in no namespace or another, unrelated namespace, then you have to specify to whole path ABC::XYZ::ClassA.
If you're in ABC you can skip the ABC and just write XYZ::ClassA.
Also, worth mentioning that if you want to refer to a function which is not in a namespace (or the "root" namespace), you can prefix it by :::
Example:
int foo() { return 1; }
namespace ABC
{
double foo() { return 2.0; }
void bar()
{
foo(); //calls the double version
::foo(); //calls the int version
}
}
|
3,199,429 | 3,199,441 | Accessing an enum in a namespace | In a header I have a setup like this
namespace NS {
typedef enum { GOOD, BAD, UGLY }enum_thing;
class Thing {
void thing(enum_thing elem);
}
}
and of course another cpp file that goes along with that header. Then I have a thread cpp file that contains main(). In this cpp file I use that enum to pass to the method thing().
using namespace NS;
int main() {
Thing t();
t.thing(BAD);
}
and of course I get other errors from G++ saying BAD was not declared. Any help on how I could overcome this error?
| Can you avoid using a typedef? Just do:
enum Foobar {good, bad, hello};
|
3,199,494 | 3,199,508 | Create a function pointer which takes a function pointer as an argument | How to create a function pointer which takes a function pointer as an argument (c++)???
i have this code
#include <iostream>
using namespace std;
int kvadrat (int a)
{
return a*a;
}
int kub (int a)
{
return a*a*a;
}
void centralna (int a, int (*pokfunk) (int))
{
int rezultat=(*pokfunk) (a);
cout<<rezultat<<endl;
}
void main ()
{
int a;
cout<<"unesite broj"<<endl;
cin>>a;
int (*pokfunk) (int) = 0;
if (a<10)
pokfunk=&kub;
if (a>=10)
pokfunk=&kvadrat;
void (*cent) (int, int*)=¢ralna; // here i have to create a pointer to the function "centralna" and call the function by its pointer
system ("pause");
}
| You need to use the function pointer type as the type of the parameter:
void (*cent) (int, int (*)(int)) = ¢ralna
|
3,199,735 | 3,199,763 | C++ timeout on getline | I need all of my threads to check periodically that they should still be running, so that they can self-terminate when the program ends. For all but one of them, this is just a matter of checking a state variable, but the last one is a user-interaction thread, and its loop will wait indefinitely on user input, only checking the state variable when the user inputs an instruction. At this point the program fails anyway since the class can't operate properly when it's not running. Ideally, though, I'd like not to get to this point.
I'm thinking that the best solution, if possible, is a timeout on the getline, but in the event that it's not possible or a good option, I'm open to any option which will allow the thread to terminate neatly.
As an aside, I see a lot of mentions of std::getline. getline seems to work whether I use the namespace or not. Is one an alias of the other, and which is the proper one to use?
| There is no (standard) way to set a timeout on std::getline. In particular, the C++ standard library does not know the existence of threads
To answer your second question, the standards-compliant version of std::getline is the one in the namespace.
|
3,199,747 | 3,199,916 | How can I set up a CBT hook on a Win32 console window? | I've been trying to set up a CBT hook for my C++ Console application with the following code:
...includes...
typedef struct _HOOKDATA
{
int type;
HOOKPROC hookproc;
HHOOK hhook;
}_HOOKDATA;
_HOOKDATA hookdata;
//CBT
LRESULT CALLBACK CBTProc(int code, WPARAM wParam, LPARAM lParam)
{
//do not proccess message
if(code < 0)
{
cout<<"code less than 0"<<endl;
return CallNextHookEx(hookdata.hhook,code,wParam,lParam);
}
switch(code)
{
case HCBT_ACTIVATE:
break;
case HCBT_CREATEWND:
cout<<"CREATEWND"<<endl;
break;
case HCBT_MINMAX:
cout<<"MINMAX"<<endl;
break;
default: //unknown
cout<<"DEFAULT"<<endl;
break;
}
return CallNextHookEx(hookdata.hhook, code, wParam, lParam);
}
int main()
{
hookdata.type = WH_CBT;
hookdata.hookproc = CBTProc;
hookdata.hhook = ::SetWindowsHookEx(hookdata.type, CBTProc,
GetModuleHandle( 0 ), GetCurrentThreadId());
if(hookdata.hhook == NULL)
{
cout<<"FAIL"<<endl;
system("pause");
}
system("pause");
return 0;
}
The program seems to be working because there is not compile errors nor run time errors. Also I do not get a 'FAIL' message stated in the main() function meaning SetWindowHookEx is working OK. However, I don't get any of the messages stated in the CBTProc function; not even the 'DEFAULT' message. Can anyone pin-point what is the logic error in the code?
Thanks.
| The problem is that SetWindowHookEx is based upon the Win32 message handling model. Console windows are children of the Kernel itself and do not create their own message pumps or windows.
AFAIK doing what you want directly is not possible.
|
3,199,761 | 3,199,817 | Define BIT0, BIT1, BIT2, etc Without #define | Is it possible in C++ to define BIT0, BIT1, BIT2 in another way in C++ without using #define?
#define BIT0 0x00000001
#define BIT1 0x00000002
#define BIT2 0x00000004
I then take the same thing and make states out of those bits:
#define MOTOR_UP BIT0
#define MOTOR_DOWN BIT1
Note: I am using 32 bits only, not 64 bits. I am also using a setBit(flagVariable, BIT) (consequently a clrBit macro to do the opposite) macro to set the bits then compare whether the bit is set using the bitwise operator such as
if (flagVariable & MOTOR_UP) {
// do something
clrBit(flagVariable, MOTOR_UP);
}
Is there a type in C++ that already contains these bit masks?
| How about:
enum Bits
{
BIT0 = 0x00000001,
BIT1 = 0x00000004,
BIT2 = 0x00000008,
MOTOR_UP = BIT0,
MOTOR_DOWN = BIT1
};
|
3,199,839 | 3,199,856 | Fastest way of doing transformations (Move, Rotate, Scale) | I was looking at this vector drawing application called Creative Docs .Net . I noticed that I can have hundreds of shapes and moving, rotating and scaling do not lag at all. Given that all verticies must be modified, how do applications generally do these transformations as quickly as possible?
Thanks
| One typical way to do it is to apply a 3x3 (or 3x2, or 2x3) affine transformation matrix to the coordinates, which can describe things like position, rotation, scale and shear.
If you use OpenGL or Direct3D you can use the graphics hardware to do the actual transformations for you.
If you do it in software, rasteration is probably going to be the bottleneck, not transforming the vertices.
|
3,199,892 | 3,199,949 | Determining wether a class has a certain member? |
Possible Duplicate:
Possible for C++ template to check for a function’s existence?
I am trying to determine wether a type has a certain member. This is what i tried:
template <typename T,typename U=void>
class HasX
{
public:
static const bool Result=false;
};
template <typename T>
class HasX<T,typename enable_if_c<(sizeof(&T::X)>0)>::type>
{
public:
static const bool Result=true;
};
struct A
{
int X();
};
struct B
{
int Y();
};
int main()
{
cout<<HasX<A>::Result<<endl; // 1
cout<<HasX<B>::Result<<endl; // 0
}
It actually compiles and works on GCC, but VC gives error C2070: 'overloaded-function': illegal sizeof operand at the point of instanciation.
Is there something wrong with the code, and are there other ways to do this?
| There is indeed:
typedef char (&no_tag)[1];
typedef char (&yes_tag)[2];
template < typename T, void (T::*)() > struct ptmf_helper {};
template< typename T > no_tag has_member_foo_helper(...);
template< typename T >
yes_tag has_member_foo_helper(ptmf_helper<T, &T::foo>* p);
template< typename T >
struct has_member_foo
{
BOOST_STATIC_CONSTANT(bool
, value = sizeof(has_member_foo_helper<T>(0)) == sizeof(yes_tag)
);
};
struct my {};
struct her { void foo(); };
int main()
{
BOOST_STATIC_ASSERT(!has_member_foo<my>::value);
BOOST_STATIC_ASSERT(has_member_foo<her>::value);
return 0;
}
Copy-pasted from here.
Edit: Update the code, which is compliant AFAIK. Also note that you have to know the arguments of the return type of the method you're checking for.
|
3,199,995 | 3,200,128 | Synchronizing access to a return value | Consider the following C++ member function:
size_t size() const
{
boost::lock_guard<boost::mutex> lock(m_mutex);
return m_size;
}
The intent here is not to synchronize access to the private member variable m_size, but just to make sure that the caller receives a valid value for m_size. The goal is to prevent the function from returning m_size at the same time that some other thread is modifying m_size.
But is there any potential race-condition involved in calling this function? I'm not sure if the RAII style lock here is adequate to protect against a race condition. Suppose the lock's destructor is called before the return value of the function is pushed onto the stack?
Would I need to do something like the following to guarantee thread-safety?
size_t size() const
{
size_t ret;
{
boost::lock_guard<boost::mutex> lock(m_mutex);
ret = m_size;
}
return ret;
}
| Both of your example constructs will do what you're looking for. The following information from the standard supports the behavior you're looking for (even in your 1st example):
12.4/10 Destructors:
Destructors are invoked implicitly ... for a constructed object with automatic storage duration (3.7.2) when the block in which the object is created exits.
And, 6.6/2 Jump statements (of which return is one):
On exit from a scope (however accomplished), destructors (12.4) are called for all constructed objects with automatic storage duration (3.7.2) (named objects or temporaries) that are declared in that scope, in the reverse order of their declaration. Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of variables with automatic storage duration that are in scope at the point transferred from but not at the point transferred to.
So at the point of the return the lock variable is in scope and therefore the dtor has not been called. Once the return has been executed, the dtor for the lock variable is called (thus releasing the lock).
|
3,200,083 | 3,200,140 | Set the backcolor of a WinAPI toolbar with Visual Styles? | Is there a way to set the background color. I thought of making a dummy window and then using TBSTATE_TRANSPARENT, but I thought there might be a cleaner solution?
Thanks
None of these solutions work for a toolbar using visual styles
| Check out TB_SETCOLORSCHEME.
|
3,200,117 | 3,200,136 | What are "cerr" and "stderr"? | What is the difference between them and how are they used?
Can anyone point me to examples?
Specifically, how do you "write" to the stream in both cases and how do you recover and output (i.e. to the screen) the text that had been written to it?
Also, the "screen" output is itself a stream right? Maybe I don't understand streams well enough. This can also be saved to a file of course, I know. Would all of these use fprintf / fscanf, etc?
| cerr is the C++ stream and stderr is the C file handle, both representing the standard error output.
You write to them the same way you write to other streams and file handles:
cerr << "Urk!\n";
fprintf (stderr, "Urk!\n");
I'm not sure what you mean by "recover" in this context, the output goes to standard error and that's it. The program's not meant to care about it after that. If you mean how to save it for later, from outside the program, see the next paragraph.
By default, they'll go to your terminal but the output can be redirected elsewhere with something like:
run_my_prog 2>error.out
And, yes, the "screen" output is a stream (or file handle) but that's generally only because stdout/cout and stderr/cerr are connected to your "screen" by default. Redirection will affect this as in the following case where nothing will be written to your screen:
run_my_prog >/dev/null 2>&1
(tricky things like writing directly to /dev/tty notwithstanding). That snippet will redirect both standard output and standard error to go to the bit bucket.
|
3,200,235 | 3,200,382 | Makefile updated library dependency | I have a large makefile which builds several libraries, installs them, and then keeps on building objects which link against those installed libraries. My trouble is that I want to use "-lfoo -lbar" as g++ flags to link against the two installed libraries, but the dependencies get messed up. If I change a header "42.h" which the library foo depends on, then of course make will rebuild and install it, but it does not appear to notice that my object "marvin" used "-lfoo" and marvin is left linked against the old version... :(
Thus far, I've been doing:
$(myObject): $(localSrc) /explicit/path/to/lib/libfoo.a
$(CXX) $(CPPFLAGS) $(INCFLAGS) -o $@ $^ $(LINKFLAGS) $(LINKLIBS)
But I'm at a point where this is no longer a viable option. I need to simply add libraries "-lfoo -lbar" to the LINKFLAGS variable and have the linker figure things out?
In the mean time, I've aliased a few commands to explicitly blow away the object file(s) in question and then call make, but this is getting silly. I'm pressed for time, but if necessary I could post a small example perhaps Friday evening or Saturday morning.
Hence, I feel like I'm back in some bad version of windows dll hell. Is there something I can do to make the linker take notice of the version of the libraries that an object was built against and relink it if those libraries change??
Updated: So I hadn't had a chance to crash the suggestions until now. The drawback of what I'm doing is using static libraries. So I can't use ldd. So I rewrote my Makefile and found a way around this problem. If I get time, I'll post what I did.
| As far as I know, make in general isn't very good at automatically detecting dependencies like this. (It's not really make's job; make is a higher-level tool that's not aware of the specifics of the commands that it's spawning or what those commands do.)
Two options come to mind.
First, you could run ldd on $(myObject), save its list of libraries to a text file, then feed that back into your makefile as a list of dependencies. (This is similar to using -MD to save a list of header files to a text file then feeding that back into the makefile as additional rules for source file compilation, as Sam Miller suggested.)
Second, you could use a LINKLIBS variable as you've been using, and use GNU Make's functions to let the same variable work for both dependencies and command-line options. For example:
LINKLIBS := /explicit/path/to/lib/libfoo.so
$(myObject): $(localSrc) $(LINKLIBS)
$(CXX) $(CPPFLAGS) $(INCFLAGS) -o $@ $^ $(LINKFLAGS) $(patsubst %,-l:%,$(LINKLIBS))
|
3,200,436 | 3,201,142 | casting from binary to multi-dimensional array on heap | i'm currently using binary files for quick access to custom objects stored in multidimensional arrays which are saved to file as object arrays. so far, reading from file hasn't been too much of a problem since i've been reading the array into an identical object array on the stack. it looks something like this:
Foo foo[5][10];
ifstream infile("foofile.dat",ios::in|ios::binary);
infile.read((char*)&foo, sizeof Foo);
the problem i'm currently running into is that i'm increasingly storing larger amounts of data, and am overflowing my stack when creating the local object array. the solution then, would seem to create the local object array on the heap, and i'm not sure how to format it so that i can cast it directly from the char*. here's how i would allocate on the heap:
Foo (*foo)[1000] = new Foo [500][1000];
however, this doesn't seem to be the proper format if i want to cast to the whole array. for instance, if i try to do the following, it doesn't work:
ifstream infile("foofile.dat",ios::in|ios::binary);
infile.read((char*)(*foo), (sizeof Foo * 500 * 1000)); //or below
infile.read((char*)(&foo), (sizeof Foo * 500 * 1000)); //or below
infile.read((char*)(foo), (sizeof Foo * 500 * 1000)); //or below
essentially, i have no idea how to structure this using an array i've allocated on the heap. can anyone give any pointers (heh)?
thanks so much,
jim
| To my opinion here it makes not much sense to use C++ mechanisms to allocate / deallocate, since you overwrite the data completely by your reads. So don't do new / delete stuff. Your cast (char*) is in fact a reinterpret_cast< char* >. Why not just use a malloc with the correct size?
typedef Foo largeFoo[500][1000];
largeFoo* data = reinterpret_cast< largeFoo* >(malloc(sizeof largeFoo));
Then do your read into that (again with a reinterpret_cast). For convenience you could then alias your pointer to a reference.
largeFoo& foo = *data;
so all of your remaining code could remain the same as in the stack version, with only a free of your pointer at the end.
|
3,200,441 | 3,200,529 | Data structure that can hold multiple types of data | Like the title says, I'm looking for some kind of data structure which will allow me to store any type of class into it that I need at the time. For example:
Foo *foo = new Foo();
Bar *bar = new Bar();
someContainer.push_back( foo );
someContainer.push_back( bar );
someContainer.access( 0 )->doFooStuff();
someContainer.access( 1 )->doBarStuff();
Ideally, as I showed there, it would also allow me to access the contents and use their functions/etc.
I want one of these as I am attempting to create an "invisible" memory management system that just requires a class to inherit my memory manager class, and everything will work automagically.
Here is an example of what I want the code to look like:
template< class T >
class MemoryManaged
{
MemoryManaged()
{
container.push_back( this );
}
void *operator new()
{
// new would probably be overloaded for reference counting etc.
}
void operator delete( void *object )
{
// delete would most definitely overloaded
}
T &operator=( T &other )
{
// = overloaded for reference counting and pointer management
}
static SomeContainer container;
}
class SomeClass : public MemoryManaged< SomeClass >
{
// some kind of stuff for the class to work
};
class AnotherClass : public MemoryManaged< AnotherClass >
{
// more stuff!
};
I hope that my code helps make clear what exactly it is I want to do. If someone knows some kind of already-built data structure that would allow me to do this, that would be awesome. Otherwise, I am currently working on building some kind of shambling zombie of a linked list class that uses templated nodes in order to link any type of class to any other type of class. I still have no idea how I'd get it to work yet, and I would love to be spared the blood, sweat, and tears (and hair) it would take to figure out how to make it work.
| Have a common base class for all of your multiple types. Have the data structure hold onto pointers of your base class's type.
|
3,200,597 | 3,200,669 | (kind of) rotating and slicing elements of a container in C++ | I have a std::vector that holds a Point struct (x,y,z and some other non-pointer types).
These points are control points for drawing a bspline curve. I'm not having trouble drawing the curve, but complications arise when I have to close the curve, which involves adding control points (alredy existing inside the container) in certain order.
For example, if I have 5 control points
A B C D E
I would have to get 5 sequences like this:
A B C D //curve is drawn from B to C
B C D E //curve is drawn from C to D
C D E A //curve is drawn from D to E
D E A B //curve is drawn from E to A
E A B C //curve is drawn from A to B
Initially, I went with std::rotate, but then realized it wasn't what I was looking for.
I'm having trouble implementing this. Best I got is a non-working version in C++ (the reason of this failing is not the question, here's a snippet).
static char letters = 'A';
typedef struct Point{
float x,y,z;
char name;
Point(float x,float y,float z=0):name(letters++){}
}Point;
typedef std::vector<Point> lpoints;
void
rotate(lpoints& points)
{
for (unsigned int i =0;i<5;i++){
lpoints::iterator beg = lista.begin() + (i%5);
lpoints::iterator dernier=lista.begin()+(4+i)%6;
lpoints subseq(beg,dernier); //4 points in subseq
//do stuff with subseq
}
}
Is there a way to do this? I know I can implement it with many nested for loops, but i'm trying to avoid that, looking for something more elegant (if the word fits).
Thanks in advance.
| What, exactly, is wrong with using std::rotate()? For example,
std::vector<int> v(5);
std::rotate(v.begin(), v.begin() + 1, v.end());
std::vector<int> firstFour(v.begin(), v.begin() + 4);
firstFour then contains the first four elements from the rotated vector. If you use this in a loop and run it v.size() times, you will get the five vectors you have in the question.
|
3,200,705 | 3,200,724 | Libraries for standard stuff (ie: cout, etc) *NEWBIE QUESTIONS* :) | I was wondering about the standard C libraries that contain all the functions/definitions like abs(), cout streams, printf, etc.
I'm familiar with the header files (stdio.h, cmath.h, time.h, etc etc) but there doesn't seem to be any corresponding .lib or .dll anywhere (ie. stdio.lib, time.dll, etc).
Where is the actual code for the functions in these header files? Am I misunderstanding something? Is there like, one huge lib file that contains all the standardized stuff, or one for each header?
Any help appreciated!!
Thanks!
| It depends on the implementation. On Windows, the standard library functionality is in the C and C++ runtime libraries. The C runtime library is always linked in automatically; the C++ runtime library is linked in automatically if you include one of the standard library headers.
|
3,201,273 | 3,206,140 | What is the correct way of Multiple inheritance in Qt/C++? | In my Qt application, I have a base class as follow. I am using QObject because I want to use Signal-Slot mechanism in all derived classes.
class IRzPlugin : public QObject {
public:
virtual void registerMenu(QWidget*);
virtual void execute();
}
Then I have another class as follow. I need to extend from QWidget because I need to implement event handling methods in all derived classes (such as mouseMoveEvent(), keyPressEvent() and others).
class IRzLayeringPlugin : public IRzPlugin , public QWidget{
}
But compiler gives these the errors:
C:\svn\osaka3d\tags\iter08\prototype\osaka3d\rinzo\plugin\moc_IRzLayeringPlugin.cxx: In member function `virtual const QMetaObject* IRzLayeringPlugin::metaObject() const':
C:\svn\osaka3d\tags\iter08\prototype\osaka3d\rinzo\plugin\moc_IRzLayeringPlugin.cxx:51: error: `QObject' is an ambiguous base of `IRzLayeringPlugin'
C:\svn\osaka3d\tags\iter08\prototype\osaka3d\rinzo\plugin\moc_IRzLayeringPlugin.cxx:51: error: `QObject' is an ambiguous base of `IRzLayeringPlugin'
make[2]: *** [CMakeFiles/Rinzo.dir/plugin/moc_IRzLayeringPlugin.cxx.obj] Error 1
| In the current incarnation, it isn't possible to use QObject in multiple inheritance paths for a derived class (like your IRzLayeringPlugin class). The only solution I've ever seen was to create an interface class without any QObject inheritence, but with functions that directly correspond to the QObject functions you want to use, then implement the bridge between the interface and your other QObject class inheritance in your specific class. It gets ugly fairly quickly.
|
3,201,342 | 3,201,355 | Meaning of #undef in C++ | I know what this means
#define M(B) (1U << ((sizeof(x) * CHAR_BIT) - B)) // CHAR_BIT=bits/byte
but I don't understand well this one:
#undef M
after this what happens? M is cleared or deleted or?
| After the #undef, it's as if the #define M... line never existed.
int a = M(123); // error, M is undefined
#define M(B) (1U << ((sizeof(x) * CHAR_BIT) - B))
int b = M(123); // no error, M is defined
#undef M
int c = M(123); // error, M is undefined
|
3,201,522 | 3,201,553 | C++ writing/reading hex values correctly (CryptoPP) | I am trying to run a program, that encrypts and decrypts using AES.
(from http://www.codeproject.com/KB/security/AESProductKey.aspx )
// From aestest1.cpp
// Runtime Includes
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include "stdafx.h"
// Crypto++ Includes
#include "cryptlib.h"
#include "aes.h" // AES
#include "modes.h" // CBC_Mode< >
#include "filters.h" // StringSource
using namespace std;
int main(int argc, char* argv[]) {
// Key and IV setup
byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ],
iv[ CryptoPP::AES::BLOCKSIZE ];
::memset( key, 0x01, CryptoPP::AES::DEFAULT_KEYLENGTH );
::memset( iv, 0x01, CryptoPP::AES::BLOCKSIZE );
// Message M
string PlainText = "Hello AES World";
// Debug
cout << "Plain Text:" << endl;
cout << " '" << PlainText << "'" << endl;
cout << endl;
// Cipher Text Sink
string CipherText;
// Encryption
CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption
Encryptor( key, sizeof(key), iv );
CryptoPP::StringSource( PlainText, true,
new CryptoPP::StreamTransformationFilter( Encryptor,
new CryptoPP::StringSink( CipherText )
) // StreamTransformationFilter
); // StringSource
///////////////////////////////////////
// DMZ //
///////////////////////////////////////
//Write data
ofstream write ("file.txt", ios::out | ios::binary);
write.write((char*)key,sizeof(key));
write.write((char*)iv,sizeof(iv));
int at = CipherText.length();
write.write(CipherText.c_str(),at);
write.close();
CipherText.erase();
//Using new key and iv later;
byte key1[ CryptoPP::AES::DEFAULT_KEYLENGTH ],
iv1[ CryptoPP::AES::BLOCKSIZE ];
//Read data
ifstream read ("file.txt", ios::in | ios::binary);
read.seekg (0, ios::end);
int fsize = read.tellg();
read.seekg (0, ios::beg);
read.read((char*)key1,sizeof(key));
read.read((char*)iv1,sizeof(iv));
int toRead = fsize - sizeof(key) - sizeof(iv);
vector<char> bData(toRead);
read.read(&bData[0],toRead);
read.close();
// Recovered Text Sink
string RecoveredText;
// Decryption
CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption
Decryptor( key1, sizeof(key1), iv1 );
CryptoPP::StringSource( &bData[0], true,
new CryptoPP::StreamTransformationFilter( Decryptor,
new CryptoPP::StringSink( RecoveredText )
) // StreamTransformationFilter
); // StringSink
// Debug
cout << "Recovered Text:" << endl;
cout << " '" << RecoveredText << "'" << endl;
cout << endl;
system("pause");
return 0;
}
So I couldn`t manage to write a code, that will correctly do the stuff, that mentioned in comments (after DMZ, where ofstream begins). Thanks in advance.
| You need to disable text processing, which messes up newline characters.
Try
ofstream write ("text.txt", ios::out | ios__binary);
and
ifstream read ("text.txt", ios::in | ios::binary);
|
3,201,549 | 3,201,574 | How to pass parameters to a constructor? | I've got a class A, which consists of objects B and C. How to write a constructor of A that gets B and C objects? Should I pass them by value, by (const) reference, or a pointer? Where should I deallocate them?
I thought about pointers, because then I could write:
A a(new B(1,2,3,4,5), new C('x','y','z'))
But I don't know whether it's a good practice or not. Any suggestions?
| Usually you pass by const reference:
A a(B(1,2,3,4,5), C('x','y','z'))
No need for pointers here.
Usually you store values unless copying is too inefficient.
The class definition then reads:
class A {
private:
B b;
C c;
public:
A(const B& b, const C& c): b(b), c(c) { }
};
|
3,201,840 | 3,202,743 | c++ compile error in codechef.com | I am trying to submit the solution of Adding Least Common Multiples(July contest) in codechef.com.
But
After submission I have got an error
/sources/tested.cpp:1: error: expected unqualified-id before numeric constant
what is it mean?
I did not get any error when I compiled in eclipse(helios) using mingw32-g++
| Can you copy paste your line of code which is causing this error?
This can happen for various reasons.
There can be name collisions wherein you decalare some variable which conflicts with some preprocessor constant.
Passing references to temporary objects as parameters wherein the function expects a reference to some class.
Sometimes it happens that the editors that you use introduce line numbers in the source files and when you copy your code from that editor the line numbers get copied too. I guess this may be a reason in your case. Try uploading your file option rather than pasting your code.
General guidelines to avoid such errors:
All uppercase names are often used for preprocessor macros, which do not respect namespace scopes. Therefore such names should generally be avoided for everything else.
Use GCC for local compilation.
|
3,202,136 | 3,202,161 | Using G++ to compile multiple .cpp and .h files | I've just inherited some C++ code that was written poorly with one cpp file which contained the main and a bunch of other functions. There are also .h files that contain classes and their function definitions.
Until now the program was compiled using the command g++ main.cpp. Now that I've separated the classes to .h and .cpp files do I need to use a makefile or can I still use the g++ main.cpp command?
| list all the other cpp files after main.cpp.
ie
g++ main.cpp other.cpp etc.cpp
and so on.
Or you can compile them all individually. You then link all the resulting ".o" files together.
|
3,202,168 | 3,202,564 | Using static class data in std::max and min | I have a static class data member declared as:
static const float MINIMUM_ZOOM_FACTOR = 4.0;
I'm using this constant in a class member function like this:
zoomFactor_ = max(zoomFactor_, MINIMUM_ZOOM_FACTOR);
At this point, the compiler complains that MINIMUM_ZOOM_FACTOR is an undefined reference. However if I use it directly like this:
if(fabs(zoomFactor_ - MINIMUM_ZOOM_FACTOR) < EPSILON) ...
it works a-ok. What am I doing wrong?
| Only integer constants can be defined inside the class like that. Floating point (or class type) constants must be declared in the class, and then defined and initialised once outside. In practice, that means you must define it in a source file.
// header file
class thingy
{
static const float MAXIMUM_ZOOM_FACTOR;
};
// source file
const float thingy::MAXIMUM_ZOOM_FACTOR = 4.0f;
As to why direct use works but max doesn't: max takes its arguments by reference, so it may require the address of the constant object. If you haven't defined the object then that won't work. Direct use might substitute it for a compile-time constant, which doesn't require an address.
|
3,202,234 | 3,202,280 | overloaded functions are hidden in derived class | In a derived class If I redefine/overload a function name from a Base class,
then those overloaded functions are not accessable/visible to derived class.
Why is this??
If we don't overload the oveloaded function from the base class in derived class
then all the overloaded versions of that function are available to derived class
objects, why is this??
what is the reason behind this. If you explain this in compiler and linker level
that will be more helpful to me. is it not possible to support this kind of scinario??
Edited
For examble:
class B
{
public:
int f() {}
int f(string s) {}
};
class D : public B
{
public:
int f(int) {}
};
int main()
{
D d;
d.f(1);
//d.f(string); //hidden for D
}
Now object 'd' can't access f() and f(string).
| TTBOMK this doesn't have a real technical reason, it's just that Stroustrup, when creating the language, considered this to be the better default. (In this it's similar to the rule that rvalues do not implicitly bind to non-const references.)
You can easily work around it be explicitly bringing base class versions into the derived class' scope:
class base {
public:
void f(int);
void g(int);
};
class derived : public base {
public:
using base::f;
void f(float);
void g(float); // hides base::g
};
or by calling the explicitly:
derived d;
d.base::g(42); // explicitly call base class version
|
3,202,320 | 3,202,356 | How to make template type inference work in this case? | Once again, I wish C++ had stronger typedefs:
#include <vector>
template<typename T>
struct A {
typedef std::vector<T> List;
};
template<typename T>
void processList(typename A<T>::List list) {
// ...
}
int main() {
A<int>::List list;
processList<int>(list); // This works.
processList(list); // This doesn't.
}
Apparently, the compiler sees list as a std::vector<int> and not an A<int>::List, so it can't match it against the A<T>::List that is expected.
In the actual case, it's a longer type name, often repeated, and it's a nuisance. Apart from letting processList accept a vector instead, is there any way to make template type inference work for me?
|
is there any way to make template type inference work for me?
No, this is what's called a non-deducible context.
However, why do you need this anyway? The idiomatic way to pass sequences around is by iterator:
template<typename It>
void processList(It begin, It end) {
typedef typename std::iterator_traits<It>::value_type T;
// ....
}
int main() {
A<int>::List list;
processList(list.begin(), list.end()); // works now
return 0;
}
(Note that in your question, you pass a vector by value, which is a bad thing to do. For iterators, that's fine and even to be preferred.)
However, if you're really desperate, you can have the function deduce any container taking a certain number of template arguments:
template<typename T, typename A, template<typename,typename> C>
void processList(C<T,A>& cont) {
// ....
}
Note, however, that this would match any template with two template arguments. OTOH, it wouldn't match a container like std::map, which has a different number of arguments.
|
3,202,520 | 3,203,429 | C++ - Memory leak testing with _CrtDumpMemoryLeaks() - Does not output line numbers | I'm working on a game with SDL in Visual Studio 2010. I came across the _CrtDumpMemoryLeaks() macro and thought I'd give it a go. Invoking _CrtDumpMemoryLeaks() does print memory leaks to the output window, but it does not show where it happens.
I've read the MSDN article at Memory Leak Detection Enabling , and it explains that if I define _CRTDBG_MAP_ALLOC it should output the line number of the offending statement. This does not happen in my case. (I was however able to get it to work if I use malloc() directly -- not by using 'new').
The code:
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int *var = new int(5);
_CrtDumpMemoryLeaks();
return 0;
}
The output is the following:
Detected memory leaks!
Dumping objects ->
{58} normal block at 0x007D1510, 4 bytes long.
Data: < > 05 00 00 00
Object dump complete.
If _CrtDumpMemoryLeaks() is unable to output line numbers when allocating using 'new' then suggestions for other ways to achieve similar behavior is appreciated.
| When you define _DEBUG and include <crtdbg.h> you get an overloaded operator new which takes additional parameters which you can use to specify the file and line numbers in placement new expressions.
E.g.
int* p = new (_NORMAL_BLOCK, __FILE__, __LINE__) int(5);
You can wrap this in a conditionally defined macro, e.g.
#ifdef _DEBUG
#define DEBUG_NEW_PLACEMENT (_NORMAL_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_NEW_PLACEMENT
#endif
int* p = new DEBUG_NEW_PLACEMENT int(5);
While you do see people defining a macro new to completely hide this form client code, I do not personally recommend it as it breaks anything already intentionally using placement new and you have to make sure that any headers using placement new (such as many standard headers) are included before any header redefining new. This can make it easy to let some inline uses of new in header files slip through without being 'adjusted'.
|
3,202,761 | 3,202,839 | C++ Precision: String to Double | I am having a problem with precision of a double after performing some operations on a converted string to double.
#include <iostream>
#include <sstream>
#include <math.h>
using namespace std;
// conversion function
void convert(const char * a, const int i, double &out)
{
double val;
istringstream in(a);
in >> val;
cout << "char a -- " << a << endl;
cout << "val ----- " << val << endl;
val *= i;
cout << "modified val --- " << val << endl;
cout << "FMOD ----- " << fmod(val, 1) << endl;
out = val;
return 0;
}
This isn't the case for all numbers entered as a string, so the error isn't constant.
It only affects some numbers (34.38 seems to be constant).
At the minute, it returns this when i pass in a = 34.38 and i=100:
char a -- 34.38
Val ----- 34.38
modified val --- 3438
FMOD ----- 4.54747e-13
This will work if I change the Val to a float, as there is lower precision, but I need a double.
This also is repro when i use atof, sscanf and strtod instead of sstream.
In C++, what is the best way to correctly convert a string to a double, and actually return an accurate value?
Thanks.
| This is almost an exact duplicate of so many questions here - basically there is no exact representation of 34.38 in binary floating point, so your 34 + 19/50 is represented as a 34 + k/n where n is a power of two, and there is no exact power of two which has 50 as a factor, so there is no exact value of k possible.
If you set the output precision, you can see that the best double representation is not exact:
cout << fixed << setprecision ( 20 );
gives
char a -- 34.38
val ----- 34.38000000000000255795
modified val --- 3438.00000000000045474735
FMOD ----- 0.00000000000045474735
So in answer to your question, you are already using the best way to convert a string to a double (though boost lexical cast wraps up your two or three lines into one line, so might save you writing your own function). The result is due to the representation used by doubles, and would apply to any finite representation based on binary floating point.
With floats, the multiplication happens to be rounded down rather than up, so you happen to get an exact result. This is not behaviour you can depend on.
|
3,202,822 | 3,202,892 | When to catch boost::bad_lexical_cast | From the documentation on the boost site for lexical cast it states that when converting from a numeric type to a string type the conversion can throw a bad_lexical_cast. Clearly in this case we should always handle this exception should it be thrown.
My question is, what about the other way around, going from a numeric type to a string? This is less risky on operation but it does not state on the boost documentation whether this operation can throw a bad_lexical_cast although the example given ommits the catch block.
log_message("Error " + boost::lexical_cast<std::string>(yoko) + ": " + strerror(yoko));
Should I be catching a potential exception when converting from a numeric type to a string?
| As far as I know, there is no scenario in which an inbuilt numeric type can fail to be expressed in a string.
|
3,203,162 | 3,203,180 | What does sizeof do? | What is the main function of sizeof (I am new to C++). For instance
int k=7;
char t='Z';
What do sizeof (k) or sizeof (int) and sizeof (char) mean?
| sizeof(x) returns the amount of memory (in bytes) that the variable or type x occupies. It has nothing to do with the value of the variable.
For example, if you have an array of some arbitrary type T then the distance between elements of that array is exactly sizeof(T).
int a[10];
assert(&(a[0]) + sizeof(int) == &(a[1]));
When used on a variable, it is equivalent to using it on the type of that variable:
T x;
assert(sizeof(T) == sizeof(x));
As a rule-of-thumb, it is best to use the variable name where possible, just in case the type changes:
int x;
std::cout << "x uses " << sizeof(x) << " bytes." << std::endl
// If x is changed to a char, then the statement doesn't need to be changed.
// If we used sizeof(int) instead, we would need to change 2 lines of code
// instead of one.
When used on user-defined types, sizeof still returns the amount of memory used by instances of that type, but it's worth pointing out that this does not necessary equal the sum of its members.
struct Foo { int a; char b; };
While sizeof(int) + sizeof(char) is typically 5, on many machines, sizeof(Foo) may be 8 because the compiler needs to pad out the structure so that it lies on 4 byte boundaries. This is not always the case, and it's quite possible that on your machine sizeof(Foo) will be 5, but you can't depend on it.
|
3,203,226 | 3,203,522 | How to use RTF export feature of KDE? | In stackoverflow.com I have found a question where a user was suggesting to use this libraries of KDE in order to export-inport RTF files. But, when I downloaded I saw that there are lot of files that are included in the .cc and .h files that are missing. So please give a hint how to download all necessary files and is there any guide that gives and example how to use the RTF exporting example(or instructions)?
BTW if you have ever done RTF exporting programmatically in a better way, please tell me how I can do that.
| First off, as you mention, that code is part of the KDE project. Its code base is very large, so in the worst case you'd have to provide most of kdebase-dev. The following link contains a tutorial for building KWord from SVN, which will pull in all the dependencies you need (then you can start deleting them as you find they aren't relevant):
http://wiki.koffice.org/index.php?title=Build_KOffice
Browsing the sources, I note a few things.
The #includes pretty much just reference QObjects, so be sure that Qt is installed.
The RTF classes you're looking for seem to subclass KDE objects. This means you may have to go through significant work to separate the base code from KDE if you can't have KDE as a dependency for your project.
edit: Looks like you could probably pull much of the algorithm from ExportFilter.cc, for example, and modify it to your needs. Looks like much of the work is being done via QString rather than KDE methonds.
|
3,203,305 | 3,203,356 | Write a function that accepts a lambda expression as argument | I have a method like this
template<typename T, typename U>
map<T,U> mapMapValues(map<T,U> old, T (f)(T,U))
{
map<T,U> new;
for(auto it = old.begin(); it != old.end(); ++it)
{
new[it->first] = f(it->first,it->second);
}
return new;
}
and the idea is that you'd call it like this
BOOST_AUTO_TEST_CASE(MapMapValues_basic)
{
map<int,int> test;
test[1] = 1;
map<int,int> transformedMap = VlcFunctional::mapMapValues(test,
[&](int key, int value) -> int
{
return key + 1;
}
);
}
However I get the error: no instance of function template "VlcFunctional::mapMapValues" matches the argument list argument types are: (std::map, std::allocator>>, __lambda1)
Any idea what I'm doing wrong? Visual Studio 2008 and Intel C++ compiler 11.1
| Your function is expecting a function pointer, not a lambda.
In C++, there are, in general, 3 types of "callable objects".
Function pointers.
Function objects.
Lambda functions.
If you want to be able to use all of these in your function interface, then you could use std::function:
template<typename T, typename U>
map<T,U> mapMapValues(map<T,U> old, std::function<T(T, U)> f)
{
...
}
This will allow the function to be called using any of the three types of callable objects above. However, the price for this convenience is a small amount of overhead on invokations on the function (usually a null pointer check, then a call through a function pointer). This means that the function is almost certainly not inlined (except maybe with advanced WPO/LTO).
Alternatively, you could add an additional template parameter to take an arbitrary type for the second parameter. This will be more efficient, but you lose type-safety on the function used, and could lead to more code bloat.
template<typename T, typename U, typename F>
map<T,U> mapMapValues(map<T,U> old, F f)
|
3,203,365 | 3,203,426 | Problem with linking against a static library which has inline functions | i have a static library which (among other things) implements a tiny function that only returns some string from a table of const strings. This function is not called anywhere inside the library, but still it's declared as inline. For clarity, it looks like this:
namespace flow
{
inline const char* GetName( BYTE methodType );
}
and the implementation:
const char* flow::GetName( BYTE methodType )
{
if ( methodType < 5 )
return cszNameTable[ methodType ];
return NULL;
}
In another project, i'm linking against this library. I have the correct .h files included and I have the using namespace flow; in my code. The problem is, I'm getting linker errors:
error LNK2001: unresolved external symbol "char const * __cdecl flow::GetName(unsigned char)" (?GetName@flow@@YAPBDE@Z)
Now i can easily fix this by removing the "inline" keyword from the function declaration in the static library. So here are my questions:
1) Why does this error appear? How can i fix it without modifying the static library source code (without removing the inline keyword)?
2) What is the benefit of using the inline keyword in a static library function that is not called inside the library itself? Does the inline keyword have any effect when linking against the library from another project (i guess it does, but i'm not sure)?
|
1) Why does this error appear? How can i fix it without modifying the static library source code (without removing the inline keyword)?
There's no point in declaring functions as inline. You have to define them in the header anyway:
namespace flow
{
inline const char* GetName( BYTE methodType )
{
if ( methodType < 5 )
return cszNameTable[ methodType ];
return NULL;
}
}
2) What is the benefit of using the inline keyword in a static library function that is not called inside the library itself? Does the inline keyword have any effect when linking against the library from another project (i guess it does, but i'm not sure)?
The effect of inline is that you can, and have to, define the function within the header, because the implementation of an inline function has to be visible where that function is called.
|
3,203,452 | 3,203,502 | How to read entire stream into a std::string? | I'm trying to read an entire stream (multiple lines) into a string.
I'm using this code, and it works, but it's offending my sense of style... Surely there's an easier way? Maybe using stringstreams?
void Obj::loadFromStream(std::istream & stream)
{
std::string s;
std::streampos p = stream.tellg(); // remember where we are
stream.seekg(0, std::ios_base::end); // go to the end
std::streamoff sz = stream.tellg() - p; // work out the size
stream.seekg(p); // restore the position
s.resize(sz); // resize the string
stream.read(&s[0], sz); // and finally, read in the data.
Actually, a const reference to a string would do as well, and that may make things easier...
const std::string &s(... a miracle occurs here...)
| How about
std::istreambuf_iterator<char> eos;
std::string s(std::istreambuf_iterator<char>(stream), eos);
(could be a one-liner if not for MVP)
post-2011 edit, this approach is now spelled
std::string s(std::istreambuf_iterator<char>(stream), {});
|
3,203,885 | 3,203,956 | Uninitialized Automatic variable forcing value to random value | This may look like a trivial problem. Sorry in that case, I am not able to find the actual way. I understand that automatic variable are un-initilaized. So a code snippet provided below is likely to dump in block-2
char *p;
if(NULL == p)
{
//do something block-1 statement
}
else
{
//do something else block-2 statement
}
Now, in most of the platform the default value of the automatic variable is either 0 or NULL especially SUSE Linux flavours.
Question
a. Is there any compiler flag or any other option which will force the setting up of local variable to a "junk" value if un-initialized?
PS : I know that static analyzer tool will be easily able to detect the problem. I just wanted to know if this can be done at run time also through some flags/option setting.
I am using SUSE 10/HP-UX and AIX platforms.
| What you see here is an artifact of how memory is usually allotted to processes on Unix.
Since the stack segment is not stored in the disk-file image of the executable the OS has to allocate new pages to the stack at program start. These come as zero-filled initially, same as the .bss. This initial zero-filling of the stack is historical. There was an attempt to "simplify" it to not do that. Too many programs broke, so the move was abandoned.
Run your program for a while, make multiple function calls, - you'll see "junk" on the stack eventually :)
|
3,204,001 | 3,205,638 | C++ / openGL: Rotating a QUAD toward a point using quaternions | When I have a QUAD at a certain position, how can I rotate it in such a way that its normal points toward a given point? Imagine the colored blocks are just rectangular quads, then this image shows a bit what I mean. The quads are all oriented in such a way they point toward the center of the sphere.
alt text http://emrahgunduz.com/wp-content/uploads/2009/01/material_id_gui-600x364.jpg
Maybe this second image shows a bit more what I'm trying to do:
alt text http://img689.imageshack.us/img689/3130/screenshot20100708at555.png
I'm using openGL / C++ (and the Eigen lib). And I have this code to draw a simple quad:
#include "ofMain.h"
#include "Quad.h"
Quad::Quad(Vector3f oPosition):position(oPosition) {
}
void Quad::update() {
}
void Quad::draw() {
float size = 1.3;
glColor3f(1.0f, 0.0f, 0.6f);
glPushMatrix();
glTranslatef(position.x(), position.y(), position.z());
glScalef(size, size,size);
glBegin(GL_QUADS);
glVertex3f(0,0,0);
glVertex3f(1,0,0);
glVertex3f(1,1,0);
glVertex3f(0,1,0);
glEnd();
glPopMatrix();
}
Update 17-07
Dear reader,
Just got a little bit further with rotating the quads. I'm positioning a couple of quads randomly and then I rotate them towards a look_at vector3f using this code using the descriptions from the replies below:
void Quad::draw() {
float size = 0.5;
glColor3f(1.0f, 0.0f, 0.6f);
glPushMatrix();
Vector3f center = look_at - position;
Vector3f center_norm = center.normalized();
float r_angle = acos(center_norm.dot(normal));
Vector3f axis = normal.normalized().cross(center_norm);
glPointSize(8);
glLineWidth(4.0f);
// draw the center point
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_POINTS);
glVertex3fv(look_at.data());
glEnd();
// draw the quad
glColor4f(0.0f, 0.0f, 0.0f, 0.85f);
glTranslatef(position.x(), position.y(), position.z());
glRotatef(r_angle * RAD_TO_DEG, axis.x(), axis.y(), axis.z());
glScalef(size, size,size);
glBegin(GL_QUADS);
glVertex3f(-0.5,-0.5,0);
glVertex3f(0.5,-0.5,0);
glVertex3f(0.5,0.5,0);
glVertex3f(-0.5,0.5,0);
glEnd();
glPopMatrix();
}
The result looks like this:
As you can see I'm almost there, though the rotation of the quads is still a bit "strange". I you see the image below with the colored quads you clearly see the difference in rotation. How can I rotate the quad in such a way I get the same result as the colored sphere below?
| Rotation axis = normalize(crossproduct(currentNormal, desiredNormal))
Rotation angle = acos(dotproduct(normalize(currentNormal), normalize(desiredNormal)).
You can build either rotation matrix or quaternion from axis and angle. Exact formula can be found in any resource about quaternions.
You may need to flip angle or axis depending on whether you rotate normal around its' base or around its' tip.
Also THIS resource seems to have enough information about quaternions, rotations, and 3d space in general.
|
3,204,313 | 3,204,353 | How do I make my BigInt and BigFraction classes interact with fundamental data types in C++ | I created my own big integer class, and big fraction class (which stores the numerator and denominator as 2 BigInt member variables). I overloaded the +,-,*,/ operators and the classes work fine. Now I want to extend them so that for example a BigInt can be added to an int painlessly, see below:
int i;
BigInt I1, I2;
BigFrac F1, F2;
I1 = i * I2;
F1 = F2 - i;
F1 = I1 + F2;
I got BigInt to exhibit the behaviour I wanted by adding constructors for int, unsigned int, long, and unsigned long. So if I try to add a BigInt and a short, integer promotion occurs, then a conversion to BigInt, then +(BigInt, BigInt) is called. To get a short to add to a BigInt I overloaded + using templates:
template <class T> const BigInt operator+(const T& A, const BigInt& B)
{ return BigInt(A)+B; }
Now if I try to do the same thing for the BigFrac class I run into all sorts of overload resolution problems when I add the constructor BigFrac(const BigInt&).
How can I achieve the behaviour I want (as painlessly as possible)?
| I don't see why this needs to be a template:
template <class T> const BigInt operator+(const T& A, const BigInt& B)
{ return BigInt(A)+B; }
If you have a conversion from type T to BigInt, and you apperntly do, simply say:
const BigInt operator+(const Bigint& A, const BigInt& B)
{ return A+B; }
|
3,204,577 | 3,204,751 | Debug heap memory leak detection - strange results? | I think my C++ application is tight and doesn't leak any memory. Long running stress tests and static code analyzers seem to indicate as much. However, when exercising a very complex usage szenario the Visual Studio 2008 built in debug heap will show a couple of warnings like the following on exit:
Detected memory leaks!
Dumping objects ->
{318231} normal block at 0x03397FF8, 0 bytes long.
Data: <> üû
What is a memory "leak" of 0 bytes length? Am I corrupting the heap somehow? What could possibly cause the debug heap to emit a warning like that?
| Seeing those "u" characters after the empty bracketed value is creepy. But looking at the CRT source code, that could be explained by a bug in the dumping code, it doesn't seem to zero-terminate the string when the memory block is 0 bytes (valbuff variable in dbgheap.c).
Allocating zero bytes is otherwise a supported scenario. And your code not de-allocating it isn't quite mysterious either perhaps. If you can get the number before the "normal block" output stable then you can assign _crtBreakAlloc() in your initialization code to force a breakpoint. Or you could set a conditional breakpoint on the CRT debug allocator. Trace into a malloc or new call to find it.
|
3,204,776 | 3,204,909 | Which school of reporting function failures is better | Very often you have a function, which for given arguments can't generate valid result or it can't perform some tasks. Apart from exceptions, which are not so commonly used in C/C++ world, there are basically two schools of reporting invalid results.
First approach mixes valid returns with a value which does not belong to codomain of a function (very often -1) and indicates an error
int foo(int arg) {
if (everything fine)
return some_value;
return -1; //on failure
}
The scond approach is to return a function status and pass the result within a reference
bool foo(int arg, int & result) {
if (everything fine) {
result = some_value;
return true;
}
return false; //on failure
}
Which way do you prefer and why. Does additional parameter in the second method bring notable performance overhead?
| Don't ignore exceptions, for exceptional and unexpected errors.
However, just answering your points, the question is ultimately subjective. The key issue is to consider what will be easier for your consumers to work with, whilst quietly nudging them to remember to check error conditions. In my opinion, this is nearly always the "Return a status code, and put the value in a separate reference", but this is entirely one mans personal view. My arguments for doing this...
If you choose to return a mixed value, then you've overloaded the concept of return to mean "Either a useful value or an error code". Overloading a single semantic concept can lead to confusion as to the right thing to do with it.
You often cannot easily find values in the function's codomain to co-opt as error codes, and so need to mix and match the two styles of error reporting within a single API.
There's almost no chance that, if they forget to check the error status, they'll use an error code as if it were actually a useful result. One can return an error code, and stick some null like concept in the return reference that will explode easily when used. If one uses the error/value mixed return model, it's very easy to pass it into another function in which the error part of the co-domain is valid input (but meaningless in the context).
Arguments for returning the mixed error code/value model might be simplicity - no extra variables floating around, for one. But to me, the dangers are worse than the limited gains - one can easily forget to check the error codes. This is one argument for exceptions - you literally can't forget to handle them (your program will flame out if you don't).
|
3,204,871 | 3,205,057 | What's the best way to sum the result of a member function for all elements in a container? | Let's say I have the following object:
struct Foo
{
int size() { return 2; }
};
What's the best way (most maintainable, readable, etc.) to get the total size of all objects in a vector<Foo>? I'll post my solution but I'm interested in better ideas.
Update:
So far we have:
std::accumulate and a functor
std::accumulate and a lambda expression
plain ol' for-loop
Are there any other workable solutions? Can you make something maintainable using boost::bind or std::bind1st/2nd?
| In addition to your own suggestion, if your compiler supports C++0x lambda expressions, you can use this shorter version:
std::vector<Foo> vf;
// do something to populate vf
int totalSize = std::accumulate(vf.begin(),
vf.end(),
0,
[](int sum, const Foo& elem){ return sum + elem.size();});
|
3,204,872 | 3,205,001 | How do I build all configurations of a Visual Studio 2008 C++ project on the command line? | I'd like to build all the configurations of a VS 2008 C++ project on the command line. Something like:
devenv TheProject.vcproj /build /nologo
But this doesn't work because the /build command insists on having a configuration following it like this:
devenv TheProject.vcproj /build "Release|Win32" /nologo
Is there a way to get a command line build of all configurations within the vcproj file?
| I was thinking you can do what you want with MSBUILD, but it appears that it isn't much better for this than DEVENV.
You still have to specify each configuration on the command line, although it would be easy to write a batch file to accomplish this with either MSBUILD or DEVENV.
It looks like previous versions of the development environment may have supported an "ALL" option, but VS 2008 does not.
http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/8701b3d0-d5c9-45fb-8dd4-e7700c8caca6/
|
3,205,197 | 3,205,275 | Remove environmental variable programmatically | I need to write a unit test for some C++ code that checks for the presence of an environmental variable. I'm using MSVS 2008 and gtest as my framework. I add the environmental variable using putenv, I check the environmental variable using getevn, but I can't figure out how to remove it so that no other test will see it. I realize this is probably easy, but I can't find the answer on the internet. Thanks
| Calling putenv again specifying "SOME_VAR=" as parameter will delete environment variable SOME_VAR. btw, Microsoft recommends using _putenv as putenv is deprecated.
|
3,205,242 | 3,205,324 | C++ basic constructor question | How should I handle the following situation :
I am writing my own 2D vector class and have the following code:
class Vector2 : public (...)
public:
Vector2(float x, float y) {
local_vector_storage_[0] = x;
local_vector_storage_[1] = y;
}
template <typename Iterator> Vector2(Iterator begin, Iterator end) {
ASSERT(end - begin == 2);
resize(2);
std::copy(begin, end, local_vector_storage_.begin());
}
// ...
};
Now if I say Vector2 v(3.0f, 4.0f); it compiles fine and calls the appropriate float constructor.
But if I write Vector2 v(3, 4); it fails because the templated iterator constructor "fits better" and Vector2(Iterator(3), Iterator(4)) is called.
What should I do in this case?
My idea was about introducing assign(It1, It2) member method instead of the constructor but maybe there is a better solution?
Edit:
Also, what do you think about ASSERT(end - begin == 2) line? I know that this means I can't, for example, pass iterators of std::list, but brings additional safety. Should I do this or not?
| Something like this seems to work:
template<typename T>
struct notnumeric {typedef int OK;};
template<>
struct notnumeric<int> {};
class Vector2
{
public:
Vector2(float x, float y)
{
}
template <typename Iterator>
Vector2(Iterator begin, Iterator end, typename notnumeric<Iterator>::OK dummy = 0)
{
}
};
I believe it's using SFINAE to prevent the compiler selecting the second ctor for non-numeric types.
As for ASSERT (end - begin == 2), I think you should be using std::distance(begin, end) to determine the distance between two iterators.
|
3,205,423 | 3,207,864 | Listing certificates from a CAC without pin | I'm developing a CAC authentication app.
I'm running RHEL 5.5 and have a card reader attached to my machine. When I insert a smart card/CAC, there is a popup notification that comes on the upper right hand side on the window where the clock is and the "Smart Card Manager" GUI is accessible clicking on the icon (card with lock on it) that appears. With Smart Card Manager displayed I can view the list of certificates on the card as well as the details etc WITHOUT having to enter a pin.
Now, on the other hand when in my C++ code when I used nss libraries to get the slot and list certificate I cannot get the list of certificates without having to enter the pin.
What I would like to do is get the list of certificates off the card and present that list to the user in a dialog box ALONG with pin text field so that User can enter the pin and then select the certificate to use for authentication ALL IN ONE step instead of application having to display a separate dialog box for pin and then the popup for certificate selection but it seems like it's not possible using nss libraries but on the other hand smart card manager gui can easily do this. Can anone point me to the right direction as to if there a separate api I can use to get the list of certificates from CAC??? Thanks!
|
Search the web for "friendly certs" or "publicly readable certs" feature/mechanism (0x1<<28 when loading the module) - by default NSS assumes that a PIN is needed before anything can be read from the token. Which is IMHO utter stupidity and keeping it as a default...
Be sure to take into account pinpad readers (protected authentication path in PKCS#11) as you hopefully will like to support better security for your users who have the capability. No PIN entry textbox should be shown when there is a pinpad reader attached.
|
3,205,442 | 3,207,600 | register for WindowServer CGScreenRefreshCallback CGScreenUpdateMoveCallback in C++ | I'm trying to register for CGScreenRefreshCallback and CGScreenUpdateMoveCallback ( here's what apple's saying about http://developer.apple.com/mac/library/documentation/GraphicsImaging/Reference/Quartz_Services_Ref/Reference/reference.html#//apple_ref/doc/uid/TP30001070-CH1g-F16970 )
using C++ only.
I wrote this simple tester for the refresh callback in order to retrieve the changing rectangles:
#include "ApplicationServices/ApplicationServices.h"
#include <iostream>
using namespace std;
/////////////HEADER
static void DHRefreshCallback (CGRectCount count,const CGRect * rectArray,void * userParameter);
///////////////////
int main (int argc, char * const argv[]) {
CGRegisterScreenRefreshCallback(DHRefreshCallback, NULL);
while (true) {
// just hanging
}
return 0;
}
static void DHRefreshCallback (CGRectCount count,const CGRect * rectArray,void * userParameter){
cout << "something changed" << endl;
return;
}
...but didn't work.
I know I need a connection with WindowServer (Quartz Compositor \ Quartz Extreme \ Quartz Extreme 2D...still can't figure out the difference) and a running thread in order to get these callbacks, but I really don't know how to do this in C++ only (no Objective-C at all).
any direction?
thx in advance,
pigiuz
| It's not about using/not using Objective-C. It's about the event loop in OS X apps in general, which is done by CFRunloop, which is a C API. See Run Loop management and CFRunLoop reference. You also need a connection to the window server, which can be established by calling
Instead of
while (true) {
// just hanging
}
just do
extern "C" void NSApplicationLoad(void);
NSApplicationLoad(); // establish a connection to the window server. In <Cocoa/Cocoa.h>
CFRunLoopRun(); // run the event loop
Don't forget to link against Cocoa.framework; just add -framework Cocoa in the command line of the compiler.
You can #import <Cocoa/Cocoa.h> but then you need to use Objective-C++ because of the Objective-C classes declared in it.
You could use
RunApplicationEventLoop(); //establish a connection to the window server
//and runs the event loop. In <Carbon/Carbon.h>
in an 32 bit app, instead of NSApplicationLoad + CFRunLoopRun, but it's not available in an 64 bit app.
|
3,205,449 | 3,217,307 | using rake with project directory structure | I have been looking into Rake for build script in our CI system (Projects built with C++). I have been playing about with a simple 'hello world' application to see what rake is capable of doing. All was well until i decided to put the .h files into a include folder and the .cpp files into src folder. Rake was able to find the .cpp files but not the include header files. File structure like this:
src/main.cpp
src/greet.cpp
include/greet.h
rake script was as follows:
require 'rake/clean'
require 'rake/loaders/makefile'
APPLICATION = 'hello.exe'
C_FILES = FileList['src/*.cpp']
HDR_FILES = FileList['include/*.h']
ALL_FILES = [C_FILES] + HDR_FILES
O_FILES = C_FILES.sub(/\.cpp$/, '.o')
file '.depend.mf' do
sh "makedepend -f- -- -- #{ALL_FILES} > .depend.mf"
end
import ".depend.mf"
file APPLICATION => O_FILES do |t|
sh "gcc #{O_FILES} -o #{t.name}"
end
rule ".o" => [".cpp"] do |t|
sh "gcc -c -o #{t.name} #{t.source}"
end
C_FILES.each do |src|
file src.ext(".o") => src
end
CLEAN.include("**/*.o")
CLEAN.include(APPLICATION)
CLEAN.include(".depend.mf")
task :default => APPLICATION
Any help would be much appreciated.
| this line: ALL_FILES = [C_FILES] + HDR_FILES should be ALL_FILES = C_FILES << HDR_FILES
a FileList is just a fancy array that rake provides for us, but it's just an array underneath the hood, so we can use all of the standard array operators on it.
the << operator will append all of the items in the HDR_FILES array onto the end of the C_FILES array.
using the + operator will add the HDR_FILES array as a single element to the end of the C_FILES array, creating an array of arrays
|
3,205,493 | 3,205,657 | Write a client-server program in C ... on a sheet of paper | This was an actual interview question. o_O
Let's leave aside the issues of asking such a question in an interview.
I'm wondering what alternatives to the ol' TCP sockets approach are readily available (as libraries, for instance), for use in C or C++.
I'm making no assumptions on platform, compiler etc - take your pick.
I'm not asking you guys to actually write the program, but merely to point at technologies that may be usable for the purpose, and possibly at an example or tutorial using that technology in C/C++.
|
I'm making no assumptions on platform,
compiler etc - take your pick.
main() {
system("apache -start")
system("telnet 127.0.0.1 80")
}
;-)
|
3,205,552 | 3,207,817 | Passing temporaries as LValues | I'd like to use the following idiom, that I think is non-standard. I have functions which return vectors taking advantage of Return Value Optimization:
vector<T> some_func()
{
...
return vector<T>( /* something */ );
}
Then, I would like to use
vector<T>& some_reference;
std::swap(some_reference, some_func());
but some_func doesn't return a LValue. The above code makes sense, and I found this idiom very useful. However, it is non-standard. VC8 only emits a warning at the highest warning level, but I suspect other compilers may reject it.
My question is: Is there some way to achieve the very same thing I want to do (ie. construct a vector, assign to another, and destroy the old one) which is compliant (and does not use the assignment operator, see below) ?
For classes I write, I usually implement assignment as
class T
{
T(T const&);
void swap(T&);
T& operator=(T x) { this->swap(x); return *this; }
};
which takes advantage of copy elision, and solves my problem. For standard types however, I really would like to use swap since I don't want an useless copy of the temporary.
And since I must use VC8 and produce standard C++, I don't want to hear about C++0x and its rvalue references.
EDIT: Finally, I came up with
typedef <typename T>
void assign(T &x, T y)
{
std::swap(x, y);
}
when I use lvalues, since the compiler is free to optimize the call to the copy constructor if y is temporary, and go with std::swap when I have lvalues. All the classes I use are "required" to implement a non-stupid version of std::swap.
| Since std::vector is a class type and member functions can be called on rvalues:
some_func().swap(some_reference);
|
3,205,561 | 3,208,972 | binding generic c++ libraries to python with boost.python | I would like to know what's the process, when binding C++ libraries that are written with in a generic way.
Is there a posibility of binding a template class, or you can only bind only a template generated class ?
| You can only bind a generated class. However, it is possible to write a template function to export your class, and call this function for each concrete types you want to export. For example:
template<class T>
struct foo {};
template<class T>
void export_foo(std::string name) {
boost::python::class_<foo<T>>(name.c_str());
}
BOOST_PYTHON_MODULE(foo)
{
export_foo<int>("foo_int");
export_foo<std::string>("foo_string");
//...
}
If it is not enough, you can also dive into meta programming (with Boost.MPL for example), to create typelists, and automatically call export_foo for all these types.
|
3,205,923 | 3,206,004 | Is there any way I can make g++ only emit warnings pertaining to my files? | I like to compile my code with -Wall, and sometimes even -pedantic. It's partly a style thing, and partly the fact that it does occasionally emit very, very useful warnings (such as using = rather than ==).
However, the writers of some of my headers are clearly not such sticklers. Compiling with either of the two warning levels yields a tremendous mess of output, completely defeating the purpose of compiling that way in the first place.
So how can I make my compiler ignore those warnings?
| Alternatively to JS Bangs' answer, you can have GCC treat them as system headers, which disables all warnings (excepting #warning directives) for those headers.
If the -isystem switch is unhelpful, you can wrap all of the offending headers with simpler headers that contain only the appropriate line:
#pragma GCC system_header
|
3,206,157 | 3,208,929 | How can I resolve foo's library path using g++ -Lhere -Lthere -lfoo without building an object? | I would like to display the explicit path to a library which will be used in the linking stage of compilation. I want to do this so that I can add the library as a dependency to a separate object file.
In other words, I often link using:
g++ myFile.cpp -Lsomewhere -Lelse -Lhere -Lthere -lfoo
Is there a way to coerce g++, ld, ldd, or something else to resolve '-lfoo' using the -L's without actually linking anything so that I can use the explicit path as a dependency? For more explicit info, see Makefile Updated Library Dependency.
| This isn't ideal, and I hope there is a cleaner answer, but you can get the default search paths from gcc, then search each one for the files. Here it is in GNU make:
libnams = foo bar
dirs = somewhere else here there
dirs += $(subst :, ,$(subst =,,$(word 2,$(shell gcc -print-search-dirs | grep libraries))))
exts = a so
paths = $(foreach L, $(libnams), \
$(firstword $(foreach D, $(dirs), \
$(foreach E, $(exts), \
$(wildcard $(D)/lib$(L).$(E))))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.