question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,949,434 | 3,949,481 | size_t and unsigned int does not match in a template function's parameter list | I want to use a stack to store indices of an array,so I use the following typedef,where istack is a template class for stack:
typedef istack<size_t> IndexStack;
and I declare a stack by
IndexStack stack;
But when I call the following function (where A.size() returns a size_t);
stack.push_back(A.size());
GCC gi... | #include <cstddef>
template <class T>
struct istack
{
void push_back(T& value);
std::size_t size() const;
};
int main()
{
typedef istack<size_t> IndexStack;
IndexStack a, stack;
stack.push_back(a.size());
}
This code produces an error
In function 'int main()':
13 no matching function for call t... |
3,949,457 | 3,949,459 | Can an integer be NaN in C++? | Can I set an int to NaN? If yes, then how can I check if an int is NaN or not?
| No, NaN is a floating point value.
Every possible value of an int is a number.
Edit
The standard says:
6.2.6.2 40) Some combinations of padding bits might generate trap
representations, for example, if one
padding bit is a parity bit.
Regardless, no arithmetic operation on
valid values can generate a trap
re... |
3,949,471 | 3,972,350 | int a; ...; (a == a) fails? | if we set float and double type to NaN then they are not equal to anything including themselves.
can such a thing happens for int?
| Although it's certainly unusual, C++ does allow int to be NaN.
First, it's possible for int to store information besides its numeric value. §3.9.1/1:
For character types, all bits of the object representation participate in the value representation. For unsigned character types, all possible bit patterns of the value ... |
3,949,497 | 3,949,524 | What's the cleanest way to fail gracefully when a file can't be opened in C++? | The program requires the file to run, but if for any myriad number of reasons it can't be found or isn't readable, etc - what's the cleanest way to fail out of the program?
| Fail as you would fail in other cases:
A command line program would output the unreadable file (full path) and the exact reason for not being able to read it on Stderr and exit with an error code. The functions strerror() and perror() help you in verbalizing the failure reason.
A Gui would post an error message like t... |
3,949,621 | 3,949,686 | How do I specialize a static member of a template class on a templated type? | Say I have the following class:
template<class T>
struct A
{
static int value;
};
template<class T>
int A<T>::value = 0;
I can specialize A::value on a concrete type without problems:
struct B
{
};
template<>
int A<B>::value = 1;
I'd like to specialize A::value on a template type, I tried the following:
templat... | Instead of introducing a whole explicit specialization, you could just specialize the initialization
template<class T>
struct Value {
static int const value = 0;
};
template<class T>
struct Value< C<T> > {
static int const value = 2;
};
template<class T>
int A<T>::value = Value<T>::value;
|
3,949,715 | 3,949,732 | c++ references array | I wounder how i can make this code work?
#include <iostream>
using namespace std;
void writeTable(int (&tab)[],int x){
for(int i=0;i<x;i++){
cout << "Enter value " << i+1 <<endl;
cin >> tab[i] ;
}
}
int main(void){
int howMany;
cout << "How many elemets" << endl;
cin >> howMany;
... | If you are intending to pass the size of the array, then remove the reference
void f(int a[])
is equivalent to
void f(int* a)
so no copying will be done, if that is the concern.
If you want to take an array by reference, then you MUST specify the dimension. e.g.
void f(int (&a)[10])
Naturally, the best of the two is... |
3,949,818 | 3,949,843 | Are >? or <? legitimate operators in any C++ dialect? | I ran across the following lines of C++ code in a file (non-contiguous lines) that gcc 4.2.1 won't accept:
int frame = blk <? mBlkCnt-1;
mInsCnt = blk <? mBlkCnt;
mInsCnt = mInsCnt+1 <? mBlkCnt;
const int to_read = (mFileSz-byte_off) <? mBlkSz;
Both <? and >? are used in various places in the code. They appear to be a... | They're called the min and max operators and were language extensions in earlier versions of gcc.
They are no longer supported.
|
3,949,974 | 3,950,016 | Is volatile required here? | EDITED and refined my question after Johannes's valuable answer
bool b = true;
volatile bool vb = true;
void f1() { }
void f2() { b = false; }
void(* volatile pf)() = &f1; //a volatile pointer to function
int main()
{
//different threads start here, some of which may change pf
while(b && vb)
{
... |
The question is, in this case pf is itself volatile, so is the compiler allowed to assume that b won't change in the loop even if b is not volatile?
It can't, because you say that pf might be changed by the other threads, and this indirectly changes b if pf is called then by the while loop. So while it is theoretical... |
3,950,235 | 3,950,673 | Which one of these two ways of writing this code would be more suited? | I've got a code that as you can see I can write in either of two following ways, the matter is the only difference is since in second function the parameter is declared as non-constant I can use that instead of declaring a new variable(num1 in first function) but I' curious which one would be more suited if there would... | Like this:
void Test(long double input)
{
long double const factor = 6.0 * input;
long double result = 9.0 * pow(factor, 5);
cout << result << '\n';
}
If you must use the loop then I would follow GMan's example.
One variable for one use. Trying to re-use variables has no meaning. The compiler does... |
3,950,360 | 3,950,411 | Calculating the spread of the hash function for a hashmap which uses chaining | I am writing a generic hash map in C++ which uses chaining to deal with collisions.
Say if I have a hash map with 11 buckets, and I insert 8 items. The hash function will distribute it as follows:
bucket[0] = empty
bucket[1] = 2 elements
bucket[2] = empty
bucket[3] = 1 element
bucket[4] = 1 element
bucket[5] = 3 eleme... | If you're only using this to tune the hash functions themselves, you could compute a genuine measure of statistical dispersion, such as the Gini coefficient. On the other hand, if you're trying to make this a feature of the hash-map itself, I would recommend against it - computing a complicated benchmark as part of the... |
3,950,588 | 3,952,765 | Strings and character encoding in C++ | I read a few posts about best practices for strings and character encoding in C++, but I am struggling a bit with finding a general purpose approach that seems to me reasonably simple and correct. Could I ask for comments on the following? I'm inclined to use UTF-8 and UTF-32, and to define something like:
typedef st... | If you plan on just passing strings around and never inspect them, you can use plain std::string though it's a poor man job.
The issue is that most frameworks, even the standard, have stupidly (I think) enforced encoding in memory. I say stupid because encoding should only matter on the interface, and those encoding ar... |
3,950,635 | 3,987,567 | How to compile dynamic library for a JNI application on linux? | I'm using Ubuntu 10.10
So that's what I did.
Hello.java:
class Hello {
public native void sayHello();
static { System.loadLibrary("hellolib"); }
public static void main(String[] args){
Hello h = new Hello();
h.sayHello();
}
}
Then I ran the follwing com... | Native library can be loaded by loadLibrary with a valid name. By example, libXXXX.so for linux family, your hellolib.so should rename to libhello.so.
By the way, I develop java with jni, I will separate the implementation and native interface (.c or .cpp).
static {
System.loadLibrary("hello"); // will load libhel... |
3,950,705 | 3,950,932 | cast Derived*const to Base*const | Edit - Put the question into context a bit more.
Given:
struct Base
{
...
};
struct Derived : public Base
{
...
};
class Alice
{
Alice(Base *const _a);
...
};
class Bob : public Alice
{
Bob(Derived *const _a);
...
};
When I try to implement
Bob::Bob(Derived *const _d) : Alice(static_cast<Base*c... | The problem was that Derived was an incomplete type, i.e. forward declared. I'm afraid I've been giving everyone a hard time :(
The answer popped up when Kiril Kirow proposed using a dynamic-cast, upon which g++ spat out this slightly more helpful error:
error: cannot dynamic_cast ‘_d’ (of type ‘struct Derived* const’)... |
3,950,718 | 3,950,795 | Wrote to a file using std::wofstream. The file remained empty | I wrote the following program using VS2008:
#include <fstream>
int main()
{
std::wofstream fout("myfile");
fout << L"Հայաստան Россия Österreich Ελλάδα भारत" << std::endl;
}
When I tried to compile it the IDE asked me whether I wanted to save my source file in unicode, I said "yes, please".
Then I run the progr... | In Visual studio the output stream is always written in ANSI encoding, and it does not support UTF-8 output.
What is basically need to do is to create a locale class, install into it UTF-8 facet and then imbue it to the fstream.
What happens that code points are not being converted to UTF encoding. So basically this wo... |
3,950,781 | 3,950,793 | C++ Inheritance Question | In the file test.cpp, I have this:
template <typename T>
class A
{
public:
A(int a){};
virtual ~A();
private:
};
class B : public A<int>
{
public:
B(int a):A(a){};
virtual ~B();
private:
};
int main()
{
return 0;
}
When I compile it, I get this:
jason@jason-linux:~/Documents/ECLibrary$ g++ -g -Wall -Wext... | You can add the template argument list to A:
B(int a) : A<int>(a) { }
Note that the code that you have--using A without the template argument list--is valid C++. Comeau and Visual C++ 2010 both accept the code as-is.
g++ 4.3 does not accept the code without the template argument list. Perhaps someone can test a l... |
3,950,841 | 3,950,864 | How to get the exact position of an element in a set? | I have a std::set<std::string> and I want to know the exact position of the element in the set after the insertion.
I tried with std::distance but without any luck:
#include <iostream>
#include <string>
#include <set>
#include <iterator>
using namespace std;
int main (int argc, char const *argv[])
{
string array... | They're being sorted lexicographically (basically alphabetically). The default comparison for std::set<T> is std::less<T>, which in turn calls operator<.
|
3,950,893 | 3,950,953 | How can I make sure all of my c++ boost threads finish before the program exits? | I know I can call thread.join() to force a thread to complete before the current thread can proceed. However, my program has a bunch of files that are read into memory, modified, and then flushed to disk. Each flush is being done in a separate thread so that the current thread can continue while the contents are flushe... | If the threads have completes execution they aren't actually threads any more. I don't see your concern. I for one would consider using a thread pool. If you want to keep a list of all spawned threads use boost::thread_group. And joining all threads is essentially and effectively the same as joining all active threads ... |
3,951,043 | 3,951,298 | C++ iptables redirection forming separate packets | I have all traffic from port 50 redirected to 5050 using
iptables -t nat -A POSTROUTING -p udp --dport 50 -j REDIRECT --to-port 5050
I listen using a RAW Socket on 5050, and I see IP packets from 0.0.0.0:50 to 0.0.0.0:5050.
The original destination address is obviously not present, since this seems to be a separate r... | Linux netfilter defines a socket option called SO_ORIGINAL_DST in <linux/netfilter_ipv4.h>.
First you need to enable port forwarding in your system, using one of these commands:
sysctl net.ipv4.ip_forward=1
echo 1 > /proc/sys/net/ipv4/ip_forward
Then you can use this:
struct sockaddr_in addr;
socklen_t addr_sz = sizeo... |
3,951,307 | 3,951,685 | How to implement a generic DOM data structure in C++? | I'm trying to write a very simple implementation of Document Object Model library in order to provide a generic data structure to use in my further projects.
Just to keep things simple I defined only three main classes: node, element and attribute. A node is defined by it's name (e.g. all html tags) and basically is a ... | Instead of trying to strongly type each node based on how many parents it has, organize your code as a tree structure:
class Element
{
public:
std::string Name;
std::map<std::string, std::string, std::less<std::string> > Attributes;
std::list<Element> Children;
};
Your public interface will probably look much di... |
3,951,326 | 3,951,331 | Performance vs Correctness/Preference? | typedef unsigned char uChar;
typedef signed char sChar;
typedef unsigned short uShort;
typedef signed short sShort;
typedef unsigned int uInt;
typedef signed int sInt;
typedef unsigned long uLong;
typedef signed long sLong;
I have a list of typedefs so when I define variables, I can be exact. For instance, if I onl... | This is the kind of premature optimization that rarely matters much. I'd choose a data structure and get on with it. Once you have a complete system that has a problem, profile it to find out where the issue is. Your chances of guessing and hitting the poor performance nail on the head are small indeed.
|
3,951,400 | 3,951,415 | Declaring a struct method in C++ | I'm trying to create a recurring struct method in my code to walk through a binary search tree. But I'm getting errors on compile and unsure what is the cause.
I've got Node* findNode(const Node *, const Object &); in the private section of the .h file
and
Node* BSTree::findNode(const Node* current, const Object &targ... | Judging from the error it looks like you have declared Node within the BSTree struct. I think your issue lies in your return type. Try declaring the return type to be BSTree::Node*.
|
3,951,540 | 3,951,577 | How can I create a new thread from a c++ boost thread_group that begins execution in a member function of an object? | There are some member variables and mutexes associated with the object, so it would be easier to use a member function rather than a standalone function.
| Provide an operator() member func.
EDIT: like ...
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <iostream>
struct MyThread
{
int x;
MyThread(): x( -1 ) {}
void run() // Name doesn't matter.
{
x = 42;
}
};
int main()
{
namespace b = boost;
using namespace std;... |
3,951,686 | 3,951,697 | static mutable member variables in C++? | why or for what reason is it not possible to declare a class member variable in C++ as static mutable? Something like
static mutable int t; //This won't compile
For me, there is no reason to ban such declarations. E.g. for reasons like maintaining a global class-wide statistics, it may be convenient to have static var... | Non-const static members of the class can already be modified by any (const and non-const) methods of the class. There's no need and no point in declaring it with mutable. That would achieve absolutely nothing.
|
3,951,706 | 3,951,723 | Overloading operator < with const, but don't insert into map as const | I'm having an issue. I have a class with an overloaded operator like this..
class Foo
{
friend bool operator<(const Foo &a, const Foo &b);
...
};
bool operator<(const Foo &a, const Foo &b)
{
return a.member < b.member;
}
Then in a function in a class that holds some Foos in a map as keys...
vo... | Keys in a map are always const, even if you don't say so. It's like that to prevent programming errors.
Consider what would happen if Update changed member - the map data structure would be based on the original ordering, but now that member has changed, that ordering could be wrong! The map would be completely broken ... |
3,951,732 | 3,951,744 | Is the typical C++ implementation of Factory class flawed? | I have the need to implement factory class in C++, but when I was thinking about that, I found one big problem that I couldn't solve, and I found out, that all factory implementation examples around are flawed in the same way. I'm probably the one who is wrong, but please tell me why.
So here is simple "typical" factor... | All global POD data is guaranteed to be initialized to a constant value before any initializers run.
So at the start of your program, before any of the register calls are made and before main is run, the pointer is NULL and all of the bools are false, automatically. Then the initializers run, including your register ... |
3,951,874 | 3,951,895 | Is there a compiler flag for Visual C++ to check for type safety for calls to printf()? | I have read there are a few flags in gcc to do catch some of the type violations for calls to printf, I haven't been able to find if there are similar ways to achieve this in Visual C++'s compiler (any version of VC++, from 2005 onward).
| As far as I know, VC++ doesn't have it. MS appears to have done almost no new development specifically for the C compiler for years now -- almost the only updates have been mostly accidental side-effects of updates to the C++ compiler. Since this would see little use in C++ it hasn't happened, and I wouldn't expect it ... |
3,951,931 | 3,951,935 | C++ design pattern to get rid of if-then-else | I have the following piece of code:
if (book.type == A) do_something();
else if (book.type == B) do_something_else();
....
else do so_some_default_thing.
This code will need to be modified whenever there is a new book type
or when a book type is removed. I know that I can use enums and use a switch
statement. Is the... | You could make a different class for each type of book. Each class could implement the same interface, and overload a method to perform the necessary class-specific logic.
I'm not saying that's necessarily better, but it is an option.
|
3,951,939 | 3,951,952 | c++ STL map copy setting boolean value to true | I'm having a problem with stl map. Initially I fill the map with data like so.
//loop
pair< int, int > xy (x,y);
currentMap.insert( make_pair(xy), value); //map< pair<int, int>, bool>
prevMap.insert( make_pair(xy), value);
// End Loop
Then I delete an element according to some rules like so.
currentMap.erase( make_pai... | You can't initialize the map's values to anything. You can only insert values along with the key. Your last code snippet should look like this if you want to return false when the key is missing:
i = currentMap.find( make_pair(xy) );
if (i != currentMap.end())
return i->second;
return false;
|
3,952,020 | 3,952,053 | Plain Old Data types with private members? | Is Demo a POD type in C++03?
struct Demo
{
private:
int x;
int y;
};
C++03, §9p4:
A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined ... | In C++03, it's definitely not a POD. According to §9/4, "A POD-struct is an aggregate class ...", and according to §8.5.1/1:
An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual... |
3,952,222 | 3,952,410 | Xcode PCH issue - Items in PCH Not Included in Source Files | I just created a "C++ Standard Dynamic" library project using Xcode and compiled using LLVM 2.0. I notice that the PCH file contains the line #include <iostream> but the file Test.cp also includes that #include <iostream> statement.
The strange thing is that by removing the statement in Test.cp, the build fails with t... | Precompiled headers are used for speeding up compilation. They don't have any other effect, in particular you still have to include the headers where you need them.
Edit - In Xcode the pch file is really a prefix header that happens to be precompiled (with the default project configuration). Check the GCC_PRECOMPILE_PR... |
3,952,304 | 3,952,313 | LLVM Compiler 2.0: Warning with "using namespace std;" | In Xcode using LLVM 2.0, when I put the line using namespace std; in my C++ code, I get this warning:
Semantic Issue
Using directive refers to implicitly-defined namespace 'std'
Is there a way to fix this? Why is it giving that warning?
| Have you included any standard header files? Otherwise the compiler doesn't know about namespace std.
Please post more code to clarify.
|
3,952,316 | 3,954,774 | opengl recompile display list | If an existing compiled display list is to be recompiled, is it necessary to call glDeleteLists() and glGenLists() first? Or can the display list be recompiled by just calling glNewList() on the existing compiled display list ID?
| Just calling glNewList/glEndList should be enough.
Note that the deletion only becomes effective on the glEndList call:
If a display list with name `list` already exists,
it is replaced only when glEndList is called.
If you'd rather have the previous list freed earlier, then by all means, do call glDeleteLists. Bei... |
3,952,322 | 3,952,330 | C++ - function overriding or overloading | class A
{
public:
int func1()
{
cout<<"A's func1";
}
}
class B:public A
{
public:
int func1()
{
cout<<"B's func1";
}
}
in the above code snippet , is the function ' func1()' getting overloaded in class B ?
or getti... | Overriding can only happen when the base class member function is declared virtual. Overloading can only happen when the two functions have different signatures.
Neither of these conditions applies here. In this case, B::func1 is simply hiding A::func1.
Side note: the condition I indicated for overloading is necessary ... |
3,952,342 | 3,952,847 | Convert errno.h error values to Win32 GetLastError() equivalents | I'm writing a layer between a POSIX filesystem, and Windows using Dokan, and need to convert error values of the errno kind (EINVAL, ENOENT, etc.), to the Win32 equivalents you'd receive when calling GetLastError() (such as ERROR_INVALID_PARAMETER).
Is there an existing function, library, or reference I can use to perf... | I had done an experiment about this subject in the past, mostly based on Microsoft DOSMAP.CPP unit. However, I cancelled the project at that time because the error mapping was not always right for particular error codes. For Example, not every POSIX version return EINVAL for ERROR_INVALID_ACCESS, some of them return EA... |
3,952,419 | 3,952,443 | Error trying to make a wrapper of the STL map container | I'm trying to make a wrapper to the STL map container, in order to add a const method to return the value given the key. In map, operator[] isn't const, and find() requires dereferencing to get the value (map.find()->second). I'm basing some of my "research" off of Idiomatic C++ for reading from a const map by the way.... | You are missing the template parameters for map, you have to specify typename when declaring the iterator (see here), and for some reason unknown to me (probably a namespace conflict) you have to use this when calling end():
template <typename K, typename V>
class easymap : public std::map<K,V>
{
//Constructor
... |
3,952,464 | 3,952,611 | Downcasting a pointer using a function instead of giant if statement | I have a vector with pointers of type Vehicle. Vehicle is the base class and there are many derived types like MotorCycle, Car, Plane, etc. Now, in my program there comes a point where I need the derived type while traversing the vector. Each Vehicle class has a GetType() function which returns an int which tells me wh... | I second the idea that you need some virtual function and a common base type. Imagine that there is some way to get the pointer which has the correct type. What will you do with it then? You'll have to make a giant switch anyway, because you call specific functions for each of your specific types.
One solution would be... |
3,952,476 | 3,952,480 | How to remove a specific pair from a C++ multimap? | #include <map>
...
multimap<char,int> mymap;
mymap.insert(pair<char,int>('a',10));
mymap.insert(pair<char,int>('b',15));
mymap.insert(pair<char,int>('b',20));
mymap.insert(pair<char,int>('c',25));
Say I now want to remove one of the pairs I have just added to the map.
I have examples to remove an entire key entry, ... | You can use std::multimap<char, int>::equal_range, which will give you an iterator range containing all pairs which have a certain key. So if you look for 'b', you will get an iterator range containing all pairs which have 'b' as the key.
You can then simply iterate over the range, and erase any pair you see fit, by ... |
3,952,508 | 3,953,316 | Any tool to determine most efficient way of passing data, by reference or by value? | For objects or primitive data with a size equal to or less than size of a pointer the most efficient passing method to a function would definitely be by value but the thing is I want to know would be there any tool capable of determining best method of passing objects of classes or primitive data with a sizes bigger th... | Yes, that tool is the compiler. Pass by reference and if the optimizer notices it can get away with storing a copy of the object instead of the address for objects whose size is less or equal to that of an address, then it may do so. This is probably the best approach for templated code, where you can't be sure if yo... |
3,952,670 | 3,953,235 | Do global variables mean faster code? | I read recently, in an article on game programming written in 1996, that using global variables is faster than passing parameters.
Was this ever true, and if so, is this still true today?
| Short answer - No, good programmers make code go faster by knowing and using the appropriate tools for the job, and then optimizing in a methodical way where their code does not meet their requirements.
Longer answer - This article, which in my opinion is not especially well-written, is not in any case general advice o... |
3,952,699 | 4,074,982 | can i use CLucene and the Cue Sheet Parser together? | i'm trying to use clucene-0.9.21b and libcue-1.3.0 in Qt Creator on Kubuntu Lucid. this code is compilable:
project.pro
SOURCES += main.cpp
LIBS += -lcue
INCLUDEPATH += /usr/include/libcue-1.3/libcue
main.cpp
extern "C" {
#include <libcue.h>
}
int main(int argc, char *argv[]) {
return 0;
}
so is this:
project.pro
S... | Ok, this time I got a chance to actually try it. Problem seems to be that libcue has a file called time.h in its include folder. So if you compile with -I/usr/include/libcue-1.4/libcue then you end up with libcue's time.h instead of libc's.
This works for me:
extern "C" {
#include <libcue/libcue.h>
}
#include <CLucene... |
3,953,154 | 3,953,230 | lvalue-to-rvalue conversion of an array in ISO C | C++ ANSI ISO IEC 14882 2003 Annex C.1 (page 668):
Change: The result of a conditional expression, an assignment expression, or a comma expression may bean lvalue
Rationale: C + + is an object-oriented language, placing relatively more emphasis on lvalues. For example, functions may return lvalues.
Effect on original fe... |
Or just microsoft's C is not ISO C but some other standard C (if there exists any).
Microsoft Visual C still supports C89 [only] whereas other compilers like gcc/clang etc support C99 too which is the current Standard.
C99 [Section 6.5.17/2] says
The left operand of a comma operator is evaluated as a voi... |
3,953,201 | 3,953,251 | Why is there a segmentation fault error if I include an array of widgets in Qt? | I'm a little new to object oriented programming, and very new to Qt and GUIs in general.
I am now playing with this example in Nokia's Qt tutorial:
http://doc.qt.nokia.com/4.1/tutorial-t5.html
I tried to extend the code; this is what I have now:
#include <QApplication>
#include <QFont>
#include <QLCDNumber>
#include <Q... | A better way is to use a array of pointers, you should try it:
QPushButton *buttons[4];
buttons[0] = new QPushButton(this);
buttons[1] = new QPushButton(this);
buttons[2] = new QPushButton(this);
buttons[3] = new QPushButton(this);
buttons[0]->setText("foo")
connect(buttons[0], SIGNAL(clicked()), this, SLOT(bar()));... |
3,953,553 | 3,953,595 | stringstream and french locale (French_France.1252) | std::stringstream stream_french;
stream_french.imbue(std::locale("")); // French_France.1252
stream_french << 1000;
std::string value_french = stream_french.str();
This code will convert 1000 to string "1 000" but the value of value_french[1] is -96 and not 32, why is that ?
value_french[0] = 49
value_french[1] = -96 ... | That -96 is the signed equivalent of 160, i.e. 0xA0; if you go and check the Windows 1252 codepage table, you'll see that such character is
A0 = U+00A0 : NO-BREAK SPACE
which is a space that don't allow an automatic line break:
Text-processing software typically assumes that an automatic line break may be inserted a... |
3,953,637 | 3,953,652 | What is the proper way to return an object from a C++ function? | I am confused between :
returning an object (but then the object is copied from the local variable in the function, which consumes memory)
returning a pointer (but then you have to remember to delete it, in the calling code, which is weird)
returning a reference (but this is not possible because this would be a refere... | Modern compilers typically implement the (Named) Return Value Optimization, by which the copy you reference (and would logically expect) is not done.
Ever since Visual Studio 2005 (VC++ 8.0) I don't think twice about returning objects.
|
3,953,644 | 3,953,767 | Silly C++ reference question | I do not know how to call a function with a reference in it :( It is a silly noob question I know.
The header is let's call it ref.h has a function in it that is:
virtual int funcName (Bike &biker, BikeArray &bikearray, int x, int y .... )
Within ref.h there is another header that is called Bike.h.
How do I call fun... | You pass objects per reference as you would pass them per copy:
someObj.funcName(myBiker, myBikeArray, 42, ...);
Note that, if a function takes arguments per non-const reference, this indicates that the function might change them. (See here for more on that.)
Also, you cannot pass rvalues (temporary objects) as non... |
3,953,734 | 3,954,043 | What makes this bucket sort function slow? | The function is defined as
void bucketsort(Array& A){
size_t numBuckets=A.size();
iarray<List> buckets(numBuckets);
//put in buckets
for(size_t i=0;i!=A.size();i++){
buckets[int(numBuckets*A[i])].push_back(A[i]);
}
////get back from buckets
//for(size_t i=0,head=0;i!=numBuckets;i++){
//size_t bu... | With
iarray<List> buckets(numBuckets);
you are basically creating a LOT of lists and that can cost you a lot especially in memory access which it theoretically linear but that's not the case in practice.
Try to reduce the number of buckets.
To verify my assertion analyse your code speed with only the creation of the ... |
3,953,818 | 11,460,827 | Creating native C++ OpenGL 3D editor and using it as a WinForms or WPF control in C# | I want to create a simple 3D editor program, and I don't like C++ windows programming. But I don't want to mess with managed code when using OpenGL, either. So, it is possible to create in native C++ a control which will host the OpenGL 3D drawing surface, with no other controls, and also with an interface (methods and... | It is also possible to use managed C++. I created a simple OpenGL control for WinForms which suits your requirements. You can find more info about it here.
|
3,954,029 | 3,954,073 | How to use SQLConnect or SQLDriverConnect | I am trying to connect to a MS-SQL server on the internet. What should I put on the ServerName parameter of SQLConnect?
I've tried this, but it fails:
"DRIVER=SQL Server;SERVER=SERVER_IP;DATABASE=sales"
SERVER_IP is something like 111.111.111.111,9999
EDIT:
I followed Johns advice and here is my current code:
SQLCHAR ... | Here is a trick with SQL Server Connection Strings. Create a file on you desktop called test.udl. Once created, double click and open the file. You will be prompted to set up the Database Connection. Configure the connection as needed. When Finished, test the connection. Finally close the wizard. Then right cli... |
3,954,092 | 3,954,124 | Copying value from char pointer to a char array | I am having a pointer *ip_address_server which holds the ip address of the server :
in_addr * address = (in_addr * )record->h_addr;
char *ip_address_server = inet_ntoa(* address);
Clearly, when I use printf to print the value of it, it gets nicely printed.
printf("p address %s" , ip_address_server);
But n... | Safe & better way to do it:
snprintf(host_name, sizeof(host_name), "%s", ip_address_server);
|
3,954,176 | 3,954,338 | Avoiding Memory Leaks w/ Exceptions in C++ | I allocate objects on the heap and under some circumstances I combine them into a new object (my Foo class mainly contains 2-3 STL containers).
(An alternative would be to use copies, but I guess that would be less efficient.)
These operations may fail, thus exceptions may be thrown.
Unless I release the dynamic memory... | This answer is going to assume that you meant return foo at the end of MakeFoo(). My first choice would be to refactor so as to not use so much dynamic allocation, along the lines of this:
Foo *MakeFoo(){
if(!something)
return 0;
return Combine(SimpleFoo(), SimpleFoo());
}
Foo SimpleFoo(){
Foo foo;
if (so... |
3,954,223 | 3,955,069 | Platform independent way to get font directory? | Is there a way I could find where fonts are stored on either Windows, OSX, or Linux? If not, is there a way I can guarantee certain paths (such as X:/Windows/Fonts/) for all 3 platforms? What ifdefs would I use for these?
| This is going to be one of those 'simple' problems could have an over-the-top solution depending on what you need this information for.
I will have to apologize for the vaguer Linux answers, as font management across Linux distributions are not consistent and can be very configurable, can be influenced by desktop envir... |
3,954,764 | 3,954,779 | How are references implemented internally? | I'm just wondering how references are actually implemented across different compilers and debug/release configurations. Does the standard provide recommendations on their implementation? Do implementations differ?
I tried to run a simple program where I return non-const references and pointers to local variables from f... | The natural implementation of a reference is indeed a pointer. However, do not depend on this in your code.
|
3,954,809 | 3,954,836 | domain in programming | in the book of Meyers about effective programming(item 38) I found some absract terms: application domain, implementation domain, will be very grateful if somebody explain me the difference, please do not copy from the book I know how to read, thanks in advance
| The application domain describes the problem you're trying to solve, using its terminology and concepts ("a molecule is a collection of atoms, an ion has a weight and a charge"). The implementation domain describes the programming language you're using to solve it, where terminology like "abstract", "polymorphic", "in... |
3,954,871 | 3,954,877 | OpenGL: Sending RGBA color struct into glColor*() as one parameter? | Is there some way to send a struct like:
struct COLOR {
float r, g, b, a;
};
directly into glColor*() function as one parameter? Would make the code nicer.
I could make own function and send separetely each R,G,B,A values onto glColor4f() but that wouldnt be that nice. So im looking a way to send it the most optim... | COLOR color;
glColor4fv((GLfloat*) &color);
Update:
I wouldn't recommend creating an inline function, however, you could use GLfloat in your struct to get the expression clearer. Use &color.r to avoid a compiler warning.
struct COLOR {
GLfloat r,g,b,a;
};
COLOR color;
glColor4fv(&color.r);
|
3,954,895 | 3,955,029 | WM_PAINT not being called after window is created | I've been playing around with the Windows api for uni, but I cant get the window messages to call WM_PAINT after the inital creation. It calls it when the window is created but not after.
All Other messages get called! Just cant get the WM_PAINT to be called.
This is part of a game lib we have to make using the Windows... | First, I really don't like your game loop as its not at all obvious where the windows message pump is.
Somewhere along the line you need to call PeekMessage() or GetMessage() and TranslateMessage() & DispatchMessage() on any messages retrieved. Lots of people unfamiliar with windows will filter the messages, either in ... |
3,954,914 | 3,955,084 | fstream absolute path doesn't work | This is really strange. Absolute path doesn't work for both ifstream and ostream. It works when I use a relative path like so:
ofstream out;
out.open("file2.txt");
string river = "i love cheese";
if(!out){
cout << "error"; // have breakpoint set here
} else {
out << river; // have breakpoint set here (stops he... | What's you're operation system? Windows 7 does not allow to create files on C:\. You could create new folder on C:\, for example C:\temp\ and try this code:
std::ofstream out;
out.open("C:\\temp\\asd.txt" );
if( ! out )
{
std::cout << "1";
}
if ( !out.is_open() )
{
std::cout << "2";
}
out.close();
This wor... |
3,955,072 | 3,955,089 | Ensuring a reference that will not become invalid is given | I'm making a TextField class, which at the moment stores a reference to a variable, and whenever the programmer wants, they can call TextField.show() and the referenced variable will be read and displayed on-screen.
This however can result in problems if the reference becomes invalid. For example, if the variable refer... | If you use a reference, then it becomes the responsibility of the caller to ensure his/her code is not undefined. Basically, there is no way to know. You could use shared_ptr to ensure that this problem won't happen, and you allow shared ownership. That means if the variable(shared_ptr) goes out of scope, the value won... |
3,955,270 | 3,955,282 | unexpected change of wchar variable | Okey this is driving me crazy now...
I'm working on a directX game in c++ and I got a global wchar variable called FpsString witch i declared like this:
WCHAR * FpsString;
And in my initialization code i initialized it like this:
WCHAR a[100];
FpsString = a;
Okay, here is the prob... FpsString suddenly changes t... | Is WCHAR a[100]; also global (static) or is it perhaps a local variable?
If it's local then that's your problem: It stops to exist when the scope (function) is complete.
Change it to FpsString = new WCHAR[100];
|
3,955,272 | 3,955,284 | Building and Using a DYLIB in Xcode | I'm trying to build a .dylib in Xcode. Currently the .dylib builds, but when I drag the .dylib into another project and try to #import one of the headers (Seeker.h) in the .dylib, I get this error:
*: No such file or directory
Seeker.h: No such file or directory
The project is available as an Xcode project here.... | Dylibs don't carry headers: they're brainless executable files. Built-in libraries have their headers in known locations, like /usr/include, which makes them globally available. What you're looking for is probably a framework.
Frameworks are packages that contain a dynamic library and header files, so once you link wit... |
3,955,919 | 3,972,813 | Need a way in C++ to set the DNS servers on all interfaces | I'm writing a small tray app in C++ for Win XP/7, with the objective that as long as the app is running, http://*.dev will point to http://localhost.
This is part of a mod for XAMPP/WAMP to permit directory-named virtual domains on localhost (so, for example, http://test.dev/index.php will map to G:\xampp\virtual\test\... | You can use WMI to configure DNS on each interface. You can do this by using the EnableDNS or SetDNSServerSearchOrder method of the Win32_NetworkAdapterConfiguration class. You can get the current setting using the DNSServerSearchOrder property. Below are a couple of resources.
http://www.activexperts.com/activmonitor... |
3,955,925 | 3,955,941 | C++ Win32 API offline documentation? | I'm learning win32 apps with C++. I've got a pretty good API reference, but it's from 1997. Is there a more modern version available for download?
My connection is horrendous so I'd like it to be fully accessible offline. Something akin to a chm or hlp file...searchable and up to date-ish.
| If you install the Windows SDK, it comes with all the documentation as well. The download is enormous though, but at least you can do it all-at-once.
|
3,956,016 | 3,957,349 | How can I pause/stop a mesh animation in DirectX9? | Does DirectX 9 have a function that will stop or pause a mesh's animation that is currently running? I need an example on how the function works.
| There is an example in the DirectX SDK on how to do it using the X-File format and D3DX classes. More info here:
http://msdn.microsoft.com/en-us/library/ee418800(VS.85).aspx
|
3,956,024 | 3,956,133 | How to list class methods in gdb? | I've been googling for this and checking through the gdb manual but can't seem to find an answer to what I'm trying to do.
Is there a way to get gdb to print out a listing of all the methods for a given class type? The print command only seems to show the data members and fields, none of the methods are displayed for i... | You can use ptype.
Suppose I add these lines to your example:
A alpha;
B beta;
Now in gdb I can ask for a description of a class type (or an instance of one):
(gdb) ptype alpha
type = class A {
public:
virtual void foo();
}
(gdb) ptype A
type = class A {
public:
virtual void foo();
}
(gdb) ptype beta
typ... |
3,956,365 | 3,956,482 | Debug a module built with Boost.Python in QtCreator | I have a module built with Boost.Python and I want to debug it in QtCreator (or perhaps gdb). I prefer a visual environment if possible.
| http://leohart.wordpress.com/2010/10/18/debug-a-module-built-with-boost-python-within-qtcreator/
After a while, I finally figured out how to do it. I documented it in the link above so future searches can find it.
|
3,956,594 | 3,956,623 | Changing Warning Level for 3rd Party Libs | I generally like to compile against warning level 4 in Visual Studio and treat all warnings as errors. The problem is, Ogre3D is not compiled with warning level 3 (neither is FBX SDK or OIS, which I am also using), and that poses a problem because now I have a ton of warnings from Ogre3D libraries that are now treated ... | You don't say exactly how you are compiling, but here are some options:
1 - Inside Visual Studio, you can set the warning level for individual source files via the Properties for each source file
2 - You can also change the the warning level dynamically within a file using
#pragma warning(push, 3)
// Some code, perhap... |
3,956,636 | 3,956,674 | C++ on Linux not recognizing commands like exit() and printf() | I get these errors after issuing a g++ command on a .cpp file:
error: ‘exit’ was not declared in this scope
error: ‘printf’ was not declared in this scope
The problem is that when I compiled this program on another linux machine, everything went fine. I tried searching around, but all I found was that I need to include... | Recent versions of GCC have gotten stricter in what responsibilities the programmer needs to fulfill. Include the cstdlib, cstdio, etc. header and access these functions from the std namespace.
|
3,956,988 | 3,957,020 | What is the natural way to express C++ "protected virtual" idiom in Objective-C? | In C++ there is a template method idiom when base class implements all its algorithms but factors out some tiny little differences (usually having to deal with data formats, etc) for subclasses to implement in the form of protected virtual methods that are not accessible to hierarchy clients.
What is the most natural ... | I would create a separate header file with a category. You could name that category Protected:
@interface MyClass(Protected)
// Place your "protected" methods here.
@end
Normal class users would not #import this file, only the main class file. But the implementation and subclasses would the also #import the header fil... |
3,957,298 | 3,957,427 | posix thread synchronization stop at same code | I have multiple threads, and I want each thread to wait for every others to complete at certain point in the code before proceeding as following:
void *run() {
for (i=0;i<1000;i++){
do_1st();
// sync() all stop here wait for all then resume
do_2nd();
}
}
I tried to use pthread_cond_wait.. but It seems... | You can use a pthread_barrier, initialize it before you start your threads, and set the count to the no. of threads that's running your loop. e.g. if you have 8 threads:
pthread_barrier_init(&my_barrier,NULL,8);
The thread loop now becomes
void *run() {
for (i=0;i<1000;i++){
do_1st();
pthread_barrier_wait(&... |
3,957,343 | 3,957,368 | How to read data from SQLite database? | I decided to use SQLite as it allows to store database into a single file. I think I have managed to do a database with SQLite Database Browser.
How can I read that data in a C/C++ program?
| How about the 'An Introduction to Sqlite C/C++ Interface', and there is a whole C++ example here on CodeProject.
This is bits of the more full sample,
#include "CppSQLite.h"
#include <ctime>
#include <iostream>
using namespace std;
const char* gszFile = "C:\\test.db";
int main(int argc, char** argv)
{
try
{
... |
3,957,559 | 4,341,000 | Tab control like in FireFox in native windows app | I would like to enable tabbing for my application. And so far it seems I could use a tab control. The problem with it is, though, that it creates a border around the client area. What I want, is more like a FireFox tab control, that only takes up a row in the application and doesn't create any frames around client area... | There is also a CPropertySheet that's a good control. But so far it seems disabling and changing some things is simply impossible. No solution for the problem except full ownerdraw path.
|
3,957,611 | 3,958,095 | C or C++ for pattern recogniton/image processing? | I about to take some courses in Pattern Recognition.
As i have no prior knowledge in either C or C++, my professors told me to learn a bit of one of them before the course, and learn more when doing the course.
Which one should i pick?
The prior knowledge in programming i have is limited to mostly C# but some PHP, SQL ... | Stroustrup (inventor of C++) argues that C++ is easier to learn than C:
There will be less type errors to catch manually […] fewer tricks to learn […], and better libraries available.
With that in mind, go for C++.
|
3,957,678 | 3,967,636 | Do I need to specify attributes on deriving classes? | I have this interface. If I derive, do I need to specify format attribute again? And, if a class Deriv implements this interface, can I use Deriv::LT_DEBUG?
class Logger
{
public:
enum LogType
{
LT_DEBUG = 0,
LT_WARNING,
LT_ERROR,
LT_STAT,
... | I could not find any documentation on it, but I guess that the __attribute__ annotation is not implicitly inherited by a derived class.
This means that, if you call EHLog through a Deriv instance, reference or pointer, the format checking is only done if the Deriv::EHLog also specifies the __attribute__((format)) annot... |
3,957,807 | 3,963,388 | started from command line? | I have a simple C/CPP process running on a linux system. This is a.out.
Another process is capable to start a.out inside its code. This is b.out.
What code do I need inside a.out to understand that it is executed from the command line?
Eg ./a.out
Is there a way a process to know if it started from the cmd or started fr... | I would set an environment variable, in the parent process, to some value (say the parent pid), and have the child process check for it.
It is unlikely that a shell user would set this variable (call it something unlikely to name-clash), so if this variable is set to the expected value, then you know that it is being s... |
3,957,916 | 3,962,947 | Why can't I use reference types as the value type of a container type? | For example, std::vector<int&> vec_int; this seems to be invalid in c++. Why is this invalid?
| Answer, as per chryspi request above. As commented in other responses, you cannot use references directly as references don't exist by themselves.
You can use references, however, but by using the boost::reference_wrapper<T> utility class:
typedef boost::reference_wrapper<int> intref;
std::vector<intref> v;
... |
3,958,066 | 4,549,280 | C++ weird RAW sockets and iptables issue | With reference to C++ iptables redirection forming separate packets, I am facing an extremely peculiar problem now. I am trying to redirect all incoming traffic on UDP port 5060 to port 56790, and all outgoing traffic from 5060 to the port 56789. I used these iptables rules:
iptables -t nat -I PREROUTING -p udp ! -s lo... | raw sockets get a copy of the original packet before modification (incoming). On outgoing it's reversed.
|
3,958,080 | 3,958,096 | Good Book/Training material to learn multithreading in C/C++ | I am just a starter at using threads in my code. I use Boost threads usually.
But I don't think I have mastered this field yet.
I am looking for learning material specifically for advanced parallel programming. Could anybody suggest something.
| There's an early access edition of C++ Concurrency in Action available at http://www.manning.com/williams/ He's very knowledgeable on the subject and AFAIK he's the author of boost threads and has also just released a version of std::thread conforming to the new c++0x standard.
I'm also reading Concurrent Programming ... |
3,958,174 | 3,958,229 | QT Creator not allowing me to save anything | I'm new to QT and the IDE is driving me insane. I've hit this problem now and It won't go away. If I load up QT Develop and edit a file, it stars it to let me know it needs saving. If I then try to save it it warns me that the file is read only, offering me the option of "Make Writeable" why it thinks it is read onl... | If the files you are editing are read only in the filesystem, then they will be read only in the IDE as well.
|
3,958,455 | 3,958,738 | Register Game Object Components in Game Subsystems? (Component-based Game Object design) | I'm creating a component-based game object system. Some tips:
GameObject is simply a list of Components.
There are GameSubsystems. For example, rendering, physics etc. Each GameSubsystem contains pointers to some of Components. GameSubsystem is a very powerful and flexible abstraction: it represents any slice (or aspe... | Vote for the third approach.
I am currently working on component-based game object system and i clearly see some of additional advantages of this approach:
The Component is more and more self-sufficing subentity as it depends only on a set of available subsystems (i presume this set is fixed in your project).
Data-dri... |
3,958,483 | 3,958,500 | Constants and Classes Declarations Across Multiple Source Files in C++ | I am sure this problem is asked a lot but I can't seem to find anything relevant. I have multiple source files in a C++ project. In typical fashion, there are multiple header files with class and function declarations and associated source files with their definitions. The problem is that when I try to use one of my cl... | The word you’re looking for is “declare”, not “prototype”.
In any case, that’s normal. Usually you’d just include the relevant header files:
// ClassB.h
#include "ClassA.h"
class ClassB {
public: ClassA* ca; };
This will cause problems with circular references, though (but in all other cases it’s fine).
Another thin... |
3,958,525 | 3,958,539 | C++ TCHAR[] to string | I have this method which receives a path through a TCHAR szFileName[] variable, which contains something like C:\app\...\Failed\
I'd like to sort through it so I can verify if the name of the last folder on that path is in fact, "Failed"
I thought that using something like this would work:
std::wstring Path = szFileNam... | Either you’re consistently using wstring (the wide character variant) or string (the “normal” variant).
Since you’re getting a TCHAR (which can be either wchar_t or char, depending on compiler flags), the appropriate type to use would be a tstring, but that doesn’t exist. However, you can define a typedef for it:
typed... |
3,958,687 | 4,141,163 | C\C++ LINPACK source code for window free for commercial use? | I need run benchmark to test my cpu FLOPS and compare this with raitings such as top500 org. I known Linpack is are standart for measure CPU perfomance. But i can find source code for windows on C\C++ without not free librarys like Intel MKL library, etc Maybe someone know where i can find C\C++ LINPACK source code for... | The only official variant of Linpack that can be used for TOP500 comparison is HPL - high performance linpack.
Do you really need some code "free for commercial use?" or you can use GPL/BSD code?
There are some good linear algebras libraries BLAS (on which HPL depends to get the high performance), e.g. ATLAS, GOTOBlas.... |
3,958,795 | 3,958,810 | different rand() results on Windows and Linux | I've noticed, that standard rand() function gives different results on Windows and Linux. Ofcourse I've used the same seed number (1234). Here are several first results:
WIN: 4068 213 12761 8758
LIN: 479142414 465566339 961126155 1057886067
My application requires that both platforms produce identical output.
What are ... | Boost has a wide range of RNGs, presumably with reproducible behaviour across platforms.
|
3,958,853 | 3,958,874 | unexplained syntax error defining threadpool inside class definition | I have the following class definition and for some reason I cannot define the threadpool inside the class definition itself. It says: syntax error: identifier 'numberofpoolthreads' I tried directly defining it in the class, but it gives me same syntax error, does anyone know why this is?
#include "stdafx.h"
#include ... | This line: resolverpool p(numberofpoolthreads); isn't valid in a class definition. You need a member variable, which you then initialise in the constructor. e.g.:
class ResolverThreadPoolManager
{
public:
explicit ResolverThreadPoolManager(int numberofpoolthreads);
...
private:
const resolverpool p;
};
... |
3,958,878 | 3,958,910 | Is i = 0, ++i defined? | I recently learned about the , operator and the fact that it introduces a sequence point.
I also learned that the following code led to undefined behavior:
i = ++i;
Because i was modified twice between two sequence points.
But what about the following codes ?
i = 0, ++i;
i = (0, ++i);
While I know the rules, I can't ... | Yes. = has higher precedence than ,, so this expression is equivalent to (i = 0), ++i. , is a sequence point, so it's guaranteed that the ++i occurs after the assignment.
I'm not sure whether i = (0, ++i) is defined though. My guess would be no; there's no sequence point between the increment and the assignment.
|
3,958,904 | 3,958,926 | How to specify include directory for configure script | I have a linux system at my workplace with pretty old packages and no root access. I'm compiling packages that I need from source with --prefix=[somewhere in homedir]. My problem is that I just can't find out how to convince configure to look for header files in a specific directory. The source is cpp. I tried with env... | The normal way to do this is --with-<feature>=<header directory>.
|
3,958,978 | 3,959,363 | Is it better to have lot of interfaces or just one? | I have been working on this plugin system. I thought I passed design and started implementing. Now I wonder if I should revisit my design. my problem is the following:
Currently in my design I have:
An interface class FileNameLoader for loading the names of all the shared libraries my application needs to load. i.e. L... | My c++ projects generally consists of objects that implement one or more interfaces.
I have found that this approach has the following effects:
Use of interfaces enforces your design.
(my opinion only) ensures a better program design.
Related functionality is grouped into interfaces.
The compiler will let you know if ... |
3,959,093 | 3,959,134 | 'stdx’ is not a namespace-name error being shown for a ptr_vector program | I've been trying a program from codeproject, about ptr_vector, and while compiling, the above error is shown.
Googling shows no hope to solve this problem. Could anyone here help out?
Here's the entire code (am compiling with gcc 4.2.2)
#include <iostream>
#include <string>
#include <boost/ptr_container/ptr_vector.hpp>... | stdx is not a standard namespace, it is defined by the particular implementation you are trying to use. You are not using the header file include #include "ptr_vector.h" inside which namespace stdx exists. Currently the ptr_vector you are using is being included from boost namespce. That begs the question, if you can u... |
3,959,118 | 3,959,260 | C#, C++ project mix: Could not load file or assembly | I have Visual Studio 2010 solution of 2 projects: c# and c++
c++ project using .net framework libraries and exposes class that is referenced from c# project.
Everything compiles fine and c# project intellisence helps me with methods exposed from c++. But when I try to launch c# project it crashes with exception:
Coul... | A combination of Fusion logger (guide) and dependency walker should give the answer.
|
3,959,306 | 3,959,389 | Array wraparound with modulo of unsigned | I'm trying to implement a lagged Fibonacci pseudo-random number generator for integers up to some maximum. It maintains an array of values
int values[SIZE] = { /* 55 seed values */ };
and uses the following function to return the next value
unsigned lagfib()
{
static unsigned idx = 0;
int r = values[idx];
... | If e.g. idx is less than 24, you'll get wraparound to the other end of the number range of unsigned int. 55 is not a divisor of e.g. 2^32, so this will not give you correct results.
I can see two options:
Maintain three separate idx variables, offset by 24 and 55 respectively.
Do e.g. (idx - 24 + SIZE) % SIZE.
Actua... |
3,959,393 | 3,961,404 | what is the best c++ wrapper to webkit ? for staticlly linking (not QWebkit) | i need to statically embed web browser in c++ , webkit is good idea , is there any easy c++
wrapper around this kit , i know the Qt version but i can only dynamically link it and its no good for me.
| For Windows, I believe that you can build the Cairo-based Windows port of webkit statically.
WebKit.org link
|
3,959,398 | 3,959,495 | -D option is expanded incorrectly from g++ command line | In C++ CodeBlocks project I added the following definitions to the project settings, compiler settings, #define:
_DEBUG
DATA_DIR=\"/media/Shared/SiX/Data\"
This produces the following g++ command line:
g++ -Wall -g -fPIC -save-temps -D_DEBUG -DDATA_DIR=\"/media/Shared/SiX/Data\" -I../Includes -c /media/Shared/S... | Putting quotes on macros is tricky and not a good idea.
Try and use the pre-processor to add the required quotes.
#define DO_QUOTE(X) #X
#define QUOTE(X) DO_QUOTE(X)
#ifndef DATA_DIR
#define DATA_DIR /tmp
#endif
char commonDataDir[] = QUOTE(DATA_DIR);
|
3,959,403 | 3,959,548 | What is RtlPcToFileHeader? | I am profiling an application using VerySleepy 0.7. The application is written in C++ with Qt 4.6.x, compiled with VS 2005 and is running on Windows 7 Ultimate x64.
The highest usage by far is a call to RtlPcToFileHeader
Exclusive Inclusive %Exclusive %Inclusive Module
33.67s 33.67s 15.13% 15.13% ntdll
I... | Just pause it under the debugger. Study the call stack to understand what it was doing and why. Then repeat several times. That will tell you where the time is going and the reasons why.
If that's too low-tech for you, try out LTProf, or any other wall-time stack sampler that reports line-level percent, preferably with... |
3,959,473 | 3,962,132 | Must I CloseHandle() on a thread handle? | _beginthreadex returns a handle to a thread:
m_hStreamStatsThread = (HANDLE) _beginthreadex( NULL, 0, StreamStatsThread, this, 0, NULL );
This handle may be used if you need to refer to the thread in calls like TerminateThread(..) for example.
According to the MSDN page on _beginthreadex, _beginthreadex won't always r... | Agree with Nemanja Trifunovic.
Even after the thread exited - its handle is valid. You can for instance query its return value.
As a general rule: every Win32 handle must be closed by CloseHandle, unless otherwise specified.
|
3,959,634 | 3,959,771 | Object-Oriented Suicide or delete this; | The following code compiled with MSVC9.0 runs and outputs Destructor four times, which is logical.
#include <iostream>
class SomeClass
{
public:
void CommitSuicide()
{
delete this;
}
void Reincarnate()
{
this->~SomeClass();
new (this) SomeClass;
}
~SomeClass()
{
std::cout... |
p->~SomeClass(); //line 5
p->CommitSuicide(); //line 6
Line (6) definitely invokes Undefined Behaviour.
That is, is invocation of another member after the explicit call of the destructor allowed (defined)?
No! Your assumption is correct.
|
3,959,783 | 3,960,176 | Trying to study shine MPEG Layer-III encoder - getting "redeclaration of C++ built-in type 'bool'" | Greetings.
I am studying the way mpeg layer-III encoding works for an upcoming project. I downloaded the shine encoder as it is said to be the simpliest of all. http://www.mp3-tech.org/programmer/sources/shine.zip is the link.
I successfully compiled them in a standalone project but i need to be using them in a QT proj... | You can mix C and C++ code in the same project, but you need to compile the C code with a C compiler. Rather than trying to include main.c from a C++ file, compile the C code separately, and declare any C functions you need to call from C++ as extern "C", for example
extern "C" int mainc(int argc, char *argv[]);
|
3,959,794 | 4,037,651 | How can I detect keyboard and/or mouse input on Windows Mobile? | I'm working on a small C++ project which involves a launcher application that does a bit of setup work and then invokes the real application. To be precise, I'm working on the launcher application - the real application is done by a separate team. These programs are both deployed to Windows Mobile devices. Now, I'd lik... | You can use SetWindowsHookEx, it is only undocumented. This is a good post about hooks and subclassing on Windows Mobile.
|
3,959,811 | 3,960,111 | Why were threads never included as part of the C++ standard? | Why is it that threads were never included as part of the C++ standard originally? Did they not exist when C++ standard was first created?
| I think the main reasons are
specifying threading behavior into the language needs a lot of work and understanding, which nobody had available back then
nobody had a great idea about a good threading API, and there was no one existing library that seemed good enough to be used as a base for further work
the standardiz... |
3,959,953 | 3,960,059 | Attribute lists or inheritance jungle? | I've got 2 applications (lets call them AppA and AppB) communicating with each other.
AppA is sending objects to AppB.
There could be different objects and AppB does not support every object.
An object could be a Model (think of a game, where models are vehicles, houses, persons etc).
There could be different AppBs. Ea... | Just for a comparison, Google's Protocol Buffers uses a combination of both but leans hard toward your second example.
If you have distinctly different data that needs to be sent over the channel, you use the tool to generate a derivitive of the "message" class, but each message can contain other messages, and you can ... |
3,959,987 | 3,968,399 | Requesting complete, compilable libxml2 sax example | I'm having a heck of a time figuring out how to use the sax parser for libxml2. Can someone post an example that parses this XML ( yes, without the <xml...> header and footer tags, if that can be parsed by the libxml2 sax parser):
<hello foo="bar">world</hello>
The parser should print out the data enclosed in element... | Adapted from http://julp.developpez.com/c/libxml2/?page=sax
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/parserInternals.h>
void start_element_callback(void *user_data, const xmlChar *name, const xmlChar **attrs) {
printf("Beginning... |
3,960,221 | 3,960,270 | Windows Named Pipe Support in Linux | I'm looking at a project which will require inter-process communication between a legacy Windows application using named pipes, and a new service running on a Linux server. The windows application cannot be changed. Does anyone know if there is a Linux library available that supports Windows named pipes? Or even better... | Windows and Linux named pipes are different animals. If an interop solution exists you are going to be one of a very small population of users.
You might be better off writing a proxy on the Windows side to map between Named Pipe and socket, and connecting this to a socket on the Linux end. This provides you a usefu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.