question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
6,779,663 | 6,779,715 | How to trigger the __cplusplus (C++) #ifdef? | #ifdef __cplusplus
// C++ code
#else
// C code
#endif
The structure is this.
My question is, how to actually trigger the #ifdef on?
I mean, in program? What code I write can turn #ifdef on?
For example, in this case.
is that
#define __cplusplus
will turn it on?
|
"#define __cplusplus"
will let it on?
Yes, it will "let it on".
__cplusplus should be automatically defined by C++ compiler. C++ uses different name mangling and the macro often used to make C headers compatible with C++:
#ifdef __cplusplus
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif
|
6,779,867 | 6,779,897 | vector<float>* causing seg fault! | I have a vector of floats, defined by:
std::vector<float>* MyVec;
and I was filling this inside a for loop later with:
MyVec->push_back(somevalue)
and I was getting a seg fault. In order to try and find out what was going on I commented out the push_back line and I still saw a seg fault, and when it seg faulted the ... | You've not allocated memory:
std::vector<float>* MyVec = new std::vector<float>();
Because MyVec is a pointer to std::vector<float>, you've to do the above, before using MyVec.
Also, don't forget to deallocate the memory, once you're done with MyVec:
delete MyVec;
Apart from that, I think, you don't need a pointer to... |
6,780,149 | 6,780,163 | Why does dereferencing a string vector iterator need parentheses? | vector<string> MyStrings;
vector<string>::iterator ItStr;
I'm using c_str() to return the pointer to the string.
Why does it need to be dereferenced with parentheses?
Doesn't compile: *ItStr.c_str();
error C2039: 'c_str' : is not a member of 'std::vector<_Ty>::iterator'
Compiles/Works with parentheses around itera... | . has higher precedence than the unary *.
*ItStr.c_str() is as if you had said *(ItStr.c_str()).
You can, of course, just use ItStr->c_str(), since (*x).y is equivalent to x->y (at least for pointers and iterators; you can, of course, overload the operators for your own types such that they are not consistent, but you'... |
6,780,265 | 6,780,312 | abstract class and static methods | I have an abstract class:
class A
{
public:
bool loaded_;
virtual int load() = 0;
}
And several derived classes :
class B:public A
{
public:
int load();
static B& instance();
}
class C:public A
{
public:
int load();
static C& instance();
}
The fact is that the code inside ::instance() methods i... | You could make instance() a free function template:
template<class T>
T& instance()
{
static T instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
Then you can use it like this:
instance<B>().do_stuff()
|
6,780,394 | 6,781,202 | C++ how to make simple sha256 generator with boost? | I need a simple string to sha256 generator class. I do not want to build big libraries for that like openSSL or Cripto++ - all I want is to turn strings into sha256. How to create such class or where to get it?
| Like others have said, I was under the impression that hashing under SHA256 is not trivial enough to simply implement yourself as a subset of a bigger coding project. If you take a look at the wikipedia page for SHA-2, you will notice some pretty intense math. If you would like the actual encryption abstract (the math ... |
6,780,649 | 6,780,686 | File I/O logic with a while statement, how would this code be expected to behave? | I'm trying to understand some differences in file i/o techniques. Suppose I have the following code:
FILE *work_fp;
char record[500] = {0};
while(!feof(work_fp))
{
static int first = 1;
fgets(record, 200, work_fp);
if (first)
{
var1 = 2;
length += var1;
}
first = 0;
if (fe... | The line:
fgets(record, 200, work_fp);
can advance to read/write head to the end of the file, thus changing the return value on feof.
|
6,780,657 | 6,780,718 | How to declare boost unordered_multimap | I'm trying to use the boost unordered_multimap class and I'm having trouble declaring it. The error follows the code.
#include <iostream>
#include <map> // header file needed for to use MAP STL
#include <boost/unordered_map.hpp>
using namespace std;
int main(void)
{
map<int, map<int, map<int,int> > > _3dstl;
_3dstl... | Change this line:
typedef boost::unordered_multimap<int, typedef boost::unordered_multimap<int, int>> unordered_map;
To this:
typedef boost::unordered_multimap<int, boost::unordered_multimap<int, int> > unordered_map;
The second typedef is not necessary and a syntax error. Also in C++2003 you have to watch out for >>... |
6,780,829 | 6,780,865 | c++ constructor question | I am still confused with the CTORs:
Question 1:
why line 15 call A:A(int) instead of A:A(double&)?
Question 2:
why line 18 did not call A:A(B&)?
#include <iostream>
using namespace std;
class B{};
class A{
public:
A(int ) {cout<<"A::A(int)"<<endl;}
A(double&){cout<<"A::A(double&)"<<endl;} // it will work if ... | Line 15: A(double&) can only take lvalues, i.e. variables that can be assigned to. (double)2.1 is an rvalue. Use A(const double&) if you need to accept rvalues as reference too.
Line 18: B is a type, not a value. A obj4(B); only declares a function with name obj4 taking a B and returning an A.
|
6,780,935 | 6,782,426 | Listing specific subsets using STL | Say I have a range of number, say {2,3,4,5}, stored in this order in a std::vector v, and that I want to list all possibles subsets which end with 5 using STL... that is :
2 3 4 5
2 3 5
2 4 5
3 4 5
2 5
3 5
4 5
5
( I hope i don't forget any:) )
I tried using while(next_permutation(v.begin(),v.end())) but didn't come up... | tomasz describes a solution which will be workable as long as n<=32 although it will be take a very long time to print 2^32 different subsets. Since the bounds for the large dataset are 2 <= n <= 500 generating all the subsets is definitely not the way to go. You need to come up with some clever way to avoid having to ... |
6,780,945 | 6,780,970 | FindWindow is not working? | I just want to know why this code is not working?
HWND hWnds = FindWindow(NULL,(LPCTSTR)"Calculator");
It always returns NULL for the hWnds....
Any idea how to fix this? Thank you :)
| Dont cast the string.
HWND hWnds = FindWindow(NULL,_T("Calculator"));
|
6,780,973 | 6,789,046 | porting wxwidgets opengl application to not library dependent application | I want to port wxwidgets opengl application that will be not library dependent.I want at least that it can be compiled without additonal libraries. I am thinking to port it to MFC or maybe WIN32.What is the most easiest?Maybe you have some other suggestion?
| MFC is by far the easiest. It's also the only realistic option if you don't want to use libraries that aren't installed with Visual Studio.
|
6,781,104 | 6,781,817 | streaming fast changing data between servers | I have server 1 which is generating a large amount of data, e.g there are files that are constantly being updated, on the time scale of milliseconds.
I would like to get these files onto another server, using C++ or standard Linux methods.
Currently, I have been doing this by compressing the files every second and usin... | Just an idea, i don't know if it'll work for your particular situation:
Write two programs. One that runs on the server on which you files are being updated, and it monitors the changes with inotify. The other program runs on the second server and maintains a tcp connection with the first one. Whenever the first progra... |
6,781,201 | 6,781,227 | Convert decimal dollar amount from string to scaled integer | "35.28" is stored as a char*. I need to turn it into an integer (35280).
I want to avoid floats. How can I do this?
| Remove the dot from the char and then
Simplest but not the best use atoi
See my answer here, for other possible ways.
|
6,781,222 | 6,781,427 | unordered_multimap element insert | I tried to insert a value into a boost unordered_multimap using the following code but that didn't work since it doesnt compile. Why is there no access [] operator?
The insert() method doesn't work either?
#include <iostream>
#include <boost/unordered_map.hpp>
using namespace std;
int main()
{
typedef boost::unor... | Neither unordered_multimap nor multimap supports operator[] because it's not well-defined what it would mean. The idea behind operator[] is that you could write myMap[key] to mean "the unique value associated with key in myMap." When dealing with a unordered_multimap, this isn't mathematically well-defined; there can... |
6,781,237 | 6,781,673 | Source compiles in GCC but not Visual Studio | This compiles on GCC 4.6 but doesn't with VS2010 sp1:
Is it my fault or VS screwed up again?
#include "stdafx.h"
enum Attribute{red_att,black_att,key_att,value_att};
struct Color{};
template<enum Attribute>
struct Tag_Value;
template<>
struct Tag_Value<red_att>
{
typedef Color type;
};
int main()
{
... | I'm not certain what the exact problem is—my guess is that it is treating enum Attribute as the beginning of a new enum declaration... perhaps as a member of Tag_Value. So you have two Attribute enums and it won't let you specialize one with the other.
To fix, just get rid of the enum:
template<enum Attribute> struct ... |
6,781,287 | 6,781,676 | Segfault on nth interation through std::map | Solution: See Bo Persson's post and my comment below.
I am getting a segmentation fault with my map. What confuses me is that the n-1 iterations over the keys works but then seg faults on the nth iteration. To add to the confusion, the key value that the iteration seg faults on is found (with an iterator) in the pervio... | This isn't just a test for presence
unsigned short* test_array = site_depths["lcl_NM_000999"];
but also inserts a node into site_depths, but with a null pointer in the second member.
The code also trusts that start and end are always within range of the array size given by size. Wouldn't hurt to validate that!
|
6,781,489 | 6,782,458 | Making a "panel" in WINapi | I need to make a Panel (borderless Window?) with WinAPI for wxWidgets since I need one with CS_OWNDC to always have the same DC.
What styles should I use?
I do not program winapi very often, so I beg you to help me out :-).
| CreateWindow() / CreateWindowEx() with WS_CHILD would create a borderless/menubarless window (aka panel).
You'll have to register a custom window class (RegisterClass()) for your custom window panel if you want an alternate class style than one that is already provided by the common controls ("static" for instance).
Ar... |
6,781,545 | 22,593,639 | Why is failbit set when eof is found on read? | I've read that <fstream> predates <exception>. Ignoring the fact that exceptions on fstream aren't very informative, I have the following question:
It's possible to enable exceptions on file streams using the exceptions() method.
ifstream stream;
stream.exceptions(ifstream::failbit | ifstream::badbit);
stream.open(file... | Improving @absence's answer, it follows a method readeof() that does the same of read() but doesn't set failbit on EOF. Also real read failures have been tested, like an interrupted transfer by hard removal of a USB stick or link drop in a network share access. It has been tested on Windows 7 with VS2010 and VS2013 and... |
6,781,622 | 6,781,830 | OpenCV 2.3 with VS 2008 - Mouse Events | Obligatory - I'm a newbie. Have a job that involves programming and I'm teaching myself as I go. Needless to say as a teacher I get things wrong frequently and thoroughly.
Where I'm at right now: I've created the class "Graph", it (surprisingly enough) makes graphs. But now I want to make it so that on a mouse click... | Yes callback functions in C++ are a joy, aren't they? You actually have to give OpenCV a function (not a class method) as you've already found out. However, you can hack around this awfulness using the following technique:
class MyClass
{
public:
void realOnMouse(int event, int x, int y, int flags)
{
... |
6,781,784 | 6,781,890 | How to draw smooth lines without using GLSL, FSAA nor GL_LINE_SMOOTH? | So i need a method to do smooth lines without using:
Full Screen Antialiasing (slow)
Shaders (not supported on all cards)
GL_LINE_SMOOTH (causes a crash on some cards)
Only way i could think of doing this was using a textured rectangle that is always faced at camera direction, but the problems are:
1. how do i always... |
Billboarding is a simple concept, but can be difficult to implement. A billboard is a flat object, usually a quad (square), which faces the camera. This direction usually changes constantly during runtime as the object and camera move, and the object needs to be rotated each frame to point in that direction. There are... |
6,781,848 | 6,781,987 | Heisenbug issue with using a dll. What do I do next? | I am working on a system that uses a Voltage Controlled Oscillator chip (VCO) to help process a signal. The makers of the chip (Analog Devices) provide a program to load setup files onto the VCO but I want to be able to setup the chip from within the overarching signal processing control system. Fortunately Analog De... | Some compilers/IDEs add extra padding to variables in debug builds or initialize them to 0 - this might explain the differences you're encountering between debugging and "normal" execution.
Some things that might be worth checking:
- are you using the correct calling convention?
- do you get the same return value if ... |
6,781,894 | 6,781,903 | how to see the value of CXX and CXXFLAG | before compiling my C++ program, i exported the CXX and CXXFLAGS from the command line.
$ export CXX="/media/space/gcc-dist/bin/g++"
$ export CXXFLAGS="-std=c++0x"
But now i want to see the values of CXX and CXXFLAGS. How do i do that.
I'm using KUbuntu 11.04
| You can usually do this on Linux systems by opening a terminal and entering
echo $CXX
echo $CXXFLAGS
|
6,781,917 | 6,782,023 | Large abstract base classes | I'm writing a large abstract base class with 30 something purely virtual methods*.
Finding all the functions to implement in a base class in the implementation classes is a little tedious, mostly because MSVC++ does not tell you which function you failed to implement with compiler error "Cannot construct abstract class... | There's no obvious correct answer to this question. Deciding whether to factor apart the base class into multiple abstract base classes should probably be a decision you make based on whether or not the base class logically represents several different concepts, rather than on poor compiler error messages. If the onl... |
6,781,985 | 6,782,085 | Is the use of std::vector<bool> objects in C++ acceptable, or should I use an alternative? | I'm working with a user-defined quantity of bits (I'm holding a three-dimensional array of bits, so the size increases cubically - assume no less then 512 bits), and need to flip them each individually. Right now, just on a computer, I'm using the bool type, since memory isn't an issue. I do plan to move the code to ... | There's nothing wrong with vector<bool>, except that it isn't equivalent to a vector<T> were T is the integer type equivalent to bool. This only shows in performance (CPUs only access bytes at a time, where in a vector<bool> every element is stored in one bit) and memory access (a reference to a first element of a vect... |
6,782,050 | 6,782,141 | Are these sizes correct for an array of variables and an array of pointers to variables? | Are the sizes and statements for the entire array stated in the comments in the code below correct?
//gArray uses sizeof(char)*100 = 1*100 = 100 bytes.
char gArray[100];
//gArray uses sizeof(char)*100*50 = 1*100*50 = 5000 bytes.
char gArray[100][50];
//gArray is a 2D array, each element is a pointer to a char (althou... | You just print out the values:
char gArray1[100];
char gArray2[100][50];
char* gArray3[100][50];
std::cout << "gArray1 " << sizeof(gArray1) << "\n"
<< "gArray2 " << sizeof(gArray2) << "\n"
<< "gArray3 " << sizeof(gArray3) << "\n";
I get:
gArray1 100
gArray2 5000
gArray3 40000
|
6,782,321 | 6,782,596 | How to use mouse hook so current window never sees specific mouse message? | I want some window to never receive mouse wheel up/downs, i can control this messages trough my mouse hook fine but is there a way to make a window never receive those messages?
I can validate the window trough mouse hook and check if its active then just never send that message to it.
I installed mouse hook globally ... | AFAIK hooks may not block the message from reaching the wndproc of the appropriate window.
You may however achieve what you need by subclassing the appropriate windows. That is, replace the window procedure of the appropriate window (use SetWindowLongPtr with GWL_WNDPROC flag) by your wndproc. It should pass all the me... |
6,782,334 | 6,782,373 | C++: How do you initialize an internal struct's members using an initialization list? | This is really two questions, noted below:
Currently I have some public internal helper structs (strictly used to pass data around as one object), during construction of an instance of the class I attempted to use initialization lists instead of assignment, but the compiler complained about the individual struct member... | In C++03, there is no way to initialize individual fields of a nested struct, nor is there a way to initialize individual fields of a nested array. In C++0x (now C++11, I guess), they've relaxed this restriction and you can initialize nested structs with a syntax like this:
Foo::Foo() : _currBar{fieldOneValue, fieldTw... |
6,782,469 | 7,090,542 | openmp segmentation fault - strange behaviour | I'm quite new at c++ and openmp in general. I have a part of my program that is causing segmentation faults in strange circumstances (strange to me at least).
It doesn't occur when using the g++ compiler, but does with intel compiler, however there are no faults in serial.
It also doesnt segfault when compiling on a di... | As already stated in the previous answer you can try to use Valgrind to detect where your memory is corrupted. Just compile your binary with "-g -O0" and then run:
valgrind --tool=memcheck --leak-check=full <binary> <arguments>
If you are lucky you will get the exact line and column in the source code where the memory... |
6,782,590 | 6,782,742 | Is it reasonable to codify lazy loading as a template class? | I'm wondering if something like
template <typename T>
class LazyLoaded
{
mutable char mem[sizeof T]; //First item in the class to keep alignment issues at bay
const std::function<void (T&)> initializer;
mutable bool loaded;
public:
LazyLoaded() : loaded(false)
{
initializer = [] (T&) {};
... | It's called boost::optional. This should provide almost all the necessary functionality.
|
6,782,632 | 6,782,644 | Using fread/fwrite for STL string. Is it correct? | I have a structure, that contain string. Something like that:
struct Chunk {
int a;
string b;
int c;
};
So, i suppose, that i cannot write and read this structure from file using fread and fwrite functions. Because string may reserve different memory capacity.
But such code works corre... | You are justified in doubting this. You should only stream POD types with fwrite and fread and string is not POD.
|
6,783,014 | 6,783,070 | Why is the heap after array allocation so large | I've got a very basic application that boils down to the following code:
char* gBigArray[200][200][200];
unsigned int Initialise(){
for(int ta=0;ta<200;ta++)
for(int tb=0;tb<200;tb++)
for(int tc=0;tc<200;tc++)
gBigArray[ta][tb][tc]=new char;
return sizeof(gBigArray);
}
The... | It doesn't sound silly if you know how memory allocators work. They keep track of the allocated blocks so there's a field storing the size and also a pointer to the next block, perhaps even some padding. Some compilers place guarding space around the allocated area in debug builds so if you write beyond or before the a... |
6,783,105 | 6,783,458 | Does the order of operations change within an if expression? | I recently came across something that I thought I understood right off the bat, but thinking more on it I would like understanding on why it works the way it does.
Consider the code below. The (x-- == 9) is clearly getting evaluated, while the (y++ == 11) is not. My first thought was that logical && kicks in, sees that... |
logical operators fall below increment operations in the order of
precedence.
Order of precedence is not order of execution. They're completely different concepts. Order of precedence only affects order of execution to the extent that operands are evaluated before their operator, and order of precedence helps tell ... |
6,783,412 | 6,783,447 | Is this a valid form of typedef struct and if so, what does it mean? | Working with a piece of code right now that features declarations of the form:
typedef PACKED(struct)
{
// some stuff in here
} struct_name;
now...PACKED is a macro on our part. What the heck does this syntax mean? I don't understand the use of parenthesis. This is not compiling, so I'm guessing this is probabl... | Usually something in all caps is a macro. In this case it's probably supposed to decorate the struct declaration with the syntax for creating a packed structure, which will vary based on the compiler used.
Chances are you're completely missing the definition of the PACKED macro.
|
6,783,534 | 6,783,724 | Can't save an image captured from webcam (imwrite compile error with OpenCV 2.3) | I'm making simple webcam program using OpenCV 2.3 and got stuck by the compile error. Any idea will be appreciated.
Upon compile, I get the following error at imwrite (in read function in the code below).
This sample that uses imwrite to save an image works on my environment, which indicates imwrite in OpenCV 2.3 shoul... | The third param is optional (array of format dependent parameters).
The error you are getting is because 'sharedImage' is of type Mat* that can't cast automatically to 'const cv::_InputArray&', the expected type for imwrite. If look at the example more carefully, you'll see that the type of the parameter passed in as s... |
6,783,586 | 6,783,605 | Using python to run a C++ program and test it | Suppose I have a simple C++ program that takes in inputs and outputs some string. Like this (actual program is much more complicated but still text based):
$ ./game
$ what kind of game? type r for regular, s for special.
$ r
$ choose a number from 1 - 10
$ 1
$ no try again
$ 2
$ no try again
$ 5
$ yes you WIN!
I haven... | Use pexpect.
Normal stdin/stdout piping usually doesn't work, because the standard library facilities in the parent and child processes tend to buffer I/O more aggressively when a file descriptor isn't a TTY (via the isatty call). Obviously, you can fix this in the parent, since you own that code; just call flush at ap... |
6,783,646 | 6,783,742 | Registering a COM object with only an IDL file | I have a third-party IDL file which, when compiled, generates a header and an _i.c file. All three of these files are part of a Visual Studio 2010 project. (So far the project is empty other than attempted COM initialization stuff.)
I can get the project to compile by calling
CoInitialize(NULL);
CoCreateInstance(stuff)... | IDL files define interfaces, not implementations. If literally all you have of this third-party component is an IDL file then you have nothing you could register.
It's possible that the IDL file describes interfaces you're to implement that third-party code calls into; in that case you wouldn't CoCreateInstance them, t... |
6,783,669 | 6,783,714 | How do I use std:vector's erase() function properly? | I am having a strange issue when using the erase() function on a std:vector. I use the following code:
int count = 0;
for (int itr=0; itr<b.size(); ++itr) {
if (b[count].notEmpty = false) {
b.erase(b.begin()+count);
--count;
}
++count;
}
However, for some reason there are no elements actual... | There's nothing wrong with your use of erase. The problem is an assignment inside the if condition:
if(b[count].notEmpty = false)
This sets b[count].notEmpty to false, then returns false. This will cause the inner-body of the if-statement to never run.
Change it to
if(b[count].notEmpty == false)
or event
if(!b[count]... |
6,783,692 | 6,783,782 | Copy constructor between derived classes | How do you copy a derived class to another?
I'm terminologically deficient, so I'll try to illustrate with an example.
We are playing a card game with a computer player and human player. Card and Command are other classes.
class Player
{
Card *Hand[4];
// etc...
};
class Human: public Player
{
Command getC... | You have a design problem here. If you want to switch a player from a Human to a Computer while maintaining the common member variables then you should structure your classes in that way.
class Player
{
public:
friend class Human; // These friends are necessary if the controllers
friend class Computer; // n... |
6,783,939 | 6,784,000 | Does using references instead of pointers, resolve memory leaks in C++? | Most of memory leaks appear when a pointer of an object returned and programmer forgot to delete it.
for example:
class my_class
{
...
};
my_class* func1()
{
my_class* c = new my_class;
return c;
}
int main()
{
my_class* var1 = func1();
...
// Programmer forgot delete the var1: delete var1;
// -- or --
... | You haven't resolved any memory leaks. If you new, then you must delete. All you did was dereference the pointer, it still needs to be deleted. You can resolve memory leaks by creating local objects and returning by value, or using smart pointers. 99 times out of 100, I prefer the return by value option.
Now, like ... |
6,783,993 | 6,784,035 | placement new and delete | What is the right method to delete all the memory allocated here?
const char* charString = "Hello, World";
void *mem = ::operator new(sizeof(Buffer) + strlen(charString) + 1);
Buffer* buf = new(mem) Buffer(strlen(charString));
delete (char*)buf;
OR
const char* charString = "Hello, World";
void *mem = ::op... | The correct method is:
buf->~Buffer();
::operator delete(mem);
You can only delete with the delete operator what you received from the new operator. If you directly call the operator new function, you must also directly call the operator delete function, and must manually call the destructor as well.
|
6,784,152 | 6,784,176 | Does this code leak memory? (references, new, but no delete) |
Possible Duplicate:
Does using references instead of pointers, resolve memory leaks in C++?
When I ask this question
Does using references instead of pointers, resolve memory leaks in C++?
A new question appears and I ask it in this post.
Does this code leak memory?
class my_class
{
...
};
my_class& func()
{
my... | Yes, it does leak memory. Everything that was created by new has to be destroyed by delete. There's new in your code, but no delete. That immediately means that the newed memory is leaked.
|
6,784,334 | 6,784,379 | compiling wxWidgets with c++0x flags | While trying to compile wxWidgets-2.9.1 from source with c++0x flags using gcc-4.6. I came across an error
narrowing conversion of '128' from 'int' to 'char' inside { } [-fpermissive]
in the file src/gtk/dcclient.cpp. The error comes from the following files:
src/gtk/bdiag.xbm
src/gtk/cdiag.xbm
src/gtk/fdiag.xbm
src/... | unsigned char, signed char and char (also known as 'plain char') are three different types. There is no conversion between unsigned char* and char*.
|
6,784,448 | 6,784,539 | Crazy C++ template - A template to access individual attributes of a class | I am a novice C++ programmer, but I thought I know enough about C++ until today when I came across code like this at work and failed to understand how it actually works.
class Object
{
};
template <
class PropObject,
class PropType,
PropType PropObject::* Prop
>
class PropReader
{
publ... | C++ templates are well-known for taking types as arguments, but they can also be parameterized over other types of data as well. For example, you could templatize a class over an integer, as shown here:
template <typename T, unsigned int N> class Array {
private:
T array[N];
public:
/* ... */
};
Templates ca... |
6,784,509 | 6,784,557 | mscoree.dll's GetRequestedRuntimeInfo() causing improper TargetFrameworkDirectories - how to debug? | I'm having a problem where my .Net build system is looking in the wrong folders for its framework references. The machine has .Net 4.0 and Visual Studio 2010 installed, and this problem happens on projects where the .Net version is less than 4.0 (my example is in .Net 3.5). The problem looked like build issues, but d... | Mscoree.dll is not an oracle. Use SysInternals' ProcMon utility to find out where your machine's registry is toasted. Best to compare the trace against a machine that's okay to quickly narrow it down.
|
6,784,518 | 6,784,567 | Problem passing C++ comparator functor as a parameter | Suppose I have a template class called LinkedList that also contains a method called Sort
I want to be able to have a default comparator which is assuming the type T can be compared with the < operator.
However, I want to be able to override that for other types.
This is part of a custom library that I'm extending. N... | You cannot say template <class T, class Comparator<T>>, i.e. have one template parameter be itself a parameter of another parameter. Do it like the standard library does it and use default parameters:
template <class T, class Comparator = std::less<T>>
class MyClass
{
...
}
Also, Comparator is going to be an object ... |
6,784,523 | 6,787,160 | Intel TBB Parallelization Overhead | Why does Intel Threading Building Blocks (TBB) parallel_for have such a large overhead? According to section 3.2.2 Automatic Chunking in the Tutorial.pdf its around half a millisecond. This is an exert from the tutorial:
CAUTION: Typically a loop needs to take at least a million clock
cycles for parallel_for to impr... |
From what I have read so far TBB uses the threadpool (pool of worker threads) pattern internally and it prevents such bad overheads by only spawning worker threads once initially (which costs hundreds of microseconds).
Yes, TBB pre-allocates threads. It doesn't physically create and join worker threads whenever it se... |
6,784,987 | 6,785,608 | Loki's SetLongevity function seems unsafe to me, is that so? | There is a global variable called "pTrackerArray", which is used in Loki's SetLongevity function.
Declaration of pTrackerArray:
typedef std::list<LifetimeTracker*> TrackerArray;
extern LOKI_EXPORT TrackerArray* pTrackerArray;
Definition of SetLongevity:
template <typename T, typename Destroyer>
void SetLongevity(T* p... | As shown, obviously not. However, if I am reading the rest of that file correctly, SetLongevity is, ultimately, only ever called from within a function that is itself properly wrapped in a mutex [provided you requested that the singleton be thread-safe, obviously]. So while that particular function has issues, its us... |
6,785,003 | 6,785,283 | Pointer class member and deleting responsibilities | If my class has a pointer of some sort that can be set by the class clients, how should I deal with deletion?
Example:
class A {
};
class B {
public:
void setA(A* a) {
this->a = a;
}
private:
A* a;
};
How should be the destructor of the class B? Should it delete a? As I see, there are two way a user c... |
How should be the destructor of the class B? Should it delete a?
You, the author of the class, decides of its semantics. Don't think in terms of pointers, references, and deletes. Think in terms of design: what's the relation between A and B? What does B needs a A for?
Two common types of relation are delegation and ... |
6,785,018 | 6,792,778 | Can I run code *after* a built-in wxWidgets event is handled? | I suspect there must be a built-in way to do this, but my Google-fu has failed me.
I'm using a wxScrolledWindow, and I have to paint an unscrolled background picture behind the contents each time the window is scrolled. I've made a scroll handler like this...
void homewindow_t::onScroll(wxScrollEvent &evt) {
Refres... | The only general solution I've found to running code after an event is handled is to post a second, different event to the event queue before skipping the current event (so that it gets handled by the default handler), and handle that when it comes up.
However, perusing the wxWidgets source code, I've found an answer t... |
6,785,214 | 6,785,947 | How to embed a file into an executable file? | I have two problems, the first has been solved.
Current problem
If I embed a file that requires a library to load it, such as a jpeg image or a mp3 music, I will need to use the file as input to the library. However, each library is different and uses a way to get a file as input, the input may be the file name or a FI... | I think that for this to work with MinGW you'll need to remove the leading underscore from the names in the .c file. See Embedding binary blobs using gcc mingw for some details.
See if using the following helps:
extern char binary_data_txt_start;
extern char binary_data_txt_end;
If you need the same source to work fo... |
6,785,290 | 6,785,367 | Should we use constexpr everywhere we can? | We obviously can't make everything constexpr. And if we don't make anything constexpr, well, there won't be any big problems. Lots of code have been written without it so far.
But is it a good idea to slap constexpr in anything that can possibly have it? Is there any potential problem with this?
| It won't bother the compiler. The compiler will (or should anyway) give you a diagnostic when/if you use it on code that doesn't fit the requirements of a constexpr.
At the same time, I'd be a bit hesitant to just slap it on there because you could. Even though it doesn't/won't bother the compiler, your primary audienc... |
6,785,524 | 6,791,135 | Do something every N seconds in sync with the Windows system clock | There are plenty of tips on how to do something every N seconds, just nothing I have found that explicitly says whether any of these methods slowly drift out of synchronisation with the system clock due to latencies.
I have a multi-threaded application running on Windows. I need to know that within as few milliseconds ... | CreateWaitableTimer and SetWaitableTimer let you wait (WaitForSingleObject, or completion port, or anything that waits) rather than sleep.
Plus, you can give it a precise absolute time, or a relative time, whichever you want. If you want precisely N seconds after 1AM, give it an absolute time of 1AM+N seconds.
Plus, it... |
6,785,885 | 6,786,589 | Extensible First Person Shooter in C++? | I've recently become interested in the study of AI programming and how it relates to games. I'm interested to see what it's like to create AI for a first person shooter-type game with C++.
So, that leads me to my question. I would rather not spend my time writing a complete FPS just for the purpose of practicing AI des... | You might want to start with the Source or Unreal engines, and then use their bot APIs or scripting plugins to experiment with writing character code.
For example, there are lots of bots for the FPS CounterStrike. Alien Swarm also shipped with the source code as part of its SDK, so you could start with the AIs there a... |
6,785,894 | 6,785,907 | Erasing element from multilevel unordered_map? | I have the following code where I wanted to eliminate the element I created initialy with the value 10. I'm having trouble setting up an iterator and erasing it. How is it done?
#include <iostream>
#include <boost/unordered_map.hpp>
using namespace std;
int main()
{
typedef boost::unordered_map<int, boost::unorde... | You have one too many [0]:
_3d[0][0][0].begin();
// should be:
_3d[0][0].begin();
Further, map_it is a type, not a variable; you need to declare a variable of type map_it and assign to or initialize that variable.
The type of _3d[0][0].begin() is simply boost::unordered_map<int, int>::iterator (or const_iterator); th... |
6,786,106 | 6,786,498 | Crashes after converting C++/Win32 console app to DLL | I've recently converted a highly threaded, unmanaged Win32 C++ console application (MediaServer.exe) to an unmanaged Win32 DLL (MediaServer.dll). I'm hosting and debugging this DLL in a separate unmanaged Win32 console app, and everything compiles and runs, but after a minute or so, I'll get a random crash, in a place ... | I would say you are initializing memory in DLL_THREAD_ATTACH instead of DLL_PROCESS_ATTACH. The situation would cause you to use a pointer or memory that has been allocated in another thread than the executing thread.
The other thing would be to check your loading of your dependencies for the DLL.
Let me explain. The C... |
6,786,138 | 6,786,152 | Structure alignment in GCC (should alignment be specified in typedef?) | Sorry for a stupid question, but if I need to ensure the alignment of a structure / class / union, should I add attribute((aligned(align))) to typedef declaration?
class myAlignedStruct{} __attribute__ ((aligned(16)));
typedef myAlignedStruct myAlignedStruct2; // Will myAlignedStruct2 be aligned by 16 bytes or not?
|
should I add attribute((aligned(align))) to typedef declaration?
No... typedefs are just pseudonyms or aliases for the actual type specified, they don't exist as a separate type to have different alignment, packing etc..
#include <iostream>
struct Default_Alignment
{
char c;
};
struct Align16
{
char c;
} __... |
6,786,264 | 6,786,615 | State Machine - Structure To Hold States, Events and pFuncs | If I make a state machine and want to use an interface like this:
AddState ( state1, state2, Key_UP );
AddEvent ( Key_UP );
AddEventFunction ( Key_UP, &UP_Function);
AddStateFunction ( state1, &State1_In_Function, &State1_Out_Function);
AddStateFunction ( state2, &State2_In_Function, &State2_Out_Function);
State1_In_F... | You could simply store them on the stack, though it's a bit more difficult :)
Still, it's an amusing solution, so here you go. The underlying principle is to play with decorators and mutability. Example of code:
State state1, state2; // creates a state
Event KEY_UP;
Event KEY_DOWN;
Transition t0(state1, KEY_UP, state2... |
6,786,332 | 6,786,612 | Using functions in a dll in c++? | I have created a dll in c++ using __declspec(dllexport) before class name. Now when i try to use it in another c++ program it crashes in between. When i debugged it i found that the function pointer is not initialized at all. help me plz.
using namespace std;
typedef void (*func)();
int main()
{
func funcpoint... | First of all use DUMPBIN /EXPORTS yourdll.dll to see if the function you expect to be exported is actually exported and its exact name. If you find the name "mangled" you probably need to declare the function as extern "C". Once you have determined the name the way you go is correct. Check also the HINSTANCE xyz became... |
6,787,213 | 6,787,610 | Writing a function using a macro with variable number of arguments | How do you write a macro with variable number of arguments to define a function? Suppose that we define the class class1 with 2 parameters and class class2 with three parameters.
class class1 {
public:
int arg1;
int arg2;
class1(int x1, int x2): arg1(x1), arg2(x2) {}
};
class class2 {
public:
int arg1;
... | First of all you should improve your formatting/code. Your code lacks "class" keywords and semicolons after classes definitions - when you post a snippet make sure it's proper code, because some people (i.e. me) will try to compile it.
Second of all, dont use function template specialization. If macros are evil, then t... |
6,787,290 | 6,787,323 | Getting the address of a pointer | My apologies, I know there are a million questions on pointers, arrays etc. although as basic as this is I just can't seem to find anything pointing (ha ha!) to an answer.
I've got a pointer that is initialised to point to a chunk of memory, I understand that I can access this memory similar to how I would an array:
ch... | &mMem[5] is the address of the 5th element. The reason why you get a printout of the memory from there is because they type of &mMem[5] is char*, but strings in legacy C are also of char*, so the << operator simply thinks that you want to print a string from there. I would try casting the pointer to a void* before prin... |
6,787,302 | 6,787,347 | What's wrong withe following C code! | I tried the following code in C as well as C++ .file1 is a c file .file2 is a c++ file and file3 is a header file for name magling.
file1.c
#include<stdio.h>
#include<stdlib.h>
#include "file3.hpp"
int main(int argc,char **argv)
{
int a[5];
int i;
for(i=0;i<5;i++)
a[i] = i;
printf("%d",a[17]);
return 0;
}
file2.c... | As one of your files is compiled as c++ use g++ for linking phase.
See: What is __gxx_personality_v0 for?
|
6,787,372 | 7,535,805 | Pixelvalues of an image in a 2D double* pointer for calculating FFT_2D | I want to calculate the FFT of an image, I read the image, and the ITK SmartPointer is called “imagen”.
The input of the function I use for calculating the FFT (fftw_plan_dft_r2c_2d) need a 2D double* pointer as input. Because of that I do that:
double *in = (double*) imagen.GetPointer(); // conversión de itk.smartpoin... | ITK also has FFT's available.
Example of the framework is:
http://www.vtk.org/Wiki/ITK/Examples/SpectralAnalysis/VnlFFTRealToComplexConjugateImageFilter
There is another very very similar options to use FFTW. Just build ITK with the USE_FFTW flag set to on. (NOTE : The USE_FFTW option is under "Advanced" settings ... |
6,787,604 | 6,787,668 | Variable assignment and usage in the same expression | I encountered a line of code:
int a = 10;
int b = 40;
a = a + b - (b = a);
cout << a << " " << b << endl;
I cannot understand what happens in this code.
Can anyone explain for me?
| Undefined behavior. the value of b is changed and used for computation without an intervening sequence point. The results of the program are unpredictable - it can print anything or crash, or do do some nasty system calls.
Except where noted, the order of evaluation of operands of individual
operators and subexpress... |
6,787,943 | 6,825,158 | Overloaded operator delete in dylib replaces system operator in OSX | I have a dylib written in C++ which has an overloaded operator new and delete.
When a link my cocoa application with my dylib I have a BAD_ACCESS_ERROR because Cocoa tries to free memory with my operator delete from my dylib.
So I think that I can use the unexported_symbols_list options, but what is the decorated names... | You can use the nm tool to extract the exported symbols from your lib and c++filt to demangle then and find which ones correspond to the mentioned operators.
|
6,788,169 | 6,788,385 | Why doesn't the compiler perform a type conversion? | Consider the following code.
#include <iostream>
#include <string>
struct SimpleStruct
{
operator std::string () { return value; }
std::string value;
};
int main ()
{
std::string s; // An empty string.
SimpleStruct x; // x.value constructed as an empty string.
bool less = s < x; // Error her... | operator< for std::string is a function template. The overloads are:
template<class charT, class traits, class Allocator>
bool operator< (const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool o... |
6,788,252 | 6,788,446 | Linker Errors due to being Already Defined | It has been about a year since I wrote any .dll plugins that use LibCurl, but I decided to start on another one tonight. Unfortunately, I have been combating the same linker errors for almost 4 hours now, and I am completely lost.
I am statically building LibCurl, and it appears to be fine for the most part, except I a... | Problem was my .dll was /MT while the libcurl was /MD. Also, I had initially blocked "libcmt", so when I was switching libcurl to /MT, it was spewing errors.
|
6,788,441 | 6,788,485 | C++ input and output streams | Is it possible for C++' input stream to read from a chatroom like msn , yahoo and things like that and return some sort of message?
just wondering as i search the net and most of it require client and server.
I am new to this
| No; the two concepts have only a passing resemblance.
C++ iostreams are a very low-level construct for reading bytes to and from operating system devices such as file systems, fifos, sockets, etc.
Chat services are implemented over high-level protocols such as XMPP, which operate over TCP via socket APIs provided by t... |
6,788,474 | 6,789,062 | Linking problem due to changing the cpp directory | I am a java programmer; so I'm facing a lot of problems when it comes to c++ due to the linking stuff and so on. The problem basically is that I want to re-factor a single file (Transformation.cpp) into (TrasnformationBackend.cpp), (TrasnformationFrontend.cpp) and a header file. As you may see, I needed to declare a gl... | An extern declaration in a header only tells the compiler that that variable will be defined in a compilation unit. It does not actually create that variable / allocate storage for it.
If you have in your .h:
extern int globalvar;
You need in one, and only one, of your .cpp files:
int globalvar;
Otherwise compilation... |
6,788,960 | 6,789,169 | clock_gettime returns some extrange values | I'm trying to profile a program with this class:
namespace smtx{
class CPerformance_clock
{
timespec t1;
timespec diff(timespec start, timespec end)
{
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
... | The fluctuation is caused by the OS scheduler. It pauses your process and gives a chance to an other process to run.
Can you report back results with CLOCK_PROCESS_CPUTIME_ID?
|
6,788,975 | 6,789,021 | Boost regexp how to parse Cookie string into map<string, string>? | So Cookie strings look like remixsettings_bits=1; wysiwyg=1,2,3,abc; remixclosed_tabs=0; remixgroup_closed_tabs=786432; remixlang=0; remixchk=5; remixsid=35d4f9907281708019490d07728c27ca5c10e5de7a869c322222225e3219e; audio_vol=100
I wonder how to parse tham into map name <-> value?
| Try this regex: (\w+)=([^;]*)
\w+ - alphanumeric one or more repetitions
=
[^;]* - any character except ; any number of repetitions
Result:
|
6,789,122 | 6,818,433 | Boost Geometry: using a 2D polar coordinate system | Im playing around with the new geometry library made available in boost 1.47 and wanted to know if it is possible to define a 2D polar system.
In the header files and documentation I found a definition for a polar system but when trying to use it with the sample code below I'm getting compilation errors:
using namespac... | Well, answering my own question (hope that this is ok) after a bit more of research: It seems that I got the wrong idea about coordinate systems in the geometry library's sense. The different coordinate systems seem to specify the intrinsic geometry like the surface of a sphere where for example the distance between tw... |
6,789,134 | 6,790,391 | Why isn't operator new forced to take argument as "const size_t"? | Not using below thing anywhere but still this question was in my mind for long.
void* operator new (size_t size)
{
// distort `size` to other value
return malloc(size);
}
Having know that above may not be a well-defined behavior for overloaded new (say if the size is decreased), Why doesn't standard force compiler... | The type of the argument in both cases, const std::size_t and plain std::size_t is std::size_t. The standard dictates that when processing a function signature in a declaration (later on definitions), the const is dropped from the type. The specific
paragraph is in §8.3.5/3:
[...] After producing the list of paramet... |
6,789,392 | 6,789,450 | Windows File Systems? | I have finished developing an archive format in managed C# that is way too flexible to be just an archive. I wish to use it as a file system.
It is well organized, very fast, and has both low-level and high-level API functions. It supports on-the-fly encryption and compression, password protection, Windows Explorer-spe... | Well, it is possible, once I have tried this approach. I've based on these samples: http://www.acc.umu.se/~bosse/
p.s. Also you don't need file system, you need a driver
|
6,789,479 | 6,789,573 | C++ - best way to do an array of different implementations | I am trying to practice OO design. I've made the following classes, which will eventually let a user pick a temperature unit type (like fahrenheit) from a list, and convert celcius temperatures to their chosen temperature:
TemperatureUnits.h:
#include "fahrenheittemperatureunit.h"
#include "kelvintemperatureunit.h"
#in... | I am pretty sure I used to do this type of thing using Java.
Java objects are references. C++ objects are values. Simply convert to a reference, and then you will have more equivalent code. Oh, and a Java list is a C++ vector. A C++ list is a linked list.
Quite simply, do not bother to carry over any Java knowledge to... |
6,789,517 | 6,791,189 | Boost spirit: how to parse string of value pairs into map<string, string> and back? | So having a string like remixsettings_bits=1; wysiwyg=1,2,3,abc; remixclosed_tabs=0; remixgroup_closed_tabs=786432; remixlang=0; remixchk=5; remixsid=35d4f9907281708019490d07728c27ca5c10e5de7a869c322222225e3219e; audio_vol=100
I wonder how to parse tham into map name <-> value using boost::spirit and than be capable t... | This should do the trick, parsing pairs and printing the results using Karma, although we should probably both go read Hartmut's article!
#include <boost/spirit/include/qi.hpp> // Parsing
#include <boost/spirit/include/karma.hpp> // Generation
#include <boost/fusion/adapted/std_pair.hpp> // Make std::pa... |
6,789,856 | 6,790,009 | C++ writing and reading doubles from a binary file | I want to perform disk I/O operations for a program that takes too much RAM.
I use matrices of doubles and think writing them to disk as bytes is the fastest way (I need to preserve the double precision).
How to do it with portability?
I found this code (here) but the author says it's not portable...
#include <iostrea... |
How to do it with portability?
There are different definitions/levels of portability. If all you ever do is to write these on one machine and read it on the same one, the only portability you are concerned with is whether this code is well-defined. (It is.)
If you want to write portably across several different platf... |
6,790,087 | 6,790,112 | What does a leading :: mean in "using namespace ::X" in C++ | can somebody explain me the difference between the following namespace usages:
using namespace ::layer::module;
and
using namespace layer::module;
What causes the additional :: before layer?
| There would be a difference if it was used in a context such as:
namespace layer {
namespace module {
int x;
}
}
namespace nest {
namespace layer {
namespace module {
int x;
}
}
using namespace /*::*/layer::module;
}
With the initial :: the first x would be visi... |
6,790,175 | 6,790,227 | Uniform way to get object address or NULL in global function | I'm building a tree-based debug/logging system for C++.
Its "user interface" is a macro which passes user-defined message and call site information (file, line, object address) to special function which then performs logging.
The function uses the object address to group messages by object instance.
Currently it looks ... | You can change your macro definition:
#define msg (event_level, message, THIS) \
do_logging_ (event_level, __FILE__, __LINE__, THIS, message)
Usage:
msg (MSG_WARNING, "some text", this); // in member methods
msg (MSG_WARNING, "some text", NULL); // otherwise
|
6,790,659 | 6,790,833 | Using STL Sort within a template function? | I have tried to create a template function that does some weighted sampling within a Monte Carlo simulation. It is below. input_data will either be a statically-allocated array (i.e. data[33]), a dynamically-allocated array, or a vector.
template <class myType>
int init_roulette_calcs(myType &input_data, int inputlen... | If you put in an array, the array name is essentially a pointer to the first element, and the array name + x is the poitner to the xth element - so you have this part correct.
The problem is that this is not the case for a vector, which is why you need to use the .begin() and .end() functions to get the pointer to thes... |
6,790,781 | 6,790,836 | Mutual include in C++ .. how does it work? |
Possible Duplicate:
Proper way to #include when there is a circular dependency?
I am pretty new to C++ and have the question asked in the title. Or more precisely: If A.h includes B.h and B.h includes A.h, I get an error message because "include# file "C:...\A.h" includes itself". File: B.h
I couldn't find a way to ... | Simple: don't let A.h include B.h. And vice-versa.
In general, header files should include as little as absolutely possible. You can use forward declaration to get around a lot of includes. The only time you absolutely must include something in a header is if there are objects that are used as non-references in that he... |
6,790,846 | 6,790,903 | type conversion for struct of array from c++ to c | I have two libraries, from C++ and C, respectively:
lib A in C++:
typedef struct {
char val[4096];
} AString;
lib B in C:
typedef struct STRING_TYPE{
unsigned char *u1_list;
signed int i4_length;
} BString;
If I cannot touch lib A & B code, i.e., cannot add a cast operator in AString class. How to conv... | Something like this:
BString convert(AString const& as)
{
size_t const N = std::min(strlen(as.val), 4096);
BString bs = { new unsigned char[N], N };
std::copy(
static_cast<unsigned char*>(&as.val[0]),
static_cast<unsigned char*>(&as.val[N]),
bs.u1_list
);
return bs;
}
Be sure to docu... |
6,790,864 | 6,793,194 | Unicode string and FreeHGlobal issue? | I tested the code from Stack Overflow question Marshaling unmanaged char** to managed string[], and it works well.
I tried to convert it to Unicode, and then I start getting "The handle is invalid". Why?
My modified code:
_declspec(dllexport) void TestArray(wchar_t** OutBuff, int Count, int MaxLength)
{
for(int i=0... | You are lucky to get the Windows heap manager to catch the bug, you must be using Vista or Windows 7. It is a subtle one and would have been easily missed if you hadn't used wcsncpy(). The problem is that you allocated maxLen bytes for the string. But you need to allocate maxLen characters. Not the same thing when ... |
6,791,433 | 6,791,470 | C++ | void *data[1000] | Is it appropriate way to keeps the pointers in statically allocated array this way in C++?
void *data[1000];
Is the size of void* various on 32 and 64 bit machines?
| It's almost certainly absolutely not appropriate. Void pointers are pretty damn bad to begin with, and mix them with mutable static data, and you have something quite awful. A primitive unwrapped array of a magic number size on top of that, and I'm very glad that I don't have that in my code. Of course, if you have to,... |
6,791,522 | 18,067,147 | Mismatched free()/delete in MsgPack | I try to use Msgpack in my program.
Can someone help me with next example (Streaming feature) from msgpack wiki: http://wiki.msgpack.org/pages/viewpage.action?pageId=1081387 and provide more correct example of using this library with streaming feature.
#include <msgpack.hpp>
#include <iostream>
#include <string>
i... | issue was fixed in new version
https://github.com/msgpack/msgpack/pull/90
|
6,791,845 | 6,791,913 | Is it possible for MapViewOfFile to return the same address twice? | Good morning, Is it possible for MapViewOfFile to return the same address twice? However, UnmapViewOfFile misbehaves when it has to unmap the same address twice. We get an Error 487 : Invalid address. Here is some pseudo code which shows how we are using MapViewOfFile and UnMapViewOfFile:
retval = UnmapViewOfFile(Tm... | After you did UnmapViewOfFile that virtual address is free to be used for other operation. So yes, the subsequent MapViewOfFile may return this address.
|
6,791,965 | 6,792,412 | Boost signals.hpp causes several compile time errors on Visual Studio 2010 | I'm trying to use boost.signals library. I know that to use it, first I need to build the boost since signals is not a header only library. I followed the steps described under this topic to build the boost and did not get any errors. However, when I include boost/signals.hpp I get several C2146, C2238, C2447 errors. M... | You would get a linker error if it were a problem with how you built it. This is compile time.
Try making a simple example for people to try.
My guess would be Qt. If you are using Qt, there may be namespace conflicts.
How do I get Boost.Signals to work with Qt?
|
6,792,134 | 6,792,178 | Function Parameters as Const Reference | Is there any reason not to send a parameter as a const & , instead of by value, when it will not be changed and no copy will be made? My understanding is that a const by value parameter is the same as without the const (and won't overload each other) so it will still be copied.
I know it's best for large objects to sen... | There's generally nothing wrong with passing read-only arguments as const-references, and for any sort of heavy-weight class that's surely the most efficient way to do it.
You might want to consider passing primitive types by copy, though, because there making the reference might actually incur more cost than just copy... |
6,792,143 | 6,792,463 | getrusage function on embedded linux | I have one bench marking application in which I am evaluating a C++ framework.
I am looking for the time and memory consumption. On linux, to get the memory occupied by the current program, I am using getrusage function. It works perfectly on my machine.
Problems arise when I cross compile this application into an arm... | Linux versions prior to 2.6.31.14 do not support the ru_maxrss field of struct rusage. Linux versions starting with 2.6.32 do. I suppose that you are running an earlier version in your embedded system than you are on your desktop.
|
6,792,462 | 6,792,576 | C++ iostream >> operator behaves differently than get() unsigned char | I was working on a piece of code to do some compression, and I wrote a bitstream class.
My bitstream class kept track of the current bit we are reading and the current byte (unsigned char).
I noticed that reading the next unsigned character from the file was done differently if I used the >> operator vs get() method in... | If you aren't parsing text, don't use operator>> or operator<<. You'll get weird bugs that are hard to track down. They are also resilient to unit tests, unless you know what to look for. Reading a uint8 for instance will fail on 9 for instance.
edit:
#include <iostream>
#include <sstream>
#include <cstdint>
void t... |
6,792,518 | 6,795,446 | Multiple indexing with big data set of small data: space inefficient? | I am not at all an expert in database design, so I will put my need in plain words before I try to translate it in CS terms: I am trying to find the right way to iterate quickly over large subsets (say ~100Mo of double) of data, in a potentially very large dataset (say several Go).
I have objects that basically consi... | With Boost.MultiIndex, you don't need as many as 12 indices (BTW, the number of permutations of 4 elements is 4!=24, not 12) to cover all queries comprising a particular subset of 4 keys: thanks to the use of composite keys, and with a little ingenuity, 6 indices suffice.
By some happy coincindence, I provided in my bl... |
6,792,859 | 6,792,944 | Schedule task on precise periods in Linux or Windows | I have this weird question.
I would like to know if it is possible to make a program in C/C++ that will run on Linux or Windows and will hook interrupt handler on a system timer set to specific period (2000 times per second, for example) and I want this interrupt to be with highest priority, meaning that it has to be e... | Yes, you can do that in MS-DOS because it is not a multi-user or multi-tasking operating system. However, the same thing will not work in Windows because it is a mult-user and multi-tasking operating system. It's also not real-time, which means there's no guarantee that your task will be executed exactly when you ask f... |
6,793,065 | 6,793,121 | Understanding the algorithm of Visual C++'s rand() function | In C/C++, rand() and srand() are usually used by us when we want to get a random integer. But when I tried to rewrite it myself, I found it difficult to understand the algorithm. The function is very easily written in only a few lines, but the formula is misunderstanding.
The main formula:
ptd->_holdrand = ptd->_holdra... | It's just modular arithmetic. You're multiplying and adding to a number which is taken modulo 2^32 (for example), and returning the upper 16 bit as your "random" number. Because you're multiplying and adding numbers which are coprime to the modulus, this creates sort of uniformly distributed numbers.
The careful choice... |
6,793,137 | 6,793,195 | Question on operator+ overload of random access iterator, in template | I would like to overload the "+" operator of iterator in list class, something like
list<double>::iterator operator+(const list<double>::iterator& it, int n)
This works well. However, when I try to implement it as template, like
template<class T>
typename list<T>::iterator operator+(const typename list<T>::iterator& ... | The problem is that the argument is not deducible in that context.
template<class T>
typename list<T>::iterator operator+(const typename list<T>::iterator& it, int n);
When you use an iterator there, the compiler would have to generate all possible instantiations of list with any given type, and try to match an intern... |
6,793,161 | 6,793,209 | When not to use include guard in header file? | We all know when to use include guard, but when shall we not use it in our project?
Recently, I saw a project with mix compilation (CUDA + GCC), one header file (CUDA file) is deliberately left without include guard. I am just curious about it.
| There are 2 scenarios off the top of my head:
when you want to turn on/off debugging capabilities (as how assert.h works)
for 'x-macro' type of functionality where you have the include file perform 2 parts of problem, such as defining an enum then defining an array of stringified names corresponding to the enums
|
6,793,262 | 6,793,390 | Why dereferencing a null pointer is undefined behaviour? | According to ISO C++, dereferencing a null pointer is undefined behaviour. My curiosity is, why? Why standard has decided to declare it undefined behaviour? What is the rationale behind this decision? Compiler dependency? Doesn't seem, because according to C99 standard, as far as I know, it is well defined. Machine dep... | Defining consistent behavior for dereferencing a NULL pointer would require the compiler to check for NULL pointers before each dereference on most CPU architectures. This is an unacceptable burden for a language that is designed for speed.
It also only fixes a small part of a larger problem - there are many ways to ha... |
6,793,482 | 6,793,773 | Bit Shifting in Place | I was just wondering if there was a way to bit shift a number "in place"?
I've googled exactly that, and I can't find anything that pertains to what I want to do.
Say I have the number 0b01001101, and I want to shift it twice to the right "in place", appending any numbers that fall off to the beginning. So it would loo... | You want to implement a rotational shift
Here's a templatized version that should work with all types of ints (including shorts, chars, ints, and unsigned/signed alike).
template<class T>
T rotate_shift_right(T x, int shift)
{
if ((shift > 0) && (shift < (sizeof(x)*8)))
{
x = ((unsigned)x >> shift) | (x... |
6,793,512 | 8,551,190 | Will web development in c++ cgi really a huge performance gain? | I'm asking the question after reading this article
http://stevehanov.ca/blog/index.php?id=95
Also isn't it a penalty to use cgi instead of fastcgi ?
Update: why some people do pretend like in answer "that you get 20-30% performance improvement" ? Is it pure guess or is this number coming from solid benchmark ? I have l... | I've done webdev in a few languages and frameworks, including python, php, and perl. I host them myself and my biggest sites get around 20k hits a day.
Any language and framework that has reasonable speed can be scaled up to take 20k hits a day just by throwing resources at it. Some take more resources than others. (Pl... |
6,793,728 | 6,795,062 | Qt4: Making fullscreen window impossible to get around (a lock screen)? | My application is an OS lock screen (like GDM's lock screen or KDE's), so I'm trying to make it function like one.
I am trying to make my application's window hover above all other windows and disable/intercept all keyboard shortcuts (ALT-TAB, CTRL-ALT-D, etc.) that would cause it disappear.
Is there any way to do this... | I don't know how to do it with Qt, but what you are looking for is called grabbing. You can grab the pointer input device as well as the keyboard.
Edit: Looking in to the Qt4 docs, have you tried to use QWidget::grabMouse? It looks like this function does exactly what you want.
|
6,793,855 | 6,793,876 | C++ basic string exception | If I just want to throw a string, isn't there a built in type somewhere so that I can just do
throw standard_exception("This is wrong!");
Or do I have to define such a standard exception that derives from exception myself? I know it is very simple to do so, I just thought this would be so common that it would be defi... | std::runtime_error and std::logic_error (both derived from std::exception) both have constructors that take strings and override the what() member function to return the provided string.
|
6,793,863 | 6,794,017 | how to sort elements by one measure | In C++ I don't quite understand how to sort elements, by defining a custom function.
Cppreference.com says that for the comparison function:
comp - comparison function which returns true if the first argument
is less than the second.
bool cmp(const Type1 &a, const Type2 &b);
Naturally I would think that for s... | There are many ways that you can do this.
If you happen to know that the second argument to z_distance is always going to be some fixed value, then you could convert the function into a comparator by writing an auxiliary function that actually does the comparison. For example:
bool CompareByDistance(const boost::files... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.