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 |
|---|---|---|---|---|
2,561,242 | 2,579,243 | shared memory STL maps | I am writing an Apache module in C++. I need to store the common data that all childs need to read as a portion of shared memory. Structure is kind of map of vectors, so I want to use STL map and vectors for it. I have written a shared allocator and a shared manager for the purpose, they work fine for vectors but not for maps, below is the example:
typedef vector<CustomersData, SharedAllocator<CustomersData> > CustomerVector;
CustomerVector spData; //this one works fine
typedef SharedAllocator< pair< const int, CustomerVector > > PairAllocator;
typedef map<int, CustomerVector, less<int>, PairAllocator > SharedMap;
SharedMap spIndex; //this one doesn't work<
I get compile time errors when I try to use the second object (spIndex), which are someting like:
../SpatialIndex.h:97: error: '((SpatialIndex*)this)->SpatialIndex::spIndex' does not have class type
It looks like the compiler cannot determine a type for SharedMap template type, which is strange in my opinion, it seems to me that all the template parameters have been specified.
Can you help?
Thanks
Benvenuto
Hello, thanks for your comments.
SpatialIndex is the class that contains the container, it basically made by the container (SharedMap spIndex; which is a member of SpatialIndex), and two methods, update and getData.
Whithin the update method the following line of code gives the compiler error above:
int spKey = this->calculateSpKey( customer.getLat(), customer.getLong() );
this->spIndex[spKey].push_back(customer);
Varying the sintax of the last line varies the error the compiler gives, but basically it says that it cannot understand which type variable spIndex is, or that it cannot find the appropriate overload constructor for this class.
| Please post the line on which you initialize spIndex. The compiler error 'does not have class type' generally means that you're referring to a function as though it were a field, which in this case probably means that your compiler has mistaken spIndex for a function somehow. I haven't seen the code, but I bet the Most Vexing Parse is going to come up somehow.
|
2,561,368 | 2,561,377 | Illegal token on right side of :: | I have the following template declaration:
template <typename T>
void IterTable(int& rIdx,
std::vector<double>& rVarVector,
const std::vector<T>& aTable,
const T aValue,
T aLowerBound = -(std::numeric_limits<T>::max()), //illegal token on right side of '::' shows here
bool aLeftOpen = true) const;
Which throws the illegal token error as noted, on the line with "-(std::numeric_limits::max())". I got this code from some old linux source that I'm trying to compile on Windows. Any idea what the issue is?
Edit: It also fails using min(), and the compiler output is:
Error 92 error C2589: '::' : illegal token on right side of '::' c:\projects\r&d\prepaydll\include\cfcdefault.h 216 PrepayDLL
Error 93 error C2059: syntax error : '::' c:\projects\r&d\prepaydll\include\cfcdefault.h 216 PrepayDLL
Line 216, is the line previously mentioned.
| My guess is that max has been made a macro. This happens at some point inside windows.h.
Define NOMINMAX prior to including to stop windows.h from doing that.
EDIT:
I'm still confident this is your problem. (Not including <limits> would result in a different error). Place #undef max and #undef min just before the function and try again. If that fixes it, I was correct, and your NOMINMAX isn't being defined properly. (Add it as a project setting.)
You can also prevent macro expansion by: (std::numeric_limits<T>::max)().
On a side note, why not do std::numeric_limits<T>::min() instead of negating the max?
|
2,561,471 | 2,561,535 | Is there any cross-platform threading library in C++? | I'm looking for some easy to use cross-platform threading library written in C++.
What's your opinion on boost::thread or Pthreads?
Does Pthreads run only on POSIX compliant systems?
What about the threading support in the Qt library?
| Boost.Thread is the draft for the coming standard threading library of the C++ language. Knowing that, I prefer to use it as it provide some strong guarantees (because it becomes standard).
Update: Now that we have the standard threading libraries, some more precisions. Some boost constructs, like boost::shared_mutex, have not been standardised (but might be later). However the standard library exploit the move semantic better. Good to know before choosing a library. Also, using C++11 threading library requires a compiler that provides it. It's not the case for all compilers today.
Update:
Now [Nov2012] most of the Standard compilers provide C++11 threading library. VS2012, GCC4.8 and Clang3.1 have support for threads and synchronization primitives and atomic operations.
For complete implementation you can also use just thread by Anthony Williams. It is C++11 compliant library supported on Windows/Mac and Linux.
Links for status of C++11 features with various compilers:
GCC 4.8 - http://gcc.gnu.org/gcc-4.8/cxx0x_status.html
Clang3.1 - http://clang.llvm.org/cxx_status.html
VS2012 - http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx
|
2,561,594 | 2,561,742 | GDI polyline partial output when printing | I'm seeing a strange problem when calling Win32 GDI Polyline() when printing out. On screen it all looks ok, however if printing it will stop the polyline when it encounters a large value. I think this discrepency is due to the scaling for printing yielding larger POINT values.
It appears as if the polyline stops drawing if it hits a value > 32767, ie, as if there is a 16 bit limit on the POINT values.
I've seen some hear-say online about 16 bit values however no definitive reasoning. I would like to find out why this is occuring before thinking about a potential solution.
| According to MS documentation, this would occur in Windows 9X, where the coordinates are 32-bit but the underlying implementation is 16-bit and the values are just truncated. In practice, I already had the same problem years ago in non-9X Windows versions, but the situation was a bit different from yours, I believe. My "big" coordinates weren't there because the DC resolution was high, but because I had lines with one end inside the screen and the other far away outside - and the behaviour was that the visible part would not intercept the screen edge at the right point. In my case I solved the problem by clipping the lines before drawing.
Maybe your problem is a bug in the specific printer driver you're using, have you tried to use another one?
http://books.google.com/books?id=-O92IIF1Bj4C&lpg=PA359&ots=Sw0FC-9lk7&dq=gdi%2016%20bit%20coordinates&pg=PA359#v=onepage&q=gdi%2016%20bit%20coordinates&f=false
|
2,561,726 | 2,894,877 | How to get MAC address of bluetooth HID device? | how can I get the MAC address of a bluetooth device which connected as HID device?
I have handle to the device
Handle = CreateFile(didetail->DevicePath, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, NULL);
but I can't find how to get the MAC address.
C++; Windows
| At first I was going to say you should pipe the results of ipconfig/all into a file, but then I found this:
http://www.codeguru.com/cpp/i-n/network/networkinformation/article.php/c5451/Three-ways-to-get-your-MAC-address.htm
Scroll halfway down to GetAdaptersInfo, that should be what you're looking for.
|
2,561,799 | 2,561,817 | NULL pointer comparison fails | I'm initializing in a class a pointer to be NULL. Afterwards I check if it is NULL in the same class. But it's not always 0x0. Sometimes it's 0x8 or 0xfeffffff or 0x3f800000 or 0x80 or other strange stuff. In most case the pointer is 0x0 but sometimes it gets altered somehow.
I'm sure that I'm not changing it anywhere in my code. Is there a way it gets changed by "itself"?
Here's my code:
MeshObject::MeshObject()
{
mesh.vertexColors = NULL;
}
MeshObject::MeshObject(const MeshObject &_copyFromMe)
{
SimpleLog("vertexColors pointer: %p", _copyFromMe.mesh.vertexColors);
if (_copyFromMe.mesh.vertexColors != NULL)
{
SimpleLog("vertexColors");
this->mesh.vertexColors = new tColor4i[_copyFromMe.mesh.vertexCount];
memcpy(this->mesh.vertexColors, _copyFromMe.mesh.vertexColors, _copyFromMe.mesh.vertexCount * sizeof(tColor4i) );
}
}
My application crashes, because vertexColors wasn't initialized and is being copied. However it is NULL and shouldn't be copied.
Thanks.
| This:
MeshObject::MeshObject(const MeshObject &_copyFromMe)
is a copy constructor. Because it is a constructor, it too should be setting the vertexColors member to some known & hopefully valid value, but it isn't, unless the value in the thing being copied is not NULL. But what if it is NULL? Basically, your if() needs an else.
|
2,561,927 | 2,564,763 | Converting C++ string/wchar_t* to C# string? | Question: I need to call a C# dll from a C++ executable.
I use COM, and it works fine for int, long and bool. But I can't get a string along...
The IDL file says it's a BSTR, but I can't pass it correctly, and neither retrieve one.
I tried using wchar_t* and using sysalloc as I did with VB6, but that doesn't seem to work.
Anybody knows how, or what might be wrong ?
| If you're using ATL you can do this:
std::string theString = "hello";
CComBSTR bstr(theString.c_str());
DoSomething(bstr); // Function that takes a BSTR as an argument
Or if no ATL:
const wchar_t* theString = L"hello";
BSTR bstr = SysAllocString(theString);
DoSomething(bstr);
SysFreeString(bstr);
|
2,562,099 | 2,562,111 | Why is only the second array dimension important? | Why when working with two dimensional arrays only second dimension is important for a compiler? Just can't get my head around that.
Thanks
| Because compiler needs to figure out how to access the data from memory. The first dimension is not important because compiler can count the number of items when all other sizes are given.
Examples:
int a1[] = { 1, 2, 3, 4 }
compiler knows to allocate space for 4 integers. Now, with this:
int a2[][] = { 1, 2, 3, 4, 5, 6} }
compiler cannot decide whether it should be a2[1][6] or a2[2][3] or a2[3][2] or a2[6][1]. Once you tell it the second dimension, it can calculate the first one.
For example, trying to access element a2[1][0] would yield different values depending on the declaration. You could get 2, 3, 4 or even invalid position.
|
2,562,176 | 2,562,194 | Storing a type in C++ | Is it possible to store a type name as a C++ variable? For example, like this:
type my_type = int; // or string, or Foo, or any other type
void* data = ...;
my_type* a = (my_type*) data;
I know that 99.9% of the time there's a better way to do what you want without resorting to casting void pointers, but I'm curious if C++ allows this sort of thing.
| No, this is not possible in C++.
The RTTI typeid operator allows you to get some information about types at runtime: you can get the type's name and check whether it is equal to another type, but that's about it.
|
2,562,320 | 2,565,037 | Specializing a template on a lambda in C++0x | I've written a traits class that lets me extract information about the arguments and type of a function or function object in C++0x (tested with gcc 4.5.0). The general case handles function objects:
template <typename F>
struct function_traits {
template <typename R, typename... A>
struct _internal { };
template <typename R, typename... A>
struct _internal<R (F::*)(A...)> {
// ...
};
typedef typename _internal<decltype(&F::operator())>::<<nested types go here>>;
};
Then I have a specialization for plain functions at global scope:
template <typename R, typename... A>
struct function_traits<R (*)(A...)> {
// ...
};
This works fine, I can pass a function into the template or a function object and it works properly:
template <typename F>
void foo(F f) {
typename function_traits<F>::whatever ...;
}
int f(int x) { ... }
foo(f);
What if, instead of passing a function or function object into foo, I want to pass a lambda expression?
foo([](int x) { ... });
The problem here is that neither specialization of function_traits<> applies. The C++0x draft says that the type of the expression is a "unique, unnamed, non-union class type". Demangling the result of calling typeid(...).name() on the expression gives me what appears to be gcc's internal naming convention for the lambda, main::{lambda(int)#1}, not something that syntactically represents a C++ typename.
In short, is there anything I can put into the template here:
template <typename R, typename... A>
struct function_traits<????> { ... }
that will allow this traits class to accept a lambda expression?
| I think it is possible to specialize traits for lambdas and do pattern matching on the signature of the unnamed functor. Here is the code that works on g++ 4.5. Although it works, the pattern matching on lambda appears to be working contrary to the intuition. I've comments inline.
struct X
{
float operator () (float i) { return i*2; }
// If the following is enabled, program fails to compile
// mostly because of ambiguity reasons.
//double operator () (float i, double d) { return d*f; }
};
template <typename T>
struct function_traits // matches when T=X or T=lambda
// As expected, lambda creates a "unique, unnamed, non-union class type"
// so it matches here
{
// Here is what you are looking for. The type of the member operator()
// of the lambda is taken and mapped again on function_traits.
typedef typename function_traits<decltype(&T::operator())>::return_type return_type;
};
// matches for X::operator() but not of lambda::operator()
template <typename R, typename C, typename... A>
struct function_traits<R (C::*)(A...)>
{
typedef R return_type;
};
// I initially thought the above defined member function specialization of
// the trait will match lambdas::operator() because a lambda is a functor.
// It does not, however. Instead, it matches the one below.
// I wonder why? implementation defined?
template <typename R, typename... A>
struct function_traits<R (*)(A...)> // matches for lambda::operator()
{
typedef R return_type;
};
template <typename F>
typename function_traits<F>::return_type
foo(F f)
{
return f(10);
}
template <typename F>
typename function_traits<F>::return_type
bar(F f)
{
return f(5.0f, 100, 0.34);
}
int f(int x) { return x + x; }
int main(void)
{
foo(f);
foo(X());
bar([](float f, int l, double d){ return f+l+d; });
}
|
2,562,373 | 2,562,488 | Is it good to have a member template function inside a non-template class in c++? | I wonder if it is a good practice to have a member template function inside a non-template class in c++? Why?
I'm trying to do something like this
in classA.h:
classA
{
public:
member_func1();
member_func2();
};
in classA.cpp:
template <class T> share_func();
classA::member_func1()
{
call share_func();
}
classA::member_func2()
{
call share_func();
}
I wonder if it is appropriate?
| That's a perfectly legitimate use of template functions. Additionally, there's no problem with using templated member functions of a non-template class. For example:
class A {
public:
void say_hello() { cout << "Hello World" << endl; }
template<T> print_it( T arg ) { cout << "Argument: " << arg << endl; }
};
...
A a;
a.say_hello();
a.print_it( 3.14159 );
a.print_it( "A string" );
|
2,562,540 | 2,562,560 | Pointers in For loops | Quick question: I am a C# guy debugging a C++ app so I am not used to memory management.
In the following code:
for(int i = 0; i < TlmMsgDB.CMTGetTelemMsgDBCount(); i++)
{
CMTTelemetryMsgCls* telm = TlmMsgDB.CMTGetTelemetryMsg(i);
CMT_SINT32_Tdef id = telm->CMTGetPackingMapID();
ManualScheduleTables.SetManualMsg(i,id);
ManualScheduleTables.SetManExec(i,false);
}
Am I leaking memory every iteration b/c of CMTTelemetryMsgCls* telm = TlmMsgDB.CMTGetTelemetryMsg(i);? The "CMTGetTelemetryMsg(int)" method returns a pointer.
Do I have to "delete telm;" at the end of each iteration?
| There is no global answer for this question.
It really depends on how the person implemented the function with the return value.
It may return a variable allocated on the heap and expect you to delete it
It may return a member variable pointer not even on the heap
If its return value is on the heap, TlmMsgDB may do its own memory management
You need to look on the implementation of the function you're calling: TlmMsgDB.CMTGetTelemetryMsg
|
2,562,906 | 2,563,542 | Ways std::stringstream can set fail/bad bit? | A common piece of code I use for simple string splitting looks like this:
inline std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
Someone mentioned that this will silently "swallow" errors occurring in std::getline. And of course I agree that's the case. But it occurred to me, what could possibly go wrong here in practice that I would need to worry about. basically it all boils down to this:
inline std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
if(/* what error can I catch here? */) {
// *** How did we get here!? ***
}
return elems;
}
A stringstream is backed by a string, so we don't have to worry about any of the issues associated with reading from a file. There is no type conversion going on here since getline simply reads until it sees the line delimeter or EOF. So we can't get any of the errors that something like boost::lexical_cast has to worry about.
I simply can't think of something besides failing to allocate enough memory that could go wrong, but that'll just throw a std::bad_alloc well before the std::getline even takes place. What am I missing?
| I can't imagine what errors this person thinks might happen, and you should ask them to explain. Nothing can go wrong except allocation errors, as you mentioned, which are thrown and not swallowed.
The only thing I see that you're directly missing is that ss.fail() is guaranteed to be true after the while loop, because that's the condition being tested. (bool(stream) is equivalent to !stream.fail(), not stream.good().) As expected, ss.eof() will also be true, indicating the failure was due to EOF.
However, there might be some confusion over what is actually happening. Because getline uses delim-terminated fields rather than delim-separated fields, input data such as "a\nb\n" has two instead of three fields, and this might be surprising. For lines this makes complete sense (and is POSIX standard), but how many fields, with a delim of '-', would you expect to find in "a-b-" after splitting?
Incidentally, here's how I'd write split:
template<class OutIter>
OutIter split(std::string const& s, char delim, OutIter dest) {
std::string::size_type begin = 0, end;
while ((end = s.find(delim, begin)) != s.npos) {
*dest++ = s.substr(begin, end - begin);
begin = end + 1;
}
*dest++ = s.substr(begin);
return dest;
}
This avoids all of the problems with iostreams in the first place, avoids extra copies (the stringstream's backing string; plus the temp returned by substr can even use a C++0x rvalue reference for move semantics if supported, as written), has the behavior I expect from split (different from yours), and works with any container.
deque<string> c;
split("a-b-", '-', back_inserter(c));
// c == {"a", "b", ""}
|
2,563,165 | 2,563,184 | C++ explicit template specialization of templated constructor of templated class | I have a class like
template <class T>
struct A{
template <class U>
A(U u);
};
I would like to write an explicit specialization of this for a declaration like
A<int>::A(float);
In the following test code, if I comment out the specialization, it compiles with g++. Otherwise, it says I have the wrong number of template parameters:
#include <iostream>
template <class T>
struct A{
template <class U>
A(T t, U *u){
*u += U(t);
}
};
template <>
template <>
A<int>::A<int,float>(int t, float *u){
*u += float(2*t);
}
int main(){
float f = 0;
int i = 1;
A<int>(i, &f);
std::cout << f << std::endl;
return 0;
}
| Try
template <>
template <>
A<int>::A(int t, float *u){
*u += float(2*t);
}
That seems to work for me.
|
2,563,227 | 2,563,242 | what is the best way to use global variables in c++? | For me, I usually make a global class with all members static. All other classes will inherit from this global class.
I wonder if this is a good practice?
Anybody got any suggestions?
| Generally try to avoid global variables as they introduce global state. And with global state you do not have referential transparency. Referential transparency is a good thing and global state is a bad thing. Global state makes unit tests pretty pointless for example.
When you have to though, I'd agree that most of the time the method you mentioned is fine. You can also declare the global variable in any .cpp file and then have in your .h file an extern to that global variable.
|
2,563,254 | 2,563,261 | Why do I have to provide default ctor? | Why do I have to provide default ctor if I want to create an array of objects of my type?
Thanks for answers
| Because they have to be initialized.
Consider if it wasn't the case:
struct foo
{
foo(int) {}
void bar(void) {}
};
foo a[10];
foo f = a[0]; // not default-constructed == not initialized == undefined behavior
Note you don't have to:
int main(){
// initializes with the int constructor
foo a[] = {1, 2, 3};
}
// if the constructor had been explicit
int main(){
// requires copy-constructor
foo a[] = {foo(1), foo(2), foo(3)};
}
If you really need an array of objects and you can't give a meaningful default constructor, use std::vector.
If you really need an array of of objects, can't give a meaningful default constructor, and want to stay on the stack, you need to lazily initialize the objects. I have written such a utility class. (You would use the second version, the first uses dynamic memory allocation.)
For example:
typedef lazy_object_stack<foo> lazy_foo;
lazy_foo a[10]; // 10 lazy foo's
for (size_t i = 0; i < 10; ++i)
{
// create a foo, on the stack, passing `i` to the constructor
a[i].create(i);
}
for (size_t i = 0; i < 10; ++i)
a[i].get().bar(); // and use it
// automatically destructed, of course
|
2,563,398 | 2,563,475 | How to keep unreachable code? | I'd like to write a function that would have some optional code to be executed or not depending on user settings. The function is cpu-intensive and having ifs in it would be slow since the branch predictor is not that good.
My idea is making a copy in memory of the function and replace NOPs with a jump when I don't want to execute some code. My working example goes like this:
int Test()
{
int x = 2;
for (int i=0 ; i<10 ; i++)
{
x *= 2;
__asm {NOP}; // to skip it replace this
__asm {NOP}; // by JMP 2 (after the goto)
x *= 2; // Op to skip or not
x *= 2;
}
return x;
}
In my test's main, I copy this function into a newly allocated executable memory and replace the NOPs by a JMP 2 so that the following x *= 2 is not executed. JMP 2 is really "skip the next 2 bytes".
The problem is that I would have to change the JMP operand every time I edit the code to be skipped and change its size.
An alternative that would fix this problem would be:
__asm {NOP}; // to skip it replace this
__asm {NOP}; // by JMP 2 (after the goto)
goto dont_do_it;
x *= 2; // Op to skip or not
dont_do_it:
x *= 2;
I would then want to skip or not the goto, which has a fixed size. Unfortunately, in full optimization mode, the goto and the x*=2 are removed because they are unreachable at compilation time.
Hence the need to keep that dead code.
I'm using VStudio 2008.
| You can cut the cost of the branch by up to 10, just by moving it out of the loop:
int Test()
{
int x = 2;
if (should_skip) {
for (int i=0 ; i<10 ; i++)
{
x *= 2;
x *= 2;
}
} else {
for (int i=0 ; i<10 ; i++)
{
x *= 2;
x *= 2;
x *= 2;
}
}
return x;
}
In this case, and others like it, that might also provoke the compiler into doing a better job of optimising the loop body, since it will consider the two possibilities separately rather than trying to optimise conditional code, and it won't optimise anything away as dead.
If this results in too much duplicated code to be maintainable, use a template that takes x by reference:
int x = 2;
if (should_skip) {
doLoop<true>(x);
} else {
doLoop<false>(x);
}
And check that the compiler inlines it.
Obviously this increases code size a bit, which will occasionally be a concern. Whichever way you do it though, if this change doesn't produce a measurable performance improvement then I'd guess that yours won't either.
|
2,563,666 | 2,564,300 | Normal C++ code in Qt doesnt build and run | I am using Qt under linux, if it matters.
I ran successfully under Geany (a simple c++ compiler) the following:
//my first program in C++ Hello World!
#include <iostream>
using namespace std;
int main ()
{cout << "Hello World!";
return 0;}
I opened Qt source file and copied the exact same code and i can't build or run.
Thank you for your responses to this simple problem.
| If you did what I think you did, you didn't open this as a project, which is the only place where you can build and run (I think).
Try the following.
- Open Qt Creator.
- Go to File->New File or Project
- At the bottom, select "Qt4 Console Application"
- Select a location; it might be nice to create a folder called "hello_world" or something to store the project in.
- A new project will have been created. Copy over the main.cpp file in sources with your code. My code looked like this:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!\n";
return 0;
}
Hit "Build All"
Hit "Run"
This worked for me. Hope this helps!
|
2,563,701 | 2,563,710 | array loop not working correctly? c++ | Trying to count how many elements within the array are not equal to 0, is something set up wrong?
I'd like to check all values in the array (it's a sudoku board) and then when all elements are "full" I need to return true.
Is something off?
bool boardFull(const Square board[BOARD_SIZE][BOARD_SIZE])
{
int totalCount=0;
for (int index1 = 0; index1 < BOARD_SIZE; index1++)
for (int index2 = 0; index2 < BOARD_SIZE; index2++){
if(board[index1][index2].number!=0)
totalCount++;
}
if(totalCount=81)
return true;
else
return false;
| You have = rather than ==
if (totalCount == 81)
is the correct line.
Doing this with a single "=" actually assigns the value 81 to totalCount, so your test is essentialy:
if (81)
And since in C++ anything nonzero is true, this is always true
|
2,563,737 | 2,563,768 | In the following implementation of static_strlen, why are the & and parentheses around str necessary? | If I change the type to const char str[Len], I get the following error:
error: no matching function for call to ‘static_strlen(const char [5])’
Am I correct that static_strlen expects an array of const char references? My understanding is that arrays are passed as pointers anyway, so what need is there for the elements to be references? Or is that interpretation completely off-the-mark?
#include <iostream>
template <size_t Len>
size_t
static_strlen(const char (&str)[Len])
{
return Len - 1;
}
int main() {
std::cout << static_strlen("oyez") << std::endl;
return 0;
}
| No, the function parameter is a reference to an array of Len const chars. That's how the function knows the length (assuming the last byte is a NUL terminator, hence the -1). The parentheses are there precisely to stop it being what you think it is.
Actually there's no such thing in C++ as an array of references, so it couldn't be what you think it is even without the parens. I guess (but am not sure) that the need for the parens is just for consistency with other similar type definitions, such as pointers to arrays:
void fn(const char *a[3]); // parameter a is of type const char**, the 3 is ignored.
void fn(const char (*a)[3]; // parameter a is a pointer to an array of 3 const chars.
That example also illustrates why an array is not a pointer. Predict the output of the following program, and then run it:
#include <iostream>
void fn(const char (*a)[3]) {
std::cout << sizeof(a) << "\n" << sizeof(*a) << "\n";
}
void fn2(const char *a[3]) {
std::cout << sizeof(a) << "\n" << sizeof(*a) << "\n";
}
int main() {
const char a[3] = {};
const char **b = 0;
fn(&a);
fn2(b);
}
#if 0
// error: declaration of `a' as array of references
void fn3(const char & a[3]) {
std::cout << sizeof(a) << "\n" << sizeof(*a) << "\n";
}
#endif
|
2,563,874 | 2,563,925 | delete a file in protected mode env(like windows xp) | I write a program to delete a file from somewhere of my harddisk in 8086
but when i use int 21h (ah=41h) an error happens and carry set to 1.and I cannot delete that.
does anyone know what can I do?
I think it should be from protected mode which does not allow my program to delete another file.I want the answer and language is not matter.
| If you assemble and link your program to as a DOS executable, it should work (provided the code is correct for DOS, of course).
My guess is that you're assembling and linking it to a Windows executable. In that case, you need to use the Windows DeleteFile function to delete the file.
|
2,563,979 | 2,563,987 | Invalid use of 'void' in C++ when using struct and classes | I have 1 compiler error. It is from this line in my code:
cout << myClass->Get_Type().description;
Where as Get_Type() is:
void Tile::Get_Type() {
return &myStruct;
}
I'm not quite sure what I am doing wrong. Or what for that matter could be going wrong.
| A function with a return type of void cannot return anything (that's what the void means: the function does not return anything). You are trying to return something (the address of myStruct).
You either need to return nothing (i.e. change your return to just be return; or remove it entirely) or change the return type of the function from void to a pointer to whatever the type of myStruct is.
|
2,564,135 | 2,564,327 | Should every class have its own namespace? | Something that has been troubling me for a while:
The current wisdom is that types should be kept in a namespace that only
contains functions which are part of the type's non-member interface (see C++ Coding Standards Sutter and Alexandrescu or here) to prevent ADL pulling in unrelated definitions.
Does this imply that all classes must have a namespace of their own? If
we assume that a class may be augmented in the future by the addition of
non-member functions, then it can never be safe to put two types in the
same namespace as either one of them may introduce non-member functions
that could interfere with the other.
The reason I ask is that namespaces are becoming cumbersome for me. I'm
writing a header-only library and I find myself using classes names such as
project::component::class_name::class_name. Their implementations call
helper functions but as these can't be in the same namespace they also have
to be fully qualified!
Edit:
Several answers have suggested that C++ namespaces are simply a mechanism for avoiding name clashes. This is not so. In C++ functions that take a parameter are resolved using Argument Dependent Lookup. This means that when the compiler tries to find a function definition that matches the function name it will look at every function in the same namespace(s) as the type(s) of its parameter(s) when finding candidates.
This can have unintended, unpleasant consequences as detailed in A Modest Proposal: Fixing ADL. Sutter and Alexandrescu's rule states never put a function in the same namespace as a class unless it is meant to be part of the interface of that class. I don't see how I can obey that rule unless I'm prepared to give every class its own namespace.
More suggestions very welcome!
| To avoid ADL, you need only two namespaces: one with all your classes, and the other with all your loose functions. ADL is definitely not a good reason for every class to have its own namespace.
Now, if you want some functions to be found via ADL, you might want to make a namespace for that purpose. But it's still quite unlikely that you'd actually need a separate namespace per class to avoid ADL collisions.
|
2,564,200 | 2,564,796 | Why might stable_sort be affecting my hashtable values? | I have defined a struct ABC to contain an int ID, string NAME, string LAST_NAME;
My procedure is this: Read in a line from an input file. Parse each line into first name and last name and insert into the ABC struct. Also, the struct's ID is given by the number of the input line.
Then, push_back the struct into a vector masterlist. I am also hashing these to a hashtable defined as vector< vector >, using first name and last name as keywords. That is,
If my data is:
Garfield Cat
Snoopy Dog
Cat Man
Then for the keyword cash hashes to a vector containing Garfield Cat and Cat Man. I insert the structs into the hashtable using push_back again.
The problem is, when I call stable_sort on my masterlist, my hashtable is affected for some reason.
I thought it might be happening since the songs are being ordered differently, so I tried making a copy of the masterlist and sorting it and it still affects the hashtable though the original masterlist is unaffected.
Any ideas why this might be happening?
EDIT--source code posted:
Here is the main
ifstream infile;
infile.open(argv[1]);
string line;
vector<file> masterlist;
vector< vector<node> > keywords(512);
hashtable uniquekeywords(keywords,512);
int id=0;
while (getline(infile,line)){
file entry;
if (!line.empty() && line.find_first_not_of(" \t\r\n")!=line.npos){
id++;
string first=beforebar(line,0);
string last=afterbar(line);
entry.first=first;
entry.last=last;
entry.id=id;
masterlist.push_back(entry);
int pos=line.find_first_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
while (pos!=(int)line.npos){
string keyword=getword(line,pos);
node bucket(keyword,id);
bucket.addentry(entry);
uniquekeywords.insert(bucket);
}
}
}
Here is the snippet of hashtable insert implementation:
struct node{
string keyword;
vector<file> entries;
int origin;
void addentry(file entry);
node(string keyword, int origin);
};
void hashtable::insert(node bucket){
int key=hashfunction(bucket.keyword);
if (table[key].empty()){
table[key].push_back(bucket);
numelt++;
}
else{
vector<node>::iterator it;
it=table[key].begin();
while(it!=table[key].end()){
if (compare((*it).keyword,bucket.keyword)==0 && (*it).origin!=bucket.origin){
(*it).entries.insert((*it).entries.end(),bucket.entries.begin(),bucket.entries.end());
(*it).origin=bucket.origin;
return;
}
it++;
}
node bucketcopy(bucket.keyword,bucket.origin);
table[key].push_back(bucket);
numelt++;
return;
}
}
| Let's see. It can be one of these things:
Your hashtable implementation is broken.
Your hash function is broken.
Somehow sorting changes the semantic value of what you've stored. A sorted vector certainly has different values than an unsorted vector.
In reality, it doesn't matter which one of these are the cause of the problem. You should be the std::map container instead for this. If for some reason you absolutely must use a hash table implementation then at least use a relatively standard hashed container such as:
std::unordered_map provided on compilers with C++11 support
boost's boost::unordered_map
std::tr1::unordered_map
hash_map provided with many compilers
etc.
Note that the above are ordered in the order that you should probably try them.
|
2,564,218 | 2,564,229 | How to combine ASCII text files, then encrypt, then decrypt, and put into a 'File' Class? C++ | For example, if I have three ASCII files:
file1.txt
file2.txt
file3.txt
...and I wanted to combine them into one encrypted file:
database.txt
Then in the application I would decrypt the database.txt and put each of the original files into a 'File' class on the heap:
class File{
public:
string getContents();
void setContents(string data);
private:
string m_data;
};
Is there some way to do this?
Thanks
| Just use a zip file?
You can of course roll your own header meta data to store the filenames, but this particular wheel has been re-invented enough times.
If you need better encryption than that provided by zlib, then you can either use the crypt functions in your platform, or it's very easy to implement something like blowfish
|
2,564,503 | 2,564,741 | How do I check if my program has data piped into it | Im writing a program that should read input via stdin, so I have the following contruct.
FILE *fp=stdin;
But this just hangs if the user hasn't piped anything into the program, how can I check if the user is actually piping data into my program like
gunzip -c file.gz |./a.out #should work
./a.out #should exit program with nice msg.
thanks
| Since you're using file pointers, you'll need both isatty() and fileno() to do this:
#include <unistd.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
FILE* fp = stdin;
if(isatty(fileno(fp)))
{
fprintf(stderr, "A nice msg.\n");
exit(1);
}
/* carry on... */
return 0;
}
Actually, that's the long way. The short way is to not use file pointers:
#include <unistd.h>
int main(int argc, char* argv[])
{
if(isatty(STDIN_FILENO))
{
fprintf(stderr, "A nice msg.\n");
exit(1);
}
/* carry on... */
return 0;
}
Several standard Unix programs do this check to modify their behavior. For example, if you have ls set up to give you pretty colors, it will turn the colors off if you pipe its stdout to another program.
|
2,564,605 | 2,564,665 | C or C++ Win32 How can I obtain the number of threads running in my program? | On Win32, how can a C++ program determine how many threads are active in my program's process? Is there an API call?
| You can use Tool Help API to enumerate the current processes running and within each process the threads running. Of course by the time you have completed the analysis more tasks and threads may have started and others may have ended.
|
2,564,952 | 2,565,030 | How does the below program work in c++? | I have just created 2 pointers which has undefined behavior and try to invoke a class member function which has no object created ?
I don't understand this?
#include<iostream>
using namespace std;
class Animal
{
public:
void talk()
{
cout<<"I am an animal"<<endl;
}
};
class Dog : public Animal
{
public:
void talk()
{
cout<<"bark"<<endl;
}
};
int main()
{
Animal * a;
Dog * d;
d->talk();
a->talk();
}
| A) It's undefined behavior. Any behavior may happen.
B) Since you're not calling a virtual method, it's pretty easy to explain why the undefined behavior actually does this (and I've tested this under just about every compiler I could find).
In C++, calling a member method is equivalent (in practice if not in definition) of calling a member with a hidden 'this' variable. If the method is virtual, it has to go through the vftable, but not for a non-virtual method.
So
Foo::Bar(){}
is the rough equivalent of
Foo_Bar(Foo *this){}
and in the calling code
Foo *foo = new Foo();
foo->bar();
the second line is roughly the moral equivalent of
Foo_Bar(foo);
Now, there's some simplification going on here, and as I said, some of this may be implementation detail rather than specification. However, the behavior holds true (though relying upon it is an error).
But, given the preceding, look at an implementation:
void Foo::Bar(){printf("Hello, world!\n");}
and calling code:
Foo *foo = 0;
foo->Bar();
As we've said, this is roughly equivalent (since we're non-virtual) to:
Foo *foo = 0;
Foo::Bar(foo);
Which means that we're calling the equivalent of the following method:
void Foo_Bar(Foo* this)
{ printf("Hello, world\n"); }
Now, given this method, we're not actually dereffing the this pointer! So, it's pretty clear why, in this case, the method will work and not fail.
The practical upshot of this is that calling non-virtual methods on a null pointer, where the method doesn't deref an a member, will generally result in this observed behavior. But, relying upon any undefined behavior is, basically, evil.
|
2,565,068 | 2,565,141 | Classes, constructor and pointer class members | I'm a bit confused about the object references. Please check the examples below:
class ListHandler {
public:
ListHandler(vector<int> &list);
private:
vector<int> list;
}
ListHandler::ListHandler(vector<int> &list) {
this->list = list;
}
Because of the internal
vector<int> list;
definition, here I would be wasting memory right? So the right one would be:
class ListHandler {
public:
ListHandler(vector<int>* list);
private:
vector<int>* list;
}
ListHandler::ListHandler(vector<int>* list) {
this->list = list;
}
ListHandler::~ListHandler() {
delete list;
}
Basically all I want is to create a vector and pass to ListHandler. This vector will not be used anywhere else than the ListHandler itself so I'm expecting ListHandler to do all the other things and cleanup etc. stuff.
| It depends on whether you want to share the underyling vector or not. In general, I think it is a good practice to avoid sharing wherever possible, since it removes the question of object ownership. Without sharing:
class ListHandler
{
public:
ListHandler(const std::vector<int>& list) : _list(list) {}
~ListHandler(){}
private:
std::vector<int> _list;
};
Note that, unlike in your example, I make it const since the original will not be modified. If, however, we want to hang on to and share the same underlying object, then we could use something like this:
class ListHandler
{
public:
ListHandler(std::vector<int>& list) : _list(&list) {}
~ListHandler(){}
private:
std::vector<int>* _list;
};
Note that in this case, I choose to leave the caller as the owner of the object (so it is the caller's responsiblity to ensure that the list is around for the lifetime of the list handler object and that the list is later deallocated). Your example, in which you take over the ownership is also a possibility:
class ListHandler
{
public:
ListHandler(std::vector<int>* list) : _list(list) {}
ListHandler(const ListHandler& o) : _list(new std::vector<int>(o._list)) {}
~ListHandler(){ delete _list; _list=0; }
ListHandler& swap(ListHandler& o){ std::swap(_list,o._list); return *this; }
ListHandler& operator=(const ListHandler& o){ ListHandler cpy(o); return swap(cpy); }
private:
std::vector<int>* _list;
};
While the above is certainly possible, I personally don't like it... I find it confusing for an object that isn't simply a smart pointer class to acquire ownership of a pointer to another object. If I were doing that, I would make it more explicit by wrapping the std::vector in a smart pointer container as in:
class ListHandler
{
public:
ListHandler(const boost::shared_ptr< std::vector<int> >& list) : _list(list) {}
~ListHandler(){}
private:
boost::shared_ptr< std::vector<int> > _list;
};
I find the above much clearer in communicating the ownership. However, all these different ways of passing along the list are acceptable... just make sure users know who will own what.
|
2,565,097 | 2,565,191 | Higher-kinded Types with C++ | This question is for the people who know both Haskell (or any other functional language that supports Higher-kinded Types) and C++...
Is it possible to model higher kinded types using C++ templates? If yes, then how?
EDIT :
From this presentation by Tony Morris:
Higher-order Polymorphism :
Languages such as Java and C# have
first-order polymorphism because they
allow us to abstract on types. e.g.
List<A> can have a reverse function
that works on any element type (the
A).
More practical programming languages
and type systems allow us to
abstract on type constructors as
well.
This feature is called higher-order
(or higher-kinded) polymorphism.
Example :
Pseudo-Java with an invented notation for higher-order polymorphism
interface Transformer<X, Y> {
Y transform(X x);
}
interface Monad<M> { // M :: * -> *
<A> M<A> pure(A a);
<A, B> M<B> bind(Transformer<A, M<B>> t, M<A> a);
}
| Template-template parameters?
template <template <typename> class m>
struct Monad {
template <typename a>
static m<a> mreturn(const a&);
template <typename a, typename b>
static m<b> mbind(const m<a>&, m<b>(*)(const a&));
};
template <typename a>
struct Maybe {
bool isNothing;
a value;
};
template <>
struct Monad<Maybe> {
template <typename a>
static Maybe<a> mreturn(const a& v) {
Maybe<a> x;
x.isNothing = false;
x.value = v;
return x;
}
template <typename a, typename b>
static Maybe<b> mbind(const Maybe<a>& action, Maybe<b>(*function)(const a&)) {
if (action.isNothing)
return Maybe<b>{true, b{}};
else
return function(action.value);
}
};
|
2,565,240 | 2,565,825 | What is a NULL value | I am wondering , what exactly is stored in the memory when we say a particular variable pointer to be NULL. suppose I have a structure, say
typdef struct MEM_LIST MEM_INSTANCE;
struct MEM_LIST
{
char *start_addr;
int size;
MEM_INSTANCE *next;
};
MEM_INSTANCE *front;
front = (MEM_INSTANCE*)malloc(sizeof(MEM_INSTANCE*));
-1) If I make front=NULL. What will be the value which actually gets stored in the different fields of the front, say front->size ,front->start_addr. Is it 0 or something else. I have limited knowledge in this NULL thing.
-2) If I do a free(front); It frees the memory which is pointed out by front. So what exactly free means here, does it make it NULL or make it all 0.
-3) What can be a good strategy to deal with initialization of pointers and freeing them .
Thanks in advance
| There are many good contributed answers which adequately address the questions. However, the coverage of NULL is light.
In a modern virtual memory architecture, NULL points to memory for which any reference (that is, an attempt to read from or write to memory at that address) causes a segfault exception—also called an access violation or memory fault. This is an intentional protective mechanism to detect and deal appropriately with invalid memory accesses:
char *p = 0;
for (int j = 0; j < 50000000; ++j)
*(p += 1000000) = 10;
This code writes a ten at every millionth memory byte. It won't run for many loops—probably not even once. Either it will attempt to access an unmapped address, or it will attempt to modify read-only memory—where constant data or program code reside. The CPU will interrupt the instruction midway and report the exception to the operating system. Since there's no exception handling specified, the default o/s handling is to terminate the program. Linux displays Segmentation fault (for historical reasons). MS Windows is inconsistent, but tends to say access violation. The same should happen with any program in protected virtual memory doing this:
char *p = NULL;
if (p [34] == 'Y')
printf ("A miracle has occurred!\n");
This segfaults. A memory location near the NULL address is being dereferenced.
At the risk of confusion, it is possible that a large offset from zero will be valid memory. Thirty-four certainly won't be okay, but 34,000 might be. Different operating systems and different program processing tools (linkers) reserve a fixed amount of the zero end of memory and arrange for it to be unmapped. It could be as little as 1K, though 8K was a popular choice in the 1990s. Systems with ample virtual address space (not memory, but potential memory) might leave an 8M or 16M memory hole. Some modern operating systems randomize the amount of space reserved, as well as randomly varying the locations for the code and data sections each time a program starts.
The other extreme is non-virtual memory architectures. Typically, these provide valid addresses beginning at address zero up to the limit of installed memory. Such is common in embedded processors, many DSPs, and pre-protected mode CPUs, 8 and 16-bit processors like the 8086, 68000, etc. Reading a NULL address does not cause any special CPU reaction—it simply reads whatever is there, which is usually interrupt vectors. Writes to low memory usually result in hard-to-diagnose dire consequences as interrupt vectors are used asynchronously and infrequently.
Even stranger is the segment model of the oddly named "real-mode" x86 using small or medium memory model conventions. Such data addresses are 16 bits using the DS register which is set to the program's initialized data area. Dereferencing NULL accesses the first bytes of this space, but MSDOS programs contain ancient runtime structures for compatibility with CP/M, an o/s Fred Flintstone used. No exceptions, and maybe no consequences for modifying the memory near NULL in this environment. These were challenging bugs to find without program source code.
Virtual memory protection was a huge leap forward in creating stable systems and protecting programmers from themselves. Properly used NULLs provide significant safety and rapid debugging of programming flaws.
|
2,565,299 | 2,565,309 | Using ASSERT and EXPECT in GoogleTest | While ASSERT_* macros cause termination of test case, EXPECT_* macros continue its evaluation.
I would like to know which is the criteria to decide whether to use one or the other.
| Use ASSERT when the condition must hold - if it doesn't the test stops right there. Use this when the remainder of the test doesn't have semantic meaning without this condition holding.
Use EXPECT when the condition should hold, but in cases where it doesn't we can still get value out of continuing the test. (The test will still ultimately fail at the end, though.)
The rule of thumb is: use EXPECT by default, unless you require something to hold for the remainder of the tests, in which case you should use ASSERT for that particular condition.
This is echoed within the primer:
Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.
|
2,565,354 | 2,581,048 | Varying performance of MSVC release exe | I am curious what could be the reason for highly varying performance of the same executable.
Sometimes, I run it and it takes 20 seconds and sometimes it is 110.
Source is compiled with MSVC in Release mode with standard options.
The code is here:
vector<double> Un;
vector<double> Ucur;
double *pUn, *pUcur;
...
// time marching
for (old_time=time-logfreq, time+=dt; time <= end_time; time+=dt)
{
for (i=1, j=Un.size()-1, pUn=&Un[1], pUcur=&Ucur[1]; i < j; ++i, ++pUn, ++pUcur)
{
*pUcur = (*pUn)*(1.0-0.5*alpha*( *(pUn+1) - *(pUn-1) ));
}
Ucur[0] = (Un[0])*(1.0-0.5*alpha*( Un[1] - Un[j] ));
Ucur[j] = (Un[j])*(1.0-0.5*alpha*( Un[0] - Un[j-1] ));
Un = Ucur;
}
EDIT
Sorry not to mention input data.
The vectors Un and Ucur are initialized to 2000 elements with value 0.
No data is read/written. No interaction with console.
When I say sometimes I run it means that I have console open, no other applications running , processor throttling disabled. I keep executing application after it finishes.
I guess it has to do with caching or something like that but I am not good on low-level things.
| Issue was resolved when I switched the arguments in this function from addresses to variables.
Before I had double &time, double &dt, double &end_time
Now: double time, double dt, double end_time
It appears to be memory-related issue... Hope, it helps anybody
|
2,565,512 | 2,565,522 | Actual long double precision does not agree with std::numeric_limits | Working on Mac OS X 10.6.2, Intel, with i686-apple-darwin10-g++-4.2.1, and compiling with the -arch x86_64 flag, I just noticed that while...
std::numeric_limits<long double>::max_exponent10 = 4932
...as is expected, when a long double is actually set to a value with exponent greater than 308, it becomes inf--ie in reality it only has 64bit precision instead of 80bit.
Also, sizeof() is showing long doubles to be 16 bytes, which they should be.
Finally, using <limits.h> gives the same results as <limits>.
Does anyone know where the discrepancy might be?
long double x = 1e308, y = 1e309;
cout << std::numeric_limits<long double>::max_exponent10 << endl;
cout << x << '\t' << y << endl;
cout << sizeof(x) << endl;
gives
4932
1e+308 inf
16
| It's because 1e309 is a literal that gives a double. You need to use a long-double literal 1e309L.
|
2,565,527 | 2,565,547 | valgrind complains doing a very simple strtok in c | Hi I'm trying to tokenize a string by loading an entire file into a char[] using fread.
For some strange reason it is not always working, and valgrind complains in this very small sample program.
Given an input like test.txt
first
second
And the following program
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
//returns the filesize in bytes
size_t fsize(const char* fname){
struct stat st ;
stat(fname,&st);
return st.st_size;
}
int main(int argc, char *argv[]){
FILE *fp = NULL;
if(NULL==(fp=fopen(argv[1],"r"))){
fprintf(stderr,"\t-> Error reading file:%s\n",argv[1]);
return 0;
}
char buffer[fsize(argv[1])];
fread(buffer,sizeof(char),fsize(argv[1]),fp);
char *str = strtok(buffer," \t\n");
while(NULL!=str){
fprintf(stderr,"token is:%s with strlen:%lu\n",str,strlen(str));
str = strtok(NULL," \t\n");
}
return 0;
}
compiling like
gcc test.c -std=c99 -ggdb
running like
./a.out test.txt
thanks
| Your buffer size should be filesize + 1. The +1 is for the null char.
filesize = fsize(argv[1]);
char buffer[filesize + 1];
Also fread does not put a \0 at the end of the string. So you'll have to do it yourself as:
fread(buffer,sizeof(char),filesize,fp);
buffer[filesize] = 0;
|
2,565,556 | 2,565,612 | Prevent committing code with svn if certain obsolete C/C++ functions are used | Is there a way to prevent developers from committing code when certain unsafe or obsolete functions are used? For example:
scanf
atoi
gets
etc..
| A project I've worked uses a simple set of macros in a header that's included in every file (some compilers let you specify such a header on the command line, so you can force it's use in a makefile):
#define strcpy strcpy_is_banned_use_strlcpy
#define strcat strcat_is_banned_use_strlcat
#define strncpy strncpy_is_banned_use_strlcpy
#define strncat strncat_is_banned_use_strlcat
#define sprintf sprintf_is_banned_use_snprintf
With these macros, the build will fail if you try to use a banned function (and the linker will tell you what you should use instead).
So it doesn't get checked on commit, per se, but as long as your team members make sure things build before they check in, the system works. And if they don't, then everyone starts getting build break emails, which tends to quickly correct the behavior.
Simple, but effective.
|
2,565,661 | 2,565,720 | wopen calls when porting to Linux | I have an application which was developed under Windows, but for gcc. The code is mostly OS-independent, with very few classes which are Windows specific because a Linux port was always regarded as necessary.
The API, especially that which gets called as a direct result of user interaction, is using wide char arrays instead of char arrays (as a side note, I cannot change the API itself - at this point, std::wstring cannot be used). These are considered as encoded in UTF-16.
In some places, the code opens files, mostly using the windows-specific _wopen function call. The problem with this is there is no wopen-like substitute for Linux because Linux "only deals with bytes".
The question is: how do I port this code ? What if I wanted to open a file with the name "something™.log", how would I go about doing so in Linux ? Is a cast to char* sufficient, would the wide chars be picked up automatically based on the locale (probably not) ? Do I need to convert manually ? I'm a bit confused regarding this, perhaps someone could point me to some documentation regarding the matter.
| The strategy I took on Mac hinges on the fact that Mac OS X uses utf-8 in all its file io POSIX api's.
I thus created a type "fschar" thats a char in windows non unicode builds, wchar_t in windows UNICODE builds and char (again) when building for Mac OS.
I pass around all file system strings using this type. String literals are encoded with wrappers (TEXT("literal")) to get the correct encoding - all my data files store utf-8 characters on disk that, on windows UNICODE builds, I MultiByteToWideChar to convert to utf16.
|
2,566,167 | 2,566,182 | Where to find __sync_add_and_fetch_8? | I got errors when trying to use __sync_add_and_fetch:
test8.cpp:(.text+0x90e): undefined reference to `__sync_add_and_fetch_8'
collect2: ld returned 1 exit status
Please kindly advise how to rectify this.
Specs:
GCC/G++: 4.4.1
GNU/Linux 2.6.32 SMP i686
Many thanks!
EDIT:
In addition to the answer provided, one can use -march=i586 or -march=i686 to link successfully.
Note: This requires GCC/G++ 4.1.x and above!
| That function is not supported on all x86 architectures. Try specifying your architecture, such as --with-arch=pentium4.
|
2,566,200 | 2,566,318 | Passing array by ref | Ref. to my last post and sellibitze's comment to that post on passing array by ref rather than by value, why is it that when I'm passing array by value compiler can deduce arguments but it won't do it if I pass it by value?
template<class T,int row, int col>
void invert(T (&a)[row][col]) //NOTE AMPERSAND
in main with declaration above I can call:
int main(int argc, char* argv[])
{
invert(a);//HERE ARGUMETS ARE AUTOMATICALLY DEDUCED
}
but without ampersand I would have to call it like so:
int main(int argc, char* argv[])
{
invert<int,3,4>(a);
}
@Paul So just to make it clear when I'm declaring fnc:
void f(int a[]);//I'm passing a pointer
but when I'm declaring:
void f(int &a[]);//I'm passing a ref?
Do I understand this correctly now?
| That's because when you pass an array "by value" it decays to a pointer. That is, you are in fact passing a pointer to the first element without any size information.
When you have a signature like this:
void foo(int arr[10]);
then the value 10 is completely ignored and you can pass arrays of ints of any size to it. It is exactly the same as
void foo(int arr[]);
or
void foo(int* arr);
As you can see the size information is not preserved, and therefore it cannot be used to deduce the size of the array.
With a two-dimensional array, the first dimension decays. For example: an array of 10 arrays of 20 integers (int arr[10][20]) decays to a pointer to arrays of 20 integers (int (*arr)[20]) etc, so the value 10 cannot be deduced but the size of the second dimension (20) is preserved an can be deduced.
template<class T,int row, int col>
void foo(T (&a)[row][col]) { }
template <class T, int col>
void bar(T arr[][col]) {}
int main()
{
int a[10][20];
foo(a);
bar(a);
}
When you pass something by reference, the type is preserved, the arrays don't decay and all the size information will remain available.
|
2,566,213 | 2,566,270 | test cases for testing a strtok-alike function [C++] | Consider the following class definition:
class StrToTokens {
StrToTokens(const char* str, const char* delimiters = "\t\r\n"); //constructor
string getNextToken();
void reset();
bool empty();
}
Can someone list some good testcases to test the above class.
A few I could think of are:
empty string, empty delimiters, repeated delimiters, consecutive delimiters, string with only delimiters.
However, the interviewer expected some more(better ones). Can you help out.
Thanks.
| Well, I usually add at least one testcase that just tests for a normal working case. And of course all the tests you guys mentioned where just for the constructor. The other methods have to be tested as well:
does reset really reset (what is reset meant to do anyway)
does empty behave as expected
are tokens retrieved in the right way/order
I usually implement some more complex testcases to test such things, such as
Initialize
read a token
reset
read a token
Or
Initialize
read all tokens
check empty
|
2,566,278 | 2,566,296 | How to see the code generated by the compiler | Guys in one of excersises (ch.5,e.8) from TC++PL Bjarne asks to do following:
'"Run some tests to see if your compiler really generates equivalent code for iteration using pointers and iteration using indexing. If different degrees of optimization can be requested, see if and how that affects the quality of the generated code"'
Any idea how to eat it and with what?
Thanks in advice.
| You want to write code something like this:
int a[] = {1,2,3,4};
int n = 0;
for ( int i = 0; i < 4; i++ ) {
n += a[i];
}
int * p = a;
for ( int i = 0; i < 4; i++ ) {
n += *p++;
}
Then you need to compile it with compiler options that gets your compiler to emit assembly language, and take a look at it. It's also instructive to do this both with and without optimisations turned on.
|
2,566,307 | 2,574,925 | WTL Child window event handling | I am developing window application in that I am having 2 child windows on left and right side.
I want to handle input events for both windows separately.
How to achieve it?
My code:
class EditorWindow : public DxWindow
{
public:
CSplitterWindow m_vSplit;
CPaneContainer m_lPane;
CPaneContainer m_rPane;
PropertyDialog m_propertyWnd;
DECLARE_WND_CLASS(_T("Specific_Class_Name"))
BEGIN_MSG_MAP(EditorWindow)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_LBUTTONDOWN, KeyHandler)
MESSAGE_HANDLER(WM_KEYUP, KeyHandler)
MESSAGE_HANDLER(WM_LBUTTONDOWN, KeyHandler)
END_MSG_MAP()
LRESULT OnCreate(UINT, WPARAM, LPARAM, BOOL&)
{
CRect rcVert;
GetClientRect(&rcVert);
m_vSplit.Create(m_hWnd, rcVert, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
m_vSplit.SetSplitterPos(rcVert.Width()/1.4f); // from left
m_lPane.Create(m_vSplit.m_hWnd);
m_vSplit.SetSplitterPane(0, m_lPane);
//m_lPane.SetTitle(L"Left Pane");
m_rPane.Create(m_vSplit.m_hWnd);
m_vSplit.SetSplitterPane(1, m_rPane);
m_rPane.SetTitle(L"Properties");
m_propertyWnd.Create(m_rPane.m_hWnd);
//m_vSplit.SetSplitterPane(SPLIT_PANE_LEFT, md.m_hWnd);
return 0;
}
LRESULT OnDestroy( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled )
{
PostQuitMessage(0);
bHandled = FALSE;
return 0;
}
LRESULT KeyHandler( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled )
{
return 0;
}
};
| WTL::CSplitterWindow and WTL::CPaneContainer do not forward the WM_KEYxxx and WM_MOUSExxx messages to their parent.
Derive your EditorWindow from WTL::CSplitterWindowImpl and your Panes from WTL::CPaneContainerImpl for instance:
class CMyPaneContainer : public CPaneContainerImpl<CMyPaneContainer>
{
public:
DECLARE_WND_CLASS_EX(_T("MyPaneContainer"), 0, -1)
BEGIN_MSG_MAP(CMyPaneContainer)
MESSAGE_RANGE_HANDLER(WM_KEYFIRST, WM_KEYLAST, OnForward)
MESSAGE_RANGE_HANDLER(WM_MOUSEFIRST, WM_MOUSELAST, OnForward)
CHAIN_MSG_MAP(CPaneContainerImpl<CMyPaneContainer>)
END_MSG_MAP()
LRESULT OnForward(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if (uMsg == WM_MOUSEWHEEL)
return bHandled = FALSE; // Don't forward WM_MOUSEWHEEL
return GetParent().SendMessage(uMsg, wParam, lParam);
}
};
class EditorWindow : public CSplitterWindowImpl<EditorWindow, true, CWindow/*DxWindow*/>
{
typedef CSplitterWindowImpl<EditorWindow, true, CWindow/*DxWindow*/> baseClass;
public:
CMyPaneContainer m_lPane;
CMyPaneContainer m_rPane;
//PropertyDialog m_propertyWnd;
DECLARE_WND_CLASS(_T("Specific_Class_Name"))
BEGIN_MSG_MAP(EditorWindow)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_LBUTTONDOWN, KeyHandler)
MESSAGE_HANDLER(WM_KEYUP, KeyHandler)
CHAIN_MSG_MAP(baseClass)
END_MSG_MAP()
LRESULT OnCreate(UINT, WPARAM, LPARAM, BOOL&)
{
m_lPane.Create(m_hWnd);
m_lPane.SetTitle(L"Left Pane");
m_rPane.Create(m_hWnd);
m_rPane.SetTitle(L"Properties");
//m_propertyWnd.Create(m_rPane.m_hWnd);
SetSplitterPosPct(70); // 70% from left
SetSplitterPanes(m_lPane, m_rPane);
return 0;
}
|
2,566,841 | 2,566,861 | Pointers into elements in a container | Say I have an object:
struct Foo
{
int bar_;
Foo(int bar) bar_(bar) {}
};
and I have an STL container that contains Foos, perhaps a vector, and I take
// Elsewhere...
vector<Foo> vec;
vec.push_back(Foo(4));
int *p = &(vec[0].bar_)
This is a terrible idea, right?
The reason is that vector is going to be storing its elements in a dynamically allocated array somewhere, and eventually, if you add enough elements, it will have to allocate another array, copy over all the elements of the original array, and delete the old array. After that happens, p points to garbage. This is why many operations on a vector will invalidate iterators.
It seems like it would be reasonable to assume that an operation that would invalidate iterators from a container will also invalidate pointers to data members of container elements, and that if an operation doesn't invalidate iterators, those pointers will still be safe. However, many reasonable assumptions are false. Is this one of them?
| The standard specifies when such pointers are invalidated. References into a vector die when you increase its size past capacity or add/remove a preceding element. References into a deque are invalidated if you add/remove from the middle.
Otherwise, references and iterators are safe to keep for the lifespan of the underlying object.
|
2,566,884 | 2,566,955 | Why boost::recursive_mutex is not working as expected? | I have a custom class that uses boost mutexes and locks like this (only relevant parts):
template<class T> class FFTBuf
{
public:
FFTBuf();
[...]
void lock();
void unlock();
private:
T *_dst;
int _siglen;
int _processed_sums;
int _expected_sums;
int _assigned_sources;
bool _written;
boost::recursive_mutex _mut;
boost::unique_lock<boost::recursive_mutex> _lock;
};
template<class T> FFTBuf<T>::FFTBuf() : _dst(NULL), _siglen(0),
_expected_sums(1), _processed_sums(0), _assigned_sources(0),
_written(false), _lock(_mut, boost::defer_lock_t())
{
}
template<class T> void FFTBuf<T>::lock()
{
std::cerr << "Locking" << std::endl;
_lock.lock();
std::cerr << "Locked" << std::endl;
}
template<class T> void FFTBuf<T>::unlock()
{
std::cerr << "Unlocking" << std::endl;
_lock.unlock();
}
If I try to lock more than once the object from the same thread, I get an exception (lock_error):
#include "fft_buf.hpp"
int main( void ) {
FFTBuf<int> b( 256 );
b.lock();
b.lock();
b.unlock();
b.unlock();
return 0;
}
This is the output:
sb@dex $ ./src/test
Locking
Locked
Locking
terminate called after throwing an instance of 'boost::lock_error'
what(): boost::lock_error
zsh: abort ./src/test
Why is this happening? Am I understanding some concept incorrectly?
| Try this:
template<class T> void FFTBuf<T>::lock()
{
std::cerr << "Locking" << std::endl;
_mut.lock();
std::cerr << "Locked" << std::endl;
}
template<class T> void FFTBuf<T>::unlock()
{
std::cerr << "Unlocking" << std::endl;
_mut.unlock();
}
You use the same instance of unique_lock _lock twice and this is a problem.
You either have to directly use methods lock () and unock() of the recursive mutex or use two different instances of unique_lock like foe example _lock and _lock_2;.
Update
I would like to add that your class has public methods lock() and unlock() and from my point of view in a real program it is a bad idea. Also having unique_lock as a member of class in a real program must be often a bad idea.
|
2,567,557 | 2,567,692 | injecting dll into exe file | I want to execute an exe file which is written in VC++.net 2008 in a computer which has windows xp and has not .net framework and none of c++ libraries.
but when i run the file i get this error:
This application has failed to start because the application configuration is incorrect....
I want a way to put all dependency together to become free of this problem.
does anyone know what should I do?
| If you are writing a pure C++ application (Win32 only, no .NET), then you want to staticly link the C++ run time, which can be changed in your project's properties. See this answer for the instructions. (It is for VC2005, but the steps are the same in VC2008)
|
2,567,589 | 2,567,593 | What is the difference between these usages: new SubElement() and SubElement()? | Into a class constructor, I need to create some objects on the fly and add them to a vector. Here is my code:
ContainerClass::ContainerClass() {
for (int i = 0; i < limit; i++)
elements.push_back(SubElement());
}
Is this the same thing with new SubElement()? Do I still need to free those SubElement() objects into the ContainerClass destructor?
| Method 1:
If you have std::vector<SubElement> elements;
Then you would use elements.push_back(SubElement()).
SubElement() creates a SubElement on the stack and then a copy gets added to the vector.
You should NOT call delete on the individual elements of the vector. They will be destructed and deallocated when the vector goes out of scope.
Method 2:
If you have std::vector<SubElement*> elements;
Then you would use elements.push_back(new SubElement()).
new SubElement() creates a SubElement on the heap, and then the address of that element gets stored in the vector.
You would need to call delete on the individual elements before the vector goes out of scope, otherwise you'll create a memory leak. They will be destructed and deallocated only when you call delete on each of the elements.
|
2,567,666 | 2,567,685 | Referencing invalid memory locations with C++ Iterators | I am a big fan of GCC, but recently I noticed a vague anomaly. Using __gnu_cxx::__normal_iterator (ie, the most common iterator type used in libstdc++, the C++ STL) it is possible to refer to an arbitrary memory location and even change its value without causing an exception! Is this expected behavior? If so, isn't a security loophole?
Here's an example:
#include <iostream>
using namespace std;
int main() {
basic_string<char> str("Hello world!");
basic_string<char>::iterator iter = str.end();
iter += str.capacity() + 99999;
*iter = 'x';
cout << "Value: " << *iter << endl;
}
| Dereferencing an iterator beyond the end of the container from which it was obtained is undefined behavior, and doing nothing is just a possibility there.
Note that this is a question of compromise, it is nice having iterators check for validity for development, but that adds extra operations to the code. In MSVS iterators are by default checked (they will verify that they are valid and fail hard when they are used in a wrong way=. But that also has an impact in runtime performance.
The solution that Dinkumware (STL inside VS) provides (checked by default, can be unchecked through compiler options) is in fact a good choice, the user selects whether he wants slow safe iterators or fast unsafe versions of it. But from the point of view of the language, both are valid.
|
2,567,693 | 2,567,727 | including a string as a parameter to a function in a header file? c++ | I have this header file, zeeheader.h, and I wrote some classes in it, I'm having problems giving a string as a parameter to one of the functions:
class DeliTest
{
public:
void DeliCheck(Stack*,string);
void ComCheck (unsigned,string);
bool EofCheck (unsigned,string);
};
As I was implementing it in the cpp file, I added #include to it, it seemed to be working, for example: as I was writing the "data." I got the "length()" appear by the intellisense, so I thought that it was working, but it wasn't. I got errors like:
syntax error : identifier 'string'
overloaded member function not found in 'DeliTest'
this is one of the functions in the cpp file:
bool DeliTest::EofCheck(unsigned i, string data)
{
if (i == data.length()-1)
return 1;
return 0;
}
Am I supposed to be adding something to the header file?
| Make sure to #include <string>, and because strings are in the std namespace, you should declare your strings as std::string in the header.
As a sidenote, make sure you do NOT declare using namespace std; in your header files. This would cause any other headers or c/cpp files that include this header to also use the std namespace. This is called polluting the namespace.
|
2,567,784 | 2,567,802 | C++ Operator overloading - 'recreating the Vector' | I am currently in a collage second level programing course... We are working on operator overloading... to do this we are to rebuild the vector class...
I was building the class and found that most of it is based on the [] operator. When I was trying to implement the + operator I run into a weird error that my professor has not seen before (apparently since the class switched IDE's from MinGW to VS express...) (I am using Visual Studio Express 2008 C++ edition...)
Vector.h
#include <string>
#include <iostream>
using namespace std;
#ifndef _VECTOR_H
#define _VECTOR_H
const int DEFAULT_VECTOR_SIZE = 5;
class Vector
{
private:
int * data;
int size;
int comp;
public:
inline Vector (int Comp = 5,int Size = 0)
: comp(Comp), size(Size) { if (comp > 0) { data = new int [comp]; }
else { data = new int [DEFAULT_VECTOR_SIZE];
comp = DEFAULT_VECTOR_SIZE; }
}
int size_ () const { return size; }
int comp_ () const { return comp; }
bool push_back (int);
bool push_front (int);
void expand ();
void expand (int);
void clear ();
const string at (int);
int& operator[ ](int);
int& operator[ ](int) const;
Vector& operator+ (Vector&);
Vector& operator- (const Vector&);
bool operator== (const Vector&);
bool operator!= (const Vector&);
~Vector() { delete [] data; }
};
ostream& operator<< (ostream&, const Vector&);
#endif
Vector.cpp
#include <iostream>
#include <string>
#include "Vector.h"
using namespace std;
const string Vector::at(int i) {
this[i];
}
void Vector::expand() {
expand(size);
}
void Vector::expand(int n ) {
int * newdata = new int [comp * 2];
if (*data != NULL) {
for (int i = 0; i <= (comp); i++) {
newdata[i] = data[i];
}
newdata -= comp;
comp += n;
data = newdata;
delete newdata;
}
else if ( *data == NULL || comp == 0) {
data = new int [DEFAULT_VECTOR_SIZE];
comp = DEFAULT_VECTOR_SIZE;
size = 0;
}
}
bool Vector::push_back(int n) {
if (comp = 0) { expand(); }
for (int k = 0; k != 2; k++) {
if ( size != comp ){
data[size] = n;
size++;
return true;
}
else {
expand();
}
}
return false;
}
void Vector::clear() {
delete [] data;
comp = 0;
size = 0;
}
int& Vector::operator[] (int place) { return (data[place]); }
int& Vector::operator[] (int place) const { return (data[place]); }
Vector& Vector::operator+ (Vector& n) {
int temp_int = 0;
if (size > n.size_() || size == n.size_()) { temp_int = size; }
else if (size < n.size_()) { temp_int = n.size_(); }
Vector newone(temp_int);
int temp_2_int = 0;
for ( int j = 0; j <= temp_int &&
j <= n.size_() &&
j <= size;
j++) {
temp_2_int = n[j] + data[j];
newone[j] = temp_2_int;
}
////////////////////////////////////////////////////////////
return newone;
////////////////////////////////////////////////////////////
}
ostream& operator<< (ostream& out, const Vector& n) {
for (int i = 0; i <= n.size_(); i++) {
////////////////////////////////////////////////////////////
out << n[i] << " ";
////////////////////////////////////////////////////////////
}
return out;
}
Errors:
out << n[i] << " "; error C2678:
binary '[' : no operator found which
takes a left-hand operand of type
'const Vector' (or there is no
acceptable conversion)
return newone;
error C2106: '=' : left
operand must be l-value
As stated above, I am a student going into Computer Science as my selected major I would appreciate tips, pointers, and better ways to do stuff :D
| This:
int operator[ ](int);
is a non-const member function. It means that it cannot be called on a const Vector.
Usually, the subscript operator is implemented such that it returns a reference (if you return a value, like you are doing, you can't use it as an lvalue, e.g. you can't do newone[j] = temp_2_int; like you have in your code):
int& operator[](int);
In order to be able to call it on a const object, you should also provide a const version of the member function:
const int& operator[](int) const;
Since you ask for "tips, pointers, and better ways to do stuff:"
You cannot name your include guard _VECTOR_H. Names beginning with an underscore followed by a capital letter are reserved for the implementation. There are a lot of rules about underscores.
You should never use using namespace std in a header.
Your operator+ should take a const Vector& since it is not going to modify its argument.
Your at should return an int and should match the semantics of the C++ standard library containers (i.e., it should throw an exception if i is out of bounds. You need to use (*this)[i] to call your overloaded operator[].
You need to learn what the * operator does. In several places you've confused pointers and the objects to which they point.
Watch out for confusing = with == (e.g. in if (comp = 0)). The compiler will warn you about this. Don't ignore warnings.
Your logic will be much simpler if you guarantee that data is never NULL.
|
2,567,847 | 2,567,858 | C++ Libraries similar to C#? | I'm coming to C++ from a .Net background. Knowing how to use the Standard C++ Libraries, and all the syntax, I've never ventured further. Now I'm looking learning a bit more, such as what libraries are commonly used? I want to start getting into Threading but have no idea to start. Is there a library (similar to how .net has System.Threading) out there that will make it a bit easier? I'm specifically looking to do Linux based network programming.
| For C++, Boost is your everything. Threading and networking are among the things it offers. But there's much more:
Smart pointers
Useful containers not found in the STL, such as fixed-size arrays and hashtables
Closures
Date/time classes
A foreach construct
Min/max functions
Command line option parsing
Regular expressions
|
2,567,906 | 2,567,927 | Returning a local object from a function | Is this the right way to return an object from a function?
Car getCar(string model, int year) {
Car c(model, year);
return c;
}
void displayCar(Car &car) {
cout << car.getModel() << ", " << car.getYear() << endl;
}
displayCar(getCar("Honda", 1999));
I'm getting an error, "taking address of temporary". Should I use this way:
Car &getCar(string model, int year) {
Car c(model, year);
return c;
}
| getCar returns a Car by value, which is correct.
You cannot pass that return value, which is a temporary object, into displayCar, because displayCar takes a Car&. You cannot bind a temporary to a non-const reference. You should change displayCar to take a const reference:
void displayCar(const Car& car) { }
Or, you can store the temporary in a local variable:
Car c = getCar("Honda", 1999);
displayCar(c);
But, it's better to have displayCar take a const reference since it doesn't modify the object.
Do not return a reference to the local Car variable.
|
2,567,980 | 2,568,016 | std::binary_function - no match for call? | include
#include <functional>
using namespace std;
int main() {
binary_function<double, double, double> operations[] = {
plus<double>(), minus<double>(), multiplies<double>(), divides<double>()
};
double a, b;
int choice;
cout << "Enter two numbers" << endl;
cin >> a >> b;
cout << "Enter opcode: 0-Add 1-Subtract 2-Multiply 3-Divide" << endl;
cin >> choice;
cout << operations[choice](a, b) << endl;
}
and the error I am getting is:
Calcy.cpp: In function ‘int main()’:
Calcy.cpp:17: error: no match for call to ‘(std::binary_function<double, double, double>) (double&, double&)’
Can anyone explain why I am getting this error and how to get rid of it?
| std::binary_function only contains typedefs for argument and return types. It was never intended to act as a polymorphic base class (and even if it was, you'd still have problems with slicing).
As an alternative, you can use boost::function (or std::tr1::function) like this:
boost::function<double(double, double)> operations[] = {
plus<double>(), minus<double>(), multiplies<double>(), divides<double>()
};
|
2,567,997 | 2,568,180 | Using a checked STL implementation, anything available for free? |
Have you used a checked STL implementation?
Did it find bugs you were not expecting?
Is there one I can try on Linux for free?
| The GNU implementation of the standard C++ library that comes with GCC has checked STL. Just add -D_GLIBCXX_DEBUG to your command line.
Yes, I've used it. I can't say for sure if it's caught bugs but it gives me more confidence that certain classes of bugs aren't being missed.
Because of performance overhead, we only use checked STL for debug builds.
|
2,568,194 | 2,568,331 | Populate a vector with all multimap values with a given key | Given a multimap<A,B> M what's a neat way to create a vector<B> of all values in M with a specific key.
e.g given a multimap how can I get a vector of all strings mapped to the value 123?
An answer is easy, looping from lower->upper bound, but is there a neat loop-free method?
| Here's the way to do it STL style :
// The following define is needed for select2nd with DinkumWare STL under VC++
#define _HAS_TRADITIONAL_STL 1
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <functional>
#include <map>
#include <iterator>
#include <iostream>
using namespace std;
void main()
{
typedef multimap<string, int> MapType;
MapType m;
vector<int> v;
// Test data
for(int i = 0; i < 10; ++i)
{
m.insert(make_pair("123", i * 2));
m.insert(make_pair("12", i));
}
MapType::iterator i = m.lower_bound("123");
MapType::iterator j = m.upper_bound("123");
transform(i, j, back_inserter(v), select2nd<MapType::value_type>());
copy(v.begin(), v.end(), ostream_iterator<int>(cout, ","));
}
|
2,568,230 | 2,569,086 | C++ STL vector iterator... but got runtime error | I'm studying STL and made win32 project..
But I got stuck in runtime error..
I tried to debug it but..
(partial code)
vector<Vertex> currPoly=polygons.back();
vector<Vertex>::iterator it;
for(it=currPoly.begin();it!=currPoly.end();++it){
vector<Vertex>::iterator p1;
vector<Vertex>::iterator n1;
vector<Vertex>::iterator n2;
if( it==currPoly.begin()){
p1=currPoly.end();
n1=it+1;
n2=it+2;
}else if( it==currPoly.end()-1){
p1=it-1;
n1=it+1;
n2=currPoly.begin();
}else if( it==currPoly.end()){
p1=it-1;
n1=currPoly.begin();
n2=currPoly.begin()+1;
}else{
p1=it-1;
n1=it+1;
n2=it+2;
}
int tmp;
tmp=it->x;
tmp=p1->x;
please click to see debugging picture
this is very strange because
in watch table,
n1,p1,it are defined but n2 isn't
and tmp is not either..
I can't find what is wrong...
please help..
| You should be a little more clear about exactly what your question is...
If it's that you're wondering why values for n1 and tmp can't be displayed in the debugger, I'm guessing that it's because you're debugging a release build (or some kind of build with optimizations), and the compiler has probably 'optimized away' those variables by that point in the execution flow (it decided they weren't used anymore or their values could be obtained elsewhere).
Try debugging a non-optimized build.
By the way, error CXX0017 (which is what the debugger is displaying for those variables) means, "Expression Evaluator Error".
|
2,568,243 | 2,568,275 | Linker error when compiling boost.asio example | I'm trying to learn a little bit C++ and Boost.Asio. I'm trying to compile the following code example:
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], "daytime");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
socket.close();
socket.connect(*endpoint_iterator++, error);
}
if (error)
throw boost::system::system_error(error);
for (;;)
{
boost::array<char, 128> buf;
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
std::cout.write(buf.data(), len);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
With the following command line:
g++ -I /usr/local/boost_1_42_0 a.cpp
and it throws an unclear error:
/tmp/ccCv9ZJA.o: In function `__static_initialization_and_destruction_0(int, int)':
a.cpp:(.text+0x654): undefined reference to `boost::system::get_system_category()'
a.cpp:(.text+0x65e): undefined reference to `boost::system::get_generic_category()'
a.cpp:(.text+0x668): undefined reference to `boost::system::get_generic_category()'
a.cpp:(.text+0x672): undefined reference to `boost::system::get_generic_category()'
a.cpp:(.text+0x67c): undefined reference to `boost::system::get_system_category()'
/tmp/ccCv9ZJA.o: In function `boost::system::error_code::error_code()':
a.cpp:(.text._ZN5boost6system10error_codeC2Ev[_ZN5boost6system10error_codeC5Ev]+0x10): undefined reference to `boost::system::get_system_category()'
/tmp/ccCv9ZJA.o: In function `boost::asio::error::get_system_category()':
a.cpp:(.text._ZN5boost4asio5error19get_system_categoryEv[boost::asio::error::get_system_category()]+0x7): undefined reference to `boost::system::get_system_category()'
/tmp/ccCv9ZJA.o: In function `boost::asio::detail::posix_thread::~posix_thread()':
a.cpp:(.text._ZN5boost4asio6detail12posix_threadD2Ev[_ZN5boost4asio6detail12posix_threadD5Ev]+0x1d): undefined reference to `pthread_detach'
/tmp/ccCv9ZJA.o: In function `boost::asio::detail::posix_thread::join()':
a.cpp:(.text._ZN5boost4asio6detail12posix_thread4joinEv[boost::asio::detail::posix_thread::join()]+0x25): undefined reference to `pthread_join'
/tmp/ccCv9ZJA.o: In function `boost::asio::detail::posix_tss_ptr<boost::asio::detail::call_stack<boost::asio::detail::task_io_service<boost::asio::detail::epoll_reactor<false> > >::context>::~posix_tss_ptr()':
a.cpp:(.text._ZN5boost4asio6detail13posix_tss_ptrINS1_10call_stackINS1_15task_io_serviceINS1_13epoll_reactorILb0EEEEEE7contextEED2Ev[_ZN5boost4asio6detail13posix_tss_ptrINS1_10call_stackINS1_15task_io_serviceINS1_13epoll_reactorILb0EEEEEE7contextEED5Ev]+0xf): undefined reference to `pthread_key_delete'
/tmp/ccCv9ZJA.o: In function `boost::asio::detail::posix_tss_ptr<boost::asio::detail::call_stack<boost::asio::detail::task_io_service<boost::asio::detail::epoll_reactor<false> > >::context>::posix_tss_ptr()':
a.cpp:(.text._ZN5boost4asio6detail13posix_tss_ptrINS1_10call_stackINS1_15task_io_serviceINS1_13epoll_reactorILb0EEEEEE7contextEEC2Ev[_ZN5boost4asio6detail13posix_tss_ptrINS1_10call_stackINS1_15task_io_serviceINS1_13epoll_reactorILb0EEEEEE7contextEEC5Ev]+0x22): undefined reference to `pthread_key_create'
collect2: ld returned 1 exit status
How can I fix it?
| you need to link against libboost_system and apparently also against libboost_thread.
g++ -I /usr/local/boost_1_42_0 -lboost_system -lboost_thread a.cpp
in case of multi-threaded libraries:
g++ -I /usr/local/boost_1_42_0 -lboost_system-mt -lboost_thread-mt a.cpp
|
2,568,294 | 2,568,322 | Is it a good idea to create an STL iterator which is noncopyable? | Most of the time, STL iterators are CopyConstructable, because several STL algorithms require this to improve performance, such as std::sort.
However, I've been working on a pet project to wrap the FindXFile API (previously asked about), but the problem is it's impossible to implement a copyable iterator around this API. A find handle cannot be duplicated by any means -- DuplicateHandle specifically forbids passing these types of handles to it. And if you just maintain a reference count to the find handle, then a single increment by any copy results in an increment of all copies -- clearly that is not what a copy constructed iterator is supposed to do.
Since I can't satisfy the traditional copy constructible requirement for iterators here, is it even worth trying to create an "STL style" iterator? On one hand, creating some other enumeration method is going to not fall into normal STL conventions, but on the other, following STL conventions are going to confuse users of this iterator if they try to CopyConstruct it later.
Which is the lesser of two evils?
| An input iterator which is not a forward iterator is copyable, but you can only "use" one of the copies: incrementing any of them invalidates the others (dereferencing one of them does not invalidate the others). This allows it to be passed to algorithms, but the algorithm must complete with a single pass. You can tell which algorithms are OK by checking their requirements - for example copy requires only an InputIterator, whereas adjacent_find requires a ForwardIterator (first one I found).
It sounds to me as though this describes your situation. Just copy the handle (or something which refcounts the handle), without duplicating it.
The user has to understand that it's only an InputIterator, but in practice this isn't a big deal. istream_iterator is the same, and for the same reason.
With the benefit of C++11 hindsight, it would almost have made sense to require InputIterators to be movable but not to require them to be copyable, since duplicates have limited use anyway. But that's "limited use", not "no use", and anyway it's too late now to remove functionality from InputIterator, considering how much code relies on the existing definition.
|
2,568,446 | 2,573,596 | What are the best (portable) cross-platform arbitrary-precision math libraries? | I’m looking for a good arbitrary precision math library in C or C++. Could you please give me some advices or suggestions?
The primary requirements:
It must handle arbitrarily big integers—my primary interest is on integers. In case that you don’t know what the word arbitrarily big means, imagine something like 100000! (the factorial of 100000).
The precision must not need to be specified during library initialization or object creation. The precision should only be constrained by the available resources of the system.
It should utilize the full power of the platform, and should handle “small” numbers natively. That means on a 64-bit platform, calculating (2^33 + 2^32) should use the available 64-bit CPU instructions. The library should not calculate this in the same way as it does with (2^66 + 2^65) on the same platform.
It must efficiently handle addition (+), subtraction (-), multiplication (*), integer division (/), remainder (%), power (**), increment (++), decrement (--), GCD, factorial, and other common integer arithmetic calculations. The ability to handle functions like square root and logarithm that do not produce integer results is a plus. The ability to handle symbolic computations is even better.
Here are what I found so far:
Java's BigInteger and BigDecimal class: I have been using these so far. I have read the source code, but I don’t understand the math underneath. It may be based on theories and algorithms that I have never learnt.
The built-in integer type or in core libraries of bc, Python, Ruby, Haskell, Lisp, Erlang, OCaml, PHP, some other languages: I have used some of these, but I have no idea which library they are using, or which kind of implementation they are using.
What I have already known:
Using char for decimal digits and char* for decimal strings, and do calculations on the digits using a for-loop.
Using int (or long int, or long long) as a basic “unit” and an array of that type as an arbitrary long integer, and do calculations on the elements using a for-loop.
Using an integer type to store a decimal digit (or a few digits) as BCD (Binary-coded decimal).
Booth’s multiplication algorithm.
What I don’t know:
Printing the binary array mentioned above in decimal without using naive methods. An example of a naive method: (1) add the bits from the lowest to the highest: 1, 2, 4, 8, 16, 32, … (2) use a char*-string mentioned above to store the intermediate decimal results).
What I appreciate:
Good comparisons on GMP, MPFR, decNumber (or other libraries that are good in your opinion).
Good suggestions on books and articles that I should read. For example, an illustration with figures on how a non-naive binary-to-decimal conversion algorithm works would be good. The article “Binary to Decimal Conversion in Limited Precision” by Douglas W. Jones is an example of a good article.
Any help in general.
Please do not answer this question if you think that using double (or long double, or long long double) can solve this problem easily. If you do think so, you don’t understand the issue in question.
| GMP is the popular choice. Squeak Smalltalk has a very nice library, but it's written in Smalltalk.
You asked for relevant books or articles. The tricky part of bignums is long division. I recommend Per Brinch Hansen's paper Multiple-Length Division Revisited: A Tour of the Minefield.
|
2,568,612 | 2,569,669 | Linking with Boost error | I just downloaded and ran the boost installer for version 1.42 (from boostpro.com), and set up my project according to the getting started guide. However, when I build the program, I get this linker error:
LINK : fatal error LNK1104: cannot open file 'libboost_program_options-vc90-mt-gd-1_42.lib'
The build log adds this (I've replaced project-specific paths with *'s):
Creating temporary file "******\Debug\RSP00001252363252.rsp" with contents
[
/OUT:"*********.exe" /INCREMENTAL /LIBPATH:"C:\Program Files\boost\boost_1_42_0\lib" /MANIFEST /MANIFESTFILE:"Debug\hw6.exe.intermediate.manifest" /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /DEBUG /PDB:"********\Debug\***.pdb" /SUBSYSTEM:CONSOLE /DYNAMICBASE /NXCOMPAT /MACHINE:X86 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib
".\Debug\****.obj"
".\Debug\****.exe.embed.manifest.res"
]
Creating command line "link.exe @********\Debug\RSP00001252363252.rsp /NOLOGO /ERRORREPORT:PROMPT"
I've also emailed info@boostpro.com (with a message very similar to this), but I thought maybe so would be faster.
EDIT: Yes, I checked if the file was there before asking this question, and yes, it's path is in the linker properties, under "Additional Library Directories" (I've tried with and without quotes).
EDIT 2: And it definitely sees the path because it appears in the 3rd line of the build log...
EDIT 4: Nevermind, it doesn't work in release mode or debug mode, but the file that doesn't work changes appropriately (same when I change the runtime library to a different type of multithreaded - I don't see single-threaded as an option, although it would work for me). Trying command line now.
| There's a slight difference between the documentation and my actual installation. Where the documentation has "boost_1_42_0" in the path, the installer made my path "boost_1_42". With that fixed, it works.
|
2,568,933 | 2,569,573 | Upper bound for custom rand48 | I'm using a custom random number function rand48 in CUDA. The function does not allow an upperbound to be set, but I require the output to be between 0 and 1.
I guess I'm missing something but how would I convert the output to be between 0 and 1, the length of the number can change e.g. 697135872 would need to be divided by 100000000 and 29186668 would need to be divided by 100000000.
Thanks everyone
| If your PRNG behaves like rand then it generates numbers between 0 and RAND_MAX with uniform probability. You just have to multiply by 1.f/RAND_MAX.
If you divide by different numbers in different cases, you will end up with non-uniform distribution.
|
2,568,996 | 2,569,017 | What container type provides better (average) performance than std::map? | In the following example a std::map structure is filled with 26 values from A - Z (for key) and 0 - 26 for value. The time taken (on my system) to lookup the last entry (10000000 times) is roughly 250 ms for the vector, and 125 ms for the map. (I compiled using release mode, with O3 option turned on for g++ 4.4)
But if for some odd reason I wanted better performance than the std::map, what data structures and functions would I need to consider using?
I apologize if the answer seems obvious to you, but I haven't had much experience in the performance critical aspects of C++ programming.
#include <ctime>
#include <map>
#include <vector>
#include <iostream>
struct mystruct
{
char key;
int value;
mystruct(char k = 0, int v = 0) : key(k), value(v) { }
};
int find(const std::vector<mystruct>& ref, char key)
{
for (std::vector<mystruct>::const_iterator i = ref.begin(); i != ref.end(); ++i)
if (i->key == key) return i->value;
return -1;
}
int main()
{
std::map<char, int> mymap;
std::vector<mystruct> myvec;
for (int i = 'a'; i < 'a' + 26; ++i)
{
mymap[i] = i - 'a';
myvec.push_back(mystruct(i, i - 'a'));
}
int pre = clock();
for (int i = 0; i < 10000000; ++i)
{
find(myvec, 'z');
}
std::cout << "linear scan: milli " << clock() - pre << "\n";
pre = clock();
for (int i = 0; i < 10000000; ++i)
{
mymap['z'];
}
std::cout << "map scan: milli " << clock() - pre << "\n";
return 0;
}
| For your example, use int value(char x) { return x - 'a'; }
More generalized, since the "keys" are continuous and dense, use an array (or vector) to guarantee Θ(1) access time.
If you don't need the keys to be sorted, use unordered_map, which should provide amortized logarithmic improvement (i.e. O(log n) -> O(1)) to most operations.
(Sometimes, esp. for small data sets, linear search is faster than hash table (unordered_map) / balanced binary trees (map) because the former has a much simpler algorithm, thus reducing the hidden constant in big-O. Profile, profile, profile.)
|
2,569,046 | 2,569,211 | Is there a way to increase the efficiency of shared_ptr by storing the reference count inside the controlled object? | This is becoming a common pattern in my code, for when I need to manage an object that needs to be noncopyable because either A. it is "heavy" or B. it is an operating system resource, such as a critical section:
class Resource;
class Implementation : public boost::noncopyable
{
friend class Resource;
HANDLE someData;
Implementation(HANDLE input) : someData(input) {};
void SomeMethodThatActsOnHandle() {
//Do stuff
};
public:
~Implementation() { FreeHandle(someData) };
};
class Resource
{
boost::shared_ptr<Implementation> impl;
public:
Resource(int argA) explicit {
HANDLE handle =
SomeLegacyCApiThatMakesSomething(argA);
if (handle == INVALID_HANDLE_VALUE)
throw SomeTypeOfException();
impl.reset(new Implementation(handle));
};
void SomeMethodThatActsOnTheResource() {
impl->SomeMethodThatActsOnTheHandle();
};
};
This way, shared_ptr takes care of the reference counting headaches, allowing Resource to be copyable, even though the underlying handle should only be closed once all references to it are destroyed.
However, it seems like we could save the overhead of allocating shared_ptr's reference counts and such separately if we could move that data inside Implementation somehow, like boost's intrusive containers do.
If this is making the premature optimization hackles nag some people, I actually agree that I don't need this for my current project. But I'm curious if it is possible.
| A partial solution is to use make_shared to create your shared_ptrs. For example,
auto my_thing = std::make_shared<Thing>();
instead of
auto my_thing = std::shared_ptr<Thing>(new Thing);
It's still non-intrusive, so nothing else needs to change. Good implementations of make_shared combine the memory allocation for the reference count and the object itself. That saves a memory allocation and keeps the count close to the object for better locality. It's not quite as efficient as something like boost:intrusive_ptr, but it's worth considering.
|
2,569,234 | 2,569,259 | Problems with delete in destructor | I wrote this code.
The constructor works normally, but in the destructor I get "Windows has triggered a breakpoint." How should I correct this?
template class CyclicalArray {
private:
T* mem_ptr;
public:
CyclicalArray(size_t capacity, const T& default_value) {
this->default_value = default_value;
this->capacity = capacity;
head_index = 0;
mem_ptr = ::new T[capacity]; //memory allocating
for(T* p = mem_ptr; p < mem_ptr + capacity * sizeof(T); p += sizeof(T)) {
::new (p) T (default_value); //initialization
}
}
~CyclicalArray() {
for(T* p = mem_ptr + sizeof(T); p < mem_ptr + capacity * sizeof(T); p += sizeof(T)) {
p->~T();
}
delete[] mem_ptr;
}
| If you're going to perform placement new, you need to do it on raw memory. Something like:
template class CyclicalArray {
private:
T* mem_ptr;
public:
CyclicalArray(size_t capacity, const T& default_value) {
this->default_value = default_value;
this->capacity = capacity;
head_index = 0;
mem_ptr = reinterpret_cast<T*>( ::new char[capacity * sizeof(T)]); //memory allocating
for(T* p = mem_ptr; p < mem_ptr + capacity; ++p) {
::new (p) T (default_value); //initialization
}
}
~CyclicalArray() {
// this
for(T* p = mem_ptr + capacity; p != mem_ptr; --p) {
(p-1)->~T();
}
delete[] reinterpret_cast<char*>( mem_ptr);
}
Otherwise you'll call the T destructor twice on the same object memory (not a good thing to do).
Also, since your p pointers are of type T*, you can perform simple increment/decrements on it - the compiler will deal with the sizeof(T) issue as a normal course of pointer arithmetic.
Finally, strictly speaking you should destroy the array elements in descending order (the opposite of construction).
I hope this catches most or all the bugs.
You might really want to consider using something like std::vector as the store. An example using std::vector<> follows (with a few other syntax fixes). I'm not sure if your class would really need a copy of the default_value or the head_index - I left them in assuming that you plan to use them in other methods:
#include <vector>
template <typename T>
class CyclicalArray {
private:
std::vector<T> backing_store;
T default_value;
size_t head_index;
public:
CyclicalArray(size_t capacity, const T& def_val) :
backing_store(capacity, def_val),
default_value( def_val),
head_index(0) {
}
~CyclicalArray() {}
};
Note how much simpler the constructor and destructor are, since all the complexity of your first class is managed by std:vector.
|
2,569,576 | 2,569,588 | How to create a const boost matrix? | How can I create a const boost matrix?
The following did not work:
const boost::numeric::ublas::matrix<double> arrayM(1, 3) = { {1.0, 2.0, 3.0} };
| Usually something akin to:
typedef boost::numeric::ublas::matrix<double> matrix_type;
const matrix_type get_matrix(void)
{
matrix_type result(1, 3);
result(0, 0) = 1;
result(0, 1) = 2;
result(0, 2) = 3;
return result;
}
const matrix_type arrayM = get_matrix();
You might also try something like this (mostly untested):
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
template <typename T, typename L = boost::numeric::ublas::row_major,
typename A = boost::numeric::ublas::unbounded_array<T> >
class matrix_builder
{
public:
// types
typedef boost::numeric::ublas::matrix<T, L, A> matrix_type;
typedef typename matrix_type::size_type size_type;
// creation
matrix_builder(size_type pRows, size_type pColumns) :
mMatrix(pRows, pColumns),
mRow(0),
mColumn(0)
{}
matrix_builder& operator()(const T& pValue)
{
mMatrix(mRow, mColumn) = pValue;
if (++mColumn == mMatrix.size2())
{
mColumn = 0;
mRow++;
}
return *this;
}
// access
operator const matrix_type&(void) const
{
return mMatrix;
}
private:
// non copyable
matrix_builder(const matrix_builder&);
matrix_builder& operator=(const matrix_builder&);
// members
matrix_type mMatrix;
size_type mRow;
size_type mColumn;
};
typedef boost::numeric::ublas::matrix<double> matrix_type;
static const matrix_type m1 = matrix_builder<double>(3, 1)
(1)(2)(3);
static const matrix_type m2 = matrix_builder<double>(3, 3)
(1)(2)(3)
(4)(5)(6)
(7)(8)(9);
int main(void)
{
std::cout << m1 << std::endl;
std::cout << m2 << std::endl;
}
Same idea, more generic. Also a bit more visual, which can be nice.
|
2,569,602 | 2,569,618 | Is there a practical benefit to casting a NULL pointer to an object and calling one of its member functions? | Ok, so I know that technically this is undefined behavior, but nonetheless, I've seen this more than once in production code. And please correct me if I'm wrong, but I've also heard that some people use this "feature" as a somewhat legitimate substitute for a lacking aspect of the current C++ standard, namely, the inability to obtain the address (well, offset really) of a member function. For example, this is out of a popular implementation of a PCRE (Perl-compatible Regular Expression) library:
#ifndef offsetof
#define offsetof(p_type,field) ((size_t)&(((p_type *)0)->field))
#endif
One can debate whether the exploitation of such a language subtlety in a case like this is valid or not, or even necessary, but I've also seen it used like this:
struct Result
{
void stat()
{
if(this)
// do something...
else
// do something else...
}
};
// ...somewhere else in the code...
((Result*)0)->stat();
This works just fine! It avoids a null pointer dereference by testing for the existence of this, and it does not try to access class members in the else block. So long as these guards are in place, it's legitimate code, right? So the question remains: Is there a practical use case, where one would benefit from using such a construct? I'm especially concerned about the second case, since the first case is more of a workaround for a language limitation. Or is it?
PS. Sorry about the C-style casts, unfortunately people still prefer to type less if they can.
| The first case is not calling anything. It's taking the address. That's a defined, permitted, operation. It yields the offset in bytes from the start of the object to the specified field. This is a very, very, common practice, since offsets like this are very commonly needed. Not all objects can be created on the stack, after all.
The second case is reasonably silly. The sensible thing would be to declare that method static.
|
2,569,655 | 2,569,665 | How to define a static array without a contant size in a constructor of a class? (C++) | I have a class defined as:
class Obj {
public:
int width, height;
Obj(int w, int h);
}
and I need it to contain a static array like so:
int presc[width][height];
however, I cannot define within the class, so it it possible to create a pointer to a 2D array (and, out of curiosity, 3, 4, and 5D arrays), have that as a member of the class, and intitalize it in the constructor like:
int ar[5][6];
Obj o(5, 6, &ar);
EDIT: The idea here is that every object will have a different width and height, so the array I use to represent that object will be unique to the object, but once that array is defined (preferably in the constructor), it will not change. And the values of width and height for a particular object are known at compile time.
EDIT: The arrays are for collision detection by superimposing the presc arrays of two objects onto one large array, and seeing where the overlap, declarations like so:
Obj player1(32, 32); //player with a width of 32 px and height of 32 px, presc[32][32]
Obj boss(500, 500); //boss with a width of 500 px and height of 500 px, presc[500][500]
| If, by "dynamic", you mean "heap-allocated", then no, there is no way to this with the current Obj. OTOH, if you know w and h at compile time:
template <int W, int H>
class Obj {
public:
// ...
private:
int presc[W][H];
}
|
2,569,662 | 2,569,675 | is there a way to use cin.getline() without having to define a char array size before hand? | Basically my task is having to sort a bunch of strings of variable length ignoring case. I understand there is a function strcasecmp() that compares cstrings, but doesn't work on strings. Right now I'm using getline() for strings so I can just read in the strings one line at a time. I add these to a vector of strings, then convert to cstrings for each call of strcasecmp(). Instead of having to convert each string to a cstring before comparing with strcasecmp(), I was wondering if there was a way I could use cin.getline() for cstrings without having a predefined char array size. Or, would the best solution be to just read in string, convert to cstring, store in vector, then sort?
| I assume by "convert to cstring" you mean using the c_str() member of string. If that is the case, in most implementation that isn't really a conversion, it's just an accessor. The difference is only important if you are worried about performance (which it sounds like you are). Internally std::strings are (pretty much always, but technically do not have to be) represented as a "cstring". The class takes care of managing it's size for you, but it's just a dynamically allocated cstring underneath.
So, to directly answer: You have to specify the size of the array when using cin.getline. If you don't want to specify a size, then use getline and std::string. There's nothing wrong with that approach.
|
2,569,695 | 2,569,791 | How can I synchronize database access between a write-thread and a read-thread? | My program has two threads:
Main execution thread that handles user input and queues up database writes
A utility thread that wakes up every second and flushes the writes to the database
Inside the main thread, I occasionally need to make reads on the database. When this happens, performance is not important, but correctness is. (In a perfect world, I would be reading from a cache, not making a round-trip to the database - but let's put that aside for the sake of discussion.)
How do I make sure that the main thread sees a correct / quiescent database?
A standard mutex won't work, since I run the risk of having the main thread grab the mutex before the data gets flushed to the database. This would be a big race condition.
What I really want is some sort of mutex that lets the main thread of execution proceed only AFTER the mutex has been grabbed and released once. Does such a thing exist? What's the best way to solve this problem?
UPDATE: After doing some additional research, I might use Boost's Conditional Variable to address this problem. Either that, or just bite the bullet and cache my writes. Thanks for the feedback!
| If you don't have more than one main execution thread (ie, the only thread that will push writes onto the worker thread is the same thread that will be reading from the database), then you can probably just have a simple "pending writes" variable/function that you can check before sending a read, and spinlock or wait for a signal until the writes have been flushed. It sounds like you won't need to perform any locking or synchonization on the writes, if they can simply be queued up to be processed by the worker thread.
Basically, as long as you are guaranteed that in between the check for that 'pending writes' state and when you actually perform the read, there are no writes, then you don't need to do anything too fancy.
|
2,569,738 | 2,569,751 | how to access child instances in a vector in c++ | I have a parent class and child class (inherited from parent).
In the child class, I have a member function named function_blah();
I used vector<parent*> A to store 5 parent instances, 3 child instances. So the total number of elements in the vector is 8.
I can easily access to member functions of element A[0] to A[4], which are parent instances.
But whenever I try to have access to member functions of element A[5] to A[7], the compiler complains that class parent has no member named 'function_blah'
The way I access to elements is using index. e.x A[i] with i = 0..7. Is it correct? if not, how?
| You need to downcast the pointer to the child class in order to use child functions on it.
When you're accessing a child object using a parent*, you are effectively telling the compiler, "treat this object as a parent". Since function_blah() only exists on the child, the compiler doesn't know what to do.
You can ameliorate this by downcasting using the dynamic_cast operator:
child* c = dynamic_cast<child*>(A[6]);
c->function_blah();
This will perform a runtime-checked, type-safe cast from the parent* to a child* where you can call function_blah().
This solution only works if you know that the object you're pulling out is definitely a child and not a parent. If there's uncertainty, what you need to do instead is use inheritance and create a virtual method on the parent which you then overload on the child.
|
2,569,782 | 2,569,819 | C++ Exceptions and Inheritance from std::exception | Given this sample code:
#include <iostream>
#include <stdexcept>
class my_exception_t : std::exception
{
public:
explicit my_exception_t()
{ }
virtual const char* what() const throw()
{ return "Hello, world!"; }
};
int main()
{
try
{ throw my_exception_t(); }
catch (const std::exception& error)
{ std::cerr << "Exception: " << error.what() << std::endl; }
catch (...)
{ std::cerr << "Exception: unknown" << std::endl; }
return 0;
}
I get the following output:
Exception: unknown
Yet simply making the inheritance of my_exception_t from std::exception public, I get the following output:
Exception: Hello, world!
Could someone please explain to me why the type of inheritance matters in this case? Bonus points for a reference in the standard.
| When you inherit privately, you cannot convert to or otherwise access that base class outside of the class. Since you asked for something from the standard:
§11.2/4:
A base class is said to be accessible if an invented public member of the base class is accessible. If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class (4.10, 4.11).
Simply put, to anything outside the class it's like you never inherited from std::exception, because it's private. Ergo, it will not be able to be caught in the std::exception& clause, since no conversion exists.
|
2,569,940 | 2,611,899 | SFML SetFramerateLimit Not Limiting Frame Rate | Compiler: Visual C++
OS: Windows 7 Enterprise
For some reason, Window::SetFramerateLimit isn't limiting the frame rate in the app I'm working on, but it works fine for others. The framerate is capped to 60, but mine jumps around at 100-99 and then goes down to 50 sometimes. It actually causes serious issues. For example, if I create many objects on screen, I'll see a heavy performance hit, whereas others report no change.
Any ideas regarding why this is happening? If you need more information, I'd be happy to oblige.
Thanks.
P.S. I have strong reasons to believe that it is not simply a case of "their hardware is just more powerful than yours."
| Solved by setting vertical sync to true.
|
2,570,036 | 2,570,037 | Why does converting from a size_t to an unsigned int give me a warning? | I have the code:
unsigned int length = strlen(somestring);
I'm compiling with the warning level on 4, and it's telling me that "conversion from size_t to unsigned int, possible loss of data" when a size_t is a typedef for an unsigned int.
Why!?
Edit:
I just solved my own problem. I'm an XP user, and my compiler was checking for 64 bit compatibility. Since size_t is platform dependent, for 64 bit it would be an unsigned long long, where that is not the same as an unsigned int.
| Because unsigned int is a narrower type on your machine than size_t. Most likely size_t is 64 bits wide, while unsigned int is 32 bits wide.
EDIT: size_t is not a typedef for unsigned int.
|
2,570,223 | 2,570,224 | Should a warning or perhaps even an assertion failure be produced if delete is used to free memory obtained using malloc()? | In C++ using delete to free memory obtained with malloc() doesn't necessarily cause a program to blow up.
Should a warning or perhaps even an assertion failure should be produced if delete is used to free memory obtained using malloc()?
Why did Stroustrup not have this feature on C++?
|
In C++ using delete to free memory obtained with malloc() doesn't necessarily cause a program to blow up.
No, but it does necessarily result in undefined behavior, which means that anything can happen, including the program blowing up or the program continuing to run in what appears to be a correct manner.
Do you guys think a warning or perhaps even an assertion failure should be produced if delete is used to free memory obtained using malloc()??
No. This is difficult, if not impossible, to check at compile time. Runtime checks are expensive, and in C++, you don't get what you don't pay for.
It might be a useful option to turn on while debugging, but really, the correct answer is just don't mix and match them. I've not once had trouble with this.
|
2,570,235 | 2,570,240 | Initialize a static member ( an array) in C++ | I intended to create a class which only have static members and static functions. One of the member variable is an array. Would it be possible to initialize it without using constructors? I am having lots of linking errors right now...
class A
{
public:
static char a[128];
static void do_something();
};
How would you initialize a[128]? Why can't I initialize a[128] by directly specifying its value like in C?
a[128] = {1,2,3,...};
| You can, just do this in your .cpp file:
char A::a[6] = {1,2,3,4,5,6};
|
2,570,275 | 2,570,288 | Using Visual studio .ncb file for reflection | I am developing visual game level editor in C++.
For this I want reflection(RTTI) mechanism to know class attributes at runtime.
I am currently using PDB files for this.But using PDB I couldn't retrieve actual code line for extra information in commented format which is given for that attribute.
Visual studio uses NCB files for intelligence.
So will it be better idea to use NCB instead PDB?
If yes,How to retrieve information from NCB files?
Is there any SDK like DIA SDK?
| The NCB file format isn't publicly documented and changes with every version of Visual Studio. With the upcoming VS2010 (due out in about a week and a half), it's going away entirely in favor of a new SQL-based format that should be much easier to work with. Microsoft is also implementing an API for integrating with the Intellisense data from the parser.
|
2,570,551 | 2,571,533 | It won't create a Java VM (JNI) | My simple command line app:
int _tmain(int argc, _TCHAR* argv[])
{
JavaVM *jvm;
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options[1];
options[0].optionString = "-Djava.class.path=."; //Path to the java source code
vm_args.version = JNI_VERSION_1_6; //JDK version. This indicates version 1.6
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = 0;
jint ret = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
return 0;
}
gives me:
Error occurred during initialization of VM
Unable to load native library: Can't find dependent libraries
The breakpoint at "return 0" is never reached. jvm.dll resides in same directory as my command line app.
I don't get it what's wrong. Any Ideas? Thanx in advance
| I think that your problem is answered by this question in the Sun JNI FAQ.
TL;DR version: Don't move the JVM installation's DLLs.
|
2,570,552 | 2,570,593 | Why are new()/delete() slower than malloc()/free()? | Why new()/delete() is slower than malloc()/free()?
EDIT:
Thanks for the answers so far. Please kindly point out specifications of standard C++ implementation of new() and delete() if you have them thanks!
| Look at this piece of C code:
struct data* pd = malloc(sizeof(struct data));
init_data(pd);
The new operator in C++ is essentially doing what the above piece of code does. That's why it is slower than malloc().
Likewise with delete. It's doing the equivalent of this:
deinit_data(pd);
free(pd);
If the constructors and destructors are empty (like for built-ins), new and delete shouldn't be slower than malloc() and free() are. (If they are, it's often due to the fact that common implementations call malloc()/free() under the hood, so they are a wrapper around them. Wrapping costs. Also, there might be code that needs to find out that no constructors/destructors are to be called. That would cost, too.)
Edit To answer your additional question:
new and delete aren't functions, they are operators. This: new data() is called a new expression. It does two things. First it calls the operator new, then it initializes the object, usually by invoking the appropriate constructor. (I say "usually" because built-ins don't have constructors. But a new expression involving a built-in works the same nevertheless.)
You can manipulate both of these phases. You can create your own constructors to manipulate initialization of your types and you can overload operator new (even with several overloads having different additional arguments and also specifically for each class, if you want) in order to manipulate allocation of free storage. If you don't implement your own operator new, the version from the standard library is used. A common implementation of this calls malloc().
Likewise, if you write delete pd, called a delete expression, two things happen: depending on pd, the object is de-initialized, usually by calling its destructor, then the memory is released by calling the appropriate operator delete.
Again, you can manipulate both phase, by writing your own destructor, and by writing your own version of operator delete. (The version of operator delete that comes with your standard library is often implemented to call free().)
|
2,570,584 | 2,570,586 | iteration on numbers with no 2 same digits | I dont know if it is asked (I couldn't find any).
I want to iterate on this kind of numbers implemented on array;
int a[10];
int i = 0;
for( ; i < 10; i++ )
a[i] = i+1;
now the array has
"1 2 3 4 5 6 7 8 9 10"
and I want to get "1 2 3 4 5 6 7 8 10 9"
and then "1 2 3 4 5 6 7 9 8 10"
"1 2 3 4 5 6 7 9 10 8" . . . .
I tried to get an algorithm but I couldn't figure it out.
Is there an easy way to implement "next" iterator for this kind of problems?
Thanks in advance
| Check std::next_permutation.
|
2,570,643 | 2,570,682 | Putting a C++ Vector as a Member in a Class that Uses a Memory Pool | I've been writing a multi-threaded DLL for database access using ADO/ODBC for use with a legacy application. I need to keep multiple database connections for each thread, so I've put the ADO objects for each connection in an object and thinking of keeping an array of them inside a custom threadInfo object. Obviously a vector would serve better here - I need to delete/rearrange objects on the go and a vector would simplify that. Problem is, I'm allocating a heap for each thread to avoid heap contention and stuff and allocating all my memory from there.
So my question is: how do I make the vector allocate from the thread-specific heap? (Or would it know internally to allocate memory from the same heap as its wrapper class - sounds unlikely, but I'm not a C++ guy) I've googled a bit and it looks like I might need to write an allocator or something - which looks like so much of work I don't want. Is there any other way? I've heard vector uses placement-new for all its stuff inside, so can overloading operator new be worked into it?
My scant knowledge of the insides of C++ doesn't help, seeing as I'm mainly a C programmer (even that - relatively). It's very possible I'm missing something elementary somewhere. If nothing easier comes up - I might just go and do the array thing, but hopefully it won't come to that.
I'm using MS-VC++ 6.0 (hey, it's rude to laugh! :-P ).
Any/all help will be much appreciated.
|
how do I make the vector allocate from the thread-specific heap?
You pass it (at compile-time) an appropriate allocator. Here is a classic on how to do so. If you follow that article's advice (or even just copy the code and adapt it where needed), for a C programmer writing an allocator might be easier than getting right the copy semantics of a class with a dynamically allocated array.
Note that, if you put objects into the vector (or your own array, FTM), which themselves use the heap (strings, for example), you need to take that they use your special heap, too. For containers of the standard library (std::basic_string<> is such a container) it's easy since you can pass them your allocator as well. For your own types you have to make that sure yourself.
And try to get away from VC6 as fast as possible. It's poisonous.
|
2,570,679 | 2,571,212 | Serialization with Qt | I am programming a GUI with Qt library. In my GUI I have a huge std::map.
"MyType" is a class that has different kinds of fields.
I want to serialize the std::map. How can I do that? Does Qt provides us with neccesary features?
| QDataStream handles a variety of C++ and Qt data types. The complete list is available at http://doc.qt.io/qt-4.8/datastreamformat.html. We can also add support for our own custom types by overloading the << and >> operators. Here's the definition of a custom data type that can be used with QDataStream:
class Painting
{
public:
Painting() { myYear = 0; }
Painting(const QString &title, const QString &artist, int year) {
myTitle = title;
myArtist = artist;
myYear = year;
}
void setTitle(const QString &title) { myTitle = title; }
QString title() const { return myTitle; }
...
private:
QString myTitle;
QString myArtist;
int myYear;
};
QDataStream &operator<<(QDataStream &out, const Painting &painting);
QDataStream &operator>>(QDataStream &in, Painting &painting);
Here's how we would implement the << operator:
QDataStream &operator<<(QDataStream &out, const Painting &painting)
{
out << painting.title() << painting.artist()
<< quint32(painting.year());
return out;
}
To output a Painting, we simply output two QStrings and a quint32. At the end of the function, we return the stream. This is a common C++ idiom that allows us to use a chain of << operators with an output stream. For example:
out << painting1 << painting2 << painting3;
The implementation of operator>>() is similar to that of operator<<():
QDataStream &operator>>(QDataStream &in, Painting &painting)
{
QString title;
QString artist;
quint32 year;
in >> title >> artist >> year;
painting = Painting(title, artist, year);
return in;
}
This is from: C++ GUI Programming with Qt 4 By Jasmin Blanchette, Mark Summerfield
|
2,570,901 | 2,570,903 | Object does not exist after constructor? | I have a constructor that looks like this (in c++):
Interpreter::Interpreter() {
tempDat == new DataObject();
tempDat->clear();
}
the constructor of dataObject does absolutely nothing, and clear does this:
bool DataObject::clear() {
//clear the object
if (current_max_id > 0) {
indexTypeLookup.clear();
intData.clear();
doubleData.clear();
current_max_id = 0;
}
}
Those members are defined as follows:
std::map<int, int> indexTypeLookup;
std::map<int, int> intData;
std::map<int, double> doubleData;
Now the strange thing is that I'm getting a segfault on tempDat->clear(); gdb says tempDat is null. How is that possible? The constructor of tempDat cannot fail, it looks like this:
DataObject::DataObject() : current_max_id(0)
{
}
I know there are probably better way's of making such a data structure, but I really like to know where this segfault problem is coming from..
| Interpreter::Interpreter() {
tempDat == new DataObject(); // <- here
tempDat->clear();
}
You're using == to assign. Use = instead:
tempDat = new DataObject();
Using == gives you an expression that compares the current value of tempDat (some random garbage) to the address of the newly created DataObject. The result of that expression is immediately discarded, and tempDat remains unchanged. So it still contains random garbage, which happened to be 0 in your debugging session.
|
2,570,959 | 2,570,973 | writing code for nm-alike command [C++] | Out of curiosity about reverse engineering, I am thinking of writing a simple program (in C++) that takes an executable as input and produces the names of all the functions that were a part of source program of that executable.
Any pointers on how should I go about it?
Step-by-step approach would be much appreciated!
EDIT:
Platform linux and i am concerned about a.out format executable files.
| Depends heavily on your platform and the origin of the code you're examining. You need a symbol table for the binary you're reversing if you want to get function names out of it. Sometimes that table is embedded in the binary (such as the export lookup table in a DLL), but many times the information simply doesn't exist.
There's no generalized solution for this. You'll need to narrow your question down to a specific platform at least, and preferably a specific target binary type.
Edit: Okay, with the specifications you've given, I'm guessing that you're probably actually concerned with ELF binaries rather than the older a.out format, which is fairly uncommon. "a.out" is still the default output name for the GCC linker, but the actual a.out binary format hasn't been commonly used in Linux for a long time.
There are a number of good walkthroughs of the ELF structure available online, and some quick searching turned up a ready-made example of reading the ELF .symtab as well.
Hope this helps.
|
2,571,018 | 3,521,428 | Shaped windows in gtkmm | How do I create shaped windows in Gtkmm. The shape must be defined using cairomm.
| Cairo and GTK+ are not directly relevant with shaped windows.
You need to look at GDK which is the windowing system for GTK+
Here is the respective method in vanilla (for C) GDK
http://library.gnome.org/devel/gtk/stable/GtkWidget.html#gtk-widget-shape-combine-mask
|
2,571,136 | 2,571,146 | Is it possible to tie a C++ output stream to another output stream? | Is it possible to tie a C++ output stream to another output stream?
I'm asking because I've written an ISAPI extension in C++ and I've written ostreams around the WriteClient and ServerSupportFunction/HSE_REQ_SEND_RESPONSE_HEADER_EX functions - one ostream for the HTTP headers and one for the body of the HTTP response. I'd like to tie the streams together so that all the HTTP headers are sent before the rest of the response is sent.
| Yes, you can:
out1.tie( & out2 );
where both outs are output streams. out2 will be flushed before output to out1.
|
2,571,157 | 2,571,234 | Debug-only ostreams in C++? | I've implemented an ostream for debug output which sends ends up sending the debug info to OutputDebugString. A typical use of it looks like this (where debug is an ostream object):
debug << "some error\n";
For release builds, what's the least painful and most performant way to not output these debug statements?
| How about this? You'd have to check that it actually optimises to nothing in release:
#ifdef NDEBUG
class DebugStream {};
template <typename T>
DebugStream &operator<<(DebugStream &s, T) { return s; }
#else
typedef ostream DebugStream;
#endif
You will have to pass the debug stream object as a DebugStream&, not as an ostream&, since in release builds it isn't one. This is an advantage, since if your debug stream isn't an ostream, that means you don't incur the usual runtime penalty of a null stream that supports the ostream interface (virtual functions that actually get called but do nothing).
Warning: I just made this up, normally I would do something similar to Neil's answer - have a macro meaning "only do this in debug builds", so that it is explicit in the source what is debugging code, and what isn't. Some things I don't actually want to abstract.
Neil's macro also has the property that it absolutely, definitely, doesn't evaluate its arguments in release. In contrast, even with my template inlined, you will find that sometimes:
debug << someFunction() << "\n";
cannot be optimised to nothing, because the compiler doesn't necessarily know that someFunction() has no side-effects. Of course if someFunction() does have side effects then you might want it to be called in release builds, but that's a peculiar mixing of logging and functional code.
|
2,571,224 | 2,571,246 | Initializing objects on the fly | I have a vector called players and a class called Player. And what I'm trying to do is to write:
players.push_back(Player(name, Weapon(bullets)));
So I want to be able to create players in a loop. But I see an error message says "no matching function for call Player::Player..."
Then I've changed that to:
Weapon w(bullets);
Player p(name, w);
players.push_back(p);
Here is my Player definition:
class Player {
public:
Player(string &name, Weapon &weapon);
private
string name;
Weapon weapon;
}
I'm just trying to learn what is the difference between these definitions. And is this the right way to pass an object to an object constructor.
Note: These are not my actual class definitions. I'm just trying to learn something about object oriented programming in C++ with coding it. I mean I know that Weapon can be initialized in Player :)
| Change constructor to:
Player(const string &name, const Weapon &weapon);
or:
Player(const string &name, Weapon weapon);
It's not valid C++ to initialize a reference with a temporary object, which is what you're doing when you use:
Player(name, Weapon(bullets));
it's legal to use a const reference though.
EDIT: You should also pass name as a const reference or by value.
|
2,571,225 | 2,571,243 | Managing libraries and imports in a programming language | I've created an interpreter for a stupid programming language in C++ and the whole core structure is finished (Tokenizer, Parser, Interpreter including Symbol tables, core functions, etc.).
Now I have a problem with creating and managing the function libraries for this interpreter (I'll explain what I mean with that later)
So currently my core function handler is horrible:
// Simplified version
myLangResult SystemFunction( name, argc, argv )
{
if ( name == "print" )
{
if( argc < 1 )
{
Error('blah');
}
cout << argv[ 0 ];
} else if ( name == "input" ) {
if( argc < 1 )
{
Error('blah');
}
string res;
getline( cin, res );
SetVariable( argv[ 0 ], res );
} else if ( name == "exit ) {
exit( 0 );
}
And now think of each else if being 10 times more complicated and there being 25 more system functions. Unmaintainable, feels horrible, is horrible.
So I thought: How to create some sort of libraries that contain all the functions and if they are imported initialize themselves and add their functions to the symbol table of the running interpreter.
However this is the point where I don't really know how to go on.
What I wanted to achieve is that there is e.g.: an (extern?) string library for my language, e.g.: string, and it is imported from within a program in that language, example:
import string
myString = "abcde"
print string.at( myString, 2 ) # output: c
My problems:
How to separate the function libs from the core interpreter and load them?
How to get all their functions into a list and add it to the symbol table when needed?
What I was thinking to do:
At the start of the interpreter, as all libraries are compiled with it, every single function calls something like RegisterFunction( string namespace, myLangResult (*functionPtr) ); which adds itself to a list. When import X is then called from within the language, the list built with RegisterFunction is then added to the symbol table.
Disadvantages that spring to mind:
All libraries are directly in the interpreter core, size grows and it will definitely slow it down.
| If your interpreter is implemented as a library, it is going to be called from other people's C++ code. It's not unreasonable for them to have to call functions in your library from their own code to add function to the interpreter. That's hat my own expression evaluator does. something like this in user code:
Interpreter in; // an instance of the interpreter
in.AddFunc( lenfun, "length", 1 );
in.AddFunc( catfun, "concat", 2 );
where the caller must supply a pointer to the implementation function, and the name and number of parameters for the function. This works well with an untyped setup - if you do strict typing, there is of course a lot more work to do.
|
2,571,265 | 2,571,284 | Overloading delete and retrieving size? | I am currently writing a small custom memory Allocator in C++, and want to use it together with operator overloading of new/ delete. Anyways, my memory Allocator basically checks if the requested memory is over a certain threshold, and if so uses malloc to allocate the requested memory chunk. Otherwise the memory will be provided by some fixedPool allocators. that generally works, but for my deallocation function looks like this:
void MemoryManager::deallocate(void * _ptr, size_t _size){
if(_size > heapThreshold)
deallocHeap(_ptr);
else
deallocFixedPool(_ptr, _size);
}
So I need to provide the size of the chunk pointed to, to deallocate from the right place.
Now the problem is that the delete keyword does not provide any hint on the size of the deleted chunk, so I would need something like this:
void operator delete(void * _ptr, size_t _size){
MemoryManager::deallocate(_ptr, _size);
}
But as far as I can see, there is no way to determine the size inside the delete operator.- If I want to keep things the way it is right now, would I have to save the size of the memory chunks myself?
| allocate more memory than neccessary and store the size information there. That's what your system allocator probably does already. Something like this (demonstrate with malloc for simplicity):
void *allocate(size_t size) {
size_t *p = malloc(size + sizeof(size_t));
p[0] = size; // store the size in the first few bytes
return (void*)(&p[1]); // return the memory just after the size we stored
}
void deallocate(void *ptr) {
size_t *p = (size_t*)ptr; // make the pointer the right type
size_t size = p[-1]; // get the data we stored at the beginning of this block
// do what you need with size here...
void *p2 = (void*)(&p[-1]); // get a pointer to the memory we originally really allocated
free(p2); // free it
}
|
2,571,317 | 2,571,338 | C++, constructor restrictions | I'm studing C++ and I can't understand the meaning of the boldface sentence below:
From IBM manual:
The following restrictions apply to constructors and destructors:
Constructors and destructors do not have return types nor can they return values.
References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
Constructors cannot be declared with the keyword virtual.
Constructors and destructors cannot be declared static, const, or volatile.
Unions cannot contain class objects that have constructors or destructors.
Could you please provide me an example?
Thank you!
| The sentence means that you can't take pointer to a constructor or a destructor. Here's an example:
class Sample{
private: int x;
public: Sample() { x = 100; };
public: void* member() { x = 200; };
};
template <class X>
void call_me(Sample s, X function){
(s.*function)();
};
call_me(s, &Sample::member); //valid
call_me(s, &Sample::Sample); //invalid
call_me(s, &Sample::~Sample); //invalid
The rationale is like this:
Constructor doesn't return anything (although it may be thought of a function that returns an initialized object). What would be the return type of it as a member function?
Constructor is not really a member function, in the sense that it can't be called on an object (like s.member()).
There may be several actual functions created for each constructor and destructor. One constructor may allocate memory, the other may not (but still initializing class members in the same way). One destructor may destroy base subobjects, the other may not. In each ctor/dtor invocation in source code compiler chooses the actual "low-level" ctor/dtor to call; this choice is made at compilation time. It can't be done if you invoke it through a pointer.
Probably this is what meant by "their addresses cannot be taken".
|
2,571,402 | 2,602,693 | How to use glOrtho() in OpenGL? | I can't understand the usage of glOrtho. Can someone explain what it is used for?
Is it used to set the range of x y and z coordinates limit?
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
It means that the x, y and z range is from -1 to 1?
| Have a look at this picture: Graphical Projections
The glOrtho command produces an "Oblique" projection that you see in the bottom row. No matter how far away vertexes are in the z direction, they will not recede into the distance.
I use glOrtho every time I need to do 2D graphics in OpenGL (such as health bars, menus etc)
using the following code every time the window is resized:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, windowWidth, windowHeight, 0.0f, 0.0f, 1.0f);
This will remap the OpenGL coordinates into the equivalent pixel values (X going from 0 to windowWidth and Y going from 0 to windowHeight). Note that I've flipped the Y values because OpenGL coordinates start from the bottom left corner of the window. So by flipping, I get a more conventional (0,0) starting at the top left corner of the window rather.
Note that the Z values are clipped from 0 to 1. So be careful when you specify a Z value for your vertex's position, it will be clipped if it falls outside that range. Otherwise if it's inside that range, it will appear to have no effect on the position except for Z tests.
|
2,571,436 | 2,574,468 | Emacs: annoying Flymake dialog box | I have the following lines in my ~/.emacs.d/init.el
(custom-set-variables
'(flymake-allowed-file-name-masks
(quote
(
("\\.cc\\'" flymake-simple-make-init)
("\\.cpp\\'" flymake-simple-make-init)))))
(add-hook 'find-file-hook 'flymake-find-file-hook)
When I open a C++ file that has a proper Makefile in the same folder, I get on-the-fly compilation and error reporting (Flymake will check the syntax and report errors and warnings during code editing).
The Makefile has a check-syntax target:
.PHONY: check-syntax
check-syntax:
$(CXX) -Wall -Wextra -pedantic -fsyntax-only $(CHK_SOURCES)
The problem is that when I open a .cc file that has no corresponding Makefile I get an annoying dialog box that warns me about flymake being disabled.
So if I launch emacs *.cc in a folder with 20 C++ files I get 20 modal dialog boxes saying something like No buildfile found for [...]. Flymake will be switched off.
Is there some hook I can use to disable that warning? Can you provide sample elisp code and explanation on how you found the proper hook?
| Easiest way to do this, and still recieve the messages, is to leave the customization variable set to true, and redefine the flymake-display-warning function.
;; Overwrite flymake-display-warning so that no annoying dialog box is
;; used.
;; This version uses lwarn instead of message-box in the original version.
;; lwarn will open another window, and display the warning in there.
(defun flymake-display-warning (warning)
"Display a warning to the user, using lwarn"
(lwarn 'flymake :warning warning))
;; Using lwarn might be kind of annoying on its own, popping up windows and
;; what not. If you prefer to recieve the warnings in the mini-buffer, use:
(defun flymake-display-warning (warning)
"Display a warning to the user, using lwarn"
(message warning))
|
2,571,449 | 2,571,473 | How to fix these compiler errors? | I have this source code from 2001 that I would like to compile.
It gives this:
$ make
g++ -O99 -Wall -DLINUX -pedantic -c -o audio.o audio.cpp
In file included from audio.cpp:7:
audio.h:14: error: use of enum ‘mad_flow’ without previous declaration
audio.h:15: error: use of enum ‘mad_flow’ without previous declaration
audio.h:17: error: use of enum ‘mad_flow’ without previous declaration
audio.cpp: In function ‘mad_flow audio::input(void*, mad_stream*)’:
audio.cpp:19: error: new declaration ‘mad_flow audio::input(void*, mad_stream*)’
audio.h:14: error: ambiguates old declaration ‘int audio::input(void*, mad_stream*)’
audio.h:11: error: ‘size_t audio::stream::BufferPos’ is private
audio.cpp:23: error: within this context
audio.h:11: error: ‘size_t audio::stream::BufferSize’ is private
audio.cpp:23: error: within this context
audio.h:10: error: ‘char* audio::stream::Buffer’ is private
audio.cpp:26: error: within this context
audio.h:11: error: ‘size_t audio::stream::BufferSize’ is private
audio.cpp:26: error: within this context
audio.h:11: error: ‘size_t audio::stream::BufferPos’ is private
audio.cpp:27: error: within this context
audio.h:11: error: ‘size_t audio::stream::BufferSize’ is private
audio.cpp:27: error: within this context
audio.cpp: In function ‘mad_flow audio::output(void*, const mad_header*, mad_pcm*)’:
audio.cpp:49: error: new declaration ‘mad_flow audio::output(void*, const mad_header*, mad_pcm*)’
audio.h:15: error: ambiguates old declaration ‘int audio::output(void*, const mad_header*, mad_pcm*)’
audio.cpp: In function ‘mad_flow audio::error(void*, mad_stream*, mad_frame*)’:
audio.cpp:83: error: new declaration ‘mad_flow audio::error(void*, mad_stream*, mad_frame*)’
audio.h:17: error: ambiguates old declaration ‘int audio::error(void*, mad_stream*, mad_frame*)’
audio.cpp: In constructor ‘audio::stream::stream(const char*)’:
audio.cpp:119: error: ‘input’ was not declared in this scope
audio.cpp:122: error: ‘output’ was not declared in this scope
audio.cpp:123: error: ‘error’ was not declared in this scope
make: *** [audio.o] Error 1
audio.h contains
#ifndef _AUDIO_H_
#define _AUDIO_H_
#include <stdlib.h>
#include "mad.h"
namespace audio {
class stream {
private:
char* Buffer;
size_t BufferSize, BufferPos;
struct mad_decoder Decoder;
friend enum mad_flow input(void* Data, struct mad_stream* MadStream);
friend enum mad_flow output(void* Data, const struct mad_header* Header,
struct mad_pcm* PCM);
friend enum mad_flow error(void* Data, struct mad_stream* MadStream,
struct mad_frame* Frame);
public:
stream(const char* FileName);
~stream();
void play();
};
}
#endif
Update:
The problem seams to be that mad_flow can't been seen. If I look in mad.h, then mad_flow is declared there.
If I just copy/paste
enum mad_flow {
MAD_FLOW_CONTINUE = 0x0000,
MAD_FLOW_STOP = 0x0010,
MAD_FLOW_BREAK = 0x0011,
MAD_FLOW_IGNORE = 0x0020
};
from mad.h the error goes away (and new errors occur).
So how do I make mad_flow available?
| Regarding:
I have tried to just insert
enum mad_flow {};
... a correct forward declaration of the type mad_flow would be:
enum mad_flow ;
But you should really be asking yourself why the declaration or definition is not already visible since the forward declaration is probably a bit of a kludge. Are all the necessary headers included?
[---edit---]
In response to Johannes Schaub's comment, here's a compilable example of a forward declared enum:
enum mad_flow ; // forward declaration
void f( mad_flow& arg ) ; // forward declaration of function
// using incomplete type
int main()
{
mad_flow x ; // Declaration using incomplete type
f( x ) ; // Function call using incomplete enum object
}
enum mad_flow // Completion of the definition
{
VALUE1,
VALUE2
} ;
void f( mad_flow& arg )
{
arg = VALUE1 ; // Use of value from complete definition
}
|
2,571,456 | 2,571,487 | Operators overloading for enums | Is it possible to define operators for enums? For example I have enum Month in my class and I would like to be able to write ++my_month.
Thanks
P.S.
In order to avoid overflowing I did something like this:
void Date::add_month()
{
switch(my_month_)
{
case Dec:
my_month_ = Jan;
add_year();
break;
default:
++my_month_;
break;
}
}
| Yes it is. Operator overloading can be done for all user defined types. That includes enums.
|
2,571,620 | 2,571,654 | Encrypt/Decrypt SQLite-database and use it "on the fly" | Here's the thing:
In my Qt4.6-Project, I use a SQLite-Database. This database shouldn't be unencrypted on my harddrive. So I want, that on every start of my program, the user gets asked to enter a password to decrypt the database. Of course the database never should appear "in clear" (not encrypted) on my harddrive.
So is there any possibility to decrypt a SQLite-database "on the fly" and read and write data? What algorithm is here the best (maybe AES)?
When it's not possible (or very slow), maybe it's better to encrypt every string in the database and decrypt the string when the password was right (so that a user could open the database, but has no clue what all the entrys could mean)?
| There is no built in support, that being said you do have options.
1) You can encrypt/decrypt all of your strings yourselves, but this is a lot of work, is not transparent, and won't allow you to do things like searching in the database.
2) SQLiteCrypt and SQLCipher do what you're looking for.
You can use them almost entirely transparent and typically they are said to have only about 5% overhead compared without encryption.
|
2,571,751 | 2,571,769 | How to provide default argument as this object? | I would like to have declaration like this:
void Date::get_days_name(const Date& = this)
which I would understand that if no argument is provided use this object as an argument. For some reason in VS I'm getting err msg:
'Error 1 error C2355: 'this' : can only be referenced inside non-static member '
Any idea what I'm doing wrong?
| You could make overloaded function:
void get_days_name(const Date&) const;
void get_days_name() const {
get_days_name(*this);
}
(BTW, this is a pointer, not a reference.)
|
2,571,816 | 2,572,087 | Is it possible to define enumalpha? | I would like to be able to write:
cout << enumalpha << Monday;
and get printed on console:
Monday
P.S. Monday is an enum type.
| Okay, let's go all preprocessor then :)
Intended way of use:
DEFINE_ENUM(DayOfWeek, (Monday)(Tuesday)(Wednesday)
(Thursday)(Friday)(Saturday)(Sunday))
int main(int argc, char* argv[])
{
DayOfWeek_t i = DayOfWeek::Monday;
std::cout << i << std::endl; // prints Monday
std::cin >> i >> std::endl; // reads the content of a string and
// deduce the corresponding enum value
}
Dark magic, involving the helpful Boost.Preprocessor library.
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#define DEFINE_ENUM_VAL_TO_STR(r, data, elem) \
case BOOST_PP_CAT(data, BOOST_PP_CAT(::, elem)): \
return out << BOOST_PP_STRINGIZE(elem);
#define DEFINE_ENUM_STR_TO_VAL(r, data, elem) \
if (s == BOOST_PP_STRINGIZE(elem)) \
{ i = BOOST_PP_CAT(data, BOOST_PP_CAT(::, elem)) ; } else
#define DEFINE_ENUM(Name, Values) \
struct Name { \
enum type { \
Invalid = 0, \
BOOST_PP_SEQ_ENUM(Values) \
}; \
}; \
typedef Name::type Name##_t; \
std::ostream& operator<<(std::ostream& out, Name##_t i) { \
switch(i) { \
BOOST_PP_SEQ_FOR_EACH(DEFINE_ENUM_VAL_TO_STR, Name, Values) \
default: return out << "~"; } } \
std::istream& operator>>(std::istream& in, Name##_t& i) { \
std::string s; in >> s; \
BOOST_PP_SEQ_FOR_EACH(DEFINE_ENUM_STR_TO_VAL, Name, Values) \
{ i = Name##::Invalid; } }
There are better ways, personally I use this little macro to store that all in a nicely sorted vector of pairs, static for the type, it also allows me to iterate through the values of the enum if the mood (or need) strikes :)
It's quite unfortunate though there is no support in the language for that. I would prefer if there was, enum are quite handy for codesets...
|
2,571,831 | 2,571,839 | Can a function return more than one value? | Can a function return more than one value directly (i.e., without returning in parameters taken by-reference)?
| No, but you can return a pair or boost::tuple which can contain multiple values.
In addition, you can use references to return multiple values like this:
void MyFunction(int a, int b, int& sum, int& difference);
You would call this function like this:
int result_sum;
int result_difference;
MyFunction(1, 2, result_sum, result_difference);
As Hogan points out, technically this isn't returning multiple variables, however it is a good substitute.
|
2,571,850 | 2,571,871 | Why does enable_shared_from_this have a non-virtual destructor? | I have a pet project with which I experiment with new features of C++11. While I have experience with C, I'm fairly new to C++. To train myself into best practices, (besides reading a lot), I have enabled some strict compiler parameters (using GCC 4.4.1):
-std=c++0x -Werror -Wall -Winline -Weffc++ -pedantic-errors
This has worked fine for me. Until now, I have been able to resolve all obstacles. However, I have a need for enable_shared_from_this, and this is causing me problems. I get the following warning (error, in my case) when compiling my code (probably triggered by -Weffc++):
base class ‘class std::enable_shared_from_this<Package>’ has a non-virtual destructor
So basically, I'm a bit bugged by this implementation of enable_shared_from_this, because:
A destructor of a class that is intended for subclassing should always be virtual, IMHO.
The destructor is empty, why have it at all?
I can't imagine anyone would want to delete their instance by reference to enable_shared_from_this.
But I'm looking for ways to deal with this, so my question is really, is there a proper way to deal with this? And: am I correct in thinking that this destructor is bogus, or is there a real purpose to it?
|
A destructor of a class that is intended for subclassing should always be virtual, IMHO.
A virtual destructor in a base class is only needed if an instance of the derived class is going to be deleted via a pointer to the base class.
Having any virtual function in a class, including a destructor, requires overhead. Boost (and the TR1 and C++11 Standard Library) doesn't want to force you to have that overhead just because you need to be able to obtain a shared_ptr from the this pointer.
The destructor is empty, why have it at all?
If you don't have a user-defined constructor, the compiler provides one for you, so it doesn't really matter.
I can't imagine anyone would want to delete their instance by reference to enable_shared_from_this.
Exactly.
As for the compiler warning, I would ignore the warning or suppress it (with a comment in the code explaining why you are doing so). Occasionally, especially at "pedantic" warning levels, compiler warnings are unhelpful, and I'd say this is one of those cases.
|
2,572,409 | 2,572,425 | Does it take time to deallocate memory? | I have a C++ program which, during execution, will allocate about 3-8Gb of memory to store a hash table (I use tr1/unordered_map) and various other data structures.
However, at the end of execution, there will be a long pause before returning to shell.
For example, at the very end of my main function I have
std::cout << "End of execution" << endl;
But the execution of my program will go something like
$ ./program
do stuff...
End of execution
[long pause of maybe 2 min]
$ -- returns to shell
Is this expected behavior or am I doing something wrong?
I'm guessing that the program is deallocating the memory at the end. But, commercial applications which use large amounts of memory (such as photoshop) do not exhibit this pause when you close the application.
Please advise :)
Edit: The biggest data structure is an unordered_map keyed with a string and stores a list of integers.
I am using g++ -O2 on linux, the computer I am using has 128GB of memory (with most of that free). There are a few giant objects
Solution: I ended up getting rid of the hashtable since it was almost full anyways. This solved my problem.
| If the data structures are sufficiently complicated when your program finishes, freeing them might actually take a long time.
If your program actually must create such complicated structures (do some memory profiling to make sure), there probably is no clean way around this.
You can short cut that freeing of memory by a dirty hack - at least on those operating systems where all memory allocated by a process is automatically freed when the process terminates.
You would do that by directly calling the libc's exit(3) function or the operating system's _exit(2). However, I would be very careful about verifying this does not short-circuit any other (important) cleanups some C++ destructor code might be doing. And what this does or does not do is highly system dependent (operating system, compiler, libc, the APIs you were using, ...).
|
2,572,533 | 2,572,658 | C++ STL-conforming Allocators | What allocators are available out there for use with STL when dealing with small objects. I have already tried playing with pool allocators from Boost, but got no performance improvement (actually, in some cases there was considerable degradation).
| You didn't say what compiler you use, but it probably comes with a bunch of pre-built allocators. This is on a Mac with gcc 4.2.1:
~$ find /usr/include/c++/4.2.1/ -name "*allocator*"
/usr/include/c++/4.2.1/bits/allocator.h
/usr/include/c++/4.2.1/ext/array_allocator.h
/usr/include/c++/4.2.1/ext/bitmap_allocator.h
/usr/include/c++/4.2.1/ext/debug_allocator.h
/usr/include/c++/4.2.1/ext/malloc_allocator.h
/usr/include/c++/4.2.1/ext/mt_allocator.h
/usr/include/c++/4.2.1/ext/new_allocator.h
/usr/include/c++/4.2.1/ext/pool_allocator.h
/usr/include/c++/4.2.1/ext/throw_allocator.h
Here's also a link to BitMagic project page that talks about how to build your own. Also check out small object allocator in the Loki library (and the book too).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.